@kanf/wema-kake 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=RegExp(`^[a-z0-9][a-z0-9-]{0,63}$`);function t(t){return e.test(t)}var n={color:`Color`,duplicate:`Duplicate`,delete:`Delete`,deleteNotes:e=>`Delete ${e} notes`,autoSize:`Auto Size`,bulletedList:`Bulleted List`,numberedList:`Numbered List`,checklist:`Checklist`,outdent:`Outdent (Shift+Tab)`,indent:`Indent (Tab)`,image:`Image`,embed:`Embed`,foldLongText:`Fold Long Text`,colorButter:`Butter`,colorRose:`Rose`,colorPeach:`Peach`,colorLavender:`Lavender`,colorSky:`Sky`,colorMint:`Mint`,colorSage:`Sage`,colorGray:`Gray`,details:`Details`,route:`Route`,from:`From`,to:`To`,line:`Line`,arrow:`Arrow`,size:`Size`,width:`Width`,lineSolid:`Solid`,lineDashed:`Dashed`,lineDotted:`Dotted`,arrowNone:`No arrow`,arrowStart:`Arrow at start`,arrowEnd:`Arrow at end`,arrowBoth:`Arrow at both ends`,sizeSmall:`Small`,sizeMedium:`Medium`,sizeLarge:`Large`,widthThin:`Thin`,widthNormal:`Normal`,widthThick:`Thick`,routeCurve:`Curve`,routePolyline:`Polyline`,anchorAuto:`Auto`,anchorTop:`Top`,anchorRight:`Right`,anchorBottom:`Bottom`,anchorLeft:`Left`,bold:`Bold`,strikethrough:`Strikethrough`,textColor:`Text Color`,link:`Link`,removeLink:`Remove link`,quote:`Quote in a new note`,ok:`OK`,deleteImage:`Delete image`,readMore:`Read more`,showLess:`Show less`,linkOut:e=>`Connects to: ${e}`,linkIn:e=>`Connected from: ${e}`,linkBoth:e=>`Connected both ways: ${e}`,linkNone:e=>`Connected: ${e}`,linkLabeled:(e,t)=>`${e} (${t})`,linkEmpty:`(No text)`},r={color:`色`,duplicate:`複製`,delete:`削除`,deleteNotes:e=>`${e} 枚の付箋を削除`,autoSize:`内容に合わせたサイズ`,bulletedList:`箇条書き`,numberedList:`番号付きリスト`,checklist:`チェックリスト`,outdent:`段上げ (Shift+Tab)`,indent:`段下げ (Tab)`,image:`画像`,embed:`埋め込み`,foldLongText:`長い本文を畳む`,colorButter:`バター`,colorRose:`ローズ`,colorPeach:`ピーチ`,colorLavender:`ラベンダー`,colorSky:`スカイ`,colorMint:`ミント`,colorSage:`セージ`,colorGray:`グレー`,details:`詳細`,route:`経路`,from:`始点`,to:`終点`,line:`線`,arrow:`矢印`,size:`サイズ`,width:`太さ`,lineSolid:`実線`,lineDashed:`破線`,lineDotted:`点線`,arrowNone:`矢印なし`,arrowStart:`始点に矢印`,arrowEnd:`終点に矢印`,arrowBoth:`両端に矢印`,sizeSmall:`小`,sizeMedium:`中`,sizeLarge:`大`,widthThin:`細い`,widthNormal:`標準`,widthThick:`太い`,routeCurve:`曲線`,routePolyline:`折れ線`,anchorAuto:`自動`,anchorTop:`上`,anchorRight:`右`,anchorBottom:`下`,anchorLeft:`左`,bold:`太字`,strikethrough:`取り消し線`,textColor:`文字色`,link:`リンク`,removeLink:`リンクを解除`,quote:`引用した付箋を作る`,ok:`OK`,deleteImage:`画像を削除`,readMore:`続きを読む`,showLess:`折り畳む`,linkOut:e=>`つながり先: ${e}`,linkIn:e=>`つながり元: ${e}`,linkBoth:e=>`相互のつながり: ${e}`,linkNone:e=>`つながり: ${e}`,linkLabeled:(e,t)=>`${e}(${t})`,linkEmpty:`(本文なし)`};function i(e,t){let r={...n},i={...e,readMore:t?.more??e?.readMore,showLess:t?.less??e?.showLess};for(let e of Object.keys(n))typeof i[e]==typeof r[e]&&(r[e]=i[e]);return r}var a=class{handlers=new Map;on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n)),n.add(t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){let n=this.handlers.get(e);if(n)for(let r of n)try{r(t)}catch(t){console.error(`Error in event handler for "${String(e)}":`,t)}}removeAllListeners(){this.handlers.clear()}};function o(){return crypto.randomUUID()}function s(e){return{left:Math.min(...e.map(e=>e.x)),top:Math.min(...e.map(e=>e.y)),right:Math.max(...e.map(e=>e.x+e.width)),bottom:Math.max(...e.map(e=>e.y+e.height))}}var c=4;function l(e,t,n,r,i){let a=t.top-i-e.height,o=t.bottom+i,s={x:(t.left+t.right)/2-e.width/2,y:r===`above`?a:o};if(!(t.right>=n.left&&t.left<=n.right&&t.bottom>=n.top&&t.top<=n.bottom))return s;let l=n.left+c,u=n.top+c,d=n.right-c-e.width,f=n.bottom-c-e.height,p=a>=u,m=o<=f,h=s.y;return r===`above`&&!p&&m&&(h=o),r===`below`&&!m&&p&&(h=a),{x:Math.max(l,Math.min(s.x,d)),y:Math.max(u,Math.min(h,f))}}var u=[`top`,`right`,`bottom`,`left`];function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2;switch(t){case`top`:return{x:n,y:e.y};case`bottom`:return{x:n,y:e.y+e.height};case`left`:return{x:e.x,y:r};case`right`:return{x:e.x+e.width,y:r};case`auto`:return{x:n,y:r}}}var f=40;function p(e,t){if(t.y-(e.y+e.height)>=f)return`bottom`;if(e.y-(t.y+t.height)>=f)return`top`;let n=e.x+e.width/2,r=e.y+e.height/2,i=t.x+t.width/2,a=t.y+t.height/2,o=i-n,s=a-r,c={top:{x:0,y:-1},right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0}},l=`right`,d=-1/0;for(let e of u){let t=c[e],n=o*t.x+s*t.y;n>d&&(d=n,l=e)}return l}function m(e){switch(e){case`top`:return{x:0,y:-1};case`bottom`:return{x:0,y:1};case`left`:return{x:-1,y:0};case`right`:return{x:1,y:0}}}function h(e,t,n,r,i){let a=n===`auto`?p(e,t):n,o=r===`auto`?p(t,e):r,s=d(e,a),c=d(t,o);if(i===`polyline`)return g(s,c,a,o);let l=Math.sqrt((c.x-s.x)**2+(c.y-s.y)**2),u=Math.min(Math.max(l*.4,40),150),f=m(a),h=m(o),_=s.x+f.x*u,v=s.y+f.y*u,y=c.x+h.x*u,b=c.y+h.y*u;return`M ${s.x} ${s.y} C ${_} ${v}, ${y} ${b}, ${c.x} ${c.y}`}function g(e,t,n,r){let i=m(n),a=m(r),o=n===`left`||n===`right`,s=r===`left`||r===`right`,c;if(o===s){if(i.x+a.x===0&&i.y+a.y===0){if(o){let n=(e.x+t.x)/2;c=[{x:n,y:e.y},{x:n,y:t.y}]}else{let n=(e.y+t.y)/2;c=[{x:e.x,y:n},{x:t.x,y:n}]}}else{let n=Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),r=Math.min(Math.max(n*.3,30),100);if(o){let n=i.x>0?Math.max(e.x,t.x)+r:Math.min(e.x,t.x)-r;c=[{x:n,y:e.y},{x:n,y:t.y}]}else{let n=i.y>0?Math.max(e.y,t.y)+r:Math.min(e.y,t.y)-r;c=[{x:e.x,y:n},{x:t.x,y:n}]}}}else c=o?[{x:t.x,y:e.y}]:[{x:e.x,y:t.y}];let l=[`M ${e.x} ${e.y}`];for(let e of c)l.push(`L ${e.x} ${e.y}`);return l.push(`L ${t.x} ${t.y}`),l.join(` `)}function _(e,t,n,r){let i=d(e,t),a=Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2);if(r===`polyline`){let e=t===`left`||t===`right`?{x:n.x,y:i.y}:{x:i.x,y:n.y};return`M ${i.x} ${i.y} L ${e.x} ${e.y} L ${n.x} ${n.y}`}let o=Math.min(Math.max(a*.4,40),150),s=m(t),c=i.x+s.x*o,l=i.y+s.y*o,u=i.x-n.x,f=i.y-n.y,p=Math.sqrt(u*u+f*f)||1,h=n.x+u/p*o,g=n.y+f/p*o;return`M ${i.x} ${i.y} C ${c} ${l}, ${h} ${g}, ${n.x} ${n.y}`}function v(e,t){let n=document.createElement(e);return t&&(n.className=t),n}function y(e,t){e.title=t,e.setAttribute(`aria-label`,t)}function b(e,t,n,r,i){let a=t.getBoundingClientRect(),o=document.documentElement,s={left:Math.max(0,-a.left),top:Math.max(0,-a.top),right:Math.min(t.clientWidth,o.clientWidth-a.left),bottom:Math.min(t.clientHeight,o.clientHeight-a.top)},c={width:e.offsetWidth,height:e.offsetHeight},{x:u,y:d}=l(c,n,s,r,i);return e.style.left=`${u}px`,e.style.top=`${d}px`,{left:u,top:d,right:u+c.width,bottom:d+c.height}}function x(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left,top:n.top-r.top,right:n.right-r.left,bottom:n.bottom-r.top}}function S(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,e);return t&&n.setAttribute(`class`,t),n}var C=`[contenteditable]:not([contenteditable="false"]), input, textarea, select`;function w(e){let t=document.getSelection();if(!t||t.rangeCount===0)return null;let n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?n:null}function T(e){let t=document.getSelection();t&&(t.removeAllRanges(),t.addRange(e))}function E(e,t){Object.assign(e.style,t)}var D=new Set([`b`,`strong`,`i`,`em`,`u`,`s`,`br`,`span`,`ul`,`ol`,`li`,`a`,`input`,`img`,`iframe`,`video`,`audio`,`div`,`p`,`blockquote`]),ee={a:new Set([`href`,`target`,`rel`]),input:new Set([`type`,`checked`]),img:new Set([`src`,`alt`,`width`,`height`]),iframe:new Set([`src`,`width`,`height`,`sandbox`,`allow`,`allowfullscreen`,`frameborder`,`title`]),video:new Set([`src`,`controls`,`preload`,`width`,`height`,`poster`]),audio:new Set([`src`,`controls`,`preload`])},O=new Set([`script`,`style`,`noscript`,`object`,`embed`,`applet`]),te=new Set([`color`,`background-color`,`font-size`,`font-weight`,`font-style`,`text-decoration`,`text-decoration-line`,`text-align`,`margin`,`padding`,`display`,`list-style-type`,`white-space`]),ne=new Set([`font-weight`,`font-style`,`text-decoration`,`text-decoration-line`]),re=new Set([`normal`,`400`,`none`]),ie=new Set([`http`,`https`,`mailto`,`tel`]),k={img:`image/`,video:`video/`,audio:`audio/`};function A(e,t){let n=e.replace(/^[\u0000- ]+/,``).replace(/[\t\n\r]/g,``).toLowerCase(),r=/^([a-z][a-z0-9+.-]*):/.exec(n)?.[1];return r===void 0||ie.has(r)?!0:r===`data`&&t!==void 0&&n.startsWith(`data:${t}`)}function j(e){if(!A(e))return null;let t,n;try{t=new URL(e,document.baseURI),n=new URL(document.baseURI)}catch{return null}let r=t.protocol===n.protocol&&t.host===n.host;return!A(t.href)&&!r?null:t.href}function ae(e,t){let n=new DOMParser().parseFromString(`<body>${e}</body>`,`text/html`).body;return se(n,t?.pasted??!1),n.innerHTML}function oe(e){let t=e.ownerDocument.createDocumentFragment();for(;e.firstChild;)t.appendChild(e.firstChild);e.parentNode?.replaceChild(t,e)}function se(e,t){let n=Array.from(e.childNodes);for(let r of n){if(r.nodeType===Node.TEXT_NODE)continue;if(r.nodeType!==Node.ELEMENT_NODE){r.parentNode?.removeChild(r);continue}let n=r,i=n.tagName.toLowerCase();if(O.has(i)){n.parentNode?.removeChild(n);continue}if(!D.has(i)){oe(n),se(e,t);return}if(i===`input`&&n.type!==`checkbox`){n.parentNode?.removeChild(n);continue}let a=ee[i],o=[];for(let e of Array.from(n.attributes)){let r=e.name.toLowerCase();if(r.startsWith(`on`))o.push(e.name);else if(r!==`class`){if(r===`style`)ce(n,t);else if(!a||!a.has(r))o.push(e.name);else if(r===`href`||r===`src`||r===`poster`){let t=r===`poster`?`image/`:k[i];A(e.value,t)||o.push(e.name)}}}for(let e of o)n.removeAttribute(e);se(n,t),t&&i===`span`&&n.attributes.length===0&&oe(n)}}function ce(e,t){let n=e.style,r=t?ne:te,i=[];for(let e=0;e<n.length;e++){let a=n[e],o=t&&re.has(n.getPropertyValue(a));(!r.has(a)||o)&&i.push(a)}for(let e of i)n.removeProperty(e);e.getAttribute(`style`)===``&&e.removeAttribute(`style`)}function M(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function N(e){return!/<[a-z][^<>]*>/i.test(e)}function le(e){let t=document.getSelection();if(!t||t.rangeCount===0)return;let n=t.getRangeAt(0);n.deleteContents();let r=document.createElement(`div`);r.innerHTML=e;let i=document.createDocumentFragment(),a=null;for(;r.firstChild;)a=i.appendChild(r.firstChild);if(n.insertNode(i),a){let e=document.createRange();e.setStartAfter(a),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}}function ue(e){if(typeof e==`object`&&e&&!Array.isArray(e))return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`)))}function de(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}var fe=`wema-checklist`,pe=`wema-checked`,me=`img, iframe, video, audio, input`;function P(e){return e?.nodeType===Node.ELEMENT_NODE}function F(e){return P(e)&&(e.tagName===`UL`||e.tagName===`OL`)}function he(e){return P(e)&&e.tagName===`LI`}function ge(e){return P(e)&&(e.tagName===`DIV`||e.tagName===`P`)}function _e(e){return P(e)&&e.tagName===`BR`}function ve(e){return e?.nodeType===Node.TEXT_NODE&&e.data===`
2
+ `}function ye(e){return Array.prototype.indexOf.call(e.parentNode?.childNodes??[],e)}function be(e){let t=[];for(let n=e.nextSibling;n;n=n.nextSibling)t.push(n);return t}function I(e,t,n){let r=(P(t)?t:t.parentElement)?.closest(n)??null;return r&&r!==e&&e.contains(r)?r:null}function xe(e,t){return I(e,t.startContainer,`li`)!==null}function L(e){return e.tagName===`OL`?`ol`:e.classList.contains(fe)?`checklist`:`ul`}function Se(e){let t=document.createElement(e===`ol`?`ol`:`ul`);return e===`checklist`&&t.classList.add(fe),t}function R(e,t){let n=e.querySelector(`:scope > input[type="checkbox"]`);if(t===`checklist`){if(n)return;let t=document.createElement(`input`);t.type=`checkbox`,e.insertBefore(t,e.firstChild)}else n?.remove(),e.classList.remove(pe)}function Ce(e){let t=document.createElement(`li`);return R(t,e),t}function z(e,t,n=null){let r=L(t);for(let i of Array.from(e))he(i)&&R(i,r),t.insertBefore(i,n)}function we(e){let{startContainer:t,startOffset:n,endContainer:r,endOffset:i}=e;return{restore(e,a,o){let s=t=>t!==e&&t!==o&&e.contains(t),c=document.createRange();return s(t)&&s(r)?(c.setStart(t,n),c.setEnd(r,i)):(c.selectNodeContents(a),c.collapse(!1)),c}}}function Te(e){for(let t of Array.from(e.childNodes)){if(t.nodeType!==Node.TEXT_NODE)continue;let e=t,n;for(;(n=e.data.indexOf(`
3
+ `))!==-1&&(n>0&&(e=e.splitText(n)),e.data.length!==1);)e=e.splitText(1)}}function Ee(e){let t=[],n=[],r=0,i=Array.from(e.childNodes);return i.forEach((e,i)=>{if(_e(e)||ve(e))t.push({nodes:n,start:r,end:i,terminator:e});else if(ge(e)||F(e))n.length>0&&t.push({nodes:n,start:r,end:i,terminator:null}),t.push({nodes:[e],start:i,end:i+1,terminator:null});else{n.push(e);return}n=[],r=i+1}),(n.length>0||t.length===0)&&t.push({nodes:n,start:r,end:i.length,terminator:null}),t}function De(e){return e.nodeType===Node.TEXT_NODE?e.data.trim()===``:!P(e)||e.textContent?.trim()===``&&!e.matches(me)&&!e.querySelector(me)}function Oe(e){return!F(e.nodes[0]??null)&&e.nodes.every(De)}function ke(e,t){let n=I(e,t.commonAncestorContainer,`div, p`);for(;n;){if(Ee(n).filter(e=>!Oe(e)).length>1&&!I(e,n,`li`))return n;n=n.parentElement?I(e,n.parentElement,`div, p`):null}return e}function Ae(e,t,n){let r=document.createRange();return ve(t)&&t.parentNode===e?r.setStart(e,ye(t)+n):r.setStart(t,n),r.collapse(!0),r}function je(e,t,n){let r=Ae(e,n.startContainer,n.startOffset),i=Ae(e,n.endContainer,n.endOffset);if(n.collapsed){let n=t.filter(t=>i.comparePoint(e,t.start)<=0),a=n.find(t=>r.comparePoint(e,t.end)>=0)??n[n.length-1]??t[0];return a?[a]:[]}let a=t=>{if(i.comparePoint(e,t.start)>0)return!1;let n=document.createRange();return n.setStart(e,t.start),n.setEnd(i.startContainer,i.startOffset),n.toString()!==``||n.cloneContents().querySelector(me)!==null},o=t.length;for(;o>0&&!a(t[o-1]);)o--;let s=t.slice(0,o).filter(t=>r.comparePoint(e,t.end)>=0);if(s.length>0)return s;let c=n.cloneRange();return c.collapse(!0),je(e,t,c)}function Me(e,t,n,r){let i=Array.from(t.childNodes).filter(he).filter(e=>n.intersectsNode(e)),a=i[i.length-1],o=t.parentNode;if(!a||!o)return null;let s=be(a);if(s.some(he)){let e=t.cloneNode(!1);z(s,e),o.insertBefore(e,t.nextSibling)}let c=t.nextSibling,l=i.map(e=>{let t=document.createElement(`div`);o.insertBefore(t,c),R(e,`ul`);for(let n of Array.from(e.childNodes))F(n)?o.insertBefore(n,c):t.appendChild(n);return t.firstChild||t.appendChild(document.createElement(`br`)),e.remove(),t});return t.firstElementChild||t.remove(),r.restore(e,l[l.length-1]??e)}function Ne(e,t,n){Te(e);let r=we(t),i=I(e,t.commonAncestorContainer,`ul, ol`);if(i){if(L(i)===n)return Me(e,i,t,r);let a=Se(n);return z(i.childNodes,a),i.replaceWith(a),r.restore(e,a)}let a=ke(e,t),o=je(a,Ee(a),t),s=o[0];if(!s)return null;let c=Se(n);a.insertBefore(c,s.nodes[0]??s.terminator);for(let e of o){let t=e.nodes[0];if(F(t)){z(t.childNodes,c),t.remove();continue}if(o.length>1&&Oe(e)){for(let t of e.nodes)t.parentNode?.removeChild(t);e.terminator?.parentNode?.removeChild(e.terminator);continue}let r=document.createElement(`li`);if(ge(t)){for(;t.firstChild;)r.appendChild(t.firstChild);_e(r.lastChild)&&r.lastChild?.remove(),t.remove()}else{for(let t of e.nodes)r.appendChild(t);e.terminator?.parentNode?.removeChild(e.terminator)}R(r,n),c.appendChild(r)}c.firstChild||c.appendChild(Ce(n));let l=c.previousSibling;F(l)&&L(l)===n&&(z(l.childNodes,c,c.firstChild),l.remove());let u=c.nextSibling;return F(u)&&L(u)===n&&(z(u.childNodes,c),u.remove()),r.restore(e,c.lastElementChild??c,a)}function Pe(e,t){let n=e.lastChild,r=F(n)&&L(n)===t?n:Se(t);r!==n&&e.appendChild(r);let i=r.appendChild(Ce(t)),a=document.createRange();return a.selectNodeContents(i),a.collapse(!1),a}function Fe(e,t){let n=I(e,t.startContainer,`li`),r=I(e,t.endContainer,`li`);if(!n||!r)return[];if(r.contains(n))return[r];let i=Array.from(e.querySelectorAll(`li`)),a=i.slice(i.indexOf(n),i.indexOf(r)+1);return a.filter(e=>!a.some(t=>t!==e&&t.contains(e)))}function Ie(e,t){if(F(e.lastElementChild))return e.lastElementChild;let n=t.cloneNode(!1);return e.appendChild(n),n}function Le(e,t){let n=we(t),r=null;for(let n of Fe(e,t)){let e=n.parentElement,t=n.previousElementSibling;if(!e||!he(t))continue;let i=Ie(t,e);R(n,L(i)),i.appendChild(n),r=n}return r?n.restore(e,r):null}function Re(e,t){let n=we(t),r=null;for(let n of Fe(e,t)){let t=n.parentElement,i=t?.parentElement;if(!t||!i||i===e||!e.contains(i))continue;let a=i.tagName===`LI`?i:F(i)?t:null,o=a?.parentElement;if(!a||!o)continue;let s=be(n);s.length>0&&z(s,Ie(n,t)),R(n,L(o)),o.insertBefore(n,a.nextSibling),t.firstElementChild||t.remove(),r=n}return r?n.restore(e,r):null}var ze=`wema-auto-size`,Be=`wema-note-placed`;function Ve(e,t){let n=parseFloat(t);return n>e&&n-e<1?e+1:e}var He=`wema-foldable`,Ue=`wema-fold-long`,We=`wema-folded`,Ge=[`x`,`y`,`width`,`height`],Ke=(e,t)=>Ge.some(n=>e[n]!==t[n]),qe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,width:n,height:r});function Je(e){return!!e.autoSize||!!e.foldable}function Ye(e){let t=getComputedStyle(e),n=e=>parseFloat(e)||0,r=n(t.lineHeight)||n(t.fontSize)*1.4;return e.scrollHeight-n(t.paddingTop)-n(t.paddingBottom)>r*2.5}var Xe=`wema-note-host-drawn`,Ze=`wema-note-has-footer`,Qe=`wema-note-has-accessory`,$e=`data-wema-focus-key`;function et(e){let t=document.activeElement;if(e&&t&&e.contains(t))return t.getAttribute(`data-wema-focus-key`)??void 0}var tt=class{notes=new Map;elements=new Map;zCounter=1;boardEl;layerEl;emitter;defaultWidth;defaultHeight;defaultColor;readOnly;viewOnly=!1;onMeasure;onLinkClick;hostRender;unreportedSizeBase=new Map;shownRects=new Map;placedRects=new Map;onPlacedMeasure;onUnderChange;onUnderResize;accessory;footer;slots;underHeights=new Map;underObserver=null;labels;unfolded=new Set;editingId=null;imageOverlay;activeImage=null;activeImageNoteId=null;handleImageOverlayDismiss;constructor(e){this.boardEl=e.boardEl,this.layerEl=e.layerEl,this.emitter=e.emitter,this.defaultWidth=e.defaultWidth,this.defaultHeight=e.defaultHeight,this.defaultColor=e.defaultColor,this.readOnly=e.readOnly,this.onMeasure=e.onMeasure,this.onPlacedMeasure=e.onPlacedMeasure,this.onLinkClick=e.onLinkClick,this.hostRender=e.hostRender,this.onUnderChange=e.onUnderChange,this.onUnderResize=e.onUnderResize,this.accessory={elementClass:`wema-note-accessory`,drawnClass:Qe,option:`renderNoteAccessory`,draw:e.hostAccessory,shown:!0,stale:new Set},this.footer={elementClass:`wema-note-footer`,drawnClass:Ze,option:`renderNoteFooter / noteLinks`,draw:e.hostFooter,shown:!1,stale:new Set},this.slots=[this.accessory,this.footer],this.labels=e.labels,(this.accessory.draw||this.footer.draw)&&typeof ResizeObserver<`u`&&(this.underObserver=new ResizeObserver(e=>{let t=!1;for(let{target:n}of e){let e=n.parentElement?.dataset.noteId;e===void 0||this.shownRects.has(e)||this.keepUnderHeight(e)&&(t=!0)}t&&this.onUnderResize()})),this.imageOverlay=v(`div`,`wema-image-overlay`),this.imageOverlay.style.display=`none`,this.imageOverlay.addEventListener(`click`,e=>e.stopPropagation()),this.imageOverlay.addEventListener(`pointerdown`,e=>e.stopPropagation()),this.imageOverlay.addEventListener(`mousedown`,e=>e.preventDefault()),this.boardEl.appendChild(this.imageOverlay),this.handleImageOverlayDismiss=e=>{this.imageOverlay.style.display!==`none`&&(this.imageOverlay.contains(e.target)||e.target!==this.activeImage&&this.hideImageOverlay())},this.boardEl.addEventListener(`click`,this.handleImageOverlayDismiss,!0)}addNote(e){let t=ue(e?.meta),n={id:o(),x:e?.x??100,y:e?.y??100,width:e?.width??this.defaultWidth,height:e?.height??this.defaultHeight,text:e?.text??``,color:e?.color??this.defaultColor,zIndex:e?.zIndex??this.zCounter++,...e?.autoSize?{autoSize:!0}:{},...e?.foldable?{foldable:!0}:{},...t?{meta:t}:{}};return n.zIndex>=this.zCounter&&(this.zCounter=n.zIndex+1),this.notes.set(n.id,n),this.renderNote(n),this.emitter.emit(`note:create`,{note:{...n},origin:`local`}),{...n}}addNoteWithId(e,t=`local`){if(this.notes.has(e.id))return;let n=this.stored(e);n.zIndex>=this.zCounter&&(this.zCounter=n.zIndex+1),this.notes.set(n.id,n),this.renderNote(n),this.emitter.emit(`note:create`,{note:{...n},origin:t})}updateNote(e,t){let n=this.applyParams(e,t);n&&this.emitUpdate(n.note,n.prev)}replayUpdate(e,t,n){let r=this.applyParams(e,t);r&&this.emitter.emit(`note:update`,{note:{...r.note},prev:r.prev,origin:n})}applyParams(e,t){let n=this.notes.get(e);if(!n)return;let r={...n};return Object.assign(n,t,{id:e}),`meta`in t&&(n.meta=ue(t.meta)),!r.foldable!=!n.foldable&&(this.unfolded.delete(e),!n.foldable&&!(`height`in t)&&(n.height=this.openHeight(n)??n.height)),this.updateNoteElement(n,`text`in t),(`text`in t||`meta`in t)&&(this.drawByHost(n),this.requestUnder(e)),(`autoSize`in t||`foldable`in t||`text`in t||`meta`in t||`width`in t||`height`in t)&&this.applyMeasuredSize(n),{note:n,prev:r}}stored(e){let{meta:t,...n}=e,r=ue(t);return r?{...n,meta:r}:n}drawByHost(e){if(!this.hostRender)return!1;let t=this.elements.get(e.id),n=t?.querySelector(`:scope > .wema-note-custom`);if(!t||!n)return!1;n.replaceChildren();let r=!1;try{r=this.hostRender({...e},n)===!0}catch(t){console.error(`Error in renderNote for note "${e.id}":`,t)}let i=t.classList.contains(Xe);return r&&!i&&this.getTextElement(e.id)?.blur(),r||n.replaceChildren(),t.classList.toggle(Xe,r),this.applyEditable(e.id),r!==i}refresh(e){let t=this.notes.get(e);if(!t)return!1;let n=this.drawByHost(t);return Je(t)&&this.measure(e),this.requestUnder(e),n}underElement(e){return this.elements.get(e)?.querySelector(`:scope > .wema-note-under`)??null}slotElement(e,t){return this.underElement(t)?.querySelector(`:scope > .${e.elementClass}`)??null}requestSlot(e,t){e.draw&&e.shown&&this.notes.has(t)&&e.drawing!==t&&(e.stale.add(t),this.onUnderChange())}requestFooter(e){this.requestSlot(this.footer,e)}requestAccessory(e){this.requestSlot(this.accessory,e)}requestUnder(e){this.requestAccessory(e),this.requestFooter(e)}setFootersShown(e){let t=this.footer;if(t.draw&&t.shown!==e){if(t.shown=e,e)t.stale=new Set(this.notes.keys()),this.onUnderChange();else{t.stale.clear();for(let e of this.notes.keys())this.emptySlot(t,e);for(let e of this.notes.keys())this.keepUnderHeight(e)}}}drawUnder(){let e=new Set;for(let t of this.slots)this.drawSlot(t,e);let t=!1;for(let n of e)this.keepUnderHeight(n)&&(t=!0);return t}keepUnderHeight(e){let t=this.drawnUnder(e)?.offsetHeight??0;return t!==(this.underHeights.get(e)??0)&&(t>0?this.underHeights.set(e,t):this.underHeights.delete(e),!0)}drawSlot(e,t){let n=e.draw;if(!n||e.stale.size===0)return;let r=e.stale;e.stale=new Set;for(let i of r){let r=this.notes.get(i),a=this.elements.get(i),o=this.slotElement(e,i);if(!r||!a||!o)continue;let s=et(o);o.replaceChildren();let c=!1;e.drawing=i;try{c=n({...r},o)===!0}catch(t){console.error(`Error in ${e.option} for note "${i}":`,t)}finally{e.drawing=void 0}c||o.replaceChildren(),a.classList.toggle(e.drawnClass,c),this.watchUnder(i),t.add(i),c&&s!==void 0&&Array.from(o.querySelectorAll(`[${$e}]`)).find(e=>e.getAttribute($e)===s)?.focus({preventScroll:!0})}}emptySlot(e,t){this.slotElement(e,t)?.replaceChildren(),this.elements.get(t)?.classList.remove(e.drawnClass),this.watchUnder(t)}hasUnder(e){return this.slots.some(t=>e.classList.contains(t.drawnClass))}drawnUnder(e){let t=this.elements.get(e);return t&&this.hasUnder(t)?this.underElement(e):null}watchUnder(e){let t=this.underElement(e);t&&this.underObserver&&(this.drawnUnder(e)?this.underObserver.observe(t):this.underObserver.unobserve(t))}isHostDrawn(e){return this.elements.get(e)?.classList.contains(Xe)??!1}getTextElement(e){return this.isHostDrawn(e)?null:this.contentElement(e)}editContent(e,t){let n=this.getTextElement(e);if(!n||!this.isEditable(e))return!1;let r=t(n,w(n));return r?(n.focus(),T(r),this.syncNoteContent(e),!0):!1}contentElement(e){return this.elements.get(e)?.querySelector(`.wema-note-content`)??null}isEditable(e){return!this.readOnly&&!this.viewOnly&&!this.isHostDrawn(e)}applyEditable(e){let t=this.contentElement(e);if(!t)return;let n=this.isEditable(e);t.contentEditable=n?`true`:`false`,n||t.blur()}emitUpdate(e,t){let n=this.unreportedSizeBase.get(e.id);this.unreportedSizeBase.delete(e.id),this.emitter.emit(`note:update`,{note:{...e},prev:n?{...t,...n}:t,origin:`local`})}applyFold(e,t){if(!e.foldable&&!t.classList.contains(Ue))return;let n=t.querySelector(`:scope > .wema-note-content`),r=t.querySelector(`:scope > .wema-note-fold-toggle`);if(!n||!r||t.offsetWidth===0&&t.offsetHeight===0)return;t.classList.remove(We);let i=!!e.foldable&&!t.classList.contains(Xe)&&Ye(n),a=i&&!this.unfolded.has(e.id)&&this.editingId!==e.id;t.classList.toggle(Ue,i),t.classList.toggle(We,a);let o=a?this.labels.readMore:this.labels.showLess;r.textContent!==o&&(r.textContent=o),a&&(n.scrollTop=0)}toggleFold(e){let t=this.elements.get(e)?.classList.contains(We)??!1;this.editingId===e&&(this.contentElement(e)?.blur(),this.editingId=null),t?this.unfolded.add(e):this.unfolded.delete(e),this.measure(e)}openHeight(e){let t=this.elements.get(e.id);if(t&&!this.isHostDrawn(e.id))return!this.shownRects.has(e.id)&&!this.placedRects.has(e.id)&&(t.style.width=`${e.width}px`),this.atModelWidth(e,t,()=>(t.classList.remove(We,Ue),t.offsetHeight||void 0))}applyMeasuredSize(e){let t=this.elements.get(e.id);return!t||!this.isSizedByContent(e)&&!t.classList.contains(Ue)?!1:this.atModelWidth(e,t,()=>this.readMeasuredSize(e,t))}atModelWidth(e,t,n){let r=t.classList.contains(Be),i=this.shownRects.get(e.id)??this.placedRects.get(e.id);if(!r&&(!i||i.width===e.width))return n();t.classList.remove(Be),t.style.width=`${e.width}px`;try{return n()}finally{i&&(t.style.width=`${i.width}px`),t.classList.toggle(Be,r),r&&this.applyFold(e,t)}}readMeasuredSize(e,t){if(this.applyFold(e,t),!this.isSizedByContent(e))return!1;let n=e.autoSize?t.offsetWidth:e.width,r=t.offsetHeight;return n===0||r===0||n===e.width&&r===e.height?!1:(e.width=n,e.height=r,!0)}measure(e){let t=this.notes.get(e);if(!t)return;let n={width:t.width,height:t.height},r=this.applyMeasuredSize(t),i=this.placedRects.get(e),a=i&&this.elements.get(e);if(i&&a&&this.sizesAtWidth([{note:t,el:a,width:i.width}])[0].height!==i.height&&this.onPlacedMeasure(e),!r)return;let o=this.unreportedSizeBase.get(e)??n;o.width===t.width&&o.height===t.height?this.unreportedSizeBase.delete(e):this.unreportedSizeBase.set(e,o),this.onMeasure(e,n)}remeasure(e){this.measure(e)}hasMeasuredHeight(e){return!!this.notes.get(e)?.foldable&&!this.isHostDrawn(e)}isSizedByContent(e){return!!e.autoSize||this.hasMeasuredHeight(e.id)}resizeToContent(e){let t=this.notes.get(e),n=this.elements.get(e);if(!t||!n||t.autoSize)return;let{width:r,height:i}=this.atModelWidth(t,n,()=>{n.classList.add(ze);let e=getComputedStyle(n),t={width:Ve(n.offsetWidth,e.width),height:Ve(n.offsetHeight,e.height)};return n.classList.remove(ze),t});r!==0&&i!==0&&(r!==t.width||i!==t.height)&&this.updateNote(e,{width:r,height:i})}deleteNote(e,t=`local`){let n=this.notes.get(e);if(!n)return;let r=this.underElement(e);r&&this.underObserver?.unobserve(r);let i=this.elements.get(e);i&&(i.remove(),this.elements.delete(e)),this.notes.delete(e),this.unreportedSizeBase.delete(e),this.shownRects.delete(e),this.placedRects.delete(e),this.underHeights.delete(e),this.unfolded.delete(e),this.editingId===e&&(this.editingId=null),this.emitter.emit(`note:delete`,{note:{...n},origin:t})}getNote(e){let t=this.notes.get(e);return t?{...t}:void 0}setShownRect(e,t){if(t)this.shownRects.set(e,t);else if(!this.shownRects.delete(e))return;let n=this.notes.get(e),r=this.elements.get(e);n&&r&&this.applyStyles(r,n);let i=t?null:this.drawnUnder(e);i&&this.underObserver&&(this.underObserver.unobserve(i),this.underObserver.observe(i))}placeNotes(e,t,n){let r=new Map;for(let[e,t]of this.notes)r.set(e,this.placedRects.get(e)??qe(t));let i=new Set(e),a=new Set;for(let e of[...this.placedRects.keys()])i.has(e)||(this.placedRects.delete(e),a.add(e));let o=[],s=[];for(let e of i){let n=this.notes.get(e),i=this.elements.get(e);if(!n||!i)continue;let a={...r.get(e),width:t??n.width};this.placedRects.has(e)&&this.placedRects.get(e).width===a.width||s.push({note:n,el:i}),this.placedRects.set(e,a),o.push({note:n,el:i})}for(let{note:e,el:t}of s)this.applyStyles(t,e);for(let{note:e,el:t}of s)this.applyFold(e,t);let c=this.sizesAtWidth(o.map(({note:e,el:t})=>({note:e,el:t,width:this.placedRects.get(e.id).width}))),l=o.map(({note:e},t)=>{let n=this.placedRects.get(e.id),{height:r,under:i}=c[t];return n.height=r,i>0?this.underHeights.set(e.id,i):this.underHeights.delete(e.id),{...e,width:n.width,height:r+i}});for(let e of n(l)){let t=this.placedRects.get(e.id);t&&(e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y))}let u=[];for(let[e,t]of this.notes){if(!Ke(this.placedRects.get(e)??t,r.get(e))&&!a.has(e))continue;u.push(e);let n=this.elements.get(e);n&&this.applyStyles(n,t)}return u}sizesAtWidth(e){let t=e.map(({note:e,el:t,width:n})=>{let r=this.isSizedByContent(e),i=this.drawnUnder(e.id),a=this.shownRects.get(e.id);return{note:e,el:t,width:n,sized:r,under:i,restore:(r||i!==null)&&a!==void 0&&a.width!==n?a.width:void 0}}),n=t.filter(e=>e.restore!==void 0);for(let{el:e,width:t}of n)e.style.width=`${t}px`;for(let{note:e,el:t,sized:r}of n)r&&this.applyFold(e,t);let r=t.map(({note:e,el:t,sized:n,under:r})=>({height:n&&t.offsetHeight||e.height,under:r?.offsetHeight??0}));for(let{el:e,restore:t}of n)e.style.width=`${t}px`;return r}getPlacedNote(e){let t=this.notes.get(e);if(t)return{...t,...this.placedRects.get(e)}}isPlaced(e){return this.placedRects.has(e)}getPlacedBoxes(){return Array.from(this.notes.values(),e=>{let t={...e,...this.placedRects.get(e.id)};return t.height+=this.underHeights.get(e.id)??0,t})}getShownBox(e){let t=this.getShownNote(e),n=this.underHeights.get(e);return t&&n?{...t,height:t.height+n}:t}getShownNote(e){let t=this.notes.get(e);if(!t)return;let n=this.shownRects.get(e);if(!n)return this.getPlacedNote(e);let r={...n},i=this.isSizedByContent(t)?this.elements.get(e):void 0;return i&&(t.autoSize&&(r.width=i.offsetWidth||r.width),r.height=i.offsetHeight||r.height),{...t,...r}}getNotes(){return Array.from(this.notes.values()).map(e=>({...e}))}lowestBottom(e){let t=null;for(let n of this.notes.values()){if(!e(n.id))continue;let r=this.placedRects.get(n.id)??n;t=Math.max(t??-1/0,r.y+r.height+(this.underHeights.get(n.id)??0))}return t}getElement(e){return this.elements.get(e)}bringToFront(e){let t=this.notes.get(e);t&&(t.zIndex=this.zCounter++,this.updateNoteElement(t,!1))}setReadOnly(e){this.readOnly=e;for(let[t,n]of this.elements){this.applyEditable(t);let r=n.querySelector(`.wema-resize-handle`);r&&(r.style.display=e?`none`:``);let i=n.querySelector(`.wema-move-handle`);i&&(i.style.visibility=e?`hidden`:``)}}setViewOnly(e){this.viewOnly=e;for(let[t,n]of this.elements){this.applyEditable(t);let r=n.querySelector(`.wema-resize-handle`);r&&(r.style.display=e||this.readOnly?`none`:``);let i=n.querySelector(`.wema-move-handle`);i&&(i.style.visibility=this.readOnly?`hidden`:``)}}getNotesWithLiveText(){return Array.from(this.notes.values()).map(e=>{let t=this.getTextElement(e.id);return{...e,text:t?t.innerHTML:e.text}})}destroy(){this.boardEl.removeEventListener(`click`,this.handleImageOverlayDismiss,!0);for(let e of this.slots)e.shown=!1,e.stale.clear();this.underObserver?.disconnect(),this.imageOverlay.remove()}showImageOverlay(e,t){this.activeImage=e,this.activeImageNoteId=t,e.classList.add(`wema-image-selected`),this.imageOverlay.innerHTML=``;for(let n of[{label:`S`,width:`25%`},{label:`M`,width:`50%`},{label:`L`,width:`75%`},{label:`100%`,width:`100%`}]){let r=v(`button`,`wema-image-overlay-btn`);r.textContent=n.label,r.title=n.width,(e.style.width===n.width||!e.style.width&&n.width===`100%`)&&r.classList.add(`active`),r.addEventListener(`click`,()=>{e.style.width=n.width,this.syncNoteContent(t),this.showImageOverlay(e,t)}),this.imageOverlay.appendChild(r)}let n=v(`button`,`wema-image-overlay-btn wema-image-overlay-delete`);n.textContent=`✕`,y(n,this.labels.deleteImage),n.addEventListener(`click`,()=>{e.remove(),this.hideImageOverlay(),this.syncNoteContent(t)}),this.imageOverlay.appendChild(n),this.imageOverlay.style.display=``,this.updateOverlayPosition()}updateOverlayPosition(){this.activeImage&&b(this.imageOverlay,this.boardEl,x(this.activeImage,this.boardEl),`above`,4)}hideImageOverlay(){this.imageOverlay.style.display=`none`,this.activeImage&&this.activeImage.classList.remove(`wema-image-selected`),this.activeImage=null,this.activeImageNoteId=null}syncNoteContent(e){let t=this.getTextElement(e);if(!t)return;let n=this.notes.get(e);if(!n)return;let r={...n};n.text=t.innerHTML,n.text!==r.text&&this.requestUnder(e);let i=this.applyMeasuredSize(n);(n.text!==r.text||i||this.unreportedSizeBase.has(e))&&this.emitUpdate(n,r)}clear(){for(let e of this.elements.values())e.remove();this.elements.clear(),this.notes.clear(),this.unreportedSizeBase.clear(),this.shownRects.clear(),this.placedRects.clear();for(let e of this.slots)e.stale.clear();this.underHeights.clear(),this.underObserver?.disconnect(),this.unfolded.clear(),this.editingId=null,this.zCounter=1}renderAll(e){this.clear();for(let t of e)this.notes.set(t.id,this.stored(t)),t.zIndex>=this.zCounter&&(this.zCounter=t.zIndex+1),this.renderNote(this.notes.get(t.id),!1);for(let e of this.notes.values())Je(e)&&this.applyMeasuredSize(e)}renderNote(e,t=!0){let n=v(`div`,`wema-note`);n.dataset.noteId=e.id;let r=v(`div`,`wema-move-handle`);r.style.position=`relative`,r.innerHTML=`<svg width="20" height="10" viewBox="0 0 20 10"><circle cx="4" cy="3" r="1.5" fill="currentColor"/><circle cx="10" cy="3" r="1.5" fill="currentColor"/><circle cx="16" cy="3" r="1.5" fill="currentColor"/><circle cx="4" cy="8" r="1.5" fill="currentColor"/><circle cx="10" cy="8" r="1.5" fill="currentColor"/><circle cx="16" cy="8" r="1.5" fill="currentColor"/></svg>`,this.readOnly&&(r.style.visibility=`hidden`);let i=v(`div`,`wema-note-content`);i.innerHTML=N(e.text)?M(e.text):ae(e.text);let a=!1;i.addEventListener(`input`,()=>{a=!0,this.measure(e.id)}),i.addEventListener(`focus`,()=>{this.editingId=e.id,this.measure(e.id)}),i.addEventListener(`blur`,()=>{this.editingId===e.id&&(this.editingId=null),this.measure(e.id),a&&(a=!1,this.syncNoteContent(e.id))}),i.addEventListener(`paste`,e=>{e.preventDefault();let t=e.clipboardData?.getData(`text/html`),n=e.clipboardData?.getData(`text/plain`)??``;le(t?ae(t,{pasted:!0}):M(n).replace(/\n/g,`<br>`)),a=!0}),i.addEventListener(`click`,t=>{let n=t.target;if(n.tagName===`INPUT`&&n.type===`checkbox`)setTimeout(()=>{let t=n;t.checked?t.setAttribute(`checked`,``):t.removeAttribute(`checked`);let r=n.closest(`li`);r&&r.classList.toggle(`wema-checked`,t.checked),a=!0,this.syncNoteContent(e.id)},0);else if(n.tagName===`A`||n.closest(`a`)){let e=n.tagName===`A`?n:n.closest(`a`);t.preventDefault();let r=e.getAttribute(`href`),i=r?j(r):null;i&&this.onLinkClick?.(i,t)!==!0&&window.open(i,`_blank`,`noopener`)}else n.tagName===`IMG`&&(t.preventDefault(),!this.readOnly&&!this.viewOnly&&this.showImageOverlay(n,e.id))}),i.addEventListener(`keydown`,t=>{if(t.key!==`Tab`||t.isComposing||t.ctrlKey||t.metaKey||t.altKey||!this.isEditable(e.id))return;let n=w(i);if(!n||!xe(i,n))return;t.preventDefault();let r=t.shiftKey?Re:Le;this.editContent(e.id,(e,t)=>t&&r(e,t))}),i.addEventListener(`keydown`,t=>{if(t.key!==`Enter`||t.isComposing||!this.isEditable(e.id))return;let n=document.getSelection();if(!n||n.rangeCount===0)return;let r=(n.anchorNode?.nodeType===Node.TEXT_NODE?n.anchorNode.parentElement:n.anchorNode)?.closest(`li`);if(!r||!r.parentElement||L(r.parentElement)!==`checklist`)return;t.preventDefault();let i=Ce(`checklist`);i.appendChild(document.createTextNode(` `));let o=n.getRangeAt(0),s=document.createRange();s.setStart(o.endContainer,o.endOffset),s.setEndAfter(r.lastChild??r);let c=s.extractContents();for(let e of Array.from(c.children))e.tagName===`INPUT`&&e.type===`checkbox`&&e.remove();i.appendChild(c),r.parentNode?.insertBefore(i,r.nextSibling);let l=document.createRange();l.setStart(i,2),l.collapse(!0),T(l),a=!0});let o=v(`div`,`wema-note-anchors`);for(let e of[`top`,`right`,`bottom`,`left`]){let t=v(`div`,`wema-anchor wema-anchor-${e}`);t.dataset.anchor=e,o.appendChild(t)}let s=v(`div`,`wema-resize-handle`);(this.readOnly||this.viewOnly)&&(s.style.display=`none`);for(let e of[`top`,`right`,`bottom`,`left`]){let t=v(`div`,`wema-note-collapse-btn`);t.dataset.side=e,t.style.display=`none`,t.addEventListener(`pointerdown`,e=>e.stopPropagation()),t.addEventListener(`click`,e=>e.stopPropagation()),n.appendChild(t)}n.appendChild(r),n.appendChild(i),n.appendChild(v(`div`,`wema-note-custom`));let c=v(`button`,`wema-note-fold-toggle`);c.type=`button`,c.addEventListener(`pointerdown`,e=>e.stopPropagation()),c.addEventListener(`mousedown`,e=>e.preventDefault()),c.addEventListener(`click`,t=>{t.stopPropagation(),this.toggleFold(e.id)}),n.appendChild(c),n.appendChild(o),n.appendChild(s);let l=this.slots.filter(e=>e.draw);if(l.length>0){let e=v(`div`,`wema-note-under`);for(let t of[`pointerdown`,`click`,`dblclick`,`keydown`])e.addEventListener(t,e=>e.stopPropagation());for(let t of l)e.appendChild(v(`div`,t.elementClass));n.appendChild(e)}this.applyStyles(n,e),this.layerEl.appendChild(n),this.elements.set(e.id,n),this.applyEditable(e.id),this.drawByHost(e),this.requestUnder(e.id),t&&Je(e)&&this.applyMeasuredSize(e)}updateNoteElement(e,t){let n=this.elements.get(e.id);if(!n)return;this.applyStyles(n,e);let r=n.querySelector(`.wema-note-content`);t&&r&&r.innerHTML!==e.text&&document.activeElement!==r&&(r.innerHTML=N(e.text)?M(e.text):ae(e.text)),Je(e)&&requestAnimationFrame(()=>this.measure(e.id))}applyStyles(e,t){let n=this.placedRects.get(t.id),r=this.shownRects.get(t.id)??n??t;e.classList.toggle(Be,n!==void 0),E(e,{left:`${r.x}px`,top:`${r.y}px`,width:`${r.width}px`,height:`${r.height}px`,zIndex:String(t.zIndex)}),e.style.setProperty(`--wema-note-color`,t.color),e.classList.toggle(ze,!!t.autoSize),e.classList.toggle(He,!!t.foldable)}},nt=e=>1-(1-e)**3,rt=(e,t,n)=>e+(t-e)*n;function it(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}var at=class{noteManager;onFrame;running=new Map;frameId=0;constructor(e){this.noteManager=e.noteManager,this.onFrame=e.onFrame}start(e,t,n){this.running.set(e,{from:{...t},start:performance.now(),duration:n}),this.noteManager.setShownRect(e,t),this.frameId||=requestAnimationFrame(()=>this.tick())}cancel(e){return this.running.delete(e)?(this.noteManager.setShownRect(e,null),!0):!1}isRunning(){return this.running.size>0}clear(){this.running.clear(),this.frameId&&cancelAnimationFrame(this.frameId),this.frameId=0}tick(){this.frameId=0;let e=performance.now(),t=[];for(let[n,{from:r,start:i,duration:a}]of this.running){let o=this.noteManager.getPlacedNote(n),s=(e-i)/a;if(!o||s>=1)this.running.delete(n),this.noteManager.setShownRect(n,null);else{let e=nt(s);this.noteManager.setShownRect(n,{x:rt(r.x,o.x,e),y:rt(r.y,o.y,e),width:rt(r.width,o.width,e),height:rt(r.height,o.height,e)})}o&&t.push(n)}t.length>0&&this.onFrame(t),this.running.size>0&&(this.frameId=requestAnimationFrame(()=>this.tick()))}},ot=`${C}, a, button, label, summary, video[controls], audio[controls], [data-wema-no-drag]`;function st(e,t){let n=e.getBoundingClientRect();if(n.width===0||e.offsetWidth===0)return!1;let r=n.width/e.offsetWidth;return t.clientX-n.left>(e.clientLeft+e.clientWidth)*r||t.clientY-n.top>(e.clientTop+e.clientHeight)*r}var ct=class{state=`IDLE`;ctx=null;boardEl;noteManager;getReadOnly;getSelection;toBoardPoint;onDragStart;onDragEnd;handlePointerDown;handlePointerMove;handlePointerUp;constructor(e){this.toBoardPoint=e.toBoardPoint,this.boardEl=e.boardEl,this.noteManager=e.noteManager,this.getReadOnly=e.getReadOnly,this.getSelection=e.getSelection,this.onDragStart=e.onDragStart,this.onDragEnd=e.onDragEnd,this.handlePointerDown=this.onPointerDown.bind(this),this.handlePointerMove=this.onPointerMove.bind(this),this.handlePointerUp=this.onPointerUp.bind(this),this.boardEl.addEventListener(`pointerdown`,this.handlePointerDown)}destroy(){this.boardEl.removeEventListener(`pointerdown`,this.handlePointerDown),this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp),this.state=`IDLE`,this.ctx=null}onPointerDown(e){if(e.button!==0||this.getReadOnly())return;let t=e.target,n=t.closest(`.wema-note-custom`),r=n?.parentElement,i=!!r&&this.noteManager.getElement(r.dataset.noteId??``)===r,a=n!==null&&i&&t.closest(ot)===null&&!(t===n&&st(n,e));if(!t.closest(`.wema-move-handle`)&&!a)return;let o=t.closest(`.wema-note`);if(!o)return;e.preventDefault();let s=o.dataset.noteId;if(!s)return;let c=this.noteManager.getNote(s);if(!c)return;let l=this.getSelection(),u=null;if(l.length>1&&l.includes(s)){u=[];for(let e of l){let t=this.noteManager.getNote(e);t&&u.push({id:e,startX:t.x,startY:t.y})}}let d=this.toBoardPoint(e.clientX,e.clientY);this.ctx={noteId:s,startX:d.x,startY:d.y,startClientX:e.clientX,startClientY:e.clientY,noteStartX:c.x,noteStartY:c.y,pointerId:e.pointerId,groupOffsets:u},this.state=`PENDING`,this.boardEl.addEventListener(`pointermove`,this.handlePointerMove),this.boardEl.addEventListener(`pointerup`,this.handlePointerUp)}onPointerMove(e){if(!this.ctx)return;let t=this.toBoardPoint(e.clientX,e.clientY),n=t.x-this.ctx.startX,r=t.y-this.ctx.startY;if(this.state===`PENDING`){if(Math.abs(e.clientX-this.ctx.startClientX)<4&&Math.abs(e.clientY-this.ctx.startClientY)<4)return;this.state=`DRAGGING`,this.onDragStart?.(),this.boardEl.setPointerCapture(this.ctx.pointerId),this.noteManager.bringToFront(this.ctx.noteId)}if(this.state===`DRAGGING`){if(this.ctx.groupOffsets)for(let e of this.ctx.groupOffsets)this.noteManager.updateNote(e.id,{x:e.startX+n,y:e.startY+r});else{let e=this.ctx.noteStartX+n,t=this.ctx.noteStartY+r;this.noteManager.updateNote(this.ctx.noteId,{x:e,y:t})}}}onPointerUp(e){if(!this.ctx)return;this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp);let t=this.state===`DRAGGING`;if(t)try{this.boardEl.releasePointerCapture(this.ctx.pointerId)}catch{}let n=this.ctx.noteId;this.state=`IDLE`,this.ctx=null,t&&this.onDragEnd?.(n)}},lt=class{selected=new Set;noteManager;emitter;layerEl;isSelectable;rubberBandEl=null;rubberBandStart=null;rubberBandActive=!1;constructor(e){this.layerEl=e.layerEl,this.noteManager=e.noteManager,this.emitter=e.emitter,this.isSelectable=e.isSelectable}canSelect(e){return this.noteManager.getNote(e)!==void 0&&this.isSelectable(e)}select(e){for(let e of this.selected)this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`);this.selected.clear();for(let t of e)this.canSelect(t)&&(this.selected.add(t),this.noteManager.getElement(t)?.classList.add(`wema-note-selected`));this.emitter.emit(`note:select`,{noteIds:this.getSelection()})}selectAll(){let e=this.noteManager.getNotes().map(e=>e.id);this.select(e)}getSelection(){return Array.from(this.selected)}addToSelection(e){for(let t of e)this.canSelect(t)&&!this.selected.has(t)&&(this.selected.add(t),this.noteManager.getElement(t)?.classList.add(`wema-note-selected`));this.emitter.emit(`note:select`,{noteIds:this.getSelection()})}toggleSelection(e){this.selected.has(e)?(this.selected.delete(e),this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`)):this.canSelect(e)&&(this.selected.add(e),this.noteManager.getElement(e)?.classList.add(`wema-note-selected`)),this.emitter.emit(`note:select`,{noteIds:this.getSelection()})}deselect(e){this.selected.has(e)&&(this.selected.delete(e),this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`))}clear(){if(this.selected.size!==0){for(let e of this.selected)this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`);this.selected.clear(),this.emitter.emit(`note:select`,{noteIds:[]})}}startRubberBand(e,t){this.rubberBandStart={x:e,y:t},this.rubberBandActive=!0,this.rubberBandEl=v(`div`,`wema-rubberband`),this.rubberBandEl.style.left=`${e}px`,this.rubberBandEl.style.top=`${t}px`,this.rubberBandEl.style.width=`0`,this.rubberBandEl.style.height=`0`,this.layerEl.appendChild(this.rubberBandEl)}updateRubberBand(e,t){if(!this.rubberBandStart||!this.rubberBandEl)return;let n=Math.min(e,this.rubberBandStart.x),r=Math.min(t,this.rubberBandStart.y),i=Math.abs(e-this.rubberBandStart.x),a=Math.abs(t-this.rubberBandStart.y);this.rubberBandEl.style.left=`${n}px`,this.rubberBandEl.style.top=`${r}px`,this.rubberBandEl.style.width=`${i}px`,this.rubberBandEl.style.height=`${a}px`;let o={left:n,top:r,right:n+i,bottom:r+a},s=[];for(let{id:e}of this.noteManager.getNotes()){let t=this.noteManager.getShownNote(e),n=t.x+t.width,r=t.y+t.height;t.x<o.right&&n>o.left&&t.y<o.bottom&&r>o.top&&s.push(t.id)}this.select(s)}endRubberBand(){this.rubberBandEl&&=(this.rubberBandEl.remove(),null),this.rubberBandStart=null,this.rubberBandActive=!1}isRubberBandActive(){return this.rubberBandActive}destroy(){this.endRubberBand(),this.clear()}},ut=`wema-arrowhead`,dt=[8,12,18],ft=12;function pt(e){return e.arrowHead??(e.style===`arrow`?`end`:`none`)}var mt=class{edges=new Map;groupElements=new Map;pathElements=new Map;hitElements=new Map;labelElements=new Map;svgEl;emitter;noteManager;selectedEdge=null;constructor(e){this.svgEl=e.svgEl,this.emitter=e.emitter,this.noteManager=e.noteManager,this.ensureMarkerDefs()}hitTest(e,t){let n=document.elementsFromPoint(e,t);for(let e of n)if(e.classList.contains(`wema-edge-hit`)){let t=e.dataset.edgeId;if(t&&this.edges.has(t))return t}return null}addEdge(e,t,n){if(e===t||!this.noteManager.getNote(e)||!this.noteManager.getNote(t))return;let r={id:o(),from:e,to:t,fromAnchor:n?.fromAnchor??`auto`,toAnchor:n?.toAnchor??`auto`,style:n?.style??`arrow`,label:n?.label};return this.edges.set(r.id,r),this.renderEdge(r),this.emitter.emit(`edge:create`,{edge:{...r},origin:`local`}),{...r}}addEdgeWithId(e,t=`local`){if(this.edges.has(e.id)||!this.noteManager.getNote(e.from)||!this.noteManager.getNote(e.to))return;let n={...e};this.edges.set(n.id,n),this.renderEdge(n),this.emitter.emit(`edge:create`,{edge:{...n},origin:t})}deleteEdge(e,t=`local`){let n=this.edges.get(e);n&&(this.removeEdgeElements(e),this.edges.delete(e),this.selectedEdge===e&&(this.selectedEdge=null),this.emitter.emit(`edge:delete`,{edge:{...n},origin:t}))}updateEdge(e,t,n=`local`){let r=this.edges.get(e);if(!r)return;let i={...r};Object.assign(r,t,{id:r.id,from:r.from,to:r.to});let a=this.pathElements.get(e);a&&this.applyEdgeStyle(a,r),this.updateEdgePath(e),this.emitter.emit(`edge:update`,{edge:{...r},prev:i,origin:n})}getEdge(e){let t=this.edges.get(e);return t?{...t}:void 0}getEdges(){return Array.from(this.edges.values()).map(e=>({...e}))}getEdgesOf(e){let t=[];for(let n of this.edges.values())(n.from===e||n.to===e)&&t.push({...n});return t}getSelectedEdge(){return this.selectedEdge}selectEdge(e){this.deselectEdge(),this.selectedEdge=e,this.pathElements.get(e)?.classList.add(`wema-edge-selected`)}deselectEdge(){this.selectedEdge&&=(this.pathElements.get(this.selectedEdge)?.classList.remove(`wema-edge-selected`),null)}updateEdgesOf(e){this.updateEdgesOfNotes([e])}updateEdgesOfNotes(e){let t=new Set(e),n=[],r=new Map;for(let[e,i]of this.edges)if(t.has(i.from)||t.has(i.to)){n.push(e);for(let e of[i.from,i.to])r.has(e)||r.set(e,this.noteManager.getShownNote(e))}for(let e of n)this.updateEdgePath(e,r)}clear(){for(let e of this.edges.keys())this.removeEdgeElements(e);this.edges.clear(),this.selectedEdge=null}renderAll(e){this.clear();for(let t of e)this.edges.set(t.id,{...t}),this.renderEdge(this.edges.get(t.id))}applyVisibility(e){for(let[t]of this.edges){let n=this.groupElements.get(t);n&&(n.style.display=e.has(t)?`none`:``)}}destroy(){this.clear()}ensureMarkerDefs(){let e=this.svgEl.querySelector(`defs`);e||(e=S(`defs`),this.svgEl.prepend(e));for(let t of dt){let n=`${ut}-${t}`;if(!e.querySelector(`#${n}`)){let r=S(`marker`);r.id=n,r.setAttribute(`viewBox`,`0 0 10 10`),r.setAttribute(`refX`,`10`),r.setAttribute(`refY`,`5`),r.setAttribute(`markerWidth`,String(t)),r.setAttribute(`markerHeight`,String(t)),r.setAttribute(`markerUnits`,`userSpaceOnUse`),r.setAttribute(`orient`,`auto-start-reverse`);let i=S(`path`);i.setAttribute(`d`,`M 0 0 L 10 5 L 0 10 Z`),i.setAttribute(`class`,`wema-arrow-fill`),r.appendChild(i),e.appendChild(r)}}}renderEdge(e){let t=this.noteManager.getNote(e.from),n=this.noteManager.getNote(e.to);if(!t||!n)return;let r=S(`g`,`wema-edge-group`);r.dataset.edgeId=e.id;let i=S(`path`,`wema-edge-hit`);i.dataset.edgeId=e.id,i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`stroke-width`,`20`),i.style.pointerEvents=`all`;let a=S(`path`,`wema-edge-path`);if(a.setAttribute(`fill`,`none`),a.dataset.edgeId=e.id,this.applyEdgeStyle(a,e),r.appendChild(i),r.appendChild(a),e.label){let t=S(`text`,`wema-edge-label`);t.textContent=e.label,t.setAttribute(`text-anchor`,`middle`),t.setAttribute(`dy`,`-6`),r.appendChild(t),this.labelElements.set(e.id,t)}this.svgEl.appendChild(r),this.groupElements.set(e.id,r),this.hitElements.set(e.id,i),this.pathElements.set(e.id,a),this.updateEdgePath(e.id)}updateEdgePath(e,t){let n=this.edges.get(e);if(!n)return;let r=t?t.get(n.from):this.noteManager.getShownNote(n.from),i=t?t.get(n.to):this.noteManager.getShownNote(n.to);if(!r||!i)return;let a=h(r,i,n.fromAnchor,n.toAnchor,n.routing),o=this.pathElements.get(e),s=this.hitElements.get(e);o?.setAttribute(`d`,a),s?.setAttribute(`d`,a);let c=this.labelElements.get(e);if(c){let e=(r.x+r.width/2+i.x+i.width/2)/2,t=(r.y+r.height/2+i.y+i.height/2)/2;c.setAttribute(`x`,String(e)),c.setAttribute(`y`,String(t))}}applyEdgeStyle(e,t){let n=t.lineStyle??(t.style===`dashed`?`dashed`:`solid`),r=pt(t),i=t.strokeWidth??2,a=t.arrowSize??ft;switch(n){case`solid`:e.removeAttribute(`stroke-dasharray`);break;case`dashed`:e.setAttribute(`stroke-dasharray`,`8 4`);break;case`dotted`:e.setAttribute(`stroke-dasharray`,`3 3`)}let o=`url(#${`${ut}-${a}`})`;r===`end`||r===`both`?e.setAttribute(`marker-end`,o):e.removeAttribute(`marker-end`),r===`start`||r===`both`?e.setAttribute(`marker-start`,o):e.removeAttribute(`marker-start`),e.style.strokeWidth=`${i}px`}removeEdgeElements(e){this.groupElements.get(e)?.remove(),this.groupElements.delete(e),this.pathElements.delete(e),this.hitElements.delete(e),this.labelElements.get(e)?.remove(),this.labelElements.delete(e)}},ht=[`out`,`in`,`both`,`none`],gt={out:`→`,in:`←`,both:`↔`,none:`―`},_t={out:`linkOut`,in:`linkIn`,both:`linkBoth`,none:`linkNone`},vt=`wema-note-link-target`,yt=1400,bt=new Set([`ADDRESS`,`BLOCKQUOTE`,`BR`,`DD`,`DIV`,`DL`,`DT`,`FIGURE`,`H1`,`H2`,`H3`,`H4`,`H5`,`H6`,`HR`,`IFRAME`,`LI`,`OL`,`P`,`PRE`,`TABLE`,`TD`,`TH`,`TR`,`UL`]),xt=new Set([`template`,`iframe`,`video`,`audio`]),St=/[​]/g,Ct=e=>{let t=e.nodeName.toLowerCase();return O.has(t)||xt.has(t)||e.style?.display===`none`};function wt(e,t){for(let n of e.childNodes)if(n.nodeType===Node.TEXT_NODE){let[e,...r]=(n.nodeValue??``).split(`
4
+ `);t[t.length-1]+=e,t.push(...r)}else if(n.nodeType===Node.ELEMENT_NODE&&!Ct(n)){let e=bt.has(n.nodeName);e&&t.push(``),wt(n,t),e&&t.push(``)}}function Tt(e){let t;N(e)?t=e.split(`
5
+ `):(t=[``],wt(new DOMParser().parseFromString(`<body>${e}</body>`,`text/html`).body,t));for(let e of t){let t=e.replace(St,``).trim();if(t!==``)return t}return``}function Et(e,t){let n=t?.get(e.id);if(n&&n.text===e.text)return n.line;let r=Tt(e.text);return t?.set(e.id,{text:e.text,line:r}),r}var Dt=(e,t)=>e.from===t?e.to:e.from;function Ot(e,t){let n=pt(e);return n===`both`||n===`none`?n:n===`end`==(e.from===t)?`out`:`in`}function kt(e,t,n,r,i){let a=[];for(let o of t){let t=Dt(o,e),s=t===e?void 0:n(t);if(!s)continue;let c;try{c=r?.(s,o)}catch(e){console.error(`Error in noteLinks.text for note "${t}":`,e)}let l=typeof c==`string`?c.trim():``,u=o.label?.trim();a.push({edgeId:o.id,direction:Ot(o,e),peer:t,text:l===``?Et(s,i):l,...u?{label:u}:{}})}return a.sort((e,t)=>ht.indexOf(e.direction)-ht.indexOf(t.direction))}var At=new WeakMap;function jt(e){clearTimeout(At.get(e)),e.classList.remove(vt),e.offsetWidth,e.classList.add(vt),At.set(e,setTimeout(()=>e.classList.remove(vt),yt))}function Mt(e,t,n){let r=n[_t[e.direction]](t);return e.label===void 0?r:n.linkLabeled(r,e.label)}function Nt(e,t,n){if(t.length===0)return!1;let r=v(`div`,`wema-note-links`);for(let e of t){let t=e.text===``?n.labels.linkEmpty:e.text,i=v(`button`,`wema-note-link`);i.type=`button`,i.setAttribute($e,e.edgeId),i.setAttribute(`aria-label`,Mt(e,t,n.labels)),i.disabled=n.isHidden(e.peer);let a=[[`wema-note-link-arrow`,gt[e.direction]],[`wema-note-link-label`,e.label],[`wema-note-link-text`,t]];for(let[e,t]of a){if(t===void 0)continue;let n=v(`span`,e);n.textContent=t,i.appendChild(n)}i.addEventListener(`click`,()=>{n.reveal(e.peer);let t=n.getElement(e.peer);t&&jt(t)}),r.appendChild(i)}return e.appendChild(r),!0}var Pt=class{boardEl;svgEl;noteManager;edgeManager;emitter;getReadOnly;toBoardPoint;onDropOnEmpty;dragging=!1;fromNoteId=null;fromAnchor=null;tempPath=null;handlePointerDown;handlePointerMove;handlePointerUp;constructor(e){this.toBoardPoint=e.toBoardPoint,this.boardEl=e.boardEl,this.svgEl=e.svgEl,this.noteManager=e.noteManager,this.edgeManager=e.edgeManager,this.emitter=e.emitter,this.getReadOnly=e.getReadOnly,this.onDropOnEmpty=e.onDropOnEmpty,this.handlePointerDown=this.onPointerDown.bind(this),this.handlePointerMove=this.onPointerMove.bind(this),this.handlePointerUp=this.onPointerUp.bind(this),this.boardEl.addEventListener(`pointerdown`,this.handlePointerDown)}destroy(){this.boardEl.removeEventListener(`pointerdown`,this.handlePointerDown),this.cleanup()}onPointerDown(e){if(e.button!==0||this.getReadOnly())return;let t=e.target.closest(`.wema-anchor`);if(!t)return;let n=t.closest(`.wema-note`);if(!n)return;let r=n.dataset.noteId,i=t.dataset.anchor;r&&i&&(e.preventDefault(),e.stopPropagation(),this.dragging=!0,this.fromNoteId=r,this.fromAnchor=i,this.tempPath=S(`path`,`wema-edge-temp`),this.tempPath.setAttribute(`fill`,`none`),this.svgEl.appendChild(this.tempPath),this.boardEl.addEventListener(`pointermove`,this.handlePointerMove),this.boardEl.addEventListener(`pointerup`,this.handlePointerUp),this.boardEl.setPointerCapture(e.pointerId))}onPointerMove(e){if(!this.dragging||!this.fromNoteId||!this.fromAnchor||!this.tempPath)return;let t=this.noteManager.getShownNote(this.fromNoteId);if(!t)return;let n=this.toBoardPoint(e.clientX,e.clientY),r=_(t,this.fromAnchor,n);this.tempPath.setAttribute(`d`,r),this.clearHighlight();let i=document.elementFromPoint(e.clientX,e.clientY);if(i){let e=i.closest?.(`.wema-note`);e&&e.dataset.noteId!==this.fromNoteId&&e.classList.add(`wema-note-drop-target`)}}onPointerUp(e){if(!this.dragging)return;this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp);try{this.boardEl.releasePointerCapture(e.pointerId)}catch{}let t=document.elementFromPoint(e.clientX,e.clientY),n=null;if(t){let e=t.closest?.(`.wema-anchor`);e?(e.dataset.anchor,n=e.closest(`.wema-note`)?.dataset.noteId??null):n=(t.closest?.(`.wema-note`))?.dataset.noteId??null}if(n&&n!==this.fromNoteId&&this.fromNoteId)this.edgeManager.addEdge(this.fromNoteId,n,{fromAnchor:`auto`,toAnchor:`auto`});else if(!n&&this.fromNoteId){let{x:t,y:n}=this.toBoardPoint(e.clientX,e.clientY);this.onDropOnEmpty?.(t,n,this.fromNoteId)}this.cleanup()}cleanup(){this.tempPath?.remove(),this.tempPath=null,this.dragging=!1,this.fromNoteId=null,this.fromAnchor=null,this.clearHighlight()}clearHighlight(){this.boardEl.querySelectorAll(`.wema-note-drop-target`).forEach(e=>{e.classList.remove(`wema-note-drop-target`)})}},Ft=80,It=60,Lt=500,Rt=class{boardEl;noteManager;getReadOnly;toBoardPoint;onResizeStart;onResizeEnd;ctx=null;onDoublePress;firstPress=null;pressedHandle=!1;handlePointerDown;handlePointerMove;handlePointerUp;handleClickAfterPress;handleAnyPointerDown;constructor(e){this.toBoardPoint=e.toBoardPoint,this.boardEl=e.boardEl,this.noteManager=e.noteManager,this.getReadOnly=e.getReadOnly,this.onResizeStart=e.onResizeStart,this.onResizeEnd=e.onResizeEnd,this.handlePointerDown=this.onPointerDown.bind(this),this.handlePointerMove=this.onPointerMove.bind(this),this.handlePointerUp=this.onPointerUp.bind(this),this.onDoublePress=e.onDoublePress,this.handleClickAfterPress=this.onClickAfterPress.bind(this),this.handleAnyPointerDown=this.onAnyPointerDown.bind(this),this.boardEl.addEventListener(`pointerdown`,this.handleAnyPointerDown,!0),this.boardEl.addEventListener(`pointerdown`,this.handlePointerDown),this.boardEl.addEventListener(`click`,this.handleClickAfterPress,!0),this.boardEl.addEventListener(`dblclick`,this.handleClickAfterPress,!0)}destroy(){this.boardEl.removeEventListener(`click`,this.handleClickAfterPress,!0),this.boardEl.removeEventListener(`dblclick`,this.handleClickAfterPress,!0),this.boardEl.removeEventListener(`pointerdown`,this.handleAnyPointerDown,!0),this.boardEl.removeEventListener(`pointerdown`,this.handlePointerDown),this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp),this.ctx=null}noteOfHandle(e){return e.button!==0||this.getReadOnly()?null:(e.target.closest(`.wema-resize-handle`)?.closest(`.wema-note`))?.dataset.noteId??null}onClickAfterPress(e){if(!this.pressedHandle)return;let t=e.target;(t===this.boardEl||t.closest(`.wema-resize-handle`))&&(e.preventDefault(),e.stopImmediatePropagation())}onAnyPointerDown(){this.pressedHandle=!1}isSecondPress(e,t){let n=this.firstPress;return n!==null&&n.noteId===t&&e.timeStamp-n.time<Lt&&Math.hypot(e.clientX-n.clientX,e.clientY-n.clientY)<4}onPointerDown(e){let t=this.noteOfHandle(e);if(!t)return;let n=this.noteManager.getNote(t);if(!n||n.autoSize)return;if(e.preventDefault(),e.stopPropagation(),this.pressedHandle=!0,this.isSecondPress(e,t)){this.firstPress=null,this.onDoublePress?.(t);return}this.firstPress={noteId:t,time:e.timeStamp,clientX:e.clientX,clientY:e.clientY};let r=this.toBoardPoint(e.clientX,e.clientY);this.ctx={noteId:t,startX:r.x,startY:r.y,startWidth:n.width,startHeight:n.height,pointerId:e.pointerId},this.boardEl.setPointerCapture(e.pointerId),this.boardEl.addEventListener(`pointermove`,this.handlePointerMove),this.boardEl.addEventListener(`pointerup`,this.handlePointerUp),this.onResizeStart?.()}onPointerMove(e){if(!this.ctx)return;let t=this.firstPress;if(t){if(Math.hypot(e.clientX-t.clientX,e.clientY-t.clientY)<4)return;this.firstPress=null}let n=this.toBoardPoint(e.clientX,e.clientY),r=n.x-this.ctx.startX,i=n.y-this.ctx.startY,{startWidth:a,startHeight:o}=this.ctx,s=Math.max(Math.min(Ft,a),a+r),c=Math.max(Math.min(It,o),o+i),l=this.noteManager.hasMeasuredHeight(this.ctx.noteId);this.noteManager.updateNote(this.ctx.noteId,l?{width:s}:{width:s,height:c})}onPointerUp(e){if(this.ctx){this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp);try{this.boardEl.releasePointerCapture(this.ctx.pointerId)}catch{}this.onResizeEnd?.(),this.ctx=null}}},zt={solid:{svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/></svg>`,label:`lineSolid`},dashed:{svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2" stroke-dasharray="4 3"/></svg>`,label:`lineDashed`},dotted:{svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2" stroke-dasharray="2 2"/></svg>`,label:`lineDotted`}},Bt=[{value:`none`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/></svg>`,label:`arrowNone`},{value:`start`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="8" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="8,8 14,5 14,11" fill="currentColor"/></svg>`,label:`arrowStart`},{value:`end`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="16" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="16,5 22,8 16,11" fill="currentColor"/></svg>`,label:`arrowEnd`},{value:`both`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="8" y1="8" x2="16" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="8,8 14,5 14,11" fill="currentColor"/><polygon points="16,5 22,8 16,11" fill="currentColor"/></svg>`,label:`arrowBoth`}],Vt=[{value:8,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="14" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="14,5.5 19,8 14,10.5" fill="currentColor"/></svg>`,label:`sizeSmall`},{value:12,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="13" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="13,4 21,8 13,12" fill="currentColor"/></svg>`,label:`sizeMedium`},{value:18,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="11" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="11,2 23,8 11,14" fill="currentColor"/></svg>`,label:`sizeLarge`}],Ht=[{value:1,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="1"/></svg>`,label:`widthThin`},{value:2,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/></svg>`,label:`widthNormal`},{value:4,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="4"/></svg>`,label:`widthThick`}],Ut=[{value:`curve`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><path d="M2 14 C8 14, 16 2, 22 2" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,label:`routeCurve`},{value:`polyline`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><polyline points="2,14 2,2 22,2" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,label:`routePolyline`}],Wt=[{value:`auto`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><circle cx="12" cy="8" r="4" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="12" cy="8" r="1.5" fill="currentColor"/></svg>`,label:`anchorAuto`},{value:`top`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="6" y="4" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="12" cy="4" r="2" fill="currentColor"/></svg>`,label:`anchorTop`},{value:`right`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="4" y="3" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="16" cy="8" r="2" fill="currentColor"/></svg>`,label:`anchorRight`},{value:`bottom`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="6" y="2" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="12" cy="12" r="2" fill="currentColor"/></svg>`,label:`anchorBottom`},{value:`left`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="8" y="3" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="8" cy="8" r="2" fill="currentColor"/></svg>`,label:`anchorLeft`}],Gt=`<svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3,2 7,5 3,8"/></svg>`,Kt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>`,qt=class{popupEl;boardEl;edgeManager;noteManager;labels;onDelete;currentEdgeId=null;anchor={x:0,y:0};view;detailsOpen=!1;constructor(e){this.boardEl=e.boardEl,this.view=e.view,this.edgeManager=e.edgeManager,this.noteManager=e.noteManager,this.labels=e.labels,this.onDelete=e.onDelete,this.popupEl=v(`div`,`wema-edge-popup`),this.popupEl.style.display=`none`,this.popupEl.addEventListener(`click`,e=>e.stopPropagation()),this.boardEl.appendChild(this.popupEl)}show(e,t,n){let r=this.edgeManager.getEdge(e);if(!r)return;this.currentEdgeId=e,this.popupEl.innerHTML=``;let i=r.routing??`curve`,a=r.lineStyle??(r.style===`dashed`?`dashed`:`solid`),o=r.arrowHead??(r.style===`arrow`?`end`:`none`),s=r.arrowSize??12,c=r.strokeWidth??2,l=v(`div`,`wema-popup-details`),u=v(`button`,`wema-popup-details-toggle`);u.innerHTML=Gt,u.append(` ${this.labels.details}`);let d=v(`div`,`wema-popup-details-content`);this.detailsOpen?(u.classList.add(`open`),d.style.display=``):d.style.display=`none`,u.addEventListener(`click`,()=>{this.detailsOpen=!this.detailsOpen,u.classList.toggle(`open`,this.detailsOpen),d.style.display=this.detailsOpen?``:`none`});let f=v(`div`,`wema-popup-section`),p=v(`div`,`wema-popup-label`);p.textContent=this.labels.route,f.appendChild(p);let m=v(`div`,`wema-popup-group`);for(let e of Ut){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===i&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{routing:e.value}),this.show(this.currentEdgeId))}),m.appendChild(t)}f.appendChild(m);let h=v(`div`,`wema-popup-section`),g=v(`div`,`wema-popup-label`);g.textContent=this.labels.from,h.appendChild(g);let _=v(`div`,`wema-popup-group`);for(let e of Wt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===r.fromAnchor&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{fromAnchor:e.value}),this.show(this.currentEdgeId))}),_.appendChild(t)}h.appendChild(_);let b=v(`div`,`wema-popup-section`),x=v(`div`,`wema-popup-label`);x.textContent=this.labels.to,b.appendChild(x);let S=v(`div`,`wema-popup-group`);for(let e of Wt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===r.toAnchor&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{toAnchor:e.value}),this.show(this.currentEdgeId))}),S.appendChild(t)}b.appendChild(S),d.appendChild(f),d.appendChild(h),d.appendChild(b),l.appendChild(u),l.appendChild(d);let C=v(`div`,`wema-popup-section`),w=v(`div`,`wema-popup-label`);w.textContent=this.labels.line,C.appendChild(w);let T=v(`div`,`wema-popup-group`);for(let e of[`solid`,`dashed`,`dotted`]){let t=zt[e],n=v(`button`,`wema-popup-btn`);n.innerHTML=t.svg,y(n,this.labels[t.label]),e===a&&n.classList.add(`active`),n.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{lineStyle:e}),this.show(this.currentEdgeId))}),T.appendChild(n)}C.appendChild(T);let E=v(`div`,`wema-popup-section`),D=v(`div`,`wema-popup-label`);D.textContent=this.labels.arrow,E.appendChild(D);let ee=v(`div`,`wema-popup-group`);for(let e of Bt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===o&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{arrowHead:e.value}),this.show(this.currentEdgeId))}),ee.appendChild(t)}E.appendChild(ee);let O=v(`div`,`wema-popup-section`),te=v(`div`,`wema-popup-label`);te.textContent=this.labels.size,O.appendChild(te);let ne=v(`div`,`wema-popup-group`);for(let e of Vt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===s&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{arrowSize:e.value}),this.show(this.currentEdgeId))}),ne.appendChild(t)}O.appendChild(ne);let re=v(`div`,`wema-popup-section`),ie=v(`div`,`wema-popup-label`);ie.textContent=this.labels.width,re.appendChild(ie);let k=v(`div`,`wema-popup-group`);for(let e of Ht){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===c&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{strokeWidth:e.value}),this.show(this.currentEdgeId))}),k.appendChild(t)}re.appendChild(k);let A=v(`div`,`wema-popup-section wema-popup-delete-section`),j=v(`button`,`wema-popup-btn wema-popup-btn-delete`);j.innerHTML=Kt,y(j,this.labels.delete),j.addEventListener(`click`,()=>{if(!this.currentEdgeId)return;let e=this.currentEdgeId;this.hide(),this.onDelete(e)}),A.appendChild(j),this.popupEl.appendChild(C),this.popupEl.appendChild(E),this.popupEl.appendChild(O),this.popupEl.appendChild(re),this.popupEl.appendChild(l),this.popupEl.appendChild(A),t!=null&&n!=null&&(this.anchor=this.view.clientToBoard(t,n)),this.popupEl.style.display=``,this.updatePosition()}updatePosition(){if(this.currentEdgeId===null)return;let{x:e,y:t}=this.view.boardToScreen(this.anchor.x,this.anchor.y);b(this.popupEl,this.boardEl,{left:e,top:t,right:e,bottom:t},`below`,12)}hide(){this.popupEl.style.display=`none`,this.currentEdgeId=null,this.detailsOpen=!1}destroy(){this.popupEl.remove()}},Jt=[{hex:`#FFF9C4`,label:`colorButter`},{hex:`#FFCDD2`,label:`colorRose`},{hex:`#FFE0B2`,label:`colorPeach`},{hex:`#E1BEE7`,label:`colorLavender`},{hex:`#BBDEFB`,label:`colorSky`},{hex:`#B2DFDB`,label:`colorMint`},{hex:`#C8E6C9`,label:`colorSage`},{hex:`#F5F5F5`,label:`colorGray`}],Yt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,Xt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>`,Zt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="3" cy="6" r="1.5" fill="currentColor" stroke="none"/><circle cx="3" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="3" cy="18" r="1.5" fill="currentColor" stroke="none"/></svg>`,Qt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><text x="2" y="8" font-size="8" fill="currentColor" stroke="none" font-family="sans-serif">1</text><text x="2" y="14" font-size="8" fill="currentColor" stroke="none" font-family="sans-serif">2</text><text x="2" y="20" font-size="8" fill="currentColor" stroke="none" font-family="sans-serif">3</text></svg>`,$t=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><polyline points="9 11 12 14 22 4" stroke-width="2"/></svg>`,en=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="12" x2="21" y2="12"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="3 9 6 12 3 15"/></svg>`,tn=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="12" x2="21" y2="12"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="6 9 3 12 6 15"/></svg>`,nn=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,rn=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>`,an=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>`,on=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="5" x2="20" y2="5"/><line x1="4" y1="10" x2="20" y2="10"/><line x1="4" y1="15" x2="12" y2="15" opacity="0.4"/><polyline points="9 19 12 22 15 19"/></svg>`,sn=class{popupEl;boardEl;noteManager;labels;onColorChange;onMultiColorChange;onDuplicate;onDelete;onMultiDelete;onInsertImage=null;onInsertEmbed=null;onAutoSizeToggle=null;onMultiAutoSizeToggle=null;onFoldableToggle=null;currentNoteId=null;currentNoteIds=null;toScreenBox;placed=null;constructor(e){this.toScreenBox=e.toScreenBox,this.boardEl=e.boardEl,this.noteManager=e.noteManager,this.labels=e.labels,this.onColorChange=e.onColorChange,this.onMultiColorChange=e.onMultiColorChange,this.onDuplicate=e.onDuplicate,this.onDelete=e.onDelete,this.onMultiDelete=e.onMultiDelete,this.onInsertImage=e.onInsertImage??null,this.onInsertEmbed=e.onInsertEmbed??null,this.onAutoSizeToggle=e.onAutoSizeToggle??null,this.onMultiAutoSizeToggle=e.onMultiAutoSizeToggle??null,this.onFoldableToggle=e.onFoldableToggle??null,this.popupEl=v(`div`,`wema-note-popup`),this.popupEl.style.display=`none`,this.popupEl.addEventListener(`click`,e=>e.stopPropagation()),this.boardEl.appendChild(this.popupEl)}show(e){let t=this.noteManager.getNote(e);if(!t)return;this.currentNoteId=e,this.popupEl.innerHTML=``;let n=v(`div`,`wema-note-popup-actions`),r=v(`button`,`wema-popup-btn wema-note-popup-color-btn`);r.style.backgroundColor=t.color,y(r,this.labels.color),r.addEventListener(`click`,()=>{let e=h.style.display!==`none`;h.style.display=e?`none`:``});let i=v(`button`,`wema-popup-btn`);i.innerHTML=Yt,y(i,this.labels.duplicate),i.addEventListener(`click`,()=>{if(!this.currentNoteId)return;let e=this.currentNoteId;this.hide(),this.onDuplicate(e)});let a=v(`button`,`wema-popup-btn wema-popup-btn-delete`);a.innerHTML=Xt,y(a,this.labels.delete),a.addEventListener(`click`,()=>{if(!this.currentNoteId)return;let e=this.currentNoteId;this.hide(),this.onDelete(e)});let o=v(`button`,`wema-popup-btn`);o.innerHTML=an,y(o,this.labels.autoSize),t.autoSize&&o.classList.add(`active`),o.addEventListener(`click`,()=>{this.currentNoteId&&this.onAutoSizeToggle?.(this.currentNoteId)}),n.appendChild(r),n.appendChild(o),this.noteManager.isHostDrawn(e)||n.appendChild(this.foldableButton([t])),n.appendChild(i),n.appendChild(a);let s=v(`div`,`wema-note-popup-actions`),c=v(`button`,`wema-popup-btn`);c.innerHTML=Zt,y(c,this.labels.bulletedList),c.addEventListener(`click`,()=>{this.currentNoteId&&this.toggleList(this.currentNoteId,`ul`)});let l=v(`button`,`wema-popup-btn`);l.innerHTML=Qt,y(l,this.labels.numberedList),l.addEventListener(`click`,()=>{this.currentNoteId&&this.toggleList(this.currentNoteId,`ol`)});let u=v(`button`,`wema-popup-btn`);u.innerHTML=$t,y(u,this.labels.checklist),u.addEventListener(`click`,()=>{this.currentNoteId&&this.toggleList(this.currentNoteId,`checklist`)});let d=v(`button`,`wema-popup-btn`);d.innerHTML=tn,y(d,this.labels.outdent),d.addEventListener(`click`,()=>{this.currentNoteId&&this.noteManager.editContent(this.currentNoteId,(e,t)=>t&&Re(e,t))});let f=v(`button`,`wema-popup-btn`);f.innerHTML=en,y(f,this.labels.indent),f.addEventListener(`click`,()=>{this.currentNoteId&&this.noteManager.editContent(this.currentNoteId,(e,t)=>t&&Le(e,t))});for(let e of[c,l,u,d,f])e.addEventListener(`mousedown`,e=>e.preventDefault());let p=v(`button`,`wema-popup-btn`);p.innerHTML=nn,y(p,this.labels.image),p.addEventListener(`click`,()=>{this.currentNoteId&&this.onInsertImage?.(this.currentNoteId)});let m=v(`button`,`wema-popup-btn`);m.innerHTML=rn,y(m,this.labels.embed),m.addEventListener(`click`,()=>{this.currentNoteId&&this.onInsertEmbed?.(this.currentNoteId)}),s.appendChild(c),s.appendChild(l),s.appendChild(u),s.appendChild(d),s.appendChild(f),s.appendChild(p),s.appendChild(m);let h=v(`div`,`wema-note-popup-colors`);h.style.display=`none`;for(let e of Jt){let n=v(`button`,`wema-color-swatch`);n.style.backgroundColor=e.hex,y(n,this.labels[e.label]),t.color.toUpperCase()===e.hex&&n.classList.add(`active`),n.addEventListener(`click`,()=>{this.currentNoteId&&(this.onColorChange(this.currentNoteId,e.hex),r.style.backgroundColor=e.hex,h.querySelectorAll(`.wema-color-swatch`).forEach(e=>e.classList.remove(`active`)),n.classList.add(`active`))}),h.appendChild(n)}this.popupEl.appendChild(n),this.noteManager.isHostDrawn(e)||this.popupEl.appendChild(s),this.popupEl.appendChild(h),this.popupEl.style.display=``,this.updatePosition()}showMulti(e){let t=e.map(e=>this.noteManager.getNote(e)).filter(e=>e!=null);if(t.length<2)return;this.currentNoteId=null,this.currentNoteIds=e.slice(),this.popupEl.innerHTML=``;let n=v(`div`,`wema-note-popup-actions`),r=v(`button`,`wema-popup-btn wema-note-popup-color-btn`),i=t.every(e=>e.color===t[0].color);r.style.backgroundColor=i?t[0].color:`#ccc`,y(r,this.labels.color),r.addEventListener(`click`,()=>{let e=c.style.display!==`none`;c.style.display=e?`none`:``});let a=t.every(e=>e.autoSize),o=v(`button`,`wema-popup-btn`);o.innerHTML=an,y(o,this.labels.autoSize),a&&o.classList.add(`active`),o.addEventListener(`click`,()=>{this.currentNoteIds&&this.onMultiAutoSizeToggle?.(this.currentNoteIds.slice())});let s=v(`button`,`wema-popup-btn wema-popup-btn-delete`);s.innerHTML=Xt,y(s,this.labels.deleteNotes(t.length)),s.addEventListener(`click`,()=>{if(!this.currentNoteIds)return;let e=this.currentNoteIds.slice();this.hide(),this.onMultiDelete(e)}),n.appendChild(r),n.appendChild(o),n.appendChild(this.foldableButton(t)),n.appendChild(s);let c=v(`div`,`wema-note-popup-colors`);c.style.display=`none`;for(let e of Jt){let n=v(`button`,`wema-color-swatch`);n.style.backgroundColor=e.hex,y(n,this.labels[e.label]),i&&t[0].color.toUpperCase()===e.hex&&n.classList.add(`active`),n.addEventListener(`click`,()=>{this.currentNoteIds&&(this.onMultiColorChange(this.currentNoteIds,e.hex),r.style.backgroundColor=e.hex,c.querySelectorAll(`.wema-color-swatch`).forEach(e=>e.classList.remove(`active`)),n.classList.add(`active`))}),c.appendChild(n)}this.popupEl.appendChild(n),this.popupEl.appendChild(c),this.popupEl.style.display=``,this.updatePosition()}foldableButton(e){let t=v(`button`,`wema-popup-btn`);t.innerHTML=on,y(t,this.labels.foldLongText),t.classList.toggle(`active`,e.every(e=>e.foldable));let n=e.map(e=>e.id);return t.addEventListener(`click`,()=>this.onFoldableToggle?.(n)),t}updatePosition(){let e=(this.currentNoteIds??(this.currentNoteId?[this.currentNoteId]:[])).map(e=>this.noteManager.getShownBox(e)).filter(e=>e!==void 0);if(e.length===0)return;let t=this.toScreenBox(s(e)),n=b(this.popupEl,this.boardEl,t,`below`,8);this.placed={box:{left:t.left,top:Math.min(t.top,n.top),right:t.right,bottom:Math.max(t.bottom,n.bottom)},side:n.top<t.top?`above`:`below`}}boxWith(e){return this.currentNoteId===e?this.placed:null}hide(){this.placed=null,this.popupEl.style.display=`none`,this.currentNoteId=null,this.currentNoteIds=null}destroy(){this.popupEl.remove()}toggleList(e,t){this.noteManager.editContent(e,(e,n)=>n?Ne(e,n,t):Pe(e,t))}insertBlockContent(e,t){let n=this.noteManager.getTextElement(e);if(!n)return;n.focus();let r=document.createElement(`div`);for(r.innerHTML=t;r.firstChild;)n.appendChild(r.firstChild);this.noteManager.updateNote(e,{text:n.innerHTML})}},cn=16;function ln(e,t={}){if(e.length===0)return[];let n=new Map(e.map(e=>[e.id,e])),r=[];for(let e of t.order??[]){let t=n.get(e);t&&n.delete(e)&&r.push(t)}r.push(...[...n.values()].sort((e,t)=>e.y-t.y||e.x-t.x));let i=t.x??Math.min(...e.map(e=>e.x)),a=t.gap??cn,o=t.y??Math.min(...e.map(e=>e.y));return r.map(e=>{let n={id:e.id,x:i,y:o,width:t.width??e.width};return o+=e.height+a,n})}function un(e,t){if(e.length<2)return[];switch(t){case`left`:{let t=Math.min(...e.map(e=>e.x));return e.map(e=>({id:e.id,x:t,y:e.y}))}case`center`:{let t=e.reduce((e,t)=>e+t.x+t.width/2,0)/e.length;return e.map(e=>({id:e.id,x:t-e.width/2,y:e.y}))}case`right`:{let t=Math.max(...e.map(e=>e.x+e.width));return e.map(e=>({id:e.id,x:t-e.width,y:e.y}))}case`top`:{let t=Math.min(...e.map(e=>e.y));return e.map(e=>({id:e.id,x:e.x,y:t}))}case`middle`:{let t=e.reduce((e,t)=>e+t.y+t.height/2,0)/e.length;return e.map(e=>({id:e.id,x:e.x,y:t-e.height/2}))}case`bottom`:{let t=Math.max(...e.map(e=>e.y+e.height));return e.map(e=>({id:e.id,x:e.x,y:t-e.height}))}}}function dn(e,t){if(e.length<3)return[];let n=[];if(t===`horizontal`){let t=[...e].sort((e,t)=>e.x-t.x),r=t[0],i=t[t.length-1],a=(i.x+i.width-r.x-t.reduce((e,t)=>e+t.width,0))/(t.length-1),o=r.x+r.width+a;for(let e=1;e<t.length-1;e++)n.push({id:t[e].id,x:o,y:t[e].y}),o+=t[e].width+a}else{let t=[...e].sort((e,t)=>e.y-t.y),r=t[0],i=t[t.length-1],a=(i.y+i.height-r.y-t.reduce((e,t)=>e+t.height,0))/(t.length-1),o=r.y+r.height+a;for(let e=1;e<t.length-1;e++)n.push({id:t[e].id,x:t[e].x,y:o}),o+=t[e].height+a}return n}var fn=40,pn=60,mn=.44,hn=150,gn=80,_n=16,vn=1.6,yn=64,bn=1.25,xn=4,Sn=1e3,Cn=(e,t)=>e.x-t.x||e.y-t.y,wn=(e,t,n)=>e.map(e=>({id:e.id,x:e.x+t,y:e.y+n}));function Tn(e,t){let n=[],r=[];e.forEach((e,i)=>{let a=i%t,o=Math.floor(i/t);n[a]=Math.max(n[a]??0,e.width),r[o]=Math.max(r[o]??0,e.height)});let i=(e,t)=>{let n=0;return e.map(e=>{let r=n;return n+=e+t,r})},a=i(n,fn),o=i(r,pn),s=n.length-1,c=r.length-1;return{width:a[s]+n[s],height:o[c]+r[c],places:e.map((e,n)=>({id:e.id,x:a[n%t],y:o[Math.floor(n/t)]}))}}function En(e,t,n){let r=[],i=0;for(let t of e)r.push(i+t/2),i+=t+fn;let a=[];for(let i=0;i<e.length;i++){let e={sum:(t[i]-r[i])*n[i],weight:n[i],count:1};for(;a.length>0;){let t=a[a.length-1];if(t.sum/t.weight<=e.sum/e.weight)break;e={sum:t.sum+e.sum,weight:t.weight+e.weight,count:t.count+e.count},a.pop()}a.push(e)}let o=[];for(let e of a)for(let t=0;t<e.count;t++)o.push(e.sum/e.weight+r[o.length]);return o}function Dn(e,t){let n=e.map(e=>{let n=t(e),r=n.filter(e=>e.passing),i=r.length>0?r:n;return{unit:e,at:i.length>0?i.reduce((e,t)=>e+t.center,0)/i.length:e.center}});n.sort((e,t)=>e.at-t.at);let r=En(n.map(e=>e.unit.block.width),n.map(e=>e.at),n.map(e=>e.unit.passing?Sn:1));n.forEach(({unit:t},n)=>{t.center=r[n],e[n]=t})}function On(e){let t=[];for(let n of e)(t[n.level]??=[]).push(n);for(let e of t)Dn(e,()=>[]);for(let e=0;e<xn;e++){for(let e=1;e<t.length;e++)Dn(t[e],e=>e.parents);for(let e=t.length-2;e>=0;e--)Dn(t[e],e=>e.children)}let n=e.filter(e=>!e.passing),r=Math.min(...n.map(e=>e.center-e.block.width/2)),i=Math.max(...n.map(e=>e.center+e.block.width/2)),a=[],o=0,s=0;for(let e of t){for(let t of e)a.push(...wn(t.block.places,t.center-t.block.width/2-r,o));s=o+Math.max(...e.map(e=>e.block.height)),o=s+kn(e)}return{width:i-r,height:s,places:a}}function kn(e){let t=0;for(let n of e)if(!n.passing)for(let e of n.children)e.passing||(t=Math.max(t,Math.abs(e.center-n.center)));return Math.min(Math.max(t*mn,pn),hn)}function An(e,t,n,r){let i=[];return{...jn(e,t,n,r,(e,t,n)=>i.push(...wn(e.places,t,n))),places:i}}function jn(e,t,n,r,i){let a=0,o=0,s=0,c=0;for(let l of e)a>0&&a+l.width>t&&(a=0,o+=s+r,s=0),i?.(l,a,o),c=Math.max(c,a+l.width),s=Math.max(s,l.height),a+=l.width+n;return{width:c,height:o+s}}function Mn(e,t,n){let r=[],i=0,a=1;return e.forEach((o,s)=>{let c=i+o.width;if(i+=o.width+t,s+1<a&&s+1<e.length)return;a=s+1<yn?s+2:Math.ceil((s+1)*bn);let l=jn(e,c,t,n),u=r[r.length-1];u&&u.width===l.width&&u.height===l.height||r.push({...l,maxWidth:c})}),r}function Nn(e,t,n){let r={width:0,height:0,maxWidth:0},i=e.length>0?Mn(e,gn,gn):[r],a=t.length>0?Mn(t,fn,pn):[r],o=e.length>0&&t.length>0?gn:0,s={fit:1/0,area:1/0,g:r,l:r,beside:!1},c=(e,t,r)=>{let i=r?e.width+o+t.width:Math.max(e.width,t.width),a=r?Math.max(e.height,t.height):e.height+o+t.height,c=Math.max(i/n,a),l=i*a;(c<s.fit||c===s.fit&&l<s.area)&&(s={fit:c,area:l,g:e,l:t,beside:r})};for(let e of i)for(let t of a)c(e,t,!1),o>0&&c(e,t,!0);let{g:l,l:u,beside:d}=s;return[...An(e,l.maxWidth,gn,gn).places,...wn(An(t,u.maxWidth,fn,pn).places,d?l.width+o:0,d?0:l.height+o)]}function Pn(e,t){let n=new Set(e.map(e=>e.id)),r=new Map,i=new Set;for(let{from:e,to:a}of t)e!==a&&n.has(e)&&n.has(a)&&(r.has(e)||r.set(e,new Set),r.get(e).add(a),i.add(a));let a=e.filter(e=>r.has(e.id)||i.has(e.id)),o=new Map(a.map(e=>[e.id,[]])),s=new Map(a.map(e=>[e.id,0])),c=new Set,l=new Set,u=[],d=[],f=e=>{c.add(e),l.add(e),d.push({id:e,next:[...r.get(e)??[]],at:0})},p=a.filter(e=>!i.has(e.id));for(let{id:e}of[...p,...a])if(!c.has(e))for(f(e);d.length>0;){let e=d[d.length-1];if(e.at===e.next.length){l.delete(e.id),u.push(e.id),d.pop();continue}let t=e.next[e.at++];l.has(t)||(o.get(e.id).push(t),s.set(t,s.get(t)+1),c.has(t)||f(t))}return{nodes:a,children:o,parentCount:s,order:u.reverse()}}function Fn({nodes:e,children:t,parentCount:n,order:r}){let i=new Map(e.map(e=>[e.id,0]));for(let e of r)for(let n of t.get(e))i.set(n,Math.max(i.get(n),i.get(e)+1));for(let{id:r}of e){let e=t.get(r);n.get(r)===0&&e.length>0&&i.set(r,Math.min(...e.map(e=>i.get(e)))-1)}return i}function In({nodes:e,children:t,parentCount:n},r){let i=new Map(e.map(e=>[e.id,e])),a=new Map,o=(e,t,n=!1)=>({block:e,level:t,passing:n,parents:[],children:[],center:0}),s=(e,t)=>{e.children.includes(t)||(e.children.push(t),t.parents.push(e))};for(let{id:s}of e){let e=t.get(s).filter(e=>t.get(e).length===0&&n.get(e)===1).map(e=>i.get(e));if(e.length<_n)continue;e.sort(Cn);let c=o(Tn(e,Math.ceil(Math.sqrt(e.length))),r.get(s)+1);for(let t of e)a.set(t.id,c)}for(let t of e)a.has(t.id)||a.set(t.id,o(Tn([t],1),r.get(t.id)));for(let{id:n}of e){let e=a.get(n);for(let r of t.get(n)){let t=a.get(r),n=e;for(let r=e.level+1;r<t.level;r++){let e=o({width:0,height:0,places:[]},r,!0);s(n,e),n=e}s(n,t)}}return a}function Ln(e,t){let n=[],r=new Set;for(let{id:i}of e){let e=t.get(i);if(r.has(e))continue;r.add(e);let a=[e];for(let e=0;e<a.length;e++)for(let t of[...a[e].parents,...a[e].children])r.has(t)||(r.add(t),a.push(t));n.push(a)}return n}function Rn(e,t,n){let r=n?.noteIds?new Set(n.noteIds):null,i=e.filter(e=>!r||r.has(e.id)).sort(Cn);if(i.length===0)return[];let a=Pn(i,t),o=In(a,Fn(a)),s=Ln(a.nodes,o).map(On),c=i.filter(e=>!o.has(e.id)).map(e=>Tn([e],1)),l=n?.aspectRatio,u=Nn(s,c,l&&l>0&&Number.isFinite(l)?l:vn),d=Math.min(...i.map(e=>e.x)),f=Math.min(...i.map(e=>e.y));return u.map(e=>({id:e.id,x:Math.round(d+e.x),y:Math.round(f+e.y)}))}function zn(e){switch(e.type){case`note:create`:case`note:delete`:return{type:e.type,note:{...e.note}};case`edge:create`:case`edge:delete`:return{type:e.type,edge:{...e.edge}};case`note:update`:case`edge:update`:return{...e,before:{...e.before},after:{...e.after}}}}function Bn(e){let t=zn(e);switch(t.type){case`note:create`:return{...t,type:`note:delete`};case`note:delete`:return{...t,type:`note:create`};case`edge:create`:return{...t,type:`edge:delete`};case`edge:delete`:return{...t,type:`edge:create`};case`note:update`:case`edge:update`:return{...t,before:t.after,after:t.before}}}function Vn(e,t,n){let r={},i={};for(let a of Object.keys(t))a===`id`||n.has(a)||de(e[a],t[a])||(r[a]=e[a],i[a]=t[a]);return{before:r,after:i}}var Hn=Object.keys({x:!0,y:!0,width:!0,height:!0,text:!0,color:!0,zIndex:!0,autoSize:!0,foldable:!0,meta:!0}),Un=Object.keys({fromAnchor:!0,toAnchor:!0,style:!0,label:!0,lineStyle:!0,strokeWidth:!0,arrowHead:!0,arrowSize:!0,routing:!0,collapsed:!0});function Wn(e,t,n){let r={};for(let i of n)Object.hasOwn(t,i)?r[i]=t[i]:Object.hasOwn(e,i)&&(r[i]=void 0);return r}function Gn(e){let t=[],n=new Map;for(let r of e){if(r.type!==`note:update`&&r.type!==`edge:update`){t.push(r),n.clear();continue}let e=r.type===`note:update`?`note:${r.noteId}`:`edge:${r.edgeId}`,i=n.get(e),a=i===void 0?void 0:t[i];i===void 0||a===void 0||a.type!==r.type?(n.set(e,t.length),t.push(r)):t[i]={...a,before:{...r.before,...a.before},after:{...a.after,...r.after}}}return t.filter(e=>{if(e.type!==`note:update`&&e.type!==`edge:update`)return!0;let t=e.before,n=e.after;for(let e of Object.keys(n))de(t[e],n[e])&&(delete t[e],delete n[e]);return Object.keys(n).length>0})}function Kn(e,t){for(let n of e)switch(n.type){case`note:create`:t.addNoteWithId(n.note);break;case`note:update`:t.updateNote(n.noteId,Wn(n.before,n.after,Hn));break;case`note:delete`:t.deleteNote(n.note.id);break;case`edge:create`:t.addEdgeWithId(n.edge);break;case`edge:update`:t.updateEdge(n.edgeId,Wn(n.before,n.after,Un));break;case`edge:delete`:t.deleteEdge(n.edge.id)}}var qn=class{undoStack=[];redoStack=[];pendingDeltas=[];pendingOrigin=`user`;batchDepth=0;commitScheduled=!1;recording=!0;ignoredNoteKeys=new Set;ignoredEdgeKeys=new Set;maxHistory;emitter;replay;handlers;constructor(e,t,n=100){this.emitter=e,this.replay=t,this.maxHistory=n,this.handlers={noteCreate:e=>this.pushDelta({type:`note:create`,note:{...e.note}}),noteUpdate:e=>{let{before:t,after:n}=Vn(e.prev,e.note,this.ignoredNoteKeys);Object.keys(n).length>0&&this.pushDelta({type:`note:update`,noteId:e.note.id,before:t,after:n})},noteDelete:e=>this.pushDelta({type:`note:delete`,note:{...e.note}}),edgeCreate:e=>this.pushDelta({type:`edge:create`,edge:{...e.edge}}),edgeUpdate:e=>{let{before:t,after:n}=Vn(e.prev,e.edge,this.ignoredEdgeKeys);Object.keys(n).length>0&&this.pushDelta({type:`edge:update`,edgeId:e.edge.id,before:t,after:n})},edgeDelete:e=>this.pushDelta({type:`edge:delete`,edge:{...e.edge}})},this.emitter.on(`note:create`,this.handlers.noteCreate),this.emitter.on(`note:update`,this.handlers.noteUpdate),this.emitter.on(`note:delete`,this.handlers.noteDelete),this.emitter.on(`edge:create`,this.handlers.edgeCreate),this.emitter.on(`edge:update`,this.handlers.edgeUpdate),this.emitter.on(`edge:delete`,this.handlers.edgeDelete)}beginBatch(e){e&&this.batchDepth===0&&(this.commitPending(),this.pendingOrigin=e),this.batchDepth++}endBatch(){this.batchDepth>0&&this.batchDepth--,this.batchDepth===0&&this.commitPending()}setIgnoredKeys(e,t){this.ignoredNoteKeys=new Set(e),this.ignoredEdgeKeys=new Set(t)}undo(){let e=this.undoStack.pop();if(!e)return;let t=e.deltas.map(Bn).reverse();this.withoutRecording(()=>Kn(t,this.replay)),this.redoStack.push(e),this.emitHistoryChange(),this.emitter.emit(`history:commit`,{deltas:t,origin:`undo`})}redo(){let e=this.redoStack.pop();e&&(this.withoutRecording(()=>Kn(e.deltas,this.replay)),this.undoStack.push(e),this.emitHistoryChange(),this.emitter.emit(`history:commit`,{deltas:e.deltas.map(zn),origin:`redo`}))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack.length=0,this.redoStack.length=0,this.pendingDeltas.length=0,this.pendingOrigin=`user`,this.batchDepth=0,this.commitScheduled=!1,this.emitHistoryChange()}destroy(){this.emitter.off(`note:create`,this.handlers.noteCreate),this.emitter.off(`note:update`,this.handlers.noteUpdate),this.emitter.off(`note:delete`,this.handlers.noteDelete),this.emitter.off(`edge:create`,this.handlers.edgeCreate),this.emitter.off(`edge:update`,this.handlers.edgeUpdate),this.emitter.off(`edge:delete`,this.handlers.edgeDelete)}isReplaying(){return!this.recording}withoutRecording(e){this.recording=!1;try{e()}finally{this.recording=!0}}pushDelta(e){this.recording&&(this.pendingDeltas.push(e),this.redoStack.length>0&&(this.redoStack.length=0),this.batchDepth===0&&!this.commitScheduled&&(this.commitScheduled=!0,queueMicrotask(()=>{this.commitScheduled=!1,this.batchDepth===0&&this.commitPending()})))}commitPending(){let e=this.pendingOrigin;this.pendingOrigin=`user`;let t=Gn(this.pendingDeltas.splice(0));if(t.length===0)return;let n={deltas:t};for(this.undoStack.push(n);this.undoStack.length>this.maxHistory;)this.undoStack.shift();this.emitHistoryChange(),this.emitter.emit(`history:commit`,{deltas:n.deltas.map(zn),origin:e})}emitHistoryChange(){this.emitter.emit(`history:change`,{canUndo:this.canUndo(),canRedo:this.canRedo()})}},Jn=[`#333333`,`#D32F2F`,`#1976D2`,`#388E3C`,`#F57C00`,`#7B1FA2`,`#00796B`,`#455A64`],Yn=[`b`,`strong`],Xn=[`s`],Zn=class{boardEl;toolbarEl;labels;onQuote;readOnly;viewOnly;rafId=0;handleSelectionChange;handleMouseDown;activeContentEl=null;savedRange=null;subPanelOpen=!1;constructor(e){this.boardEl=e.boardEl,this.labels=e.labels,this.onQuote=e.onQuote,this.readOnly=e.readOnly,this.viewOnly=e.viewOnly,this.toolbarEl=v(`div`,`wema-richtext-toolbar`),this.toolbarEl.style.display=`none`,this.toolbarEl.addEventListener(`mousedown`,e=>{e.preventDefault()}),this.toolbarEl.addEventListener(`pointerdown`,e=>{e.stopPropagation()}),this.boardEl.appendChild(this.toolbarEl),this.handleSelectionChange=()=>{this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.onSelectionChange())},this.handleMouseDown=e=>{this.toolbarEl.contains(e.target)&&e.preventDefault()},document.addEventListener(`selectionchange`,this.handleSelectionChange),this.boardEl.addEventListener(`mousedown`,this.handleMouseDown)}setReadOnly(e){this.readOnly=e,e&&this.hide()}setViewOnly(e){this.viewOnly=e,e&&this.hide()}destroy(){document.removeEventListener(`selectionchange`,this.handleSelectionChange),this.boardEl.removeEventListener(`mousedown`,this.handleMouseDown),this.rafId&&cancelAnimationFrame(this.rafId),this.toolbarEl.remove()}hide(){this.toolbarEl.style.display=`none`,this.activeContentEl=null,this.savedRange=null,this.subPanelOpen=!1}updatePosition(){if(!this.activeContentEl)return;let e=document.getSelection(),t=this.savedRange??(e&&e.rangeCount>0?e.getRangeAt(0):null);t&&this.positionToolbar(t)}onSelectionChange(){if(this.readOnly||this.viewOnly){this.hide();return}if(this.subPanelOpen)return;let e=document.getSelection();if(!e||e.rangeCount===0||e.isCollapsed){this.hide();return}let t=e.getRangeAt(0),n=t.commonAncestorContainer,r=(n.nodeType===Node.TEXT_NODE?n.parentElement:n)?.closest(`.wema-note-content`);!r||!this.boardEl.contains(r)?this.hide():(this.activeContentEl=r,this.buildToolbar(),this.toolbarEl.style.display=``,this.positionToolbar(t))}buildToolbar(){this.toolbarEl.innerHTML=``;let e=(e,t,n,r)=>{let i=v(`button`,`wema-richtext-btn`);return i.innerHTML=e,y(i,t),i.classList.toggle(`active`,r),i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleInline(n)}),i},t=e(`<b>B</b>`,this.labels.bold,Yn,this.isFormatActive(`bold`)),n=e(`<s>S</s>`,this.labels.strikethrough,Xn,this.findSelectionAncestor(Xn)!==null),r=v(`button`,`wema-richtext-btn`);r.innerHTML=`<span style="border-bottom: 2px solid currentColor;">A</span>`,y(r,this.labels.textColor);let i=this.buildColorPalette();i.style.display=`none`,r.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation();let t=i.style.display!==`none`;i.style.display=t?`none`:``,o.style.display=`none`,this.subPanelOpen=!t});let a=v(`button`,`wema-richtext-btn`);a.innerHTML=`🔗`,y(a,this.labels.link);let o=this.buildLinkInput();o.style.display=`none`,a.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation();let t=o.style.display!==`none`;if(o.style.display=t?`none`:``,i.style.display=`none`,this.subPanelOpen=!t,t)this.savedRange=null;else{let e=document.getSelection();e&&e.rangeCount>0&&(this.savedRange=e.getRangeAt(0).cloneRange());let t=this.getParentTag(`a`),n=o.querySelector(`input`);n.value=t?t.href:``,setTimeout(()=>n.focus(),0)}});let s=v(`button`,`wema-richtext-btn`);s.textContent=`❞`,y(s,this.labels.quote),s.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.quoteSelection()}),this.toolbarEl.appendChild(t),this.toolbarEl.appendChild(n),this.toolbarEl.appendChild(r),this.toolbarEl.appendChild(a),this.toolbarEl.appendChild(s),this.toolbarEl.appendChild(i),this.toolbarEl.appendChild(o)}buildColorPalette(){let e=v(`div`,`wema-richtext-colors`);for(let t of Jn){let n=v(`button`,`wema-color-swatch`);n.style.backgroundColor=t,n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.applyColor(t)}),e.appendChild(n)}return e}buildLinkInput(){let e=v(`div`,`wema-richtext-link-input`),t=document.createElement(`input`);t.type=`url`,t.placeholder=`https://...`,t.addEventListener(`mousedown`,e=>e.stopPropagation()),t.addEventListener(`click`,e=>e.stopPropagation());let n=v(`button`,`wema-richtext-btn`);n.textContent=this.labels.ok,n.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation();let r=t.value.trim();r&&this.applyLink(r),e.style.display=`none`,this.subPanelOpen=!1});let r=v(`button`,`wema-richtext-btn`);return r.textContent=`✕`,y(r,this.labels.removeLink),r.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeLink(),e.style.display=`none`,this.subPanelOpen=!1}),e.appendChild(t),e.appendChild(n),e.appendChild(r),e}positionToolbar(e){b(this.toolbarEl,this.boardEl,x(e,this.boardEl),`above`,8)}isFormatActive(e){try{return document.queryCommandState(e)}catch{return!1}}getParentTag(e){let t=document.getSelection();if(!t||t.rangeCount===0)return null;let n=t.anchorNode;for(;n&&n!==this.activeContentEl;){if(n.nodeType===Node.ELEMENT_NODE&&n.tagName.toLowerCase()===e)return n;n=n.parentNode}return null}findSelectionAncestor(e){let t=document.getSelection();if(!t||t.rangeCount===0)return null;let n=this.findAncestor(t.getRangeAt(0).commonAncestorContainer,e);return n&&this.activeContentEl?.contains(n)?n:null}toggleInline(e){let t=document.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let n=this.findSelectionAncestor(e);n?this.unwrapElement(n):this.wrapSelection(e[0]),this.triggerInput()}quoteSelection(){let e=this.activeContentEl?w(this.activeContentEl):null,t=this.activeContentEl?.closest(`.wema-note`)?.dataset.noteId;if(!e||e.collapsed||!t)return;let n=document.createElement(`div`);if(n.appendChild(e.cloneContents()),n.textContent?.trim()===``&&!n.querySelector(`img, iframe, video, audio`))return;if(n.querySelector(`:scope > li`)){let t=e.commonAncestorContainer,r=(t instanceof Element?t:t.parentElement)?.closest(`ul, ol`),i=r?r.cloneNode(!1):document.createElement(`ul`);i.append(...n.childNodes),n.appendChild(i)}let r=n.innerHTML;document.getSelection()?.removeAllRanges(),this.hide(),this.onQuote(t,r)}applyColor(e){let t=document.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let n=t.getRangeAt(0),r=this.findColorSpan(n.commonAncestorContainer);if(r&&this.activeContentEl?.contains(r))r.style.color=e;else{let t=document.createElement(`span`);t.style.color=e,this.wrapSelectionWithElement(t)}this.triggerInput()}applyLink(e){if(!this.activeContentEl)return;if(!A(e)){this.savedRange=null;return}this.restoreSavedRange();let t=document.getSelection();if(!t||t.rangeCount===0)return;let n=this.getParentTag(`a`);if(n)n.href=e;else{if(t.isCollapsed)return;let n=document.createElement(`a`);n.href=e,n.target=`_blank`,n.rel=`noopener`,this.wrapSelectionWithElement(n)}this.savedRange=null,this.triggerInput()}removeLink(){this.restoreSavedRange();let e=this.getParentTag(`a`);e&&this.activeContentEl?.contains(e)&&(this.unwrapElement(e),this.triggerInput()),this.savedRange=null}restoreSavedRange(){if(!this.savedRange||!this.activeContentEl)return;this.activeContentEl.focus();let e=document.getSelection();e&&(e.removeAllRanges(),e.addRange(this.savedRange))}wrapSelection(e){let t=document.createElement(e);this.wrapSelectionWithElement(t)}wrapSelectionWithElement(e){let t=document.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let n=t.getRangeAt(0),r=n.extractContents();e.appendChild(r),n.insertNode(e);let i=document.createRange();i.selectNodeContents(e),t.removeAllRanges(),t.addRange(i)}unwrapElement(e){let t=e.parentNode;if(t){for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}}findAncestor(e,t){let n=e;for(;n&&n!==this.activeContentEl;){if(n.nodeType===Node.ELEMENT_NODE){let e=n.tagName.toLowerCase();if(t.includes(e))return n}n=n.parentNode}return null}findColorSpan(e){let t=e;for(;t&&t!==this.activeContentEl;){if(t.nodeType===Node.ELEMENT_NODE){let e=t;if(e.tagName.toLowerCase()===`span`&&e.style.color)return t}t=t.parentNode}return null}triggerInput(){this.activeContentEl&&this.activeContentEl.dispatchEvent(new Event(`input`,{bubbles:!0}))}},Qn=class{x=0;y=0;zoom;minZoom;maxZoom;boardEl;layerEl;constructor(e){this.boardEl=e.boardEl,this.layerEl=e.layerEl;let t=(e,t)=>e!==void 0&&Number.isFinite(e)&&e>0?e:t;this.minZoom=t(e.minZoom,.25),this.maxZoom=Math.max(t(e.maxZoom,2),this.minZoom),this.zoom=this.clampZoom(1),this.layerEl.style.transformOrigin=`0 0`,this.applyTransform()}get(){return{x:this.x,y:this.y,zoom:this.zoom}}clampZoom(e){return Math.min(this.maxZoom,Math.max(this.minZoom,e))}set(e){let t=e.x??this.x,n=e.y??this.y,r=this.clampZoom(e.zoom??this.zoom);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||t===this.x&&n===this.y&&r===this.zoom?!1:(this.x=t,this.y=n,this.zoom=r,this.applyTransform(),!0)}applyTransform(){let e=this.zoom===1?``:` scale(${this.zoom})`;this.layerEl.style.transform=`translate(${this.x}px, ${this.y}px)${e}`}screenCenter(){return{x:this.boardEl.clientWidth/2,y:this.boardEl.clientHeight/2}}clientToScreen(e,t){let n=this.boardEl.getBoundingClientRect();return{x:e-n.left,y:t-n.top}}screenToBoard(e,t){return{x:(e-this.x)/this.zoom,y:(t-this.y)/this.zoom}}boardToScreen(e,t){return{x:e*this.zoom+this.x,y:t*this.zoom+this.y}}boardBoxToScreen(e){let t=this.boardToScreen(e.left,e.top),n=this.boardToScreen(e.right,e.bottom);return{left:t.x,top:t.y,right:n.x,bottom:n.y}}clientToBoard(e,t){let n=this.clientToScreen(e,t);return this.screenToBoard(n.x,n.y)}};function $n(e){for(let t of nr){let n=e.match(t.pattern);if(n)return t.toEmbed(n)}return e}var er=/^https?:\/\/bsky\.app\/profile\/([^/]+)\/post\/([a-zA-Z0-9]+)/;async function tr(e){let t=$n(e);if(t!==e)return t;let n=e.match(er);if(n&&!n[1].startsWith(`did:`))try{let e=await fetch(`https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(n[1])}`);if(e.ok)return`https://embed.bsky.app/embed/${(await e.json()).did}/app.bsky.feed.post/${n[2]}`}catch{}return e}var nr=[{pattern:/^https?:\/\/(?:www\.)?youtube\.com\/watch\?.*v=([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://www.youtube.com/embed/${e[1]}`},{pattern:/^https?:\/\/(?:www\.)?youtube\.com\/shorts\/([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://www.youtube.com/embed/${e[1]}`},{pattern:/^https?:\/\/youtu\.be\/([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://www.youtube.com/embed/${e[1]}`},{pattern:/^https?:\/\/(?:www\.)?youtube\.com\/embed\/[a-zA-Z0-9_-]+/,toEmbed:e=>e[0]},{pattern:/^https?:\/\/(?:www\.)?vimeo\.com\/(\d+)/,toEmbed:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https?:\/\/player\.vimeo\.com\/video\/\d+/,toEmbed:e=>e[0]},{pattern:/^https?:\/\/open\.spotify\.com\/(track|album|playlist|episode|show)\/([a-zA-Z0-9]+)/,toEmbed:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`},{pattern:/^https?:\/\/docs\.google\.com\/presentation\/d\/([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://docs.google.com/presentation/d/${e[1]}/embed`},{pattern:/^https?:\/\/(?:www\.)?google\.[a-z.]+\/maps\/.+/,toEmbed:e=>`https://maps.google.com/maps?output=embed&q=${encodeURIComponent(e[0])}`},{pattern:/^https?:\/\/(?:twitter\.com|x\.com)\/([a-zA-Z0-9_]+)\/status\/(\d+)/,toEmbed:e=>`https://platform.twitter.com/embed/Tweet.html?id=${e[2]}`},{pattern:/^https?:\/\/bsky\.app\/profile\/(did:[^/]+)\/post\/([a-zA-Z0-9]+)/,toEmbed:e=>`https://embed.bsky.app/embed/${e[1]}/app.bsky.feed.post/${e[2]}`}],rr=`.wema-edge-popup, .wema-note-popup, .wema-richtext-toolbar, .wema-image-overlay, .wema-embed-input`,ir=6,ar=.01,or=30,sr=80,cr=20,lr=24,ur=20,dr=e=>e.order?{...e,order:[...e.order]}:{...e},fr=(e,t,n)=>(n-(t-e))/2,pr=class e{emitter=new a;boardEl;viewportEl;svgEl;view;wheelPan;wheelZoom;emptyDrag;panMargin;spaceHeld=!1;pointerInside=!1;pageScroll=!1;holdsPageHeight=!1;stack=null;restackPending=!1;flushQueued=!1;embedInput=null;overlayObserver=null;pan=null;panMoved=!1;noteManager;dragManager;selectionManager;edgeManager;anchorDragManager;resizeManager;edgePopup;notePopup;richTextToolbar;historyManager;noteAnimator;visibilitySuspended=!1;noteFilter=null;hiddenNoteIds=new Set;redrawNoteLinkPeers=null;noteLinkLines=new Map;reportedHidden=new Set;visibilityPending=!1;buttonEdges=[];stackedSides=new Map;onImageUpload;changePending=!1;measuredSizes=new Map;container;labels;readOnly;viewOnly;defaultNoteWidth;defaultNoteHeight;positionSnapshot=null;collapsedEdgeSnapshot=null;theme;rubberBandMoved=!1;noteDragged=!1;handleDblClick;handleKeyDown;handleBoardClick;handleRubberBandDown;handleRubberBandMove;handleRubberBandUp;handlePanDown;handlePanMove;handlePanUp;handlePointerEnter;handlePointerLeave;handleSpaceDown;handleKeyUp;handleBlur;handlePageChange;handleWheel;constructor(e){this.container=e.container,this.labels=i(e.labels,e.foldLabels),this.readOnly=e.readOnly??!1,this.viewOnly=e.viewOnly??!1,this.defaultNoteWidth=e.defaultNoteWidth??200,this.defaultNoteHeight=e.defaultNoteHeight??150,this.theme=e.theme??`default`,this.onImageUpload=e.onImageUpload,this.wheelPan=e.wheelPan??!0,this.wheelZoom=e.wheelZoom??!0,this.emptyDrag=e.emptyDrag===`pan`?`pan`:`select`,this.panMargin=e.panMargin!==void 0&&e.panMargin>=0?e.panMargin:200,this.boardEl=v(`div`,`wema-board`),this.theme!=="default"&&this.boardEl.classList.add(`wema-theme-${this.theme}`),E(this.boardEl,{position:`relative`,width:`100%`,height:`100%`,overflow:`hidden`}),this.boardEl.tabIndex=0,this.viewportEl=v(`div`,`wema-viewport`),E(this.viewportEl,{position:`absolute`,top:`0`,left:`0`,width:`0`,height:`0`}),this.boardEl.appendChild(this.viewportEl),this.view=new Qn({boardEl:this.boardEl,layerEl:this.viewportEl,minZoom:e.minZoom,maxZoom:e.maxZoom}),this.svgEl=S(`svg`,`wema-edges`),this.svgEl.setAttribute(`width`,`1`),this.svgEl.setAttribute(`height`,`1`),E(this.svgEl,{position:`absolute`,top:`0`,left:`0`,overflow:`visible`,pointerEvents:`none`}),this.viewportEl.appendChild(this.svgEl),this.container.appendChild(this.boardEl);let t=null;e.noteLinks&&!e.renderNoteFooter&&(t=e.noteLinks===!0?{}:e.noteLinks);let n;if(t){let e=t.text,{padding:r}=t,i=typeof r==`number`&&Number.isFinite(r)&&r>=0?r:void 0,a={labels:this.labels,isHidden:e=>this.hiddenNoteIds.has(e),reveal:e=>this.revealNotes([e],{padding:i}),getElement:e=>this.noteManager.getElement(e)};n=(t,n)=>Nt(n,kt(t.id,this.edgeManager.getEdgesOf(t.id),e=>this.noteManager.getNote(e),e,this.noteLinkLines),a)}this.noteManager=new tt({boardEl:this.boardEl,layerEl:this.viewportEl,emitter:this.emitter,defaultWidth:e.defaultNoteWidth??200,defaultHeight:e.defaultNoteHeight??150,defaultColor:e.defaultNoteColor??`#FFF9C4`,readOnly:this.readOnly,onMeasure:(e,t)=>{this.edgeManager.updateEdgesOf(e),this.updatePageHeight(),this.placeOverlays(),this.scheduleMeasure(e,t),this.scheduleChange()},onPlacedMeasure:()=>this.scheduleRestack(),onLinkClick:e.onLinkClick,hostRender:e.renderNote,hostFooter:n??e.renderNoteFooter,hostAccessory:e.renderNoteAccessory,onUnderChange:()=>this.queueFlush(),onUnderResize:()=>this.followUnder(),labels:this.labels}),this.selectionManager=new lt({layerEl:this.viewportEl,noteManager:this.noteManager,emitter:this.emitter,isSelectable:e=>!this.hiddenNoteIds.has(e)}),this.edgeManager=new mt({boardEl:this.boardEl,svgEl:this.svgEl,noteManager:this.noteManager,emitter:this.emitter});let r=()=>this.readOnly||this.viewOnly,a=()=>this.stack!==null;if(this.dragManager=new ct({boardEl:this.boardEl,noteManager:this.noteManager,getReadOnly:()=>this.readOnly||a(),getSelection:()=>this.selectionManager.getSelection(),toBoardPoint:(e,t)=>this.view.clientToBoard(e,t),onDragStart:()=>{this.notePopup.hide(),this.noteDragged=!0,this.historyManager.beginBatch()},onDragEnd:e=>{this.historyManager.endBatch(),this.selectionManager.getSelection().includes(e)||this.selectionManager.select([e]),this.updateNotePopup()}}),this.anchorDragManager=new Pt({boardEl:this.boardEl,svgEl:this.svgEl,noteManager:this.noteManager,edgeManager:this.edgeManager,emitter:this.emitter,getReadOnly:r,toBoardPoint:(e,t)=>this.view.clientToBoard(e,t),onDropOnEmpty:(e,t,n)=>{let r=this.noteManager.addNote(this.newNotePlace({x:e-this.defaultNoteWidth/2,y:t-this.defaultNoteHeight/2}));this.edgeManager.addEdge(n,r.id,{fromAnchor:`auto`,toAnchor:`auto`}),this.stack&&this.revealNotes([r.id])}}),this.resizeManager=new Rt({boardEl:this.boardEl,noteManager:this.noteManager,getReadOnly:()=>r()||a(),toBoardPoint:(e,t)=>this.view.clientToBoard(e,t),onResizeStart:()=>{this.historyManager.beginBatch()},onResizeEnd:()=>{this.historyManager.endBatch()},onDoublePress:e=>{let t=this.selectionManager.getSelection();this.resizeNotesToContent(t.includes(e)?t:[e])}}),this.edgePopup=new qt({boardEl:this.boardEl,view:this.view,edgeManager:this.edgeManager,noteManager:this.noteManager,labels:this.labels,onDelete:e=>{this.edgeManager.deselectEdge(),this.edgeManager.deleteEdge(e)}}),this.notePopup=new sn({boardEl:this.boardEl,noteManager:this.noteManager,labels:this.labels,toScreenBox:e=>this.view.boardBoxToScreen(e),onColorChange:(e,t)=>{this.noteManager.updateNote(e,{color:t})},onMultiColorChange:(e,t)=>{for(let n of e)this.noteManager.updateNote(n,{color:t})},onDuplicate:e=>{let t=this.noteManager.getNote(e);if(!t)return;let n=this.noteManager.addNote({...this.newNotePlace({x:t.x+20,y:t.y+20}),width:t.width,height:t.height,text:t.text,color:t.color,...t.autoSize?{autoSize:!0}:{},...t.foldable?{foldable:!0}:{}});this.selectionManager.select([n.id]),this.notePopup.show(n.id),this.stack&&this.revealNotes([n.id])},onDelete:e=>{this.deleteNote(e)},onMultiDelete:e=>{for(let t of e)this.deleteNote(t)},onInsertImage:e=>{this.insertImageIntoNote(e)},onInsertEmbed:e=>{this.showEmbedInput(e)},onAutoSizeToggle:e=>{let t=this.noteManager.getNote(e);t&&(this.noteManager.updateNote(e,{autoSize:!t.autoSize}),this.notePopup.show(e))},onMultiAutoSizeToggle:e=>{let t=this.getNotesByIds(e).every(e=>e.autoSize);for(let n of e)this.noteManager.updateNote(n,{autoSize:!t});this.notePopup.showMulti(e)},onFoldableToggle:e=>{let t=!this.getNotesByIds(e).every(e=>e.foldable);this.batch(()=>{for(let n of e)this.noteManager.updateNote(n,{foldable:t})}),this.updateNotePopup()}}),this.richTextToolbar=new Zn({boardEl:this.boardEl,labels:this.labels,readOnly:this.readOnly,viewOnly:this.viewOnly,onQuote:(e,t)=>this.quoteInNewNote(e,t)}),typeof ResizeObserver<`u`){this.overlayObserver=new ResizeObserver(()=>this.placeOverlays()),this.overlayObserver.observe(this.boardEl);for(let e of this.boardEl.children)e.matches(rr)&&this.overlayObserver.observe(e)}if(this.historyManager=new qn(this.emitter,this.createReplay(`local`)),this.noteAnimator=new at({noteManager:this.noteManager,onFrame:e=>this.followShownNotes(e)}),this.emitter.on(`note:update`,({note:e,prev:t})=>{Ke(e,t)&&(this.stack||this.noteAnimator.cancel(e.id),this.updatePageHeight()),this.edgeManager.updateEdgesOf(e.id),this.scheduleRestack()}),this.emitter.on(`note:create`,({note:e,origin:t})=>{t===`remote`&&this.positionSnapshot?.set(e.id,{x:e.x,y:e.y})}),this.emitter.on(`note:update`,({note:e,prev:t,origin:n})=>{let r=n===`remote`?this.positionSnapshot?.get(e.id):void 0;r&&(e.x!==t.x&&(r.x=e.x),e.y!==t.y&&(r.y=e.y))}),this.emitter.on(`edge:create`,({edge:e,origin:t})=>{t===`remote`&&this.collapsedEdgeSnapshot?.set(e.id,!!e.collapsed)}),this.emitter.on(`edge:update`,({edge:e,prev:t,origin:n})=>{n===`remote`&&e.collapsed!==t.collapsed&&this.collapsedEdgeSnapshot?.set(e.id,!!e.collapsed)}),t){let e=e=>e.forEach(e=>this.noteManager.requestFooter(e)),t=t=>{if(this.stack)for(let n of t)e(this.edgeManager.getEdgesOf(n).map(e=>Dt(e,n)))};this.redrawNoteLinkPeers=t;let n=({edge:t})=>e([t.from,t.to]);this.emitter.on(`edge:create`,n),this.emitter.on(`edge:update`,n),this.emitter.on(`edge:delete`,n),this.emitter.on(`note:update`,({note:e,prev:n})=>{e.text===n.text&&de(e.meta,n.meta)||t([e.id])}),this.emitter.on(`note:delete`,({note:e})=>this.noteLinkLines.delete(e.id)),this.emitter.on(`note:visibility`,({hidden:e,shown:n})=>t([...e,...n]))}this.emitter.on(`edge:create`,()=>this.recomputeVisibility()),this.emitter.on(`edge:update`,()=>this.recomputeVisibility()),this.emitter.on(`edge:delete`,()=>this.recomputeVisibility()),this.emitter.on(`note:create`,({note:e})=>{this.historyManager.isReplaying()||this.noteFilter?.add(e.id),this.recomputeVisibility()}),this.emitter.on(`note:delete`,()=>this.recomputeVisibility()),this.emitter.on(`note:create`,()=>this.scheduleChange()),this.emitter.on(`note:update`,()=>this.scheduleChange()),this.emitter.on(`note:delete`,()=>this.scheduleChange()),this.emitter.on(`edge:create`,()=>this.scheduleChange()),this.emitter.on(`edge:update`,()=>this.scheduleChange()),this.emitter.on(`edge:delete`,()=>this.scheduleChange()),this.handleDblClick=t=>{if(t.target.closest(`.wema-note, ${rr}`))return;if(!this.readOnly&&!this.viewOnly&&(e.createOnDblClick??!0)){let e=this.addNote(this.newNotePlace(this.view.clientToBoard(t.clientX,t.clientY)));this.stack&&this.revealNotes([e.id]);return}let n=this.view.get(),r=this.view.clientToScreen(t.clientX,t.clientY),i=this.view.screenCenter();this.panWithinLimit({x:n.x+i.x-r.x,y:n.y+i.y-r.y})},this.boardEl.addEventListener(`dblclick`,this.handleDblClick),this.handleKeyDown=e=>{if((e.ctrlKey||e.metaKey)&&!this.readOnly&&!this.viewOnly&&!e.target.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select`)){if(e.key===`z`&&!e.shiftKey){e.preventDefault(),this.undo();return}if(e.key===`z`&&e.shiftKey||e.key===`y`){e.preventDefault(),this.redo();return}}if(!(this.readOnly||this.viewOnly)&&(e.key===`Delete`||e.key===`Backspace`)){if(e.target.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select`))return;let t=this.edgeManager.getSelectedEdge();if(t){this.edgeManager.deleteEdge(t);return}let n=this.selectionManager.getSelection();this.notePopup.hide();for(let e of n)this.deleteNote(e)}},this.boardEl.addEventListener(`keydown`,this.handleKeyDown),this.handleBoardClick=e=>{if(this.panMoved){this.panMoved=!1;return}if(this.rubberBandMoved){this.rubberBandMoved=!1;return}if(this.noteDragged){this.noteDragged=!1;return}if(e.target.closest(rr)||this.readOnly)return;let t=this.viewOnly?null:this.edgeManager.hitTest(e.clientX,e.clientY);if(t){this.selectionManager.clear(),this.notePopup.hide(),this.edgeManager.selectEdge(t),this.edgePopup.show(t,e.clientX,e.clientY),this.boardEl.focus();return}this.edgeManager.deselectEdge(),this.edgePopup.hide();let n=e.target.closest(`.wema-note`);if(n){let t=n.dataset.noteId;t&&(e.shiftKey?this.selectionManager.addToSelection([t]):e.ctrlKey||e.metaKey?this.selectionManager.toggleSelection(t):this.selectionManager.select([t]),this.noteManager.bringToFront(t),this.updateNotePopup())}else this.selectionManager.clear(),this.notePopup.hide();let r=document.activeElement;r&&r.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select`)||this.boardEl.focus()},this.boardEl.addEventListener(`click`,this.handleBoardClick),this.handleRubberBandDown=e=>{if(e.button!==0||this.readOnly||this.pan||this.leavesToPage(e)||e.target.closest(`.wema-note, ${rr}`))return;let{x:t,y:n}=this.view.clientToBoard(e.clientX,e.clientY);this.selectionManager.startRubberBand(t,n),this.boardEl.setPointerCapture(e.pointerId),this.boardEl.addEventListener(`pointermove`,this.handleRubberBandMove),this.boardEl.addEventListener(`pointerup`,this.handleRubberBandUp),this.boardEl.addEventListener(`pointercancel`,this.handleRubberBandUp)},this.handleRubberBandMove=e=>{if(!this.selectionManager.isRubberBandActive())return;this.rubberBandMoved=!0;let{x:t,y:n}=this.view.clientToBoard(e.clientX,e.clientY);this.selectionManager.updateRubberBand(t,n)},this.handleRubberBandUp=e=>{this.boardEl.removeEventListener(`pointermove`,this.handleRubberBandMove),this.boardEl.removeEventListener(`pointerup`,this.handleRubberBandUp),this.boardEl.removeEventListener(`pointercancel`,this.handleRubberBandUp);try{this.boardEl.releasePointerCapture(e.pointerId)}catch{}this.selectionManager.endRubberBand(),this.updateNotePopup()},this.boardEl.addEventListener(`pointerdown`,this.handleRubberBandDown),this.handlePanDown=e=>{if(this.leavesToPage(e)){e.stopPropagation();return}if(!this.wantsPan(e))return;e.preventDefault(),e.stopPropagation();let t=!e.target.closest(`.wema-note`);e.button===0&&t&&this.boardEl.focus({preventScroll:!0}),this.pan={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1},this.boardEl.classList.add(`wema-panning`),this.boardEl.setPointerCapture(e.pointerId),this.boardEl.addEventListener(`pointermove`,this.handlePanMove),this.boardEl.addEventListener(`pointerup`,this.handlePanUp),this.boardEl.addEventListener(`pointercancel`,this.handlePanUp)},this.handlePanMove=e=>{if(!this.pan||e.pointerId!==this.pan.pointerId)return;let t=e.clientX-this.pan.startX,n=e.clientY-this.pan.startY;(Math.abs(t)>=4||Math.abs(n)>=4)&&(this.pan.moved=!0);let r=this.view.get();this.panWithinLimit({x:r.x+e.clientX-this.pan.lastX,y:r.y+e.clientY-this.pan.lastY}),this.pan.lastX=e.clientX,this.pan.lastY=e.clientY},this.handlePanUp=e=>{if(this.pan&&e.pointerId===this.pan.pointerId){this.boardEl.removeEventListener(`pointermove`,this.handlePanMove),this.boardEl.removeEventListener(`pointerup`,this.handlePanUp),this.boardEl.removeEventListener(`pointercancel`,this.handlePanUp);try{this.boardEl.releasePointerCapture(e.pointerId)}catch{}this.panMoved=this.pan.moved&&e.type===`pointerup`&&e.button===0,this.pan=null,this.boardEl.classList.remove(`wema-panning`)}},this.handlePointerEnter=()=>{this.pointerInside=!0},this.handlePointerLeave=()=>{this.pointerInside=!1},this.handleSpaceDown=e=>{e.code!==`Space`||e.ctrlKey||e.metaKey||e.altKey||this.pointerInside&&!this.pageScroll&&(document.activeElement?.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select, button`)||(e.preventDefault(),this.setSpaceHeld(!0)))},this.handleKeyUp=e=>{e.code===`Space`&&this.setSpaceHeld(!1)},this.handleBlur=()=>this.setSpaceHeld(!1),this.handlePageChange=()=>this.placeOverlays(),this.handleWheel=e=>{if(this.pageScroll)return;let t=e.target,n=e.deltaMode===1?16:e.deltaMode===2?this.boardEl.clientHeight:1,r=this.view.get();if(e.ctrlKey||e.metaKey){if(!this.wheelZoom)return;e.preventDefault();let t=Math.max(-30,Math.min(or,e.deltaY*n));this.panWithinLimit(this.zoomedAround(r.zoom*2**(-t*ar),e));return}if(!this.wheelPan||t.closest(rr))return;let i=t.closest(`.wema-note-content, .wema-note-custom`);if(i&&i.scrollHeight>i.clientHeight)return;e.preventDefault();let a=e.deltaX*n,o=e.deltaY*n;e.shiftKey&&a===0&&(a=o,o=0),this.panWithinLimit({x:r.x-a,y:r.y-o})},this.boardEl.addEventListener(`pointerdown`,this.handlePanDown,!0),this.boardEl.addEventListener(`pointerenter`,this.handlePointerEnter),this.boardEl.addEventListener(`pointerleave`,this.handlePointerLeave),document.addEventListener(`keydown`,this.handleSpaceDown),document.addEventListener(`keyup`,this.handleKeyUp),window.addEventListener(`blur`,this.handleBlur),window.addEventListener(`scroll`,this.handlePageChange,{capture:!0,passive:!0}),window.addEventListener(`resize`,this.handlePageChange),this.boardEl.addEventListener(`wheel`,this.handleWheel,{passive:!1}),e.data&&this.importData(e.data),this.viewOnly&&this.enterViewOnly(),e.pageScroll&&this.setPageScroll(!0),e.stacked&&this.setStacked(e.stacked)}destroy(){this.boardEl.removeEventListener(`dblclick`,this.handleDblClick),this.boardEl.removeEventListener(`keydown`,this.handleKeyDown),this.boardEl.removeEventListener(`click`,this.handleBoardClick),this.boardEl.removeEventListener(`pointerdown`,this.handleRubberBandDown),this.boardEl.removeEventListener(`pointermove`,this.handleRubberBandMove),this.boardEl.removeEventListener(`pointerup`,this.handleRubberBandUp),this.boardEl.removeEventListener(`pointerdown`,this.handlePanDown,!0),this.boardEl.removeEventListener(`pointermove`,this.handlePanMove),this.boardEl.removeEventListener(`pointerup`,this.handlePanUp),this.boardEl.removeEventListener(`pointercancel`,this.handlePanUp),this.boardEl.removeEventListener(`pointerenter`,this.handlePointerEnter),this.boardEl.removeEventListener(`pointerleave`,this.handlePointerLeave),document.removeEventListener(`keydown`,this.handleSpaceDown),document.removeEventListener(`keyup`,this.handleKeyUp),window.removeEventListener(`blur`,this.handleBlur),window.removeEventListener(`scroll`,this.handlePageChange,{capture:!0}),window.removeEventListener(`resize`,this.handlePageChange),this.boardEl.removeEventListener(`wheel`,this.handleWheel),this.overlayObserver?.disconnect(),this.noteAnimator.clear(),this.measuredSizes.clear(),this.restackPending=!1,this.noteManager.destroy(),this.dragManager.destroy(),this.anchorDragManager.destroy(),this.resizeManager.destroy(),this.edgePopup.destroy(),this.notePopup.destroy(),this.richTextToolbar.destroy(),this.historyManager.destroy(),this.selectionManager.destroy(),this.edgeManager.destroy(),this.emitter.removeAllListeners(),this.boardEl.remove()}addNote(e){if(this.readOnly||this.viewOnly)return;let{left:t,top:n}=this.pageScroll?this.boardEl.getBoundingClientRect():{left:0,top:0},r=this.view.screenToBoard(Math.max(-t,0),Math.max(-n,0)),i=this.newNotePlace({x:r.x+100,y:r.y+100});return this.noteManager.addNote({...e,x:e?.x??i.x,y:e?.y??i.y})}newNotePlace(e){let t=this.stack?this.noteManager.getNotes():[];if(t.length===0)return e;let n=s(t);return{x:n.left,y:n.bottom+ur}}updateNote(e,t){this.readOnly||this.noteManager.updateNote(e,t)}deleteNote(e){this.readOnly||this.viewOnly||this.removeNote(e)}getNote(e){return this.noteManager.getNote(e)}refreshNote(e){this.noteManager.refresh(e)&&this.updateNotePopup(),this.redrawNoteLinkPeers?.([e])}refreshNoteAccessory(e){this.noteManager.requestAccessory(e)}resizeNotesToContent(e){this.readOnly||this.viewOnly||(this.batch(()=>{for(let t of e)this.noteManager.resizeToContent(t)}),this.updateNotePopup())}quoteInNewNote(e,t){if(this.readOnly||this.viewOnly)return;this.noteManager.getTextElement(e)?.blur();let n=this.noteManager.getNote(e);if(!n)return;let r=n.width,i=this.defaultNoteHeight,a=this.pageScroll?n.x:n.x+n.width+sr,o=this.pageScroll?n.y+n.height+cr:n.y,s=this.noteManager.getNotes().filter(e=>!this.hiddenNoteIds.has(e.id)&&e.x<a+r&&e.x+e.width>a).sort((e,t)=>e.y-t.y);for(let e of s)e.y<o+i&&e.y+e.height>o&&(o=e.y+e.height+cr);({x:a,y:o}=this.newNotePlace({x:a,y:o}));let c=this.batch(()=>{let s=this.noteManager.addNote({x:a,y:o,width:r,height:i,text:`<blockquote>${t}</blockquote><div><br></div>`,color:n.color,autoSize:n.autoSize,foldable:n.foldable});return this.edgeManager.addEdge(e,s.id),s},{origin:`user`});this.selectionManager.select([c.id]),this.updateNotePopup(),this.revealNotes([c.id])}getNotes(){return this.noteManager.getNotes()}addEdge(e,t,n){if(!(this.readOnly||this.viewOnly))return this.edgeManager.addEdge(e,t,n)}getSelectedEdge(){return this.edgeManager.getSelectedEdge()}updateEdge(e,t){if(!this.readOnly){if(this.viewOnly){if(!(`collapsed`in t))return;t={collapsed:t.collapsed}}this.edgeManager.updateEdge(e,t)}}deleteEdge(e){this.readOnly||this.viewOnly||this.edgeManager.deleteEdge(e)}getEdges(){return this.edgeManager.getEdges()}getEdgesOf(e){return this.edgeManager.getEdgesOf(e)}updateNotePopup(){if(this.viewOnly)return;let e=this.selectionManager.getSelection();e.length===1?this.notePopup.show(e[0]):e.length>=2?this.notePopup.showMulti(e):this.notePopup.hide()}select(e){this.selectionManager.select(e)}selectAll(){this.selectionManager.selectAll(),this.updateNotePopup()}getSelection(){return this.selectionManager.getSelection()}setNoteFilter(e){this.noteFilter=e?new Set(e):null,this.recomputeVisibility()}getNoteFilter(){return this.noteFilter?Array.from(this.noteFilter):null}isNoteHidden(e){return this.hiddenNoteIds.has(e)}getViewport(){return this.view.get()}setViewport(e){this.pageScroll||this.applyViewport(e)}applyViewport(e){this.view.set(e)&&(this.placeOverlays(),this.emitter.emit(`viewport:change`,this.getViewport()))}zoomTo(e,t){this.setViewport(this.zoomedAround(e,t))}zoomedAround(e,t){let n=this.view.get(),r=this.view.clampZoom(e),i=t?this.view.clientToScreen(t.clientX,t.clientY):this.view.screenCenter(),a=r/n.zoom;return{x:i.x-(i.x-n.x)*a,y:i.y-(i.y-n.y)*a,zoom:r}}panWithinLimit(e){let t=Number.isFinite(this.panMargin)?this.visibleBounds():null;if(!t){this.setViewport(e);return}let n=this.view.get(),r=e.zoom??n.zoom,i=this.panMargin,a=r===n.zoom,o=(e,t,n,o,s)=>{let c=Math.min(s-i-o*r,-n*r),l=Math.max(i-n*r,s-o*r);return a&&(c=Math.min(c,t),l=Math.max(l,t)),Math.min(Math.max(e,c),l)+0};this.setViewport({x:o(e.x,n.x,t.left,t.right,this.boardEl.clientWidth),y:o(e.y,n.y,t.top,t.bottom,this.boardEl.clientHeight),zoom:r})}revealNotes(e,t){let n=t?.padding??24;this.pageScroll?this.scrollPageToNotes(e,n):this.moveToNotes(e,n,(e,t,r)=>e<n?n:t>r-n?r-n-(t-e):e)}centerContent(e){this.moveToNotes(e?.noteIds,e?.padding??24,fr)}fitToContent(e){let t=e?.padding??24;this.moveToNotes(e?.noteIds,t,fr,(n,r,i,a)=>Math.min(Math.max(i-t*2,1)/Math.max(n,1),Math.max(a-t*2,1)/Math.max(r,1),e?.maxZoom??1))}moveToNotes(e,t,n,r){let i=this.visibleBounds(e),a=this.boardEl.clientWidth,o=this.boardEl.clientHeight;if(!i||a===0||o===0)return;let s=this.view.get(),c=r?this.view.clampZoom(r(i.right-i.left,i.bottom-i.top,a,o)):s.zoom,l=(e,r,i,a)=>{let o=e*c+i,s=r*c+i;return i+(s-o+t*2>a?t:n(o,s,a))-o};this.setViewport({x:l(i.left,i.right,s.x,a),y:l(i.top,i.bottom,s.y,o),zoom:c})}visibleBounds(e){let t=e?new Set(e):null;this.stack&&this.flushPending();let n=this.noteManager.getPlacedBoxes().filter(e=>(!t||t.has(e.id))&&!this.hiddenNoteIds.has(e.id));return n.length===0?null:s(n)}setPageScroll(e){this.pageScroll!==e&&(e&&(this.pan&&this.handlePanUp(new PointerEvent(`pointercancel`,{pointerId:this.pan.pointerId})),this.setSpaceHeld(!1),this.applyViewport({x:0,y:0,zoom:1})),this.pageScroll=e,this.boardEl.classList.toggle(`wema-page-scroll`,e),E(this.boardEl,{height:e?`0px`:`100%`,minHeight:e?`100%`:``,overflow:e?`visible`:`hidden`}),this.updatePageHeight(),this.placeOverlays())}setStacked(e,t){(e||this.stack)&&(this.stack=e?dr(e):null,this.stackedSides.clear(),this.boardEl.classList.toggle(`wema-stacked`,this.stack!==null),this.stack&&(this.edgeManager.deselectEdge(),this.edgePopup.hide()),this.noteManager.setFootersShown(this.stack!==null),this.restack(this.noteManager.getNotes().map(e=>e.id),t?.duration))}getStacked(){return this.stack?dr(this.stack):null}restack(e=[],t){this.restackPending=!1;let n=this.stack,r=n?this.noteManager.getNotes().filter(e=>!this.hiddenNoteIds.has(e.id)).map(e=>e.id):[],i=[];this.animateNotes(e,t,()=>(i=this.noteManager.placeNotes(r,n?.width,e=>ln(e,{x:0,y:0,...n})),i)),i.length>0&&this.updateNoteCollapseBtns()}scheduleRestack(){this.stack&&(this.restackPending=!0,this.queueFlush())}queueFlush(){this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flushPending()}))}flushPending(){let e=this.restackPending;this.restackPending=!1;let t=this.noteManager.drawUnder();e||t&&this.stack?this.restack():t&&this.followUnder()}followUnder(){this.stack?this.scheduleRestack():(this.updatePageHeight(),this.placeOverlays())}isPageScroll(){return this.pageScroll}updatePageHeight(){if(!this.pageScroll)return;let e=this.noteManager.lowestBottom(e=>!this.hiddenNoteIds.has(e)),t=e===null?0:Math.ceil(this.view.boardToScreen(0,e).y)+lr;if(t<(parseFloat(this.boardEl.style.height)||0)&&(this.holdsPageHeight||this.noteAnimator.isRunning()))return;let n=`${Math.max(t,0)}px`;this.boardEl.style.height!==n&&(this.boardEl.style.height=n)}leavesToPage(e){return this.pageScroll&&(e.pointerType===`touch`||this.wantsPan(e))}scrollPageToNotes(e,t){let n=this.visibleBounds(e);if(!n)return;let r=v(`div`);E(r,{position:`absolute`,left:`${n.left}px`,top:`${n.top}px`,width:`${n.right-n.left}px`,height:`${n.bottom-n.top}px`,scrollMargin:`${t}px`,visibility:`hidden`,pointerEvents:`none`}),this.viewportEl.appendChild(r),r.scrollIntoView?.({block:`nearest`,inline:`nearest`}),r.remove()}wantsPan(e){let t=e.target;if(t.closest(rr))return!1;if(e.button===1)return!0;if(e.button!==0)return!1;if(this.spaceHeld)return!0;if(t.closest(`.wema-note`))return!1;if(this.readOnly)return!0;let n=this.viewOnly||this.emptyDrag===`pan`,r=e.shiftKey||this.emptyDrag===`pan`&&(e.ctrlKey||e.metaKey);return n&&!r}setSpaceHeld(e){this.spaceHeld=e,this.boardEl.classList.toggle(`wema-pan-ready`,e)}moveNotes(e,t){this.readOnly||this.applyMoves(e,t)}alignNotes(e,t,n){this.readOnly||this.viewOnly||this.applyMoves(un(this.getNotesByIds(e),t),n)}distributeNotes(e,t,n){this.readOnly||this.viewOnly||this.applyMoves(dn(this.getNotesByIds(e),t),n)}autoLayout(e,t){if(this.readOnly||this.viewOnly)return;let n=e??this.getNoteFilter()??void 0,r=this.boardEl.clientWidth/this.boardEl.clientHeight;this.applyMoves(Rn(this.noteManager.getNotes(),this.edgeManager.getEdges(),{noteIds:n,aspectRatio:r}),t)}stackNotes(e={}){if(this.readOnly)return;let{noteIds:t,duration:n,...r}=e,i=(t??this.noteManager.getNotes().map(e=>e.id)).filter(e=>!this.hiddenNoteIds.has(e));this.animateNotes(this.movedOnScreen(i),n,()=>{r.width!==void 0&&this.setNoteRects(i.map(e=>({id:e,width:r.width}))),this.setNoteRects(ln(this.getNotesByIds(i),r))})}getNotesByIds(e){return e.map(e=>this.noteManager.getNote(e)).filter(e=>e!=null)}applyMoves(e,t){this.animateNotes(this.movedOnScreen(e.map(e=>e.id)),t?.duration,()=>this.setNoteRects(e))}movedOnScreen(e){return this.stack?[]:e}setNoteRects(e){for(let t of e){let e=this.noteManager.getNote(t.id);if(!e)continue;let n={};for(let r of Ge){if(r===`width`&&e.autoSize||r===`height`&&(e.autoSize||this.noteManager.hasMeasuredHeight(e.id)))continue;let i=t[r];typeof i==`number`&&Number.isFinite(i)&&i!==e[r]&&(n[r]=i)}Object.keys(n).length>0&&this.noteManager.updateNote(t.id,n)}}animateNotes(e,t,n){let r=typeof t==`number`&&t>0&&Number.isFinite(t)&&!it(),i=new Map;for(let t of e){let e=this.noteManager.getShownNote(t);e&&i.set(t,qe(e))}let a=[];this.holdsPageHeight=!0;try{a=n()??[]}finally{this.holdsPageHeight=!1}let o=new Set(a);for(let[e,n]of i){let i=this.noteManager.getPlacedNote(e);r&&i&&Ke(n,i)?(this.noteAnimator.start(e,n,t),o.add(e)):this.noteAnimator.cancel(e)&&o.add(e)}o.size>0?this.followShownNotes([...o]):this.updatePageHeight(),this.updateNotePopup()}followShownNotes(e){this.edgeManager.updateEdgesOfNotes(e),this.updatePageHeight(),this.placeOverlays()}batch(e,t){this.historyManager.beginBatch(t?.origin);try{return e()}finally{this.historyManager.endBatch()}}applyRemote(e){this.visibilitySuspended=!0;try{this.historyManager.withoutRecording(()=>Kn(e,this.createReplay(`remote`)))}finally{this.visibilitySuspended=!1,this.recomputeVisibility()}this.edgeManager.getSelectedEdge()||this.edgePopup.hide(),this.updateNotePopup()}createReplay(e){return{addNoteWithId:t=>{this.noteManager.addNoteWithId(t,e)},updateNote:(t,n)=>{this.noteManager.replayUpdate(t,n,e)},deleteNote:t=>{this.removeNote(t,e)},addEdgeWithId:t=>{this.edgeManager.addEdgeWithId(t,e)},updateEdge:(t,n)=>{this.edgeManager.updateEdge(t,n,e)},deleteEdge:t=>{this.edgeManager.deleteEdge(t,e)}}}removeNote(e,t=`local`){for(let n of this.edgeManager.getEdgesOf(e))this.edgeManager.deleteEdge(n.id,t);this.selectionManager.deselect(e),this.noteManager.deleteNote(e,t)}undo(){this.viewOnly||(this.notePopup.hide(),this.edgePopup.hide(),this.selectionManager.clear(),this.historyManager.undo())}redo(){this.viewOnly||(this.notePopup.hide(),this.edgePopup.hide(),this.selectionManager.clear(),this.historyManager.redo())}canUndo(){return this.historyManager.canUndo()}canRedo(){return this.historyManager.canRedo()}exportData(){let e={version:1,notes:this.noteManager.getNotesWithLiveText(),edges:this.edgeManager.getEdges()};return JSON.parse(JSON.stringify(e))}importData(e){this.noteFilter=null,this.noteAnimator.clear(),this.measuredSizes.clear(),this.noteLinkLines.clear(),this.selectionManager.clear(),this.edgeManager.clear(),this.noteManager.renderAll(e.notes),e.edges&&this.edgeManager.renderAll(e.edges),this.historyManager.clear(),this.viewOnly&&this.snapshotForViewOnly(),this.recomputeVisibility(),this.reportedHidden=new Set(this.hiddenNoteIds)}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setReadOnly(e){this.readOnly!==e&&(this.readOnly=e,this.noteManager.setReadOnly(e),this.richTextToolbar.setReadOnly(e),e?(this.boardEl.classList.add(`wema-readonly`),this.selectionManager.clear(),this.notePopup.hide(),this.edgePopup.hide()):this.boardEl.classList.remove(`wema-readonly`),this.emitter.emit(`readOnly:change`,{readOnly:e}),this.recomputeVisibility())}isReadOnly(){return this.readOnly}setViewOnly(e){if(this.viewOnly!==e){if(this.viewOnly=e,this.richTextToolbar.setViewOnly(e),e)this.selectionManager.clear(),this.enterViewOnly(),this.notePopup.hide(),this.edgePopup.hide();else{if(this.positionSnapshot){for(let[e,{x:t,y:n}]of this.positionSnapshot)this.noteManager.updateNote(e,{x:t,y:n});this.positionSnapshot=null}if(this.collapsedEdgeSnapshot){for(let[e,t]of this.collapsedEdgeSnapshot)this.edgeManager.updateEdge(e,{collapsed:t?!0:void 0});this.collapsedEdgeSnapshot=null}this.historyManager.setIgnoredKeys([],[]),this.boardEl.classList.remove(`wema-viewonly`),this.noteManager.setViewOnly(!1)}this.emitter.emit(`viewOnly:change`,{viewOnly:e}),this.recomputeVisibility()}}enterViewOnly(){this.snapshotForViewOnly(),this.historyManager.setIgnoredKeys([`x`,`y`],[`collapsed`]),this.boardEl.classList.add(`wema-viewonly`),this.noteManager.setViewOnly(!0)}snapshotForViewOnly(){this.positionSnapshot=new Map(this.noteManager.getNotes().map(e=>[e.id,{x:e.x,y:e.y}])),this.collapsedEdgeSnapshot=new Map(this.edgeManager.getEdges().map(e=>[e.id,!!e.collapsed]))}isViewOnly(){return this.viewOnly}setTheme(e){this.theme!==e&&(this.boardEl.classList.remove(`wema-theme-${this.theme}`),this.theme=e,e!=="default"&&this.boardEl.classList.add(`wema-theme-${e}`))}getTheme(){return this.theme}insertImageIntoNote(e){let t=document.createElement(`input`);t.type=`file`,t.accept=`image/*`,t.addEventListener(`change`,()=>{let n=t.files?.[0];if(!n)return;if(this.onImageUpload){this.uploadImage(e,n,this.onImageUpload);return}let r=new FileReader;r.onload=()=>{this.appendImage(e,r.result,n.name)},r.readAsDataURL(n)}),t.click()}async uploadImage(e,t,n){try{let r=await n(t);if(typeof r!=`string`||r===``||!A(r,`image/`))throw Error(`onImageUpload returned an unusable URL: ${String(r)}`);if(this.readOnly||this.viewOnly)throw Error(`The board became read-only before the upload finished`);this.appendImage(e,r,t.name)}catch(n){this.emitter.emit(`image:error`,{noteId:e,file:t,error:n})}}appendImage(e,t,n){let r=this.noteManager.getTextElement(e);if(!r)return;let i=document.createElement(`img`);i.src=t,i.alt=n,i.style.maxWidth=`100%`,r.appendChild(i),r.dispatchEvent(new Event(`input`,{bubbles:!0})),this.noteManager.updateNote(e,{text:r.innerHTML})}showEmbedInput(e){if(this.embedInput?.el.remove(),this.embedInput=null,!this.noteManager.getNote(e))return;let t=v(`div`,`wema-embed-input`);this.embedInput={el:t,noteId:e};let n=()=>{t.remove(),this.embedInput?.el===t&&(this.embedInput=null)};t.style.position=`absolute`,t.style.zIndex=`10002`,t.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`mousedown`,e=>e.stopPropagation()),t.addEventListener(`pointerdown`,e=>e.stopPropagation());let r=document.createElement(`input`);r.type=`text`,r.placeholder=`https://...`,r.style.cssText=`width:200px;padding:4px 6px;border:1px solid #ddd;border-radius:3px;font-size:12px;`;let i=v(`button`,`wema-popup-btn`);i.textContent=this.labels.ok,i.addEventListener(`click`,()=>{let t=r.value.trim();t&&this.embedUrl(e,t),n()});let a=v(`button`,`wema-popup-btn`);a.textContent=`✕`,a.addEventListener(`click`,n),t.appendChild(r),t.appendChild(i),t.appendChild(a),this.boardEl.appendChild(t),this.placeEmbedInput(),r.focus()}placeEmbedInput(){if(!this.embedInput)return;let e=this.noteManager.getShownNote(this.embedInput.noteId);if(!e)return;let{box:t,side:n}=this.notePopup.boxWith(e.id)??{box:this.view.boardBoxToScreen(s([e])),side:`below`};b(this.embedInput.el,this.boardEl,t,n,ir)}placeOverlays(){this.notePopup.updatePosition(),this.edgePopup.updatePosition(),this.richTextToolbar.updatePosition(),this.noteManager.updateOverlayPosition(),this.placeEmbedInput()}static IMAGE_URL_RE=/\.(?:png|jpe?g|gif|webp|svg|bmp|ico)(?:\?.*)?$/i;static VIDEO_URL_RE=/\.(?:mp4|webm|ogg|mov)(?:\?.*)?$/i;static AUDIO_URL_RE=/\.(?:mp3|wav|flac|aac|m4a|opus|weba)(?:\?.*)?$/i;async embedUrl(t,n){if(!A(n))return;let r=this.noteManager.getTextElement(t);if(r){if(e.IMAGE_URL_RE.test(n)){let e=document.createElement(`img`);e.src=n,r.appendChild(e)}else if(e.VIDEO_URL_RE.test(n)){let e=document.createElement(`video`);e.src=n,e.controls=!0,e.preload=`metadata`,r.appendChild(e)}else if(e.AUDIO_URL_RE.test(n)){let e=document.createElement(`audio`);e.src=n,e.controls=!0,e.preload=`metadata`,r.appendChild(e)}else{let e=await tr(n),t=document.createElement(`iframe`);t.src=e,t.width=`100%`,t.height=`200`,t.style.border=`none`,t.setAttribute(`allowfullscreen`,``),t.setAttribute(`allow`,`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`),r.appendChild(t)}r.dispatchEvent(new Event(`input`,{bubbles:!0})),this.noteManager.updateNote(t,{text:r.innerHTML})}}recomputeVisibility(){if(this.visibilitySuspended)return;let e=this.noteManager.getNotes(),t=this.edgeManager.getEdges(),n=new Set,r=new Set,i=this.noteFilter,a=e=>!i||i.has(e),o=t.filter(e=>a(e.from)&&a(e.to));for(let t of e)a(t.id)||n.add(t.id);for(let e of t)a(e.from)&&a(e.to)||r.add(e.id);for(let e of o)e.collapsed&&(r.add(e.id),this.dfsHideNotes(e.to,o,n,r));this.hiddenNoteIds=n,this.scheduleVisibility();let s=this.selectionManager.getSelection(),c=s.filter(e=>!n.has(e));c.length!==s.length&&(this.selectionManager.select(c),this.updateNotePopup());let l=this.edgeManager.getSelectedEdge();l&&r.has(l)&&(this.edgeManager.deselectEdge(),this.edgePopup.hide());for(let t of e){let e=this.noteManager.getElement(t.id);if(!e)continue;let r=e.style.display===`none`,i=n.has(t.id);e.style.display=i?`none`:``,r&&!i&&this.noteManager.remeasure(t.id)}this.edgeManager.applyVisibility(r),this.buttonEdges=o,this.updateNoteCollapseBtns(),this.scheduleRestack(),this.updatePageHeight()}dfsHideNotes(e,t,n,r){if(!n.has(e)){n.add(e);for(let i of t)i.from===e&&(r.add(i.id),this.dfsHideNotes(i.to,t,n,r))}}updateNoteCollapseBtns(){let e=this.hiddenNoteIds,t=new Map;for(let e of this.buttonEdges){let n=this.noteManager.getPlacedNote(e.from),r=this.noteManager.getPlacedNote(e.to);if(!n||!r)continue;let i;e.fromAnchor===`auto`?this.stack===null?i=p(n,r):this.noteManager.isPlaced(e.from)&&this.noteManager.isPlaced(e.to)?(i=p(n,r),this.stackedSides.set(e.id,i)):i=this.stackedSides.get(e.id)??`bottom`:i=e.fromAnchor;let a=t.get(e.from);a||(a=new Map,t.set(e.from,a));let o=a.get(i);o||(o=[],a.set(i,o)),o.push(e)}let n=[`top`,`right`,`bottom`,`left`];for(let r of this.noteManager.getNotes()){let i=this.noteManager.getElement(r.id);if(!i)continue;let a=t.get(r.id);for(let t of n){let n=i.querySelector(`.wema-note-collapse-btn[data-side="${t}"]`);if(!n)continue;let o=a?.get(t);if(!o||o.length===0||e.has(r.id)||this.readOnly){n.style.display=`none`,n.classList.remove(`wema-note-collapse-badge`);continue}let s=o.every(e=>e.collapsed);n.style.display=``;let c=o.map(e=>e.id);if(n.onclick=e=>{if(e.stopPropagation(),s)for(let e of c)this.edgeManager.updateEdge(e,{collapsed:!1});else for(let e of c)this.edgeManager.updateEdge(e,{collapsed:!0})},s){let e=this.countSubtreeFromEdges(o,this.buttonEdges);n.className=`wema-note-collapse-btn wema-note-collapse-badge`,n.dataset.side=t,n.textContent=String(e)}else n.className=`wema-note-collapse-btn`,n.dataset.side=t,n.innerHTML=`<svg width="10" height="2" viewBox="0 0 10 2" fill="none"><line x1="1" y1="1" x2="9" y2="1" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`}}}countSubtreeFromEdges(e,t){let n=new Set;for(let r of e)r.collapsed&&this.countSubtreeDFS(r.to,t,n);return n.size}countSubtreeDFS(e,t,n){if(!n.has(e)){n.add(e);for(let r of t)r.from===e&&this.countSubtreeDFS(r.to,t,n)}}scheduleMeasure(e,t){this.measuredSizes.has(e)||(this.measuredSizes.set(e,t),!(this.measuredSizes.size>1)&&queueMicrotask(()=>{let e=this.measuredSizes;this.measuredSizes=new Map;for(let[t,{width:n,height:r}]of e){let e=this.noteManager.getNote(t);!e||e.width===n&&e.height===r||this.emitter.emit(`note:measure`,{note:e,prev:{...e,width:n,height:r}})}}))}scheduleVisibility(){this.visibilityPending||(this.visibilityPending=!0,queueMicrotask(()=>{this.visibilityPending=!1;let e=this.reportedHidden,t=this.hiddenNoteIds;this.reportedHidden=new Set(t);let n=[...t].filter(t=>!e.has(t)),r=[...e].filter(e=>!t.has(e)&&this.noteManager.getNote(e)!==void 0);(n.length>0||r.length>0)&&this.emitter.emit(`note:visibility`,{hidden:n,shown:r})}))}scheduleChange(){this.changePending||(this.changePending=!0,queueMicrotask(()=>{this.changePending=!1,this.emitter.emit(`change`,{data:this.exportData()})}))}},mr=(e,t)=>`<b>${e}</b>${t.map(e=>`<div>${e}</div>`).join(``)}`,hr=e=>`<b>${e.heading}</b><div><b>${e.bold}</b>${e.separator}<s>${e.strike}</s>${e.separator}<span style="color: #d32f2f">${e.color}</span>${e.separator}<a href="https://github.com/kan/wema-kake" target="_blank" rel="noopener">${e.link}</a></div><ul><li>${e.bullet}<ul><li>${e.nested}</li></ul></li></ul><ol><li>${e.numbered[0]}</li><li>${e.numbered[1]}</li></ol><ul class="wema-checklist"><li><input type="checkbox">${e.todo}</li><li class="wema-checked"><input type="checkbox" checked>${e.done}</li></ul>`,gr={ja:{firstPageTitle:`最初のページ`,intro:{first:mr(`wema-kake へようこそ`,[`付箋を並べて書く Wiki です。`,`1 ページが、1 枚のボードになります。`,`このページの付箋は、消してかまいません。`]),help:mr(`使い方`,[`試すためのボードです。`,`付箋を動かしたり、書き換えたりできます。`,`ここでの変更は、保存されません。`])},sample:hr({heading:`装飾の見本`,bold:`太字`,strike:`取り消し線`,color:`文字の色`,link:`リンク`,separator:`、`,bullet:`箇条書き`,nested:`段を下げた項目`,numbered:[`番号付きのリスト`,`2 つ目`],todo:`チェックリスト`,done:`済んだ項目`}),sections:{notes:[`付箋`,[`空いている場所をダブルクリック → 作る`,`上端をドラッグ → 動かす`,`右下をドラッグ → 大きさを変える`,`右下をダブルクリック → 内容に合わせる`,`選択して Delete → 削除する`,`Shift + クリック → 複数を選ぶ`,`Ctrl + ドラッグ → 囲んで選ぶ`]],text:[`本文`,[`文字を選択 → 太字、取り消し線、色、リンク`,`付箋を選択 → 色、リスト、画像`,`リストの中で Tab → 段を下げる`,`長い本文は、畳んで表示できる`]],edges:[`接続線`,[`縁の ● をドラッグ → 他の付箋とつなぐ`,`空いている場所で離す → 先に付箋を作る`,`線をクリック → 種類やラベルを変える`]],view:[`表示`,[`ホイール、空いた場所をドラッグ → 動かす`,`Ctrl + ホイール、ピンチ → 拡大と縮小`,`Ctrl + Z → 元に戻す(自分の操作だけ)`,`メニューの「参照モード」 → 読むだけにする`,`狭い画面では、縦 1 列に並べて表示する`,`並んでいる間は動かせず、線は印になる`]],pages:[`ページ`,[`「子ページを置く」 → 中にページを作る`,`子ページの表示名をクリック → 中へ入る`,`付箋を子ページへドラッグ → 中へ移動(Ctrl でコピー)`,`/p/ページ名 へのリンク → 他のページへ移る`,`左上の表示名をクリック → 名前を変える`]],llm:[`LLM`,[`MCP でつなぐと、Claude などが読み書きできる`,`LLM の操作は、メニューの「操作の履歴」に残る`,`履歴から、操作ごとに取り消せる`]]},column:460},en:{firstPageTitle:`First page`,intro:{first:mr(`Welcome to wema-kake`,[`A wiki you write with sticky notes.`,`Each page is one board.`,`Feel free to delete the notes on this page.`]),help:mr(`Help`,[`A board for trying things out.`,`Move the notes around or rewrite them.`,`Nothing you change here is saved.`])},sample:hr({heading:`Formatting sample`,bold:`Bold`,strike:`strikethrough`,color:`text color`,link:`link`,separator:`, `,bullet:`Bulleted list`,nested:`Indented item`,numbered:[`Numbered list`,`Second item`],todo:`Checklist`,done:`Finished item`}),sections:{notes:[`Notes`,[`Double-click an empty spot → create`,`Drag the top edge → move`,`Drag the bottom-right corner → resize`,`Double-click that corner → fit the content`,`Select and press Delete → delete`,`Shift + click → select several`,`Ctrl + drag → select an area`]],text:[`Text`,[`Select text → bold, strikethrough, color, link`,`Select a note → color, lists, image`,`Tab inside a list → indent`,`A long text can be shown folded`]],edges:[`Connections`,[`Drag a ● on the edge → connect to a note`,`Drop on an empty spot → create a note there`,`Click a line → change its style or label`]],view:[`View`,[`Wheel, or drag an empty spot → pan`,`Ctrl + wheel, or pinch → zoom`,`Ctrl + Z → undo (your own changes only)`,`“View-only mode” in the menu → read only`,`A narrow screen shows the notes in one column`,`There, notes do not move; lines become chips`]],pages:[`Pages`,[`“Place a child page” → a page inside this one`,`Click a child page’s title → go inside`,`Drag a note onto a child page → move it inside (Ctrl: copy)`,`A link to /p/page-name → go to that page`,`Click the title at the top left → rename`]],llm:[`LLM`,[`Over MCP, Claude and others can read and write`,`Their operations are kept in “Operation history”`,`Revert them there, one operation at a time`]]},column:480}},_r=[60,370,680],vr={sample:{color:`#F5F5F5`,column:0,row:0,height:250},intro:{color:`#FFF9C4`,column:1,row:0,height:120},notes:{color:`#BBDEFB`,column:0,row:1,height:220},text:{color:`#FFE0B2`,column:1,row:1,height:170},edges:{color:`#C8E6C9`,column:2,row:1,height:150},view:{color:`#FFCDD2`,column:0,row:2,height:210},pages:{color:`#E1BEE7`,column:1,row:2,height:170},llm:{color:`#B2DFDB`,column:2,row:2,height:150}},yr=[[`intro`,`notes`],[`intro`,`text`],[`intro`,`edges`],[`notes`,`view`],[`text`,`pages`],[`edges`,`llm`]],br=e=>`guide-${e}`,xr=br(`intro`);function Sr(e,t){let n=gr[t],r=t=>{if(t===`sample`)return n.sample;if(t===`intro`)return n.intro[e];let[r,i]=n.sections[t];return`<b>${r}</b><ul>${i.map(e=>`<li>${e}</li>`).join(``)}</ul>`};return{notes:Object.keys(vr).map((e,t)=>{let{color:i,column:a,row:o,height:s}=vr[e];return{id:br(e),x:60+a*n.column,y:_r[o],width:380,height:s,text:r(e),color:i,zIndex:t+1,autoSize:!0}}),edges:yr.map(([e,t])=>({id:`guide-${e}-${t}`,from:br(e),to:br(t),fromAnchor:`auto`,toAnchor:`auto`,style:`arrow`}))}}var Cr=[`ja`,`en`],wr=`wk_lang`,Tr=e=>Cr.includes(e);function Er(e,t,n){if(Tr(e))return e;for(let e of t){let t=e.trim().toLowerCase().split(`-`)[0];if(Tr(t))return t}return n}function Dr(e,t){for(let n of(e??``).split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}}var Or={siteName:`wema-kake`,defaultLang:`en`},kr=`wema-kake-site`;function Ar(e){let t={};try{let n=JSON.parse(e??``);n&&typeof n==`object`&&(t=n)}catch{}return{siteName:typeof t.siteName==`string`&&t.siteName!==``?t.siteName:Or.siteName,defaultLang:typeof t.defaultLang==`string`&&Tr(t.defaultLang)?t.defaultLang:Or.defaultLang}}var jr=globalThis.document,Mr=Ar(jr?.querySelector(`meta[name="${kr}"]`)?.getAttribute(`content`)),B=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,Nr={loading:`Loading…`,notFound:`Page not found`,list:`All pages`,close:`Close`,save:`Save`,title:`Title`,help:`Help`,undo:`Undo (Ctrl+Z)`,redo:`Redo (Ctrl+Shift+Z)`,documentTitle:(e,t)=>`${e} - ${t}`,"lang.switch":`日本語`,"failed.bookmark":e=>`Could not change the bookmark (${e})`,"failed.ancestors":e=>`Could not load the parent pages (${e})`,"failed.rename":e=>`Could not rename the page (${e})`,"failed.color":e=>`Could not change the page color (${e})`,"failed.backlinks":e=>`Could not load the backlinks (${e})`,"failed.history":e=>`Could not load the history (${e})`,"failed.revert":e=>`Could not revert the operation (${e})`,"failed.delete":e=>`Could not delete the page (${e})`,"failed.create":e=>`Could not create the page (${e})`,"failed.transfer":e=>`Could not send the notes to the child page (${e})`,"zoom.reset":`Reset to 100%`,"zoom.out":`Zoom out`,"zoom.in":`Zoom in`,"zoom.fit":`Zoom out to fit everything`,"zoom.center":`Center on the notes (keep the zoom)`,"links.loadFailed":e=>`Could not load (${e})`,"nav.title":`Go to a page (bookmarks, recent changes)`,"nav.filter":`Filter by page name`,"nav.bookmarked":`Bookmarked page`,"nav.empty":`No pages`,"nav.noMatch":`No matching pages`,"nav.more":`There are more. Type more to narrow them down`,"bookmark.add":`Bookmark this page`,"bookmark.remove":`Remove the bookmark`,"bookmark.unwritten":`A page with nothing written on it yet cannot be bookmarked`,"form.optional":`Optional`,"form.slugHint":`The name used in the URL. Lowercase letters, digits and hyphens`,"form.slugInvalid":`A slug is lowercase letters, digits and hyphens, up to 64 characters`,"form.create":`Create`,"form.slugTaken":`A page with that slug already exists. `,"form.openIt":`Open it`,"page.rename":`Rename`,"page.delete":`Delete page`,"page.deleteConfirm":e=>`Delete the page “${e}”? All its notes and history will be removed. This cannot be undone.`,"page.alreadyDeleted":`This page has already been deleted`,"page.deletedAlert":`This page was deleted. Returning to the list of pages.`,"page.titleHint":e=>`/p/${e} (click to rename)`,"page.color":`Page color`,"page.colorNone":`No color`,"index.filter":`Filter pages`,"index.newPage":`+ New page`,"index.count":e=>B(e,`page`),"index.matched":(e,t,n)=>`${e} / ${B(t,`page`)}${n}`,"index.searchFailed":e=>` (text search failed: ${e})`,"index.empty":`No pages yet`,"index.loadFailed":e=>`Could not load the list of pages (${e})`,"index.meta":(e,t,n)=>`${e} · ${B(t,`note`)}${n>0?` · ${B(n,`child page`)}`:``}`,"index.descendantHits":e=>`${B(e,`match`,`matches`)} in child pages`,"index.missing":`Not created`,"note.add":`Add a note`,"author.agentTitle":e=>`Note made by AI (${e})`,"author.detail":(e,t)=>`${e} · ${t}`,"layout.title":`Align and arrange`,"align.left":`Align left edges`,"align.center":`Align horizontal centers`,"align.right":`Align right edges`,"align.top":`Align top edges`,"align.middle":`Align vertical centers`,"align.bottom":`Align bottom edges`,"layout.distributeH":`Distribute horizontally (select 3 or more)`,"layout.distributeV":`Distribute vertically (select 3 or more)`,"layout.auto":`Arrange along the connections (whole board)`,"status.connecting":`Connecting…`,"status.offline":`Offline (reconnecting)`,"status.saving":`Saving…`,"sync.conflict":`Someone else was editing the same note, so your change was undone`,"sync.rejected":e=>`Your change could not be saved and was undone (${e})`,"backlinks.count":e=>`Backlinks ${e}`,"backlinks.title":`Pages that link to this page`,"menu.title":`Menu`,"menu.viewOnly":`View-only mode`,"menu.viewOnlyExit":`Leave view-only mode`,"menu.themeCard":`Note style: Card`,"menu.themeDefault":`Note style: Default`,"menu.history":`Operation history…`,"menu.exportJson":`Export as JSON`,"menu.deletePage":`Delete page…`,"ops.title":`Operation history`,"ops.agentOnly":`Agent operations only`,"ops.refresh":`Refresh`,"ops.empty":`No operations`,"ops.revert":`Revert`,"ops.noSummary":`(no description)`,"ops.revertedMark":` (reverted)`,"ops.summary.pageCreated":`Page created`,"ops.summary.childRemoved":e=>`Child page ${e} removed`,"ops.summary.revert":e=>`Reverted #${e}`,"ops.summary.revertUnknown":`Revert`,"ops.summary.notesReceived":e=>`Notes received from page ${e}`,"ops.summary.notesSent":e=>`Notes moved to page ${e}`,"ops.summary.childRecolored":e=>`Matched the color of child page ${e}`,"revert.done":`Reverted`,"revert.none":e=>`There was nothing to revert${e}`,"revert.partial":(e,t)=>`Partly reverted. ${B(e,`change`)} left as is${t}`,"revert.reasons":e=>` (${e.join(`, `)})`,"skip.modified":`changed since then`,"skip.connected":`other connections are attached`,"skip.deleted":`already deleted`,"skip.exists":`the same item already exists`,"skip.endpoint-missing":`a note at either end is missing`,"child.place":`Place a child page`,"child.newHeading":`Create a new page and place it`,"child.createAndPlace":`Create and place`,"child.existingHeading":`Place an existing page`,"child.rootPage":`Root page`,"child.slugPlaceholder":`Page name (slug)`,"child.placeExisting":`Place`,"child.slugTaken":`A page with that slug already exists. You can place it as an existing page`,"child.summary":(e,t)=>`Child page · ${B(e,`note`)} (/p/${t})`,"child.elsewhere":e=>`Placed in “${e}”`,"child.rejected":(e,t)=>`Could not place it as a child page (${e})${t?`. The page you created remains in the list as a root page`:``}`,"transfer.moved":(e,t)=>`Moved ${B(e,`note`)} to “${t}”`,"transfer.copied":(e,t)=>`Copied ${B(e,`note`)} to “${t}”`,"transfer.partial":e=>`Placed the notes in “${e}”, but some could not be removed from this page and are now in both (notes changed during the move are kept)`,"transfer.confirmMoveLinked":e=>`Also move the ${B(e,`note`)} connected by lines?\nChoose “Cancel” to move only the notes you dragged`,"transfer.confirmCopyLinked":e=>`Also copy the ${B(e,`note`)} connected by lines?\nChoose “Cancel” to copy only the notes you dragged`,"child.reject.not-found":`Page not found`,"child.reject.self":`A page cannot be placed in itself`,"child.reject.other-parent":`It is already a child of another page`,"child.reject.duplicate":`It is already placed on this page`,"child.reject.ancestor":`It is an ancestor of this page, so it would make a loop`,"child.reject.too-deep":e=>`Pages can be nested up to ${e} levels`,"help.unsaved":`This board is not saved`},Pr={loading:`読み込み中…`,notFound:`ページが見つかりません`,list:`一覧`,close:`閉じる`,save:`保存`,title:`表示名`,help:`使い方`,undo:`元に戻す (Ctrl+Z)`,redo:`やり直す (Ctrl+Shift+Z)`,documentTitle:(e,t)=>`${e} - ${t}`,"lang.switch":`English`,"failed.bookmark":e=>`ブックマークの変更に失敗しました(${e})`,"failed.ancestors":e=>`親ページの取得に失敗しました(${e})`,"failed.rename":e=>`表示名の変更に失敗しました(${e})`,"failed.color":e=>`ページの色の変更に失敗しました(${e})`,"failed.backlinks":e=>`リンク元の取得に失敗しました(${e})`,"failed.history":e=>`履歴の取得に失敗しました(${e})`,"failed.revert":e=>`取り消しに失敗しました(${e})`,"failed.delete":e=>`削除に失敗しました(${e})`,"failed.create":e=>`作成に失敗しました(${e})`,"failed.transfer":e=>`子ページへ付箋を送れませんでした(${e})`,"zoom.reset":`等倍に戻す`,"zoom.out":`縮小`,"zoom.in":`拡大`,"zoom.fit":`全体が収まるように縮小`,"zoom.center":`付箋全体の中央へ移動(倍率はそのまま)`,"links.loadFailed":e=>`取得できませんでした(${e})`,"nav.title":`ページへ移る(ブックマーク、最近の変更)`,"nav.filter":`ページ名で絞り込む`,"nav.bookmarked":`ブックマークしたページ`,"nav.empty":`ページはありません`,"nav.noMatch":`一致するページはありません`,"nav.more":`ほかにもあります。文字を足して絞り込めます`,"bookmark.add":`このページをブックマークする`,"bookmark.remove":`ブックマークを外す`,"bookmark.unwritten":`まだ何も書かれていないページには、付けられません`,"form.optional":`省略できます`,"form.slugHint":`URL に使う名前。小文字の英数字とハイフン`,"form.slugInvalid":`スラッグは小文字の英数字とハイフンで、64 文字までです`,"form.create":`作成`,"form.slugTaken":`そのスラッグのページはすでにあります。`,"form.openIt":`開く`,"page.rename":`表示名を変える`,"page.delete":`ページを削除`,"page.deleteConfirm":e=>`ページ「${e}」を削除します。付箋と履歴がすべて消え、取り消しはできません。`,"page.alreadyDeleted":`このページは、すでに削除されています`,"page.deletedAlert":`このページは削除されました。一覧へ戻ります。`,"page.titleHint":e=>`/p/${e}(クリックして表示名を変える)`,"page.color":`ページの色`,"page.colorNone":`色なし`,"index.filter":`ページを絞り込む`,"index.newPage":`+ 新規ページ`,"index.count":e=>`${e} ページ`,"index.matched":(e,t,n)=>`${e} / ${t} ページ${n}`,"index.searchFailed":e=>`(本文の検索に失敗しました: ${e})`,"index.empty":`まだページがありません`,"index.loadFailed":e=>`一覧を取得できませんでした(${e})`,"index.meta":(e,t,n)=>`${e}・付箋 ${t} 枚${n>0?`・子ページ ${n}`:``}`,"index.descendantHits":e=>`子ページに ${e} 件の一致`,"index.missing":`未作成`,"note.add":`付箋を追加`,"author.agentTitle":e=>`AI(${e})が作った付箋`,"author.detail":(e,t)=>`${e}・${t}`,"layout.title":`整列と配置`,"align.left":`左端をそろえる`,"align.center":`左右の中央をそろえる`,"align.right":`右端をそろえる`,"align.top":`上端をそろえる`,"align.middle":`上下の中央をそろえる`,"align.bottom":`下端をそろえる`,"layout.distributeH":`左右に均等に並べる(3 枚以上を選択)`,"layout.distributeV":`上下に均等に並べる(3 枚以上を選択)`,"layout.auto":`接続線に沿って自動で配置(全体)`,"status.connecting":`接続中…`,"status.offline":`オフライン(再接続します)`,"status.saving":`保存中…`,"sync.conflict":`他の人が同じ付箋を編集していたため、変更を取り消しました`,"sync.rejected":e=>`変更を保存できなかったため、取り消しました(${e})`,"backlinks.count":e=>`リンク元 ${e}`,"backlinks.title":`このページへリンクしているページ`,"menu.title":`メニュー`,"menu.viewOnly":`参照モード(読むだけ)`,"menu.viewOnlyExit":`参照モードを終える`,"menu.themeCard":`付箋の見た目: カード`,"menu.themeDefault":`付箋の見た目: 標準`,"menu.history":`操作の履歴…`,"menu.exportJson":`JSON を書き出す`,"menu.deletePage":`ページを削除…`,"ops.title":`操作の履歴`,"ops.agentOnly":`agent の操作だけ`,"ops.refresh":`更新`,"ops.empty":`操作はありません`,"ops.revert":`取り消す`,"ops.noSummary":`(説明なし)`,"ops.revertedMark":`(取り消し済み)`,"ops.summary.pageCreated":`ページの作成`,"ops.summary.childRemoved":e=>`子ページ ${e} の削除`,"ops.summary.revert":e=>`#${e} の取り消し`,"ops.summary.revertUnknown":`取り消し`,"ops.summary.notesReceived":e=>`ページ ${e} から付箋を受け取り`,"ops.summary.notesSent":e=>`ページ ${e} へ付箋を移動`,"ops.summary.childRecolored":e=>`子ページ ${e} の色に合わせる`,"revert.done":`取り消しました`,"revert.none":e=>`取り消せる変更がありませんでした${e}`,"revert.partial":(e,t)=>`一部を取り消しました。${e} 件は残しています${t}`,"revert.reasons":e=>`(${e.join(`、`)})`,"skip.modified":`その後に変更された`,"skip.connected":`他の接続線がつながっている`,"skip.deleted":`すでに削除されている`,"skip.exists":`同じものがすでにある`,"skip.endpoint-missing":`両端の付箋がない`,"child.place":`子ページを置く`,"child.newHeading":`新しいページを作って置く`,"child.createAndPlace":`作成して置く`,"child.existingHeading":`既存のページを置く`,"child.rootPage":`ルートのページ`,"child.slugPlaceholder":`ページの名前(スラッグ)`,"child.placeExisting":`置く`,"child.slugTaken":`そのスラッグのページはすでにあります。既存のページとして置けます`,"child.summary":(e,t)=>`子ページ・付箋 ${e} 枚(/p/${t})`,"child.elsewhere":e=>`「${e}」に置かれています`,"child.rejected":(e,t)=>`子ページとして置けませんでした(${e})${t?`。作成したページは、ルートのページとして一覧に残っています`:``}`,"transfer.moved":(e,t)=>`付箋 ${e} 枚を「${t}」へ移動しました`,"transfer.copied":(e,t)=>`付箋 ${e} 枚を「${t}」へコピーしました`,"transfer.partial":e=>`「${e}」へ付箋を置きましたが、一部の付箋はこのページから消せなかったので、両方にあります(移動の途中で変更された付箋は、消さずに残します)`,"transfer.confirmMoveLinked":e=>`線でつながっている付箋 ${e} 枚も一緒に移動しますか?\n「キャンセル」を選ぶと、ドラッグした付箋だけを移動します`,"transfer.confirmCopyLinked":e=>`線でつながっている付箋 ${e} 枚も一緒にコピーしますか?\n「キャンセル」を選ぶと、ドラッグした付箋だけをコピーします`,"child.reject.not-found":`ページが見つかりません`,"child.reject.self":`自分自身は置けません`,"child.reject.other-parent":`すでに別のページの子になっています`,"child.reject.duplicate":`このページにすでに置いてあります`,"child.reject.ancestor":`このページの先祖なので、輪になります`,"child.reject.too-deep":e=>`階層は ${e} 段までです`,"help.unsaved":`このボードは保存されません`},Fr=globalThis.document,V=Fr===void 0?`ja`:Er(Dr(Fr.cookie,wr),navigator.languages??[],Mr.defaultLang),Ir=V===`ja`?Pr:Nr;function H(e,...t){let n=Ir[e];return typeof n==`string`?n:n(...t)}var Lr=V===`ja`?`en`:`ja`;function Rr(e,t){let n;try{n=new URL(e)}catch{return null}return n.origin===t?n.href:null}var zr=new AbortController,U=()=>zr.signal;function W(e){zr.signal.addEventListener(`abort`,e,{once:!0})}var Br;function Vr(e){Br=e}var Hr;function Ur(e){Hr=e}var Wr=e=>/^\/p\/([^/]+)\/?$/.exec(e)?.[1],Gr=()=>!1,Kr=0,qr=()=>Kr;async function Jr(e,t){let n=++Kr;await Br?.(),n===Kr&&(Br=void 0,Hr=void 0,zr.abort(),zr=new AbortController,Gr(e,!1,t)||location.reload())}async function Yr(){await Br?.(),location.reload()}function Xr(e){Gr=e,Gr(location.pathname,!0),window.addEventListener(`popstate`,()=>void Zr(location.pathname))}async function Zr(e){let t=++Kr,n;try{n=await Hr?.(e)}catch{}t===Kr&&await Jr(e,n)}function Qr(e,t){let n=new URL(e,location.href),{pathname:r}=n;n.origin!==location.origin||!(r===`/`||r===`/help`||r.startsWith(`/p/`))?location.assign(n.href):(history.pushState(null,``,n.pathname+n.search+n.hash),Jr(n.pathname,t))}function G(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n.filter(e=>e!=null&&e!==!1)),r}function $r(e,t){let n=ni(e,t);return n!==null&&(Qr(n),!0)}var ei=e=>!(e.ctrlKey||e.metaKey||e.shiftKey||e.button!==0);function ti(e,...t){let n=G(`a`,{href:e},...t);return n.addEventListener(`click`,t=>{ei(t)&&(t.preventDefault(),Qr(e))}),n}function ni(e,t){return ei(t)?Rr(e,location.origin):null}var ri={autocomplete:`off`,"data-1p-ignore":``,"data-lpignore":`true`,"data-bwignore":``,"data-form-type":`other`};function K(e={}){let t=G(`input`,e);for(let[e,n]of Object.entries(ri))t.setAttribute(e,n);return t}function ii(){let e=``;for(;e.length<6;){let t=crypto.getRandomValues(new Uint8Array(1))[0];t>=252||(e+=(t%36).toString(36))}return e}function ai(e){return confirm(H(`page.deleteConfirm`,e))}function oi(e){return e instanceof Error?e.message:String(e)}function q(e,t){return H(e,oi(t))}var si=new Intl.DateTimeFormat(V,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`});function ci(e){return si.format(e)}var li=`(max-width: 640px)`,ui=12,di=`stacked`;function fi(e,t,{onChange:n,first:r=[]}={}){let i=matchMedia(li),a,o=()=>{if(i.matches){t.classList.add(di);let i=t.clientWidth-24;if(i===a||i<=0)return;let o=a===void 0;a=i,e.setPageScroll(!0),e.setStacked({x:ui,y:ui,width:i,order:r}),o&&n?.(!0)}else if(a!==void 0){t.classList.remove(di),e.setStacked(null),e.setPageScroll(!1);try{n?.(!1)}finally{a=void 0}}else t.classList.remove(di)};return{isStacked:()=>a!==void 0,start(){o(),i.addEventListener(`change`,o,{signal:U()});let e=new ResizeObserver(o);e.observe(t),W(()=>e.disconnect())}}}var pi=5e3,mi=[`#FFF9C4`,`#FFCDD2`,`#FFE0B2`,`#E1BEE7`,`#BBDEFB`,`#B2DFDB`,`#C8E6C9`,`#F5F5F5`],J=e=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`,Y=e=>`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">${e}</svg>`,hi=e=>`<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">${e.map(([e,t])=>`<circle cx="${e}" cy="${t}" r="1.5"/>`).join(``)}</svg>`,gi=e=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="${e}"/></svg>`,_i=[3,8,13],vi=`12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2`,yi={undo:J(`<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>`),redo:J(`<polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.13-9.36L23 10"/>`),add:J(`<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>`),layout:hi(_i.flatMap(e=>_i.map(t=>[t,e]))),alignLeft:Y(`<line x1="2" y1="2" x2="2" y2="14"/><rect x="4" y="3" width="10" height="3" rx="0.5"/><rect x="4" y="8" width="6" height="3" rx="0.5"/>`),alignCenter:Y(`<line x1="8" y1="1" x2="8" y2="15"/><rect x="3" y="3" width="10" height="3" rx="0.5"/><rect x="5" y="8" width="6" height="3" rx="0.5"/>`),alignRight:Y(`<line x1="14" y1="2" x2="14" y2="14"/><rect x="2" y="3" width="10" height="3" rx="0.5"/><rect x="6" y="8" width="6" height="3" rx="0.5"/>`),alignTop:Y(`<line x1="2" y1="2" x2="14" y2="2"/><rect x="3" y="4" width="3" height="10" rx="0.5"/><rect x="8" y="4" width="3" height="6" rx="0.5"/>`),alignMiddle:Y(`<line x1="1" y1="8" x2="15" y2="8"/><rect x="3" y="3" width="3" height="10" rx="0.5"/><rect x="8" y="5" width="3" height="6" rx="0.5"/>`),alignBottom:Y(`<line x1="2" y1="14" x2="14" y2="14"/><rect x="3" y="2" width="3" height="10" rx="0.5"/><rect x="8" y="6" width="3" height="6" rx="0.5"/>`),distributeH:Y(`<rect x="1" y="4" width="3" height="8" rx="0.5"/><rect x="6.5" y="4" width="3" height="8" rx="0.5"/><rect x="12" y="4" width="3" height="8" rx="0.5"/>`),distributeV:Y(`<rect x="4" y="1" width="8" height="3" rx="0.5"/><rect x="4" y="6.5" width="8" height="3" rx="0.5"/><rect x="4" y="12" width="8" height="3" rx="0.5"/>`),autoLayout:J(`<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="8.5" y="14" width="7" height="7" rx="1"/><line x1="6.5" y1="10" x2="6.5" y2="14"/><line x1="6.5" y1="14" x2="12" y2="14"/><line x1="17.5" y1="10" x2="17.5" y2="14"/><line x1="17.5" y1="14" x2="12" y2="14"/>`),zoomOut:J(`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/>`),zoomIn:J(`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/>`),zoomFit:J(`<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>`),center:J(`<circle cx="12" cy="12" r="3"/><line x1="12" y1="2" x2="12" y2="6"/><line x1="12" y1="18" x2="12" y2="22"/><line x1="2" y1="12" x2="6" y2="12"/><line x1="18" y1="12" x2="22" y2="12"/>`),childPage:J(`<rect x="3" y="3" width="18" height="18" rx="2"/><rect x="7" y="7" width="6" height="5" rx="1"/><line x1="16" y1="14" x2="16" y2="18"/><line x1="14" y1="16" x2="18" y2="16"/>`),edit:J(`<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>`),trash:J(`<polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>`),star:J(`<polygon points="${vi}"/>`),starFilled:J(`<polygon points="${vi}" fill="currentColor"/>`),bookmarks:J(`<path d="M17 21l-6-4.5L5 21V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"/><path d="M9 1.5h9a2 2 0 0 1 2 2V17"/>`),menu:hi([[3,8],[8,8],[13,8]]),claude:gi(`m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z`),openai:gi(`M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z`),agent:J(`<rect x="4" y="8" width="16" height="12" rx="2"/><line x1="12" y1="4" x2="12" y2="8"/><circle cx="12" cy="3" r="1"/><line x1="9" y1="13" x2="9" y2="15"/><line x1="15" y1="13" x2="15" y2="15"/>`)};function bi(e){return G(`span`,{className:`icon`,innerHTML:yi[e]})}function xi(e,t,n){return G(`header`,{className:`page-header`},G(`div`,{className:`zone zone-left`},...e),G(`div`,{className:`zone zone-tools`},...t),G(`div`,{className:`zone zone-right`},...n))}function X(e,t,n){let r=G(`button`,{type:`button`,className:`icon-button`,title:t,ariaLabel:t},bi(e));return n&&r.addEventListener(`click`,n),r}var Si=()=>G(`span`,{className:`separator`});function Ci(e,t,n){document.addEventListener(`pointerdown`,r=>{!e.hidden&&!t.contains(r.target)&&n()},{capture:!0,signal:U()})}function wi(e,t,n={}){t.classList.add(`popover-panel`,`popover-${n.align??`left`}`),t.hidden=!0;let r=G(`span`,{className:`popover`},e,t),i=()=>{t.hidden=!0,e.ariaExpanded=`false`};return e.ariaExpanded=`false`,e.addEventListener(`click`,()=>{if(!t.hidden)return i();n.instead?.()||(t.hidden=!1,e.ariaExpanded=`true`,n.onOpen?.())}),Ci(t,r,i),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&!t.hidden&&i()},{signal:U()}),{root:r,close:i}}function Ti(e,...t){let n=G(`dialog`,{className:`modal ${e}`},...t,G(`form`,{method:`dialog`,className:`modal-foot`},G(`button`,{textContent:H(`close`)})));return n.addEventListener(`click`,e=>{if(e.target!==n)return;let t=n.getBoundingClientRect();e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom||n.close()}),n}var Ei={"#FFF9C4":`colorButter`,"#FFCDD2":`colorRose`,"#FFE0B2":`colorPeach`,"#E1BEE7":`colorLavender`,"#BBDEFB":`colorSky`,"#B2DFDB":`colorMint`,"#C8E6C9":`colorSage`,"#F5F5F5":`colorGray`};function Di(e){let t=V===`ja`?r:n,i=G(`button`,{type:`button`,className:`color-button`,title:H(`page.color`),ariaLabel:H(`page.color`)}),a=G(`div`,{className:`color-panel`}),o=wi(i,a),s=new Map,c=(t,n)=>{let r=G(`button`,{type:`button`,className:`color-swatch`,title:n,ariaLabel:n});t!==null&&(r.style.backgroundColor=t),r.addEventListener(`click`,()=>{e(t),o.close()}),s.set(t,r),a.append(r)};for(let e of mi)c(e,t[Ei[e]]);return c(null,H(`page.colorNone`)),{root:o.root,show(e){i.style.backgroundColor=e??``;for(let[t,n]of s)n.classList.toggle(`active`,t===e)}}}function Oi(e,t,n=``){let r=G(`button`,{type:`button`,className:`menu-item ${n}`.trim(),textContent:e});return r.addEventListener(`click`,t),r}var ki=V===`ja`?r:void 0,Ai=31536e3;function ji(){document.cookie=`${wr}=${Lr}; Path=/; Max-Age=${Ai}; SameSite=Lax`,Yr()}function Mi(){let e=G(`button`,{type:`button`,className:`text-button`,textContent:H(`lang.switch`)});return e.addEventListener(`click`,ji),e}function Ni(e){return{undo:X(`undo`,H(`undo`),()=>e.undo()),redo:X(`redo`,H(`redo`),()=>e.redo())}}var Pi=1.25;function Fi(e,t){let n=[...t.querySelectorAll(`.wema-note`)].filter(e=>e.offsetParent!==null).map(e=>e.getBoundingClientRect());if(n.length===0)return;let r=(e,t)=>(Math.min(...e)+Math.max(...t))/2,i=t.getBoundingClientRect(),{x:a,y:o}=e.getViewport();e.setViewport({x:a+(i.left+i.right)/2-r(n.map(e=>e.left),n.map(e=>e.right)),y:o+(i.top+i.bottom)/2-r(n.map(e=>e.top),n.map(e=>e.bottom))})}function Ii(e,t){let n=G(`button`,{type:`button`,className:`zoom-level`,title:H(`zoom.reset`)});n.addEventListener(`click`,()=>e.zoomTo(1));let r=``,i=e=>{let t=`${Math.round(e*100)}%`;t!==r&&(r=t,n.textContent=t)};return e.on(`viewport:change`,({zoom:e})=>i(e)),i(e.getViewport().zoom),G(`span`,{className:`tool-group`},X(`zoomOut`,H(`zoom.out`),()=>e.zoomTo(e.getViewport().zoom/Pi)),n,X(`zoomIn`,H(`zoom.in`),()=>e.zoomTo(e.getViewport().zoom*Pi)),X(`zoomFit`,H(`zoom.fit`),()=>e.fitToContent()),X(`center`,H(`zoom.center`),()=>Fi(e,t)))}function Li(e,t){let n=G(`div`,{className:`toast`,hidden:!0,role:`status`});e.append(n);let r;return e=>{n.textContent=e,n.hidden=!1,clearTimeout(r),r=setTimeout(()=>{n.hidden=!0},t)}}var Ri={get(e){try{return localStorage.getItem(`wema-kake:${e}`)}catch{return null}},set(e,t){try{localStorage.setItem(`wema-kake:${e}`,t)}catch{}}};function zi(e){document.title=H(`documentTitle`,H(`help`),Mr.siteName);let t=G(`div`,{className:`board`});e.append(G(`div`,{className:`page-body`},t));let n=new pr({container:t,data:{version:1,...Sr(`help`,V)},onLinkClick:$r,noteLinks:!0,labels:ki,emptyDrag:`pan`});W(()=>n.destroy()),fi(n,t,{first:[xr]}).start();let{undo:r,redo:i}=Ni(n),a=()=>{r.disabled=!n.canUndo(),i.disabled=!n.canRedo()};n.on(`history:change`,a),a();let o=Ii(n,t);o.classList.add(`optional`),e.prepend(xi([ti(`/`,H(`list`)),G(`h1`,{textContent:H(`help`)})],[r,i,Si(),o],[G(`span`,{className:`help-note`,textContent:H(`help.unsaved`)}),Mi()]))}var Z=class extends Error{status;constructor(e,t){super(e),this.status=t}};async function Q(e,t,n){let r=await fetch(t,{method:e,headers:n===void 0?void 0:{"Content-Type":`application/json`},body:n===void 0?void 0:JSON.stringify(n)}),i=await r.json().catch(()=>null);if(!r.ok||i===null)throw new Z(i?.error??`${e} ${t}: ${r.status}`,r.status);return i}var Bi=()=>Q(`GET`,`/api/index`);async function Vi(e){let{pages:t}=await Q(`GET`,`/api/search?roots=1&q=${encodeURIComponent(e)}`);return t}async function Hi(e){return e.length===0?[]:(await Q(`POST`,`/api/pages-info`,{names:e})).pages}var Ui=e=>Q(`GET`,`/api/pages/${e}/ancestors`),Wi=(e,t)=>Q(`POST`,`/api/pages/${e}`,{title:t});async function Gi(){return(await Q(`GET`,`/api/bookmarks`)).pages}var Ki=(e,t)=>Q(t?`PUT`:`DELETE`,`/api/bookmarks/${e}`);async function qi(e,t=``){return(await Q(`GET`,`/api/pages?${new URLSearchParams({limit:String(e),...t===``?{}:{name:t}})}`)).pages}var Ji=e=>Q(`GET`,`/api/pages/${e}/backlinks`),Yi=(e,t,n=!1)=>Q(`PUT`,`/api/pages/${e}/title`,{title:t,mustExist:n}),Xi=(e,t)=>Q(`PUT`,`/api/pages/${e}/color`,{color:t}),Zi=e=>Q(`DELETE`,`/api/pages/${e}`),Qi=(e,t)=>Q(`GET`,`/api/pages/${e}/ops${t?`?agent=1`:``}`),$i=(e,t,n)=>Q(`POST`,`/api/pages/${e}/ops/${t}/revert`,{clientId:n,opId:crypto.randomUUID()}),ea=(e,t)=>Q(`POST`,`/api/pages/${e}/transfer`,t);async function ta(e){let t=await fetch(`/api/images`,{method:`POST`,headers:{"Content-Type":e.type},body:e});if(!t.ok)throw Error(`image upload failed: ${t.status}`);return(await t.json()).url}async function na(){try{let e=await fetch(`/api/session`,{redirect:`manual`});return e.status!==401&&e.type!==`opaqueredirect`}catch{return!0}}var ra=e=>e.replace(/[A-Z]+/g,e=>e.toLowerCase()),ia=(e,t)=>ra(e.name).includes(t)||ra(e.title??``).includes(t);function aa(e,t,n=``){let r=ra(n.trim()),i=new Set(e.map(e=>e.name)),a=t.filter(e=>!i.has(e.name));return{pinned:r===``?e:e.filter(e=>ia(e,r)),rest:r===``?a.slice(0,5):a}}function oa(e,t){return e.map(e=>ti(`/p/${e.name}`,G(`span`,{className:`link-title`,textContent:e.title??e.name}),t&&G(`span`,{className:`link-detail`,textContent:t(e)})))}var sa=30,ca=200;function la(e,t){return ti(`/p/${e.name}`,t&&G(`span`,{className:`link-star`,title:H(`nav.bookmarked`)},bi(`starFilled`)),G(`span`,{className:`link-title`,textContent:e.title??e.name}),e.updated_at!==null&&G(`span`,{className:`link-detail`,textContent:ci(e.updated_at)}))}function ua(){let e=U(),t=K({type:`search`,className:`nav-filter`,placeholder:H(`nav.filter`),ariaLabel:H(`nav.filter`),maxLength:200}),n=G(`div`,{className:`link-list`}),r=G(`div`,{className:`page-nav`},t,n),i,a=0,o=!1,s,c=e=>n.replaceChildren(G(`span`,{className:`empty`,textContent:e})),l=async()=>{let r=++a,s=t.value.trim(),l=i??=Gi();l.catch(()=>{i===l&&(i=void 0)});try{let[t,i]=await Promise.all([l,s===``?qi(105):qi(sa,s)]);if(e.aborted||r!==a)return;let{pinned:u,rest:d}=aa(t,i,s);u.length+d.length===0?c(H(s===``?`nav.empty`:`nav.noMatch`)):(n.replaceChildren(),n.append(...u.map(e=>la(e,!0)),...u.length>0&&d.length>0?[G(`hr`)]:[],...d.map(e=>la(e,!1))),s!==``&&i.length>=sa&&n.append(G(`span`,{className:`empty`,textContent:H(`nav.more`)}))),o=!0}catch(t){!e.aborted&&r===a&&c(H(`links.loadFailed`,oi(t)))}};return t.addEventListener(`input`,()=>{o=!1,a++,clearTimeout(s),s=setTimeout(()=>void l(),ca)}),t.addEventListener(`keydown`,e=>{e.key!==`Enter`||e.isComposing||(e.preventDefault(),o&&n.querySelector(`a`)?.click())}),e.addEventListener(`abort`,()=>clearTimeout(s)),wi(X(`bookmarks`,H(`nav.title`)),r,{align:`right`,onOpen(){clearTimeout(s),t.value=``,o=!1,i=void 0,n.childElementCount===0&&c(H(`loading`)),l(),matchMedia(`(pointer: coarse)`).matches||t.focus()}}).root}function da(e,t){let n=U(),r=!1,i=X(`star`,``,()=>{let o=!r;i.disabled=!0,Ki(e,o).then(()=>{n.aborted||a(o)}).catch(e=>{n.aborted||t(e instanceof Z&&e.status===404?Error(H(`bookmark.unwritten`)):e)}).finally(()=>{i.disabled=!1})}),a=e=>{r=e,i.replaceChildren(bi(r?`starFilled`:`star`)),i.title=H(r?`bookmark.remove`:`bookmark.add`),i.ariaLabel=i.title,i.ariaPressed=String(r)};return a(!1),i.disabled=!0,Gi().then(t=>{n.aborted||(a(t.some(t=>t.name===e)),i.disabled=!1)}).catch(()=>{}),i}var fa=120,pa=4,ma=200;function ha(e,t){let n=X(`edit`,H(`page.rename`)),r=X(`trash`,H(`page.delete`)),i=G(`div`,{className:`note-actions`,hidden:!0},n,r),a=K({maxLength:200,ariaLabel:H(`title`)}),o=G(`form`,{className:`note-rename`,hidden:!0},a,G(`button`,{type:`submit`,textContent:H(`save`)}));e.append(i,o);let s,c=t=>{let n=e.querySelector(`.wema-note[data-note-id="${CSS.escape(t)}"]`);if(!n)return;let r=n.getBoundingClientRect(),i=e.getBoundingClientRect();return{left:r.left-i.left,top:r.top-i.top,right:r.right-i.left,width:r.width}},l=()=>{s=void 0,i.hidden=!0,o.hidden=!0},u=(t,n,r)=>{let i=(e,t)=>Math.max(pa,Math.min(e,t-pa));t.style.left=`${i(n,e.clientWidth-t.offsetWidth)}px`,t.style.top=`${i(r,e.clientHeight-t.offsetHeight)}px`},d=e=>{if(e===s)return;let n=c(e);if(!n||n.width<fa||t.titleOf(e)===void 0)return l();s=e,i.hidden=!1,u(i,n.right-i.offsetWidth-pa,n.top+pa)};e.addEventListener(`pointerover`,e=>{if(!o.hidden)return;let t=e.target;if(i.contains(t))return;let n=t.closest(`.wema-note`)?.dataset.noteId;n===void 0?l():d(n)}),e.addEventListener(`pointerleave`,()=>{o.hidden&&l()});for(let e of[i,o])for(let t of[`pointerdown`,`dblclick`,`wheel`])e.addEventListener(t,e=>e.stopPropagation());return n.addEventListener(`click`,()=>{if(s===void 0)return;let e=c(s);if(!e)return l();i.hidden=!0,o.hidden=!1,o.style.width=`${Math.max(e.width-8,ma)}px`,u(o,e.left+pa,e.top+pa),a.value=t.titleOf(s)??``,a.placeholder=s,a.focus(),a.select()}),o.addEventListener(`submit`,e=>{e.preventDefault();let n=s,r=a.value.trim();l(),n!==void 0&&r!==(t.titleOf(n)??``)&&t.rename(n,r)}),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&!e.isComposing&&l()}),Ci(o,o,l),r.addEventListener(`click`,()=>{let e=s;l(),e!==void 0&&t.remove(e)}),l}var ga=220,_a=160,va=40,ya=40,ba=`#E0E0E0`;function xa(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}var Sa={fromAnchor:`auto`,toAnchor:`auto`,style:`arrow`,strokeWidth:1,arrowSize:8},Ca=`font-size: 11px; color: #666`;function wa(e,t){let n=xa(e.title??e.name),r=H(`index.meta`,t(e.updated_at),e.note_count,e.child_count);return`<a href="/p/${e.name}"><b>${n}</b></a><div>${xa(e.excerpt)}</div><div><span style="${Ca}">${xa(r)}</span></div>`}function Ta(e){return e===0?``:`<div><span style="font-size: 11px; color: #1d4ed8"><b>${xa(H(`index.descendantHits`,e))}</b></span></div>`}function Ea(e){return`<a href="/p/${e}">${e}</a><div><span style="${Ca}">${xa(H(`index.missing`))}</span></div>`}var Da=260,Oa=200,ka=60,Aa=80;function ja(e,t,n){let r=new Set(e),i=new Map,a=new Set;for(let{from:e,to:n}of t){if(!r.has(e))continue;let t=i.get(e);t?t.push(n):i.set(e,[n]),a.add(n)}let o=new Map,s=e=>{let t=e.filter(e=>!o.has(e));for(let e=0;t.length>0;e++){for(let n of t)o.set(n,e);t=[...new Set(t.flatMap(e=>i.get(e)??[]))].filter(e=>!o.has(e))}};s(e.filter(e=>!a.has(e)));for(let t of e)s([t]);let c=[];for(let t of e)(c[o.get(t)]??=[]).push(t);let l=Math.max(...c.map(e=>e.length)),u=Math.min(n,Math.max(2,Math.ceil(Math.sqrt(l*2)))),d=Math.min(u,l)*Da-va,f=new Map,p=0;for(let e of c){for(let t=0;t<e.length;t+=u){let n=e.slice(t,t+u),r=(d-(n.length*Da-va))/2;n.forEach((e,t)=>f.set(e,{x:r+t*Da,y:p})),p+=Oa}p+=ka}return{width:d,height:p-va-ka,positions:f}}function Ma(e,t){let n=new Map(e.map(e=>[e,e])),r=e=>{let t=e;for(;n.get(t)!==t;)t=n.get(t);return n.set(e,t),t};for(let{from:e,to:i}of t)n.set(r(e),r(i));let i=new Map;for(let t of e){let e=r(t),n=i.get(e);n?n.push(t):i.set(e,[t])}return[...i.values()]}function Na(e,t,n,r){let i=new Map,a=new Map,o=(e,t,n,r)=>{i.set(e,{id:e,x:0,y:0,width:ga,height:_a,text:t,color:n,zIndex:1}),a.set(e,r.toLowerCase())};for(let t of e)o(t.name,wa(t,r),t.color??`#FFF9C4`,`${t.title??``}\n${t.name}`);let s=[],c=new Set;for(let{from_page:e,to_page:n,missing:r}of t)if(e!==n&&i.has(e)){if(!i.has(n)){if(!r)continue;o(n,Ea(n),ba,n)}s.push({id:`${e}>${n}`,from:e,to:n,...Sa}),c.add(e).add(n)}let l=Math.max(1,Math.floor((n.width-80+va)/Da)),u=n.width/Math.max(1,n.height),d=Math.ceil(i.size/l)*Oa+ya<=n.height?l:Math.max(l,Math.ceil(Math.sqrt(i.size*u*Oa/Da))),f=d*Da-va,p=(e,t,n)=>{let r=i.get(e);r.x=ya+t,r.y=ya+n},m=0,h=0,g=0,_=[...i.keys()].filter(e=>c.has(e));for(let e of Ma(_,s)){let t=ja(e,s,d);m>0&&m+t.width>f&&(m=0,h+=g+Aa,g=0);for(let[e,n]of t.positions)p(e,m+n.x,h+n.y);m+=t.width+va,g=Math.max(g,t.height)}g>0&&(h+=g+Aa);let v=0;for(let e of i.keys())c.has(e)||(p(e,v%d*Da,h+Math.floor(v/d)*Oa),v++);for(let e of s){let t=i.get(e.to).y-i.get(e.from).y;t!==0&&(e.fromAnchor=t>0?`bottom`:`top`,e.toAnchor=t>0?`top`:`bottom`)}let y=new Map([...i.values()].map(e=>[e.id,e.text]));return{data:{version:1,notes:[...i.values()],edges:s},searchText:a,texts:y}}function Pa(){let e=K({placeholder:H(`form.optional`),maxLength:200}),t=K({value:ii(),title:H(`form.slugHint`)});return{title:e,slug:t,labels:[G(`label`,{},H(`title`),e),G(`label`,{},`URL`,G(`span`,{className:`slug-field`},`/p/`,t))],reset(){e.value=``,t.value=ii(),e.focus()}}}function Fa(e,n){let r=e.value.trim();if(t(r))return r;n.textContent=H(`form.slugInvalid`)}var Ia=220,La=32,Ra=.5,za=.5,Ba=()=>matchMedia(`(prefers-reduced-motion: reduce)`).matches,Va=e=>e<.5?2*e*e:1-(-2*e+2)**2/2;function Ha(e,t,n){if(Ba())return e.setViewport(t),Promise.resolve();let r=e.getViewport(),i=U(),a=performance.now();return new Promise(o=>{let s=c=>{if(i.aborted||n())return o();let l=Math.min(1,(c-a)/Ia),u=Va(l);e.setViewport({x:r.x+(t.x-r.x)*u,y:r.y+(t.y-r.y)*u,zoom:r.zoom*(t.zoom/r.zoom)**u}),l<1?requestAnimationFrame(s):o()};requestAnimationFrame(s)})}function Ua(e,t){let n=e.getViewport();t();let r=e.getViewport();return e.setViewport(n),r}var Wa=(e,t)=>Ua(e,()=>e.fitToContent({noteIds:[t.id],padding:La,maxZoom:1/0})),Ga=(e,t)=>Ua(e,()=>e.zoomTo(e.getViewport().zoom*t));function Ka(e,t,n){let r=!1,i=0,a=t=>{let n=++i;return Ha(e,t,()=>n!==i)},o=async(e,i)=>{if(r)return;r=!0,t?.();let o=n?.()?void 0:e();return o&&await a(o),i},s=async(e,t,n)=>{let r=U(),i=qr(),a=await o(e,n);a&&!r.aborted&&i===qr()&&Qr(t,a)},c=t=>()=>{let n=e.getNote(t);return n&&Wa(e,n)},l=()=>Ga(e,za);return{enter(e,t){return s(c(e),t,{kind:`enter`})},leave(e,t){return s(l,e,{kind:`leave`,from:t})},enterOnPop(e){return o(c(e),{kind:`enter`})},leaveOnPop(e){return o(l,{kind:`leave`,from:e})},async arrive(t,r){if(n?.())return;let i=e.getViewport();if(t?.kind===`enter`)e.zoomTo(i.zoom*Ra);else if(t?.kind===`leave`){let n=r(t.from);if(!n)return;e.fitToContent({noteIds:[n.id],padding:La,maxZoom:1/0})}else return;await a(i)}}}var qa=200,Ja=8e3;function Ya(){let e=Pa(),t=G(`div`,{className:`form-error`}),n=G(`form`,{className:`new-page`},...e.labels,G(`button`,{type:`submit`,textContent:H(`form.create`)}),t),r=async()=>{let n=Fa(e.slug,t);if(n!==void 0){try{await Wi(n,e.title.value)}catch(e){e instanceof Z&&e.status===409?t.replaceChildren(H(`form.slugTaken`),ti(`/p/${n}`,H(`form.openIt`))):t.textContent=q(`failed.create`,e);return}Qr(`/p/${n}`)}};return n.addEventListener(`submit`,e=>{e.preventDefault(),r()}),n}var Xa=.05;function Za(e){let t,n=n=>{if(n!==t){t=n,e.classList.toggle(`index-focus`,n!==void 0);for(let t of e.querySelectorAll(`.wema-edge-group`)){let[e,r]=(t.dataset.edgeId??``).split(`>`);t.classList.toggle(`index-linked`,n!==void 0&&(e===n||r===n))}}};e.addEventListener(`pointerover`,e=>{n(e.target.closest(`.wema-note`)?.dataset.noteId)}),e.addEventListener(`pointerleave`,()=>n(void 0))}var Qa;function $a(e,t){document.title=Mr.siteName;let n=U(),r=K({type:`search`,className:`index-search`,placeholder:H(`index.filter`),maxLength:200,value:new URLSearchParams(location.search).get(`q`)??``}),i=G(`span`,{className:`index-count`}),a=G(`span`,{className:`tool-group optional`}),o=Ya(),s=wi(G(`button`,{type:`button`,className:`text-button primary`,textContent:H(`index.newPage`)}),o,{align:`right`,onOpen:()=>o.querySelector(`input`)?.focus()}),c=G(`div`,{className:`index-canvas`}),l=G(`div`,{className:`index-board`});e.append(xi([G(`h1`,{textContent:Mr.siteName})],[r,i,a],[ua(),Mi(),s.root]),c);let u,d,f=0,p=location.search,m,h=null,g=new Set,_=(e=``)=>{if(!u||!d)return;let t=d.data.notes.length,n=new Map([...h??[]].filter(([,e])=>e>0));for(let e of new Set([...g,...n.keys()])){let t=d.texts.get(e);t!==void 0&&u.updateNote(e,{text:t+Ta(n.get(e)??0)})}g=new Set(n.keys()),u.setNoteFilter(h&&[...h.keys()]),i.textContent=h?H(`index.matched`,h.size,t,e):H(`index.count`,t)},v=async()=>{if(!u||!d)return;let e=r.value.trim();if(e===m)return;m=e,history.replaceState(null,``,e?`/?q=${encodeURIComponent(e)}`:`/`),p=location.search;let t=++f;if(e===``){h=null,_(),u.setViewport({x:0,y:0,zoom:1});return}let n=()=>{_(),u?.fitToContent()},i=e.toLowerCase(),a=new Map([...d.searchText].filter(([,e])=>e.includes(i)).map(([e])=>[e,0]));h=a,n();try{let r=await Vi(e);if(t!==f)return;let i=a.size;for(let{name:e,root:t}of r)d.searchText.has(t)&&a.set(t,(a.get(t)??0)+(e===t?0:1));a.size===i?_():n()}catch(e){t===f&&_(H(`index.searchFailed`,oi(e)))}},y;r.addEventListener(`input`,()=>{clearTimeout(y),y=setTimeout(()=>void v(),qa)});let b=[],x=[],S=()=>Na(b,x,{width:c.clientWidth,height:c.clientHeight},ci),C=Li(c,Ja),w=()=>{if(u){if(b.length===0)return location.reload();D(),d=S(),u.importData(d.data),g=new Set;for(let e of[...h?.keys()??[]])d.searchText.has(e)||h?.delete(e);_()}},T=e=>{b=b.filter(t=>t.name!==e),h?.has(e)&&h.set(e,0),x=x.filter(t=>t.from_page!==e).map(t=>t.to_page===e?{...t,missing:1}:t),w()},E=new Set,D=ha(c,{titleOf:e=>E.has(e)?void 0:b.find(t=>t.name===e)?.title,rename(e,t){Yi(e,t,!0).then(t=>{b=b.map(n=>n.name===e?{...n,title:t.title}:n),w()}).catch(t=>{t instanceof Z&&t.status===404?(C(H(`page.alreadyDeleted`)),T(e)):C(q(`failed.rename`,t))})},remove(e){let t=b.find(t=>t.name===e);t&&ai(t.title??e)&&(E.add(e),Zi(e).then(()=>T(e)).catch(e=>C(q(`failed.delete`,e))).finally(()=>E.delete(e)))}});Bi().then(e=>{if(n.aborted)return;if({pages:b,links:x}=e,b.length===0){c.append(G(`p`,{className:`empty`,textContent:H(`index.empty`)}));return}c.append(l),d=S(),u=new pr({container:l,data:d.data,viewOnly:!0,labels:ki,minZoom:Xa,onLinkClick(e,t){let n=ni(e,t);if(n===null)return!1;let r=t.target.closest(`.wema-note`)?.dataset.noteId;return r===void 0?Qr(n):f.enter(r,n),!0}});let r=u,i=!1,o=()=>{i||(i=!0,Qa=s.isStacked()?{search:p,scrollTop:l.scrollTop}:{search:p,viewport:r.getViewport()})},s=fi(u,l,{onChange(e){D(),!e&&h&&r.fitToContent()}});s.start();let f=Ka(u,o,s.isStacked);Ur(e=>{let t=Wr(e);if(t!==void 0&&r.getNote(t)&&h?.has(t)!==!1)return f.enterOnPop(t)}),W(()=>{o(),clearTimeout(y),u=void 0,r.destroy()}),a.append(Si(),Ii(u,c)),Za(c),u.on(`viewport:change`,D),l.addEventListener(`scroll`,D,{signal:n});let m=Qa?.search===location.search?Qa:void 0;v().then(()=>{if(!n.aborted)return s.isStacked()?m?.scrollTop!==void 0&&(l.scrollTop=m.scrollTop):m?.viewport&&r.setViewport(m.viewport),f.arrive(t,e=>r.getNote(e))})}).catch(e=>{c.replaceChildren(G(`p`,{className:`empty`,textContent:H(`index.loadFailed`,oi(e))}))})}var eo=`page`,to={width:240,height:180},no=`child page: `;function ro(e){if(!e.startsWith(no))return;let[t,n]=e.slice(12).split(`: `);return{code:t,page:n??``}}function $(e){return e.meta?.[eo]}var io=`system:`;function ao(e){if(!e.startsWith(io))return null;let[t,...n]=e.slice(7).split(`:`),r=n.join(`:`);return t===`page-created`&&r===``?{kind:`pageCreated`}:t===`child-removed`&&r!==``?{kind:`childRemoved`,page:r}:t===`revert`&&/^\d+$/.test(r)?{kind:`revert`,seq:Number(r)}:t===`notes-received`&&r!==``?{kind:`notesReceived`,page:r}:t===`notes-sent`&&r!==``?{kind:`notesSent`,page:r}:t===`child-recolored`&&r!==``?{kind:`childRecolored`,page:r}:null}var oo=`ping`,so=`http://www.w3.org/2000/svg`,co=40,lo=300,uo=pi+2e3;function fo(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function po(e){let t=document.createElementNS(so,`svg`);if(t.setAttribute(`class`,`child-layout`),e.length===0)return t;let n=Math.min(...e.map(([e])=>e))-co,r=Math.min(...e.map(([,e])=>e))-co,i=Math.max(...e.map(([e,,t])=>e+t))+co,a=Math.max(...e.map(([,e,,t])=>e+t))+co;t.setAttribute(`viewBox`,`${n} ${r} ${i-n} ${a-r}`);for(let[n,r,i,a,o]of e){let e=document.createElementNS(so,`rect`);e.setAttribute(`x`,String(n)),e.setAttribute(`y`,String(r)),e.setAttribute(`width`,String(i)),e.setAttribute(`height`,String(a)),e.setAttribute(`fill`,o),t.append(e)}return t}var mo=class{slug;open;pages=new Map;board;refreshTimer;ahead=new Set;indexedTimer;constructor(e,t){this.slug=e,this.open=t}render=(e,t)=>{let n=$(e);if(n===void 0)return!1;this.pages.has(n)||this.scheduleRefresh();let r=this.pages.get(n),i=G(`a`,{className:`child-title`,href:`/p/${n}`,textContent:r?.title??n});return i.addEventListener(`click`,t=>{t.stopPropagation(),ei(t)&&(t.preventDefault(),this.open(n,e.id))}),t.classList.add(`child-note`),t.append(i,G(`div`,{className:`child-meta`,textContent:this.describe(n,r)})),r&&t.append(po(fo(r.layout))),!0};describe(e,t){return t===void 0?H(`loading`):t===null?H(`notFound`):t.parent!==null&&t.parent!==this.slug?H(`child.elsewhere`,t.parent):H(`child.summary`,t.note_count,e)}attach(e){this.board=e,window.addEventListener(`focus`,()=>this.scheduleRefresh(),{signal:U()}),W(()=>{clearTimeout(this.refreshTimer),clearTimeout(this.indexedTimer),this.board=void 0})}titleOf(e){return this.pages.get(e)?.title??e}contentChanged(e){this.pages.set(e.name,e),this.ahead.add(e.name);let t=this.board?.getNotes().find(t=>$(t)===e.name);t&&this.board?.refreshNote(t.id),clearTimeout(this.indexedTimer),this.indexedTimer=setTimeout(()=>{this.ahead.clear(),this.refresh()},uo)}scheduleRefresh(){clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(()=>void this.refresh(),lo)}async refresh(){let e=this.board;if(!e)return;let t=new Map;for(let n of e.getNotes()){let e=$(n);e!==void 0&&t.set(e,n.id)}if(t.size===0)return;let n;try{n=await Hi([...t.keys()])}catch{return}if(this.board!==e)return;let r=new Map(n.map(e=>[e.name,e])),i=[];for(let[e,n]of t)this.ahead.has(e)||(this.pages.set(e,r.get(e)??null),i.push(n));for(let t of i)e.refreshNote(t)}},ho={"not-found":H(`child.reject.not-found`),self:H(`child.reject.self`),"other-parent":H(`child.reject.other-parent`),duplicate:H(`child.reject.duplicate`),ancestor:H(`child.reject.ancestor`),"too-deep":H(`child.reject.too-deep`,5)};function go(e,t){let n=new Set,r=Pa(),i=G(`div`,{className:`form-error`}),a=G(`button`,{type:`submit`,textContent:H(`child.createAndPlace`)}),o=G(`form`,{className:`new-page`},G(`strong`,{textContent:H(`child.newHeading`)}),...r.labels,a),s=G(`datalist`,{id:`child-page-roots`}),c=K({placeholder:H(`child.slugPlaceholder`)});c.setAttribute(`list`,s.id);let l=G(`form`,{className:`new-page`},G(`strong`,{textContent:H(`child.existingHeading`)}),G(`label`,{},H(`child.rootPage`),c),s,G(`button`,{type:`submit`,textContent:H(`child.placeExisting`)}));return o.addEventListener(`submit`,e=>{e.preventDefault();let o=Fa(r.slug,i);o!==void 0&&(a.disabled=!0,Wi(o,r.title.value).then(()=>{n.add(o),t(o)}).catch(e=>{i.textContent=e instanceof Z&&e.status===409?H(`child.slugTaken`):q(`failed.create`,e)}).finally(()=>{a.disabled=!1}))}),l.addEventListener(`submit`,e=>{e.preventDefault();let n=Fa(c,i);n!==void 0&&t(n)}),{root:G(`div`,{className:`child-form`},o,l,i),opened(){i.textContent=``,c.value=``,r.reset(),Bi().then(({pages:t})=>{s.replaceChildren(...t.filter(t=>t.name!==e).map(e=>G(`option`,{value:e.name,label:e.title??e.name})))}).catch(()=>{})},rejectionMessage(e){let t=ro(e);return t?H(`child.rejected`,ho[t.code]??e,n.has(t.page)):void 0}}}var _o=e=>e?.startsWith(`agent:`)??!1;function vo(e,t,n,r){let i=new Set;for(let a of r)a.type===`note:create`?(e.set(a.note.id,{createdBy:t,updatedAt:n}),i.add(a.note.id)):a.type===`note:delete`?e.delete(a.note.id)&&i.add(a.note.id):a.type===`note:update`&&(e.set(a.noteId,{createdBy:e.get(a.noteId)?.createdBy??null,updatedAt:n}),i.add(a.noteId));return i}function yo(e){let t=e.slice(e.indexOf(`:`)+1);return e.startsWith(`user:`)&&t.split(`@`)[0]||t}function bo(e){return e.startsWith(`claude`)?`claude`:e.startsWith(`chatgpt`)||e.startsWith(`openai`)?`openai`:`agent`}var xo=class{board;lookup=()=>void 0;render=(e,t)=>{let n=this.lookup(e.id);if(!n)return!1;let{createdBy:r}=n,i=ci(n.updatedAt);if(t.append(G(`span`,{className:`note-author`,textContent:r===null?i:H(`author.detail`,yo(r),i),title:r??``})),r!==null&&_o(r)){let e=yo(r),n=bi(bo(e));n.classList.add(`note-agent`,`note-agent-${bo(e)}`),n.role=`img`,n.title=n.ariaLabel=H(`author.agentTitle`,e),t.append(n)}return!0};attach(e,t){this.board=e,this.lookup=t,W(()=>{this.board=void 0})}refresh=e=>{for(let t of e)this.board?.refreshNoteAccessory(t)}};function So(e,t,n=()=>!0){let r=new Map,i=(e,t)=>{let n=r.get(e);n?n.push(t):r.set(e,[t])};for(let e of t)i(e.from,e.to),i(e.to,e.from);let a=new Set(e),o=new Set,s=[...a];for(let e=s.pop();e!==void 0;e=s.pop())for(let t of r.get(e)??[])a.has(t)||o.has(t)||!n(t)||(o.add(t),s.push(t));return[...o]}var Co=new Set([`x`,`y`,`zIndex`]),wo=`drop-target`,To=`note-leaving`;function Eo(e,t,n){let r=U(),i=new Set,a,o,s,c=t=>{let n=e.getNote(t);return n!==void 0&&$(n)!==void 0},l=new Set,u=t=>e.getNote(t)!==void 0&&!c(t)&&!l.has(t),d=(e,n,r)=>{let i=document.elementsFromPoint(e,n).find(e=>e instanceof HTMLElement&&e.matches(`.wema-note`)&&t.contains(e)&&!r.has(e.dataset.noteId??``));return i&&c(i.dataset.noteId??``)?i:void 0},f=e=>t.querySelector(`.wema-note[data-note-id="${CSS.escape(e)}"]`),p=e=>{e!==s&&(s?.classList.remove(wo),e?.classList.add(wo),s=e)},m={capture:!0,signal:r};window.addEventListener(`pointerdown`,n=>{if(!n.isPrimary)return;let r=n.target instanceof Element?n.target.closest(`.wema-note`):null,i=n.button===0&&r&&t.contains(r)?e.getNote(r.dataset.noteId??``):void 0;a=i&&{id:i.id,x:i.x,y:i.y}},m),window.addEventListener(`pointermove`,t=>{if(!a)return;let n=e.getNote(a.id);if(!n||n.x===a.x&&n.y===a.y||e.isViewOnly())return p(void 0);let r=e.getSelection(),i=new Set(r.includes(a.id)?r:[a.id]);p([...i].every(c)?void 0:d(t.clientX,t.clientY,i))},m);let h=e=>{e.isPrimary&&(p(void 0),a&&e.type===`pointerup`&&(o={x:e.clientX,y:e.clientY,copy:e.ctrlKey||e.metaKey},setTimeout(()=>o=void 0)),a=void 0)};window.addEventListener(`pointerup`,h,m),window.addEventListener(`pointercancel`,h,m),e.on(`history:commit`,({deltas:t,origin:n})=>{let r=o;if(o=void 0,!r||n!==`user`||e.isViewOnly())return;let a=new Map;for(let e of t){if(e.type!==`note:update`||!Object.keys(e.after).every(e=>Co.has(e)))return;let{zIndex:t,...n}=e.before;a.set(e.noteId,{...n,...a.get(e.noteId)})}let s=e.getNote(d(r.x,r.y,new Set(a.keys()))?.dataset.noteId??``),c=s&&$(s),l=[...a.keys()].filter(u);if(c===void 0||l.length===0)return;let f=g(c,l,a,r.copy).finally(()=>i.delete(f));i.add(f)});async function g(t,i,a,o){let s=t=>{let n=[...a].filter(([n])=>t(n)&&e.getNote(n)!==void 0);n.length>0&&e.batch(()=>n.forEach(([t,n])=>e.updateNote(t,n)))},c=[],d=[],p=!1,m=e=>{c.push(...e);for(let t of e)l.add(t);if(o)return;let t=e.flatMap(e=>f(e)??[]);for(let e of t)e.classList.add(To);d.push(...t)};try{await Promise.resolve(),m(i),s(e=>o||!i.includes(e));let l=So(i,e.getEdges(),u);if(l.length>0){if(await new Promise(e=>requestAnimationFrame(()=>setTimeout(e))),r.aborted)return;confirm(H(o?`transfer.confirmCopyLinked`:`transfer.confirmMoveLinked`,l.length))&&m(l.filter(u))}let f=c.filter(t=>e.getNote(t)!==void 0),h=Object.fromEntries(f.flatMap(t=>{let n=a.get(t),r=e.getNote(t);return n&&r?[[t,{x:n.x??r.x,y:n.y??r.y}]]:[]})),g={clientId:n.clientId,opId:crypto.randomUUID(),to:t,noteIds:f,positions:h,copy:o},_=await ea(n.slug,g).catch(e=>{if(e instanceof Z)throw e;return ea(n.slug,g)}).catch(e=>({error:e}));if(r.aborted)return;if(`error`in _){for(let e of d)e.classList.remove(To);s(()=>!o);let e=_.error instanceof Z&&_.error.status===409;n.notify(e?H(`transfer.partial`,n.titleOf(t)):q(`failed.transfer`,_.error));return}o||(p=!0),n.notify(H(o?`transfer.copied`:`transfer.moved`,f.length,n.titleOf(t))),_.page&&n.onSent(_.page)}finally{if(!p)for(let e of c)l.delete(e)}}return{settled:()=>Promise.allSettled(i).then(()=>{})}}function Do(e){return[...e].reverse().map(e=>{switch(e.type){case`note:create`:return{type:`note:delete`,note:e.note};case`note:delete`:return{type:`note:create`,note:e.note};case`edge:create`:return{type:`edge:delete`,edge:e.edge};case`edge:delete`:return{type:`edge:create`,edge:e.edge};case`note:update`:return{type:e.type,noteId:e.noteId,before:e.after,after:e.before};case`edge:update`:return{type:e.type,edgeId:e.edgeId,before:e.after,after:e.before}}})}function Oo(e){return{send:t=>e.send(t),close:()=>e.close(),onMessage:t=>e.addEventListener(`message`,e=>t(String(e.data))),onClose:t=>e.addEventListener(`close`,e=>t(e.code))}}var ko=3e4,Ao=3e4;function jo(e){if(e.type===`note:update`)return`note:${e.noteId}`;if(e.type===`edge:update`)return`edge:${e.edgeId}`}function Mo(e){let t=new Set;for(let n of e)n.type===`note:update`||n.type===`edge:update`?t.add(jo(n)):n.type===`note:create`||n.type===`note:delete`?t.add(`note:${n.note.id}`):t.add(`edge:${n.edge.id}`);return t}var No=class{board;connect;hooks;clientId=crypto.randomUUID();lastSeq;snapshotSeq=0;epoch;pending=[];infos=new Map;socket;status=`connecting`;ready=!1;stopped=!1;retries=0;stopPing;stopRetry;constructor(e,t,n={}){this.board=e,this.connect=t,this.hooks=n,e.on(`history:commit`,({deltas:e})=>this.commit(e))}start(){this.setStatus(`connecting`),this.open()}stop(){this.stopped=!0,this.stopPing?.(),this.stopRetry?.(),this.socket?.close()}get pendingCount(){return this.pending.length}noteInfo(e){return this.infos.get(e)}setStatus(e){this.status=e,this.hooks.onStatus?.(e,this.pending.length)}send(e){this.socket?.send(JSON.stringify(e))}authExpired(){this.stopped=!0,this.hooks.onAuthExpired?.()}async open(){if(this.stopped)return;let e;try{e=await this.connect()}catch{if(this.stopped)return;let e=this.hooks.isAuthenticated!==void 0&&!await this.hooks.isAuthenticated();if(this.stopped)return;e?this.authExpired():this.scheduleReconnect();return}if(this.stopped){e.close();return}this.socket=e,e.onMessage(e=>this.onMessage(e)),e.onClose(t=>this.onClose(e,t)),this.send({type:`hello`,clientId:this.clientId,lastSeq:this.lastSeq,epoch:this.epoch});for(let{opId:e,deltas:t}of this.pending)this.send({type:`ops`,opId:e,deltas:t});let t=setInterval(()=>this.socket?.send(oo),ko);this.stopPing=()=>clearInterval(t)}onClose(e,t){this.socket===e&&(this.socket=void 0,this.stopPing?.(),!this.stopped&&(t===4401?this.authExpired():t===4410?(this.stopped=!0,this.hooks.onDeleted?.()):this.scheduleReconnect()))}scheduleReconnect(){this.setStatus(this.ready?`offline`:`connecting`);let e=Math.min(1e3*2**this.retries,Ao);this.retries++;let t=setTimeout(()=>void this.open(),e);this.stopRetry=()=>clearTimeout(t)}commit(e){let t={opId:crypto.randomUUID(),deltas:e,applied:!0};this.pending.push(t),this.send({type:`ops`,opId:t.opId,deltas:e}),this.setStatus(this.status)}onMessage(e){if(e===`pong`)return;let t=JSON.parse(e);switch(t.type){case`snapshot`:this.infos=new Map(Object.entries(t.info??{})),this.board.importData(t.data),this.lastSeq=t.seq,this.snapshotSeq=t.seq,this.epoch=t.epoch??void 0;for(let e of this.pending)e.applied=!1;this.hooks.onTitle?.(t.title),this.hooks.onColor?.(t.color),this.synced();break;case`meta`:this.epoch=t.epoch??void 0,this.hooks.onTitle?.(t.title),this.hooks.onColor?.(t.color),this.synced();break;case`ops`:this.onOps(t);break;case`reject`:this.onReject(t.opId,t.reason,t.fixups??[])}}synced(){this.retries=0,this.setStatus(`synced`),this.ready||(this.ready=!0,this.hooks.onReady?.())}takePending(e){let t=this.pending.findIndex(t=>t.opId===e);return t===-1?void 0:this.pending.splice(t,1)[0]}pendingUpdates(e){return this.pending.filter(e=>e.applied).flatMap(e=>e.deltas).filter(t=>{let n=jo(t);return n!==void 0&&e.has(n)})}applyServer(e){e.length!==0&&this.board.applyRemote([...e,...this.pendingUpdates(Mo(e))])}onOps(e){let t=e.createdAt!==void 0&&e.seq>(this.lastSeq??0)?vo(this.infos,e.actor,e.createdAt,e.deltas):void 0;this.lastSeq=Math.max(this.lastSeq??0,e.seq),this.applyOps(e),t?.size&&this.hooks.onNoteInfo?.(t)}applyOps(e){if(e.clientId!==this.clientId||e.reverts!==void 0){this.applyServer(e.deltas);return}let t=this.takePending(e.opId);t&&(t.applied?this.applyServer(e.fixups??[]):e.seq>this.snapshotSeq&&this.applyServer(e.deltas),this.setStatus(this.status))}onReject(e,t,n){let r=this.takePending(e);if(!r)return;let i=r.applied?Do(r.deltas):[],a=this.pending.filter(e=>e.applied).flatMap(e=>e.deltas);this.board.applyRemote([...i,...n,...a]),this.hooks.onReject?.(t),this.setStatus(this.status)}},Po=`viewports`;function Fo(){try{let e=JSON.parse(Ri.get(Po)??`[]`);return Array.isArray(e)?e.map(e=>Array.isArray(e)&&e.length===4?[e[0],e[3]]:e).filter(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&typeof e[1]==`number`&&Number.isFinite(e[1])):[]}catch{return[]}}var Io=300;function Lo(e,t,n,r=()=>!1){let i=`idle`,a=e.getViewport().zoom,o,s=a,c=()=>{o!==void 0&&(clearTimeout(o),o=void 0,zo(t,s))};return e.on(`viewport:change`,e=>{let t=e.zoom!==a;a=e.zoom,i===`saving`&&t&&!r()&&(s=a,clearTimeout(o),o=setTimeout(c,Io))}),window.addEventListener(`pagehide`,c,{signal:U()}),W(c),{restore(){let r=Ro(t);r===void 0?e.fitToContent():e.setViewport({zoom:r}),Fi(e,n)},start(){i===`idle`&&(i=`saving`)},freeze(){c(),i=`frozen`}}}function Ro(e){return Fo().find(([t])=>t===e)?.[1]}function zo(e,t){let n=Fo().filter(([t])=>t!==e);n.push([e,Math.round(t*1e3)/1e3]),Ri.set(Po,JSON.stringify(n.slice(-200)))}var Bo=8e3,Vo=1500,Ho=`view-only`,Uo=`theme`,Wo=[[`alignLeft`,H(`align.left`),`left`],[`alignCenter`,H(`align.center`),`center`],[`alignRight`,H(`align.right`),`right`],[`alignTop`,H(`align.top`),`top`],[`alignMiddle`,H(`align.middle`),`middle`],[`alignBottom`,H(`align.bottom`),`bottom`]],Go={connecting:H(`status.connecting`),synced:``,offline:H(`status.offline`)},Ko={modified:H(`skip.modified`),connected:H(`skip.connected`),deleted:H(`skip.deleted`),exists:H(`skip.exists`),"endpoint-missing":H(`skip.endpoint-missing`)};function qo(e){let t=[...new Set(e.skipped.map(e=>Ko[e.reason]))],n=t.length>0?H(`revert.reasons`,t):``;return e.applied===0?H(`revert.none`,n):e.skipped.length===0?H(`revert.done`):H(`revert.partial`,e.skipped.length,n)}function Jo(e){if(e.summary===null)return e.reverts===null?H(`ops.noSummary`):H(`ops.summary.revertUnknown`);let t=ao(e.summary);switch(t?.kind){case`pageCreated`:return H(`ops.summary.pageCreated`);case`childRemoved`:return H(`ops.summary.childRemoved`,t.page);case`revert`:return H(`ops.summary.revert`,t.seq);case`notesReceived`:return H(`ops.summary.notesReceived`,t.page);case`notesSent`:return H(`ops.summary.notesSent`,t.page);case`childRecolored`:return H(`ops.summary.childRecolored`,t.page);default:return e.summary}}function Yo(e){return new Promise((t,n)=>{let r=location.protocol===`https:`?`wss`:`ws`,i=new WebSocket(`${r}://${location.host}/ws/${e}`);i.addEventListener(`close`,()=>n(Error(`websocket closed`)),{once:!0}),i.addEventListener(`open`,()=>t(Oo(i)),{once:!0})})}function Xo(e,t,n){let r=null,i=!1,a=G(`div`,{className:`board`}),o=G(`div`,{className:`page-body`},a),s=new mo(t,(e,t)=>void f.enter(t,`/p/${e}`)),c=new xo,l=new pr({container:a,readOnly:!0,theme:Ri.get(Uo)===`card`?`card`:`default`,onImageUpload:ta,onLinkClick:$r,renderNote:s.render,renderNoteAccessory:c.render,noteLinks:{text(e){let t=$(e);return t===void 0?void 0:s.titleOf(t)}},labels:ki,emptyDrag:`pan`});s.attach(l);let u=fi(l,a,{onChange(e){e||d.restore()}}),d=Lo(l,t,a,u.isStacked),f=Ka(l,d.freeze,u.isStacked),p=(e,t)=>(e.addEventListener(`click`,n=>{ei(n)&&(n.preventDefault(),f.leave(e.href,t()))}),e),m=e=>l.getNotes().find(t=>$(t)===e),h=[t],g=()=>h[0];Ur(e=>{if(e===`/`)return f.leaveOnPop(g());let n=Wr(e);if(n===void 0||n===t)return;let r=h.indexOf(n);if(r>=0)return f.leaveOnPop(h[r+1]);let i=m(n);return i&&f.enterOnPop(i.id)});let _=async()=>{if(u.isStacked()){let e=n?.kind===`leave`?m(n.from):void 0;e&&l.revealNotes([e.id])}else d.restore();await f.arrive(n,m),d.start()},v=Li(o,Bo),y=e=>t=>v(q(e,t)),b=G(`h1`,{className:`page-title`,title:H(`page.titleHint`,t)}),x=G(`span`,{className:`sync-status`}),S=G(`span`,{className:`crumbs`}),C=e=>{r=e,b.textContent=e??t,document.title=H(`documentTitle`,e??t,Mr.siteName)};C(null);let w=Di(e=>{Xi(t,e).then(e=>P(e.color)).catch(y(`failed.color`))}),{undo:T,redo:E}=Ni(l),D=()=>{if(u.isStacked())return{};let e=l.getNotes().length%10*20,t=l.getViewport();return{x:(120+e-t.x)/t.zoom,y:(80+e-t.y)/t.zoom}},ee=(e={})=>{let t=l.addNote({...D(),...e});t&&u.isStacked()&&l.revealNotes([t.id])},O=X(`add`,H(`note.add`),()=>ee()),te=go(t,e=>{ee({...to,text:``,meta:{[eo]:e}}),re.close()}),ne=X(`childPage`,H(`child.place`)),re=wi(ne,te.root,{onOpen:te.opened}),ie=()=>{l.autoLayout(),Fi(l,a)},k=X(`layout`,H(`layout.title`)),A=()=>l.getSelection().length<2,j=G(`div`,{className:`layout-panel`}),ae=wi(k,j,{instead:()=>A()?(ie(),!0):!1}),oe,se=e=>{if(e===oe)return;oe=e,ae.close();let t=H(e?`layout.auto`:`layout.title`);k.title=k.ariaLabel=t,k.replaceChildren(bi(e?`autoLayout`:`layout`)),k.ariaExpanded=e?null:`false`},ce=[],M=(e,t,n,r)=>{let i=X(e,t,()=>{r(l.getSelection()),ae.close()});ce.push([i,n]),j.append(i)};for(let[e,t,n]of Wo)M(e,t,2,e=>l.alignNotes(e,n));M(`distributeH`,H(`layout.distributeH`),3,e=>l.distributeNotes(e,`horizontal`)),M(`distributeV`,H(`layout.distributeV`),3,e=>l.distributeNotes(e,`vertical`)),M(`autoLayout`,H(`layout.auto`),0,ie);let N=()=>{let e=l.isReadOnly()||l.isViewOnly();T.disabled=e||!l.canUndo(),E.disabled=e||!l.canRedo(),O.disabled=e,ne.disabled=e;let t=l.getSelection().length;for(let[n,r]of ce)n.disabled=e||t<r;let n=A();se(n),k.disabled=n&&e};document.addEventListener(`keydown`,e=>{if(!(e.ctrlKey||e.metaKey)||e.key!==`a`||l.isReadOnly()||document.querySelector(`dialog[open]`))return;let t=document.activeElement;t instanceof HTMLElement&&(t.isContentEditable||t.matches(`input, textarea`))||(e.preventDefault(),l.selectAll())},{signal:U()}),l.on(`readOnly:change`,N),l.on(`history:change`,N),l.on(`note:select`,N),l.on(`note:delete`,N),N();let le=G(`button`,{type:`button`,className:`text-button`,hidden:!0}),ue=G(`div`,{className:`link-list`}),de=G(`div`,{className:`menu`}),fe=wi(X(`menu`,H(`menu.title`)),de,{align:`right`}),pe=da(t,y(`failed.bookmark`)),me=xi([p(G(`a`,{href:`/`,textContent:H(`list`)}),g),S,b,w.root,pe,x],[G(`span`,{className:`tool-group`},T,E),Si(),G(`span`,{className:`tool-group`},O,re.root),Si(),G(`span`,{className:`tool-group optional`},ae.root,Si(),Ii(l,a))],[wi(le,ue,{align:`right`}).root,ua(),fe.root]);e.append(me,o);let P=e=>{me.style.backgroundColor=e??``,w.show(e)};Ui(t).then(({ancestors:e})=>{h=[...e.map(e=>e.name),t],e.forEach((e,t)=>{let n=h[t+1],r=G(`a`,{href:`/p/${e.name}`,textContent:e.title??e.name});S.append(p(r,()=>n),`›`)})}).catch(y(`failed.ancestors`));let F=new No(l,()=>Yo(t),{onNoteInfo:c.refresh,onReady(){l.setReadOnly(!1),Ri.get(Ho)===`1`&&l.setViewOnly(!0),u.start(),_()},onStatus(e,t){let n=e===`synced`&&t>0?H(`status.saving`):Go[e];x.title!==n&&(x.title=n,x.textContent=e===`offline`?n:``),x.dataset.state!==e&&(x.dataset.state=e)},onTitle:C,onColor:P,onAuthExpired:()=>location.reload(),isAuthenticated:na,onDeleted(){l.setReadOnly(!0),!i&&(alert(H(`page.deletedAlert`)),location.assign(`/`))},onReject(e){v(e===`text conflict`?H(`sync.conflict`):te.rejectionMessage(e)??H(`sync.rejected`,e))}});c.attach(l,e=>F.noteInfo(e)),F.start();let he=Eo(l,a,{slug:t,clientId:F.clientId,titleOf:e=>s.titleOf(e),notify:v,onSent:e=>s.contentChanged(e)});Vr(async()=>{let e=Date.now()+Vo;for(await Promise.race([he.settled(),new Promise(e=>setTimeout(e,Vo))]);F.pendingCount>0&&Date.now()<e;)await new Promise(e=>setTimeout(e,50))}),W(()=>{F.stop(),l.destroy()}),b.addEventListener(`click`,()=>{let e=K({className:`title-input`,value:r??``,placeholder:t,maxLength:200}),n=!1,i=i=>{if(n)return;n=!0,e.replaceWith(b);let a=e.value.trim();i&&a!==(r??``)&&Yi(t,a).catch(y(`failed.rename`))};e.addEventListener(`keydown`,e=>{e.isComposing||(e.key===`Enter`?i(!0):e.key===`Escape`&&i(!1))}),e.addEventListener(`blur`,()=>i(!0)),b.replaceWith(e),e.focus(),e.select()}),Ji(t).then(({pages:e})=>{e.length!==0&&(le.textContent=H(`backlinks.count`,e.length),le.title=H(`backlinks.title`),le.hidden=!1,ue.append(...oa(e)))}).catch(y(`failed.backlinks`));let ge=G(`input`,{type:`checkbox`,checked:!0}),_e=G(`ul`,{className:`op-list`}),ve=G(`div`,{className:`op-result`,role:`status`}),ye=e=>t=>{ve.textContent=q(e,t)},be=async()=>{let{ops:e}=await Qi(t,ge.checked);_e.replaceChildren(...e.map(L)),e.length===0&&_e.append(G(`li`,{className:`empty`,textContent:H(`ops.empty`)}))},I=()=>be().catch(ye(`failed.history`)),xe=async(e,n)=>{n.disabled=!0;try{ve.textContent=qo(await $i(t,e.seq,F.clientId)),await be()}catch(e){ye(`failed.revert`)(e)}};function L(e){let t=e.revertedBy!==null,n=G(`button`,{type:`button`,textContent:H(`ops.revert`),disabled:t});n.addEventListener(`click`,()=>void xe(e,n));let r=Jo(e);return G(`li`,{className:t?`reverted`:``},G(`div`,{className:`op-meta`,textContent:`${ci(e.createdAt)} ${e.actor}`}),G(`div`,{className:`op-summary`,textContent:r+(t?H(`ops.revertedMark`):``)}),n)}ge.addEventListener(`change`,I);let Se=Ti(`history-dialog`,G(`h2`,{textContent:H(`ops.title`)}),G(`div`,{className:`history-head`},G(`label`,{},ge,` `,H(`ops.agentOnly`)),G(`button`,{type:`button`,textContent:H(`ops.refresh`),onclick:I})),ve,_e);e.append(Se);let R=Oi(``,()=>{if(l.isReadOnly())return;let e=!l.isViewOnly();Ri.set(Ho,e?`1`:`0`),l.setViewOnly(e),fe.close()}),Ce=()=>{R.textContent=H(l.isViewOnly()?`menu.viewOnlyExit`:`menu.viewOnly`),N()};l.on(`viewOnly:change`,Ce),Ce();let z=Oi(``,()=>{let e=l.getTheme()===`card`?`default`:`card`;l.setTheme(e),Ri.set(Uo,e),we()}),we=()=>{z.textContent=H(l.getTheme()===`card`?`menu.themeCard`:`menu.themeDefault`)};we(),de.append(R,z,Oi(H(`menu.history`),()=>{fe.close(),ve.textContent=``,Se.showModal(),I()}),Oi(H(`menu.exportJson`),()=>{let e=new Blob([JSON.stringify(l.exportData(),null,2)],{type:`application/json`}),n=G(`a`,{href:URL.createObjectURL(e),download:`${t}.json`});n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e4),fe.close()}),Oi(H(`help`),()=>Qr(`/help`)),Oi(H(`lang.switch`),ji),G(`hr`),Oi(H(`menu.deletePage`),()=>{fe.close(),ai(r??t)&&(i=!0,Zi(t).then(()=>location.assign(`/`)).catch(e=>{i=!1,y(`failed.delete`)(e)}))},`danger`))}var Zo=document.getElementById(`app`);document.documentElement.lang=V,Xr((e,n,r)=>{let i=Wr(e),a=i!==void 0&&t(i);return a||e===`/`||e===`/help`?(Zo.replaceChildren(),a?Xo(Zo,i,r):e===`/help`?zi(Zo):$a(Zo,r),!0):n?(Zo.textContent=H(`notFound`),!0):!1});
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
7
7
  <title>wema-kake</title>
8
- <script type="module" crossorigin src="/assets/index-DaZ8I4iZ.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-KO6AqS9t.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/assets/index-Cgi5orcJ.css">
10
10
  </head>
11
11
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanf/wema-kake",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "付箋ボードライブラリ wema を使った Wiki。Cloudflare Workers の上で動き、利用側が自分の Worker を作ってデプロイする",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -57,9 +57,9 @@
57
57
  },
58
58
  "//dependencies": "Worker の側が実行時に使うもの。@kanf/wema は、画面のビルドに入るほか、Worker の側も自動配置(computeAutoLayout)と型に使うので、ここに置く",
59
59
  "dependencies": {
60
- "@kanf/wema": "^0.16.0",
60
+ "@kanf/wema": "^0.16.1",
61
61
  "@modelcontextprotocol/server": "^2.0.0",
62
- "agents": "^0.28.0",
62
+ "agents": "^0.30.0",
63
63
  "hono": "^4.13.13",
64
64
  "jose": "^6.2.12",
65
65
  "zod": "^4.6.5"
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "//dependencies": "Wiki の本体。画面、D1 のマイグレーションも、このパッケージに入っている",
18
18
  "dependencies": {
19
- "@kanf/wema-kake": "^0.1.2"
19
+ "@kanf/wema-kake": "^0.1.3"
20
20
  },
21
21
  "devDependencies": {
22
22
  "typescript": "^7.0.2",
@@ -1,5 +0,0 @@
1
- (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=RegExp(`^[a-z0-9][a-z0-9-]{0,63}$`);function t(t){return e.test(t)}var n={color:`Color`,duplicate:`Duplicate`,delete:`Delete`,deleteNotes:e=>`Delete ${e} notes`,autoSize:`Auto Size`,bulletedList:`Bulleted List`,numberedList:`Numbered List`,checklist:`Checklist`,outdent:`Outdent (Shift+Tab)`,indent:`Indent (Tab)`,image:`Image`,embed:`Embed`,foldLongText:`Fold Long Text`,colorButter:`Butter`,colorRose:`Rose`,colorPeach:`Peach`,colorLavender:`Lavender`,colorSky:`Sky`,colorMint:`Mint`,colorSage:`Sage`,colorGray:`Gray`,details:`Details`,route:`Route`,from:`From`,to:`To`,line:`Line`,arrow:`Arrow`,size:`Size`,width:`Width`,lineSolid:`Solid`,lineDashed:`Dashed`,lineDotted:`Dotted`,arrowNone:`No arrow`,arrowStart:`Arrow at start`,arrowEnd:`Arrow at end`,arrowBoth:`Arrow at both ends`,sizeSmall:`Small`,sizeMedium:`Medium`,sizeLarge:`Large`,widthThin:`Thin`,widthNormal:`Normal`,widthThick:`Thick`,routeCurve:`Curve`,routePolyline:`Polyline`,anchorAuto:`Auto`,anchorTop:`Top`,anchorRight:`Right`,anchorBottom:`Bottom`,anchorLeft:`Left`,bold:`Bold`,strikethrough:`Strikethrough`,textColor:`Text Color`,link:`Link`,removeLink:`Remove link`,quote:`Quote in a new note`,ok:`OK`,deleteImage:`Delete image`,readMore:`Read more`,showLess:`Show less`,linkOut:e=>`Connects to: ${e}`,linkIn:e=>`Connected from: ${e}`,linkBoth:e=>`Connected both ways: ${e}`,linkNone:e=>`Connected: ${e}`,linkLabeled:(e,t)=>`${e} (${t})`,linkEmpty:`(No text)`},r={color:`色`,duplicate:`複製`,delete:`削除`,deleteNotes:e=>`${e} 枚の付箋を削除`,autoSize:`内容に合わせたサイズ`,bulletedList:`箇条書き`,numberedList:`番号付きリスト`,checklist:`チェックリスト`,outdent:`段上げ (Shift+Tab)`,indent:`段下げ (Tab)`,image:`画像`,embed:`埋め込み`,foldLongText:`長い本文を畳む`,colorButter:`バター`,colorRose:`ローズ`,colorPeach:`ピーチ`,colorLavender:`ラベンダー`,colorSky:`スカイ`,colorMint:`ミント`,colorSage:`セージ`,colorGray:`グレー`,details:`詳細`,route:`経路`,from:`始点`,to:`終点`,line:`線`,arrow:`矢印`,size:`サイズ`,width:`太さ`,lineSolid:`実線`,lineDashed:`破線`,lineDotted:`点線`,arrowNone:`矢印なし`,arrowStart:`始点に矢印`,arrowEnd:`終点に矢印`,arrowBoth:`両端に矢印`,sizeSmall:`小`,sizeMedium:`中`,sizeLarge:`大`,widthThin:`細い`,widthNormal:`標準`,widthThick:`太い`,routeCurve:`曲線`,routePolyline:`折れ線`,anchorAuto:`自動`,anchorTop:`上`,anchorRight:`右`,anchorBottom:`下`,anchorLeft:`左`,bold:`太字`,strikethrough:`取り消し線`,textColor:`文字色`,link:`リンク`,removeLink:`リンクを解除`,quote:`引用した付箋を作る`,ok:`OK`,deleteImage:`画像を削除`,readMore:`続きを読む`,showLess:`折り畳む`,linkOut:e=>`つながり先: ${e}`,linkIn:e=>`つながり元: ${e}`,linkBoth:e=>`相互のつながり: ${e}`,linkNone:e=>`つながり: ${e}`,linkLabeled:(e,t)=>`${e}(${t})`,linkEmpty:`(本文なし)`};function i(e,t){let r={...n},i={...e,readMore:t?.more??e?.readMore,showLess:t?.less??e?.showLess};for(let e of Object.keys(n))typeof i[e]==typeof r[e]&&(r[e]=i[e]);return r}var a=class{handlers=new Map;on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n)),n.add(t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){let n=this.handlers.get(e);if(n)for(let r of n)try{r(t)}catch(t){console.error(`Error in event handler for "${String(e)}":`,t)}}removeAllListeners(){this.handlers.clear()}};function o(){return crypto.randomUUID()}function s(e){return{left:Math.min(...e.map(e=>e.x)),top:Math.min(...e.map(e=>e.y)),right:Math.max(...e.map(e=>e.x+e.width)),bottom:Math.max(...e.map(e=>e.y+e.height))}}var c=4;function l(e,t,n,r,i){let a=t.top-i-e.height,o=t.bottom+i,s={x:(t.left+t.right)/2-e.width/2,y:r===`above`?a:o};if(!(t.right>=n.left&&t.left<=n.right&&t.bottom>=n.top&&t.top<=n.bottom))return s;let l=n.left+c,u=n.top+c,d=n.right-c-e.width,f=n.bottom-c-e.height,p=a>=u,m=o<=f,h=s.y;return r===`above`&&!p&&m&&(h=o),r===`below`&&!m&&p&&(h=a),{x:Math.max(l,Math.min(s.x,d)),y:Math.max(u,Math.min(h,f))}}var u=[`top`,`right`,`bottom`,`left`];function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2;switch(t){case`top`:return{x:n,y:e.y};case`bottom`:return{x:n,y:e.y+e.height};case`left`:return{x:e.x,y:r};case`right`:return{x:e.x+e.width,y:r};case`auto`:return{x:n,y:r}}}var f=40;function p(e,t){if(t.y-(e.y+e.height)>=f)return`bottom`;if(e.y-(t.y+t.height)>=f)return`top`;let n=e.x+e.width/2,r=e.y+e.height/2,i=t.x+t.width/2,a=t.y+t.height/2,o=i-n,s=a-r,c={top:{x:0,y:-1},right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0}},l=`right`,d=-1/0;for(let e of u){let t=c[e],n=o*t.x+s*t.y;n>d&&(d=n,l=e)}return l}function m(e){switch(e){case`top`:return{x:0,y:-1};case`bottom`:return{x:0,y:1};case`left`:return{x:-1,y:0};case`right`:return{x:1,y:0}}}function h(e,t,n,r,i){let a=n===`auto`?p(e,t):n,o=r===`auto`?p(t,e):r,s=d(e,a),c=d(t,o);if(i===`polyline`)return g(s,c,a,o);let l=Math.sqrt((c.x-s.x)**2+(c.y-s.y)**2),u=Math.min(Math.max(l*.4,40),150),f=m(a),h=m(o),_=s.x+f.x*u,v=s.y+f.y*u,y=c.x+h.x*u,b=c.y+h.y*u;return`M ${s.x} ${s.y} C ${_} ${v}, ${y} ${b}, ${c.x} ${c.y}`}function g(e,t,n,r){let i=m(n),a=m(r),o=n===`left`||n===`right`,s=r===`left`||r===`right`,c;if(o===s){if(i.x+a.x===0&&i.y+a.y===0){if(o){let n=(e.x+t.x)/2;c=[{x:n,y:e.y},{x:n,y:t.y}]}else{let n=(e.y+t.y)/2;c=[{x:e.x,y:n},{x:t.x,y:n}]}}else{let n=Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),r=Math.min(Math.max(n*.3,30),100);if(o){let n=i.x>0?Math.max(e.x,t.x)+r:Math.min(e.x,t.x)-r;c=[{x:n,y:e.y},{x:n,y:t.y}]}else{let n=i.y>0?Math.max(e.y,t.y)+r:Math.min(e.y,t.y)-r;c=[{x:e.x,y:n},{x:t.x,y:n}]}}}else c=o?[{x:t.x,y:e.y}]:[{x:e.x,y:t.y}];let l=[`M ${e.x} ${e.y}`];for(let e of c)l.push(`L ${e.x} ${e.y}`);return l.push(`L ${t.x} ${t.y}`),l.join(` `)}function _(e,t,n,r){let i=d(e,t),a=Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2);if(r===`polyline`){let e=t===`left`||t===`right`?{x:n.x,y:i.y}:{x:i.x,y:n.y};return`M ${i.x} ${i.y} L ${e.x} ${e.y} L ${n.x} ${n.y}`}let o=Math.min(Math.max(a*.4,40),150),s=m(t),c=i.x+s.x*o,l=i.y+s.y*o,u=i.x-n.x,f=i.y-n.y,p=Math.sqrt(u*u+f*f)||1,h=n.x+u/p*o,g=n.y+f/p*o;return`M ${i.x} ${i.y} C ${c} ${l}, ${h} ${g}, ${n.x} ${n.y}`}function v(e,t){let n=document.createElement(e);return t&&(n.className=t),n}function y(e,t){e.title=t,e.setAttribute(`aria-label`,t)}function b(e,t,n,r,i){let a=t.getBoundingClientRect(),o=document.documentElement,s={left:Math.max(0,-a.left),top:Math.max(0,-a.top),right:Math.min(t.clientWidth,o.clientWidth-a.left),bottom:Math.min(t.clientHeight,o.clientHeight-a.top)},c={width:e.offsetWidth,height:e.offsetHeight},{x:u,y:d}=l(c,n,s,r,i);return e.style.left=`${u}px`,e.style.top=`${d}px`,{left:u,top:d,right:u+c.width,bottom:d+c.height}}function x(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left,top:n.top-r.top,right:n.right-r.left,bottom:n.bottom-r.top}}function S(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,e);return t&&n.setAttribute(`class`,t),n}var C=`[contenteditable]:not([contenteditable="false"]), input, textarea, select`;function w(e){let t=document.getSelection();if(!t||t.rangeCount===0)return null;let n=t.getRangeAt(0);return e.contains(n.commonAncestorContainer)?n:null}function T(e){let t=document.getSelection();t&&(t.removeAllRanges(),t.addRange(e))}function E(e,t){Object.assign(e.style,t)}var D=new Set([`b`,`strong`,`i`,`em`,`u`,`s`,`br`,`span`,`ul`,`ol`,`li`,`a`,`input`,`img`,`iframe`,`video`,`audio`,`div`,`p`,`blockquote`]),ee={a:new Set([`href`,`target`,`rel`]),input:new Set([`type`,`checked`]),img:new Set([`src`,`alt`,`width`,`height`]),iframe:new Set([`src`,`width`,`height`,`sandbox`,`allow`,`allowfullscreen`,`frameborder`,`title`]),video:new Set([`src`,`controls`,`preload`,`width`,`height`,`poster`]),audio:new Set([`src`,`controls`,`preload`])},O=new Set([`script`,`style`,`noscript`,`object`,`embed`,`applet`]),te=new Set([`color`,`background-color`,`font-size`,`font-weight`,`font-style`,`text-decoration`,`text-decoration-line`,`text-align`,`margin`,`padding`,`display`,`list-style-type`,`white-space`]),ne=new Set([`font-weight`,`font-style`,`text-decoration`,`text-decoration-line`]),re=new Set([`normal`,`400`,`none`]),ie=new Set([`http`,`https`,`mailto`,`tel`]),k={img:`image/`,video:`video/`,audio:`audio/`};function A(e,t){let n=e.replace(/^[\u0000- ]+/,``).replace(/[\t\n\r]/g,``).toLowerCase(),r=/^([a-z][a-z0-9+.-]*):/.exec(n)?.[1];return r===void 0||ie.has(r)?!0:r===`data`&&t!==void 0&&n.startsWith(`data:${t}`)}function j(e){if(!A(e))return null;let t,n;try{t=new URL(e,document.baseURI),n=new URL(document.baseURI)}catch{return null}let r=t.protocol===n.protocol&&t.host===n.host;return!A(t.href)&&!r?null:t.href}function ae(e,t){let n=new DOMParser().parseFromString(`<body>${e}</body>`,`text/html`).body;return se(n,t?.pasted??!1),n.innerHTML}function oe(e){let t=e.ownerDocument.createDocumentFragment();for(;e.firstChild;)t.appendChild(e.firstChild);e.parentNode?.replaceChild(t,e)}function se(e,t){let n=Array.from(e.childNodes);for(let r of n){if(r.nodeType===Node.TEXT_NODE)continue;if(r.nodeType!==Node.ELEMENT_NODE){r.parentNode?.removeChild(r);continue}let n=r,i=n.tagName.toLowerCase();if(O.has(i)){n.parentNode?.removeChild(n);continue}if(!D.has(i)){oe(n),se(e,t);return}if(i===`input`&&n.type!==`checkbox`){n.parentNode?.removeChild(n);continue}let a=ee[i],o=[];for(let e of Array.from(n.attributes)){let r=e.name.toLowerCase();if(r.startsWith(`on`)){o.push(e.name);continue}if(r!==`class`){if(r===`style`){ce(n,t);continue}if(!a||!a.has(r)){o.push(e.name);continue}if(r===`href`||r===`src`||r===`poster`){let t=r===`poster`?`image/`:k[i];A(e.value,t)||o.push(e.name)}}}for(let e of o)n.removeAttribute(e);se(n,t),t&&i===`span`&&n.attributes.length===0&&oe(n)}}function ce(e,t){let n=e.style,r=t?ne:te,i=[];for(let e=0;e<n.length;e++){let a=n[e],o=t&&re.has(n.getPropertyValue(a));(!r.has(a)||o)&&i.push(a)}for(let e of i)n.removeProperty(e);e.getAttribute(`style`)===``&&e.removeAttribute(`style`)}function M(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function N(e){return!/<[a-z][^<>]*>/i.test(e)}function le(e){let t=document.getSelection();if(!t||t.rangeCount===0)return;let n=t.getRangeAt(0);n.deleteContents();let r=document.createElement(`div`);r.innerHTML=e;let i=document.createDocumentFragment(),a=null;for(;r.firstChild;)a=i.appendChild(r.firstChild);if(n.insertNode(i),a){let e=document.createRange();e.setStartAfter(a),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}}function ue(e){if(typeof e==`object`&&e&&!Array.isArray(e))return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`)))}function de(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}var fe=`wema-checklist`,pe=`wema-checked`,me=`img, iframe, video, audio, input`;function P(e){return e?.nodeType===Node.ELEMENT_NODE}function F(e){return P(e)&&(e.tagName===`UL`||e.tagName===`OL`)}function he(e){return P(e)&&e.tagName===`LI`}function ge(e){return P(e)&&(e.tagName===`DIV`||e.tagName===`P`)}function _e(e){return P(e)&&e.tagName===`BR`}function ve(e){return e?.nodeType===Node.TEXT_NODE&&e.data===`
2
- `}function ye(e){return Array.prototype.indexOf.call(e.parentNode?.childNodes??[],e)}function be(e){let t=[];for(let n=e.nextSibling;n;n=n.nextSibling)t.push(n);return t}function I(e,t,n){let r=(P(t)?t:t.parentElement)?.closest(n)??null;return r&&r!==e&&e.contains(r)?r:null}function xe(e,t){return I(e,t.startContainer,`li`)!==null}function L(e){return e.tagName===`OL`?`ol`:e.classList.contains(fe)?`checklist`:`ul`}function Se(e){let t=document.createElement(e===`ol`?`ol`:`ul`);return e===`checklist`&&t.classList.add(fe),t}function R(e,t){let n=e.querySelector(`:scope > input[type="checkbox"]`);if(t===`checklist`){if(n)return;let t=document.createElement(`input`);t.type=`checkbox`,e.insertBefore(t,e.firstChild)}else n?.remove(),e.classList.remove(pe)}function Ce(e){let t=document.createElement(`li`);return R(t,e),t}function z(e,t,n=null){let r=L(t);for(let i of Array.from(e))he(i)&&R(i,r),t.insertBefore(i,n)}function we(e){let{startContainer:t,startOffset:n,endContainer:r,endOffset:i}=e;return{restore(e,a,o){let s=t=>t!==e&&t!==o&&e.contains(t),c=document.createRange();return s(t)&&s(r)?(c.setStart(t,n),c.setEnd(r,i)):(c.selectNodeContents(a),c.collapse(!1)),c}}}function Te(e){for(let t of Array.from(e.childNodes)){if(t.nodeType!==Node.TEXT_NODE)continue;let e=t,n;for(;(n=e.data.indexOf(`
3
- `))!==-1&&(n>0&&(e=e.splitText(n)),e.data.length!==1);)e=e.splitText(1)}}function Ee(e){let t=[],n=[],r=0,i=Array.from(e.childNodes);return i.forEach((e,i)=>{if(_e(e)||ve(e))t.push({nodes:n,start:r,end:i,terminator:e});else if(ge(e)||F(e))n.length>0&&t.push({nodes:n,start:r,end:i,terminator:null}),t.push({nodes:[e],start:i,end:i+1,terminator:null});else{n.push(e);return}n=[],r=i+1}),(n.length>0||t.length===0)&&t.push({nodes:n,start:r,end:i.length,terminator:null}),t}function De(e){return e.nodeType===Node.TEXT_NODE?e.data.trim()===``:!P(e)||e.textContent?.trim()===``&&!e.matches(me)&&!e.querySelector(me)}function Oe(e){return!F(e.nodes[0]??null)&&e.nodes.every(De)}function ke(e,t){let n=I(e,t.commonAncestorContainer,`div, p`);for(;n;){if(Ee(n).filter(e=>!Oe(e)).length>1&&!I(e,n,`li`))return n;n=n.parentElement?I(e,n.parentElement,`div, p`):null}return e}function Ae(e,t,n){let r=document.createRange();return ve(t)&&t.parentNode===e?r.setStart(e,ye(t)+n):r.setStart(t,n),r.collapse(!0),r}function je(e,t,n){let r=Ae(e,n.startContainer,n.startOffset),i=Ae(e,n.endContainer,n.endOffset);if(n.collapsed){let n=t.filter(t=>i.comparePoint(e,t.start)<=0),a=n.find(t=>r.comparePoint(e,t.end)>=0)??n[n.length-1]??t[0];return a?[a]:[]}let a=t=>{if(i.comparePoint(e,t.start)>0)return!1;let n=document.createRange();return n.setStart(e,t.start),n.setEnd(i.startContainer,i.startOffset),n.toString()!==``||n.cloneContents().querySelector(me)!==null},o=t.length;for(;o>0&&!a(t[o-1]);)o--;let s=t.slice(0,o).filter(t=>r.comparePoint(e,t.end)>=0);if(s.length>0)return s;let c=n.cloneRange();return c.collapse(!0),je(e,t,c)}function Me(e,t,n,r){let i=Array.from(t.childNodes).filter(he).filter(e=>n.intersectsNode(e)),a=i[i.length-1],o=t.parentNode;if(!a||!o)return null;let s=be(a);if(s.some(he)){let e=t.cloneNode(!1);z(s,e),o.insertBefore(e,t.nextSibling)}let c=t.nextSibling,l=i.map(e=>{let t=document.createElement(`div`);o.insertBefore(t,c),R(e,`ul`);for(let n of Array.from(e.childNodes))F(n)?o.insertBefore(n,c):t.appendChild(n);return t.firstChild||t.appendChild(document.createElement(`br`)),e.remove(),t});return t.firstElementChild||t.remove(),r.restore(e,l[l.length-1]??e)}function Ne(e,t,n){Te(e);let r=we(t),i=I(e,t.commonAncestorContainer,`ul, ol`);if(i){if(L(i)===n)return Me(e,i,t,r);let a=Se(n);return z(i.childNodes,a),i.replaceWith(a),r.restore(e,a)}let a=ke(e,t),o=je(a,Ee(a),t),s=o[0];if(!s)return null;let c=Se(n);a.insertBefore(c,s.nodes[0]??s.terminator);for(let e of o){let t=e.nodes[0];if(F(t)){z(t.childNodes,c),t.remove();continue}if(o.length>1&&Oe(e)){for(let t of e.nodes)t.parentNode?.removeChild(t);e.terminator?.parentNode?.removeChild(e.terminator);continue}let r=document.createElement(`li`);if(ge(t)){for(;t.firstChild;)r.appendChild(t.firstChild);_e(r.lastChild)&&r.lastChild?.remove(),t.remove()}else{for(let t of e.nodes)r.appendChild(t);e.terminator?.parentNode?.removeChild(e.terminator)}R(r,n),c.appendChild(r)}c.firstChild||c.appendChild(Ce(n));let l=c.previousSibling;F(l)&&L(l)===n&&(z(l.childNodes,c,c.firstChild),l.remove());let u=c.nextSibling;return F(u)&&L(u)===n&&(z(u.childNodes,c),u.remove()),r.restore(e,c.lastElementChild??c,a)}function Pe(e,t){let n=e.lastChild,r=F(n)&&L(n)===t?n:Se(t);r!==n&&e.appendChild(r);let i=r.appendChild(Ce(t)),a=document.createRange();return a.selectNodeContents(i),a.collapse(!1),a}function Fe(e,t){let n=I(e,t.startContainer,`li`),r=I(e,t.endContainer,`li`);if(!n||!r)return[];if(r.contains(n))return[r];let i=Array.from(e.querySelectorAll(`li`)),a=i.slice(i.indexOf(n),i.indexOf(r)+1);return a.filter(e=>!a.some(t=>t!==e&&t.contains(e)))}function Ie(e,t){if(F(e.lastElementChild))return e.lastElementChild;let n=t.cloneNode(!1);return e.appendChild(n),n}function Le(e,t){let n=we(t),r=null;for(let n of Fe(e,t)){let e=n.parentElement,t=n.previousElementSibling;if(!e||!he(t))continue;let i=Ie(t,e);R(n,L(i)),i.appendChild(n),r=n}return r?n.restore(e,r):null}function Re(e,t){let n=we(t),r=null;for(let n of Fe(e,t)){let t=n.parentElement,i=t?.parentElement;if(!t||!i||i===e||!e.contains(i))continue;let a=i.tagName===`LI`?i:F(i)?t:null,o=a?.parentElement;if(!a||!o)continue;let s=be(n);s.length>0&&z(s,Ie(n,t)),R(n,L(o)),o.insertBefore(n,a.nextSibling),t.firstElementChild||t.remove(),r=n}return r?n.restore(e,r):null}var ze=`wema-auto-size`,Be=`wema-note-placed`;function Ve(e,t){let n=parseFloat(t);return n>e&&n-e<1?e+1:e}var He=`wema-foldable`,Ue=`wema-fold-long`,We=`wema-folded`,Ge=[`x`,`y`,`width`,`height`],Ke=(e,t)=>Ge.some(n=>e[n]!==t[n]),qe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,width:n,height:r});function Je(e){return!!e.autoSize||!!e.foldable}function Ye(e){let t=getComputedStyle(e),n=e=>parseFloat(e)||0,r=n(t.lineHeight)||n(t.fontSize)*1.4;return e.scrollHeight-n(t.paddingTop)-n(t.paddingBottom)>r*2.5}var Xe=`wema-note-host-drawn`,Ze=`wema-note-has-footer`,Qe=`wema-note-has-accessory`,$e=`data-wema-focus-key`;function et(e){let t=document.activeElement;if(e&&t&&e.contains(t))return t.getAttribute(`data-wema-focus-key`)??void 0}var tt=class{notes=new Map;elements=new Map;zCounter=1;boardEl;layerEl;emitter;defaultWidth;defaultHeight;defaultColor;readOnly;viewOnly=!1;onMeasure;onLinkClick;hostRender;unreportedSizeBase=new Map;shownRects=new Map;placedRects=new Map;onPlacedMeasure;onUnderChange;onUnderResize;accessory;footer;slots;underHeights=new Map;underObserver=null;labels;unfolded=new Set;editingId=null;imageOverlay;activeImage=null;activeImageNoteId=null;handleImageOverlayDismiss;constructor(e){this.boardEl=e.boardEl,this.layerEl=e.layerEl,this.emitter=e.emitter,this.defaultWidth=e.defaultWidth,this.defaultHeight=e.defaultHeight,this.defaultColor=e.defaultColor,this.readOnly=e.readOnly,this.onMeasure=e.onMeasure,this.onPlacedMeasure=e.onPlacedMeasure,this.onLinkClick=e.onLinkClick,this.hostRender=e.hostRender,this.onUnderChange=e.onUnderChange,this.onUnderResize=e.onUnderResize,this.accessory={elementClass:`wema-note-accessory`,drawnClass:Qe,option:`renderNoteAccessory`,draw:e.hostAccessory,shown:!0,stale:new Set},this.footer={elementClass:`wema-note-footer`,drawnClass:Ze,option:`renderNoteFooter / noteLinks`,draw:e.hostFooter,shown:!1,stale:new Set},this.slots=[this.accessory,this.footer],this.labels=e.labels,(this.accessory.draw||this.footer.draw)&&typeof ResizeObserver<`u`&&(this.underObserver=new ResizeObserver(e=>{let t=!1;for(let{target:n}of e){let e=n.parentElement?.dataset.noteId;e===void 0||this.shownRects.has(e)||this.keepUnderHeight(e)&&(t=!0)}t&&this.onUnderResize()})),this.imageOverlay=v(`div`,`wema-image-overlay`),this.imageOverlay.style.display=`none`,this.imageOverlay.addEventListener(`click`,e=>e.stopPropagation()),this.imageOverlay.addEventListener(`pointerdown`,e=>e.stopPropagation()),this.imageOverlay.addEventListener(`mousedown`,e=>e.preventDefault()),this.boardEl.appendChild(this.imageOverlay),this.handleImageOverlayDismiss=e=>{this.imageOverlay.style.display!==`none`&&(this.imageOverlay.contains(e.target)||e.target!==this.activeImage&&this.hideImageOverlay())},this.boardEl.addEventListener(`click`,this.handleImageOverlayDismiss,!0)}addNote(e){let t=ue(e?.meta),n={id:o(),x:e?.x??100,y:e?.y??100,width:e?.width??this.defaultWidth,height:e?.height??this.defaultHeight,text:e?.text??``,color:e?.color??this.defaultColor,zIndex:e?.zIndex??this.zCounter++,...e?.autoSize?{autoSize:!0}:{},...e?.foldable?{foldable:!0}:{},...t?{meta:t}:{}};return n.zIndex>=this.zCounter&&(this.zCounter=n.zIndex+1),this.notes.set(n.id,n),this.renderNote(n),this.emitter.emit(`note:create`,{note:{...n},origin:`local`}),{...n}}addNoteWithId(e,t=`local`){if(this.notes.has(e.id))return;let n=this.stored(e);n.zIndex>=this.zCounter&&(this.zCounter=n.zIndex+1),this.notes.set(n.id,n),this.renderNote(n),this.emitter.emit(`note:create`,{note:{...n},origin:t})}updateNote(e,t){let n=this.applyParams(e,t);n&&this.emitUpdate(n.note,n.prev)}replayUpdate(e,t,n){let r=this.applyParams(e,t);r&&this.emitter.emit(`note:update`,{note:{...r.note},prev:r.prev,origin:n})}applyParams(e,t){let n=this.notes.get(e);if(!n)return;let r={...n};return Object.assign(n,t,{id:e}),`meta`in t&&(n.meta=ue(t.meta)),!r.foldable!=!n.foldable&&(this.unfolded.delete(e),!n.foldable&&!(`height`in t)&&(n.height=this.openHeight(n)??n.height)),this.updateNoteElement(n,`text`in t),(`text`in t||`meta`in t)&&(this.drawByHost(n),this.requestUnder(e)),(`autoSize`in t||`foldable`in t||`text`in t||`meta`in t||`width`in t||`height`in t)&&this.applyMeasuredSize(n),{note:n,prev:r}}stored(e){let{meta:t,...n}=e,r=ue(t);return r?{...n,meta:r}:n}drawByHost(e){if(!this.hostRender)return!1;let t=this.elements.get(e.id),n=t?.querySelector(`:scope > .wema-note-custom`);if(!t||!n)return!1;n.replaceChildren();let r=!1;try{r=this.hostRender({...e},n)===!0}catch(t){console.error(`Error in renderNote for note "${e.id}":`,t)}let i=t.classList.contains(Xe);return r&&!i&&this.getTextElement(e.id)?.blur(),r||n.replaceChildren(),t.classList.toggle(Xe,r),this.applyEditable(e.id),r!==i}refresh(e){let t=this.notes.get(e);if(!t)return!1;let n=this.drawByHost(t);return Je(t)&&this.measure(e),this.requestUnder(e),n}underElement(e){return this.elements.get(e)?.querySelector(`:scope > .wema-note-under`)??null}slotElement(e,t){return this.underElement(t)?.querySelector(`:scope > .${e.elementClass}`)??null}requestSlot(e,t){e.draw&&e.shown&&this.notes.has(t)&&e.drawing!==t&&(e.stale.add(t),this.onUnderChange())}requestFooter(e){this.requestSlot(this.footer,e)}requestAccessory(e){this.requestSlot(this.accessory,e)}requestUnder(e){this.requestAccessory(e),this.requestFooter(e)}setFootersShown(e){let t=this.footer;if(t.draw&&t.shown!==e){if(t.shown=e,e)t.stale=new Set(this.notes.keys()),this.onUnderChange();else{t.stale.clear();for(let e of this.notes.keys())this.emptySlot(t,e);for(let e of this.notes.keys())this.keepUnderHeight(e)}}}drawUnder(){let e=new Set;for(let t of this.slots)this.drawSlot(t,e);let t=!1;for(let n of e)this.keepUnderHeight(n)&&(t=!0);return t}keepUnderHeight(e){let t=this.drawnUnder(e)?.offsetHeight??0;return t!==(this.underHeights.get(e)??0)&&(t>0?this.underHeights.set(e,t):this.underHeights.delete(e),!0)}drawSlot(e,t){let n=e.draw;if(!n||e.stale.size===0)return;let r=e.stale;e.stale=new Set;for(let i of r){let r=this.notes.get(i),a=this.elements.get(i),o=this.slotElement(e,i);if(!r||!a||!o)continue;let s=et(o);o.replaceChildren();let c=!1;e.drawing=i;try{c=n({...r},o)===!0}catch(t){console.error(`Error in ${e.option} for note "${i}":`,t)}finally{e.drawing=void 0}c||o.replaceChildren(),a.classList.toggle(e.drawnClass,c),this.watchUnder(i),t.add(i),c&&s!==void 0&&Array.from(o.querySelectorAll(`[${$e}]`)).find(e=>e.getAttribute($e)===s)?.focus({preventScroll:!0})}}emptySlot(e,t){this.slotElement(e,t)?.replaceChildren(),this.elements.get(t)?.classList.remove(e.drawnClass),this.watchUnder(t)}hasUnder(e){return this.slots.some(t=>e.classList.contains(t.drawnClass))}drawnUnder(e){let t=this.elements.get(e);return t&&this.hasUnder(t)?this.underElement(e):null}watchUnder(e){let t=this.underElement(e);t&&this.underObserver&&(this.drawnUnder(e)?this.underObserver.observe(t):this.underObserver.unobserve(t))}isHostDrawn(e){return this.elements.get(e)?.classList.contains(Xe)??!1}getTextElement(e){return this.isHostDrawn(e)?null:this.contentElement(e)}editContent(e,t){let n=this.getTextElement(e);if(!n||!this.isEditable(e))return!1;let r=t(n,w(n));return r?(n.focus(),T(r),this.syncNoteContent(e),!0):!1}contentElement(e){return this.elements.get(e)?.querySelector(`.wema-note-content`)??null}isEditable(e){return!this.readOnly&&!this.viewOnly&&!this.isHostDrawn(e)}applyEditable(e){let t=this.contentElement(e);if(!t)return;let n=this.isEditable(e);t.contentEditable=n?`true`:`false`,n||t.blur()}emitUpdate(e,t){let n=this.unreportedSizeBase.get(e.id);this.unreportedSizeBase.delete(e.id),this.emitter.emit(`note:update`,{note:{...e},prev:n?{...t,...n}:t,origin:`local`})}applyFold(e,t){if(!e.foldable&&!t.classList.contains(Ue))return;let n=t.querySelector(`:scope > .wema-note-content`),r=t.querySelector(`:scope > .wema-note-fold-toggle`);if(!n||!r||t.offsetWidth===0&&t.offsetHeight===0)return;t.classList.remove(We);let i=!!e.foldable&&!t.classList.contains(Xe)&&Ye(n),a=i&&!this.unfolded.has(e.id)&&this.editingId!==e.id;t.classList.toggle(Ue,i),t.classList.toggle(We,a);let o=a?this.labels.readMore:this.labels.showLess;r.textContent!==o&&(r.textContent=o),a&&(n.scrollTop=0)}toggleFold(e){let t=this.elements.get(e)?.classList.contains(We)??!1;this.editingId===e&&(this.contentElement(e)?.blur(),this.editingId=null),t?this.unfolded.add(e):this.unfolded.delete(e),this.measure(e)}openHeight(e){let t=this.elements.get(e.id);if(t&&!this.isHostDrawn(e.id))return!this.shownRects.has(e.id)&&!this.placedRects.has(e.id)&&(t.style.width=`${e.width}px`),this.atModelWidth(e,t,()=>(t.classList.remove(We,Ue),t.offsetHeight||void 0))}applyMeasuredSize(e){let t=this.elements.get(e.id);return!t||!this.isSizedByContent(e)&&!t.classList.contains(Ue)?!1:this.atModelWidth(e,t,()=>this.readMeasuredSize(e,t))}atModelWidth(e,t,n){let r=t.classList.contains(Be),i=this.shownRects.get(e.id)??this.placedRects.get(e.id);if(!r&&(!i||i.width===e.width))return n();t.classList.remove(Be),t.style.width=`${e.width}px`;try{return n()}finally{i&&(t.style.width=`${i.width}px`),t.classList.toggle(Be,r),r&&this.applyFold(e,t)}}readMeasuredSize(e,t){if(this.applyFold(e,t),!this.isSizedByContent(e))return!1;let n=e.autoSize?t.offsetWidth:e.width,r=t.offsetHeight;return n===0||r===0||n===e.width&&r===e.height?!1:(e.width=n,e.height=r,!0)}measure(e){let t=this.notes.get(e);if(!t)return;let n={width:t.width,height:t.height},r=this.applyMeasuredSize(t),i=this.placedRects.get(e),a=i&&this.elements.get(e);if(i&&a&&this.sizesAtWidth([{note:t,el:a,width:i.width}])[0].height!==i.height&&this.onPlacedMeasure(e),!r)return;let o=this.unreportedSizeBase.get(e)??n;o.width===t.width&&o.height===t.height?this.unreportedSizeBase.delete(e):this.unreportedSizeBase.set(e,o),this.onMeasure(e,n)}remeasure(e){this.measure(e)}hasMeasuredHeight(e){return!!this.notes.get(e)?.foldable&&!this.isHostDrawn(e)}isSizedByContent(e){return!!e.autoSize||this.hasMeasuredHeight(e.id)}resizeToContent(e){let t=this.notes.get(e),n=this.elements.get(e);if(!t||!n||t.autoSize)return;let{width:r,height:i}=this.atModelWidth(t,n,()=>{n.classList.add(ze);let e=getComputedStyle(n),t={width:Ve(n.offsetWidth,e.width),height:Ve(n.offsetHeight,e.height)};return n.classList.remove(ze),t});r!==0&&i!==0&&(r!==t.width||i!==t.height)&&this.updateNote(e,{width:r,height:i})}deleteNote(e,t=`local`){let n=this.notes.get(e);if(!n)return;let r=this.underElement(e);r&&this.underObserver?.unobserve(r);let i=this.elements.get(e);i&&(i.remove(),this.elements.delete(e)),this.notes.delete(e),this.unreportedSizeBase.delete(e),this.shownRects.delete(e),this.placedRects.delete(e),this.underHeights.delete(e),this.unfolded.delete(e),this.editingId===e&&(this.editingId=null),this.emitter.emit(`note:delete`,{note:{...n},origin:t})}getNote(e){let t=this.notes.get(e);return t?{...t}:void 0}setShownRect(e,t){if(t)this.shownRects.set(e,t);else if(!this.shownRects.delete(e))return;let n=this.notes.get(e),r=this.elements.get(e);n&&r&&this.applyStyles(r,n);let i=t?null:this.drawnUnder(e);i&&this.underObserver&&(this.underObserver.unobserve(i),this.underObserver.observe(i))}placeNotes(e,t,n){let r=new Map;for(let[e,t]of this.notes)r.set(e,this.placedRects.get(e)??qe(t));let i=new Set(e),a=new Set;for(let e of[...this.placedRects.keys()])i.has(e)||(this.placedRects.delete(e),a.add(e));let o=[],s=[];for(let e of i){let n=this.notes.get(e),i=this.elements.get(e);if(!n||!i)continue;let a={...r.get(e),width:t??n.width};(!this.placedRects.has(e)||this.placedRects.get(e).width!==a.width)&&s.push({note:n,el:i}),this.placedRects.set(e,a),o.push({note:n,el:i})}for(let{note:e,el:t}of s)this.applyStyles(t,e);for(let{note:e,el:t}of s)this.applyFold(e,t);let c=this.sizesAtWidth(o.map(({note:e,el:t})=>({note:e,el:t,width:this.placedRects.get(e.id).width}))),l=o.map(({note:e},t)=>{let n=this.placedRects.get(e.id),{height:r,under:i}=c[t];return n.height=r,i>0?this.underHeights.set(e.id,i):this.underHeights.delete(e.id),{...e,width:n.width,height:r+i}});for(let e of n(l)){let t=this.placedRects.get(e.id);t&&(e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y))}let u=[];for(let[e,t]of this.notes){if(!Ke(this.placedRects.get(e)??t,r.get(e))&&!a.has(e))continue;u.push(e);let n=this.elements.get(e);n&&this.applyStyles(n,t)}return u}sizesAtWidth(e){let t=e.map(({note:e,el:t,width:n})=>{let r=this.isSizedByContent(e),i=this.drawnUnder(e.id),a=this.shownRects.get(e.id);return{note:e,el:t,width:n,sized:r,under:i,restore:(r||i!==null)&&a!==void 0&&a.width!==n?a.width:void 0}}),n=t.filter(e=>e.restore!==void 0);for(let{el:e,width:t}of n)e.style.width=`${t}px`;for(let{note:e,el:t,sized:r}of n)r&&this.applyFold(e,t);let r=t.map(({note:e,el:t,sized:n,under:r})=>({height:n&&t.offsetHeight||e.height,under:r?.offsetHeight??0}));for(let{el:e,restore:t}of n)e.style.width=`${t}px`;return r}getPlacedNote(e){let t=this.notes.get(e);if(t)return{...t,...this.placedRects.get(e)}}isPlaced(e){return this.placedRects.has(e)}getPlacedBoxes(){return Array.from(this.notes.values(),e=>{let t={...e,...this.placedRects.get(e.id)};return t.height+=this.underHeights.get(e.id)??0,t})}getShownBox(e){let t=this.getShownNote(e),n=this.underHeights.get(e);return t&&n?{...t,height:t.height+n}:t}getShownNote(e){let t=this.notes.get(e);if(!t)return;let n=this.shownRects.get(e);if(!n)return this.getPlacedNote(e);let r={...n},i=this.isSizedByContent(t)?this.elements.get(e):void 0;return i&&(t.autoSize&&(r.width=i.offsetWidth||r.width),r.height=i.offsetHeight||r.height),{...t,...r}}getNotes(){return Array.from(this.notes.values()).map(e=>({...e}))}lowestBottom(e){let t=null;for(let n of this.notes.values()){if(!e(n.id))continue;let r=this.placedRects.get(n.id)??n;t=Math.max(t??-1/0,r.y+r.height+(this.underHeights.get(n.id)??0))}return t}getElement(e){return this.elements.get(e)}bringToFront(e){let t=this.notes.get(e);t&&(t.zIndex=this.zCounter++,this.updateNoteElement(t,!1))}setReadOnly(e){this.readOnly=e;for(let[t,n]of this.elements){this.applyEditable(t);let r=n.querySelector(`.wema-resize-handle`);r&&(r.style.display=e?`none`:``);let i=n.querySelector(`.wema-move-handle`);i&&(i.style.visibility=e?`hidden`:``)}}setViewOnly(e){this.viewOnly=e;for(let[t,n]of this.elements){this.applyEditable(t);let r=n.querySelector(`.wema-resize-handle`);r&&(r.style.display=e||this.readOnly?`none`:``);let i=n.querySelector(`.wema-move-handle`);i&&(i.style.visibility=this.readOnly?`hidden`:``)}}getNotesWithLiveText(){return Array.from(this.notes.values()).map(e=>{let t=this.getTextElement(e.id);return{...e,text:t?t.innerHTML:e.text}})}destroy(){this.boardEl.removeEventListener(`click`,this.handleImageOverlayDismiss,!0);for(let e of this.slots)e.shown=!1,e.stale.clear();this.underObserver?.disconnect(),this.imageOverlay.remove()}showImageOverlay(e,t){this.activeImage=e,this.activeImageNoteId=t,e.classList.add(`wema-image-selected`),this.imageOverlay.innerHTML=``;for(let n of[{label:`S`,width:`25%`},{label:`M`,width:`50%`},{label:`L`,width:`75%`},{label:`100%`,width:`100%`}]){let r=v(`button`,`wema-image-overlay-btn`);r.textContent=n.label,r.title=n.width,(e.style.width===n.width||!e.style.width&&n.width===`100%`)&&r.classList.add(`active`),r.addEventListener(`click`,()=>{e.style.width=n.width,this.syncNoteContent(t),this.showImageOverlay(e,t)}),this.imageOverlay.appendChild(r)}let n=v(`button`,`wema-image-overlay-btn wema-image-overlay-delete`);n.textContent=`✕`,y(n,this.labels.deleteImage),n.addEventListener(`click`,()=>{e.remove(),this.hideImageOverlay(),this.syncNoteContent(t)}),this.imageOverlay.appendChild(n),this.imageOverlay.style.display=``,this.updateOverlayPosition()}updateOverlayPosition(){this.activeImage&&b(this.imageOverlay,this.boardEl,x(this.activeImage,this.boardEl),`above`,4)}hideImageOverlay(){this.imageOverlay.style.display=`none`,this.activeImage&&this.activeImage.classList.remove(`wema-image-selected`),this.activeImage=null,this.activeImageNoteId=null}syncNoteContent(e){let t=this.getTextElement(e);if(!t)return;let n=this.notes.get(e);if(!n)return;let r={...n};n.text=t.innerHTML,n.text!==r.text&&this.requestUnder(e);let i=this.applyMeasuredSize(n);(n.text!==r.text||i||this.unreportedSizeBase.has(e))&&this.emitUpdate(n,r)}clear(){for(let e of this.elements.values())e.remove();this.elements.clear(),this.notes.clear(),this.unreportedSizeBase.clear(),this.shownRects.clear(),this.placedRects.clear();for(let e of this.slots)e.stale.clear();this.underHeights.clear(),this.underObserver?.disconnect(),this.unfolded.clear(),this.editingId=null,this.zCounter=1}renderAll(e){this.clear();for(let t of e)this.notes.set(t.id,this.stored(t)),t.zIndex>=this.zCounter&&(this.zCounter=t.zIndex+1),this.renderNote(this.notes.get(t.id),!1);for(let e of this.notes.values())Je(e)&&this.applyMeasuredSize(e)}renderNote(e,t=!0){let n=v(`div`,`wema-note`);n.dataset.noteId=e.id;let r=v(`div`,`wema-move-handle`);r.style.position=`relative`,r.innerHTML=`<svg width="20" height="10" viewBox="0 0 20 10"><circle cx="4" cy="3" r="1.5" fill="currentColor"/><circle cx="10" cy="3" r="1.5" fill="currentColor"/><circle cx="16" cy="3" r="1.5" fill="currentColor"/><circle cx="4" cy="8" r="1.5" fill="currentColor"/><circle cx="10" cy="8" r="1.5" fill="currentColor"/><circle cx="16" cy="8" r="1.5" fill="currentColor"/></svg>`,this.readOnly&&(r.style.visibility=`hidden`);let i=v(`div`,`wema-note-content`);i.innerHTML=N(e.text)?M(e.text):ae(e.text);let a=!1;i.addEventListener(`input`,()=>{a=!0,this.measure(e.id)}),i.addEventListener(`focus`,()=>{this.editingId=e.id,this.measure(e.id)}),i.addEventListener(`blur`,()=>{this.editingId===e.id&&(this.editingId=null),this.measure(e.id),a&&(a=!1,this.syncNoteContent(e.id))}),i.addEventListener(`paste`,e=>{e.preventDefault();let t=e.clipboardData?.getData(`text/html`),n=e.clipboardData?.getData(`text/plain`)??``;le(t?ae(t,{pasted:!0}):M(n).replace(/\n/g,`<br>`)),a=!0}),i.addEventListener(`click`,t=>{let n=t.target;if(n.tagName===`INPUT`&&n.type===`checkbox`){setTimeout(()=>{let t=n;t.checked?t.setAttribute(`checked`,``):t.removeAttribute(`checked`);let r=n.closest(`li`);r&&r.classList.toggle(`wema-checked`,t.checked),a=!0,this.syncNoteContent(e.id)},0);return}if(n.tagName===`A`||n.closest(`a`)){let e=n.tagName===`A`?n:n.closest(`a`);t.preventDefault();let r=e.getAttribute(`href`),i=r?j(r):null;i&&this.onLinkClick?.(i,t)!==!0&&window.open(i,`_blank`,`noopener`);return}n.tagName===`IMG`&&(t.preventDefault(),!this.readOnly&&!this.viewOnly&&this.showImageOverlay(n,e.id))}),i.addEventListener(`keydown`,t=>{if(t.key!==`Tab`||t.isComposing||t.ctrlKey||t.metaKey||t.altKey||!this.isEditable(e.id))return;let n=w(i);if(!n||!xe(i,n))return;t.preventDefault();let r=t.shiftKey?Re:Le;this.editContent(e.id,(e,t)=>t&&r(e,t))}),i.addEventListener(`keydown`,t=>{if(t.key!==`Enter`||t.isComposing||!this.isEditable(e.id))return;let n=document.getSelection();if(!n||n.rangeCount===0)return;let r=(n.anchorNode?.nodeType===Node.TEXT_NODE?n.anchorNode.parentElement:n.anchorNode)?.closest(`li`);if(!r||!r.parentElement||L(r.parentElement)!==`checklist`)return;t.preventDefault();let i=Ce(`checklist`);i.appendChild(document.createTextNode(` `));let o=n.getRangeAt(0),s=document.createRange();s.setStart(o.endContainer,o.endOffset),s.setEndAfter(r.lastChild??r);let c=s.extractContents();for(let e of Array.from(c.children))e.tagName===`INPUT`&&e.type===`checkbox`&&e.remove();i.appendChild(c),r.parentNode?.insertBefore(i,r.nextSibling);let l=document.createRange();l.setStart(i,2),l.collapse(!0),T(l),a=!0});let o=v(`div`,`wema-note-anchors`);for(let e of[`top`,`right`,`bottom`,`left`]){let t=v(`div`,`wema-anchor wema-anchor-${e}`);t.dataset.anchor=e,o.appendChild(t)}let s=v(`div`,`wema-resize-handle`);(this.readOnly||this.viewOnly)&&(s.style.display=`none`);for(let e of[`top`,`right`,`bottom`,`left`]){let t=v(`div`,`wema-note-collapse-btn`);t.dataset.side=e,t.style.display=`none`,t.addEventListener(`pointerdown`,e=>e.stopPropagation()),t.addEventListener(`click`,e=>e.stopPropagation()),n.appendChild(t)}n.appendChild(r),n.appendChild(i),n.appendChild(v(`div`,`wema-note-custom`));let c=v(`button`,`wema-note-fold-toggle`);c.type=`button`,c.addEventListener(`pointerdown`,e=>e.stopPropagation()),c.addEventListener(`mousedown`,e=>e.preventDefault()),c.addEventListener(`click`,t=>{t.stopPropagation(),this.toggleFold(e.id)}),n.appendChild(c),n.appendChild(o),n.appendChild(s);let l=this.slots.filter(e=>e.draw);if(l.length>0){let e=v(`div`,`wema-note-under`);for(let t of[`pointerdown`,`click`,`dblclick`,`keydown`])e.addEventListener(t,e=>e.stopPropagation());for(let t of l)e.appendChild(v(`div`,t.elementClass));n.appendChild(e)}this.applyStyles(n,e),this.layerEl.appendChild(n),this.elements.set(e.id,n),this.applyEditable(e.id),this.drawByHost(e),this.requestUnder(e.id),t&&Je(e)&&this.applyMeasuredSize(e)}updateNoteElement(e,t){let n=this.elements.get(e.id);if(!n)return;this.applyStyles(n,e);let r=n.querySelector(`.wema-note-content`);t&&r&&r.innerHTML!==e.text&&document.activeElement!==r&&(r.innerHTML=N(e.text)?M(e.text):ae(e.text)),Je(e)&&requestAnimationFrame(()=>this.measure(e.id))}applyStyles(e,t){let n=this.placedRects.get(t.id),r=this.shownRects.get(t.id)??n??t;e.classList.toggle(Be,n!==void 0),E(e,{left:`${r.x}px`,top:`${r.y}px`,width:`${r.width}px`,height:`${r.height}px`,zIndex:String(t.zIndex)}),e.style.setProperty(`--wema-note-color`,t.color),e.classList.toggle(ze,!!t.autoSize),e.classList.toggle(He,!!t.foldable)}},nt=e=>1-(1-e)**3,rt=(e,t,n)=>e+(t-e)*n;function it(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}var at=class{noteManager;onFrame;running=new Map;frameId=0;constructor(e){this.noteManager=e.noteManager,this.onFrame=e.onFrame}start(e,t,n){this.running.set(e,{from:{...t},start:performance.now(),duration:n}),this.noteManager.setShownRect(e,t),this.frameId||=requestAnimationFrame(()=>this.tick())}cancel(e){return this.running.delete(e)?(this.noteManager.setShownRect(e,null),!0):!1}isRunning(){return this.running.size>0}clear(){this.running.clear(),this.frameId&&cancelAnimationFrame(this.frameId),this.frameId=0}tick(){this.frameId=0;let e=performance.now(),t=[];for(let[n,{from:r,start:i,duration:a}]of this.running){let o=this.noteManager.getPlacedNote(n),s=(e-i)/a;if(!o||s>=1)this.running.delete(n),this.noteManager.setShownRect(n,null);else{let e=nt(s);this.noteManager.setShownRect(n,{x:rt(r.x,o.x,e),y:rt(r.y,o.y,e),width:rt(r.width,o.width,e),height:rt(r.height,o.height,e)})}o&&t.push(n)}t.length>0&&this.onFrame(t),this.running.size>0&&(this.frameId=requestAnimationFrame(()=>this.tick()))}},ot=`${C}, a, button, label, summary, video[controls], audio[controls], [data-wema-no-drag]`;function st(e,t){let n=e.getBoundingClientRect();if(n.width===0||e.offsetWidth===0)return!1;let r=n.width/e.offsetWidth;return t.clientX-n.left>(e.clientLeft+e.clientWidth)*r||t.clientY-n.top>(e.clientTop+e.clientHeight)*r}var ct=class{state=`IDLE`;ctx=null;boardEl;noteManager;getReadOnly;getSelection;toBoardPoint;onDragStart;onDragEnd;handlePointerDown;handlePointerMove;handlePointerUp;constructor(e){this.toBoardPoint=e.toBoardPoint,this.boardEl=e.boardEl,this.noteManager=e.noteManager,this.getReadOnly=e.getReadOnly,this.getSelection=e.getSelection,this.onDragStart=e.onDragStart,this.onDragEnd=e.onDragEnd,this.handlePointerDown=this.onPointerDown.bind(this),this.handlePointerMove=this.onPointerMove.bind(this),this.handlePointerUp=this.onPointerUp.bind(this),this.boardEl.addEventListener(`pointerdown`,this.handlePointerDown)}destroy(){this.boardEl.removeEventListener(`pointerdown`,this.handlePointerDown),this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp),this.state=`IDLE`,this.ctx=null}onPointerDown(e){if(e.button!==0||this.getReadOnly())return;let t=e.target,n=t.closest(`.wema-note-custom`),r=n?.parentElement,i=!!r&&this.noteManager.getElement(r.dataset.noteId??``)===r,a=n!==null&&i&&t.closest(ot)===null&&!(t===n&&st(n,e));if(!t.closest(`.wema-move-handle`)&&!a)return;let o=t.closest(`.wema-note`);if(!o)return;e.preventDefault();let s=o.dataset.noteId;if(!s)return;let c=this.noteManager.getNote(s);if(!c)return;let l=this.getSelection(),u=null;if(l.length>1&&l.includes(s)){u=[];for(let e of l){let t=this.noteManager.getNote(e);t&&u.push({id:e,startX:t.x,startY:t.y})}}let d=this.toBoardPoint(e.clientX,e.clientY);this.ctx={noteId:s,startX:d.x,startY:d.y,startClientX:e.clientX,startClientY:e.clientY,noteStartX:c.x,noteStartY:c.y,pointerId:e.pointerId,groupOffsets:u},this.state=`PENDING`,this.boardEl.addEventListener(`pointermove`,this.handlePointerMove),this.boardEl.addEventListener(`pointerup`,this.handlePointerUp)}onPointerMove(e){if(!this.ctx)return;let t=this.toBoardPoint(e.clientX,e.clientY),n=t.x-this.ctx.startX,r=t.y-this.ctx.startY;if(this.state===`PENDING`){if(Math.abs(e.clientX-this.ctx.startClientX)<4&&Math.abs(e.clientY-this.ctx.startClientY)<4)return;this.state=`DRAGGING`,this.onDragStart?.(),this.boardEl.setPointerCapture(this.ctx.pointerId),this.noteManager.bringToFront(this.ctx.noteId)}if(this.state===`DRAGGING`){if(this.ctx.groupOffsets)for(let e of this.ctx.groupOffsets)this.noteManager.updateNote(e.id,{x:e.startX+n,y:e.startY+r});else{let e=this.ctx.noteStartX+n,t=this.ctx.noteStartY+r;this.noteManager.updateNote(this.ctx.noteId,{x:e,y:t})}}}onPointerUp(e){if(!this.ctx)return;this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp);let t=this.state===`DRAGGING`;if(t)try{this.boardEl.releasePointerCapture(this.ctx.pointerId)}catch{}let n=this.ctx.noteId;this.state=`IDLE`,this.ctx=null,t&&this.onDragEnd?.(n)}},lt=class{selected=new Set;noteManager;emitter;layerEl;isSelectable;rubberBandEl=null;rubberBandStart=null;rubberBandActive=!1;constructor(e){this.layerEl=e.layerEl,this.noteManager=e.noteManager,this.emitter=e.emitter,this.isSelectable=e.isSelectable}canSelect(e){return this.noteManager.getNote(e)!==void 0&&this.isSelectable(e)}select(e){for(let e of this.selected)this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`);this.selected.clear();for(let t of e)this.canSelect(t)&&(this.selected.add(t),this.noteManager.getElement(t)?.classList.add(`wema-note-selected`));this.emitter.emit(`note:select`,{noteIds:this.getSelection()})}selectAll(){let e=this.noteManager.getNotes().map(e=>e.id);this.select(e)}getSelection(){return Array.from(this.selected)}addToSelection(e){for(let t of e)this.canSelect(t)&&!this.selected.has(t)&&(this.selected.add(t),this.noteManager.getElement(t)?.classList.add(`wema-note-selected`));this.emitter.emit(`note:select`,{noteIds:this.getSelection()})}toggleSelection(e){this.selected.has(e)?(this.selected.delete(e),this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`)):this.canSelect(e)&&(this.selected.add(e),this.noteManager.getElement(e)?.classList.add(`wema-note-selected`)),this.emitter.emit(`note:select`,{noteIds:this.getSelection()})}deselect(e){this.selected.has(e)&&(this.selected.delete(e),this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`))}clear(){if(this.selected.size!==0){for(let e of this.selected)this.noteManager.getElement(e)?.classList.remove(`wema-note-selected`);this.selected.clear(),this.emitter.emit(`note:select`,{noteIds:[]})}}startRubberBand(e,t){this.rubberBandStart={x:e,y:t},this.rubberBandActive=!0,this.rubberBandEl=v(`div`,`wema-rubberband`),this.rubberBandEl.style.left=`${e}px`,this.rubberBandEl.style.top=`${t}px`,this.rubberBandEl.style.width=`0`,this.rubberBandEl.style.height=`0`,this.layerEl.appendChild(this.rubberBandEl)}updateRubberBand(e,t){if(!this.rubberBandStart||!this.rubberBandEl)return;let n=Math.min(e,this.rubberBandStart.x),r=Math.min(t,this.rubberBandStart.y),i=Math.abs(e-this.rubberBandStart.x),a=Math.abs(t-this.rubberBandStart.y);this.rubberBandEl.style.left=`${n}px`,this.rubberBandEl.style.top=`${r}px`,this.rubberBandEl.style.width=`${i}px`,this.rubberBandEl.style.height=`${a}px`;let o={left:n,top:r,right:n+i,bottom:r+a},s=[];for(let{id:e}of this.noteManager.getNotes()){let t=this.noteManager.getShownNote(e),n=t.x+t.width,r=t.y+t.height;t.x<o.right&&n>o.left&&t.y<o.bottom&&r>o.top&&s.push(t.id)}this.select(s)}endRubberBand(){this.rubberBandEl&&=(this.rubberBandEl.remove(),null),this.rubberBandStart=null,this.rubberBandActive=!1}isRubberBandActive(){return this.rubberBandActive}destroy(){this.endRubberBand(),this.clear()}},ut=`wema-arrowhead`,dt=[8,12,18],ft=12;function pt(e){return e.arrowHead??(e.style===`arrow`?`end`:`none`)}var mt=class{edges=new Map;groupElements=new Map;pathElements=new Map;hitElements=new Map;labelElements=new Map;svgEl;emitter;noteManager;selectedEdge=null;constructor(e){this.svgEl=e.svgEl,this.emitter=e.emitter,this.noteManager=e.noteManager,this.ensureMarkerDefs()}hitTest(e,t){let n=document.elementsFromPoint(e,t);for(let e of n)if(e.classList.contains(`wema-edge-hit`)){let t=e.dataset.edgeId;if(t&&this.edges.has(t))return t}return null}addEdge(e,t,n){if(e===t||!this.noteManager.getNote(e)||!this.noteManager.getNote(t))return;let r={id:o(),from:e,to:t,fromAnchor:n?.fromAnchor??`auto`,toAnchor:n?.toAnchor??`auto`,style:n?.style??`arrow`,label:n?.label};return this.edges.set(r.id,r),this.renderEdge(r),this.emitter.emit(`edge:create`,{edge:{...r},origin:`local`}),{...r}}addEdgeWithId(e,t=`local`){if(this.edges.has(e.id)||!this.noteManager.getNote(e.from)||!this.noteManager.getNote(e.to))return;let n={...e};this.edges.set(n.id,n),this.renderEdge(n),this.emitter.emit(`edge:create`,{edge:{...n},origin:t})}deleteEdge(e,t=`local`){let n=this.edges.get(e);n&&(this.removeEdgeElements(e),this.edges.delete(e),this.selectedEdge===e&&(this.selectedEdge=null),this.emitter.emit(`edge:delete`,{edge:{...n},origin:t}))}updateEdge(e,t,n=`local`){let r=this.edges.get(e);if(!r)return;let i={...r};Object.assign(r,t,{id:r.id,from:r.from,to:r.to});let a=this.pathElements.get(e);a&&this.applyEdgeStyle(a,r),this.updateEdgePath(e),this.emitter.emit(`edge:update`,{edge:{...r},prev:i,origin:n})}getEdge(e){let t=this.edges.get(e);return t?{...t}:void 0}getEdges(){return Array.from(this.edges.values()).map(e=>({...e}))}getEdgesOf(e){let t=[];for(let n of this.edges.values())(n.from===e||n.to===e)&&t.push({...n});return t}getSelectedEdge(){return this.selectedEdge}selectEdge(e){this.deselectEdge(),this.selectedEdge=e,this.pathElements.get(e)?.classList.add(`wema-edge-selected`)}deselectEdge(){this.selectedEdge&&=(this.pathElements.get(this.selectedEdge)?.classList.remove(`wema-edge-selected`),null)}updateEdgesOf(e){this.updateEdgesOfNotes([e])}updateEdgesOfNotes(e){let t=new Set(e),n=[],r=new Map;for(let[e,i]of this.edges)if(t.has(i.from)||t.has(i.to)){n.push(e);for(let e of[i.from,i.to])r.has(e)||r.set(e,this.noteManager.getShownNote(e))}for(let e of n)this.updateEdgePath(e,r)}clear(){for(let e of this.edges.keys())this.removeEdgeElements(e);this.edges.clear(),this.selectedEdge=null}renderAll(e){this.clear();for(let t of e)this.edges.set(t.id,{...t}),this.renderEdge(this.edges.get(t.id))}applyVisibility(e){for(let[t]of this.edges){let n=this.groupElements.get(t);n&&(n.style.display=e.has(t)?`none`:``)}}destroy(){this.clear()}ensureMarkerDefs(){let e=this.svgEl.querySelector(`defs`);e||(e=S(`defs`),this.svgEl.prepend(e));for(let t of dt){let n=`${ut}-${t}`;if(!e.querySelector(`#${n}`)){let r=S(`marker`);r.id=n,r.setAttribute(`viewBox`,`0 0 10 10`),r.setAttribute(`refX`,`10`),r.setAttribute(`refY`,`5`),r.setAttribute(`markerWidth`,String(t)),r.setAttribute(`markerHeight`,String(t)),r.setAttribute(`markerUnits`,`userSpaceOnUse`),r.setAttribute(`orient`,`auto-start-reverse`);let i=S(`path`);i.setAttribute(`d`,`M 0 0 L 10 5 L 0 10 Z`),i.setAttribute(`class`,`wema-arrow-fill`),r.appendChild(i),e.appendChild(r)}}}renderEdge(e){let t=this.noteManager.getNote(e.from),n=this.noteManager.getNote(e.to);if(!t||!n)return;let r=S(`g`,`wema-edge-group`);r.dataset.edgeId=e.id;let i=S(`path`,`wema-edge-hit`);i.dataset.edgeId=e.id,i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`stroke-width`,`20`),i.style.pointerEvents=`all`;let a=S(`path`,`wema-edge-path`);if(a.setAttribute(`fill`,`none`),a.dataset.edgeId=e.id,this.applyEdgeStyle(a,e),r.appendChild(i),r.appendChild(a),e.label){let t=S(`text`,`wema-edge-label`);t.textContent=e.label,t.setAttribute(`text-anchor`,`middle`),t.setAttribute(`dy`,`-6`),r.appendChild(t),this.labelElements.set(e.id,t)}this.svgEl.appendChild(r),this.groupElements.set(e.id,r),this.hitElements.set(e.id,i),this.pathElements.set(e.id,a),this.updateEdgePath(e.id)}updateEdgePath(e,t){let n=this.edges.get(e);if(!n)return;let r=t?t.get(n.from):this.noteManager.getShownNote(n.from),i=t?t.get(n.to):this.noteManager.getShownNote(n.to);if(!r||!i)return;let a=h(r,i,n.fromAnchor,n.toAnchor,n.routing),o=this.pathElements.get(e),s=this.hitElements.get(e);o?.setAttribute(`d`,a),s?.setAttribute(`d`,a);let c=this.labelElements.get(e);if(c){let e=(r.x+r.width/2+i.x+i.width/2)/2,t=(r.y+r.height/2+i.y+i.height/2)/2;c.setAttribute(`x`,String(e)),c.setAttribute(`y`,String(t))}}applyEdgeStyle(e,t){let n=t.lineStyle??(t.style===`dashed`?`dashed`:`solid`),r=pt(t),i=t.strokeWidth??2,a=t.arrowSize??ft;switch(n){case`solid`:e.removeAttribute(`stroke-dasharray`);break;case`dashed`:e.setAttribute(`stroke-dasharray`,`8 4`);break;case`dotted`:e.setAttribute(`stroke-dasharray`,`3 3`)}let o=`url(#${`${ut}-${a}`})`;r===`end`||r===`both`?e.setAttribute(`marker-end`,o):e.removeAttribute(`marker-end`),r===`start`||r===`both`?e.setAttribute(`marker-start`,o):e.removeAttribute(`marker-start`),e.style.strokeWidth=`${i}px`}removeEdgeElements(e){this.groupElements.get(e)?.remove(),this.groupElements.delete(e),this.pathElements.delete(e),this.hitElements.delete(e),this.labelElements.get(e)?.remove(),this.labelElements.delete(e)}},ht=[`out`,`in`,`both`,`none`],gt={out:`→`,in:`←`,both:`↔`,none:`―`},_t={out:`linkOut`,in:`linkIn`,both:`linkBoth`,none:`linkNone`},vt=`wema-note-link-target`,yt=1400,bt=new Set([`ADDRESS`,`BLOCKQUOTE`,`BR`,`DD`,`DIV`,`DL`,`DT`,`FIGURE`,`H1`,`H2`,`H3`,`H4`,`H5`,`H6`,`HR`,`IFRAME`,`LI`,`OL`,`P`,`PRE`,`TABLE`,`TD`,`TH`,`TR`,`UL`]),xt=new Set([`template`,`iframe`,`video`,`audio`]),St=/[​]/g,Ct=e=>{let t=e.nodeName.toLowerCase();return O.has(t)||xt.has(t)||e.style?.display===`none`};function wt(e,t){for(let n of e.childNodes)if(n.nodeType===Node.TEXT_NODE){let[e,...r]=(n.nodeValue??``).split(`
4
- `);t[t.length-1]+=e,t.push(...r)}else if(n.nodeType===Node.ELEMENT_NODE&&!Ct(n)){let e=bt.has(n.nodeName);e&&t.push(``),wt(n,t),e&&t.push(``)}}function Tt(e){let t;N(e)?t=e.split(`
5
- `):(t=[``],wt(new DOMParser().parseFromString(`<body>${e}</body>`,`text/html`).body,t));for(let e of t){let t=e.replace(St,``).trim();if(t!==``)return t}return``}function Et(e,t){let n=t?.get(e.id);if(n&&n.text===e.text)return n.line;let r=Tt(e.text);return t?.set(e.id,{text:e.text,line:r}),r}var Dt=(e,t)=>e.from===t?e.to:e.from;function Ot(e,t){let n=pt(e);return n===`both`||n===`none`?n:n===`end`==(e.from===t)?`out`:`in`}function kt(e,t,n,r,i){let a=[];for(let o of t){let t=Dt(o,e),s=t===e?void 0:n(t);if(!s)continue;let c;try{c=r?.(s,o)}catch(e){console.error(`Error in noteLinks.text for note "${t}":`,e)}let l=typeof c==`string`?c.trim():``,u=o.label?.trim();a.push({edgeId:o.id,direction:Ot(o,e),peer:t,text:l===``?Et(s,i):l,...u?{label:u}:{}})}return a.sort((e,t)=>ht.indexOf(e.direction)-ht.indexOf(t.direction))}var At=new WeakMap;function jt(e){clearTimeout(At.get(e)),e.classList.remove(vt),e.offsetWidth,e.classList.add(vt),At.set(e,setTimeout(()=>e.classList.remove(vt),yt))}function Mt(e,t,n){let r=n[_t[e.direction]](t);return e.label===void 0?r:n.linkLabeled(r,e.label)}function Nt(e,t,n){if(t.length===0)return!1;let r=v(`div`,`wema-note-links`);for(let e of t){let t=e.text===``?n.labels.linkEmpty:e.text,i=v(`button`,`wema-note-link`);i.type=`button`,i.setAttribute($e,e.edgeId),i.setAttribute(`aria-label`,Mt(e,t,n.labels)),i.disabled=n.isHidden(e.peer);let a=[[`wema-note-link-arrow`,gt[e.direction]],[`wema-note-link-label`,e.label],[`wema-note-link-text`,t]];for(let[e,t]of a){if(t===void 0)continue;let n=v(`span`,e);n.textContent=t,i.appendChild(n)}i.addEventListener(`click`,()=>{n.reveal(e.peer);let t=n.getElement(e.peer);t&&jt(t)}),r.appendChild(i)}return e.appendChild(r),!0}var Pt=class{boardEl;svgEl;noteManager;edgeManager;emitter;getReadOnly;toBoardPoint;onDropOnEmpty;dragging=!1;fromNoteId=null;fromAnchor=null;tempPath=null;handlePointerDown;handlePointerMove;handlePointerUp;constructor(e){this.toBoardPoint=e.toBoardPoint,this.boardEl=e.boardEl,this.svgEl=e.svgEl,this.noteManager=e.noteManager,this.edgeManager=e.edgeManager,this.emitter=e.emitter,this.getReadOnly=e.getReadOnly,this.onDropOnEmpty=e.onDropOnEmpty,this.handlePointerDown=this.onPointerDown.bind(this),this.handlePointerMove=this.onPointerMove.bind(this),this.handlePointerUp=this.onPointerUp.bind(this),this.boardEl.addEventListener(`pointerdown`,this.handlePointerDown)}destroy(){this.boardEl.removeEventListener(`pointerdown`,this.handlePointerDown),this.cleanup()}onPointerDown(e){if(e.button!==0||this.getReadOnly())return;let t=e.target.closest(`.wema-anchor`);if(!t)return;let n=t.closest(`.wema-note`);if(!n)return;let r=n.dataset.noteId,i=t.dataset.anchor;r&&i&&(e.preventDefault(),e.stopPropagation(),this.dragging=!0,this.fromNoteId=r,this.fromAnchor=i,this.tempPath=S(`path`,`wema-edge-temp`),this.tempPath.setAttribute(`fill`,`none`),this.svgEl.appendChild(this.tempPath),this.boardEl.addEventListener(`pointermove`,this.handlePointerMove),this.boardEl.addEventListener(`pointerup`,this.handlePointerUp),this.boardEl.setPointerCapture(e.pointerId))}onPointerMove(e){if(!this.dragging||!this.fromNoteId||!this.fromAnchor||!this.tempPath)return;let t=this.noteManager.getShownNote(this.fromNoteId);if(!t)return;let n=this.toBoardPoint(e.clientX,e.clientY),r=_(t,this.fromAnchor,n);this.tempPath.setAttribute(`d`,r),this.clearHighlight();let i=document.elementFromPoint(e.clientX,e.clientY);if(i){let e=i.closest?.(`.wema-note`);e&&e.dataset.noteId!==this.fromNoteId&&e.classList.add(`wema-note-drop-target`)}}onPointerUp(e){if(!this.dragging)return;this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp);try{this.boardEl.releasePointerCapture(e.pointerId)}catch{}let t=document.elementFromPoint(e.clientX,e.clientY),n=null;if(t){let e=t.closest?.(`.wema-anchor`);e?(e.dataset.anchor,n=e.closest(`.wema-note`)?.dataset.noteId??null):n=(t.closest?.(`.wema-note`))?.dataset.noteId??null}if(n&&n!==this.fromNoteId&&this.fromNoteId)this.edgeManager.addEdge(this.fromNoteId,n,{fromAnchor:`auto`,toAnchor:`auto`});else if(!n&&this.fromNoteId){let{x:t,y:n}=this.toBoardPoint(e.clientX,e.clientY);this.onDropOnEmpty?.(t,n,this.fromNoteId)}this.cleanup()}cleanup(){this.tempPath?.remove(),this.tempPath=null,this.dragging=!1,this.fromNoteId=null,this.fromAnchor=null,this.clearHighlight()}clearHighlight(){this.boardEl.querySelectorAll(`.wema-note-drop-target`).forEach(e=>{e.classList.remove(`wema-note-drop-target`)})}},Ft=80,It=60,Lt=500,Rt=class{boardEl;noteManager;getReadOnly;toBoardPoint;onResizeStart;onResizeEnd;ctx=null;onDoublePress;firstPress=null;pressedHandle=!1;handlePointerDown;handlePointerMove;handlePointerUp;handleClickAfterPress;handleAnyPointerDown;constructor(e){this.toBoardPoint=e.toBoardPoint,this.boardEl=e.boardEl,this.noteManager=e.noteManager,this.getReadOnly=e.getReadOnly,this.onResizeStart=e.onResizeStart,this.onResizeEnd=e.onResizeEnd,this.handlePointerDown=this.onPointerDown.bind(this),this.handlePointerMove=this.onPointerMove.bind(this),this.handlePointerUp=this.onPointerUp.bind(this),this.onDoublePress=e.onDoublePress,this.handleClickAfterPress=this.onClickAfterPress.bind(this),this.handleAnyPointerDown=this.onAnyPointerDown.bind(this),this.boardEl.addEventListener(`pointerdown`,this.handleAnyPointerDown,!0),this.boardEl.addEventListener(`pointerdown`,this.handlePointerDown),this.boardEl.addEventListener(`click`,this.handleClickAfterPress,!0),this.boardEl.addEventListener(`dblclick`,this.handleClickAfterPress,!0)}destroy(){this.boardEl.removeEventListener(`click`,this.handleClickAfterPress,!0),this.boardEl.removeEventListener(`dblclick`,this.handleClickAfterPress,!0),this.boardEl.removeEventListener(`pointerdown`,this.handleAnyPointerDown,!0),this.boardEl.removeEventListener(`pointerdown`,this.handlePointerDown),this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp),this.ctx=null}noteOfHandle(e){return e.button!==0||this.getReadOnly()?null:(e.target.closest(`.wema-resize-handle`)?.closest(`.wema-note`))?.dataset.noteId??null}onClickAfterPress(e){if(!this.pressedHandle)return;let t=e.target;(t===this.boardEl||t.closest(`.wema-resize-handle`))&&(e.preventDefault(),e.stopImmediatePropagation())}onAnyPointerDown(){this.pressedHandle=!1}isSecondPress(e,t){let n=this.firstPress;return n!==null&&n.noteId===t&&e.timeStamp-n.time<Lt&&Math.hypot(e.clientX-n.clientX,e.clientY-n.clientY)<4}onPointerDown(e){let t=this.noteOfHandle(e);if(!t)return;let n=this.noteManager.getNote(t);if(!n||n.autoSize)return;if(e.preventDefault(),e.stopPropagation(),this.pressedHandle=!0,this.isSecondPress(e,t)){this.firstPress=null,this.onDoublePress?.(t);return}this.firstPress={noteId:t,time:e.timeStamp,clientX:e.clientX,clientY:e.clientY};let r=this.toBoardPoint(e.clientX,e.clientY);this.ctx={noteId:t,startX:r.x,startY:r.y,startWidth:n.width,startHeight:n.height,pointerId:e.pointerId},this.boardEl.setPointerCapture(e.pointerId),this.boardEl.addEventListener(`pointermove`,this.handlePointerMove),this.boardEl.addEventListener(`pointerup`,this.handlePointerUp),this.onResizeStart?.()}onPointerMove(e){if(!this.ctx)return;let t=this.firstPress;if(t){if(Math.hypot(e.clientX-t.clientX,e.clientY-t.clientY)<4)return;this.firstPress=null}let n=this.toBoardPoint(e.clientX,e.clientY),r=n.x-this.ctx.startX,i=n.y-this.ctx.startY,{startWidth:a,startHeight:o}=this.ctx,s=Math.max(Math.min(Ft,a),a+r),c=Math.max(Math.min(It,o),o+i),l=this.noteManager.hasMeasuredHeight(this.ctx.noteId);this.noteManager.updateNote(this.ctx.noteId,l?{width:s}:{width:s,height:c})}onPointerUp(e){if(this.ctx){this.boardEl.removeEventListener(`pointermove`,this.handlePointerMove),this.boardEl.removeEventListener(`pointerup`,this.handlePointerUp);try{this.boardEl.releasePointerCapture(this.ctx.pointerId)}catch{}this.onResizeEnd?.(),this.ctx=null}}},zt={solid:{svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/></svg>`,label:`lineSolid`},dashed:{svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2" stroke-dasharray="4 3"/></svg>`,label:`lineDashed`},dotted:{svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2" stroke-dasharray="2 2"/></svg>`,label:`lineDotted`}},Bt=[{value:`none`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/></svg>`,label:`arrowNone`},{value:`start`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="8" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="8,8 14,5 14,11" fill="currentColor"/></svg>`,label:`arrowStart`},{value:`end`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="16" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="16,5 22,8 16,11" fill="currentColor"/></svg>`,label:`arrowEnd`},{value:`both`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="8" y1="8" x2="16" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="8,8 14,5 14,11" fill="currentColor"/><polygon points="16,5 22,8 16,11" fill="currentColor"/></svg>`,label:`arrowBoth`}],Vt=[{value:8,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="14" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="14,5.5 19,8 14,10.5" fill="currentColor"/></svg>`,label:`sizeSmall`},{value:12,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="13" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="13,4 21,8 13,12" fill="currentColor"/></svg>`,label:`sizeMedium`},{value:18,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="11" y2="8" stroke="currentColor" stroke-width="2"/><polygon points="11,2 23,8 11,14" fill="currentColor"/></svg>`,label:`sizeLarge`}],Ht=[{value:1,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="1"/></svg>`,label:`widthThin`},{value:2,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="2"/></svg>`,label:`widthNormal`},{value:4,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><line x1="2" y1="8" x2="22" y2="8" stroke="currentColor" stroke-width="4"/></svg>`,label:`widthThick`}],Ut=[{value:`curve`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><path d="M2 14 C8 14, 16 2, 22 2" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,label:`routeCurve`},{value:`polyline`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><polyline points="2,14 2,2 22,2" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,label:`routePolyline`}],Wt=[{value:`auto`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><circle cx="12" cy="8" r="4" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="12" cy="8" r="1.5" fill="currentColor"/></svg>`,label:`anchorAuto`},{value:`top`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="6" y="4" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="12" cy="4" r="2" fill="currentColor"/></svg>`,label:`anchorTop`},{value:`right`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="4" y="3" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="16" cy="8" r="2" fill="currentColor"/></svg>`,label:`anchorRight`},{value:`bottom`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="6" y="2" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="12" cy="12" r="2" fill="currentColor"/></svg>`,label:`anchorBottom`},{value:`left`,svg:`<svg width="24" height="16" viewBox="0 0 24 16"><rect x="8" y="3" width="12" height="10" rx="1" stroke="currentColor" stroke-width="1.5" fill="none"/><circle cx="8" cy="8" r="2" fill="currentColor"/></svg>`,label:`anchorLeft`}],Gt=`<svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3,2 7,5 3,8"/></svg>`,Kt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>`,qt=class{popupEl;boardEl;edgeManager;noteManager;labels;onDelete;currentEdgeId=null;anchor={x:0,y:0};view;detailsOpen=!1;constructor(e){this.boardEl=e.boardEl,this.view=e.view,this.edgeManager=e.edgeManager,this.noteManager=e.noteManager,this.labels=e.labels,this.onDelete=e.onDelete,this.popupEl=v(`div`,`wema-edge-popup`),this.popupEl.style.display=`none`,this.popupEl.addEventListener(`click`,e=>e.stopPropagation()),this.boardEl.appendChild(this.popupEl)}show(e,t,n){let r=this.edgeManager.getEdge(e);if(!r)return;this.currentEdgeId=e,this.popupEl.innerHTML=``;let i=r.routing??`curve`,a=r.lineStyle??(r.style===`dashed`?`dashed`:`solid`),o=r.arrowHead??(r.style===`arrow`?`end`:`none`),s=r.arrowSize??12,c=r.strokeWidth??2,l=v(`div`,`wema-popup-details`),u=v(`button`,`wema-popup-details-toggle`);u.innerHTML=Gt,u.append(` ${this.labels.details}`);let d=v(`div`,`wema-popup-details-content`);this.detailsOpen?(u.classList.add(`open`),d.style.display=``):d.style.display=`none`,u.addEventListener(`click`,()=>{this.detailsOpen=!this.detailsOpen,u.classList.toggle(`open`,this.detailsOpen),d.style.display=this.detailsOpen?``:`none`});let f=v(`div`,`wema-popup-section`),p=v(`div`,`wema-popup-label`);p.textContent=this.labels.route,f.appendChild(p);let m=v(`div`,`wema-popup-group`);for(let e of Ut){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===i&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{routing:e.value}),this.show(this.currentEdgeId))}),m.appendChild(t)}f.appendChild(m);let h=v(`div`,`wema-popup-section`),g=v(`div`,`wema-popup-label`);g.textContent=this.labels.from,h.appendChild(g);let _=v(`div`,`wema-popup-group`);for(let e of Wt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===r.fromAnchor&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{fromAnchor:e.value}),this.show(this.currentEdgeId))}),_.appendChild(t)}h.appendChild(_);let b=v(`div`,`wema-popup-section`),x=v(`div`,`wema-popup-label`);x.textContent=this.labels.to,b.appendChild(x);let S=v(`div`,`wema-popup-group`);for(let e of Wt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===r.toAnchor&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{toAnchor:e.value}),this.show(this.currentEdgeId))}),S.appendChild(t)}b.appendChild(S),d.appendChild(f),d.appendChild(h),d.appendChild(b),l.appendChild(u),l.appendChild(d);let C=v(`div`,`wema-popup-section`),w=v(`div`,`wema-popup-label`);w.textContent=this.labels.line,C.appendChild(w);let T=v(`div`,`wema-popup-group`);for(let e of[`solid`,`dashed`,`dotted`]){let t=zt[e],n=v(`button`,`wema-popup-btn`);n.innerHTML=t.svg,y(n,this.labels[t.label]),e===a&&n.classList.add(`active`),n.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{lineStyle:e}),this.show(this.currentEdgeId))}),T.appendChild(n)}C.appendChild(T);let E=v(`div`,`wema-popup-section`),D=v(`div`,`wema-popup-label`);D.textContent=this.labels.arrow,E.appendChild(D);let ee=v(`div`,`wema-popup-group`);for(let e of Bt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===o&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{arrowHead:e.value}),this.show(this.currentEdgeId))}),ee.appendChild(t)}E.appendChild(ee);let O=v(`div`,`wema-popup-section`),te=v(`div`,`wema-popup-label`);te.textContent=this.labels.size,O.appendChild(te);let ne=v(`div`,`wema-popup-group`);for(let e of Vt){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===s&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{arrowSize:e.value}),this.show(this.currentEdgeId))}),ne.appendChild(t)}O.appendChild(ne);let re=v(`div`,`wema-popup-section`),ie=v(`div`,`wema-popup-label`);ie.textContent=this.labels.width,re.appendChild(ie);let k=v(`div`,`wema-popup-group`);for(let e of Ht){let t=v(`button`,`wema-popup-btn`);t.innerHTML=e.svg,y(t,this.labels[e.label]),e.value===c&&t.classList.add(`active`),t.addEventListener(`click`,()=>{this.currentEdgeId&&(this.edgeManager.updateEdge(this.currentEdgeId,{strokeWidth:e.value}),this.show(this.currentEdgeId))}),k.appendChild(t)}re.appendChild(k);let A=v(`div`,`wema-popup-section wema-popup-delete-section`),j=v(`button`,`wema-popup-btn wema-popup-btn-delete`);j.innerHTML=Kt,y(j,this.labels.delete),j.addEventListener(`click`,()=>{if(!this.currentEdgeId)return;let e=this.currentEdgeId;this.hide(),this.onDelete(e)}),A.appendChild(j),this.popupEl.appendChild(C),this.popupEl.appendChild(E),this.popupEl.appendChild(O),this.popupEl.appendChild(re),this.popupEl.appendChild(l),this.popupEl.appendChild(A),t!=null&&n!=null&&(this.anchor=this.view.clientToBoard(t,n)),this.popupEl.style.display=``,this.updatePosition()}updatePosition(){if(this.currentEdgeId===null)return;let{x:e,y:t}=this.view.boardToScreen(this.anchor.x,this.anchor.y);b(this.popupEl,this.boardEl,{left:e,top:t,right:e,bottom:t},`below`,12)}hide(){this.popupEl.style.display=`none`,this.currentEdgeId=null,this.detailsOpen=!1}destroy(){this.popupEl.remove()}},Jt=[{hex:`#FFF9C4`,label:`colorButter`},{hex:`#FFCDD2`,label:`colorRose`},{hex:`#FFE0B2`,label:`colorPeach`},{hex:`#E1BEE7`,label:`colorLavender`},{hex:`#BBDEFB`,label:`colorSky`},{hex:`#B2DFDB`,label:`colorMint`},{hex:`#C8E6C9`,label:`colorSage`},{hex:`#F5F5F5`,label:`colorGray`}],Yt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,Xt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>`,Zt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="3" cy="6" r="1.5" fill="currentColor" stroke="none"/><circle cx="3" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="3" cy="18" r="1.5" fill="currentColor" stroke="none"/></svg>`,Qt=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><text x="2" y="8" font-size="8" fill="currentColor" stroke="none" font-family="sans-serif">1</text><text x="2" y="14" font-size="8" fill="currentColor" stroke="none" font-family="sans-serif">2</text><text x="2" y="20" font-size="8" fill="currentColor" stroke="none" font-family="sans-serif">3</text></svg>`,$t=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><polyline points="9 11 12 14 22 4" stroke-width="2"/></svg>`,en=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="12" x2="21" y2="12"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="3 9 6 12 3 15"/></svg>`,tn=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="12" x2="21" y2="12"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="6 9 3 12 6 15"/></svg>`,nn=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,rn=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>`,an=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>`,on=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="5" x2="20" y2="5"/><line x1="4" y1="10" x2="20" y2="10"/><line x1="4" y1="15" x2="12" y2="15" opacity="0.4"/><polyline points="9 19 12 22 15 19"/></svg>`,sn=class{popupEl;boardEl;noteManager;labels;onColorChange;onMultiColorChange;onDuplicate;onDelete;onMultiDelete;onInsertImage=null;onInsertEmbed=null;onAutoSizeToggle=null;onMultiAutoSizeToggle=null;onFoldableToggle=null;currentNoteId=null;currentNoteIds=null;toScreenBox;placed=null;constructor(e){this.toScreenBox=e.toScreenBox,this.boardEl=e.boardEl,this.noteManager=e.noteManager,this.labels=e.labels,this.onColorChange=e.onColorChange,this.onMultiColorChange=e.onMultiColorChange,this.onDuplicate=e.onDuplicate,this.onDelete=e.onDelete,this.onMultiDelete=e.onMultiDelete,this.onInsertImage=e.onInsertImage??null,this.onInsertEmbed=e.onInsertEmbed??null,this.onAutoSizeToggle=e.onAutoSizeToggle??null,this.onMultiAutoSizeToggle=e.onMultiAutoSizeToggle??null,this.onFoldableToggle=e.onFoldableToggle??null,this.popupEl=v(`div`,`wema-note-popup`),this.popupEl.style.display=`none`,this.popupEl.addEventListener(`click`,e=>e.stopPropagation()),this.boardEl.appendChild(this.popupEl)}show(e){let t=this.noteManager.getNote(e);if(!t)return;this.currentNoteId=e,this.popupEl.innerHTML=``;let n=v(`div`,`wema-note-popup-actions`),r=v(`button`,`wema-popup-btn wema-note-popup-color-btn`);r.style.backgroundColor=t.color,y(r,this.labels.color),r.addEventListener(`click`,()=>{let e=h.style.display!==`none`;h.style.display=e?`none`:``});let i=v(`button`,`wema-popup-btn`);i.innerHTML=Yt,y(i,this.labels.duplicate),i.addEventListener(`click`,()=>{if(!this.currentNoteId)return;let e=this.currentNoteId;this.hide(),this.onDuplicate(e)});let a=v(`button`,`wema-popup-btn wema-popup-btn-delete`);a.innerHTML=Xt,y(a,this.labels.delete),a.addEventListener(`click`,()=>{if(!this.currentNoteId)return;let e=this.currentNoteId;this.hide(),this.onDelete(e)});let o=v(`button`,`wema-popup-btn`);o.innerHTML=an,y(o,this.labels.autoSize),t.autoSize&&o.classList.add(`active`),o.addEventListener(`click`,()=>{this.currentNoteId&&this.onAutoSizeToggle?.(this.currentNoteId)}),n.appendChild(r),n.appendChild(o),this.noteManager.isHostDrawn(e)||n.appendChild(this.foldableButton([t])),n.appendChild(i),n.appendChild(a);let s=v(`div`,`wema-note-popup-actions`),c=v(`button`,`wema-popup-btn`);c.innerHTML=Zt,y(c,this.labels.bulletedList),c.addEventListener(`click`,()=>{this.currentNoteId&&this.toggleList(this.currentNoteId,`ul`)});let l=v(`button`,`wema-popup-btn`);l.innerHTML=Qt,y(l,this.labels.numberedList),l.addEventListener(`click`,()=>{this.currentNoteId&&this.toggleList(this.currentNoteId,`ol`)});let u=v(`button`,`wema-popup-btn`);u.innerHTML=$t,y(u,this.labels.checklist),u.addEventListener(`click`,()=>{this.currentNoteId&&this.toggleList(this.currentNoteId,`checklist`)});let d=v(`button`,`wema-popup-btn`);d.innerHTML=tn,y(d,this.labels.outdent),d.addEventListener(`click`,()=>{this.currentNoteId&&this.noteManager.editContent(this.currentNoteId,(e,t)=>t&&Re(e,t))});let f=v(`button`,`wema-popup-btn`);f.innerHTML=en,y(f,this.labels.indent),f.addEventListener(`click`,()=>{this.currentNoteId&&this.noteManager.editContent(this.currentNoteId,(e,t)=>t&&Le(e,t))});for(let e of[c,l,u,d,f])e.addEventListener(`mousedown`,e=>e.preventDefault());let p=v(`button`,`wema-popup-btn`);p.innerHTML=nn,y(p,this.labels.image),p.addEventListener(`click`,()=>{this.currentNoteId&&this.onInsertImage?.(this.currentNoteId)});let m=v(`button`,`wema-popup-btn`);m.innerHTML=rn,y(m,this.labels.embed),m.addEventListener(`click`,()=>{this.currentNoteId&&this.onInsertEmbed?.(this.currentNoteId)}),s.appendChild(c),s.appendChild(l),s.appendChild(u),s.appendChild(d),s.appendChild(f),s.appendChild(p),s.appendChild(m);let h=v(`div`,`wema-note-popup-colors`);h.style.display=`none`;for(let e of Jt){let n=v(`button`,`wema-color-swatch`);n.style.backgroundColor=e.hex,y(n,this.labels[e.label]),t.color.toUpperCase()===e.hex&&n.classList.add(`active`),n.addEventListener(`click`,()=>{this.currentNoteId&&(this.onColorChange(this.currentNoteId,e.hex),r.style.backgroundColor=e.hex,h.querySelectorAll(`.wema-color-swatch`).forEach(e=>e.classList.remove(`active`)),n.classList.add(`active`))}),h.appendChild(n)}this.popupEl.appendChild(n),this.noteManager.isHostDrawn(e)||this.popupEl.appendChild(s),this.popupEl.appendChild(h),this.popupEl.style.display=``,this.updatePosition()}showMulti(e){let t=e.map(e=>this.noteManager.getNote(e)).filter(e=>e!=null);if(t.length<2)return;this.currentNoteId=null,this.currentNoteIds=e.slice(),this.popupEl.innerHTML=``;let n=v(`div`,`wema-note-popup-actions`),r=v(`button`,`wema-popup-btn wema-note-popup-color-btn`),i=t.every(e=>e.color===t[0].color);r.style.backgroundColor=i?t[0].color:`#ccc`,y(r,this.labels.color),r.addEventListener(`click`,()=>{let e=c.style.display!==`none`;c.style.display=e?`none`:``});let a=t.every(e=>e.autoSize),o=v(`button`,`wema-popup-btn`);o.innerHTML=an,y(o,this.labels.autoSize),a&&o.classList.add(`active`),o.addEventListener(`click`,()=>{this.currentNoteIds&&this.onMultiAutoSizeToggle?.(this.currentNoteIds.slice())});let s=v(`button`,`wema-popup-btn wema-popup-btn-delete`);s.innerHTML=Xt,y(s,this.labels.deleteNotes(t.length)),s.addEventListener(`click`,()=>{if(!this.currentNoteIds)return;let e=this.currentNoteIds.slice();this.hide(),this.onMultiDelete(e)}),n.appendChild(r),n.appendChild(o),n.appendChild(this.foldableButton(t)),n.appendChild(s);let c=v(`div`,`wema-note-popup-colors`);c.style.display=`none`;for(let e of Jt){let n=v(`button`,`wema-color-swatch`);n.style.backgroundColor=e.hex,y(n,this.labels[e.label]),i&&t[0].color.toUpperCase()===e.hex&&n.classList.add(`active`),n.addEventListener(`click`,()=>{this.currentNoteIds&&(this.onMultiColorChange(this.currentNoteIds,e.hex),r.style.backgroundColor=e.hex,c.querySelectorAll(`.wema-color-swatch`).forEach(e=>e.classList.remove(`active`)),n.classList.add(`active`))}),c.appendChild(n)}this.popupEl.appendChild(n),this.popupEl.appendChild(c),this.popupEl.style.display=``,this.updatePosition()}foldableButton(e){let t=v(`button`,`wema-popup-btn`);t.innerHTML=on,y(t,this.labels.foldLongText),t.classList.toggle(`active`,e.every(e=>e.foldable));let n=e.map(e=>e.id);return t.addEventListener(`click`,()=>this.onFoldableToggle?.(n)),t}updatePosition(){let e=(this.currentNoteIds??(this.currentNoteId?[this.currentNoteId]:[])).map(e=>this.noteManager.getShownBox(e)).filter(e=>e!==void 0);if(e.length===0)return;let t=this.toScreenBox(s(e)),n=b(this.popupEl,this.boardEl,t,`below`,8);this.placed={box:{left:t.left,top:Math.min(t.top,n.top),right:t.right,bottom:Math.max(t.bottom,n.bottom)},side:n.top<t.top?`above`:`below`}}boxWith(e){return this.currentNoteId===e?this.placed:null}hide(){this.placed=null,this.popupEl.style.display=`none`,this.currentNoteId=null,this.currentNoteIds=null}destroy(){this.popupEl.remove()}toggleList(e,t){this.noteManager.editContent(e,(e,n)=>n?Ne(e,n,t):Pe(e,t))}insertBlockContent(e,t){let n=this.noteManager.getTextElement(e);if(!n)return;n.focus();let r=document.createElement(`div`);for(r.innerHTML=t;r.firstChild;)n.appendChild(r.firstChild);this.noteManager.updateNote(e,{text:n.innerHTML})}},cn=16;function ln(e,t={}){if(e.length===0)return[];let n=new Map(e.map(e=>[e.id,e])),r=[];for(let e of t.order??[]){let t=n.get(e);t&&n.delete(e)&&r.push(t)}r.push(...[...n.values()].sort((e,t)=>e.y-t.y||e.x-t.x));let i=t.x??Math.min(...e.map(e=>e.x)),a=t.gap??cn,o=t.y??Math.min(...e.map(e=>e.y));return r.map(e=>{let n={id:e.id,x:i,y:o,width:t.width??e.width};return o+=e.height+a,n})}function un(e,t){if(e.length<2)return[];switch(t){case`left`:{let t=Math.min(...e.map(e=>e.x));return e.map(e=>({id:e.id,x:t,y:e.y}))}case`center`:{let t=e.reduce((e,t)=>e+t.x+t.width/2,0)/e.length;return e.map(e=>({id:e.id,x:t-e.width/2,y:e.y}))}case`right`:{let t=Math.max(...e.map(e=>e.x+e.width));return e.map(e=>({id:e.id,x:t-e.width,y:e.y}))}case`top`:{let t=Math.min(...e.map(e=>e.y));return e.map(e=>({id:e.id,x:e.x,y:t}))}case`middle`:{let t=e.reduce((e,t)=>e+t.y+t.height/2,0)/e.length;return e.map(e=>({id:e.id,x:e.x,y:t-e.height/2}))}case`bottom`:{let t=Math.max(...e.map(e=>e.y+e.height));return e.map(e=>({id:e.id,x:e.x,y:t-e.height}))}}}function dn(e,t){if(e.length<3)return[];let n=[];if(t===`horizontal`){let t=[...e].sort((e,t)=>e.x-t.x),r=t[0],i=t[t.length-1],a=(i.x+i.width-r.x-t.reduce((e,t)=>e+t.width,0))/(t.length-1),o=r.x+r.width+a;for(let e=1;e<t.length-1;e++)n.push({id:t[e].id,x:o,y:t[e].y}),o+=t[e].width+a}else{let t=[...e].sort((e,t)=>e.y-t.y),r=t[0],i=t[t.length-1],a=(i.y+i.height-r.y-t.reduce((e,t)=>e+t.height,0))/(t.length-1),o=r.y+r.height+a;for(let e=1;e<t.length-1;e++)n.push({id:t[e].id,x:t[e].x,y:o}),o+=t[e].height+a}return n}var fn=40,pn=60,mn=.44,hn=150,gn=80,_n=16,vn=1.6,yn=64,bn=1.25,xn=4,Sn=1e3,Cn=(e,t)=>e.x-t.x||e.y-t.y,wn=(e,t,n)=>e.map(e=>({id:e.id,x:e.x+t,y:e.y+n}));function Tn(e,t){let n=[],r=[];e.forEach((e,i)=>{let a=i%t,o=Math.floor(i/t);n[a]=Math.max(n[a]??0,e.width),r[o]=Math.max(r[o]??0,e.height)});let i=(e,t)=>{let n=0;return e.map(e=>{let r=n;return n+=e+t,r})},a=i(n,fn),o=i(r,pn),s=n.length-1,c=r.length-1;return{width:a[s]+n[s],height:o[c]+r[c],places:e.map((e,n)=>({id:e.id,x:a[n%t],y:o[Math.floor(n/t)]}))}}function En(e,t,n){let r=[],i=0;for(let t of e)r.push(i+t/2),i+=t+fn;let a=[];for(let i=0;i<e.length;i++){let e={sum:(t[i]-r[i])*n[i],weight:n[i],count:1};for(;a.length>0;){let t=a[a.length-1];if(t.sum/t.weight<=e.sum/e.weight)break;e={sum:t.sum+e.sum,weight:t.weight+e.weight,count:t.count+e.count},a.pop()}a.push(e)}let o=[];for(let e of a)for(let t=0;t<e.count;t++)o.push(e.sum/e.weight+r[o.length]);return o}function Dn(e,t){let n=e.map(e=>{let n=t(e),r=n.filter(e=>e.passing),i=r.length>0?r:n;return{unit:e,at:i.length>0?i.reduce((e,t)=>e+t.center,0)/i.length:e.center}});n.sort((e,t)=>e.at-t.at);let r=En(n.map(e=>e.unit.block.width),n.map(e=>e.at),n.map(e=>e.unit.passing?Sn:1));n.forEach(({unit:t},n)=>{t.center=r[n],e[n]=t})}function On(e){let t=[];for(let n of e)(t[n.level]??=[]).push(n);for(let e of t)Dn(e,()=>[]);for(let e=0;e<xn;e++){for(let e=1;e<t.length;e++)Dn(t[e],e=>e.parents);for(let e=t.length-2;e>=0;e--)Dn(t[e],e=>e.children)}let n=e.filter(e=>!e.passing),r=Math.min(...n.map(e=>e.center-e.block.width/2)),i=Math.max(...n.map(e=>e.center+e.block.width/2)),a=[],o=0,s=0;for(let e of t){for(let t of e)a.push(...wn(t.block.places,t.center-t.block.width/2-r,o));s=o+Math.max(...e.map(e=>e.block.height)),o=s+kn(e)}return{width:i-r,height:s,places:a}}function kn(e){let t=0;for(let n of e)if(!n.passing)for(let e of n.children)e.passing||(t=Math.max(t,Math.abs(e.center-n.center)));return Math.min(Math.max(t*mn,pn),hn)}function An(e,t,n,r){let i=[];return{...jn(e,t,n,r,(e,t,n)=>i.push(...wn(e.places,t,n))),places:i}}function jn(e,t,n,r,i){let a=0,o=0,s=0,c=0;for(let l of e)a>0&&a+l.width>t&&(a=0,o+=s+r,s=0),i?.(l,a,o),c=Math.max(c,a+l.width),s=Math.max(s,l.height),a+=l.width+n;return{width:c,height:o+s}}function Mn(e,t,n){let r=[],i=0,a=1;return e.forEach((o,s)=>{let c=i+o.width;if(i+=o.width+t,s+1<a&&s+1<e.length)return;a=s+1<yn?s+2:Math.ceil((s+1)*bn);let l=jn(e,c,t,n),u=r[r.length-1];(!u||u.width!==l.width||u.height!==l.height)&&r.push({...l,maxWidth:c})}),r}function Nn(e,t,n){let r={width:0,height:0,maxWidth:0},i=e.length>0?Mn(e,gn,gn):[r],a=t.length>0?Mn(t,fn,pn):[r],o=e.length>0&&t.length>0?gn:0,s={fit:1/0,area:1/0,g:r,l:r,beside:!1},c=(e,t,r)=>{let i=r?e.width+o+t.width:Math.max(e.width,t.width),a=r?Math.max(e.height,t.height):e.height+o+t.height,c=Math.max(i/n,a),l=i*a;(c<s.fit||c===s.fit&&l<s.area)&&(s={fit:c,area:l,g:e,l:t,beside:r})};for(let e of i)for(let t of a)c(e,t,!1),o>0&&c(e,t,!0);let{g:l,l:u,beside:d}=s;return[...An(e,l.maxWidth,gn,gn).places,...wn(An(t,u.maxWidth,fn,pn).places,d?l.width+o:0,d?0:l.height+o)]}function Pn(e,t){let n=new Set(e.map(e=>e.id)),r=new Map,i=new Set;for(let{from:e,to:a}of t)e!==a&&n.has(e)&&n.has(a)&&(r.has(e)||r.set(e,new Set),r.get(e).add(a),i.add(a));let a=e.filter(e=>r.has(e.id)||i.has(e.id)),o=new Map(a.map(e=>[e.id,[]])),s=new Map(a.map(e=>[e.id,0])),c=new Set,l=new Set,u=[],d=[],f=e=>{c.add(e),l.add(e),d.push({id:e,next:[...r.get(e)??[]],at:0})},p=a.filter(e=>!i.has(e.id));for(let{id:e}of[...p,...a])if(!c.has(e))for(f(e);d.length>0;){let e=d[d.length-1];if(e.at===e.next.length){l.delete(e.id),u.push(e.id),d.pop();continue}let t=e.next[e.at++];l.has(t)||(o.get(e.id).push(t),s.set(t,s.get(t)+1),c.has(t)||f(t))}return{nodes:a,children:o,parentCount:s,order:u.reverse()}}function Fn({nodes:e,children:t,parentCount:n,order:r}){let i=new Map(e.map(e=>[e.id,0]));for(let e of r)for(let n of t.get(e))i.set(n,Math.max(i.get(n),i.get(e)+1));for(let{id:r}of e){let e=t.get(r);n.get(r)===0&&e.length>0&&i.set(r,Math.min(...e.map(e=>i.get(e)))-1)}return i}function In({nodes:e,children:t,parentCount:n},r){let i=new Map(e.map(e=>[e.id,e])),a=new Map,o=(e,t,n=!1)=>({block:e,level:t,passing:n,parents:[],children:[],center:0}),s=(e,t)=>{e.children.includes(t)||(e.children.push(t),t.parents.push(e))};for(let{id:s}of e){let e=t.get(s).filter(e=>t.get(e).length===0&&n.get(e)===1).map(e=>i.get(e));if(e.length<_n)continue;e.sort(Cn);let c=o(Tn(e,Math.ceil(Math.sqrt(e.length))),r.get(s)+1);for(let t of e)a.set(t.id,c)}for(let t of e)a.has(t.id)||a.set(t.id,o(Tn([t],1),r.get(t.id)));for(let{id:n}of e){let e=a.get(n);for(let r of t.get(n)){let t=a.get(r),n=e;for(let r=e.level+1;r<t.level;r++){let e=o({width:0,height:0,places:[]},r,!0);s(n,e),n=e}s(n,t)}}return a}function Ln(e,t){let n=[],r=new Set;for(let{id:i}of e){let e=t.get(i);if(r.has(e))continue;r.add(e);let a=[e];for(let e=0;e<a.length;e++)for(let t of[...a[e].parents,...a[e].children])r.has(t)||(r.add(t),a.push(t));n.push(a)}return n}function Rn(e,t,n){let r=n?.noteIds?new Set(n.noteIds):null,i=e.filter(e=>!r||r.has(e.id)).sort(Cn);if(i.length===0)return[];let a=Pn(i,t),o=In(a,Fn(a)),s=Ln(a.nodes,o).map(On),c=i.filter(e=>!o.has(e.id)).map(e=>Tn([e],1)),l=n?.aspectRatio,u=Nn(s,c,l&&l>0&&Number.isFinite(l)?l:vn),d=Math.min(...i.map(e=>e.x)),f=Math.min(...i.map(e=>e.y));return u.map(e=>({id:e.id,x:Math.round(d+e.x),y:Math.round(f+e.y)}))}function zn(e){switch(e.type){case`note:create`:case`note:delete`:return{type:e.type,note:{...e.note}};case`edge:create`:case`edge:delete`:return{type:e.type,edge:{...e.edge}};case`note:update`:case`edge:update`:return{...e,before:{...e.before},after:{...e.after}}}}function Bn(e){let t=zn(e);switch(t.type){case`note:create`:return{...t,type:`note:delete`};case`note:delete`:return{...t,type:`note:create`};case`edge:create`:return{...t,type:`edge:delete`};case`edge:delete`:return{...t,type:`edge:create`};case`note:update`:case`edge:update`:return{...t,before:t.after,after:t.before}}}function Vn(e,t,n){let r={},i={};for(let a of Object.keys(t))a===`id`||n.has(a)||de(e[a],t[a])||(r[a]=e[a],i[a]=t[a]);return{before:r,after:i}}var Hn=Object.keys({x:!0,y:!0,width:!0,height:!0,text:!0,color:!0,zIndex:!0,autoSize:!0,foldable:!0,meta:!0}),Un=Object.keys({fromAnchor:!0,toAnchor:!0,style:!0,label:!0,lineStyle:!0,strokeWidth:!0,arrowHead:!0,arrowSize:!0,routing:!0,collapsed:!0});function Wn(e,t,n){let r={};for(let i of n)Object.hasOwn(t,i)?r[i]=t[i]:Object.hasOwn(e,i)&&(r[i]=void 0);return r}function Gn(e){let t=[],n=new Map;for(let r of e){if(r.type!==`note:update`&&r.type!==`edge:update`){t.push(r),n.clear();continue}let e=r.type===`note:update`?`note:${r.noteId}`:`edge:${r.edgeId}`,i=n.get(e),a=i===void 0?void 0:t[i];if(i===void 0||a===void 0||a.type!==r.type){n.set(e,t.length),t.push(r);continue}t[i]={...a,before:{...r.before,...a.before},after:{...a.after,...r.after}}}return t.filter(e=>{if(e.type!==`note:update`&&e.type!==`edge:update`)return!0;let t=e.before,n=e.after;for(let e of Object.keys(n))de(t[e],n[e])&&(delete t[e],delete n[e]);return Object.keys(n).length>0})}function Kn(e,t){for(let n of e)switch(n.type){case`note:create`:t.addNoteWithId(n.note);break;case`note:update`:t.updateNote(n.noteId,Wn(n.before,n.after,Hn));break;case`note:delete`:t.deleteNote(n.note.id);break;case`edge:create`:t.addEdgeWithId(n.edge);break;case`edge:update`:t.updateEdge(n.edgeId,Wn(n.before,n.after,Un));break;case`edge:delete`:t.deleteEdge(n.edge.id)}}var qn=class{undoStack=[];redoStack=[];pendingDeltas=[];pendingOrigin=`user`;batchDepth=0;commitScheduled=!1;recording=!0;ignoredNoteKeys=new Set;ignoredEdgeKeys=new Set;maxHistory;emitter;replay;handlers;constructor(e,t,n=100){this.emitter=e,this.replay=t,this.maxHistory=n,this.handlers={noteCreate:e=>this.pushDelta({type:`note:create`,note:{...e.note}}),noteUpdate:e=>{let{before:t,after:n}=Vn(e.prev,e.note,this.ignoredNoteKeys);Object.keys(n).length>0&&this.pushDelta({type:`note:update`,noteId:e.note.id,before:t,after:n})},noteDelete:e=>this.pushDelta({type:`note:delete`,note:{...e.note}}),edgeCreate:e=>this.pushDelta({type:`edge:create`,edge:{...e.edge}}),edgeUpdate:e=>{let{before:t,after:n}=Vn(e.prev,e.edge,this.ignoredEdgeKeys);Object.keys(n).length>0&&this.pushDelta({type:`edge:update`,edgeId:e.edge.id,before:t,after:n})},edgeDelete:e=>this.pushDelta({type:`edge:delete`,edge:{...e.edge}})},this.emitter.on(`note:create`,this.handlers.noteCreate),this.emitter.on(`note:update`,this.handlers.noteUpdate),this.emitter.on(`note:delete`,this.handlers.noteDelete),this.emitter.on(`edge:create`,this.handlers.edgeCreate),this.emitter.on(`edge:update`,this.handlers.edgeUpdate),this.emitter.on(`edge:delete`,this.handlers.edgeDelete)}beginBatch(e){e&&this.batchDepth===0&&(this.commitPending(),this.pendingOrigin=e),this.batchDepth++}endBatch(){this.batchDepth>0&&this.batchDepth--,this.batchDepth===0&&this.commitPending()}setIgnoredKeys(e,t){this.ignoredNoteKeys=new Set(e),this.ignoredEdgeKeys=new Set(t)}undo(){let e=this.undoStack.pop();if(!e)return;let t=e.deltas.map(Bn).reverse();this.withoutRecording(()=>Kn(t,this.replay)),this.redoStack.push(e),this.emitHistoryChange(),this.emitter.emit(`history:commit`,{deltas:t,origin:`undo`})}redo(){let e=this.redoStack.pop();e&&(this.withoutRecording(()=>Kn(e.deltas,this.replay)),this.undoStack.push(e),this.emitHistoryChange(),this.emitter.emit(`history:commit`,{deltas:e.deltas.map(zn),origin:`redo`}))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack.length=0,this.redoStack.length=0,this.pendingDeltas.length=0,this.pendingOrigin=`user`,this.batchDepth=0,this.commitScheduled=!1,this.emitHistoryChange()}destroy(){this.emitter.off(`note:create`,this.handlers.noteCreate),this.emitter.off(`note:update`,this.handlers.noteUpdate),this.emitter.off(`note:delete`,this.handlers.noteDelete),this.emitter.off(`edge:create`,this.handlers.edgeCreate),this.emitter.off(`edge:update`,this.handlers.edgeUpdate),this.emitter.off(`edge:delete`,this.handlers.edgeDelete)}isReplaying(){return!this.recording}withoutRecording(e){this.recording=!1;try{e()}finally{this.recording=!0}}pushDelta(e){this.recording&&(this.pendingDeltas.push(e),this.redoStack.length>0&&(this.redoStack.length=0),this.batchDepth===0&&!this.commitScheduled&&(this.commitScheduled=!0,queueMicrotask(()=>{this.commitScheduled=!1,this.batchDepth===0&&this.commitPending()})))}commitPending(){let e=this.pendingOrigin;this.pendingOrigin=`user`;let t=Gn(this.pendingDeltas.splice(0));if(t.length===0)return;let n={deltas:t};for(this.undoStack.push(n);this.undoStack.length>this.maxHistory;)this.undoStack.shift();this.emitHistoryChange(),this.emitter.emit(`history:commit`,{deltas:n.deltas.map(zn),origin:e})}emitHistoryChange(){this.emitter.emit(`history:change`,{canUndo:this.canUndo(),canRedo:this.canRedo()})}},Jn=[`#333333`,`#D32F2F`,`#1976D2`,`#388E3C`,`#F57C00`,`#7B1FA2`,`#00796B`,`#455A64`],Yn=[`b`,`strong`],Xn=[`s`],Zn=class{boardEl;toolbarEl;labels;onQuote;readOnly;viewOnly;rafId=0;handleSelectionChange;handleMouseDown;activeContentEl=null;savedRange=null;subPanelOpen=!1;constructor(e){this.boardEl=e.boardEl,this.labels=e.labels,this.onQuote=e.onQuote,this.readOnly=e.readOnly,this.viewOnly=e.viewOnly,this.toolbarEl=v(`div`,`wema-richtext-toolbar`),this.toolbarEl.style.display=`none`,this.toolbarEl.addEventListener(`mousedown`,e=>{e.preventDefault()}),this.toolbarEl.addEventListener(`pointerdown`,e=>{e.stopPropagation()}),this.boardEl.appendChild(this.toolbarEl),this.handleSelectionChange=()=>{this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.onSelectionChange())},this.handleMouseDown=e=>{this.toolbarEl.contains(e.target)&&e.preventDefault()},document.addEventListener(`selectionchange`,this.handleSelectionChange),this.boardEl.addEventListener(`mousedown`,this.handleMouseDown)}setReadOnly(e){this.readOnly=e,e&&this.hide()}setViewOnly(e){this.viewOnly=e,e&&this.hide()}destroy(){document.removeEventListener(`selectionchange`,this.handleSelectionChange),this.boardEl.removeEventListener(`mousedown`,this.handleMouseDown),this.rafId&&cancelAnimationFrame(this.rafId),this.toolbarEl.remove()}hide(){this.toolbarEl.style.display=`none`,this.activeContentEl=null,this.savedRange=null,this.subPanelOpen=!1}updatePosition(){if(!this.activeContentEl)return;let e=document.getSelection(),t=this.savedRange??(e&&e.rangeCount>0?e.getRangeAt(0):null);t&&this.positionToolbar(t)}onSelectionChange(){if(this.readOnly||this.viewOnly){this.hide();return}if(this.subPanelOpen)return;let e=document.getSelection();if(!e||e.rangeCount===0||e.isCollapsed){this.hide();return}let t=e.getRangeAt(0),n=t.commonAncestorContainer,r=(n.nodeType===Node.TEXT_NODE?n.parentElement:n)?.closest(`.wema-note-content`);if(!r||!this.boardEl.contains(r)){this.hide();return}this.activeContentEl=r,this.buildToolbar(),this.toolbarEl.style.display=``,this.positionToolbar(t)}buildToolbar(){this.toolbarEl.innerHTML=``;let e=(e,t,n,r)=>{let i=v(`button`,`wema-richtext-btn`);return i.innerHTML=e,y(i,t),i.classList.toggle(`active`,r),i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.toggleInline(n)}),i},t=e(`<b>B</b>`,this.labels.bold,Yn,this.isFormatActive(`bold`)),n=e(`<s>S</s>`,this.labels.strikethrough,Xn,this.findSelectionAncestor(Xn)!==null),r=v(`button`,`wema-richtext-btn`);r.innerHTML=`<span style="border-bottom: 2px solid currentColor;">A</span>`,y(r,this.labels.textColor);let i=this.buildColorPalette();i.style.display=`none`,r.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation();let t=i.style.display!==`none`;i.style.display=t?`none`:``,o.style.display=`none`,this.subPanelOpen=!t});let a=v(`button`,`wema-richtext-btn`);a.innerHTML=`🔗`,y(a,this.labels.link);let o=this.buildLinkInput();o.style.display=`none`,a.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation();let t=o.style.display!==`none`;if(o.style.display=t?`none`:``,i.style.display=`none`,this.subPanelOpen=!t,t)this.savedRange=null;else{let e=document.getSelection();e&&e.rangeCount>0&&(this.savedRange=e.getRangeAt(0).cloneRange());let t=this.getParentTag(`a`),n=o.querySelector(`input`);n.value=t?t.href:``,setTimeout(()=>n.focus(),0)}});let s=v(`button`,`wema-richtext-btn`);s.textContent=`❞`,y(s,this.labels.quote),s.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.quoteSelection()}),this.toolbarEl.appendChild(t),this.toolbarEl.appendChild(n),this.toolbarEl.appendChild(r),this.toolbarEl.appendChild(a),this.toolbarEl.appendChild(s),this.toolbarEl.appendChild(i),this.toolbarEl.appendChild(o)}buildColorPalette(){let e=v(`div`,`wema-richtext-colors`);for(let t of Jn){let n=v(`button`,`wema-color-swatch`);n.style.backgroundColor=t,n.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.applyColor(t)}),e.appendChild(n)}return e}buildLinkInput(){let e=v(`div`,`wema-richtext-link-input`),t=document.createElement(`input`);t.type=`url`,t.placeholder=`https://...`,t.addEventListener(`mousedown`,e=>e.stopPropagation()),t.addEventListener(`click`,e=>e.stopPropagation());let n=v(`button`,`wema-richtext-btn`);n.textContent=this.labels.ok,n.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation();let r=t.value.trim();r&&this.applyLink(r),e.style.display=`none`,this.subPanelOpen=!1});let r=v(`button`,`wema-richtext-btn`);return r.textContent=`✕`,y(r,this.labels.removeLink),r.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeLink(),e.style.display=`none`,this.subPanelOpen=!1}),e.appendChild(t),e.appendChild(n),e.appendChild(r),e}positionToolbar(e){b(this.toolbarEl,this.boardEl,x(e,this.boardEl),`above`,8)}isFormatActive(e){try{return document.queryCommandState(e)}catch{return!1}}getParentTag(e){let t=document.getSelection();if(!t||t.rangeCount===0)return null;let n=t.anchorNode;for(;n&&n!==this.activeContentEl;){if(n.nodeType===Node.ELEMENT_NODE&&n.tagName.toLowerCase()===e)return n;n=n.parentNode}return null}findSelectionAncestor(e){let t=document.getSelection();if(!t||t.rangeCount===0)return null;let n=this.findAncestor(t.getRangeAt(0).commonAncestorContainer,e);return n&&this.activeContentEl?.contains(n)?n:null}toggleInline(e){let t=document.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let n=this.findSelectionAncestor(e);n?this.unwrapElement(n):this.wrapSelection(e[0]),this.triggerInput()}quoteSelection(){let e=this.activeContentEl?w(this.activeContentEl):null,t=this.activeContentEl?.closest(`.wema-note`)?.dataset.noteId;if(!e||e.collapsed||!t)return;let n=document.createElement(`div`);if(n.appendChild(e.cloneContents()),n.textContent?.trim()===``&&!n.querySelector(`img, iframe, video, audio`))return;if(n.querySelector(`:scope > li`)){let t=e.commonAncestorContainer,r=(t instanceof Element?t:t.parentElement)?.closest(`ul, ol`),i=r?r.cloneNode(!1):document.createElement(`ul`);i.append(...n.childNodes),n.appendChild(i)}let r=n.innerHTML;document.getSelection()?.removeAllRanges(),this.hide(),this.onQuote(t,r)}applyColor(e){let t=document.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let n=t.getRangeAt(0),r=this.findColorSpan(n.commonAncestorContainer);if(r&&this.activeContentEl?.contains(r))r.style.color=e;else{let t=document.createElement(`span`);t.style.color=e,this.wrapSelectionWithElement(t)}this.triggerInput()}applyLink(e){if(!this.activeContentEl)return;if(!A(e)){this.savedRange=null;return}this.restoreSavedRange();let t=document.getSelection();if(!t||t.rangeCount===0)return;let n=this.getParentTag(`a`);if(n)n.href=e;else{if(t.isCollapsed)return;let n=document.createElement(`a`);n.href=e,n.target=`_blank`,n.rel=`noopener`,this.wrapSelectionWithElement(n)}this.savedRange=null,this.triggerInput()}removeLink(){this.restoreSavedRange();let e=this.getParentTag(`a`);e&&this.activeContentEl?.contains(e)&&(this.unwrapElement(e),this.triggerInput()),this.savedRange=null}restoreSavedRange(){if(!this.savedRange||!this.activeContentEl)return;this.activeContentEl.focus();let e=document.getSelection();e&&(e.removeAllRanges(),e.addRange(this.savedRange))}wrapSelection(e){let t=document.createElement(e);this.wrapSelectionWithElement(t)}wrapSelectionWithElement(e){let t=document.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let n=t.getRangeAt(0),r=n.extractContents();e.appendChild(r),n.insertNode(e);let i=document.createRange();i.selectNodeContents(e),t.removeAllRanges(),t.addRange(i)}unwrapElement(e){let t=e.parentNode;if(t){for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}}findAncestor(e,t){let n=e;for(;n&&n!==this.activeContentEl;){if(n.nodeType===Node.ELEMENT_NODE){let e=n.tagName.toLowerCase();if(t.includes(e))return n}n=n.parentNode}return null}findColorSpan(e){let t=e;for(;t&&t!==this.activeContentEl;){if(t.nodeType===Node.ELEMENT_NODE){let e=t;if(e.tagName.toLowerCase()===`span`&&e.style.color)return t}t=t.parentNode}return null}triggerInput(){this.activeContentEl&&this.activeContentEl.dispatchEvent(new Event(`input`,{bubbles:!0}))}},Qn=class{x=0;y=0;zoom;minZoom;maxZoom;boardEl;layerEl;constructor(e){this.boardEl=e.boardEl,this.layerEl=e.layerEl;let t=(e,t)=>e!==void 0&&Number.isFinite(e)&&e>0?e:t;this.minZoom=t(e.minZoom,.25),this.maxZoom=Math.max(t(e.maxZoom,2),this.minZoom),this.zoom=this.clampZoom(1),this.layerEl.style.transformOrigin=`0 0`,this.applyTransform()}get(){return{x:this.x,y:this.y,zoom:this.zoom}}clampZoom(e){return Math.min(this.maxZoom,Math.max(this.minZoom,e))}set(e){let t=e.x??this.x,n=e.y??this.y,r=this.clampZoom(e.zoom??this.zoom);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||t===this.x&&n===this.y&&r===this.zoom?!1:(this.x=t,this.y=n,this.zoom=r,this.applyTransform(),!0)}applyTransform(){let e=this.zoom===1?``:` scale(${this.zoom})`;this.layerEl.style.transform=`translate(${this.x}px, ${this.y}px)${e}`}screenCenter(){return{x:this.boardEl.clientWidth/2,y:this.boardEl.clientHeight/2}}clientToScreen(e,t){let n=this.boardEl.getBoundingClientRect();return{x:e-n.left,y:t-n.top}}screenToBoard(e,t){return{x:(e-this.x)/this.zoom,y:(t-this.y)/this.zoom}}boardToScreen(e,t){return{x:e*this.zoom+this.x,y:t*this.zoom+this.y}}boardBoxToScreen(e){let t=this.boardToScreen(e.left,e.top),n=this.boardToScreen(e.right,e.bottom);return{left:t.x,top:t.y,right:n.x,bottom:n.y}}clientToBoard(e,t){let n=this.clientToScreen(e,t);return this.screenToBoard(n.x,n.y)}};function $n(e){for(let t of nr){let n=e.match(t.pattern);if(n)return t.toEmbed(n)}return e}var er=/^https?:\/\/bsky\.app\/profile\/([^/]+)\/post\/([a-zA-Z0-9]+)/;async function tr(e){let t=$n(e);if(t!==e)return t;let n=e.match(er);if(n&&!n[1].startsWith(`did:`))try{let e=await fetch(`https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(n[1])}`);if(e.ok)return`https://embed.bsky.app/embed/${(await e.json()).did}/app.bsky.feed.post/${n[2]}`}catch{}return e}var nr=[{pattern:/^https?:\/\/(?:www\.)?youtube\.com\/watch\?.*v=([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://www.youtube.com/embed/${e[1]}`},{pattern:/^https?:\/\/(?:www\.)?youtube\.com\/shorts\/([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://www.youtube.com/embed/${e[1]}`},{pattern:/^https?:\/\/youtu\.be\/([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://www.youtube.com/embed/${e[1]}`},{pattern:/^https?:\/\/(?:www\.)?youtube\.com\/embed\/[a-zA-Z0-9_-]+/,toEmbed:e=>e[0]},{pattern:/^https?:\/\/(?:www\.)?vimeo\.com\/(\d+)/,toEmbed:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https?:\/\/player\.vimeo\.com\/video\/\d+/,toEmbed:e=>e[0]},{pattern:/^https?:\/\/open\.spotify\.com\/(track|album|playlist|episode|show)\/([a-zA-Z0-9]+)/,toEmbed:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`},{pattern:/^https?:\/\/docs\.google\.com\/presentation\/d\/([a-zA-Z0-9_-]+)/,toEmbed:e=>`https://docs.google.com/presentation/d/${e[1]}/embed`},{pattern:/^https?:\/\/(?:www\.)?google\.[a-z.]+\/maps\/.+/,toEmbed:e=>`https://maps.google.com/maps?output=embed&q=${encodeURIComponent(e[0])}`},{pattern:/^https?:\/\/(?:twitter\.com|x\.com)\/([a-zA-Z0-9_]+)\/status\/(\d+)/,toEmbed:e=>`https://platform.twitter.com/embed/Tweet.html?id=${e[2]}`},{pattern:/^https?:\/\/bsky\.app\/profile\/(did:[^/]+)\/post\/([a-zA-Z0-9]+)/,toEmbed:e=>`https://embed.bsky.app/embed/${e[1]}/app.bsky.feed.post/${e[2]}`}],rr=`.wema-edge-popup, .wema-note-popup, .wema-richtext-toolbar, .wema-image-overlay, .wema-embed-input`,ir=6,ar=.01,or=30,sr=80,cr=20,lr=24,ur=20,dr=e=>e.order?{...e,order:[...e.order]}:{...e},fr=(e,t,n)=>(n-(t-e))/2,pr=class e{emitter=new a;boardEl;viewportEl;svgEl;view;wheelPan;wheelZoom;emptyDrag;panMargin;spaceHeld=!1;pointerInside=!1;pageScroll=!1;holdsPageHeight=!1;stack=null;restackPending=!1;flushQueued=!1;embedInput=null;overlayObserver=null;pan=null;panMoved=!1;noteManager;dragManager;selectionManager;edgeManager;anchorDragManager;resizeManager;edgePopup;notePopup;richTextToolbar;historyManager;noteAnimator;visibilitySuspended=!1;noteFilter=null;hiddenNoteIds=new Set;redrawNoteLinkPeers=null;noteLinkLines=new Map;reportedHidden=new Set;visibilityPending=!1;buttonEdges=[];stackedSides=new Map;onImageUpload;changePending=!1;measuredSizes=new Map;container;labels;readOnly;viewOnly;defaultNoteWidth;defaultNoteHeight;positionSnapshot=null;collapsedEdgeSnapshot=null;theme;rubberBandMoved=!1;noteDragged=!1;handleDblClick;handleKeyDown;handleBoardClick;handleRubberBandDown;handleRubberBandMove;handleRubberBandUp;handlePanDown;handlePanMove;handlePanUp;handlePointerEnter;handlePointerLeave;handleSpaceDown;handleKeyUp;handleBlur;handlePageChange;handleWheel;constructor(e){this.container=e.container,this.labels=i(e.labels,e.foldLabels),this.readOnly=e.readOnly??!1,this.viewOnly=e.viewOnly??!1,this.defaultNoteWidth=e.defaultNoteWidth??200,this.defaultNoteHeight=e.defaultNoteHeight??150,this.theme=e.theme??`default`,this.onImageUpload=e.onImageUpload,this.wheelPan=e.wheelPan??!0,this.wheelZoom=e.wheelZoom??!0,this.emptyDrag=e.emptyDrag===`pan`?`pan`:`select`,this.panMargin=e.panMargin!==void 0&&e.panMargin>=0?e.panMargin:200,this.boardEl=v(`div`,`wema-board`),this.theme!=="default"&&this.boardEl.classList.add(`wema-theme-${this.theme}`),E(this.boardEl,{position:`relative`,width:`100%`,height:`100%`,overflow:`hidden`}),this.boardEl.tabIndex=0,this.viewportEl=v(`div`,`wema-viewport`),E(this.viewportEl,{position:`absolute`,top:`0`,left:`0`,width:`0`,height:`0`}),this.boardEl.appendChild(this.viewportEl),this.view=new Qn({boardEl:this.boardEl,layerEl:this.viewportEl,minZoom:e.minZoom,maxZoom:e.maxZoom}),this.svgEl=S(`svg`,`wema-edges`),this.svgEl.setAttribute(`width`,`1`),this.svgEl.setAttribute(`height`,`1`),E(this.svgEl,{position:`absolute`,top:`0`,left:`0`,overflow:`visible`,pointerEvents:`none`}),this.viewportEl.appendChild(this.svgEl),this.container.appendChild(this.boardEl);let t=null;e.noteLinks&&!e.renderNoteFooter&&(t=e.noteLinks===!0?{}:e.noteLinks);let n;if(t){let e=t.text,{padding:r}=t,i=typeof r==`number`&&Number.isFinite(r)&&r>=0?r:void 0,a={labels:this.labels,isHidden:e=>this.hiddenNoteIds.has(e),reveal:e=>this.revealNotes([e],{padding:i}),getElement:e=>this.noteManager.getElement(e)};n=(t,n)=>Nt(n,kt(t.id,this.edgeManager.getEdgesOf(t.id),e=>this.noteManager.getNote(e),e,this.noteLinkLines),a)}this.noteManager=new tt({boardEl:this.boardEl,layerEl:this.viewportEl,emitter:this.emitter,defaultWidth:e.defaultNoteWidth??200,defaultHeight:e.defaultNoteHeight??150,defaultColor:e.defaultNoteColor??`#FFF9C4`,readOnly:this.readOnly,onMeasure:(e,t)=>{this.edgeManager.updateEdgesOf(e),this.updatePageHeight(),this.placeOverlays(),this.scheduleMeasure(e,t),this.scheduleChange()},onPlacedMeasure:()=>this.scheduleRestack(),onLinkClick:e.onLinkClick,hostRender:e.renderNote,hostFooter:n??e.renderNoteFooter,hostAccessory:e.renderNoteAccessory,onUnderChange:()=>this.queueFlush(),onUnderResize:()=>this.followUnder(),labels:this.labels}),this.selectionManager=new lt({layerEl:this.viewportEl,noteManager:this.noteManager,emitter:this.emitter,isSelectable:e=>!this.hiddenNoteIds.has(e)}),this.edgeManager=new mt({boardEl:this.boardEl,svgEl:this.svgEl,noteManager:this.noteManager,emitter:this.emitter});let r=()=>this.readOnly||this.viewOnly,a=()=>this.stack!==null;if(this.dragManager=new ct({boardEl:this.boardEl,noteManager:this.noteManager,getReadOnly:()=>this.readOnly||a(),getSelection:()=>this.selectionManager.getSelection(),toBoardPoint:(e,t)=>this.view.clientToBoard(e,t),onDragStart:()=>{this.notePopup.hide(),this.noteDragged=!0,this.historyManager.beginBatch()},onDragEnd:e=>{this.historyManager.endBatch(),this.selectionManager.getSelection().includes(e)||this.selectionManager.select([e]),this.updateNotePopup()}}),this.anchorDragManager=new Pt({boardEl:this.boardEl,svgEl:this.svgEl,noteManager:this.noteManager,edgeManager:this.edgeManager,emitter:this.emitter,getReadOnly:r,toBoardPoint:(e,t)=>this.view.clientToBoard(e,t),onDropOnEmpty:(e,t,n)=>{let r=this.noteManager.addNote(this.newNotePlace({x:e-this.defaultNoteWidth/2,y:t-this.defaultNoteHeight/2}));this.edgeManager.addEdge(n,r.id,{fromAnchor:`auto`,toAnchor:`auto`}),this.stack&&this.revealNotes([r.id])}}),this.resizeManager=new Rt({boardEl:this.boardEl,noteManager:this.noteManager,getReadOnly:()=>r()||a(),toBoardPoint:(e,t)=>this.view.clientToBoard(e,t),onResizeStart:()=>{this.historyManager.beginBatch()},onResizeEnd:()=>{this.historyManager.endBatch()},onDoublePress:e=>{let t=this.selectionManager.getSelection();this.resizeNotesToContent(t.includes(e)?t:[e])}}),this.edgePopup=new qt({boardEl:this.boardEl,view:this.view,edgeManager:this.edgeManager,noteManager:this.noteManager,labels:this.labels,onDelete:e=>{this.edgeManager.deselectEdge(),this.edgeManager.deleteEdge(e)}}),this.notePopup=new sn({boardEl:this.boardEl,noteManager:this.noteManager,labels:this.labels,toScreenBox:e=>this.view.boardBoxToScreen(e),onColorChange:(e,t)=>{this.noteManager.updateNote(e,{color:t})},onMultiColorChange:(e,t)=>{for(let n of e)this.noteManager.updateNote(n,{color:t})},onDuplicate:e=>{let t=this.noteManager.getNote(e);if(!t)return;let n=this.noteManager.addNote({...this.newNotePlace({x:t.x+20,y:t.y+20}),width:t.width,height:t.height,text:t.text,color:t.color,...t.autoSize?{autoSize:!0}:{},...t.foldable?{foldable:!0}:{}});this.selectionManager.select([n.id]),this.notePopup.show(n.id),this.stack&&this.revealNotes([n.id])},onDelete:e=>{this.deleteNote(e)},onMultiDelete:e=>{for(let t of e)this.deleteNote(t)},onInsertImage:e=>{this.insertImageIntoNote(e)},onInsertEmbed:e=>{this.showEmbedInput(e)},onAutoSizeToggle:e=>{let t=this.noteManager.getNote(e);t&&(this.noteManager.updateNote(e,{autoSize:!t.autoSize}),this.notePopup.show(e))},onMultiAutoSizeToggle:e=>{let t=this.getNotesByIds(e).every(e=>e.autoSize);for(let n of e)this.noteManager.updateNote(n,{autoSize:!t});this.notePopup.showMulti(e)},onFoldableToggle:e=>{let t=!this.getNotesByIds(e).every(e=>e.foldable);this.batch(()=>{for(let n of e)this.noteManager.updateNote(n,{foldable:t})}),this.updateNotePopup()}}),this.richTextToolbar=new Zn({boardEl:this.boardEl,labels:this.labels,readOnly:this.readOnly,viewOnly:this.viewOnly,onQuote:(e,t)=>this.quoteInNewNote(e,t)}),typeof ResizeObserver<`u`){this.overlayObserver=new ResizeObserver(()=>this.placeOverlays()),this.overlayObserver.observe(this.boardEl);for(let e of this.boardEl.children)e.matches(rr)&&this.overlayObserver.observe(e)}if(this.historyManager=new qn(this.emitter,this.createReplay(`local`)),this.noteAnimator=new at({noteManager:this.noteManager,onFrame:e=>this.followShownNotes(e)}),this.emitter.on(`note:update`,({note:e,prev:t})=>{Ke(e,t)&&(this.stack||this.noteAnimator.cancel(e.id),this.updatePageHeight()),this.edgeManager.updateEdgesOf(e.id),this.scheduleRestack()}),this.emitter.on(`note:create`,({note:e,origin:t})=>{t===`remote`&&this.positionSnapshot?.set(e.id,{x:e.x,y:e.y})}),this.emitter.on(`note:update`,({note:e,prev:t,origin:n})=>{let r=n===`remote`?this.positionSnapshot?.get(e.id):void 0;r&&(e.x!==t.x&&(r.x=e.x),e.y!==t.y&&(r.y=e.y))}),this.emitter.on(`edge:create`,({edge:e,origin:t})=>{t===`remote`&&this.collapsedEdgeSnapshot?.set(e.id,!!e.collapsed)}),this.emitter.on(`edge:update`,({edge:e,prev:t,origin:n})=>{n===`remote`&&e.collapsed!==t.collapsed&&this.collapsedEdgeSnapshot?.set(e.id,!!e.collapsed)}),t){let e=e=>e.forEach(e=>this.noteManager.requestFooter(e)),t=t=>{if(this.stack)for(let n of t)e(this.edgeManager.getEdgesOf(n).map(e=>Dt(e,n)))};this.redrawNoteLinkPeers=t;let n=({edge:t})=>e([t.from,t.to]);this.emitter.on(`edge:create`,n),this.emitter.on(`edge:update`,n),this.emitter.on(`edge:delete`,n),this.emitter.on(`note:update`,({note:e,prev:n})=>{(e.text!==n.text||!de(e.meta,n.meta))&&t([e.id])}),this.emitter.on(`note:delete`,({note:e})=>this.noteLinkLines.delete(e.id)),this.emitter.on(`note:visibility`,({hidden:e,shown:n})=>t([...e,...n]))}this.emitter.on(`edge:create`,()=>this.recomputeVisibility()),this.emitter.on(`edge:update`,()=>this.recomputeVisibility()),this.emitter.on(`edge:delete`,()=>this.recomputeVisibility()),this.emitter.on(`note:create`,({note:e})=>{this.historyManager.isReplaying()||this.noteFilter?.add(e.id),this.recomputeVisibility()}),this.emitter.on(`note:delete`,()=>this.recomputeVisibility()),this.emitter.on(`note:create`,()=>this.scheduleChange()),this.emitter.on(`note:update`,()=>this.scheduleChange()),this.emitter.on(`note:delete`,()=>this.scheduleChange()),this.emitter.on(`edge:create`,()=>this.scheduleChange()),this.emitter.on(`edge:update`,()=>this.scheduleChange()),this.emitter.on(`edge:delete`,()=>this.scheduleChange()),this.handleDblClick=t=>{if(t.target.closest(`.wema-note, ${rr}`))return;if(!this.readOnly&&!this.viewOnly&&(e.createOnDblClick??!0)){let e=this.addNote(this.newNotePlace(this.view.clientToBoard(t.clientX,t.clientY)));this.stack&&this.revealNotes([e.id]);return}let n=this.view.get(),r=this.view.clientToScreen(t.clientX,t.clientY),i=this.view.screenCenter();this.panWithinLimit({x:n.x+i.x-r.x,y:n.y+i.y-r.y})},this.boardEl.addEventListener(`dblclick`,this.handleDblClick),this.handleKeyDown=e=>{if((e.ctrlKey||e.metaKey)&&!this.readOnly&&!this.viewOnly&&!e.target.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select`)){if(e.key===`z`&&!e.shiftKey){e.preventDefault(),this.undo();return}if(e.key===`z`&&e.shiftKey||e.key===`y`){e.preventDefault(),this.redo();return}}if(!(this.readOnly||this.viewOnly)&&(e.key===`Delete`||e.key===`Backspace`)){if(e.target.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select`))return;let t=this.edgeManager.getSelectedEdge();if(t){this.edgeManager.deleteEdge(t);return}let n=this.selectionManager.getSelection();this.notePopup.hide();for(let e of n)this.deleteNote(e)}},this.boardEl.addEventListener(`keydown`,this.handleKeyDown),this.handleBoardClick=e=>{if(this.panMoved){this.panMoved=!1;return}if(this.rubberBandMoved){this.rubberBandMoved=!1;return}if(this.noteDragged){this.noteDragged=!1;return}if(e.target.closest(rr)||this.readOnly)return;let t=this.viewOnly?null:this.edgeManager.hitTest(e.clientX,e.clientY);if(t){this.selectionManager.clear(),this.notePopup.hide(),this.edgeManager.selectEdge(t),this.edgePopup.show(t,e.clientX,e.clientY),this.boardEl.focus();return}this.edgeManager.deselectEdge(),this.edgePopup.hide();let n=e.target.closest(`.wema-note`);if(n){let t=n.dataset.noteId;t&&(e.shiftKey?this.selectionManager.addToSelection([t]):e.ctrlKey||e.metaKey?this.selectionManager.toggleSelection(t):this.selectionManager.select([t]),this.noteManager.bringToFront(t),this.updateNotePopup())}else this.selectionManager.clear(),this.notePopup.hide();let r=document.activeElement;(!r||!r.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select`))&&this.boardEl.focus()},this.boardEl.addEventListener(`click`,this.handleBoardClick),this.handleRubberBandDown=e=>{if(e.button!==0||this.readOnly||this.pan||this.leavesToPage(e)||e.target.closest(`.wema-note, ${rr}`))return;let{x:t,y:n}=this.view.clientToBoard(e.clientX,e.clientY);this.selectionManager.startRubberBand(t,n),this.boardEl.setPointerCapture(e.pointerId),this.boardEl.addEventListener(`pointermove`,this.handleRubberBandMove),this.boardEl.addEventListener(`pointerup`,this.handleRubberBandUp),this.boardEl.addEventListener(`pointercancel`,this.handleRubberBandUp)},this.handleRubberBandMove=e=>{if(!this.selectionManager.isRubberBandActive())return;this.rubberBandMoved=!0;let{x:t,y:n}=this.view.clientToBoard(e.clientX,e.clientY);this.selectionManager.updateRubberBand(t,n)},this.handleRubberBandUp=e=>{this.boardEl.removeEventListener(`pointermove`,this.handleRubberBandMove),this.boardEl.removeEventListener(`pointerup`,this.handleRubberBandUp),this.boardEl.removeEventListener(`pointercancel`,this.handleRubberBandUp);try{this.boardEl.releasePointerCapture(e.pointerId)}catch{}this.selectionManager.endRubberBand(),this.updateNotePopup()},this.boardEl.addEventListener(`pointerdown`,this.handleRubberBandDown),this.handlePanDown=e=>{if(this.leavesToPage(e)){e.stopPropagation();return}if(!this.wantsPan(e))return;e.preventDefault(),e.stopPropagation();let t=!e.target.closest(`.wema-note`);e.button===0&&t&&this.boardEl.focus({preventScroll:!0}),this.pan={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1},this.boardEl.classList.add(`wema-panning`),this.boardEl.setPointerCapture(e.pointerId),this.boardEl.addEventListener(`pointermove`,this.handlePanMove),this.boardEl.addEventListener(`pointerup`,this.handlePanUp),this.boardEl.addEventListener(`pointercancel`,this.handlePanUp)},this.handlePanMove=e=>{if(!this.pan||e.pointerId!==this.pan.pointerId)return;let t=e.clientX-this.pan.startX,n=e.clientY-this.pan.startY;(Math.abs(t)>=4||Math.abs(n)>=4)&&(this.pan.moved=!0);let r=this.view.get();this.panWithinLimit({x:r.x+e.clientX-this.pan.lastX,y:r.y+e.clientY-this.pan.lastY}),this.pan.lastX=e.clientX,this.pan.lastY=e.clientY},this.handlePanUp=e=>{if(this.pan&&e.pointerId===this.pan.pointerId){this.boardEl.removeEventListener(`pointermove`,this.handlePanMove),this.boardEl.removeEventListener(`pointerup`,this.handlePanUp),this.boardEl.removeEventListener(`pointercancel`,this.handlePanUp);try{this.boardEl.releasePointerCapture(e.pointerId)}catch{}this.panMoved=this.pan.moved&&e.type===`pointerup`&&e.button===0,this.pan=null,this.boardEl.classList.remove(`wema-panning`)}},this.handlePointerEnter=()=>{this.pointerInside=!0},this.handlePointerLeave=()=>{this.pointerInside=!1},this.handleSpaceDown=e=>{e.code!==`Space`||e.ctrlKey||e.metaKey||e.altKey||this.pointerInside&&!this.pageScroll&&(document.activeElement?.closest(`[contenteditable]:not([contenteditable="false"]), input, textarea, select, button`)||(e.preventDefault(),this.setSpaceHeld(!0)))},this.handleKeyUp=e=>{e.code===`Space`&&this.setSpaceHeld(!1)},this.handleBlur=()=>this.setSpaceHeld(!1),this.handlePageChange=()=>this.placeOverlays(),this.handleWheel=e=>{if(this.pageScroll)return;let t=e.target,n=e.deltaMode===1?16:e.deltaMode===2?this.boardEl.clientHeight:1,r=this.view.get();if(e.ctrlKey||e.metaKey){if(!this.wheelZoom)return;e.preventDefault();let t=Math.max(-30,Math.min(or,e.deltaY*n));this.panWithinLimit(this.zoomedAround(r.zoom*2**(-t*ar),e));return}if(!this.wheelPan||t.closest(rr))return;let i=t.closest(`.wema-note-content, .wema-note-custom`);if(i&&i.scrollHeight>i.clientHeight)return;e.preventDefault();let a=e.deltaX*n,o=e.deltaY*n;e.shiftKey&&a===0&&(a=o,o=0),this.panWithinLimit({x:r.x-a,y:r.y-o})},this.boardEl.addEventListener(`pointerdown`,this.handlePanDown,!0),this.boardEl.addEventListener(`pointerenter`,this.handlePointerEnter),this.boardEl.addEventListener(`pointerleave`,this.handlePointerLeave),document.addEventListener(`keydown`,this.handleSpaceDown),document.addEventListener(`keyup`,this.handleKeyUp),window.addEventListener(`blur`,this.handleBlur),window.addEventListener(`scroll`,this.handlePageChange,{capture:!0,passive:!0}),window.addEventListener(`resize`,this.handlePageChange),this.boardEl.addEventListener(`wheel`,this.handleWheel,{passive:!1}),e.data&&this.importData(e.data),this.viewOnly&&this.enterViewOnly(),e.pageScroll&&this.setPageScroll(!0),e.stacked&&this.setStacked(e.stacked)}destroy(){this.boardEl.removeEventListener(`dblclick`,this.handleDblClick),this.boardEl.removeEventListener(`keydown`,this.handleKeyDown),this.boardEl.removeEventListener(`click`,this.handleBoardClick),this.boardEl.removeEventListener(`pointerdown`,this.handleRubberBandDown),this.boardEl.removeEventListener(`pointermove`,this.handleRubberBandMove),this.boardEl.removeEventListener(`pointerup`,this.handleRubberBandUp),this.boardEl.removeEventListener(`pointerdown`,this.handlePanDown,!0),this.boardEl.removeEventListener(`pointermove`,this.handlePanMove),this.boardEl.removeEventListener(`pointerup`,this.handlePanUp),this.boardEl.removeEventListener(`pointercancel`,this.handlePanUp),this.boardEl.removeEventListener(`pointerenter`,this.handlePointerEnter),this.boardEl.removeEventListener(`pointerleave`,this.handlePointerLeave),document.removeEventListener(`keydown`,this.handleSpaceDown),document.removeEventListener(`keyup`,this.handleKeyUp),window.removeEventListener(`blur`,this.handleBlur),window.removeEventListener(`scroll`,this.handlePageChange,{capture:!0}),window.removeEventListener(`resize`,this.handlePageChange),this.boardEl.removeEventListener(`wheel`,this.handleWheel),this.overlayObserver?.disconnect(),this.noteAnimator.clear(),this.measuredSizes.clear(),this.restackPending=!1,this.noteManager.destroy(),this.dragManager.destroy(),this.anchorDragManager.destroy(),this.resizeManager.destroy(),this.edgePopup.destroy(),this.notePopup.destroy(),this.richTextToolbar.destroy(),this.historyManager.destroy(),this.selectionManager.destroy(),this.edgeManager.destroy(),this.emitter.removeAllListeners(),this.boardEl.remove()}addNote(e){if(this.readOnly||this.viewOnly)return;let{left:t,top:n}=this.pageScroll?this.boardEl.getBoundingClientRect():{left:0,top:0},r=this.view.screenToBoard(Math.max(-t,0),Math.max(-n,0)),i=this.newNotePlace({x:r.x+100,y:r.y+100});return this.noteManager.addNote({...e,x:e?.x??i.x,y:e?.y??i.y})}newNotePlace(e){let t=this.stack?this.noteManager.getNotes():[];if(t.length===0)return e;let n=s(t);return{x:n.left,y:n.bottom+ur}}updateNote(e,t){this.readOnly||this.noteManager.updateNote(e,t)}deleteNote(e){this.readOnly||this.viewOnly||this.removeNote(e)}getNote(e){return this.noteManager.getNote(e)}refreshNote(e){this.noteManager.refresh(e)&&this.updateNotePopup(),this.redrawNoteLinkPeers?.([e])}refreshNoteAccessory(e){this.noteManager.requestAccessory(e)}resizeNotesToContent(e){this.readOnly||this.viewOnly||(this.batch(()=>{for(let t of e)this.noteManager.resizeToContent(t)}),this.updateNotePopup())}quoteInNewNote(e,t){if(this.readOnly||this.viewOnly)return;this.noteManager.getTextElement(e)?.blur();let n=this.noteManager.getNote(e);if(!n)return;let r=n.width,i=this.defaultNoteHeight,a=this.pageScroll?n.x:n.x+n.width+sr,o=this.pageScroll?n.y+n.height+cr:n.y,s=this.noteManager.getNotes().filter(e=>!this.hiddenNoteIds.has(e.id)&&e.x<a+r&&e.x+e.width>a).sort((e,t)=>e.y-t.y);for(let e of s)e.y<o+i&&e.y+e.height>o&&(o=e.y+e.height+cr);({x:a,y:o}=this.newNotePlace({x:a,y:o}));let c=this.batch(()=>{let s=this.noteManager.addNote({x:a,y:o,width:r,height:i,text:`<blockquote>${t}</blockquote><div><br></div>`,color:n.color,autoSize:n.autoSize,foldable:n.foldable});return this.edgeManager.addEdge(e,s.id),s},{origin:`user`});this.selectionManager.select([c.id]),this.updateNotePopup(),this.revealNotes([c.id])}getNotes(){return this.noteManager.getNotes()}addEdge(e,t,n){if(!(this.readOnly||this.viewOnly))return this.edgeManager.addEdge(e,t,n)}getSelectedEdge(){return this.edgeManager.getSelectedEdge()}updateEdge(e,t){if(!this.readOnly){if(this.viewOnly){if(!(`collapsed`in t))return;t={collapsed:t.collapsed}}this.edgeManager.updateEdge(e,t)}}deleteEdge(e){this.readOnly||this.viewOnly||this.edgeManager.deleteEdge(e)}getEdges(){return this.edgeManager.getEdges()}getEdgesOf(e){return this.edgeManager.getEdgesOf(e)}updateNotePopup(){if(this.viewOnly)return;let e=this.selectionManager.getSelection();e.length===1?this.notePopup.show(e[0]):e.length>=2?this.notePopup.showMulti(e):this.notePopup.hide()}select(e){this.selectionManager.select(e)}selectAll(){this.selectionManager.selectAll(),this.updateNotePopup()}getSelection(){return this.selectionManager.getSelection()}setNoteFilter(e){this.noteFilter=e?new Set(e):null,this.recomputeVisibility()}getNoteFilter(){return this.noteFilter?Array.from(this.noteFilter):null}isNoteHidden(e){return this.hiddenNoteIds.has(e)}getViewport(){return this.view.get()}setViewport(e){this.pageScroll||this.applyViewport(e)}applyViewport(e){this.view.set(e)&&(this.placeOverlays(),this.emitter.emit(`viewport:change`,this.getViewport()))}zoomTo(e,t){this.setViewport(this.zoomedAround(e,t))}zoomedAround(e,t){let n=this.view.get(),r=this.view.clampZoom(e),i=t?this.view.clientToScreen(t.clientX,t.clientY):this.view.screenCenter(),a=r/n.zoom;return{x:i.x-(i.x-n.x)*a,y:i.y-(i.y-n.y)*a,zoom:r}}panWithinLimit(e){let t=Number.isFinite(this.panMargin)?this.visibleBounds():null;if(!t){this.setViewport(e);return}let n=this.view.get(),r=e.zoom??n.zoom,i=this.panMargin,a=r===n.zoom,o=(e,t,n,o,s)=>{let c=Math.min(s-i-o*r,-n*r),l=Math.max(i-n*r,s-o*r);return a&&(c=Math.min(c,t),l=Math.max(l,t)),Math.min(Math.max(e,c),l)+0};this.setViewport({x:o(e.x,n.x,t.left,t.right,this.boardEl.clientWidth),y:o(e.y,n.y,t.top,t.bottom,this.boardEl.clientHeight),zoom:r})}revealNotes(e,t){let n=t?.padding??24;if(this.pageScroll){this.scrollPageToNotes(e,n);return}this.moveToNotes(e,n,(e,t,r)=>e<n?n:t>r-n?r-n-(t-e):e)}centerContent(e){this.moveToNotes(e?.noteIds,e?.padding??24,fr)}fitToContent(e){let t=e?.padding??24;this.moveToNotes(e?.noteIds,t,fr,(n,r,i,a)=>Math.min(Math.max(i-t*2,1)/Math.max(n,1),Math.max(a-t*2,1)/Math.max(r,1),e?.maxZoom??1))}moveToNotes(e,t,n,r){let i=this.visibleBounds(e),a=this.boardEl.clientWidth,o=this.boardEl.clientHeight;if(!i||a===0||o===0)return;let s=this.view.get(),c=r?this.view.clampZoom(r(i.right-i.left,i.bottom-i.top,a,o)):s.zoom,l=(e,r,i,a)=>{let o=e*c+i,s=r*c+i;return i+(s-o+t*2>a?t:n(o,s,a))-o};this.setViewport({x:l(i.left,i.right,s.x,a),y:l(i.top,i.bottom,s.y,o),zoom:c})}visibleBounds(e){let t=e?new Set(e):null;this.stack&&this.flushPending();let n=this.noteManager.getPlacedBoxes().filter(e=>(!t||t.has(e.id))&&!this.hiddenNoteIds.has(e.id));return n.length===0?null:s(n)}setPageScroll(e){this.pageScroll!==e&&(e&&(this.pan&&this.handlePanUp(new PointerEvent(`pointercancel`,{pointerId:this.pan.pointerId})),this.setSpaceHeld(!1),this.applyViewport({x:0,y:0,zoom:1})),this.pageScroll=e,this.boardEl.classList.toggle(`wema-page-scroll`,e),E(this.boardEl,{height:e?`0px`:`100%`,minHeight:e?`100%`:``,overflow:e?`visible`:`hidden`}),this.updatePageHeight(),this.placeOverlays())}setStacked(e,t){(e||this.stack)&&(this.stack=e?dr(e):null,this.stackedSides.clear(),this.boardEl.classList.toggle(`wema-stacked`,this.stack!==null),this.stack&&(this.edgeManager.deselectEdge(),this.edgePopup.hide()),this.noteManager.setFootersShown(this.stack!==null),this.restack(this.noteManager.getNotes().map(e=>e.id),t?.duration))}getStacked(){return this.stack?dr(this.stack):null}restack(e=[],t){this.restackPending=!1;let n=this.stack,r=n?this.noteManager.getNotes().filter(e=>!this.hiddenNoteIds.has(e.id)).map(e=>e.id):[],i=[];this.animateNotes(e,t,()=>(i=this.noteManager.placeNotes(r,n?.width,e=>ln(e,{x:0,y:0,...n})),i)),i.length>0&&this.updateNoteCollapseBtns()}scheduleRestack(){this.stack&&(this.restackPending=!0,this.queueFlush())}queueFlush(){this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flushPending()}))}flushPending(){let e=this.restackPending;this.restackPending=!1;let t=this.noteManager.drawUnder();e||t&&this.stack?this.restack():t&&this.followUnder()}followUnder(){if(this.stack){this.scheduleRestack();return}this.updatePageHeight(),this.placeOverlays()}isPageScroll(){return this.pageScroll}updatePageHeight(){if(!this.pageScroll)return;let e=this.noteManager.lowestBottom(e=>!this.hiddenNoteIds.has(e)),t=e===null?0:Math.ceil(this.view.boardToScreen(0,e).y)+lr;if(t<(parseFloat(this.boardEl.style.height)||0)&&(this.holdsPageHeight||this.noteAnimator.isRunning()))return;let n=`${Math.max(t,0)}px`;this.boardEl.style.height!==n&&(this.boardEl.style.height=n)}leavesToPage(e){return this.pageScroll&&(e.pointerType===`touch`||this.wantsPan(e))}scrollPageToNotes(e,t){let n=this.visibleBounds(e);if(!n)return;let r=v(`div`);E(r,{position:`absolute`,left:`${n.left}px`,top:`${n.top}px`,width:`${n.right-n.left}px`,height:`${n.bottom-n.top}px`,scrollMargin:`${t}px`,visibility:`hidden`,pointerEvents:`none`}),this.viewportEl.appendChild(r),r.scrollIntoView?.({block:`nearest`,inline:`nearest`}),r.remove()}wantsPan(e){let t=e.target;if(t.closest(rr))return!1;if(e.button===1)return!0;if(e.button!==0)return!1;if(this.spaceHeld)return!0;if(t.closest(`.wema-note`))return!1;if(this.readOnly)return!0;let n=this.viewOnly||this.emptyDrag===`pan`,r=e.shiftKey||this.emptyDrag===`pan`&&(e.ctrlKey||e.metaKey);return n&&!r}setSpaceHeld(e){this.spaceHeld=e,this.boardEl.classList.toggle(`wema-pan-ready`,e)}moveNotes(e,t){this.readOnly||this.applyMoves(e,t)}alignNotes(e,t,n){this.readOnly||this.viewOnly||this.applyMoves(un(this.getNotesByIds(e),t),n)}distributeNotes(e,t,n){this.readOnly||this.viewOnly||this.applyMoves(dn(this.getNotesByIds(e),t),n)}autoLayout(e,t){if(this.readOnly||this.viewOnly)return;let n=e??this.getNoteFilter()??void 0,r=this.boardEl.clientWidth/this.boardEl.clientHeight;this.applyMoves(Rn(this.noteManager.getNotes(),this.edgeManager.getEdges(),{noteIds:n,aspectRatio:r}),t)}stackNotes(e={}){if(this.readOnly)return;let{noteIds:t,duration:n,...r}=e,i=(t??this.noteManager.getNotes().map(e=>e.id)).filter(e=>!this.hiddenNoteIds.has(e));this.animateNotes(this.movedOnScreen(i),n,()=>{r.width!==void 0&&this.setNoteRects(i.map(e=>({id:e,width:r.width}))),this.setNoteRects(ln(this.getNotesByIds(i),r))})}getNotesByIds(e){return e.map(e=>this.noteManager.getNote(e)).filter(e=>e!=null)}applyMoves(e,t){this.animateNotes(this.movedOnScreen(e.map(e=>e.id)),t?.duration,()=>this.setNoteRects(e))}movedOnScreen(e){return this.stack?[]:e}setNoteRects(e){for(let t of e){let e=this.noteManager.getNote(t.id);if(!e)continue;let n={};for(let r of Ge){if(r===`width`&&e.autoSize||r===`height`&&(e.autoSize||this.noteManager.hasMeasuredHeight(e.id)))continue;let i=t[r];typeof i==`number`&&Number.isFinite(i)&&i!==e[r]&&(n[r]=i)}Object.keys(n).length>0&&this.noteManager.updateNote(t.id,n)}}animateNotes(e,t,n){let r=typeof t==`number`&&t>0&&Number.isFinite(t)&&!it(),i=new Map;for(let t of e){let e=this.noteManager.getShownNote(t);e&&i.set(t,qe(e))}let a=[];this.holdsPageHeight=!0;try{a=n()??[]}finally{this.holdsPageHeight=!1}let o=new Set(a);for(let[e,n]of i){let i=this.noteManager.getPlacedNote(e);r&&i&&Ke(n,i)?(this.noteAnimator.start(e,n,t),o.add(e)):this.noteAnimator.cancel(e)&&o.add(e)}o.size>0?this.followShownNotes([...o]):this.updatePageHeight(),this.updateNotePopup()}followShownNotes(e){this.edgeManager.updateEdgesOfNotes(e),this.updatePageHeight(),this.placeOverlays()}batch(e,t){this.historyManager.beginBatch(t?.origin);try{return e()}finally{this.historyManager.endBatch()}}applyRemote(e){this.visibilitySuspended=!0;try{this.historyManager.withoutRecording(()=>Kn(e,this.createReplay(`remote`)))}finally{this.visibilitySuspended=!1,this.recomputeVisibility()}this.edgeManager.getSelectedEdge()||this.edgePopup.hide(),this.updateNotePopup()}createReplay(e){return{addNoteWithId:t=>{this.noteManager.addNoteWithId(t,e)},updateNote:(t,n)=>{this.noteManager.replayUpdate(t,n,e)},deleteNote:t=>{this.removeNote(t,e)},addEdgeWithId:t=>{this.edgeManager.addEdgeWithId(t,e)},updateEdge:(t,n)=>{this.edgeManager.updateEdge(t,n,e)},deleteEdge:t=>{this.edgeManager.deleteEdge(t,e)}}}removeNote(e,t=`local`){for(let n of this.edgeManager.getEdgesOf(e))this.edgeManager.deleteEdge(n.id,t);this.selectionManager.deselect(e),this.noteManager.deleteNote(e,t)}undo(){this.viewOnly||(this.notePopup.hide(),this.edgePopup.hide(),this.selectionManager.clear(),this.historyManager.undo())}redo(){this.viewOnly||(this.notePopup.hide(),this.edgePopup.hide(),this.selectionManager.clear(),this.historyManager.redo())}canUndo(){return this.historyManager.canUndo()}canRedo(){return this.historyManager.canRedo()}exportData(){let e={version:1,notes:this.noteManager.getNotesWithLiveText(),edges:this.edgeManager.getEdges()};return JSON.parse(JSON.stringify(e))}importData(e){this.noteFilter=null,this.noteAnimator.clear(),this.measuredSizes.clear(),this.noteLinkLines.clear(),this.selectionManager.clear(),this.edgeManager.clear(),this.noteManager.renderAll(e.notes),e.edges&&this.edgeManager.renderAll(e.edges),this.historyManager.clear(),this.viewOnly&&this.snapshotForViewOnly(),this.recomputeVisibility(),this.reportedHidden=new Set(this.hiddenNoteIds)}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setReadOnly(e){this.readOnly!==e&&(this.readOnly=e,this.noteManager.setReadOnly(e),this.richTextToolbar.setReadOnly(e),e?(this.boardEl.classList.add(`wema-readonly`),this.selectionManager.clear(),this.notePopup.hide(),this.edgePopup.hide()):this.boardEl.classList.remove(`wema-readonly`),this.emitter.emit(`readOnly:change`,{readOnly:e}),this.recomputeVisibility())}isReadOnly(){return this.readOnly}setViewOnly(e){if(this.viewOnly!==e){if(this.viewOnly=e,this.richTextToolbar.setViewOnly(e),e)this.selectionManager.clear(),this.enterViewOnly(),this.notePopup.hide(),this.edgePopup.hide();else{if(this.positionSnapshot){for(let[e,{x:t,y:n}]of this.positionSnapshot)this.noteManager.updateNote(e,{x:t,y:n});this.positionSnapshot=null}if(this.collapsedEdgeSnapshot){for(let[e,t]of this.collapsedEdgeSnapshot)this.edgeManager.updateEdge(e,{collapsed:t?!0:void 0});this.collapsedEdgeSnapshot=null}this.historyManager.setIgnoredKeys([],[]),this.boardEl.classList.remove(`wema-viewonly`),this.noteManager.setViewOnly(!1)}this.emitter.emit(`viewOnly:change`,{viewOnly:e}),this.recomputeVisibility()}}enterViewOnly(){this.snapshotForViewOnly(),this.historyManager.setIgnoredKeys([`x`,`y`],[`collapsed`]),this.boardEl.classList.add(`wema-viewonly`),this.noteManager.setViewOnly(!0)}snapshotForViewOnly(){this.positionSnapshot=new Map(this.noteManager.getNotes().map(e=>[e.id,{x:e.x,y:e.y}])),this.collapsedEdgeSnapshot=new Map(this.edgeManager.getEdges().map(e=>[e.id,!!e.collapsed]))}isViewOnly(){return this.viewOnly}setTheme(e){this.theme!==e&&(this.boardEl.classList.remove(`wema-theme-${this.theme}`),this.theme=e,e!=="default"&&this.boardEl.classList.add(`wema-theme-${e}`))}getTheme(){return this.theme}insertImageIntoNote(e){let t=document.createElement(`input`);t.type=`file`,t.accept=`image/*`,t.addEventListener(`change`,()=>{let n=t.files?.[0];if(!n)return;if(this.onImageUpload){this.uploadImage(e,n,this.onImageUpload);return}let r=new FileReader;r.onload=()=>{this.appendImage(e,r.result,n.name)},r.readAsDataURL(n)}),t.click()}async uploadImage(e,t,n){try{let r=await n(t);if(typeof r!=`string`||r===``||!A(r,`image/`))throw Error(`onImageUpload returned an unusable URL: ${String(r)}`);if(this.readOnly||this.viewOnly)throw Error(`The board became read-only before the upload finished`);this.appendImage(e,r,t.name)}catch(n){this.emitter.emit(`image:error`,{noteId:e,file:t,error:n})}}appendImage(e,t,n){let r=this.noteManager.getTextElement(e);if(!r)return;let i=document.createElement(`img`);i.src=t,i.alt=n,i.style.maxWidth=`100%`,r.appendChild(i),r.dispatchEvent(new Event(`input`,{bubbles:!0})),this.noteManager.updateNote(e,{text:r.innerHTML})}showEmbedInput(e){if(this.embedInput?.el.remove(),this.embedInput=null,!this.noteManager.getNote(e))return;let t=v(`div`,`wema-embed-input`);this.embedInput={el:t,noteId:e};let n=()=>{t.remove(),this.embedInput?.el===t&&(this.embedInput=null)};t.style.position=`absolute`,t.style.zIndex=`10002`,t.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`mousedown`,e=>e.stopPropagation()),t.addEventListener(`pointerdown`,e=>e.stopPropagation());let r=document.createElement(`input`);r.type=`text`,r.placeholder=`https://...`,r.style.cssText=`width:200px;padding:4px 6px;border:1px solid #ddd;border-radius:3px;font-size:12px;`;let i=v(`button`,`wema-popup-btn`);i.textContent=this.labels.ok,i.addEventListener(`click`,()=>{let t=r.value.trim();t&&this.embedUrl(e,t),n()});let a=v(`button`,`wema-popup-btn`);a.textContent=`✕`,a.addEventListener(`click`,n),t.appendChild(r),t.appendChild(i),t.appendChild(a),this.boardEl.appendChild(t),this.placeEmbedInput(),r.focus()}placeEmbedInput(){if(!this.embedInput)return;let e=this.noteManager.getShownNote(this.embedInput.noteId);if(!e)return;let{box:t,side:n}=this.notePopup.boxWith(e.id)??{box:this.view.boardBoxToScreen(s([e])),side:`below`};b(this.embedInput.el,this.boardEl,t,n,ir)}placeOverlays(){this.notePopup.updatePosition(),this.edgePopup.updatePosition(),this.richTextToolbar.updatePosition(),this.noteManager.updateOverlayPosition(),this.placeEmbedInput()}static IMAGE_URL_RE=/\.(?:png|jpe?g|gif|webp|svg|bmp|ico)(?:\?.*)?$/i;static VIDEO_URL_RE=/\.(?:mp4|webm|ogg|mov)(?:\?.*)?$/i;static AUDIO_URL_RE=/\.(?:mp3|wav|flac|aac|m4a|opus|weba)(?:\?.*)?$/i;async embedUrl(t,n){if(!A(n))return;let r=this.noteManager.getTextElement(t);if(r){if(e.IMAGE_URL_RE.test(n)){let e=document.createElement(`img`);e.src=n,r.appendChild(e)}else if(e.VIDEO_URL_RE.test(n)){let e=document.createElement(`video`);e.src=n,e.controls=!0,e.preload=`metadata`,r.appendChild(e)}else if(e.AUDIO_URL_RE.test(n)){let e=document.createElement(`audio`);e.src=n,e.controls=!0,e.preload=`metadata`,r.appendChild(e)}else{let e=await tr(n),t=document.createElement(`iframe`);t.src=e,t.width=`100%`,t.height=`200`,t.style.border=`none`,t.setAttribute(`allowfullscreen`,``),t.setAttribute(`allow`,`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`),r.appendChild(t)}r.dispatchEvent(new Event(`input`,{bubbles:!0})),this.noteManager.updateNote(t,{text:r.innerHTML})}}recomputeVisibility(){if(this.visibilitySuspended)return;let e=this.noteManager.getNotes(),t=this.edgeManager.getEdges(),n=new Set,r=new Set,i=this.noteFilter,a=e=>!i||i.has(e),o=t.filter(e=>a(e.from)&&a(e.to));for(let t of e)a(t.id)||n.add(t.id);for(let e of t)(!a(e.from)||!a(e.to))&&r.add(e.id);for(let e of o)e.collapsed&&(r.add(e.id),this.dfsHideNotes(e.to,o,n,r));this.hiddenNoteIds=n,this.scheduleVisibility();let s=this.selectionManager.getSelection(),c=s.filter(e=>!n.has(e));c.length!==s.length&&(this.selectionManager.select(c),this.updateNotePopup());let l=this.edgeManager.getSelectedEdge();l&&r.has(l)&&(this.edgeManager.deselectEdge(),this.edgePopup.hide());for(let t of e){let e=this.noteManager.getElement(t.id);if(!e)continue;let r=e.style.display===`none`,i=n.has(t.id);e.style.display=i?`none`:``,r&&!i&&this.noteManager.remeasure(t.id)}this.edgeManager.applyVisibility(r),this.buttonEdges=o,this.updateNoteCollapseBtns(),this.scheduleRestack(),this.updatePageHeight()}dfsHideNotes(e,t,n,r){if(!n.has(e)){n.add(e);for(let i of t)i.from===e&&(r.add(i.id),this.dfsHideNotes(i.to,t,n,r))}}updateNoteCollapseBtns(){let e=this.hiddenNoteIds,t=new Map;for(let e of this.buttonEdges){let n=this.noteManager.getPlacedNote(e.from),r=this.noteManager.getPlacedNote(e.to);if(!n||!r)continue;let i;e.fromAnchor===`auto`?this.stack===null?i=p(n,r):this.noteManager.isPlaced(e.from)&&this.noteManager.isPlaced(e.to)?(i=p(n,r),this.stackedSides.set(e.id,i)):i=this.stackedSides.get(e.id)??`bottom`:i=e.fromAnchor;let a=t.get(e.from);a||(a=new Map,t.set(e.from,a));let o=a.get(i);o||(o=[],a.set(i,o)),o.push(e)}let n=[`top`,`right`,`bottom`,`left`];for(let r of this.noteManager.getNotes()){let i=this.noteManager.getElement(r.id);if(!i)continue;let a=t.get(r.id);for(let t of n){let n=i.querySelector(`.wema-note-collapse-btn[data-side="${t}"]`);if(!n)continue;let o=a?.get(t);if(!o||o.length===0||e.has(r.id)||this.readOnly){n.style.display=`none`,n.classList.remove(`wema-note-collapse-badge`);continue}let s=o.every(e=>e.collapsed);n.style.display=``;let c=o.map(e=>e.id);if(n.onclick=e=>{if(e.stopPropagation(),s)for(let e of c)this.edgeManager.updateEdge(e,{collapsed:!1});else for(let e of c)this.edgeManager.updateEdge(e,{collapsed:!0})},s){let e=this.countSubtreeFromEdges(o,this.buttonEdges);n.className=`wema-note-collapse-btn wema-note-collapse-badge`,n.dataset.side=t,n.textContent=String(e)}else n.className=`wema-note-collapse-btn`,n.dataset.side=t,n.innerHTML=`<svg width="10" height="2" viewBox="0 0 10 2" fill="none"><line x1="1" y1="1" x2="9" y2="1" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`}}}countSubtreeFromEdges(e,t){let n=new Set;for(let r of e)r.collapsed&&this.countSubtreeDFS(r.to,t,n);return n.size}countSubtreeDFS(e,t,n){if(!n.has(e)){n.add(e);for(let r of t)r.from===e&&this.countSubtreeDFS(r.to,t,n)}}scheduleMeasure(e,t){this.measuredSizes.has(e)||(this.measuredSizes.set(e,t),!(this.measuredSizes.size>1)&&queueMicrotask(()=>{let e=this.measuredSizes;this.measuredSizes=new Map;for(let[t,{width:n,height:r}]of e){let e=this.noteManager.getNote(t);!e||e.width===n&&e.height===r||this.emitter.emit(`note:measure`,{note:e,prev:{...e,width:n,height:r}})}}))}scheduleVisibility(){this.visibilityPending||(this.visibilityPending=!0,queueMicrotask(()=>{this.visibilityPending=!1;let e=this.reportedHidden,t=this.hiddenNoteIds;this.reportedHidden=new Set(t);let n=[...t].filter(t=>!e.has(t)),r=[...e].filter(e=>!t.has(e)&&this.noteManager.getNote(e)!==void 0);(n.length>0||r.length>0)&&this.emitter.emit(`note:visibility`,{hidden:n,shown:r})}))}scheduleChange(){this.changePending||(this.changePending=!0,queueMicrotask(()=>{this.changePending=!1,this.emitter.emit(`change`,{data:this.exportData()})}))}},mr=(e,t)=>`<b>${e}</b>${t.map(e=>`<div>${e}</div>`).join(``)}`,hr=e=>`<b>${e.heading}</b><div><b>${e.bold}</b>${e.separator}<s>${e.strike}</s>${e.separator}<span style="color: #d32f2f">${e.color}</span>${e.separator}<a href="https://github.com/kan/wema-kake" target="_blank" rel="noopener">${e.link}</a></div><ul><li>${e.bullet}<ul><li>${e.nested}</li></ul></li></ul><ol><li>${e.numbered[0]}</li><li>${e.numbered[1]}</li></ol><ul class="wema-checklist"><li><input type="checkbox">${e.todo}</li><li class="wema-checked"><input type="checkbox" checked>${e.done}</li></ul>`,gr={ja:{firstPageTitle:`最初のページ`,intro:{first:mr(`wema-kake へようこそ`,[`付箋を並べて書く Wiki です。`,`1 ページが、1 枚のボードになります。`,`このページの付箋は、消してかまいません。`]),help:mr(`使い方`,[`試すためのボードです。`,`付箋を動かしたり、書き換えたりできます。`,`ここでの変更は、保存されません。`])},sample:hr({heading:`装飾の見本`,bold:`太字`,strike:`取り消し線`,color:`文字の色`,link:`リンク`,separator:`、`,bullet:`箇条書き`,nested:`段を下げた項目`,numbered:[`番号付きのリスト`,`2 つ目`],todo:`チェックリスト`,done:`済んだ項目`}),sections:{notes:[`付箋`,[`空いている場所をダブルクリック → 作る`,`上端をドラッグ → 動かす`,`右下をドラッグ → 大きさを変える`,`右下をダブルクリック → 内容に合わせる`,`選択して Delete → 削除する`,`Shift + クリック → 複数を選ぶ`,`Ctrl + ドラッグ → 囲んで選ぶ`]],text:[`本文`,[`文字を選択 → 太字、取り消し線、色、リンク`,`付箋を選択 → 色、リスト、画像`,`リストの中で Tab → 段を下げる`,`長い本文は、畳んで表示できる`]],edges:[`接続線`,[`縁の ● をドラッグ → 他の付箋とつなぐ`,`空いている場所で離す → 先に付箋を作る`,`線をクリック → 種類やラベルを変える`]],view:[`表示`,[`ホイール、空いた場所をドラッグ → 動かす`,`Ctrl + ホイール、ピンチ → 拡大と縮小`,`Ctrl + Z → 元に戻す(自分の操作だけ)`,`メニューの「参照モード」 → 読むだけにする`,`狭い画面では、縦 1 列に並べて表示する`,`並んでいる間は動かせず、線は印になる`]],pages:[`ページ`,[`「子ページを置く」 → 中にページを作る`,`子ページの表示名をクリック → 中へ入る`,`付箋を子ページへドラッグ → 中へ移動(Ctrl でコピー)`,`/p/ページ名 へのリンク → 他のページへ移る`,`左上の表示名をクリック → 名前を変える`]],llm:[`LLM`,[`MCP でつなぐと、Claude などが読み書きできる`,`LLM の操作は、メニューの「操作の履歴」に残る`,`履歴から、操作ごとに取り消せる`]]},column:460},en:{firstPageTitle:`First page`,intro:{first:mr(`Welcome to wema-kake`,[`A wiki you write with sticky notes.`,`Each page is one board.`,`Feel free to delete the notes on this page.`]),help:mr(`Help`,[`A board for trying things out.`,`Move the notes around or rewrite them.`,`Nothing you change here is saved.`])},sample:hr({heading:`Formatting sample`,bold:`Bold`,strike:`strikethrough`,color:`text color`,link:`link`,separator:`, `,bullet:`Bulleted list`,nested:`Indented item`,numbered:[`Numbered list`,`Second item`],todo:`Checklist`,done:`Finished item`}),sections:{notes:[`Notes`,[`Double-click an empty spot → create`,`Drag the top edge → move`,`Drag the bottom-right corner → resize`,`Double-click that corner → fit the content`,`Select and press Delete → delete`,`Shift + click → select several`,`Ctrl + drag → select an area`]],text:[`Text`,[`Select text → bold, strikethrough, color, link`,`Select a note → color, lists, image`,`Tab inside a list → indent`,`A long text can be shown folded`]],edges:[`Connections`,[`Drag a ● on the edge → connect to a note`,`Drop on an empty spot → create a note there`,`Click a line → change its style or label`]],view:[`View`,[`Wheel, or drag an empty spot → pan`,`Ctrl + wheel, or pinch → zoom`,`Ctrl + Z → undo (your own changes only)`,`“View-only mode” in the menu → read only`,`A narrow screen shows the notes in one column`,`There, notes do not move; lines become chips`]],pages:[`Pages`,[`“Place a child page” → a page inside this one`,`Click a child page’s title → go inside`,`Drag a note onto a child page → move it inside (Ctrl: copy)`,`A link to /p/page-name → go to that page`,`Click the title at the top left → rename`]],llm:[`LLM`,[`Over MCP, Claude and others can read and write`,`Their operations are kept in “Operation history”`,`Revert them there, one operation at a time`]]},column:480}},_r=[60,370,680],vr={sample:{color:`#F5F5F5`,column:0,row:0,height:250},intro:{color:`#FFF9C4`,column:1,row:0,height:120},notes:{color:`#BBDEFB`,column:0,row:1,height:220},text:{color:`#FFE0B2`,column:1,row:1,height:170},edges:{color:`#C8E6C9`,column:2,row:1,height:150},view:{color:`#FFCDD2`,column:0,row:2,height:210},pages:{color:`#E1BEE7`,column:1,row:2,height:170},llm:{color:`#B2DFDB`,column:2,row:2,height:150}},yr=[[`intro`,`notes`],[`intro`,`text`],[`intro`,`edges`],[`notes`,`view`],[`text`,`pages`],[`edges`,`llm`]],br=e=>`guide-${e}`,xr=br(`intro`);function Sr(e,t){let n=gr[t],r=t=>{if(t===`sample`)return n.sample;if(t===`intro`)return n.intro[e];let[r,i]=n.sections[t];return`<b>${r}</b><ul>${i.map(e=>`<li>${e}</li>`).join(``)}</ul>`};return{notes:Object.keys(vr).map((e,t)=>{let{color:i,column:a,row:o,height:s}=vr[e];return{id:br(e),x:60+a*n.column,y:_r[o],width:380,height:s,text:r(e),color:i,zIndex:t+1,autoSize:!0}}),edges:yr.map(([e,t])=>({id:`guide-${e}-${t}`,from:br(e),to:br(t),fromAnchor:`auto`,toAnchor:`auto`,style:`arrow`}))}}var Cr=[`ja`,`en`],wr=`wk_lang`,Tr=e=>Cr.includes(e);function Er(e,t,n){if(Tr(e))return e;for(let e of t){let t=e.trim().toLowerCase().split(`-`)[0];if(Tr(t))return t}return n}function Dr(e,t){for(let n of(e??``).split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}}var Or={siteName:`wema-kake`,defaultLang:`en`},kr=`wema-kake-site`;function Ar(e){let t={};try{let n=JSON.parse(e??``);n&&typeof n==`object`&&(t=n)}catch{}return{siteName:typeof t.siteName==`string`&&t.siteName!==``?t.siteName:Or.siteName,defaultLang:typeof t.defaultLang==`string`&&Tr(t.defaultLang)?t.defaultLang:Or.defaultLang}}var jr=globalThis.document,Mr=Ar(jr?.querySelector(`meta[name="${kr}"]`)?.getAttribute(`content`)),B=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,Nr={loading:`Loading…`,notFound:`Page not found`,list:`All pages`,close:`Close`,save:`Save`,title:`Title`,help:`Help`,undo:`Undo (Ctrl+Z)`,redo:`Redo (Ctrl+Shift+Z)`,documentTitle:(e,t)=>`${e} - ${t}`,"lang.switch":`日本語`,"failed.bookmark":e=>`Could not change the bookmark (${e})`,"failed.ancestors":e=>`Could not load the parent pages (${e})`,"failed.rename":e=>`Could not rename the page (${e})`,"failed.color":e=>`Could not change the page color (${e})`,"failed.backlinks":e=>`Could not load the backlinks (${e})`,"failed.history":e=>`Could not load the history (${e})`,"failed.revert":e=>`Could not revert the operation (${e})`,"failed.delete":e=>`Could not delete the page (${e})`,"failed.create":e=>`Could not create the page (${e})`,"failed.transfer":e=>`Could not send the notes to the child page (${e})`,"zoom.reset":`Reset to 100%`,"zoom.out":`Zoom out`,"zoom.in":`Zoom in`,"zoom.fit":`Zoom out to fit everything`,"zoom.center":`Center on the notes (keep the zoom)`,"links.loadFailed":e=>`Could not load (${e})`,"nav.title":`Go to a page (bookmarks, recent changes)`,"nav.filter":`Filter by page name`,"nav.bookmarked":`Bookmarked page`,"nav.empty":`No pages`,"nav.noMatch":`No matching pages`,"nav.more":`There are more. Type more to narrow them down`,"bookmark.add":`Bookmark this page`,"bookmark.remove":`Remove the bookmark`,"bookmark.unwritten":`A page with nothing written on it yet cannot be bookmarked`,"form.optional":`Optional`,"form.slugHint":`The name used in the URL. Lowercase letters, digits and hyphens`,"form.slugInvalid":`A slug is lowercase letters, digits and hyphens, up to 64 characters`,"form.create":`Create`,"form.slugTaken":`A page with that slug already exists. `,"form.openIt":`Open it`,"page.rename":`Rename`,"page.delete":`Delete page`,"page.deleteConfirm":e=>`Delete the page “${e}”? All its notes and history will be removed. This cannot be undone.`,"page.alreadyDeleted":`This page has already been deleted`,"page.deletedAlert":`This page was deleted. Returning to the list of pages.`,"page.titleHint":e=>`/p/${e} (click to rename)`,"page.color":`Page color`,"page.colorNone":`No color`,"index.filter":`Filter pages`,"index.newPage":`+ New page`,"index.count":e=>B(e,`page`),"index.matched":(e,t,n)=>`${e} / ${B(t,`page`)}${n}`,"index.searchFailed":e=>` (text search failed: ${e})`,"index.empty":`No pages yet`,"index.loadFailed":e=>`Could not load the list of pages (${e})`,"index.meta":(e,t,n)=>`${e} · ${B(t,`note`)}${n>0?` · ${B(n,`child page`)}`:``}`,"index.descendantHits":e=>`${B(e,`match`,`matches`)} in child pages`,"index.missing":`Not created`,"note.add":`Add a note`,"author.agentTitle":e=>`Note made by AI (${e})`,"author.detail":(e,t)=>`${e} · ${t}`,"layout.title":`Align and arrange`,"align.left":`Align left edges`,"align.center":`Align horizontal centers`,"align.right":`Align right edges`,"align.top":`Align top edges`,"align.middle":`Align vertical centers`,"align.bottom":`Align bottom edges`,"layout.distributeH":`Distribute horizontally (select 3 or more)`,"layout.distributeV":`Distribute vertically (select 3 or more)`,"layout.auto":`Arrange along the connections (whole board)`,"status.connecting":`Connecting…`,"status.offline":`Offline (reconnecting)`,"status.saving":`Saving…`,"sync.conflict":`Someone else was editing the same note, so your change was undone`,"sync.rejected":e=>`Your change could not be saved and was undone (${e})`,"backlinks.count":e=>`Backlinks ${e}`,"backlinks.title":`Pages that link to this page`,"menu.title":`Menu`,"menu.viewOnly":`View-only mode`,"menu.viewOnlyExit":`Leave view-only mode`,"menu.themeCard":`Note style: Card`,"menu.themeDefault":`Note style: Default`,"menu.history":`Operation history…`,"menu.exportJson":`Export as JSON`,"menu.deletePage":`Delete page…`,"ops.title":`Operation history`,"ops.agentOnly":`Agent operations only`,"ops.refresh":`Refresh`,"ops.empty":`No operations`,"ops.revert":`Revert`,"ops.noSummary":`(no description)`,"ops.revertedMark":` (reverted)`,"ops.summary.pageCreated":`Page created`,"ops.summary.childRemoved":e=>`Child page ${e} removed`,"ops.summary.revert":e=>`Reverted #${e}`,"ops.summary.revertUnknown":`Revert`,"ops.summary.notesReceived":e=>`Notes received from page ${e}`,"ops.summary.notesSent":e=>`Notes moved to page ${e}`,"ops.summary.childRecolored":e=>`Matched the color of child page ${e}`,"revert.done":`Reverted`,"revert.none":e=>`There was nothing to revert${e}`,"revert.partial":(e,t)=>`Partly reverted. ${B(e,`change`)} left as is${t}`,"revert.reasons":e=>` (${e.join(`, `)})`,"skip.modified":`changed since then`,"skip.connected":`other connections are attached`,"skip.deleted":`already deleted`,"skip.exists":`the same item already exists`,"skip.endpoint-missing":`a note at either end is missing`,"child.place":`Place a child page`,"child.newHeading":`Create a new page and place it`,"child.createAndPlace":`Create and place`,"child.existingHeading":`Place an existing page`,"child.rootPage":`Root page`,"child.slugPlaceholder":`Page name (slug)`,"child.placeExisting":`Place`,"child.slugTaken":`A page with that slug already exists. You can place it as an existing page`,"child.summary":(e,t)=>`Child page · ${B(e,`note`)} (/p/${t})`,"child.elsewhere":e=>`Placed in “${e}”`,"child.rejected":(e,t)=>`Could not place it as a child page (${e})${t?`. The page you created remains in the list as a root page`:``}`,"transfer.moved":(e,t)=>`Moved ${B(e,`note`)} to “${t}”`,"transfer.copied":(e,t)=>`Copied ${B(e,`note`)} to “${t}”`,"transfer.partial":e=>`Placed the notes in “${e}”, but some could not be removed from this page and are now in both (notes changed during the move are kept)`,"transfer.confirmMoveLinked":e=>`Also move the ${B(e,`note`)} connected by lines?\nChoose “Cancel” to move only the notes you dragged`,"transfer.confirmCopyLinked":e=>`Also copy the ${B(e,`note`)} connected by lines?\nChoose “Cancel” to copy only the notes you dragged`,"child.reject.not-found":`Page not found`,"child.reject.self":`A page cannot be placed in itself`,"child.reject.other-parent":`It is already a child of another page`,"child.reject.duplicate":`It is already placed on this page`,"child.reject.ancestor":`It is an ancestor of this page, so it would make a loop`,"child.reject.too-deep":e=>`Pages can be nested up to ${e} levels`,"help.unsaved":`This board is not saved`},Pr={loading:`読み込み中…`,notFound:`ページが見つかりません`,list:`一覧`,close:`閉じる`,save:`保存`,title:`表示名`,help:`使い方`,undo:`元に戻す (Ctrl+Z)`,redo:`やり直す (Ctrl+Shift+Z)`,documentTitle:(e,t)=>`${e} - ${t}`,"lang.switch":`English`,"failed.bookmark":e=>`ブックマークの変更に失敗しました(${e})`,"failed.ancestors":e=>`親ページの取得に失敗しました(${e})`,"failed.rename":e=>`表示名の変更に失敗しました(${e})`,"failed.color":e=>`ページの色の変更に失敗しました(${e})`,"failed.backlinks":e=>`リンク元の取得に失敗しました(${e})`,"failed.history":e=>`履歴の取得に失敗しました(${e})`,"failed.revert":e=>`取り消しに失敗しました(${e})`,"failed.delete":e=>`削除に失敗しました(${e})`,"failed.create":e=>`作成に失敗しました(${e})`,"failed.transfer":e=>`子ページへ付箋を送れませんでした(${e})`,"zoom.reset":`等倍に戻す`,"zoom.out":`縮小`,"zoom.in":`拡大`,"zoom.fit":`全体が収まるように縮小`,"zoom.center":`付箋全体の中央へ移動(倍率はそのまま)`,"links.loadFailed":e=>`取得できませんでした(${e})`,"nav.title":`ページへ移る(ブックマーク、最近の変更)`,"nav.filter":`ページ名で絞り込む`,"nav.bookmarked":`ブックマークしたページ`,"nav.empty":`ページはありません`,"nav.noMatch":`一致するページはありません`,"nav.more":`ほかにもあります。文字を足して絞り込めます`,"bookmark.add":`このページをブックマークする`,"bookmark.remove":`ブックマークを外す`,"bookmark.unwritten":`まだ何も書かれていないページには、付けられません`,"form.optional":`省略できます`,"form.slugHint":`URL に使う名前。小文字の英数字とハイフン`,"form.slugInvalid":`スラッグは小文字の英数字とハイフンで、64 文字までです`,"form.create":`作成`,"form.slugTaken":`そのスラッグのページはすでにあります。`,"form.openIt":`開く`,"page.rename":`表示名を変える`,"page.delete":`ページを削除`,"page.deleteConfirm":e=>`ページ「${e}」を削除します。付箋と履歴がすべて消え、取り消しはできません。`,"page.alreadyDeleted":`このページは、すでに削除されています`,"page.deletedAlert":`このページは削除されました。一覧へ戻ります。`,"page.titleHint":e=>`/p/${e}(クリックして表示名を変える)`,"page.color":`ページの色`,"page.colorNone":`色なし`,"index.filter":`ページを絞り込む`,"index.newPage":`+ 新規ページ`,"index.count":e=>`${e} ページ`,"index.matched":(e,t,n)=>`${e} / ${t} ページ${n}`,"index.searchFailed":e=>`(本文の検索に失敗しました: ${e})`,"index.empty":`まだページがありません`,"index.loadFailed":e=>`一覧を取得できませんでした(${e})`,"index.meta":(e,t,n)=>`${e}・付箋 ${t} 枚${n>0?`・子ページ ${n}`:``}`,"index.descendantHits":e=>`子ページに ${e} 件の一致`,"index.missing":`未作成`,"note.add":`付箋を追加`,"author.agentTitle":e=>`AI(${e})が作った付箋`,"author.detail":(e,t)=>`${e}・${t}`,"layout.title":`整列と配置`,"align.left":`左端をそろえる`,"align.center":`左右の中央をそろえる`,"align.right":`右端をそろえる`,"align.top":`上端をそろえる`,"align.middle":`上下の中央をそろえる`,"align.bottom":`下端をそろえる`,"layout.distributeH":`左右に均等に並べる(3 枚以上を選択)`,"layout.distributeV":`上下に均等に並べる(3 枚以上を選択)`,"layout.auto":`接続線に沿って自動で配置(全体)`,"status.connecting":`接続中…`,"status.offline":`オフライン(再接続します)`,"status.saving":`保存中…`,"sync.conflict":`他の人が同じ付箋を編集していたため、変更を取り消しました`,"sync.rejected":e=>`変更を保存できなかったため、取り消しました(${e})`,"backlinks.count":e=>`リンク元 ${e}`,"backlinks.title":`このページへリンクしているページ`,"menu.title":`メニュー`,"menu.viewOnly":`参照モード(読むだけ)`,"menu.viewOnlyExit":`参照モードを終える`,"menu.themeCard":`付箋の見た目: カード`,"menu.themeDefault":`付箋の見た目: 標準`,"menu.history":`操作の履歴…`,"menu.exportJson":`JSON を書き出す`,"menu.deletePage":`ページを削除…`,"ops.title":`操作の履歴`,"ops.agentOnly":`agent の操作だけ`,"ops.refresh":`更新`,"ops.empty":`操作はありません`,"ops.revert":`取り消す`,"ops.noSummary":`(説明なし)`,"ops.revertedMark":`(取り消し済み)`,"ops.summary.pageCreated":`ページの作成`,"ops.summary.childRemoved":e=>`子ページ ${e} の削除`,"ops.summary.revert":e=>`#${e} の取り消し`,"ops.summary.revertUnknown":`取り消し`,"ops.summary.notesReceived":e=>`ページ ${e} から付箋を受け取り`,"ops.summary.notesSent":e=>`ページ ${e} へ付箋を移動`,"ops.summary.childRecolored":e=>`子ページ ${e} の色に合わせる`,"revert.done":`取り消しました`,"revert.none":e=>`取り消せる変更がありませんでした${e}`,"revert.partial":(e,t)=>`一部を取り消しました。${e} 件は残しています${t}`,"revert.reasons":e=>`(${e.join(`、`)})`,"skip.modified":`その後に変更された`,"skip.connected":`他の接続線がつながっている`,"skip.deleted":`すでに削除されている`,"skip.exists":`同じものがすでにある`,"skip.endpoint-missing":`両端の付箋がない`,"child.place":`子ページを置く`,"child.newHeading":`新しいページを作って置く`,"child.createAndPlace":`作成して置く`,"child.existingHeading":`既存のページを置く`,"child.rootPage":`ルートのページ`,"child.slugPlaceholder":`ページの名前(スラッグ)`,"child.placeExisting":`置く`,"child.slugTaken":`そのスラッグのページはすでにあります。既存のページとして置けます`,"child.summary":(e,t)=>`子ページ・付箋 ${e} 枚(/p/${t})`,"child.elsewhere":e=>`「${e}」に置かれています`,"child.rejected":(e,t)=>`子ページとして置けませんでした(${e})${t?`。作成したページは、ルートのページとして一覧に残っています`:``}`,"transfer.moved":(e,t)=>`付箋 ${e} 枚を「${t}」へ移動しました`,"transfer.copied":(e,t)=>`付箋 ${e} 枚を「${t}」へコピーしました`,"transfer.partial":e=>`「${e}」へ付箋を置きましたが、一部の付箋はこのページから消せなかったので、両方にあります(移動の途中で変更された付箋は、消さずに残します)`,"transfer.confirmMoveLinked":e=>`線でつながっている付箋 ${e} 枚も一緒に移動しますか?\n「キャンセル」を選ぶと、ドラッグした付箋だけを移動します`,"transfer.confirmCopyLinked":e=>`線でつながっている付箋 ${e} 枚も一緒にコピーしますか?\n「キャンセル」を選ぶと、ドラッグした付箋だけをコピーします`,"child.reject.not-found":`ページが見つかりません`,"child.reject.self":`自分自身は置けません`,"child.reject.other-parent":`すでに別のページの子になっています`,"child.reject.duplicate":`このページにすでに置いてあります`,"child.reject.ancestor":`このページの先祖なので、輪になります`,"child.reject.too-deep":e=>`階層は ${e} 段までです`,"help.unsaved":`このボードは保存されません`},Fr=globalThis.document,V=Fr===void 0?`ja`:Er(Dr(Fr.cookie,wr),navigator.languages??[],Mr.defaultLang),Ir=V===`ja`?Pr:Nr;function H(e,...t){let n=Ir[e];return typeof n==`string`?n:n(...t)}var Lr=V===`ja`?`en`:`ja`;function Rr(e,t){let n;try{n=new URL(e)}catch{return null}return n.origin===t?n.href:null}var zr=new AbortController,U=()=>zr.signal;function W(e){zr.signal.addEventListener(`abort`,e,{once:!0})}var Br;function Vr(e){Br=e}var Hr;function Ur(e){Hr=e}var Wr=e=>/^\/p\/([^/]+)\/?$/.exec(e)?.[1],Gr=()=>!1,Kr=0,qr=()=>Kr;async function Jr(e,t){let n=++Kr;await Br?.(),n===Kr&&(Br=void 0,Hr=void 0,zr.abort(),zr=new AbortController,Gr(e,!1,t)||location.reload())}async function Yr(){await Br?.(),location.reload()}function Xr(e){Gr=e,Gr(location.pathname,!0),window.addEventListener(`popstate`,()=>void Zr(location.pathname))}async function Zr(e){let t=++Kr,n;try{n=await Hr?.(e)}catch{}t===Kr&&await Jr(e,n)}function Qr(e,t){let n=new URL(e,location.href),{pathname:r}=n;if(n.origin!==location.origin||!(r===`/`||r===`/help`||r.startsWith(`/p/`))){location.assign(n.href);return}history.pushState(null,``,n.pathname+n.search+n.hash),Jr(n.pathname,t)}function G(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n.filter(e=>e!=null&&e!==!1)),r}function $r(e,t){let n=ni(e,t);return n!==null&&(Qr(n),!0)}var ei=e=>!(e.ctrlKey||e.metaKey||e.shiftKey||e.button!==0);function ti(e,...t){let n=G(`a`,{href:e},...t);return n.addEventListener(`click`,t=>{ei(t)&&(t.preventDefault(),Qr(e))}),n}function ni(e,t){return ei(t)?Rr(e,location.origin):null}var ri={autocomplete:`off`,"data-1p-ignore":``,"data-lpignore":`true`,"data-bwignore":``,"data-form-type":`other`};function K(e={}){let t=G(`input`,e);for(let[e,n]of Object.entries(ri))t.setAttribute(e,n);return t}function ii(){let e=``;for(;e.length<6;){let t=crypto.getRandomValues(new Uint8Array(1))[0];t>=252||(e+=(t%36).toString(36))}return e}function ai(e){return confirm(H(`page.deleteConfirm`,e))}function oi(e){return e instanceof Error?e.message:String(e)}function q(e,t){return H(e,oi(t))}var si=new Intl.DateTimeFormat(V,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`});function ci(e){return si.format(e)}var li=`(max-width: 640px)`,ui=12,di=`stacked`;function fi(e,t,{onChange:n,first:r=[]}={}){let i=matchMedia(li),a,o=()=>{if(i.matches){t.classList.add(di);let i=t.clientWidth-24;if(i===a||i<=0)return;let o=a===void 0;a=i,e.setPageScroll(!0),e.setStacked({x:ui,y:ui,width:i,order:r}),o&&n?.(!0)}else if(a!==void 0){t.classList.remove(di),e.setStacked(null),e.setPageScroll(!1);try{n?.(!1)}finally{a=void 0}}else t.classList.remove(di)};return{isStacked:()=>a!==void 0,start(){o(),i.addEventListener(`change`,o,{signal:U()});let e=new ResizeObserver(o);e.observe(t),W(()=>e.disconnect())}}}var pi=5e3,mi=[`#FFF9C4`,`#FFCDD2`,`#FFE0B2`,`#E1BEE7`,`#BBDEFB`,`#B2DFDB`,`#C8E6C9`,`#F5F5F5`],J=e=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`,Y=e=>`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">${e}</svg>`,hi=e=>`<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">${e.map(([e,t])=>`<circle cx="${e}" cy="${t}" r="1.5"/>`).join(``)}</svg>`,gi=e=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="${e}"/></svg>`,_i=[3,8,13],vi=`12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2`,yi={undo:J(`<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>`),redo:J(`<polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.13-9.36L23 10"/>`),add:J(`<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>`),layout:hi(_i.flatMap(e=>_i.map(t=>[t,e]))),alignLeft:Y(`<line x1="2" y1="2" x2="2" y2="14"/><rect x="4" y="3" width="10" height="3" rx="0.5"/><rect x="4" y="8" width="6" height="3" rx="0.5"/>`),alignCenter:Y(`<line x1="8" y1="1" x2="8" y2="15"/><rect x="3" y="3" width="10" height="3" rx="0.5"/><rect x="5" y="8" width="6" height="3" rx="0.5"/>`),alignRight:Y(`<line x1="14" y1="2" x2="14" y2="14"/><rect x="2" y="3" width="10" height="3" rx="0.5"/><rect x="6" y="8" width="6" height="3" rx="0.5"/>`),alignTop:Y(`<line x1="2" y1="2" x2="14" y2="2"/><rect x="3" y="4" width="3" height="10" rx="0.5"/><rect x="8" y="4" width="3" height="6" rx="0.5"/>`),alignMiddle:Y(`<line x1="1" y1="8" x2="15" y2="8"/><rect x="3" y="3" width="3" height="10" rx="0.5"/><rect x="8" y="5" width="3" height="6" rx="0.5"/>`),alignBottom:Y(`<line x1="2" y1="14" x2="14" y2="14"/><rect x="3" y="2" width="3" height="10" rx="0.5"/><rect x="8" y="6" width="3" height="6" rx="0.5"/>`),distributeH:Y(`<rect x="1" y="4" width="3" height="8" rx="0.5"/><rect x="6.5" y="4" width="3" height="8" rx="0.5"/><rect x="12" y="4" width="3" height="8" rx="0.5"/>`),distributeV:Y(`<rect x="4" y="1" width="8" height="3" rx="0.5"/><rect x="4" y="6.5" width="8" height="3" rx="0.5"/><rect x="4" y="12" width="8" height="3" rx="0.5"/>`),autoLayout:J(`<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="8.5" y="14" width="7" height="7" rx="1"/><line x1="6.5" y1="10" x2="6.5" y2="14"/><line x1="6.5" y1="14" x2="12" y2="14"/><line x1="17.5" y1="10" x2="17.5" y2="14"/><line x1="17.5" y1="14" x2="12" y2="14"/>`),zoomOut:J(`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/>`),zoomIn:J(`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/>`),zoomFit:J(`<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>`),center:J(`<circle cx="12" cy="12" r="3"/><line x1="12" y1="2" x2="12" y2="6"/><line x1="12" y1="18" x2="12" y2="22"/><line x1="2" y1="12" x2="6" y2="12"/><line x1="18" y1="12" x2="22" y2="12"/>`),childPage:J(`<rect x="3" y="3" width="18" height="18" rx="2"/><rect x="7" y="7" width="6" height="5" rx="1"/><line x1="16" y1="14" x2="16" y2="18"/><line x1="14" y1="16" x2="18" y2="16"/>`),edit:J(`<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>`),trash:J(`<polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>`),star:J(`<polygon points="${vi}"/>`),starFilled:J(`<polygon points="${vi}" fill="currentColor"/>`),bookmarks:J(`<path d="M17 21l-6-4.5L5 21V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"/><path d="M9 1.5h9a2 2 0 0 1 2 2V17"/>`),menu:hi([[3,8],[8,8],[13,8]]),claude:gi(`m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z`),openai:gi(`M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z`),agent:J(`<rect x="4" y="8" width="16" height="12" rx="2"/><line x1="12" y1="4" x2="12" y2="8"/><circle cx="12" cy="3" r="1"/><line x1="9" y1="13" x2="9" y2="15"/><line x1="15" y1="13" x2="15" y2="15"/>`)};function bi(e){return G(`span`,{className:`icon`,innerHTML:yi[e]})}function xi(e,t,n){return G(`header`,{className:`page-header`},G(`div`,{className:`zone zone-left`},...e),G(`div`,{className:`zone zone-tools`},...t),G(`div`,{className:`zone zone-right`},...n))}function X(e,t,n){let r=G(`button`,{type:`button`,className:`icon-button`,title:t,ariaLabel:t},bi(e));return n&&r.addEventListener(`click`,n),r}var Si=()=>G(`span`,{className:`separator`});function Ci(e,t,n){document.addEventListener(`pointerdown`,r=>{!e.hidden&&!t.contains(r.target)&&n()},{capture:!0,signal:U()})}function wi(e,t,n={}){t.classList.add(`popover-panel`,`popover-${n.align??`left`}`),t.hidden=!0;let r=G(`span`,{className:`popover`},e,t),i=()=>{t.hidden=!0,e.ariaExpanded=`false`};return e.ariaExpanded=`false`,e.addEventListener(`click`,()=>{if(!t.hidden)return i();n.instead?.()||(t.hidden=!1,e.ariaExpanded=`true`,n.onOpen?.())}),Ci(t,r,i),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&!t.hidden&&i()},{signal:U()}),{root:r,close:i}}function Ti(e,...t){let n=G(`dialog`,{className:`modal ${e}`},...t,G(`form`,{method:`dialog`,className:`modal-foot`},G(`button`,{textContent:H(`close`)})));return n.addEventListener(`click`,e=>{if(e.target!==n)return;let t=n.getBoundingClientRect();e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom||n.close()}),n}var Ei={"#FFF9C4":`colorButter`,"#FFCDD2":`colorRose`,"#FFE0B2":`colorPeach`,"#E1BEE7":`colorLavender`,"#BBDEFB":`colorSky`,"#B2DFDB":`colorMint`,"#C8E6C9":`colorSage`,"#F5F5F5":`colorGray`};function Di(e){let t=V===`ja`?r:n,i=G(`button`,{type:`button`,className:`color-button`,title:H(`page.color`),ariaLabel:H(`page.color`)}),a=G(`div`,{className:`color-panel`}),o=wi(i,a),s=new Map,c=(t,n)=>{let r=G(`button`,{type:`button`,className:`color-swatch`,title:n,ariaLabel:n});t!==null&&(r.style.backgroundColor=t),r.addEventListener(`click`,()=>{e(t),o.close()}),s.set(t,r),a.append(r)};for(let e of mi)c(e,t[Ei[e]]);return c(null,H(`page.colorNone`)),{root:o.root,show(e){i.style.backgroundColor=e??``;for(let[t,n]of s)n.classList.toggle(`active`,t===e)}}}function Oi(e,t,n=``){let r=G(`button`,{type:`button`,className:`menu-item ${n}`.trim(),textContent:e});return r.addEventListener(`click`,t),r}var ki=V===`ja`?r:void 0,Ai=31536e3;function ji(){document.cookie=`${wr}=${Lr}; Path=/; Max-Age=${Ai}; SameSite=Lax`,Yr()}function Mi(){let e=G(`button`,{type:`button`,className:`text-button`,textContent:H(`lang.switch`)});return e.addEventListener(`click`,ji),e}function Ni(e){return{undo:X(`undo`,H(`undo`),()=>e.undo()),redo:X(`redo`,H(`redo`),()=>e.redo())}}var Pi=1.25;function Fi(e,t){let n=[...t.querySelectorAll(`.wema-note`)].filter(e=>e.offsetParent!==null).map(e=>e.getBoundingClientRect());if(n.length===0)return;let r=(e,t)=>(Math.min(...e)+Math.max(...t))/2,i=t.getBoundingClientRect(),{x:a,y:o}=e.getViewport();e.setViewport({x:a+(i.left+i.right)/2-r(n.map(e=>e.left),n.map(e=>e.right)),y:o+(i.top+i.bottom)/2-r(n.map(e=>e.top),n.map(e=>e.bottom))})}function Ii(e,t){let n=G(`button`,{type:`button`,className:`zoom-level`,title:H(`zoom.reset`)});n.addEventListener(`click`,()=>e.zoomTo(1));let r=``,i=e=>{let t=`${Math.round(e*100)}%`;t!==r&&(r=t,n.textContent=t)};return e.on(`viewport:change`,({zoom:e})=>i(e)),i(e.getViewport().zoom),G(`span`,{className:`tool-group`},X(`zoomOut`,H(`zoom.out`),()=>e.zoomTo(e.getViewport().zoom/Pi)),n,X(`zoomIn`,H(`zoom.in`),()=>e.zoomTo(e.getViewport().zoom*Pi)),X(`zoomFit`,H(`zoom.fit`),()=>e.fitToContent()),X(`center`,H(`zoom.center`),()=>Fi(e,t)))}function Li(e,t){let n=G(`div`,{className:`toast`,hidden:!0,role:`status`});e.append(n);let r;return e=>{n.textContent=e,n.hidden=!1,clearTimeout(r),r=setTimeout(()=>{n.hidden=!0},t)}}var Ri={get(e){try{return localStorage.getItem(`wema-kake:${e}`)}catch{return null}},set(e,t){try{localStorage.setItem(`wema-kake:${e}`,t)}catch{}}};function zi(e){document.title=H(`documentTitle`,H(`help`),Mr.siteName);let t=G(`div`,{className:`board`});e.append(G(`div`,{className:`page-body`},t));let n=new pr({container:t,data:{version:1,...Sr(`help`,V)},onLinkClick:$r,noteLinks:!0,labels:ki,emptyDrag:`pan`});W(()=>n.destroy()),fi(n,t,{first:[xr]}).start();let{undo:r,redo:i}=Ni(n),a=()=>{r.disabled=!n.canUndo(),i.disabled=!n.canRedo()};n.on(`history:change`,a),a();let o=Ii(n,t);o.classList.add(`optional`),e.prepend(xi([ti(`/`,H(`list`)),G(`h1`,{textContent:H(`help`)})],[r,i,Si(),o],[G(`span`,{className:`help-note`,textContent:H(`help.unsaved`)}),Mi()]))}var Z=class extends Error{status;constructor(e,t){super(e),this.status=t}};async function Q(e,t,n){let r=await fetch(t,{method:e,headers:n===void 0?void 0:{"Content-Type":`application/json`},body:n===void 0?void 0:JSON.stringify(n)}),i=await r.json().catch(()=>null);if(!r.ok||i===null)throw new Z(i?.error??`${e} ${t}: ${r.status}`,r.status);return i}var Bi=()=>Q(`GET`,`/api/index`);async function Vi(e){let{pages:t}=await Q(`GET`,`/api/search?roots=1&q=${encodeURIComponent(e)}`);return t}async function Hi(e){return e.length===0?[]:(await Q(`POST`,`/api/pages-info`,{names:e})).pages}var Ui=e=>Q(`GET`,`/api/pages/${e}/ancestors`),Wi=(e,t)=>Q(`POST`,`/api/pages/${e}`,{title:t});async function Gi(){return(await Q(`GET`,`/api/bookmarks`)).pages}var Ki=(e,t)=>Q(t?`PUT`:`DELETE`,`/api/bookmarks/${e}`);async function qi(e,t=``){return(await Q(`GET`,`/api/pages?${new URLSearchParams({limit:String(e),...t===``?{}:{name:t}})}`)).pages}var Ji=e=>Q(`GET`,`/api/pages/${e}/backlinks`),Yi=(e,t,n=!1)=>Q(`PUT`,`/api/pages/${e}/title`,{title:t,mustExist:n}),Xi=(e,t)=>Q(`PUT`,`/api/pages/${e}/color`,{color:t}),Zi=e=>Q(`DELETE`,`/api/pages/${e}`),Qi=(e,t)=>Q(`GET`,`/api/pages/${e}/ops${t?`?agent=1`:``}`),$i=(e,t,n)=>Q(`POST`,`/api/pages/${e}/ops/${t}/revert`,{clientId:n,opId:crypto.randomUUID()}),ea=(e,t)=>Q(`POST`,`/api/pages/${e}/transfer`,t);async function ta(e){let t=await fetch(`/api/images`,{method:`POST`,headers:{"Content-Type":e.type},body:e});if(!t.ok)throw Error(`image upload failed: ${t.status}`);return(await t.json()).url}async function na(){try{let e=await fetch(`/api/session`,{redirect:`manual`});return e.status!==401&&e.type!==`opaqueredirect`}catch{return!0}}var ra=e=>e.replace(/[A-Z]+/g,e=>e.toLowerCase()),ia=(e,t)=>ra(e.name).includes(t)||ra(e.title??``).includes(t);function aa(e,t,n=``){let r=ra(n.trim()),i=new Set(e.map(e=>e.name)),a=t.filter(e=>!i.has(e.name));return{pinned:r===``?e:e.filter(e=>ia(e,r)),rest:r===``?a.slice(0,5):a}}function oa(e,t){return e.map(e=>ti(`/p/${e.name}`,G(`span`,{className:`link-title`,textContent:e.title??e.name}),t&&G(`span`,{className:`link-detail`,textContent:t(e)})))}var sa=30,ca=200;function la(e,t){return ti(`/p/${e.name}`,t&&G(`span`,{className:`link-star`,title:H(`nav.bookmarked`)},bi(`starFilled`)),G(`span`,{className:`link-title`,textContent:e.title??e.name}),e.updated_at!==null&&G(`span`,{className:`link-detail`,textContent:ci(e.updated_at)}))}function ua(){let e=U(),t=K({type:`search`,className:`nav-filter`,placeholder:H(`nav.filter`),ariaLabel:H(`nav.filter`),maxLength:200}),n=G(`div`,{className:`link-list`}),r=G(`div`,{className:`page-nav`},t,n),i,a=0,o=!1,s,c=e=>n.replaceChildren(G(`span`,{className:`empty`,textContent:e})),l=async()=>{let r=++a,s=t.value.trim(),l=i??=Gi();l.catch(()=>{i===l&&(i=void 0)});try{let[t,i]=await Promise.all([l,s===``?qi(105):qi(sa,s)]);if(e.aborted||r!==a)return;let{pinned:u,rest:d}=aa(t,i,s);u.length+d.length===0?c(H(s===``?`nav.empty`:`nav.noMatch`)):(n.replaceChildren(),n.append(...u.map(e=>la(e,!0)),...u.length>0&&d.length>0?[G(`hr`)]:[],...d.map(e=>la(e,!1))),s!==``&&i.length>=sa&&n.append(G(`span`,{className:`empty`,textContent:H(`nav.more`)}))),o=!0}catch(t){!e.aborted&&r===a&&c(H(`links.loadFailed`,oi(t)))}};return t.addEventListener(`input`,()=>{o=!1,a++,clearTimeout(s),s=setTimeout(()=>void l(),ca)}),t.addEventListener(`keydown`,e=>{e.key!==`Enter`||e.isComposing||(e.preventDefault(),o&&n.querySelector(`a`)?.click())}),e.addEventListener(`abort`,()=>clearTimeout(s)),wi(X(`bookmarks`,H(`nav.title`)),r,{align:`right`,onOpen(){clearTimeout(s),t.value=``,o=!1,i=void 0,n.childElementCount===0&&c(H(`loading`)),l(),matchMedia(`(pointer: coarse)`).matches||t.focus()}}).root}function da(e,t){let n=U(),r=!1,i=X(`star`,``,()=>{let o=!r;i.disabled=!0,Ki(e,o).then(()=>{n.aborted||a(o)}).catch(e=>{n.aborted||t(e instanceof Z&&e.status===404?Error(H(`bookmark.unwritten`)):e)}).finally(()=>{i.disabled=!1})}),a=e=>{r=e,i.replaceChildren(bi(r?`starFilled`:`star`)),i.title=H(r?`bookmark.remove`:`bookmark.add`),i.ariaLabel=i.title,i.ariaPressed=String(r)};return a(!1),i.disabled=!0,Gi().then(t=>{n.aborted||(a(t.some(t=>t.name===e)),i.disabled=!1)}).catch(()=>{}),i}var fa=120,pa=4,ma=200;function ha(e,t){let n=X(`edit`,H(`page.rename`)),r=X(`trash`,H(`page.delete`)),i=G(`div`,{className:`note-actions`,hidden:!0},n,r),a=K({maxLength:200,ariaLabel:H(`title`)}),o=G(`form`,{className:`note-rename`,hidden:!0},a,G(`button`,{type:`submit`,textContent:H(`save`)}));e.append(i,o);let s,c=t=>{let n=e.querySelector(`.wema-note[data-note-id="${CSS.escape(t)}"]`);if(!n)return;let r=n.getBoundingClientRect(),i=e.getBoundingClientRect();return{left:r.left-i.left,top:r.top-i.top,right:r.right-i.left,width:r.width}},l=()=>{s=void 0,i.hidden=!0,o.hidden=!0},u=(t,n,r)=>{let i=(e,t)=>Math.max(pa,Math.min(e,t-pa));t.style.left=`${i(n,e.clientWidth-t.offsetWidth)}px`,t.style.top=`${i(r,e.clientHeight-t.offsetHeight)}px`},d=e=>{if(e===s)return;let n=c(e);if(!n||n.width<fa||t.titleOf(e)===void 0)return l();s=e,i.hidden=!1,u(i,n.right-i.offsetWidth-pa,n.top+pa)};e.addEventListener(`pointerover`,e=>{if(!o.hidden)return;let t=e.target;if(i.contains(t))return;let n=t.closest(`.wema-note`)?.dataset.noteId;n===void 0?l():d(n)}),e.addEventListener(`pointerleave`,()=>{o.hidden&&l()});for(let e of[i,o])for(let t of[`pointerdown`,`dblclick`,`wheel`])e.addEventListener(t,e=>e.stopPropagation());return n.addEventListener(`click`,()=>{if(s===void 0)return;let e=c(s);if(!e)return l();i.hidden=!0,o.hidden=!1,o.style.width=`${Math.max(e.width-8,ma)}px`,u(o,e.left+pa,e.top+pa),a.value=t.titleOf(s)??``,a.placeholder=s,a.focus(),a.select()}),o.addEventListener(`submit`,e=>{e.preventDefault();let n=s,r=a.value.trim();l(),n!==void 0&&r!==(t.titleOf(n)??``)&&t.rename(n,r)}),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&!e.isComposing&&l()}),Ci(o,o,l),r.addEventListener(`click`,()=>{let e=s;l(),e!==void 0&&t.remove(e)}),l}var ga=220,_a=160,va=40,ya=40,ba=`#E0E0E0`;function xa(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}var Sa={fromAnchor:`auto`,toAnchor:`auto`,style:`arrow`,strokeWidth:1,arrowSize:8},Ca=`font-size: 11px; color: #666`;function wa(e,t){let n=xa(e.title??e.name),r=H(`index.meta`,t(e.updated_at),e.note_count,e.child_count);return`<a href="/p/${e.name}"><b>${n}</b></a><div>${xa(e.excerpt)}</div><div><span style="${Ca}">${xa(r)}</span></div>`}function Ta(e){return e===0?``:`<div><span style="font-size: 11px; color: #1d4ed8"><b>${xa(H(`index.descendantHits`,e))}</b></span></div>`}function Ea(e){return`<a href="/p/${e}">${e}</a><div><span style="${Ca}">${xa(H(`index.missing`))}</span></div>`}var Da=260,Oa=200,ka=60,Aa=80;function ja(e,t,n){let r=new Set(e),i=new Map,a=new Set;for(let{from:e,to:n}of t){if(!r.has(e))continue;let t=i.get(e);t?t.push(n):i.set(e,[n]),a.add(n)}let o=new Map,s=e=>{let t=e.filter(e=>!o.has(e));for(let e=0;t.length>0;e++){for(let n of t)o.set(n,e);t=[...new Set(t.flatMap(e=>i.get(e)??[]))].filter(e=>!o.has(e))}};s(e.filter(e=>!a.has(e)));for(let t of e)s([t]);let c=[];for(let t of e)(c[o.get(t)]??=[]).push(t);let l=Math.max(...c.map(e=>e.length)),u=Math.min(n,Math.max(2,Math.ceil(Math.sqrt(l*2)))),d=Math.min(u,l)*Da-va,f=new Map,p=0;for(let e of c){for(let t=0;t<e.length;t+=u){let n=e.slice(t,t+u),r=(d-(n.length*Da-va))/2;n.forEach((e,t)=>f.set(e,{x:r+t*Da,y:p})),p+=Oa}p+=ka}return{width:d,height:p-va-ka,positions:f}}function Ma(e,t){let n=new Map(e.map(e=>[e,e])),r=e=>{let t=e;for(;n.get(t)!==t;)t=n.get(t);return n.set(e,t),t};for(let{from:e,to:i}of t)n.set(r(e),r(i));let i=new Map;for(let t of e){let e=r(t),n=i.get(e);n?n.push(t):i.set(e,[t])}return[...i.values()]}function Na(e,t,n,r){let i=new Map,a=new Map,o=(e,t,n,r)=>{i.set(e,{id:e,x:0,y:0,width:ga,height:_a,text:t,color:n,zIndex:1}),a.set(e,r.toLowerCase())};for(let t of e)o(t.name,wa(t,r),t.color??`#FFF9C4`,`${t.title??``}\n${t.name}`);let s=[],c=new Set;for(let{from_page:e,to_page:n,missing:r}of t)if(e!==n&&i.has(e)){if(!i.has(n)){if(!r)continue;o(n,Ea(n),ba,n)}s.push({id:`${e}>${n}`,from:e,to:n,...Sa}),c.add(e).add(n)}let l=Math.max(1,Math.floor((n.width-80+va)/Da)),u=n.width/Math.max(1,n.height),d=Math.ceil(i.size/l)*Oa+ya<=n.height?l:Math.max(l,Math.ceil(Math.sqrt(i.size*u*Oa/Da))),f=d*Da-va,p=(e,t,n)=>{let r=i.get(e);r.x=ya+t,r.y=ya+n},m=0,h=0,g=0,_=[...i.keys()].filter(e=>c.has(e));for(let e of Ma(_,s)){let t=ja(e,s,d);m>0&&m+t.width>f&&(m=0,h+=g+Aa,g=0);for(let[e,n]of t.positions)p(e,m+n.x,h+n.y);m+=t.width+va,g=Math.max(g,t.height)}g>0&&(h+=g+Aa);let v=0;for(let e of i.keys())c.has(e)||(p(e,v%d*Da,h+Math.floor(v/d)*Oa),v++);for(let e of s){let t=i.get(e.to).y-i.get(e.from).y;t!==0&&(e.fromAnchor=t>0?`bottom`:`top`,e.toAnchor=t>0?`top`:`bottom`)}let y=new Map([...i.values()].map(e=>[e.id,e.text]));return{data:{version:1,notes:[...i.values()],edges:s},searchText:a,texts:y}}function Pa(){let e=K({placeholder:H(`form.optional`),maxLength:200}),t=K({value:ii(),title:H(`form.slugHint`)});return{title:e,slug:t,labels:[G(`label`,{},H(`title`),e),G(`label`,{},`URL`,G(`span`,{className:`slug-field`},`/p/`,t))],reset(){e.value=``,t.value=ii(),e.focus()}}}function Fa(e,n){let r=e.value.trim();if(t(r))return r;n.textContent=H(`form.slugInvalid`)}var Ia=220,La=32,Ra=.5,za=.5,Ba=()=>matchMedia(`(prefers-reduced-motion: reduce)`).matches,Va=e=>e<.5?2*e*e:1-(-2*e+2)**2/2;function Ha(e,t,n){if(Ba())return e.setViewport(t),Promise.resolve();let r=e.getViewport(),i=U(),a=performance.now();return new Promise(o=>{let s=c=>{if(i.aborted||n())return o();let l=Math.min(1,(c-a)/Ia),u=Va(l);e.setViewport({x:r.x+(t.x-r.x)*u,y:r.y+(t.y-r.y)*u,zoom:r.zoom*(t.zoom/r.zoom)**u}),l<1?requestAnimationFrame(s):o()};requestAnimationFrame(s)})}function Ua(e,t){let n=e.getViewport();t();let r=e.getViewport();return e.setViewport(n),r}var Wa=(e,t)=>Ua(e,()=>e.fitToContent({noteIds:[t.id],padding:La,maxZoom:1/0})),Ga=(e,t)=>Ua(e,()=>e.zoomTo(e.getViewport().zoom*t));function Ka(e,t,n){let r=!1,i=0,a=t=>{let n=++i;return Ha(e,t,()=>n!==i)},o=async(e,i)=>{if(r)return;r=!0,t?.();let o=n?.()?void 0:e();return o&&await a(o),i},s=async(e,t,n)=>{let r=U(),i=qr(),a=await o(e,n);a&&!r.aborted&&i===qr()&&Qr(t,a)},c=t=>()=>{let n=e.getNote(t);return n&&Wa(e,n)},l=()=>Ga(e,za);return{enter(e,t){return s(c(e),t,{kind:`enter`})},leave(e,t){return s(l,e,{kind:`leave`,from:t})},enterOnPop(e){return o(c(e),{kind:`enter`})},leaveOnPop(e){return o(l,{kind:`leave`,from:e})},async arrive(t,r){if(n?.())return;let i=e.getViewport();if(t?.kind===`enter`)e.zoomTo(i.zoom*Ra);else if(t?.kind===`leave`){let n=r(t.from);if(!n)return;e.fitToContent({noteIds:[n.id],padding:La,maxZoom:1/0})}else return;await a(i)}}}var qa=200,Ja=8e3;function Ya(){let e=Pa(),t=G(`div`,{className:`form-error`}),n=G(`form`,{className:`new-page`},...e.labels,G(`button`,{type:`submit`,textContent:H(`form.create`)}),t),r=async()=>{let n=Fa(e.slug,t);if(n!==void 0){try{await Wi(n,e.title.value)}catch(e){e instanceof Z&&e.status===409?t.replaceChildren(H(`form.slugTaken`),ti(`/p/${n}`,H(`form.openIt`))):t.textContent=q(`failed.create`,e);return}Qr(`/p/${n}`)}};return n.addEventListener(`submit`,e=>{e.preventDefault(),r()}),n}var Xa=.05;function Za(e){let t,n=n=>{if(n!==t){t=n,e.classList.toggle(`index-focus`,n!==void 0);for(let t of e.querySelectorAll(`.wema-edge-group`)){let[e,r]=(t.dataset.edgeId??``).split(`>`);t.classList.toggle(`index-linked`,n!==void 0&&(e===n||r===n))}}};e.addEventListener(`pointerover`,e=>{n(e.target.closest(`.wema-note`)?.dataset.noteId)}),e.addEventListener(`pointerleave`,()=>n(void 0))}var Qa;function $a(e,t){document.title=Mr.siteName;let n=U(),r=K({type:`search`,className:`index-search`,placeholder:H(`index.filter`),maxLength:200,value:new URLSearchParams(location.search).get(`q`)??``}),i=G(`span`,{className:`index-count`}),a=G(`span`,{className:`tool-group optional`}),o=Ya(),s=wi(G(`button`,{type:`button`,className:`text-button primary`,textContent:H(`index.newPage`)}),o,{align:`right`,onOpen:()=>o.querySelector(`input`)?.focus()}),c=G(`div`,{className:`index-canvas`}),l=G(`div`,{className:`index-board`});e.append(xi([G(`h1`,{textContent:Mr.siteName})],[r,i,a],[ua(),Mi(),s.root]),c);let u,d,f=0,p=location.search,m,h=null,g=new Set,_=(e=``)=>{if(!u||!d)return;let t=d.data.notes.length,n=new Map([...h??[]].filter(([,e])=>e>0));for(let e of new Set([...g,...n.keys()])){let t=d.texts.get(e);t!==void 0&&u.updateNote(e,{text:t+Ta(n.get(e)??0)})}g=new Set(n.keys()),u.setNoteFilter(h&&[...h.keys()]),i.textContent=h?H(`index.matched`,h.size,t,e):H(`index.count`,t)},v=async()=>{if(!u||!d)return;let e=r.value.trim();if(e===m)return;m=e,history.replaceState(null,``,e?`/?q=${encodeURIComponent(e)}`:`/`),p=location.search;let t=++f;if(e===``){h=null,_(),u.setViewport({x:0,y:0,zoom:1});return}let n=()=>{_(),u?.fitToContent()},i=e.toLowerCase(),a=new Map([...d.searchText].filter(([,e])=>e.includes(i)).map(([e])=>[e,0]));h=a,n();try{let r=await Vi(e);if(t!==f)return;let i=a.size;for(let{name:e,root:t}of r)d.searchText.has(t)&&a.set(t,(a.get(t)??0)+(e===t?0:1));a.size===i?_():n()}catch(e){t===f&&_(H(`index.searchFailed`,oi(e)))}},y;r.addEventListener(`input`,()=>{clearTimeout(y),y=setTimeout(()=>void v(),qa)});let b=[],x=[],S=()=>Na(b,x,{width:c.clientWidth,height:c.clientHeight},ci),C=Li(c,Ja),w=()=>{if(u){if(b.length===0)return location.reload();D(),d=S(),u.importData(d.data),g=new Set;for(let e of[...h?.keys()??[]])d.searchText.has(e)||h?.delete(e);_()}},T=e=>{b=b.filter(t=>t.name!==e),h?.has(e)&&h.set(e,0),x=x.filter(t=>t.from_page!==e).map(t=>t.to_page===e?{...t,missing:1}:t),w()},E=new Set,D=ha(c,{titleOf:e=>E.has(e)?void 0:b.find(t=>t.name===e)?.title,rename(e,t){Yi(e,t,!0).then(t=>{b=b.map(n=>n.name===e?{...n,title:t.title}:n),w()}).catch(t=>{t instanceof Z&&t.status===404?(C(H(`page.alreadyDeleted`)),T(e)):C(q(`failed.rename`,t))})},remove(e){let t=b.find(t=>t.name===e);t&&ai(t.title??e)&&(E.add(e),Zi(e).then(()=>T(e)).catch(e=>C(q(`failed.delete`,e))).finally(()=>E.delete(e)))}});Bi().then(e=>{if(n.aborted)return;if({pages:b,links:x}=e,b.length===0){c.append(G(`p`,{className:`empty`,textContent:H(`index.empty`)}));return}c.append(l),d=S(),u=new pr({container:l,data:d.data,viewOnly:!0,labels:ki,minZoom:Xa,onLinkClick(e,t){let n=ni(e,t);if(n===null)return!1;let r=t.target.closest(`.wema-note`)?.dataset.noteId;return r===void 0?Qr(n):f.enter(r,n),!0}});let r=u,i=!1,o=()=>{i||(i=!0,Qa=s.isStacked()?{search:p,scrollTop:l.scrollTop}:{search:p,viewport:r.getViewport()})},s=fi(u,l,{onChange(e){D(),!e&&h&&r.fitToContent()}});s.start();let f=Ka(u,o,s.isStacked);Ur(e=>{let t=Wr(e);if(t!==void 0&&r.getNote(t)&&h?.has(t)!==!1)return f.enterOnPop(t)}),W(()=>{o(),clearTimeout(y),u=void 0,r.destroy()}),a.append(Si(),Ii(u,c)),Za(c),u.on(`viewport:change`,D),l.addEventListener(`scroll`,D,{signal:n});let m=Qa?.search===location.search?Qa:void 0;v().then(()=>{if(!n.aborted)return s.isStacked()?m?.scrollTop!==void 0&&(l.scrollTop=m.scrollTop):m?.viewport&&r.setViewport(m.viewport),f.arrive(t,e=>r.getNote(e))})}).catch(e=>{c.replaceChildren(G(`p`,{className:`empty`,textContent:H(`index.loadFailed`,oi(e))}))})}var eo=`page`,to={width:240,height:180},no=`child page: `;function ro(e){if(!e.startsWith(no))return;let[t,n]=e.slice(12).split(`: `);return{code:t,page:n??``}}function $(e){return e.meta?.[eo]}var io=`system:`;function ao(e){if(!e.startsWith(io))return null;let[t,...n]=e.slice(7).split(`:`),r=n.join(`:`);return t===`page-created`&&r===``?{kind:`pageCreated`}:t===`child-removed`&&r!==``?{kind:`childRemoved`,page:r}:t===`revert`&&/^\d+$/.test(r)?{kind:`revert`,seq:Number(r)}:t===`notes-received`&&r!==``?{kind:`notesReceived`,page:r}:t===`notes-sent`&&r!==``?{kind:`notesSent`,page:r}:t===`child-recolored`&&r!==``?{kind:`childRecolored`,page:r}:null}var oo=`ping`,so=`http://www.w3.org/2000/svg`,co=40,lo=300,uo=pi+2e3;function fo(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function po(e){let t=document.createElementNS(so,`svg`);if(t.setAttribute(`class`,`child-layout`),e.length===0)return t;let n=Math.min(...e.map(([e])=>e))-co,r=Math.min(...e.map(([,e])=>e))-co,i=Math.max(...e.map(([e,,t])=>e+t))+co,a=Math.max(...e.map(([,e,,t])=>e+t))+co;t.setAttribute(`viewBox`,`${n} ${r} ${i-n} ${a-r}`);for(let[n,r,i,a,o]of e){let e=document.createElementNS(so,`rect`);e.setAttribute(`x`,String(n)),e.setAttribute(`y`,String(r)),e.setAttribute(`width`,String(i)),e.setAttribute(`height`,String(a)),e.setAttribute(`fill`,o),t.append(e)}return t}var mo=class{slug;open;pages=new Map;board;refreshTimer;ahead=new Set;indexedTimer;constructor(e,t){this.slug=e,this.open=t}render=(e,t)=>{let n=$(e);if(n===void 0)return!1;this.pages.has(n)||this.scheduleRefresh();let r=this.pages.get(n),i=G(`a`,{className:`child-title`,href:`/p/${n}`,textContent:r?.title??n});return i.addEventListener(`click`,t=>{t.stopPropagation(),ei(t)&&(t.preventDefault(),this.open(n,e.id))}),t.classList.add(`child-note`),t.append(i,G(`div`,{className:`child-meta`,textContent:this.describe(n,r)})),r&&t.append(po(fo(r.layout))),!0};describe(e,t){return t===void 0?H(`loading`):t===null?H(`notFound`):t.parent!==null&&t.parent!==this.slug?H(`child.elsewhere`,t.parent):H(`child.summary`,t.note_count,e)}attach(e){this.board=e,window.addEventListener(`focus`,()=>this.scheduleRefresh(),{signal:U()}),W(()=>{clearTimeout(this.refreshTimer),clearTimeout(this.indexedTimer),this.board=void 0})}titleOf(e){return this.pages.get(e)?.title??e}contentChanged(e){this.pages.set(e.name,e),this.ahead.add(e.name);let t=this.board?.getNotes().find(t=>$(t)===e.name);t&&this.board?.refreshNote(t.id),clearTimeout(this.indexedTimer),this.indexedTimer=setTimeout(()=>{this.ahead.clear(),this.refresh()},uo)}scheduleRefresh(){clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(()=>void this.refresh(),lo)}async refresh(){let e=this.board;if(!e)return;let t=new Map;for(let n of e.getNotes()){let e=$(n);e!==void 0&&t.set(e,n.id)}if(t.size===0)return;let n;try{n=await Hi([...t.keys()])}catch{return}if(this.board!==e)return;let r=new Map(n.map(e=>[e.name,e])),i=[];for(let[e,n]of t)this.ahead.has(e)||(this.pages.set(e,r.get(e)??null),i.push(n));for(let t of i)e.refreshNote(t)}},ho={"not-found":H(`child.reject.not-found`),self:H(`child.reject.self`),"other-parent":H(`child.reject.other-parent`),duplicate:H(`child.reject.duplicate`),ancestor:H(`child.reject.ancestor`),"too-deep":H(`child.reject.too-deep`,5)};function go(e,t){let n=new Set,r=Pa(),i=G(`div`,{className:`form-error`}),a=G(`button`,{type:`submit`,textContent:H(`child.createAndPlace`)}),o=G(`form`,{className:`new-page`},G(`strong`,{textContent:H(`child.newHeading`)}),...r.labels,a),s=G(`datalist`,{id:`child-page-roots`}),c=K({placeholder:H(`child.slugPlaceholder`)});c.setAttribute(`list`,s.id);let l=G(`form`,{className:`new-page`},G(`strong`,{textContent:H(`child.existingHeading`)}),G(`label`,{},H(`child.rootPage`),c),s,G(`button`,{type:`submit`,textContent:H(`child.placeExisting`)}));return o.addEventListener(`submit`,e=>{e.preventDefault();let o=Fa(r.slug,i);o!==void 0&&(a.disabled=!0,Wi(o,r.title.value).then(()=>{n.add(o),t(o)}).catch(e=>{i.textContent=e instanceof Z&&e.status===409?H(`child.slugTaken`):q(`failed.create`,e)}).finally(()=>{a.disabled=!1}))}),l.addEventListener(`submit`,e=>{e.preventDefault();let n=Fa(c,i);n!==void 0&&t(n)}),{root:G(`div`,{className:`child-form`},o,l,i),opened(){i.textContent=``,c.value=``,r.reset(),Bi().then(({pages:t})=>{s.replaceChildren(...t.filter(t=>t.name!==e).map(e=>G(`option`,{value:e.name,label:e.title??e.name})))}).catch(()=>{})},rejectionMessage(e){let t=ro(e);return t?H(`child.rejected`,ho[t.code]??e,n.has(t.page)):void 0}}}var _o=e=>e?.startsWith(`agent:`)??!1;function vo(e,t,n,r){let i=new Set;for(let a of r)a.type===`note:create`?(e.set(a.note.id,{createdBy:t,updatedAt:n}),i.add(a.note.id)):a.type===`note:delete`?e.delete(a.note.id)&&i.add(a.note.id):a.type===`note:update`&&(e.set(a.noteId,{createdBy:e.get(a.noteId)?.createdBy??null,updatedAt:n}),i.add(a.noteId));return i}function yo(e){let t=e.slice(e.indexOf(`:`)+1);return e.startsWith(`user:`)&&t.split(`@`)[0]||t}function bo(e){return e.startsWith(`claude`)?`claude`:e.startsWith(`chatgpt`)||e.startsWith(`openai`)?`openai`:`agent`}var xo=class{board;lookup=()=>void 0;render=(e,t)=>{let n=this.lookup(e.id);if(!n)return!1;let{createdBy:r}=n,i=ci(n.updatedAt);if(t.append(G(`span`,{className:`note-author`,textContent:r===null?i:H(`author.detail`,yo(r),i),title:r??``})),r!==null&&_o(r)){let e=yo(r),n=bi(bo(e));n.classList.add(`note-agent`,`note-agent-${bo(e)}`),n.role=`img`,n.title=n.ariaLabel=H(`author.agentTitle`,e),t.append(n)}return!0};attach(e,t){this.board=e,this.lookup=t,W(()=>{this.board=void 0})}refresh=e=>{for(let t of e)this.board?.refreshNoteAccessory(t)}};function So(e,t,n=()=>!0){let r=new Map,i=(e,t)=>{let n=r.get(e);n?n.push(t):r.set(e,[t])};for(let e of t)i(e.from,e.to),i(e.to,e.from);let a=new Set(e),o=new Set,s=[...a];for(let e=s.pop();e!==void 0;e=s.pop())for(let t of r.get(e)??[])a.has(t)||o.has(t)||!n(t)||(o.add(t),s.push(t));return[...o]}var Co=new Set([`x`,`y`,`zIndex`]),wo=`drop-target`,To=`note-leaving`;function Eo(e,t,n){let r=U(),i=new Set,a,o,s,c=t=>{let n=e.getNote(t);return n!==void 0&&$(n)!==void 0},l=new Set,u=t=>e.getNote(t)!==void 0&&!c(t)&&!l.has(t),d=(e,n,r)=>{let i=document.elementsFromPoint(e,n).find(e=>e instanceof HTMLElement&&e.matches(`.wema-note`)&&t.contains(e)&&!r.has(e.dataset.noteId??``));return i&&c(i.dataset.noteId??``)?i:void 0},f=e=>t.querySelector(`.wema-note[data-note-id="${CSS.escape(e)}"]`),p=e=>{e!==s&&(s?.classList.remove(wo),e?.classList.add(wo),s=e)},m={capture:!0,signal:r};window.addEventListener(`pointerdown`,n=>{if(!n.isPrimary)return;let r=n.target instanceof Element?n.target.closest(`.wema-note`):null,i=n.button===0&&r&&t.contains(r)?e.getNote(r.dataset.noteId??``):void 0;a=i&&{id:i.id,x:i.x,y:i.y}},m),window.addEventListener(`pointermove`,t=>{if(!a)return;let n=e.getNote(a.id);if(!n||n.x===a.x&&n.y===a.y||e.isViewOnly())return p(void 0);let r=e.getSelection(),i=new Set(r.includes(a.id)?r:[a.id]);p([...i].every(c)?void 0:d(t.clientX,t.clientY,i))},m);let h=e=>{e.isPrimary&&(p(void 0),a&&e.type===`pointerup`&&(o={x:e.clientX,y:e.clientY,copy:e.ctrlKey||e.metaKey},setTimeout(()=>o=void 0)),a=void 0)};window.addEventListener(`pointerup`,h,m),window.addEventListener(`pointercancel`,h,m),e.on(`history:commit`,({deltas:t,origin:n})=>{let r=o;if(o=void 0,!r||n!==`user`||e.isViewOnly())return;let a=new Map;for(let e of t){if(e.type!==`note:update`||!Object.keys(e.after).every(e=>Co.has(e)))return;let{zIndex:t,...n}=e.before;a.set(e.noteId,{...n,...a.get(e.noteId)})}let s=e.getNote(d(r.x,r.y,new Set(a.keys()))?.dataset.noteId??``),c=s&&$(s),l=[...a.keys()].filter(u);if(c===void 0||l.length===0)return;let f=g(c,l,a,r.copy).finally(()=>i.delete(f));i.add(f)});async function g(t,i,a,o){let s=t=>{let n=[...a].filter(([n])=>t(n)&&e.getNote(n)!==void 0);n.length>0&&e.batch(()=>n.forEach(([t,n])=>e.updateNote(t,n)))},c=[],d=[],p=!1,m=e=>{c.push(...e);for(let t of e)l.add(t);if(o)return;let t=e.flatMap(e=>f(e)??[]);for(let e of t)e.classList.add(To);d.push(...t)};try{await Promise.resolve(),m(i),s(e=>o||!i.includes(e));let l=So(i,e.getEdges(),u);if(l.length>0){if(await new Promise(e=>requestAnimationFrame(()=>setTimeout(e))),r.aborted)return;confirm(H(o?`transfer.confirmCopyLinked`:`transfer.confirmMoveLinked`,l.length))&&m(l.filter(u))}let f=c.filter(t=>e.getNote(t)!==void 0),h=Object.fromEntries(f.flatMap(t=>{let n=a.get(t),r=e.getNote(t);return n&&r?[[t,{x:n.x??r.x,y:n.y??r.y}]]:[]})),g={clientId:n.clientId,opId:crypto.randomUUID(),to:t,noteIds:f,positions:h,copy:o},_=await ea(n.slug,g).catch(e=>{if(e instanceof Z)throw e;return ea(n.slug,g)}).catch(e=>({error:e}));if(r.aborted)return;if(`error`in _){for(let e of d)e.classList.remove(To);s(()=>!o);let e=_.error instanceof Z&&_.error.status===409;n.notify(e?H(`transfer.partial`,n.titleOf(t)):q(`failed.transfer`,_.error));return}o||(p=!0),n.notify(H(o?`transfer.copied`:`transfer.moved`,f.length,n.titleOf(t))),_.page&&n.onSent(_.page)}finally{if(!p)for(let e of c)l.delete(e)}}return{settled:()=>Promise.allSettled(i).then(()=>{})}}function Do(e){return[...e].reverse().map(e=>{switch(e.type){case`note:create`:return{type:`note:delete`,note:e.note};case`note:delete`:return{type:`note:create`,note:e.note};case`edge:create`:return{type:`edge:delete`,edge:e.edge};case`edge:delete`:return{type:`edge:create`,edge:e.edge};case`note:update`:return{type:e.type,noteId:e.noteId,before:e.after,after:e.before};case`edge:update`:return{type:e.type,edgeId:e.edgeId,before:e.after,after:e.before}}})}function Oo(e){return{send:t=>e.send(t),close:()=>e.close(),onMessage:t=>e.addEventListener(`message`,e=>t(String(e.data))),onClose:t=>e.addEventListener(`close`,e=>t(e.code))}}var ko=3e4,Ao=3e4;function jo(e){if(e.type===`note:update`)return`note:${e.noteId}`;if(e.type===`edge:update`)return`edge:${e.edgeId}`}function Mo(e){let t=new Set;for(let n of e)n.type===`note:update`||n.type===`edge:update`?t.add(jo(n)):n.type===`note:create`||n.type===`note:delete`?t.add(`note:${n.note.id}`):t.add(`edge:${n.edge.id}`);return t}var No=class{board;connect;hooks;clientId=crypto.randomUUID();lastSeq;snapshotSeq=0;epoch;pending=[];infos=new Map;socket;status=`connecting`;ready=!1;stopped=!1;retries=0;stopPing;stopRetry;constructor(e,t,n={}){this.board=e,this.connect=t,this.hooks=n,e.on(`history:commit`,({deltas:e})=>this.commit(e))}start(){this.setStatus(`connecting`),this.open()}stop(){this.stopped=!0,this.stopPing?.(),this.stopRetry?.(),this.socket?.close()}get pendingCount(){return this.pending.length}noteInfo(e){return this.infos.get(e)}setStatus(e){this.status=e,this.hooks.onStatus?.(e,this.pending.length)}send(e){this.socket?.send(JSON.stringify(e))}authExpired(){this.stopped=!0,this.hooks.onAuthExpired?.()}async open(){if(this.stopped)return;let e;try{e=await this.connect()}catch{if(this.stopped)return;let e=this.hooks.isAuthenticated!==void 0&&!await this.hooks.isAuthenticated();if(this.stopped)return;e?this.authExpired():this.scheduleReconnect();return}if(this.stopped){e.close();return}this.socket=e,e.onMessage(e=>this.onMessage(e)),e.onClose(t=>this.onClose(e,t)),this.send({type:`hello`,clientId:this.clientId,lastSeq:this.lastSeq,epoch:this.epoch});for(let{opId:e,deltas:t}of this.pending)this.send({type:`ops`,opId:e,deltas:t});let t=setInterval(()=>this.socket?.send(oo),ko);this.stopPing=()=>clearInterval(t)}onClose(e,t){this.socket===e&&(this.socket=void 0,this.stopPing?.(),!this.stopped&&(t===4401?this.authExpired():t===4410?(this.stopped=!0,this.hooks.onDeleted?.()):this.scheduleReconnect()))}scheduleReconnect(){this.setStatus(this.ready?`offline`:`connecting`);let e=Math.min(1e3*2**this.retries,Ao);this.retries++;let t=setTimeout(()=>void this.open(),e);this.stopRetry=()=>clearTimeout(t)}commit(e){let t={opId:crypto.randomUUID(),deltas:e,applied:!0};this.pending.push(t),this.send({type:`ops`,opId:t.opId,deltas:e}),this.setStatus(this.status)}onMessage(e){if(e===`pong`)return;let t=JSON.parse(e);switch(t.type){case`snapshot`:this.infos=new Map(Object.entries(t.info??{})),this.board.importData(t.data),this.lastSeq=t.seq,this.snapshotSeq=t.seq,this.epoch=t.epoch??void 0;for(let e of this.pending)e.applied=!1;this.hooks.onTitle?.(t.title),this.hooks.onColor?.(t.color),this.synced();break;case`meta`:this.epoch=t.epoch??void 0,this.hooks.onTitle?.(t.title),this.hooks.onColor?.(t.color),this.synced();break;case`ops`:this.onOps(t);break;case`reject`:this.onReject(t.opId,t.reason,t.fixups??[])}}synced(){this.retries=0,this.setStatus(`synced`),this.ready||(this.ready=!0,this.hooks.onReady?.())}takePending(e){let t=this.pending.findIndex(t=>t.opId===e);return t===-1?void 0:this.pending.splice(t,1)[0]}pendingUpdates(e){return this.pending.filter(e=>e.applied).flatMap(e=>e.deltas).filter(t=>{let n=jo(t);return n!==void 0&&e.has(n)})}applyServer(e){e.length!==0&&this.board.applyRemote([...e,...this.pendingUpdates(Mo(e))])}onOps(e){let t=e.createdAt!==void 0&&e.seq>(this.lastSeq??0)?vo(this.infos,e.actor,e.createdAt,e.deltas):void 0;this.lastSeq=Math.max(this.lastSeq??0,e.seq),this.applyOps(e),t?.size&&this.hooks.onNoteInfo?.(t)}applyOps(e){if(e.clientId!==this.clientId||e.reverts!==void 0){this.applyServer(e.deltas);return}let t=this.takePending(e.opId);t&&(t.applied?this.applyServer(e.fixups??[]):e.seq>this.snapshotSeq&&this.applyServer(e.deltas),this.setStatus(this.status))}onReject(e,t,n){let r=this.takePending(e);if(!r)return;let i=r.applied?Do(r.deltas):[],a=this.pending.filter(e=>e.applied).flatMap(e=>e.deltas);this.board.applyRemote([...i,...n,...a]),this.hooks.onReject?.(t),this.setStatus(this.status)}},Po=`viewports`;function Fo(){try{let e=JSON.parse(Ri.get(Po)??`[]`);return Array.isArray(e)?e.map(e=>Array.isArray(e)&&e.length===4?[e[0],e[3]]:e).filter(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&typeof e[1]==`number`&&Number.isFinite(e[1])):[]}catch{return[]}}var Io=300;function Lo(e,t,n,r=()=>!1){let i=`idle`,a=e.getViewport().zoom,o,s=a,c=()=>{o!==void 0&&(clearTimeout(o),o=void 0,zo(t,s))};return e.on(`viewport:change`,e=>{let t=e.zoom!==a;a=e.zoom,i===`saving`&&t&&!r()&&(s=a,clearTimeout(o),o=setTimeout(c,Io))}),window.addEventListener(`pagehide`,c,{signal:U()}),W(c),{restore(){let r=Ro(t);r===void 0?e.fitToContent():e.setViewport({zoom:r}),Fi(e,n)},start(){i===`idle`&&(i=`saving`)},freeze(){c(),i=`frozen`}}}function Ro(e){return Fo().find(([t])=>t===e)?.[1]}function zo(e,t){let n=Fo().filter(([t])=>t!==e);n.push([e,Math.round(t*1e3)/1e3]),Ri.set(Po,JSON.stringify(n.slice(-200)))}var Bo=8e3,Vo=1500,Ho=`view-only`,Uo=`theme`,Wo=[[`alignLeft`,H(`align.left`),`left`],[`alignCenter`,H(`align.center`),`center`],[`alignRight`,H(`align.right`),`right`],[`alignTop`,H(`align.top`),`top`],[`alignMiddle`,H(`align.middle`),`middle`],[`alignBottom`,H(`align.bottom`),`bottom`]],Go={connecting:H(`status.connecting`),synced:``,offline:H(`status.offline`)},Ko={modified:H(`skip.modified`),connected:H(`skip.connected`),deleted:H(`skip.deleted`),exists:H(`skip.exists`),"endpoint-missing":H(`skip.endpoint-missing`)};function qo(e){let t=[...new Set(e.skipped.map(e=>Ko[e.reason]))],n=t.length>0?H(`revert.reasons`,t):``;return e.applied===0?H(`revert.none`,n):e.skipped.length===0?H(`revert.done`):H(`revert.partial`,e.skipped.length,n)}function Jo(e){if(e.summary===null)return e.reverts===null?H(`ops.noSummary`):H(`ops.summary.revertUnknown`);let t=ao(e.summary);switch(t?.kind){case`pageCreated`:return H(`ops.summary.pageCreated`);case`childRemoved`:return H(`ops.summary.childRemoved`,t.page);case`revert`:return H(`ops.summary.revert`,t.seq);case`notesReceived`:return H(`ops.summary.notesReceived`,t.page);case`notesSent`:return H(`ops.summary.notesSent`,t.page);case`childRecolored`:return H(`ops.summary.childRecolored`,t.page);default:return e.summary}}function Yo(e){return new Promise((t,n)=>{let r=location.protocol===`https:`?`wss`:`ws`,i=new WebSocket(`${r}://${location.host}/ws/${e}`);i.addEventListener(`close`,()=>n(Error(`websocket closed`)),{once:!0}),i.addEventListener(`open`,()=>t(Oo(i)),{once:!0})})}function Xo(e,t,n){let r=null,i=!1,a=G(`div`,{className:`board`}),o=G(`div`,{className:`page-body`},a),s=new mo(t,(e,t)=>void f.enter(t,`/p/${e}`)),c=new xo,l=new pr({container:a,readOnly:!0,theme:Ri.get(Uo)===`card`?`card`:`default`,onImageUpload:ta,onLinkClick:$r,renderNote:s.render,renderNoteAccessory:c.render,noteLinks:{text(e){let t=$(e);return t===void 0?void 0:s.titleOf(t)}},labels:ki,emptyDrag:`pan`});s.attach(l);let u=fi(l,a,{onChange(e){e||d.restore()}}),d=Lo(l,t,a,u.isStacked),f=Ka(l,d.freeze,u.isStacked),p=(e,t)=>(e.addEventListener(`click`,n=>{ei(n)&&(n.preventDefault(),f.leave(e.href,t()))}),e),m=e=>l.getNotes().find(t=>$(t)===e),h=[t],g=()=>h[0];Ur(e=>{if(e===`/`)return f.leaveOnPop(g());let n=Wr(e);if(n===void 0||n===t)return;let r=h.indexOf(n);if(r>=0)return f.leaveOnPop(h[r+1]);let i=m(n);return i&&f.enterOnPop(i.id)});let _=async()=>{if(u.isStacked()){let e=n?.kind===`leave`?m(n.from):void 0;e&&l.revealNotes([e.id])}else d.restore();await f.arrive(n,m),d.start()},v=Li(o,Bo),y=e=>t=>v(q(e,t)),b=G(`h1`,{className:`page-title`,title:H(`page.titleHint`,t)}),x=G(`span`,{className:`sync-status`}),S=G(`span`,{className:`crumbs`}),C=e=>{r=e,b.textContent=e??t,document.title=H(`documentTitle`,e??t,Mr.siteName)};C(null);let w=Di(e=>{Xi(t,e).then(e=>P(e.color)).catch(y(`failed.color`))}),{undo:T,redo:E}=Ni(l),D=()=>{if(u.isStacked())return{};let e=l.getNotes().length%10*20,t=l.getViewport();return{x:(120+e-t.x)/t.zoom,y:(80+e-t.y)/t.zoom}},ee=(e={})=>{let t=l.addNote({...D(),...e});t&&u.isStacked()&&l.revealNotes([t.id])},O=X(`add`,H(`note.add`),()=>ee()),te=go(t,e=>{ee({...to,text:``,meta:{[eo]:e}}),re.close()}),ne=X(`childPage`,H(`child.place`)),re=wi(ne,te.root,{onOpen:te.opened}),ie=()=>{l.autoLayout(),Fi(l,a)},k=X(`layout`,H(`layout.title`)),A=()=>l.getSelection().length<2,j=G(`div`,{className:`layout-panel`}),ae=wi(k,j,{instead:()=>A()?(ie(),!0):!1}),oe,se=e=>{if(e===oe)return;oe=e,ae.close();let t=H(e?`layout.auto`:`layout.title`);k.title=k.ariaLabel=t,k.replaceChildren(bi(e?`autoLayout`:`layout`)),k.ariaExpanded=e?null:`false`},ce=[],M=(e,t,n,r)=>{let i=X(e,t,()=>{r(l.getSelection()),ae.close()});ce.push([i,n]),j.append(i)};for(let[e,t,n]of Wo)M(e,t,2,e=>l.alignNotes(e,n));M(`distributeH`,H(`layout.distributeH`),3,e=>l.distributeNotes(e,`horizontal`)),M(`distributeV`,H(`layout.distributeV`),3,e=>l.distributeNotes(e,`vertical`)),M(`autoLayout`,H(`layout.auto`),0,ie);let N=()=>{let e=l.isReadOnly()||l.isViewOnly();T.disabled=e||!l.canUndo(),E.disabled=e||!l.canRedo(),O.disabled=e,ne.disabled=e;let t=l.getSelection().length;for(let[n,r]of ce)n.disabled=e||t<r;let n=A();se(n),k.disabled=n&&e};document.addEventListener(`keydown`,e=>{if(!(e.ctrlKey||e.metaKey)||e.key!==`a`||l.isReadOnly()||document.querySelector(`dialog[open]`))return;let t=document.activeElement;t instanceof HTMLElement&&(t.isContentEditable||t.matches(`input, textarea`))||(e.preventDefault(),l.selectAll())},{signal:U()}),l.on(`readOnly:change`,N),l.on(`history:change`,N),l.on(`note:select`,N),l.on(`note:delete`,N),N();let le=G(`button`,{type:`button`,className:`text-button`,hidden:!0}),ue=G(`div`,{className:`link-list`}),de=G(`div`,{className:`menu`}),fe=wi(X(`menu`,H(`menu.title`)),de,{align:`right`}),pe=da(t,y(`failed.bookmark`)),me=xi([p(G(`a`,{href:`/`,textContent:H(`list`)}),g),S,b,w.root,pe,x],[G(`span`,{className:`tool-group`},T,E),Si(),G(`span`,{className:`tool-group`},O,re.root),Si(),G(`span`,{className:`tool-group optional`},ae.root,Si(),Ii(l,a))],[wi(le,ue,{align:`right`}).root,ua(),fe.root]);e.append(me,o);let P=e=>{me.style.backgroundColor=e??``,w.show(e)};Ui(t).then(({ancestors:e})=>{h=[...e.map(e=>e.name),t],e.forEach((e,t)=>{let n=h[t+1],r=G(`a`,{href:`/p/${e.name}`,textContent:e.title??e.name});S.append(p(r,()=>n),`›`)})}).catch(y(`failed.ancestors`));let F=new No(l,()=>Yo(t),{onNoteInfo:c.refresh,onReady(){l.setReadOnly(!1),Ri.get(Ho)===`1`&&l.setViewOnly(!0),u.start(),_()},onStatus(e,t){let n=e===`synced`&&t>0?H(`status.saving`):Go[e];x.title!==n&&(x.title=n,x.textContent=e===`offline`?n:``),x.dataset.state!==e&&(x.dataset.state=e)},onTitle:C,onColor:P,onAuthExpired:()=>location.reload(),isAuthenticated:na,onDeleted(){l.setReadOnly(!0),!i&&(alert(H(`page.deletedAlert`)),location.assign(`/`))},onReject(e){v(e===`text conflict`?H(`sync.conflict`):te.rejectionMessage(e)??H(`sync.rejected`,e))}});c.attach(l,e=>F.noteInfo(e)),F.start();let he=Eo(l,a,{slug:t,clientId:F.clientId,titleOf:e=>s.titleOf(e),notify:v,onSent:e=>s.contentChanged(e)});Vr(async()=>{let e=Date.now()+Vo;for(await Promise.race([he.settled(),new Promise(e=>setTimeout(e,Vo))]);F.pendingCount>0&&Date.now()<e;)await new Promise(e=>setTimeout(e,50))}),W(()=>{F.stop(),l.destroy()}),b.addEventListener(`click`,()=>{let e=K({className:`title-input`,value:r??``,placeholder:t,maxLength:200}),n=!1,i=i=>{if(n)return;n=!0,e.replaceWith(b);let a=e.value.trim();i&&a!==(r??``)&&Yi(t,a).catch(y(`failed.rename`))};e.addEventListener(`keydown`,e=>{e.isComposing||(e.key===`Enter`?i(!0):e.key===`Escape`&&i(!1))}),e.addEventListener(`blur`,()=>i(!0)),b.replaceWith(e),e.focus(),e.select()}),Ji(t).then(({pages:e})=>{e.length!==0&&(le.textContent=H(`backlinks.count`,e.length),le.title=H(`backlinks.title`),le.hidden=!1,ue.append(...oa(e)))}).catch(y(`failed.backlinks`));let ge=G(`input`,{type:`checkbox`,checked:!0}),_e=G(`ul`,{className:`op-list`}),ve=G(`div`,{className:`op-result`,role:`status`}),ye=e=>t=>{ve.textContent=q(e,t)},be=async()=>{let{ops:e}=await Qi(t,ge.checked);_e.replaceChildren(...e.map(L)),e.length===0&&_e.append(G(`li`,{className:`empty`,textContent:H(`ops.empty`)}))},I=()=>be().catch(ye(`failed.history`)),xe=async(e,n)=>{n.disabled=!0;try{ve.textContent=qo(await $i(t,e.seq,F.clientId)),await be()}catch(e){ye(`failed.revert`)(e)}};function L(e){let t=e.revertedBy!==null,n=G(`button`,{type:`button`,textContent:H(`ops.revert`),disabled:t});n.addEventListener(`click`,()=>void xe(e,n));let r=Jo(e);return G(`li`,{className:t?`reverted`:``},G(`div`,{className:`op-meta`,textContent:`${ci(e.createdAt)} ${e.actor}`}),G(`div`,{className:`op-summary`,textContent:r+(t?H(`ops.revertedMark`):``)}),n)}ge.addEventListener(`change`,I);let Se=Ti(`history-dialog`,G(`h2`,{textContent:H(`ops.title`)}),G(`div`,{className:`history-head`},G(`label`,{},ge,` `,H(`ops.agentOnly`)),G(`button`,{type:`button`,textContent:H(`ops.refresh`),onclick:I})),ve,_e);e.append(Se);let R=Oi(``,()=>{if(l.isReadOnly())return;let e=!l.isViewOnly();Ri.set(Ho,e?`1`:`0`),l.setViewOnly(e),fe.close()}),Ce=()=>{R.textContent=H(l.isViewOnly()?`menu.viewOnlyExit`:`menu.viewOnly`),N()};l.on(`viewOnly:change`,Ce),Ce();let z=Oi(``,()=>{let e=l.getTheme()===`card`?`default`:`card`;l.setTheme(e),Ri.set(Uo,e),we()}),we=()=>{z.textContent=H(l.getTheme()===`card`?`menu.themeCard`:`menu.themeDefault`)};we(),de.append(R,z,Oi(H(`menu.history`),()=>{fe.close(),ve.textContent=``,Se.showModal(),I()}),Oi(H(`menu.exportJson`),()=>{let e=new Blob([JSON.stringify(l.exportData(),null,2)],{type:`application/json`}),n=G(`a`,{href:URL.createObjectURL(e),download:`${t}.json`});n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e4),fe.close()}),Oi(H(`help`),()=>Qr(`/help`)),Oi(H(`lang.switch`),ji),G(`hr`),Oi(H(`menu.deletePage`),()=>{fe.close(),ai(r??t)&&(i=!0,Zi(t).then(()=>location.assign(`/`)).catch(e=>{i=!1,y(`failed.delete`)(e)}))},`danger`))}var Zo=document.getElementById(`app`);document.documentElement.lang=V,Xr((e,n,r)=>{let i=Wr(e),a=i!==void 0&&t(i);return a||e===`/`||e===`/help`?(Zo.replaceChildren(),a?Xo(Zo,i,r):e===`/help`?zi(Zo):$a(Zo,r),!0):n?(Zo.textContent=H(`notFound`),!0):!1});