From e48654026812987a2538677ec65d2602c1ceb205 Mon Sep 17 00:00:00 2001 From: DaxtonD Date: Sun, 8 Feb 2026 13:52:26 -0600 Subject: [PATCH] fix(collections): refresh chips after changes --- .../{index-C-10yejU.js => index-CIHictPt.js} | 28 +++++++++--------- client-dist/index.html | 29 +++++++++---------- .../src/components/MoveToCollectionModal.tsx | 3 ++ client/src/components/NoteCard.tsx | 27 +++++++++++++++++ client/src/components/Sidebar.tsx | 12 ++++++++ 5 files changed, 70 insertions(+), 29 deletions(-) rename client-dist/assets/{index-C-10yejU.js => index-CIHictPt.js} (82%) diff --git a/client-dist/assets/index-C-10yejU.js b/client-dist/assets/index-CIHictPt.js similarity index 82% rename from client-dist/assets/index-C-10yejU.js rename to client-dist/assets/index-CIHictPt.js index 95e73a0..163097d 100644 --- a/client-dist/assets/index-C-10yejU.js +++ b/client-dist/assets/index-CIHictPt.js @@ -22,7 +22,7 @@ var jj=Object.defineProperty;var Pj=(t,e,n)=>e in t?jj(t,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */(function(t){function e(q,se){var xe=q.length;q.push(se);e:for(;0>>1,Q=q[Me];if(0>>1;Mei(J,xe))ati($t,J)?(q[Me]=$t,q[at]=xe,Me=at):(q[Me]=J,q[_t]=xe,Me=_t);else if(ati($t,xe))q[Me]=$t,q[at]=xe,Me=at;else break e}}return se}function i(q,se){var xe=q.sortIndex-se.sortIndex;return xe!==0?xe:q.id-se.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var a=[],c=[],u=1,d=null,f=3,p=!1,m=!1,g=!1,y=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function x(q){for(var se=n(c);se!==null;){if(se.callback===null)r(c);else if(se.startTime<=q)r(c),se.sortIndex=se.expirationTime,e(a,se);else break;se=n(c)}}function E(q){if(g=!1,x(q),!m)if(n(a)!==null)m=!0,Ae(k);else{var se=n(c);se!==null&&me(E,se.startTime-q)}}function k(q,se){m=!1,g&&(g=!1,v(z),z=-1),p=!0;var xe=f;try{for(x(se),d=n(a);d!==null&&(!(d.expirationTime>se)||q&&!H());){var Me=d.callback;if(typeof Me=="function"){d.callback=null,f=d.priorityLevel;var Q=Me(d.expirationTime<=se);se=t.unstable_now(),typeof Q=="function"?d.callback=Q:d===n(a)&&r(a),x(se)}else r(a);d=n(a)}if(d!==null)var Je=!0;else{var _t=n(c);_t!==null&&me(E,_t.startTime-se),Je=!1}return Je}finally{d=null,f=xe,p=!1}}var M=!1,N=null,z=-1,X=5,L=-1;function H(){return!(t.unstable_now()-Lq||125Me?(q.sortIndex=xe,e(c,q),n(a)===null&&q===n(c)&&(g?(v(z),z=-1):g=!0,me(E,xe-Me))):(q.sortIndex=Q,e(a,q),m||p||(m=!0,Ae(k))),q},t.unstable_shouldYield=H,t.unstable_wrapCallback=function(q){var se=f;return function(){var xe=f;f=se;try{return q.apply(this,arguments)}finally{f=xe}}}})(FN);zN.exports=FN;var rP=zN.exports;/** + */(function(t){function e(q,se){var xe=q.length;q.push(se);e:for(;0>>1,Q=q[Me];if(0>>1;Mei(J,xe))ati($t,J)?(q[Me]=$t,q[at]=xe,Me=at):(q[Me]=J,q[_t]=xe,Me=_t);else if(ati($t,xe))q[Me]=$t,q[at]=xe,Me=at;else break e}}return se}function i(q,se){var xe=q.sortIndex-se.sortIndex;return xe!==0?xe:q.id-se.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var a=[],c=[],u=1,d=null,f=3,p=!1,m=!1,g=!1,y=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function x(q){for(var se=n(c);se!==null;){if(se.callback===null)r(c);else if(se.startTime<=q)r(c),se.sortIndex=se.expirationTime,e(a,se);else break;se=n(c)}}function E(q){if(g=!1,x(q),!m)if(n(a)!==null)m=!0,Ae(k);else{var se=n(c);se!==null&&me(E,se.startTime-q)}}function k(q,se){m=!1,g&&(g=!1,v(z),z=-1),p=!0;var xe=f;try{for(x(se),d=n(a);d!==null&&(!(d.expirationTime>se)||q&&!H());){var Me=d.callback;if(typeof Me=="function"){d.callback=null,f=d.priorityLevel;var Q=Me(d.expirationTime<=se);se=t.unstable_now(),typeof Q=="function"?d.callback=Q:d===n(a)&&r(a),x(se)}else r(a);d=n(a)}if(d!==null)var Je=!0;else{var _t=n(c);_t!==null&&me(E,_t.startTime-se),Je=!1}return Je}finally{d=null,f=xe,p=!1}}var M=!1,N=null,z=-1,X=5,L=-1;function H(){return!(t.unstable_now()-Lq||125Me?(q.sortIndex=xe,e(c,q),n(a)===null&&q===n(c)&&(g?(v(z),z=-1):g=!0,me(E,xe-Me))):(q.sortIndex=Q,e(a,q),m||p||(m=!0,Ae(k))),q},t.unstable_shouldYield=H,t.unstable_wrapCallback=function(q){var se=f;return function(){var xe=f;f=se;try{return q.apply(this,arguments)}finally{f=xe}}}})(FN);zN.exports=FN;var rP=zN.exports;/** * @license React * react-dom.production.min.js * @@ -37,12 +37,12 @@ var jj=Object.defineProperty;var Pj=(t,e,n)=>e in t?jj(t,e,{enumerable:!0,config `+i[o].replace(" at new "," at ");return t.displayName&&a.includes("")&&(a=a.replace("",t.displayName)),a}while(1<=o&&0<=l);break}}}finally{Bg=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?au(t):""}function cP(t){switch(t.tag){case 5:return au(t.type);case 16:return au("Lazy");case 13:return au("Suspense");case 19:return au("SuspenseList");case 0:case 2:case 15:return t=Ug(t.type,!1),t;case 11:return t=Ug(t.type.render,!1),t;case 1:return t=Ug(t.type,!0),t;default:return""}}function xv(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Aa:return"Fragment";case Ta:return"Portal";case vv:return"Profiler";case Lw:return"StrictMode";case wv:return"Suspense";case bv:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case UN:return(t.displayName||"Context")+".Consumer";case BN:return(t._context.displayName||"Context")+".Provider";case _w:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case zw:return e=t.displayName||null,e!==null?e:xv(t.type)||"Memo";case To:e=t._payload,t=t._init;try{return xv(t(e))}catch{}}return null}function uP(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return xv(e);case 8:return e===Lw?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function rl(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function VN(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function dP(t){var e=VN(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Sf(t){t._valueTracker||(t._valueTracker=dP(t))}function WN(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=VN(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function zh(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function kv(t,e){var n=e.checked;return Rn({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function Y1(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=rl(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function KN(t,e){e=e.checked,e!=null&&Pw(t,"checked",e,!1)}function Sv(t,e){KN(t,e);var n=rl(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?Cv(t,e.type,n):e.hasOwnProperty("defaultValue")&&Cv(t,e.type,rl(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function q1(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function Cv(t,e,n){(e!=="number"||zh(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var cu=Array.isArray;function Ba(t,e,n,r){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=Cf.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function Yu(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var vu={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},fP=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(t){fP.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),vu[e]=vu[t]})});function GN(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||vu.hasOwnProperty(t)&&vu[t]?(""+e).trim():e+"px"}function XN(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=GN(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,i):t[n]=i}}var hP=Rn({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Tv(t,e){if(e){if(hP[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(Te(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(Te(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(Te(61))}if(e.style!=null&&typeof e.style!="object")throw Error(Te(62))}}function Av(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Mv=null;function Fw(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var Iv=null,Ua=null,Ha=null;function X1(t){if(t=Bd(t)){if(typeof Iv!="function")throw Error(Te(280));var e=t.stateNode;e&&(e=Dm(e),Iv(t.stateNode,t.type,e))}}function QN(t){Ua?Ha?Ha.push(t):Ha=[t]:Ua=t}function ZN(){if(Ua){var t=Ua,e=Ha;if(Ha=Ua=null,X1(t),e)for(t=0;t>>=0,t===0?32:31-(CP(t)/EP|0)|0}var Ef=64,Nf=4194304;function uu(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function Uh(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,i=t.suspendedLanes,s=t.pingedLanes,o=n&268435455;if(o!==0){var l=o&~i;l!==0?r=uu(l):(s&=o,s!==0&&(r=uu(s)))}else o=n&~i,o!==0?r=uu(o):s!==0&&(r=uu(s));if(r===0)return 0;if(e!==0&&e!==r&&!(e&i)&&(i=r&-r,s=e&-e,i>=s||i===16&&(s&4194240)!==0))return e;if(r&4&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0n;n++)e.push(t);return e}function Fd(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Xi(e),t[e]=n}function MP(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0=bu),ok=" ",lk=!1;function wT(t,e){switch(t){case"keyup":return rL.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function bT(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ma=!1;function sL(t,e){switch(t){case"compositionend":return bT(e);case"keypress":return e.which!==32?null:(lk=!0,ok);case"textInput":return t=e.data,t===ok&&lk?null:t;default:return null}}function oL(t,e){if(Ma)return t==="compositionend"||!Yw&&wT(t,e)?(t=yT(),dh=Vw=zo=null,Ma=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=dk(n)}}function CT(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?CT(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function ET(){for(var t=window,e=zh();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=zh(t.document)}return e}function qw(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function mL(t){var e=ET(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&CT(n.ownerDocument.documentElement,n)){if(r!==null&&qw(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!t.extend&&s>r&&(i=r,r=s,s=i),i=fk(n,s);var o=fk(n,r);i&&o&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==o.node||t.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),s>r?(t.addRange(e),t.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Ia=null,Lv=null,ku=null,_v=!1;function hk(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;_v||Ia==null||Ia!==zh(r)||(r=Ia,"selectionStart"in r&&qw(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),ku&&Zu(ku,r)||(ku=r,r=Wh(Lv,"onSelect"),0Oa||(t.current=Hv[Oa],Hv[Oa]=null,Oa--)}function bn(t,e){Oa++,Hv[Oa]=t.current,t.current=e}var il={},Rr=gl(il),ei=gl(!1),Wl=il;function sc(t,e){var n=t.type.contextTypes;if(!n)return il;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=e[s];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function ti(t){return t=t.childContextTypes,t!=null}function Yh(){Sn(ei),Sn(Rr)}function bk(t,e,n){if(Rr.current!==il)throw Error(Te(168));bn(Rr,e),bn(ei,n)}function jT(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in e))throw Error(Te(108,uP(t)||"Unknown",i));return Rn({},n,r)}function qh(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||il,Wl=Rr.current,bn(Rr,t),bn(ei,ei.current),!0}function xk(t,e,n){var r=t.stateNode;if(!r)throw Error(Te(169));n?(t=jT(t,e,Wl),r.__reactInternalMemoizedMergedChildContext=t,Sn(ei),Sn(Rr),bn(Rr,t)):Sn(ei),bn(ei,n)}var Vs=null,Om=!1,ny=!1;function PT(t){Vs===null?Vs=[t]:Vs.push(t)}function TL(t){Om=!0,PT(t)}function yl(){if(!ny&&Vs!==null){ny=!0;var t=0,e=un;try{var n=Vs;for(un=1;t>=o,i-=o,Ys=1<<32-Xi(e)+i|n<z?(X=N,N=null):X=N.sibling;var L=f(v,N,x[z],E);if(L===null){N===null&&(N=X);break}t&&N&&L.alternate===null&&e(v,N),w=s(L,w,z),M===null?k=L:M.sibling=L,M=L,N=X}if(z===x.length)return n(v,N),Tn&&Sl(v,z),k;if(N===null){for(;zz?(X=N,N=null):X=N.sibling;var H=f(v,N,L.value,E);if(H===null){N===null&&(N=X);break}t&&N&&H.alternate===null&&e(v,N),w=s(H,w,z),M===null?k=H:M.sibling=H,M=H,N=X}if(L.done)return n(v,N),Tn&&Sl(v,z),k;if(N===null){for(;!L.done;z++,L=x.next())L=d(v,L.value,E),L!==null&&(w=s(L,w,z),M===null?k=L:M.sibling=L,M=L);return Tn&&Sl(v,z),k}for(N=r(v,N);!L.done;z++,L=x.next())L=p(N,v,z,L.value,E),L!==null&&(t&&L.alternate!==null&&N.delete(L.key===null?z:L.key),w=s(L,w,z),M===null?k=L:M.sibling=L,M=L);return t&&N.forEach(function(W){return e(v,W)}),Tn&&Sl(v,z),k}function y(v,w,x,E){if(typeof x=="object"&&x!==null&&x.type===Aa&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case kf:e:{for(var k=x.key,M=w;M!==null;){if(M.key===k){if(k=x.type,k===Aa){if(M.tag===7){n(v,M.sibling),w=i(M,x.props.children),w.return=v,v=w;break e}}else if(M.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===To&&Ck(k)===M.type){n(v,M.sibling),w=i(M,x.props),w.ref=Xc(v,M,x),w.return=v,v=w;break e}n(v,M);break}else e(v,M);M=M.sibling}x.type===Aa?(w=_l(x.props.children,v.mode,E,x.key),w.return=v,v=w):(E=wh(x.type,x.key,x.props,null,v.mode,E),E.ref=Xc(v,w,x),E.return=v,v=E)}return o(v);case Ta:e:{for(M=x.key;w!==null;){if(w.key===M)if(w.tag===4&&w.stateNode.containerInfo===x.containerInfo&&w.stateNode.implementation===x.implementation){n(v,w.sibling),w=i(w,x.children||[]),w.return=v,v=w;break e}else{n(v,w);break}else e(v,w);w=w.sibling}w=uy(x,v.mode,E),w.return=v,v=w}return o(v);case To:return M=x._init,y(v,w,M(x._payload),E)}if(cu(x))return m(v,w,x,E);if(Kc(x))return g(v,w,x,E);Of(v,x)}return typeof x=="string"&&x!==""||typeof x=="number"?(x=""+x,w!==null&&w.tag===6?(n(v,w.sibling),w=i(w,x),w.return=v,v=w):(n(v,w),w=cy(x,v.mode,E),w.return=v,v=w),o(v)):n(v,w)}return y}var lc=FT(!0),$T=FT(!1),Xh=gl(null),Qh=null,La=null,Qw=null;function Zw(){Qw=La=Qh=null}function eb(t){var e=Xh.current;Sn(Xh),t._currentValue=e}function Kv(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function Wa(t,e){Qh=t,Qw=La=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Zr=!0),t.firstContext=null)}function ji(t){var e=t._currentValue;if(Qw!==t)if(t={context:t,memoizedValue:e,next:null},La===null){if(Qh===null)throw Error(Te(308));La=t,Qh.dependencies={lanes:0,firstContext:t}}else La=La.next=t;return e}var Ml=null;function tb(t){Ml===null?Ml=[t]:Ml.push(t)}function BT(t,e,n,r){var i=e.interleaved;return i===null?(n.next=n,tb(e)):(n.next=i.next,i.next=n),e.interleaved=n,so(t,r)}function so(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var Ao=!1;function nb(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function UT(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Qs(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function qo(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,en&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,so(t,n)}return i=r.interleaved,i===null?(e.next=e,tb(r)):(e.next=i.next,i.next=e),r.interleaved=e,so(t,n)}function hh(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Bw(t,n)}}function Ek(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?i=s=e:s=s.next=e}else i=s=e;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function Zh(t,e,n,r){var i=t.updateQueue;Ao=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,l=i.shared.pending;if(l!==null){i.shared.pending=null;var a=l,c=a.next;a.next=null,o===null?s=c:o.next=c,o=a;var u=t.alternate;u!==null&&(u=u.updateQueue,l=u.lastBaseUpdate,l!==o&&(l===null?u.firstBaseUpdate=c:l.next=c,u.lastBaseUpdate=a))}if(s!==null){var d=i.baseState;o=0,u=c=a=null,l=s;do{var f=l.lane,p=l.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var m=t,g=l;switch(f=e,p=n,g.tag){case 1:if(m=g.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Rn({},d,f);break e;case 2:Ao=!0}}l.callback!==null&&l.lane!==0&&(t.flags|=64,f=i.effects,f===null?i.effects=[l]:f.push(l))}else p={eventTime:p,lane:f,tag:l.tag,payload:l.payload,callback:l.callback,next:null},u===null?(c=u=p,a=d):u=u.next=p,o|=f;if(l=l.next,l===null){if(l=i.shared.pending,l===null)break;f=l,l=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(u===null&&(a=d),i.baseState=a,i.firstBaseUpdate=c,i.lastBaseUpdate=u,e=i.shared.interleaved,e!==null){i=e;do o|=i.lane,i=i.next;while(i!==e)}else s===null&&(i.shared.lanes=0);ql|=o,t.lanes=o,t.memoizedState=d}}function Nk(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;en?n:4,t(!0);var r=iy.transition;iy.transition={};try{t(!1),e()}finally{un=n,iy.transition=r}}function sA(){return Pi().memoizedState}function RL(t,e,n){var r=Go(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},oA(t))lA(e,n);else if(n=BT(t,e,n,r),n!==null){var i=$r();Qi(n,t,r,i),aA(n,e,r)}}function DL(t,e,n){var r=Go(t),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(oA(t))lA(e,i);else{var s=t.alternate;if(t.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,l=s(o,n);if(i.hasEagerState=!0,i.eagerState=l,es(l,o)){var a=e.interleaved;a===null?(i.next=i,tb(e)):(i.next=a.next,a.next=i),e.interleaved=i;return}}catch{}finally{}n=BT(t,e,i,r),n!==null&&(i=$r(),Qi(n,t,r,i),aA(n,e,r))}}function oA(t){var e=t.alternate;return t===In||e!==null&&e===In}function lA(t,e){Su=tp=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function aA(t,e,n){if(n&4194240){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Bw(t,n)}}var np={readContext:ji,useCallback:Cr,useContext:Cr,useEffect:Cr,useImperativeHandle:Cr,useInsertionEffect:Cr,useLayoutEffect:Cr,useMemo:Cr,useReducer:Cr,useRef:Cr,useState:Cr,useDebugValue:Cr,useDeferredValue:Cr,useTransition:Cr,useMutableSource:Cr,useSyncExternalStore:Cr,useId:Cr,unstable_isNewReconciler:!1},OL={readContext:ji,useCallback:function(t,e){return ms().memoizedState=[t,e===void 0?null:e],t},useContext:ji,useEffect:Ak,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,mh(4194308,4,eA.bind(null,e,t),n)},useLayoutEffect:function(t,e){return mh(4194308,4,t,e)},useInsertionEffect:function(t,e){return mh(4,2,t,e)},useMemo:function(t,e){var n=ms();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=ms();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=RL.bind(null,In,t),[r.memoizedState,t]},useRef:function(t){var e=ms();return t={current:t},e.memoizedState=t},useState:Tk,useDebugValue:ub,useDeferredValue:function(t){return ms().memoizedState=t},useTransition:function(){var t=Tk(!1),e=t[0];return t=IL.bind(null,t[1]),ms().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=In,i=ms();if(Tn){if(n===void 0)throw Error(Te(407));n=n()}else{if(n=e(),ar===null)throw Error(Te(349));Yl&30||KT(r,e,n)}i.memoizedState=n;var s={value:n,getSnapshot:e};return i.queue=s,Ak(qT.bind(null,r,s,t),[t]),r.flags|=2048,ld(9,YT.bind(null,r,s,n,e),void 0,null),n},useId:function(){var t=ms(),e=ar.identifierPrefix;if(Tn){var n=qs,r=Ys;n=(r&~(1<<32-Xi(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=sd++,0<\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=o.createElement(n,{is:r.is}):(t=o.createElement(n),n==="select"&&(o=t,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):t=o.createElementNS(t,n),t[vs]=e,t[nd]=r,vA(t,e,!1,!1),e.stateNode=t;e:{switch(o=Av(n,r),n){case"dialog":xn("cancel",t),xn("close",t),i=r;break;case"iframe":case"object":case"embed":xn("load",t),i=r;break;case"video":case"audio":for(i=0;iuc&&(e.flags|=128,r=!0,Qc(s,!1),e.lanes=4194304)}else{if(!r)if(t=ep(o),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Qc(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!Tn)return Er(e),null}else 2*_n()-s.renderingStartTime>uc&&n!==1073741824&&(e.flags|=128,r=!0,Qc(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(n=s.last,n!==null?n.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=_n(),e.sibling=null,n=An.current,bn(An,r?n&1|2:n&1),e):(Er(e),null);case 22:case 23:return gb(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?ci&1073741824&&(Er(e),e.subtreeFlags&6&&(e.flags|=8192)):Er(e),null;case 24:return null;case 25:return null}throw Error(Te(156,e.tag))}function BL(t,e){switch(Gw(e),e.tag){case 1:return ti(e.type)&&Yh(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return ac(),Sn(ei),Sn(Rr),sb(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return ib(e),null;case 13:if(Sn(An),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Te(340));oc()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Sn(An),null;case 4:return ac(),null;case 10:return eb(e.type._context),null;case 22:case 23:return gb(),null;case 24:return null;default:return null}}var Pf=!1,Ar=!1,UL=typeof WeakSet=="function"?WeakSet:Set,Qe=null;function _a(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){On(t,e,r)}else n.current=null}function t0(t,e,n){try{n()}catch(r){On(t,e,r)}}var Fk=!1;function HL(t,e){if(zv=Hh,t=ET(),qw(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,l=-1,a=-1,c=0,u=0,d=t,f=null;t:for(;;){for(var p;d!==n||i!==0&&d.nodeType!==3||(l=o+i),d!==s||r!==0&&d.nodeType!==3||(a=o+r),d.nodeType===3&&(o+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===t)break t;if(f===n&&++c===i&&(l=o),f===s&&++u===r&&(a=o),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=l===-1||a===-1?null:{start:l,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Fv={focusedElem:t,selectionRange:n},Hh=!1,Qe=e;Qe!==null;)if(e=Qe,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Qe=t;else for(;Qe!==null;){e=Qe;try{var m=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var g=m.memoizedProps,y=m.memoizedState,v=e.stateNode,w=v.getSnapshotBeforeUpdate(e.elementType===e.type?g:Wi(e.type,g),y);v.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var x=e.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Te(163))}}catch(E){On(e,e.return,E)}if(t=e.sibling,t!==null){t.return=e.return,Qe=t;break}Qe=e.return}return m=Fk,Fk=!1,m}function Cu(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&t)===t){var s=i.destroy;i.destroy=void 0,s!==void 0&&t0(e,n,s)}i=i.next}while(i!==r)}}function Lm(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function n0(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function xA(t){var e=t.alternate;e!==null&&(t.alternate=null,xA(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[vs],delete e[nd],delete e[Uv],delete e[EL],delete e[NL])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function kA(t){return t.tag===5||t.tag===3||t.tag===4}function $k(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||kA(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function r0(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Kh));else if(r!==4&&(t=t.child,t!==null))for(r0(t,e,n),t=t.sibling;t!==null;)r0(t,e,n),t=t.sibling}function i0(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(i0(t,e,n),t=t.sibling;t!==null;)i0(t,e,n),t=t.sibling}var pr=null,Ki=!1;function So(t,e,n){for(n=n.child;n!==null;)SA(t,e,n),n=n.sibling}function SA(t,e,n){if(ks&&typeof ks.onCommitFiberUnmount=="function")try{ks.onCommitFiberUnmount(Am,n)}catch{}switch(n.tag){case 5:Ar||_a(n,e);case 6:var r=pr,i=Ki;pr=null,So(t,e,n),pr=r,Ki=i,pr!==null&&(Ki?(t=pr,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):pr.removeChild(n.stateNode));break;case 18:pr!==null&&(Ki?(t=pr,n=n.stateNode,t.nodeType===8?ty(t.parentNode,n):t.nodeType===1&&ty(t,n),Xu(t)):ty(pr,n.stateNode));break;case 4:r=pr,i=Ki,pr=n.stateNode.containerInfo,Ki=!0,So(t,e,n),pr=r,Ki=i;break;case 0:case 11:case 14:case 15:if(!Ar&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&t0(n,e,o),i=i.next}while(i!==r)}So(t,e,n);break;case 1:if(!Ar&&(_a(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){On(n,e,l)}So(t,e,n);break;case 21:So(t,e,n);break;case 22:n.mode&1?(Ar=(r=Ar)||n.memoizedState!==null,So(t,e,n),Ar=r):So(t,e,n);break;default:So(t,e,n)}}function Bk(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new UL),e.forEach(function(r){var i=QL.bind(null,t,r);n.has(r)||(n.add(r),r.then(i,i))})}}function Hi(t,e){var n=e.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=_n()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*WL(r/1960))-r,10t?16:t,Fo===null)var r=!1;else{if(t=Fo,Fo=null,sp=0,en&6)throw Error(Te(331));var i=en;for(en|=4,Qe=t.current;Qe!==null;){var s=Qe,o=s.child;if(Qe.flags&16){var l=s.deletions;if(l!==null){for(var a=0;a_n()-pb?Ll(t,0):hb|=n),ni(t,e)}function RA(t,e){e===0&&(t.mode&1?(e=Nf,Nf<<=1,!(Nf&130023424)&&(Nf=4194304)):e=1);var n=$r();t=so(t,e),t!==null&&(Fd(t,e,n),ni(t,n))}function XL(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),RA(t,n)}function QL(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,i=t.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(Te(314))}r!==null&&r.delete(e),RA(t,n)}var DA;DA=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||ei.current)Zr=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return Zr=!1,FL(t,e,n);Zr=!!(t.flags&131072)}else Zr=!1,Tn&&e.flags&1048576&<(e,Gh,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;gh(t,e),t=e.pendingProps;var i=sc(e,Rr.current);Wa(e,n),i=lb(null,e,r,t,i,n);var s=ab();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,ti(r)?(s=!0,qh(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,nb(e),i.updater=Pm,e.stateNode=i,i._reactInternals=e,qv(e,r,t,n),e=Xv(null,e,r,!0,s,n)):(e.tag=0,Tn&&s&&Jw(e),_r(null,e,i,n),e=e.child),e;case 16:r=e.elementType;e:{switch(gh(t,e),t=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=e_(r),t=Wi(r,t),i){case 0:e=Gv(null,e,r,t,n);break e;case 1:e=Lk(null,e,r,t,n);break e;case 11:e=jk(null,e,r,t,n);break e;case 14:e=Pk(null,e,r,Wi(r.type,t),n);break e}throw Error(Te(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),Gv(t,e,r,i,n);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),Lk(t,e,r,i,n);case 3:e:{if(mA(e),t===null)throw Error(Te(387));r=e.pendingProps,s=e.memoizedState,i=s.element,UT(t,e),Zh(e,r,null,n);var o=e.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){i=cc(Error(Te(423)),e),e=_k(t,e,r,n,i);break e}else if(r!==i){i=cc(Error(Te(424)),e),e=_k(t,e,r,n,i);break e}else for(di=Yo(e.stateNode.containerInfo.firstChild),fi=e,Tn=!0,Yi=null,n=$T(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(oc(),r===i){e=oo(t,e,n);break e}_r(t,e,r,n)}e=e.child}return e;case 5:return HT(e),t===null&&Wv(e),r=e.type,i=e.pendingProps,s=t!==null?t.memoizedProps:null,o=i.children,$v(r,i)?o=null:s!==null&&$v(r,s)&&(e.flags|=32),pA(t,e),_r(t,e,o,n),e.child;case 6:return t===null&&Wv(e),null;case 13:return gA(t,e,n);case 4:return rb(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=lc(e,null,r,n):_r(t,e,r,n),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),jk(t,e,r,i,n);case 7:return _r(t,e,e.pendingProps,n),e.child;case 8:return _r(t,e,e.pendingProps.children,n),e.child;case 12:return _r(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,bn(Xh,r._currentValue),r._currentValue=o,s!==null)if(es(s.value,o)){if(s.children===i.children&&!ei.current){e=oo(t,e,n);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var l=s.dependencies;if(l!==null){o=s.child;for(var a=l.firstContext;a!==null;){if(a.context===r){if(s.tag===1){a=Qs(-1,n&-n),a.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?a.next=a:(a.next=u.next,u.next=a),c.pending=a}}s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),Kv(s.return,n,e),l.lanes|=n;break}a=a.next}}else if(s.tag===10)o=s.type===e.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(Te(341));o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Kv(o,n,e),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===e){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}_r(t,e,i.children,n),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,Wa(e,n),i=ji(i),r=r(i),e.flags|=1,_r(t,e,r,n),e.child;case 14:return r=e.type,i=Wi(r,e.pendingProps),i=Wi(r.type,i),Pk(t,e,r,i,n);case 15:return fA(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),gh(t,e),e.tag=1,ti(r)?(t=!0,qh(e)):t=!1,Wa(e,n),cA(e,r,i),qv(e,r,i,n),Xv(null,e,r,!0,t,n);case 19:return yA(t,e,n);case 22:return hA(t,e,n)}throw Error(Te(156,e.tag))};function OA(t,e){return oT(t,e)}function ZL(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Mi(t,e,n,r){return new ZL(t,e,n,r)}function vb(t){return t=t.prototype,!(!t||!t.isReactComponent)}function e_(t){if(typeof t=="function")return vb(t)?1:0;if(t!=null){if(t=t.$$typeof,t===_w)return 11;if(t===zw)return 14}return 2}function Xo(t,e){var n=t.alternate;return n===null?(n=Mi(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function wh(t,e,n,r,i,s){var o=2;if(r=t,typeof t=="function")vb(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case Aa:return _l(n.children,i,s,e);case Lw:o=8,i|=8;break;case vv:return t=Mi(12,n,e,i|2),t.elementType=vv,t.lanes=s,t;case wv:return t=Mi(13,n,e,i),t.elementType=wv,t.lanes=s,t;case bv:return t=Mi(19,n,e,i),t.elementType=bv,t.lanes=s,t;case HN:return zm(n,i,s,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case BN:o=10;break e;case UN:o=9;break e;case _w:o=11;break e;case zw:o=14;break e;case To:o=16,r=null;break e}throw Error(Te(130,t==null?t:typeof t,""))}return e=Mi(o,n,e,i),e.elementType=t,e.type=r,e.lanes=s,e}function _l(t,e,n,r){return t=Mi(7,t,r,e),t.lanes=n,t}function zm(t,e,n,r){return t=Mi(22,t,r,e),t.elementType=HN,t.lanes=n,t.stateNode={isHidden:!1},t}function cy(t,e,n){return t=Mi(6,t,null,e),t.lanes=n,t}function uy(t,e,n){return e=Mi(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function t_(t,e,n,r,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vg(0),this.expirationTimes=Vg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vg(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function wb(t,e,n,r,i,s,o,l,a){return t=new t_(t,e,n,l,a),e===1?(e=1,s===!0&&(e|=8)):e=0,s=Mi(3,null,null,e),t.current=s,s.stateNode=t,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},nb(s),t}function n_(t,e,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(_A)}catch(t){console.error(t)}}_A(),_N.exports=mi;var zn=_N.exports;const l_=EN(zn);var zA,Jk=zn;zA=Jk.createRoot,Jk.hydrateRoot;const Gk="fn.deviceKey",Xk="fn.deviceName";function Qk(t){try{return localStorage.getItem(t)}catch{return null}}function Zk(t,e){try{localStorage.setItem(t,e)}catch{}}function a_(){try{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID()}catch{}return"dev_"+Math.random().toString(36).slice(2)+"_"+Date.now().toString(36)}function c_(){var t,e;try{const n=navigator.userAgentData,r=n&&typeof n.platform=="string"&&n.platform||navigator.platform||"device",s=!!(n&&typeof n.mobile=="boolean"?n.mobile:/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent||""))?"Mobile":"Desktop",o=typeof window<"u"?(t=window.screen)==null?void 0:t.width:0,l=typeof window<"u"?(e=window.screen)==null?void 0:e.height:0,a=o&&l?`${Math.max(o,l)}x${Math.min(o,l)}`:"";return[r,s,a].filter(Boolean).join(" ")}catch{return"Device"}}function FA(){let t=Qk(Gk)||"";t||(t=a_(),Zk(Gk,t));let e=Qk(Xk)||"";return e||(e=c_(),Zk(Xk,e)),{deviceKey:t,deviceName:e}}function Hd(){const t=FA();return{"x-device-key":t.deviceKey,"x-device-name":t.deviceName}}async function u_(t,e,n,r){const i={email:t,password:e};n&&(i.name=n),r&&(i.inviteToken=r);const s=await fetch("/api/auth/register",{method:"POST",headers:{"Content-Type":"application/json",...Hd()},body:JSON.stringify(i)});if(!s.ok)throw new Error(await s.text());return s.json()}async function d_(t,e){const n=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json",...Hd()},body:JSON.stringify({email:t,password:e})});if(!n.ok)throw new Error(await n.text());return n.json()}async function f_(t){const e=await fetch("/api/auth/me",{headers:{Authorization:`Bearer ${t}`,...Hd()}});if(!e.ok)throw new Error(await e.text());return e.json()}async function h_(t,e){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Hd()},body:JSON.stringify(e)});if(!n.ok)throw new Error(await n.text());return n.json()}async function p_(t,e){const n=await fetch("/api/auth/me/photo",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Hd()},body:JSON.stringify({dataUrl:e})});if(!n.ok)throw new Error(await n.text());return n.json()}const $A=b.createContext(void 0);function Sr(){const t=b.useContext($A);if(!t)throw new Error("useAuth must be used within AuthProvider");return t}const m_=({children:t})=>{const[e,n]=b.useState(null),[r,i]=b.useState(()=>localStorage.getItem("fn_token"));b.useEffect(()=>{r&&f_(r).then(u=>n(u.user)).catch(()=>{n(null),i(null),localStorage.removeItem("fn_token")})},[r]),b.useEffect(()=>{if(e)try{if(e.fontFamily&&(document.documentElement.style.setProperty("--app-font-family",e.fontFamily),localStorage.setItem("prefs.fontFamily",e.fontFamily)),typeof e.noteWidth=="number"){const u=e.noteWidth;document.documentElement.style.setProperty("--note-card-width",String(u)+"px"),localStorage.setItem("prefs.noteWidth",String(u));try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}}e.dragBehavior&&localStorage.setItem("prefs.dragBehavior",e.dragBehavior),e.animationSpeed&&localStorage.setItem("prefs.animationSpeed",e.animationSpeed),typeof e.checklistSpacing=="number"&&(document.documentElement.style.setProperty("--checklist-gap",String(e.checklistSpacing)+"px"),localStorage.setItem("prefs.checklistSpacing",String(e.checklistSpacing))),typeof e.checkboxSize=="number"&&(document.documentElement.style.setProperty("--checklist-checkbox-size",String(e.checkboxSize)+"px"),localStorage.setItem("prefs.checkboxSize",String(e.checkboxSize))),typeof e.checklistTextSize=="number"&&(document.documentElement.style.setProperty("--checklist-text-size",String(e.checklistTextSize)+"px"),localStorage.setItem("prefs.checklistTextSize",String(e.checklistTextSize))),typeof e.noteLineSpacing=="number"&&(document.documentElement.style.setProperty("--note-line-height",String(e.noteLineSpacing)),localStorage.setItem("prefs.noteLineSpacing",String(e.noteLineSpacing))),typeof e.imageThumbSize=="number"&&(document.documentElement.style.setProperty("--image-thumb-size",String(e.imageThumbSize)+"px"),localStorage.setItem("prefs.imageThumbSize",String(e.imageThumbSize))),e.checkboxBg&&(document.documentElement.style.setProperty("--checkbox-bg",e.checkboxBg),localStorage.setItem("prefs.checkboxBg",e.checkboxBg)),e.checkboxBorder&&(document.documentElement.style.setProperty("--checkbox-border",e.checkboxBorder),localStorage.setItem("prefs.checkboxBorder",e.checkboxBorder))}catch{}},[e]);async function s(u,d){const f=await d_(u,d),p=f.token;i(p),localStorage.setItem("fn_token",p),n(f.user)}async function o(u,d,f,p){const m=await u_(u,d,f,p),g=m.token;i(g),localStorage.setItem("fn_token",g),n(m.user)}async function l(u){const d=r||localStorage.getItem("fn_token");if(!d)throw new Error("Not authenticated");const f=await p_(d,u);f&&f.user&&n(f.user)}async function a(u){if(!r)throw new Error("Not authenticated");const d=await h_(r,u);d&&d.user?n(d.user):n(f=>f&&{...f,...u||{}})}function c(){i(null),n(null),localStorage.removeItem("fn_token")}return h.jsx($A.Provider,{value:{user:e,token:r,login:s,register:o,logout:c,uploadPhoto:l,updateMe:a},children:t})};function g_({onClose:t}){const{token:e}=Sr(),[n,r]=b.useState(""),[i,s]=b.useState("user"),[o,l]=b.useState(null),[a,c]=b.useState(!1);async function u(d){d&&d.preventDefault(),l(null),c(!0);try{const f=await fetch("/api/invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:e?`Bearer ${e}`:""},body:JSON.stringify({email:n,role:i})});if(!f.ok)throw new Error(await f.text());const p=await f.json();l(`Invite created for ${p.invite.email} (role: ${p.invite.role})`),r(""),s("user")}catch(f){l(`Error: ${(f==null?void 0:f.message)??String(f)}`)}finally{c(!1)}}return h.jsx("div",{className:"image-dialog-backdrop",children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Settings"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsxs("div",{style:{padding:8},children:[h.jsx("h4",{children:"Invites"}),h.jsxs("form",{onSubmit:u,style:{display:"flex",gap:8,alignItems:"center"},children:[h.jsx("input",{placeholder:"Email to invite",value:n,onChange:d=>r(d.target.value),className:"image-url-input"}),h.jsxs("select",{value:i,onChange:d=>s(d.target.value),className:"image-url-input","aria-label":"Role",children:[h.jsx("option",{value:"user",children:"User"}),h.jsx("option",{value:"admin",children:"Admin"})]}),h.jsx("button",{className:"btn",type:"submit",disabled:a||!n,children:"Send invite"})]}),o&&h.jsx("div",{style:{marginTop:8},children:o})]})]})})}const BA=b.createContext(null);function eS(){try{return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch{return"dark"}}function tS(t){try{document.documentElement.dataset.theme=t}catch{}}function y_({children:t}){const[e,n]=b.useState(()=>{try{return localStorage.getItem("prefs.theme")||"system"}catch{return"system"}}),r=b.useMemo(()=>e==="system"?eS():e,[e]);b.useEffect(()=>{tS(r);try{localStorage.setItem("prefs.theme",e)}catch{}if(e==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>tS(eS());try{s.addEventListener("change",o)}catch{}return()=>{try{s.removeEventListener("change",o)}catch{}}}},[e,r]);const i={choice:e,effective:r,setChoice:n};return h.jsx(BA.Provider,{value:i,children:t})}function Sb(){const t=b.useContext(BA);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const v_="0.4.4",w_="/icons/darkicon.png",b_="/icons/lighticon.png",x_="/icons/freemannotes.png",k_="/icons/version.png",S_="/icons/version-light.png";function C_({onClose:t}){var wt,ae,Ee,Ke,ze,Pe,it,ot,xt;const e=(()=>{try{return Sr()}catch{return null}})(),n=(()=>{try{return Sb()}catch{return null}})(),r=n&&n.effective||"dark",i=n&&n.choice||"system",s=n&&n.setChoice||(()=>{}),[o,l]=b.useState(()=>{try{const oe=localStorage.getItem("prefs.checklistSpacing");return oe?Number(oe):15}catch{return 15}}),[a,c]=b.useState(()=>{try{return Number(localStorage.getItem("prefs.checkboxSize")||"20")}catch{return 20}}),[u,d]=b.useState(()=>{try{return Number(localStorage.getItem("prefs.checklistTextSize")||"17")}catch{return 17}}),[f,p]=b.useState(()=>{var oe;try{const Ye=localStorage.getItem("prefs.noteLineSpacing");if(Ye)return Number(Ye);const Ge=e&&((oe=e.user)==null?void 0:oe.noteLineSpacing);return typeof Ge=="number"?Ge:1.38}catch{return 1.38}}),[m,g]=b.useState(()=>{try{const oe=localStorage.getItem("prefs.noteWidth");if(oe)return Number(oe);const Ye=getComputedStyle(document.documentElement);return Number(Ye.getPropertyValue("--note-card-width"))||300}catch{return 300}}),[y,v]=b.useState(()=>{var oe;try{const Ye=localStorage.getItem("prefs.imageThumbSize");if(Ye)return Number(Ye);const Ge=e&&((oe=e.user)==null?void 0:oe.imageThumbSize);if(typeof Ge=="number")return Ge;const K=getComputedStyle(document.documentElement);return Number.parseInt(String(K.getPropertyValue("--image-thumb-size")||"").trim(),10)||96}catch{return 96}}),[w,x]=b.useState(()=>{var oe;try{const Ye=e&&((oe=e.user)==null?void 0:oe.checkboxBg),Ge=localStorage.getItem("prefs.checkboxBg");return Ye||Ge||getComputedStyle(document.documentElement).getPropertyValue("--card").trim()||"#1e1e1e"}catch{return"#1e1e1e"}}),[E,k]=b.useState(()=>{var oe;try{const Ye=e&&((oe=e.user)==null?void 0:oe.checkboxBorder),Ge=localStorage.getItem("prefs.checkboxBorder");return Ye||Ge||getComputedStyle(document.documentElement).getPropertyValue("--checkbox-border-default").trim()||"#ffffff"}catch{return"#ffffff"}}),[M,N]=b.useState(!1),[z,X]=b.useState(()=>{try{return localStorage.getItem("prefs.fontFamily")||"Calibri, system-ui, Arial, sans-serif"}catch{return"Calibri, system-ui, Arial, sans-serif"}}),[L,H]=b.useState(()=>!1),[W,te]=b.useState(()=>{try{return localStorage.getItem("prefs.dragBehavior")||"swap"}catch{return"swap"}}),[ce,ue]=b.useState(()=>{try{return localStorage.getItem("prefs.animationSpeed")||"normal"}catch{return"normal"}}),[Ae,me]=b.useState(()=>{var oe;try{return e&&((oe=e.user)==null?void 0:oe.chipDisplayMode)||"image+text"}catch{return"image+text"}}),q=(()=>{try{const oe=window.matchMedia,Ye=!!(oe&&(oe("(pointer: coarse)").matches||oe("(any-pointer: coarse)").matches)),Ge=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,K=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight,ge=Math.min(Ge,K);return Ye&&ge<=600}catch{return!1}})();b.useEffect(()=>{var Ye,Ge,K,ge,De,Be;const oe=(()=>{try{return Number(localStorage.getItem("prefs.checklistSpacing")||"8")}catch{return 8}})();l(oe);try{const Le=localStorage.getItem("prefs.fontFamily");Le&&X(Le)}catch{}try{const Le=localStorage.getItem("prefs.noteLineSpacing")??((e&&((Ye=e.user)==null?void 0:Ye.noteLineSpacing))!=null?String(e.user.noteLineSpacing):null);Le&&p(Number(Le))}catch{}try{const Le=localStorage.getItem("prefs.noteWidth")??((e&&((Ge=e.user)==null?void 0:Ge.noteWidth))!=null?String(e.user.noteWidth):null);Le&&g(Number(Le))}catch{}try{const Le=localStorage.getItem("prefs.imageThumbSize")??((e&&((K=e.user)==null?void 0:K.imageThumbSize))!=null?String(e.user.imageThumbSize):null);Le&&v(Number(Le))}catch{}try{const Le=localStorage.getItem("prefs.dragBehavior")||e&&((ge=e.user)==null?void 0:ge.dragBehavior)||"swap";Le&&te(Le)}catch{}try{const Le=localStorage.getItem("prefs.animationSpeed")||e&&((De=e.user)==null?void 0:De.animationSpeed)||"normal";Le&&ue(Le)}catch{}try{const Le=e&&((Be=e.user)==null?void 0:Be.chipDisplayMode)||"image+text";Le&&me(Le)}catch{}},[]);async function se(){var oe;document.documentElement.style.setProperty("--checklist-gap",`${o}px`),document.documentElement.style.setProperty("--checklist-checkbox-size",`${a}px`),document.documentElement.style.setProperty("--checklist-text-size",`${u}px`),document.documentElement.style.setProperty("--note-line-height",String(f)),q||document.documentElement.style.setProperty("--note-card-width",`${m}px`),document.documentElement.style.setProperty("--image-thumb-size",`${y}px`);try{localStorage.setItem("prefs.checklistSpacing",String(o))}catch{}try{localStorage.setItem("prefs.checkboxSize",String(a))}catch{}try{localStorage.setItem("prefs.checklistTextSize",String(u))}catch{}try{localStorage.setItem("prefs.noteLineSpacing",String(f))}catch{}if(!q)try{localStorage.setItem("prefs.noteWidth",String(m))}catch{}try{localStorage.setItem("prefs.imageThumbSize",String(y))}catch{}try{localStorage.setItem("prefs.fontFamily",z)}catch{}try{localStorage.setItem("prefs.dragBehavior",W)}catch{}try{localStorage.setItem("prefs.animationSpeed",ce)}catch{}document.documentElement.style.setProperty("--app-font-family",z);try{window.dispatchEvent(new CustomEvent("notes-grid:recalc")),window.dispatchEvent(new Event("resize"))}catch{}try{const Ye={fontFamily:z,...q?{}:{noteWidth:m},dragBehavior:W,animationSpeed:ce,checklistSpacing:o,checkboxSize:a,checklistTextSize:u,noteLineSpacing:f,chipDisplayMode:Ae,imageThumbSize:y};await((oe=e==null?void 0:e.updateMe)==null?void 0:oe.call(e,Ye))}catch{}try{localStorage.removeItem("prefs.checkboxBg"),localStorage.removeItem("prefs.checkboxBorder")}catch{}t()}function xe(){N(!0);try{const oe=getComputedStyle(document.documentElement),Ye=oe.getPropertyValue("--card").trim()||"#1e1e1e",Ge=oe.getPropertyValue("--checkbox-border-default").trim()||"#ffffff";x(Ye),k(Ge)}catch{x("#1e1e1e"),k("#ffffff")}}function Me(){t()}const[Q,Je]=b.useState(!1),[_t,J]=b.useState(null),[at,$t]=b.useState(!1),[ct,nt]=b.useState(null);async function At(oe){var Ye;try{if(J(K=>{try{K&&URL.revokeObjectURL(K)}catch{}return oe?URL.createObjectURL(oe):null}),!oe)return;$t(!0);const Ge=await Vt(oe);await((Ye=e==null?void 0:e.uploadPhoto)==null?void 0:Ye.call(e,Ge)),J(K=>{try{K&&URL.revokeObjectURL(K)}catch{}return null})}catch(Ge){console.error("Failed to upload photo",Ge),window.alert("Failed to upload photo"),J(K=>{try{K&&URL.revokeObjectURL(K)}catch{}return null})}finally{$t(!1)}}function Vt(oe){return new Promise((Ye,Ge)=>{const K=new FileReader;K.onload=()=>Ye(String(K.result||"")),K.onerror=ge=>Ge(ge),K.readAsDataURL(oe)})}return B.useEffect(()=>()=>{try{_t&&URL.revokeObjectURL(_t)}catch{}},[_t]),h.jsxs("div",{className:"image-dialog-backdrop",children:[h.jsxs("div",{className:"prefs-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Preferences"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsx("div",{style:{padding:12},children:ct==null?h.jsxs("div",{children:[h.jsxs("div",{style:{display:"grid",gap:10},children:[h.jsx("button",{className:"btn",onClick:()=>nt("about"),children:"About"}),h.jsx("button",{className:"btn",onClick:()=>nt("appearance"),children:"Appearance"}),!1,h.jsx("button",{className:"btn",onClick:()=>nt("drag"),children:"Drag & Animation"}),h.jsx("button",{className:"btn",onClick:()=>nt("collaborators"),children:"Collaborators"})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:Me,children:"Close"}),h.jsx("span",{style:{flex:1}}),((wt=e==null?void 0:e.user)==null?void 0:wt.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="about"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"About Freeman Notes"}),h.jsxs("div",{className:"about-hero-group",children:[h.jsxs("div",{className:"about-hero","aria-label":"Freeman Notes branding",children:[h.jsx("img",{src:r==="light"?b_:w_,alt:"Freeman Notes icon",className:"about-hero-icon"}),h.jsx("img",{src:x_,alt:"",role:"presentation",className:"about-hero-wordmark",onError:oe=>{oe.currentTarget.style.display="none"}})]}),h.jsxs("div",{className:"about-version-row","aria-label":"Current version",children:[h.jsx("img",{src:r==="light"?S_:k_,alt:"Version badge",className:"about-version-icon"}),h.jsx("span",{className:"about-version-text",children:v_})]})]}),h.jsxs("div",{className:"about-description",children:[h.jsx("p",{children:"Freeman Notes exists to prevent small thoughts from becoming resonance cascades."}),h.jsx("p",{children:"It captures ideas before they scatter, organizes them without Combine interference, and keeps Civil Protection out of your creative process."}),h.jsx("p",{children:"No manhacks. No surveillance. Just free notes, recorded and remembered on your terms."})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:Me,children:"Close"}),h.jsx("span",{style:{flex:1}}),((ae=e==null?void 0:e.user)==null?void 0:ae.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="appearance"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Appearance"}),h.jsxs("div",{style:{marginBottom:16},children:[h.jsx("h5",{style:{margin:0,color:"var(--muted)"},children:"Theme"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Appearance"}),h.jsxs("select",{value:i,onChange:oe=>s(oe.target.value),children:[h.jsx("option",{value:"dark",children:"Dark"}),h.jsx("option",{value:"light",children:"Light"}),h.jsx("option",{value:"system",children:"System"})]})]})]}),h.jsxs("div",{style:{marginBottom:16},children:[h.jsx("h5",{style:{margin:0,color:"var(--muted)"},children:"Profile Photo"}),h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[_t?h.jsx("img",{src:_t,alt:"Profile preview",style:{width:55,height:55,borderRadius:"50%",objectFit:"cover"}}):(Ee=e==null?void 0:e.user)!=null&&Ee.userImageUrl?h.jsx("img",{src:(e==null?void 0:e.user).userImageUrl,alt:"Profile",style:{width:55,height:55,borderRadius:"50%",objectFit:"cover"}}):h.jsx("div",{className:"avatar",style:{width:55,height:55,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:(((Ke=e==null?void 0:e.user)==null?void 0:Ke.name)||((ze=e==null?void 0:e.user)==null?void 0:ze.email)||"U")[0]}),h.jsx("input",{type:"file",accept:"image/*",disabled:at,onChange:oe=>{var Ye;return At(((Ye=oe.target.files)==null?void 0:Ye[0])||null)}}),at&&h.jsx("div",{style:{color:"var(--muted)",fontSize:13},children:"Uploading…"})]})]}),h.jsxs("div",{style:{display:"block"},children:[h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checklist item spacing"}),h.jsx("input",{"aria-label":"checklist spacing",type:"range",min:2,max:24,value:o,onChange:oe=>l(Number(oe.target.value))}),h.jsxs("div",{style:{width:48,textAlign:"left"},children:[o,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Note line spacing"}),h.jsx("input",{"aria-label":"note line spacing",type:"range",min:.9,max:1.8,step:.02,value:f,onChange:oe=>p(Number(oe.target.value))}),h.jsx("div",{style:{width:48,textAlign:"left"},children:f.toFixed(2)})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checkbox size"}),h.jsx("input",{"aria-label":"checkbox size",type:"range",min:10,max:36,value:a,onChange:oe=>c(Number(oe.target.value))}),h.jsxs("div",{style:{width:48,textAlign:"left"},children:[a,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Text size"}),h.jsx("input",{"aria-label":"checklist text size",type:"range",min:12,max:20,value:u,onChange:oe=>d(Number(oe.target.value))}),h.jsxs("div",{style:{width:48,textAlign:"left"},children:[u,"px"]})]}),h.jsx("div",{style:{height:10}}),q?h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start",opacity:.7},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Note width"}),h.jsx("div",{style:{color:"var(--muted)"},children:"Auto (disabled on mobile)"})]}):h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Note width"}),h.jsx("input",{"aria-label":"note width",type:"range",min:180,max:520,value:m,onChange:oe=>g(Number(oe.target.value))}),h.jsxs("div",{style:{width:64,textAlign:"left"},children:[m,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Image thumbnails"}),h.jsx("input",{"aria-label":"image thumbnail size",type:"range",min:48,max:192,step:8,value:y,onChange:oe=>v(Number(oe.target.value))}),h.jsxs("div",{style:{width:64,textAlign:"left"},children:[y,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"App font"}),h.jsxs("select",{value:z,onChange:oe=>X(oe.target.value),children:[h.jsx("option",{value:'Inter, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial',children:"Inter"}),h.jsx("option",{value:"Calibri, system-ui, Arial, sans-serif",children:"Calibri"}),h.jsx("option",{value:"Segoe UI, system-ui, Arial, sans-serif",children:"Segoe UI"}),h.jsx("option",{value:"Roboto, system-ui, Arial, sans-serif",children:"Roboto"}),h.jsx("option",{value:"Helvetica Neue, Helvetica, Arial, sans-serif",children:"Helvetica Neue"}),h.jsx("option",{value:"Arial, Helvetica, sans-serif",children:"Arial"}),h.jsx("option",{value:"Verdana, Geneva, sans-serif",children:"Verdana"}),h.jsx("option",{value:"Tahoma, Geneva, sans-serif",children:"Tahoma"}),h.jsx("option",{value:"Trebuchet MS, Helvetica, sans-serif",children:"Trebuchet MS"}),h.jsx("option",{value:"Gill Sans, Calibri, sans-serif",children:"Gill Sans"})]})]})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((Pe=e==null?void 0:e.user)==null?void 0:Pe.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="colors"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Colors"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checkbox background"}),h.jsx("input",{"aria-label":"checkbox bg",type:"color",value:w,onChange:oe=>x(oe.target.value),style:{width:44,height:28,padding:0}})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checkbox border"}),h.jsx("input",{"aria-label":"checkbox border",type:"color",value:E,onChange:oe=>k(oe.target.value),style:{width:44,height:28,padding:0}})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:xe,title:"Reset colors to defaults",children:"Reset colors"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((it=e==null?void 0:e.user)==null?void 0:it.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="drag"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Drag & Animation"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Behavior"}),h.jsx("label",{style:{color:"var(--muted)"},children:"Swap"}),h.jsx("input",{"aria-label":"drag swap",type:"radio",name:"dragBehavior",checked:W==="swap",onChange:()=>te("swap")}),h.jsx("label",{style:{color:"var(--muted)"},children:"Rearrange"}),h.jsx("input",{"aria-label":"drag rearrange",type:"radio",name:"dragBehavior",checked:W==="rearrange",onChange:()=>te("rearrange")})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Speed"}),h.jsxs("select",{"aria-label":"animation speed",value:ce,onChange:oe=>ue(oe.target.value),children:[h.jsx("option",{value:"fast",children:"Fast"}),h.jsx("option",{value:"normal",children:"Normal"}),h.jsx("option",{value:"slow",children:"Slow"})]})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((ot=e==null?void 0:e.user)==null?void 0:ot.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Collaborators"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Display"}),h.jsxs("select",{"aria-label":"collaborator chip display",value:Ae,onChange:oe=>me(oe.target.value),children:[h.jsx("option",{value:"image+text",children:"Image + Text"}),h.jsx("option",{value:"image",children:"Image only"}),h.jsx("option",{value:"text",children:"Text only"})]})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((xt=e==null?void 0:e.user)==null?void 0:xt.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]})})]}),Q&&h.jsx(g_,{onClose:()=>Je(!1)})]})}function E_({onToggleSidebar:t,searchQuery:e,onSearchChange:n}){const[r,i]=b.useState(!1),{user:s}=Sr(),o=(()=>{try{return Sb()}catch{return{effective:"dark"}}})();return h.jsxs("header",{className:"app-header",children:[h.jsxs("div",{className:"header-left",children:[h.jsx("button",{className:"menu-btn","aria-label":"menu",onClick:()=>t&&t(),children:"☰"}),h.jsxs("div",{className:"brand-inline",children:[h.jsx("img",{src:o.effective==="light"?"/icons/lighticon.png":"/icons/darkicon.png",alt:"FreemanNotes icon",className:"app-icon"}),h.jsx("div",{className:"brand",children:"Freeman Notes"})]})]}),h.jsx("div",{className:"header-center",children:h.jsx("input",{className:"search",placeholder:"Search",value:e??"",onChange:l=>n&&n(l.target.value)})}),h.jsx("div",{className:"header-right",style:{position:"relative"},children:s?h.jsx(h.Fragment,{children:s.userImageUrl?h.jsx("img",{src:s.userImageUrl,alt:"User",className:"avatar",style:{width:33,height:33,borderRadius:"50%",objectFit:"cover",cursor:"pointer"},onClick:()=>i(!0)}):h.jsx("div",{className:"avatar",style:{width:33,height:33,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},onClick:()=>i(!0),children:s.name&&s.email?(s.name||s.email)[0]:""})}):null}),r&&h.jsx(C_,{onClose:()=>i(!1)})]})}const Ks={sortKey:"default",sortDir:"desc",smartFilter:"none",groupBy:"none"};function nS({selectedLabelIds:t=[],onToggleLabel:e,onClearLabels:n,collapsed:r=!1,onRequestClose:i,collectionStack:s=[],onCollectionStackChange:o,sortConfig:l=Ks,onSortConfigChange:a}){const{token:c}=Sr(),[u,d]=b.useState([]),[f,p]=b.useState(!1),[m,g]=b.useState(!1),[y,v]=b.useState(!1),[w,x]=b.useState(!1),[E,k]=b.useState(!1),[M,N]=b.useState([]),[z,X]=b.useState(!1),[L,H]=b.useState("");b.useEffect(()=>{if(!c){d([]);return}fetch("/api/labels",{headers:{Authorization:`Bearer ${c}`}}).then(Ee=>Ee.json()).then(Ee=>d(Array.isArray(Ee.labels)?Ee.labels:[])).catch(()=>d([]));const ae=()=>{fetch("/api/labels",{headers:{Authorization:`Bearer ${c}`}}).then(Ee=>Ee.json()).then(Ee=>d(Array.isArray(Ee.labels)?Ee.labels:[])).catch(()=>{})};return typeof window<"u"&&window.addEventListener("labels:refresh",ae),()=>{typeof window<"u"&&window.removeEventListener("labels:refresh",ae)}},[c]);const W=ae=>{try{const Ee={...l,...ae};a&&a(Ee)}catch{}},te=(ae,Ee)=>{if(l.sortKey!==ae){W({sortKey:ae,sortDir:Ee});return}W({sortDir:l.sortDir==="asc"?"desc":"asc"})},ce=ae=>{W({groupBy:l.groupBy===ae?"none":ae})},ue=ae=>{W({smartFilter:ae})},Ae=ae=>l.sortKey===ae,me={color:"var(--muted)",opacity:.7,cursor:"not-allowed"},q=()=>{try{a&&a(Ks)}catch{}try{g(!1)}catch{}try{v(!1)}catch{}try{x(!1)}catch{}try{n&&n()}catch{}try{o&&o([])}catch{}try{p(!1)}catch{}try{k(!1)}catch{}},se=()=>{q();try{i&&i()}catch{}},xe=()=>{p(ae=>{const Ee=!ae;if(!Ee){try{n&&n()}catch{}try{q()}catch{}}return Ee})},Me=()=>{g(ae=>{const Ee=!ae;if(!Ee)try{q()}catch{}return Ee})},Q=()=>{v(ae=>{const Ee=!ae;if(!Ee)try{ue("none")}catch{}return Ee})},Je=()=>{x(ae=>{const Ee=!ae;if(!Ee)try{W({groupBy:"none"})}catch{}return Ee})},_t=Array.isArray(s)&&s.length?Number(s[s.length-1].id):null,J=B.useCallback(async()=>{if(!c){N([]);return}if(!r&&E){X(!0);try{const ae=_t==null?"":`?parentId=${encodeURIComponent(String(_t))}`,Ke=await(await fetch(`/api/collections${ae}`,{headers:{Authorization:`Bearer ${c}`}})).json(),ze=Array.isArray(Ke==null?void 0:Ke.collections)?Ke.collections:[];N(ze.map(Pe=>({id:Number(Pe.id),name:String(Pe.name||""),parentId:Pe.parentId==null?null:Number(Pe.parentId),hasChildren:!!Pe.hasChildren,noteCount:typeof Pe.noteCount=="number"?Number(Pe.noteCount):void 0})).filter(Pe=>Number.isFinite(Pe.id)&&Pe.name.length))}catch{N([])}finally{X(!1)}}},[c,r,E,_t]);b.useEffect(()=>{J()},[J]);const at=()=>{k(ae=>{const Ee=!ae;if(!Ee)try{H("")}catch{}return Ee})},$t=(ae,Ee)=>{const Ke=[...Array.isArray(s)?s:[],{id:Number(ae),name:String(Ee||"")}];try{o&&o(Ke)}catch{}},ct=()=>{const ae=Array.isArray(s)?s:[];if(ae.length)try{o&&o(ae.slice(0,-1))}catch{}},nt=()=>{try{o&&o([])}catch{}},At=async()=>{const ae=String(L||"").trim();if(!(!ae||!c))try{const Ee=await fetch("/api/collections",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({name:ae,parentId:_t})});if(!Ee.ok)throw new Error(await Ee.text());try{H("")}catch{}await J()}catch(Ee){window.alert("Failed to create collection: "+String(Ee))}},Vt=async(ae,Ee)=>{if(!c)return;const Ke=window.prompt("Rename collection:",Ee);if(Ke==null)return;const ze=String(Ke).trim();if(ze)try{const Pe=await fetch(`/api/collections/${encodeURIComponent(String(ae))}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({name:ze})});if(!Pe.ok)throw new Error(await Pe.text());try{const it=Array.isArray(s)?s:[],ot=it.findIndex(xt=>Number(xt.id)===Number(ae));if(ot>=0){const xt=it.slice();xt[ot]={...xt[ot],name:ze},o&&o(xt)}}catch{}await J()}catch(Pe){window.alert("Failed to rename collection: "+String(Pe))}},wt=async(ae,Ee)=>{if(!(!c||!window.confirm(`Delete collection "${Ee}"? This will delete all nested collections.`)))try{const ze=await fetch(`/api/collections/${encodeURIComponent(String(ae))}`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`}});if(!ze.ok)throw new Error(await ze.text());try{const Pe=Array.isArray(s)?s:[],it=Pe.findIndex(ot=>Number(ot.id)===Number(ae));it>=0&&o&&o(Pe.slice(0,it))}catch{}await J()}catch(ze){window.alert("Failed to delete collection: "+String(ze))}};return h.jsx("aside",{className:"sidebar"+(r?" collapsed":""),children:h.jsxs("div",{className:"sidebar-section",children:[h.jsxs("div",{className:"sidebar-item active",title:"Notes",style:{cursor:"pointer"},onClick:se,children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M6 3h9l3 3v15H6zM14 3v4h4"})})}),!r&&h.jsx("span",{className:"text",children:"Notes"})]}),h.jsxs("div",{className:"sidebar-item",title:"Reminders",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),!r&&h.jsx("span",{className:"text",children:"Reminders"})]}),h.jsxs("div",{className:"sidebar-item",onClick:xe,style:{cursor:"pointer"},title:"Labels",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M6 3h12v18l-6-4-6 4V3z"})})}),!r&&h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(f?" open":""),children:"▶"})}),"Labels"]})]}),f&&!r&&h.jsxs("div",{style:{paddingLeft:8},children:[u.length===0&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)"},children:"No labels"}),u.map(ae=>h.jsxs("label",{className:"sidebar-item",style:{display:"flex",alignItems:"center",gap:8},children:[h.jsx("input",{type:"checkbox",checked:t.includes(ae.id),onChange:()=>e&&e(ae.id)}),h.jsx("span",{children:ae.name})]},ae.id)),u.length>0&&h.jsx("button",{className:"btn",onClick:n,style:{marginTop:6},children:"Clear"})]}),h.jsxs("div",{className:"sidebar-item",onClick:Me,style:{cursor:"pointer"},title:"Sorting",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M3 18h6v-2H3v2zm0-5h12v-2H3v2zm0-7v2h18V6H3z"})})}),!r&&h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(m?" open":""),children:"▶"})}),"Sorting"]})]}),m&&!r&&h.jsxs("div",{style:{paddingLeft:8},children:[h.jsxs("div",{className:"sidebar-item",style:{cursor:"pointer",display:"flex",justifyContent:"space-between",fontWeight:l.sortKey==="createdAt"?700:void 0},onClick:()=>te("createdAt","desc"),title:"Sort by date created",children:[h.jsx("span",{className:"text",children:"Date created"}),h.jsx("span",{className:"sidebar-indicator"+(Ae("createdAt")?"":" placeholder"),"aria-hidden":!0,children:h.jsx("span",{className:"dir"+(l.sortDir==="desc"&&Ae("createdAt")?" desc":""),children:"▲"})})]}),h.jsxs("div",{className:"sidebar-item",style:{cursor:"pointer",display:"flex",justifyContent:"space-between",fontWeight:l.sortKey==="updatedAt"?700:void 0},onClick:()=>te("updatedAt","desc"),title:"Sort by date updated",children:[h.jsx("span",{className:"text",children:"Date updated"}),h.jsx("span",{className:"sidebar-indicator"+(Ae("updatedAt")?"":" placeholder"),"aria-hidden":!0,children:h.jsx("span",{className:"dir"+(l.sortDir==="desc"&&Ae("updatedAt")?" desc":""),children:"▲"})})]}),h.jsxs("div",{className:"sidebar-item",style:{cursor:"pointer",display:"flex",justifyContent:"space-between",fontWeight:l.sortKey==="title"?700:void 0},onClick:()=>te("title","asc"),title:"Sort alphabetically by title",children:[h.jsx("span",{className:"text",children:"Alphabetical"}),h.jsx("span",{className:"sidebar-indicator"+(Ae("title")?"":" placeholder"),"aria-hidden":!0,children:h.jsx("span",{className:"dir"+(l.sortDir==="desc"&&Ae("title")?" desc":""),children:"▲"})})]}),h.jsx("div",{className:"sidebar-item",onClick:Q,style:{cursor:"pointer",marginTop:4},title:"Filters",children:h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(y?" open":""),children:"▶"})}),"Filters"]})}),y&&h.jsxs("div",{style:{paddingLeft:10},children:[h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"Due soon"})}),h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"Least accessed"})}),h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"Most edited"})}),h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"“At risk”"})}),h.jsx("div",{style:{display:"none"},children:h.jsx("button",{onClick:()=>ue("none"),children:"none"})})]}),h.jsx("div",{className:"sidebar-item",onClick:Je,style:{cursor:"pointer",marginTop:4},title:"Grouping",children:h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(w?" open":""),children:"▶"})}),"Grouping"]})}),w&&h.jsxs("div",{style:{paddingLeft:10},children:[h.jsx("div",{className:"sidebar-item",style:{cursor:"pointer",fontWeight:l.groupBy==="week"?700:void 0},onClick:()=>ce("week"),title:"Group by week",children:h.jsx("span",{className:"text",children:"By week"})}),h.jsx("div",{className:"sidebar-item",style:{cursor:"pointer",fontWeight:l.groupBy==="month"?700:void 0},onClick:()=>ce("month"),title:"Group by month",children:h.jsx("span",{className:"text",children:"By month"})})]})]}),h.jsxs("div",{className:"sidebar-item",title:"Collections",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M3 7h6l2 2h10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"})})}),!r&&h.jsxs("span",{className:"text",style:{cursor:"pointer"},onClick:at,children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(E?" open":""),children:"▶"})}),"Collections"]})]}),E&&!r&&h.jsxs("div",{style:{paddingLeft:8},children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:6},children:[h.jsx("div",{style:{display:"flex",gap:6,alignItems:"center"},children:s.length>0&&h.jsxs(h.Fragment,{children:[h.jsx("button",{className:"btn",onClick:ct,title:"Back",children:"Back"}),h.jsx("button",{className:"btn",onClick:nt,title:"All notes",children:"All"})]})}),s.length>0&&h.jsx("button",{className:"btn",title:"Delete this collection",onClick:()=>{const ae=s[s.length-1];wt(Number(ae.id),String(ae.name||""))},children:"Delete"})]}),s.length>0&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)",fontSize:12,paddingLeft:0},title:"Current path",children:s.map(ae=>String(ae.name||"")).join(" / ")}),h.jsx("div",{className:"sidebar-item"+(s.length?"":" active"),style:{cursor:"pointer"},onClick:()=>{nt()},title:"Show all notes",children:h.jsx("span",{className:"text",children:"All notes"})}),z&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)"},children:"Loading…"}),!z&&M.length===0&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)"},children:"No collections"}),M.map(ae=>h.jsxs("div",{className:"sidebar-item",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",flex:1,minWidth:0},onClick:()=>{$t(ae.id,ae.name)},title:ae.name,children:[h.jsx("span",{className:"text",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ae.name}),typeof ae.noteCount=="number"&&h.jsxs("span",{style:{color:"var(--muted)",fontSize:12},children:["(",ae.noteCount,")"]})]}),h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[h.jsx("button",{className:"btn",title:"Rename",onClick:Ee=>{Ee.stopPropagation(),Vt(ae.id,ae.name)},children:"Rename"}),h.jsx("button",{className:"btn",title:"Delete",onClick:Ee=>{Ee.stopPropagation(),wt(ae.id,ae.name)},children:"✕"})]})]},ae.id)),h.jsxs("div",{style:{display:"flex",gap:6,marginTop:6},children:[h.jsx("input",{value:L,onChange:ae=>H(ae.target.value),placeholder:"New collection",style:{flex:1,minWidth:0,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",background:"var(--panel)",color:"var(--text)"},onKeyDown:ae=>{ae.key==="Enter"&&At()}}),h.jsx("button",{className:"btn",onClick:At,disabled:!L.trim(),children:"Add"})]})]}),h.jsxs("div",{className:"sidebar-item",title:"Archive",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M20.54 5.23L19.4 4H4.6L3.46 5.23 3 6v2h18V6l-.46-.77zM6 10v9h12V10H6zm3 2h6v2H9v-2z"})})}),!r&&h.jsx("span",{className:"text",children:"Archive"})]}),h.jsxs("div",{className:"sidebar-item",title:"Bin",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M4 7h16"}),h.jsx("path",{d:"M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12"}),h.jsx("path",{d:"M9 7V5h6v2"})]})}),!r&&h.jsx("span",{className:"text",children:"Bin"})]})]})})}const Hm=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Dc(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function Cb(t){return"nodeType"in t}function qr(t){var e,n;return t?Dc(t)?t:Cb(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Eb(t){const{Document:e}=qr(t);return t instanceof e}function Vd(t){return Dc(t)?!1:t instanceof qr(t).HTMLElement}function UA(t){return t instanceof qr(t).SVGElement}function Oc(t){return t?Dc(t)?t.document:Cb(t)?Eb(t)?t:Vd(t)||UA(t)?t.ownerDocument:document:document:document}const lo=Hm?b.useLayoutEffect:b.useEffect;function Vm(t){const e=b.useRef(t);return lo(()=>{e.current=t}),b.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{t.current=setInterval(r,i)},[]),n=b.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function cd(t,e){e===void 0&&(e=[t]);const n=b.useRef(t);return lo(()=>{n.current!==t&&(n.current=t)},e),n}function Wd(t,e){const n=b.useRef();return b.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function ap(t){const e=Vm(t),n=b.useRef(null),r=b.useCallback(i=>{i!==n.current&&(e==null||e(i,n.current)),n.current=i},[]);return[n,r]}function cp(t){const e=b.useRef();return b.useEffect(()=>{e.current=t},[t]),e.current}let dy={};function Wm(t,e){return b.useMemo(()=>{if(e)return e;const n=dy[t]==null?0:dy[t]+1;return dy[t]=n,t+"-"+n},[t,e])}function HA(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const l=Object.entries(o);for(const[a,c]of l){const u=s[a];u!=null&&(s[a]=u+t*c)}return s},{...e})}}const Ya=HA(1),up=HA(-1);function T_(t){return"clientX"in t&&"clientY"in t}function Nb(t){if(!t)return!1;const{KeyboardEvent:e}=qr(t.target);return e&&t instanceof e}function A_(t){if(!t)return!1;const{TouchEvent:e}=qr(t.target);return e&&t instanceof e}function dp(t){if(A_(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return T_(t)?{x:t.clientX,y:t.clientY}:null}const ud=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[ud.Translate.toString(t),ud.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),rS="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function M_(t){return t.matches(rS)?t:t.querySelector(rS)}const I_={display:"none"};function R_(t){let{id:e,value:n}=t;return B.createElement("div",{id:e,style:I_},n)}function D_(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return B.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function O_(){const[t,e]=b.useState("");return{announce:b.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const VA=b.createContext(null);function j_(t){const e=b.useContext(VA);b.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(t)},[t,e])}function P_(){const[t]=b.useState(()=>new Set),e=b.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[b.useCallback(r=>{let{type:i,event:s}=r;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const L_={draggable:` +`+s.stack}return{value:t,source:e,stack:i,digest:null}}function ly(t,e,n){return{value:t,source:null,stack:n??null,digest:e??null}}function Jv(t,e){try{console.error(e.value)}catch(n){setTimeout(function(){throw n})}}var LL=typeof WeakMap=="function"?WeakMap:Map;function uA(t,e,n){n=Qs(-1,n),n.tag=3,n.payload={element:null};var r=e.value;return n.callback=function(){ip||(ip=!0,s0=r),Jv(t,e)},n}function dA(t,e,n){n=Qs(-1,n),n.tag=3;var r=t.type.getDerivedStateFromError;if(typeof r=="function"){var i=e.value;n.payload=function(){return r(i)},n.callback=function(){Jv(t,e)}}var s=t.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(n.callback=function(){Jv(t,e),typeof r!="function"&&(Jo===null?Jo=new Set([this]):Jo.add(this));var o=e.stack;this.componentDidCatch(e.value,{componentStack:o!==null?o:""})}),n}function Rk(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new LL;var i=new Set;r.set(e,i)}else i=r.get(e),i===void 0&&(i=new Set,r.set(e,i));i.has(n)||(i.add(n),t=GL.bind(null,t,e,n),e.then(t,t))}function Dk(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function Ok(t,e,n,r,i){return t.mode&1?(t.flags|=65536,t.lanes=i,t):(t===e?t.flags|=65536:(t.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(e=Qs(-1,1),e.tag=2,qo(n,e,1))),n.lanes|=1),t)}var _L=po.ReactCurrentOwner,Zr=!1;function _r(t,e,n,r){e.child=t===null?$T(e,null,n,r):lc(e,t.child,n,r)}function jk(t,e,n,r,i){n=n.render;var s=e.ref;return Wa(e,i),r=lb(t,e,n,r,s,i),n=ab(),t!==null&&!Zr?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~i,oo(t,e,i)):(Tn&&n&&Jw(e),e.flags|=1,_r(t,e,r,i),e.child)}function Pk(t,e,n,r,i){if(t===null){var s=n.type;return typeof s=="function"&&!vb(s)&&s.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(e.tag=15,e.type=s,fA(t,e,s,r,i)):(t=wh(n.type,null,r,e,e.mode,i),t.ref=e.ref,t.return=e,e.child=t)}if(s=t.child,!(t.lanes&i)){var o=s.memoizedProps;if(n=n.compare,n=n!==null?n:Zu,n(o,r)&&t.ref===e.ref)return oo(t,e,i)}return e.flags|=1,t=Xo(s,r),t.ref=e.ref,t.return=e,e.child=t}function fA(t,e,n,r,i){if(t!==null){var s=t.memoizedProps;if(Zu(s,r)&&t.ref===e.ref)if(Zr=!1,e.pendingProps=r=s,(t.lanes&i)!==0)t.flags&131072&&(Zr=!0);else return e.lanes=t.lanes,oo(t,e,i)}return Gv(t,e,n,r,i)}function hA(t,e,n){var r=e.pendingProps,i=r.children,s=t!==null?t.memoizedState:null;if(r.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},bn(za,ci),ci|=n;else{if(!(n&1073741824))return t=s!==null?s.baseLanes|n:n,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,bn(za,ci),ci|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=s!==null?s.baseLanes:n,bn(za,ci),ci|=r}else s!==null?(r=s.baseLanes|n,e.memoizedState=null):r=n,bn(za,ci),ci|=r;return _r(t,e,i,n),e.child}function pA(t,e){var n=e.ref;(t===null&&n!==null||t!==null&&t.ref!==n)&&(e.flags|=512,e.flags|=2097152)}function Gv(t,e,n,r,i){var s=ti(n)?Wl:Rr.current;return s=sc(e,s),Wa(e,i),n=lb(t,e,n,r,s,i),r=ab(),t!==null&&!Zr?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~i,oo(t,e,i)):(Tn&&r&&Jw(e),e.flags|=1,_r(t,e,n,i),e.child)}function Lk(t,e,n,r,i){if(ti(n)){var s=!0;qh(e)}else s=!1;if(Wa(e,i),e.stateNode===null)gh(t,e),cA(e,n,r),qv(e,n,r,i),r=!0;else if(t===null){var o=e.stateNode,l=e.memoizedProps;o.props=l;var a=o.context,c=n.contextType;typeof c=="object"&&c!==null?c=ji(c):(c=ti(n)?Wl:Rr.current,c=sc(e,c));var u=n.getDerivedStateFromProps,d=typeof u=="function"||typeof o.getSnapshotBeforeUpdate=="function";d||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(l!==r||a!==c)&&Ik(e,o,r,c),Ao=!1;var f=e.memoizedState;o.state=f,Zh(e,r,o,i),a=e.memoizedState,l!==r||f!==a||ei.current||Ao?(typeof u=="function"&&(Yv(e,n,u,r),a=e.memoizedState),(l=Ao||Mk(e,n,l,r,f,a,c))?(d||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(e.flags|=4194308)):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=a),o.props=r,o.state=a,o.context=c,r=l):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{o=e.stateNode,UT(t,e),l=e.memoizedProps,c=e.type===e.elementType?l:Wi(e.type,l),o.props=c,d=e.pendingProps,f=o.context,a=n.contextType,typeof a=="object"&&a!==null?a=ji(a):(a=ti(n)?Wl:Rr.current,a=sc(e,a));var p=n.getDerivedStateFromProps;(u=typeof p=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(l!==d||f!==a)&&Ik(e,o,r,a),Ao=!1,f=e.memoizedState,o.state=f,Zh(e,r,o,i);var m=e.memoizedState;l!==d||f!==m||ei.current||Ao?(typeof p=="function"&&(Yv(e,n,p,r),m=e.memoizedState),(c=Ao||Mk(e,n,c,r,f,m,a)||!1)?(u||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(r,m,a),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(r,m,a)),typeof o.componentDidUpdate=="function"&&(e.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof o.componentDidUpdate!="function"||l===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||l===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=m),o.props=r,o.state=m,o.context=a,r=c):(typeof o.componentDidUpdate!="function"||l===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||l===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),r=!1)}return Xv(t,e,n,r,s,i)}function Xv(t,e,n,r,i,s){pA(t,e);var o=(e.flags&128)!==0;if(!r&&!o)return i&&xk(e,n,!1),oo(t,e,s);r=e.stateNode,_L.current=e;var l=o&&typeof n.getDerivedStateFromError!="function"?null:r.render();return e.flags|=1,t!==null&&o?(e.child=lc(e,t.child,null,s),e.child=lc(e,null,l,s)):_r(t,e,l,s),e.memoizedState=r.state,i&&xk(e,n,!0),e.child}function mA(t){var e=t.stateNode;e.pendingContext?bk(t,e.pendingContext,e.pendingContext!==e.context):e.context&&bk(t,e.context,!1),rb(t,e.containerInfo)}function _k(t,e,n,r,i){return oc(),Xw(i),e.flags|=256,_r(t,e,n,r),e.child}var Qv={dehydrated:null,treeContext:null,retryLane:0};function Zv(t){return{baseLanes:t,cachePool:null,transitions:null}}function gA(t,e,n){var r=e.pendingProps,i=An.current,s=!1,o=(e.flags&128)!==0,l;if((l=o)||(l=t!==null&&t.memoizedState===null?!1:(i&2)!==0),l?(s=!0,e.flags&=-129):(t===null||t.memoizedState!==null)&&(i|=1),bn(An,i&1),t===null)return Wv(e),t=e.memoizedState,t!==null&&(t=t.dehydrated,t!==null)?(e.mode&1?t.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(o=r.children,t=r.fallback,s?(r=e.mode,s=e.child,o={mode:"hidden",children:o},!(r&1)&&s!==null?(s.childLanes=0,s.pendingProps=o):s=zm(o,r,0,null),t=_l(t,r,n,null),s.return=e,t.return=e,s.sibling=t,e.child=s,e.child.memoizedState=Zv(n),e.memoizedState=Qv,t):db(e,o));if(i=t.memoizedState,i!==null&&(l=i.dehydrated,l!==null))return zL(t,e,o,r,l,i,n);if(s){s=r.fallback,o=e.mode,i=t.child,l=i.sibling;var a={mode:"hidden",children:r.children};return!(o&1)&&e.child!==i?(r=e.child,r.childLanes=0,r.pendingProps=a,e.deletions=null):(r=Xo(i,a),r.subtreeFlags=i.subtreeFlags&14680064),l!==null?s=Xo(l,s):(s=_l(s,o,n,null),s.flags|=2),s.return=e,r.return=e,r.sibling=s,e.child=r,r=s,s=e.child,o=t.child.memoizedState,o=o===null?Zv(n):{baseLanes:o.baseLanes|n,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=t.childLanes&~n,e.memoizedState=Qv,r}return s=t.child,t=s.sibling,r=Xo(s,{mode:"visible",children:r.children}),!(e.mode&1)&&(r.lanes=n),r.return=e,r.sibling=null,t!==null&&(n=e.deletions,n===null?(e.deletions=[t],e.flags|=16):n.push(t)),e.child=r,e.memoizedState=null,r}function db(t,e){return e=zm({mode:"visible",children:e},t.mode,0,null),e.return=t,t.child=e}function jf(t,e,n,r){return r!==null&&Xw(r),lc(e,t.child,null,n),t=db(e,e.pendingProps.children),t.flags|=2,e.memoizedState=null,t}function zL(t,e,n,r,i,s,o){if(n)return e.flags&256?(e.flags&=-257,r=ly(Error(Te(422))),jf(t,e,o,r)):e.memoizedState!==null?(e.child=t.child,e.flags|=128,null):(s=r.fallback,i=e.mode,r=zm({mode:"visible",children:r.children},i,0,null),s=_l(s,i,o,null),s.flags|=2,r.return=e,s.return=e,r.sibling=s,e.child=r,e.mode&1&&lc(e,t.child,null,o),e.child.memoizedState=Zv(o),e.memoizedState=Qv,s);if(!(e.mode&1))return jf(t,e,o,null);if(i.data==="$!"){if(r=i.nextSibling&&i.nextSibling.dataset,r)var l=r.dgst;return r=l,s=Error(Te(419)),r=ly(s,r,void 0),jf(t,e,o,r)}if(l=(o&t.childLanes)!==0,Zr||l){if(r=ar,r!==null){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(r.suspendedLanes|o)?0:i,i!==0&&i!==s.retryLane&&(s.retryLane=i,so(t,i),Qi(r,t,i,-1))}return yb(),r=ly(Error(Te(421))),jf(t,e,o,r)}return i.data==="$?"?(e.flags|=128,e.child=t.child,e=XL.bind(null,t),i._reactRetry=e,null):(t=s.treeContext,di=Yo(i.nextSibling),fi=e,Tn=!0,Yi=null,t!==null&&(Ci[Ei++]=Ys,Ci[Ei++]=qs,Ci[Ei++]=Kl,Ys=t.id,qs=t.overflow,Kl=e),e=db(e,r.children),e.flags|=4096,e)}function zk(t,e,n){t.lanes|=e;var r=t.alternate;r!==null&&(r.lanes|=e),Kv(t.return,e,n)}function ay(t,e,n,r,i){var s=t.memoizedState;s===null?t.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(s.isBackwards=e,s.rendering=null,s.renderingStartTime=0,s.last=r,s.tail=n,s.tailMode=i)}function yA(t,e,n){var r=e.pendingProps,i=r.revealOrder,s=r.tail;if(_r(t,e,r.children,n),r=An.current,r&2)r=r&1|2,e.flags|=128;else{if(t!==null&&t.flags&128)e:for(t=e.child;t!==null;){if(t.tag===13)t.memoizedState!==null&&zk(t,n,e);else if(t.tag===19)zk(t,n,e);else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;t=t.return}t.sibling.return=t.return,t=t.sibling}r&=1}if(bn(An,r),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(n=e.child,i=null;n!==null;)t=n.alternate,t!==null&&ep(t)===null&&(i=n),n=n.sibling;n=i,n===null?(i=e.child,e.child=null):(i=n.sibling,n.sibling=null),ay(e,!1,i,n,s);break;case"backwards":for(n=null,i=e.child,e.child=null;i!==null;){if(t=i.alternate,t!==null&&ep(t)===null){e.child=i;break}t=i.sibling,i.sibling=n,n=i,i=t}ay(e,!0,n,null,s);break;case"together":ay(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function gh(t,e){!(e.mode&1)&&t!==null&&(t.alternate=null,e.alternate=null,e.flags|=2)}function oo(t,e,n){if(t!==null&&(e.dependencies=t.dependencies),ql|=e.lanes,!(n&e.childLanes))return null;if(t!==null&&e.child!==t.child)throw Error(Te(153));if(e.child!==null){for(t=e.child,n=Xo(t,t.pendingProps),e.child=n,n.return=e;t.sibling!==null;)t=t.sibling,n=n.sibling=Xo(t,t.pendingProps),n.return=e;n.sibling=null}return e.child}function FL(t,e,n){switch(e.tag){case 3:mA(e),oc();break;case 5:HT(e);break;case 1:ti(e.type)&&qh(e);break;case 4:rb(e,e.stateNode.containerInfo);break;case 10:var r=e.type._context,i=e.memoizedProps.value;bn(Xh,r._currentValue),r._currentValue=i;break;case 13:if(r=e.memoizedState,r!==null)return r.dehydrated!==null?(bn(An,An.current&1),e.flags|=128,null):n&e.child.childLanes?gA(t,e,n):(bn(An,An.current&1),t=oo(t,e,n),t!==null?t.sibling:null);bn(An,An.current&1);break;case 19:if(r=(n&e.childLanes)!==0,t.flags&128){if(r)return yA(t,e,n);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),bn(An,An.current),r)break;return null;case 22:case 23:return e.lanes=0,hA(t,e,n)}return oo(t,e,n)}var vA,e0,wA,bA;vA=function(t,e){for(var n=e.child;n!==null;){if(n.tag===5||n.tag===6)t.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};e0=function(){};wA=function(t,e,n,r){var i=t.memoizedProps;if(i!==r){t=e.stateNode,Il(Ss.current);var s=null;switch(n){case"input":i=kv(t,i),r=kv(t,r),s=[];break;case"select":i=Rn({},i,{value:void 0}),r=Rn({},r,{value:void 0}),s=[];break;case"textarea":i=Ev(t,i),r=Ev(t,r),s=[];break;default:typeof i.onClick!="function"&&typeof r.onClick=="function"&&(t.onclick=Kh)}Tv(n,r);var o;n=null;for(c in i)if(!r.hasOwnProperty(c)&&i.hasOwnProperty(c)&&i[c]!=null)if(c==="style"){var l=i[c];for(o in l)l.hasOwnProperty(o)&&(n||(n={}),n[o]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(Ku.hasOwnProperty(c)?s||(s=[]):(s=s||[]).push(c,null));for(c in r){var a=r[c];if(l=i!=null?i[c]:void 0,r.hasOwnProperty(c)&&a!==l&&(a!=null||l!=null))if(c==="style")if(l){for(o in l)!l.hasOwnProperty(o)||a&&a.hasOwnProperty(o)||(n||(n={}),n[o]="");for(o in a)a.hasOwnProperty(o)&&l[o]!==a[o]&&(n||(n={}),n[o]=a[o])}else n||(s||(s=[]),s.push(c,n)),n=a;else c==="dangerouslySetInnerHTML"?(a=a?a.__html:void 0,l=l?l.__html:void 0,a!=null&&l!==a&&(s=s||[]).push(c,a)):c==="children"?typeof a!="string"&&typeof a!="number"||(s=s||[]).push(c,""+a):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(Ku.hasOwnProperty(c)?(a!=null&&c==="onScroll"&&xn("scroll",t),s||l===a||(s=[])):(s=s||[]).push(c,a))}n&&(s=s||[]).push("style",n);var c=s;(e.updateQueue=c)&&(e.flags|=4)}};bA=function(t,e,n,r){n!==r&&(e.flags|=4)};function Qc(t,e){if(!Tn)switch(t.tailMode){case"hidden":e=t.tail;for(var n=null;e!==null;)e.alternate!==null&&(n=e),e=e.sibling;n===null?t.tail=null:n.sibling=null;break;case"collapsed":n=t.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?e||t.tail===null?t.tail=null:t.tail.sibling=null:r.sibling=null}}function Er(t){var e=t.alternate!==null&&t.alternate.child===t.child,n=0,r=0;if(e)for(var i=t.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=t,i=i.sibling;else for(i=t.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=t,i=i.sibling;return t.subtreeFlags|=r,t.childLanes=n,e}function $L(t,e,n){var r=e.pendingProps;switch(Gw(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Er(e),null;case 1:return ti(e.type)&&Yh(),Er(e),null;case 3:return r=e.stateNode,ac(),Sn(ei),Sn(Rr),sb(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(t===null||t.child===null)&&(Df(e)?e.flags|=4:t===null||t.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,Yi!==null&&(a0(Yi),Yi=null))),e0(t,e),Er(e),null;case 5:ib(e);var i=Il(id.current);if(n=e.type,t!==null&&e.stateNode!=null)wA(t,e,n,r,i),t.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!r){if(e.stateNode===null)throw Error(Te(166));return Er(e),null}if(t=Il(Ss.current),Df(e)){r=e.stateNode,n=e.type;var s=e.memoizedProps;switch(r[vs]=e,r[nd]=s,t=(e.mode&1)!==0,n){case"dialog":xn("cancel",r),xn("close",r);break;case"iframe":case"object":case"embed":xn("load",r);break;case"video":case"audio":for(i=0;i<\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=o.createElement(n,{is:r.is}):(t=o.createElement(n),n==="select"&&(o=t,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):t=o.createElementNS(t,n),t[vs]=e,t[nd]=r,vA(t,e,!1,!1),e.stateNode=t;e:{switch(o=Av(n,r),n){case"dialog":xn("cancel",t),xn("close",t),i=r;break;case"iframe":case"object":case"embed":xn("load",t),i=r;break;case"video":case"audio":for(i=0;iuc&&(e.flags|=128,r=!0,Qc(s,!1),e.lanes=4194304)}else{if(!r)if(t=ep(o),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Qc(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!Tn)return Er(e),null}else 2*_n()-s.renderingStartTime>uc&&n!==1073741824&&(e.flags|=128,r=!0,Qc(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(n=s.last,n!==null?n.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=_n(),e.sibling=null,n=An.current,bn(An,r?n&1|2:n&1),e):(Er(e),null);case 22:case 23:return gb(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?ci&1073741824&&(Er(e),e.subtreeFlags&6&&(e.flags|=8192)):Er(e),null;case 24:return null;case 25:return null}throw Error(Te(156,e.tag))}function BL(t,e){switch(Gw(e),e.tag){case 1:return ti(e.type)&&Yh(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return ac(),Sn(ei),Sn(Rr),sb(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return ib(e),null;case 13:if(Sn(An),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Te(340));oc()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Sn(An),null;case 4:return ac(),null;case 10:return eb(e.type._context),null;case 22:case 23:return gb(),null;case 24:return null;default:return null}}var Pf=!1,Ar=!1,UL=typeof WeakSet=="function"?WeakSet:Set,Qe=null;function _a(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){On(t,e,r)}else n.current=null}function t0(t,e,n){try{n()}catch(r){On(t,e,r)}}var Fk=!1;function HL(t,e){if(zv=Hh,t=ET(),qw(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,l=-1,a=-1,c=0,u=0,d=t,f=null;t:for(;;){for(var p;d!==n||i!==0&&d.nodeType!==3||(l=o+i),d!==s||r!==0&&d.nodeType!==3||(a=o+r),d.nodeType===3&&(o+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===t)break t;if(f===n&&++c===i&&(l=o),f===s&&++u===r&&(a=o),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=l===-1||a===-1?null:{start:l,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Fv={focusedElem:t,selectionRange:n},Hh=!1,Qe=e;Qe!==null;)if(e=Qe,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Qe=t;else for(;Qe!==null;){e=Qe;try{var m=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var g=m.memoizedProps,y=m.memoizedState,v=e.stateNode,w=v.getSnapshotBeforeUpdate(e.elementType===e.type?g:Wi(e.type,g),y);v.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var x=e.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Te(163))}}catch(E){On(e,e.return,E)}if(t=e.sibling,t!==null){t.return=e.return,Qe=t;break}Qe=e.return}return m=Fk,Fk=!1,m}function Cu(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&t)===t){var s=i.destroy;i.destroy=void 0,s!==void 0&&t0(e,n,s)}i=i.next}while(i!==r)}}function Lm(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function n0(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function xA(t){var e=t.alternate;e!==null&&(t.alternate=null,xA(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[vs],delete e[nd],delete e[Uv],delete e[EL],delete e[NL])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function kA(t){return t.tag===5||t.tag===3||t.tag===4}function $k(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||kA(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function r0(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Kh));else if(r!==4&&(t=t.child,t!==null))for(r0(t,e,n),t=t.sibling;t!==null;)r0(t,e,n),t=t.sibling}function i0(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(i0(t,e,n),t=t.sibling;t!==null;)i0(t,e,n),t=t.sibling}var pr=null,Ki=!1;function So(t,e,n){for(n=n.child;n!==null;)SA(t,e,n),n=n.sibling}function SA(t,e,n){if(ks&&typeof ks.onCommitFiberUnmount=="function")try{ks.onCommitFiberUnmount(Am,n)}catch{}switch(n.tag){case 5:Ar||_a(n,e);case 6:var r=pr,i=Ki;pr=null,So(t,e,n),pr=r,Ki=i,pr!==null&&(Ki?(t=pr,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):pr.removeChild(n.stateNode));break;case 18:pr!==null&&(Ki?(t=pr,n=n.stateNode,t.nodeType===8?ty(t.parentNode,n):t.nodeType===1&&ty(t,n),Xu(t)):ty(pr,n.stateNode));break;case 4:r=pr,i=Ki,pr=n.stateNode.containerInfo,Ki=!0,So(t,e,n),pr=r,Ki=i;break;case 0:case 11:case 14:case 15:if(!Ar&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&t0(n,e,o),i=i.next}while(i!==r)}So(t,e,n);break;case 1:if(!Ar&&(_a(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){On(n,e,l)}So(t,e,n);break;case 21:So(t,e,n);break;case 22:n.mode&1?(Ar=(r=Ar)||n.memoizedState!==null,So(t,e,n),Ar=r):So(t,e,n);break;default:So(t,e,n)}}function Bk(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new UL),e.forEach(function(r){var i=QL.bind(null,t,r);n.has(r)||(n.add(r),r.then(i,i))})}}function Hi(t,e){var n=e.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=_n()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*WL(r/1960))-r,10t?16:t,Fo===null)var r=!1;else{if(t=Fo,Fo=null,sp=0,en&6)throw Error(Te(331));var i=en;for(en|=4,Qe=t.current;Qe!==null;){var s=Qe,o=s.child;if(Qe.flags&16){var l=s.deletions;if(l!==null){for(var a=0;a_n()-pb?Ll(t,0):hb|=n),ni(t,e)}function RA(t,e){e===0&&(t.mode&1?(e=Nf,Nf<<=1,!(Nf&130023424)&&(Nf=4194304)):e=1);var n=$r();t=so(t,e),t!==null&&(Fd(t,e,n),ni(t,n))}function XL(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),RA(t,n)}function QL(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,i=t.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(Te(314))}r!==null&&r.delete(e),RA(t,n)}var DA;DA=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||ei.current)Zr=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return Zr=!1,FL(t,e,n);Zr=!!(t.flags&131072)}else Zr=!1,Tn&&e.flags&1048576&<(e,Gh,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;gh(t,e),t=e.pendingProps;var i=sc(e,Rr.current);Wa(e,n),i=lb(null,e,r,t,i,n);var s=ab();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,ti(r)?(s=!0,qh(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,nb(e),i.updater=Pm,e.stateNode=i,i._reactInternals=e,qv(e,r,t,n),e=Xv(null,e,r,!0,s,n)):(e.tag=0,Tn&&s&&Jw(e),_r(null,e,i,n),e=e.child),e;case 16:r=e.elementType;e:{switch(gh(t,e),t=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=e_(r),t=Wi(r,t),i){case 0:e=Gv(null,e,r,t,n);break e;case 1:e=Lk(null,e,r,t,n);break e;case 11:e=jk(null,e,r,t,n);break e;case 14:e=Pk(null,e,r,Wi(r.type,t),n);break e}throw Error(Te(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),Gv(t,e,r,i,n);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),Lk(t,e,r,i,n);case 3:e:{if(mA(e),t===null)throw Error(Te(387));r=e.pendingProps,s=e.memoizedState,i=s.element,UT(t,e),Zh(e,r,null,n);var o=e.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){i=cc(Error(Te(423)),e),e=_k(t,e,r,n,i);break e}else if(r!==i){i=cc(Error(Te(424)),e),e=_k(t,e,r,n,i);break e}else for(di=Yo(e.stateNode.containerInfo.firstChild),fi=e,Tn=!0,Yi=null,n=$T(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(oc(),r===i){e=oo(t,e,n);break e}_r(t,e,r,n)}e=e.child}return e;case 5:return HT(e),t===null&&Wv(e),r=e.type,i=e.pendingProps,s=t!==null?t.memoizedProps:null,o=i.children,$v(r,i)?o=null:s!==null&&$v(r,s)&&(e.flags|=32),pA(t,e),_r(t,e,o,n),e.child;case 6:return t===null&&Wv(e),null;case 13:return gA(t,e,n);case 4:return rb(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=lc(e,null,r,n):_r(t,e,r,n),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),jk(t,e,r,i,n);case 7:return _r(t,e,e.pendingProps,n),e.child;case 8:return _r(t,e,e.pendingProps.children,n),e.child;case 12:return _r(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,bn(Xh,r._currentValue),r._currentValue=o,s!==null)if(es(s.value,o)){if(s.children===i.children&&!ei.current){e=oo(t,e,n);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var l=s.dependencies;if(l!==null){o=s.child;for(var a=l.firstContext;a!==null;){if(a.context===r){if(s.tag===1){a=Qs(-1,n&-n),a.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?a.next=a:(a.next=u.next,u.next=a),c.pending=a}}s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),Kv(s.return,n,e),l.lanes|=n;break}a=a.next}}else if(s.tag===10)o=s.type===e.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(Te(341));o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Kv(o,n,e),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===e){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}_r(t,e,i.children,n),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,Wa(e,n),i=ji(i),r=r(i),e.flags|=1,_r(t,e,r,n),e.child;case 14:return r=e.type,i=Wi(r,e.pendingProps),i=Wi(r.type,i),Pk(t,e,r,i,n);case 15:return fA(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Wi(r,i),gh(t,e),e.tag=1,ti(r)?(t=!0,qh(e)):t=!1,Wa(e,n),cA(e,r,i),qv(e,r,i,n),Xv(null,e,r,!0,t,n);case 19:return yA(t,e,n);case 22:return hA(t,e,n)}throw Error(Te(156,e.tag))};function OA(t,e){return oT(t,e)}function ZL(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Mi(t,e,n,r){return new ZL(t,e,n,r)}function vb(t){return t=t.prototype,!(!t||!t.isReactComponent)}function e_(t){if(typeof t=="function")return vb(t)?1:0;if(t!=null){if(t=t.$$typeof,t===_w)return 11;if(t===zw)return 14}return 2}function Xo(t,e){var n=t.alternate;return n===null?(n=Mi(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function wh(t,e,n,r,i,s){var o=2;if(r=t,typeof t=="function")vb(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case Aa:return _l(n.children,i,s,e);case Lw:o=8,i|=8;break;case vv:return t=Mi(12,n,e,i|2),t.elementType=vv,t.lanes=s,t;case wv:return t=Mi(13,n,e,i),t.elementType=wv,t.lanes=s,t;case bv:return t=Mi(19,n,e,i),t.elementType=bv,t.lanes=s,t;case HN:return zm(n,i,s,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case BN:o=10;break e;case UN:o=9;break e;case _w:o=11;break e;case zw:o=14;break e;case To:o=16,r=null;break e}throw Error(Te(130,t==null?t:typeof t,""))}return e=Mi(o,n,e,i),e.elementType=t,e.type=r,e.lanes=s,e}function _l(t,e,n,r){return t=Mi(7,t,r,e),t.lanes=n,t}function zm(t,e,n,r){return t=Mi(22,t,r,e),t.elementType=HN,t.lanes=n,t.stateNode={isHidden:!1},t}function cy(t,e,n){return t=Mi(6,t,null,e),t.lanes=n,t}function uy(t,e,n){return e=Mi(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function t_(t,e,n,r,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vg(0),this.expirationTimes=Vg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vg(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function wb(t,e,n,r,i,s,o,l,a){return t=new t_(t,e,n,l,a),e===1?(e=1,s===!0&&(e|=8)):e=0,s=Mi(3,null,null,e),t.current=s,s.stateNode=t,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},nb(s),t}function n_(t,e,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(_A)}catch(t){console.error(t)}}_A(),_N.exports=mi;var zn=_N.exports;const l_=EN(zn);var zA,Jk=zn;zA=Jk.createRoot,Jk.hydrateRoot;const Gk="fn.deviceKey",Xk="fn.deviceName";function Qk(t){try{return localStorage.getItem(t)}catch{return null}}function Zk(t,e){try{localStorage.setItem(t,e)}catch{}}function a_(){try{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID()}catch{}return"dev_"+Math.random().toString(36).slice(2)+"_"+Date.now().toString(36)}function c_(){var t,e;try{const n=navigator.userAgentData,r=n&&typeof n.platform=="string"&&n.platform||navigator.platform||"device",s=!!(n&&typeof n.mobile=="boolean"?n.mobile:/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent||""))?"Mobile":"Desktop",o=typeof window<"u"?(t=window.screen)==null?void 0:t.width:0,l=typeof window<"u"?(e=window.screen)==null?void 0:e.height:0,a=o&&l?`${Math.max(o,l)}x${Math.min(o,l)}`:"";return[r,s,a].filter(Boolean).join(" ")}catch{return"Device"}}function FA(){let t=Qk(Gk)||"";t||(t=a_(),Zk(Gk,t));let e=Qk(Xk)||"";return e||(e=c_(),Zk(Xk,e)),{deviceKey:t,deviceName:e}}function Hd(){const t=FA();return{"x-device-key":t.deviceKey,"x-device-name":t.deviceName}}async function u_(t,e,n,r){const i={email:t,password:e};n&&(i.name=n),r&&(i.inviteToken=r);const s=await fetch("/api/auth/register",{method:"POST",headers:{"Content-Type":"application/json",...Hd()},body:JSON.stringify(i)});if(!s.ok)throw new Error(await s.text());return s.json()}async function d_(t,e){const n=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json",...Hd()},body:JSON.stringify({email:t,password:e})});if(!n.ok)throw new Error(await n.text());return n.json()}async function f_(t){const e=await fetch("/api/auth/me",{headers:{Authorization:`Bearer ${t}`,...Hd()}});if(!e.ok)throw new Error(await e.text());return e.json()}async function h_(t,e){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Hd()},body:JSON.stringify(e)});if(!n.ok)throw new Error(await n.text());return n.json()}async function p_(t,e){const n=await fetch("/api/auth/me/photo",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Hd()},body:JSON.stringify({dataUrl:e})});if(!n.ok)throw new Error(await n.text());return n.json()}const $A=b.createContext(void 0);function Sr(){const t=b.useContext($A);if(!t)throw new Error("useAuth must be used within AuthProvider");return t}const m_=({children:t})=>{const[e,n]=b.useState(null),[r,i]=b.useState(()=>localStorage.getItem("fn_token"));b.useEffect(()=>{r&&f_(r).then(u=>n(u.user)).catch(()=>{n(null),i(null),localStorage.removeItem("fn_token")})},[r]),b.useEffect(()=>{if(e)try{if(e.fontFamily&&(document.documentElement.style.setProperty("--app-font-family",e.fontFamily),localStorage.setItem("prefs.fontFamily",e.fontFamily)),typeof e.noteWidth=="number"){const u=e.noteWidth;document.documentElement.style.setProperty("--note-card-width",String(u)+"px"),localStorage.setItem("prefs.noteWidth",String(u));try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}}e.dragBehavior&&localStorage.setItem("prefs.dragBehavior",e.dragBehavior),e.animationSpeed&&localStorage.setItem("prefs.animationSpeed",e.animationSpeed),typeof e.checklistSpacing=="number"&&(document.documentElement.style.setProperty("--checklist-gap",String(e.checklistSpacing)+"px"),localStorage.setItem("prefs.checklistSpacing",String(e.checklistSpacing))),typeof e.checkboxSize=="number"&&(document.documentElement.style.setProperty("--checklist-checkbox-size",String(e.checkboxSize)+"px"),localStorage.setItem("prefs.checkboxSize",String(e.checkboxSize))),typeof e.checklistTextSize=="number"&&(document.documentElement.style.setProperty("--checklist-text-size",String(e.checklistTextSize)+"px"),localStorage.setItem("prefs.checklistTextSize",String(e.checklistTextSize))),typeof e.noteLineSpacing=="number"&&(document.documentElement.style.setProperty("--note-line-height",String(e.noteLineSpacing)),localStorage.setItem("prefs.noteLineSpacing",String(e.noteLineSpacing))),typeof e.imageThumbSize=="number"&&(document.documentElement.style.setProperty("--image-thumb-size",String(e.imageThumbSize)+"px"),localStorage.setItem("prefs.imageThumbSize",String(e.imageThumbSize))),e.checkboxBg&&(document.documentElement.style.setProperty("--checkbox-bg",e.checkboxBg),localStorage.setItem("prefs.checkboxBg",e.checkboxBg)),e.checkboxBorder&&(document.documentElement.style.setProperty("--checkbox-border",e.checkboxBorder),localStorage.setItem("prefs.checkboxBorder",e.checkboxBorder))}catch{}},[e]);async function s(u,d){const f=await d_(u,d),p=f.token;i(p),localStorage.setItem("fn_token",p),n(f.user)}async function o(u,d,f,p){const m=await u_(u,d,f,p),g=m.token;i(g),localStorage.setItem("fn_token",g),n(m.user)}async function l(u){const d=r||localStorage.getItem("fn_token");if(!d)throw new Error("Not authenticated");const f=await p_(d,u);f&&f.user&&n(f.user)}async function a(u){if(!r)throw new Error("Not authenticated");const d=await h_(r,u);d&&d.user?n(d.user):n(f=>f&&{...f,...u||{}})}function c(){i(null),n(null),localStorage.removeItem("fn_token")}return h.jsx($A.Provider,{value:{user:e,token:r,login:s,register:o,logout:c,uploadPhoto:l,updateMe:a},children:t})};function g_({onClose:t}){const{token:e}=Sr(),[n,r]=b.useState(""),[i,s]=b.useState("user"),[o,l]=b.useState(null),[a,c]=b.useState(!1);async function u(d){d&&d.preventDefault(),l(null),c(!0);try{const f=await fetch("/api/invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:e?`Bearer ${e}`:""},body:JSON.stringify({email:n,role:i})});if(!f.ok)throw new Error(await f.text());const p=await f.json();l(`Invite created for ${p.invite.email} (role: ${p.invite.role})`),r(""),s("user")}catch(f){l(`Error: ${(f==null?void 0:f.message)??String(f)}`)}finally{c(!1)}}return h.jsx("div",{className:"image-dialog-backdrop",children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Settings"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsxs("div",{style:{padding:8},children:[h.jsx("h4",{children:"Invites"}),h.jsxs("form",{onSubmit:u,style:{display:"flex",gap:8,alignItems:"center"},children:[h.jsx("input",{placeholder:"Email to invite",value:n,onChange:d=>r(d.target.value),className:"image-url-input"}),h.jsxs("select",{value:i,onChange:d=>s(d.target.value),className:"image-url-input","aria-label":"Role",children:[h.jsx("option",{value:"user",children:"User"}),h.jsx("option",{value:"admin",children:"Admin"})]}),h.jsx("button",{className:"btn",type:"submit",disabled:a||!n,children:"Send invite"})]}),o&&h.jsx("div",{style:{marginTop:8},children:o})]})]})})}const BA=b.createContext(null);function eS(){try{return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch{return"dark"}}function tS(t){try{document.documentElement.dataset.theme=t}catch{}}function y_({children:t}){const[e,n]=b.useState(()=>{try{return localStorage.getItem("prefs.theme")||"system"}catch{return"system"}}),r=b.useMemo(()=>e==="system"?eS():e,[e]);b.useEffect(()=>{tS(r);try{localStorage.setItem("prefs.theme",e)}catch{}if(e==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>tS(eS());try{s.addEventListener("change",o)}catch{}return()=>{try{s.removeEventListener("change",o)}catch{}}}},[e,r]);const i={choice:e,effective:r,setChoice:n};return h.jsx(BA.Provider,{value:i,children:t})}function Sb(){const t=b.useContext(BA);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const v_="0.4.6",w_="/icons/darkicon.png",b_="/icons/lighticon.png",x_="/icons/freemannotes.png",k_="/icons/version.png",S_="/icons/version-light.png";function C_({onClose:t}){var wt,ce,Ee,Ke,ze,Pe,it,ot,xt;const e=(()=>{try{return Sr()}catch{return null}})(),n=(()=>{try{return Sb()}catch{return null}})(),r=n&&n.effective||"dark",i=n&&n.choice||"system",s=n&&n.setChoice||(()=>{}),[o,l]=b.useState(()=>{try{const oe=localStorage.getItem("prefs.checklistSpacing");return oe?Number(oe):15}catch{return 15}}),[a,c]=b.useState(()=>{try{return Number(localStorage.getItem("prefs.checkboxSize")||"20")}catch{return 20}}),[u,d]=b.useState(()=>{try{return Number(localStorage.getItem("prefs.checklistTextSize")||"17")}catch{return 17}}),[f,p]=b.useState(()=>{var oe;try{const Ye=localStorage.getItem("prefs.noteLineSpacing");if(Ye)return Number(Ye);const Ge=e&&((oe=e.user)==null?void 0:oe.noteLineSpacing);return typeof Ge=="number"?Ge:1.38}catch{return 1.38}}),[m,g]=b.useState(()=>{try{const oe=localStorage.getItem("prefs.noteWidth");if(oe)return Number(oe);const Ye=getComputedStyle(document.documentElement);return Number(Ye.getPropertyValue("--note-card-width"))||300}catch{return 300}}),[y,v]=b.useState(()=>{var oe;try{const Ye=localStorage.getItem("prefs.imageThumbSize");if(Ye)return Number(Ye);const Ge=e&&((oe=e.user)==null?void 0:oe.imageThumbSize);if(typeof Ge=="number")return Ge;const Y=getComputedStyle(document.documentElement);return Number.parseInt(String(Y.getPropertyValue("--image-thumb-size")||"").trim(),10)||96}catch{return 96}}),[w,x]=b.useState(()=>{var oe;try{const Ye=e&&((oe=e.user)==null?void 0:oe.checkboxBg),Ge=localStorage.getItem("prefs.checkboxBg");return Ye||Ge||getComputedStyle(document.documentElement).getPropertyValue("--card").trim()||"#1e1e1e"}catch{return"#1e1e1e"}}),[E,k]=b.useState(()=>{var oe;try{const Ye=e&&((oe=e.user)==null?void 0:oe.checkboxBorder),Ge=localStorage.getItem("prefs.checkboxBorder");return Ye||Ge||getComputedStyle(document.documentElement).getPropertyValue("--checkbox-border-default").trim()||"#ffffff"}catch{return"#ffffff"}}),[M,N]=b.useState(!1),[z,X]=b.useState(()=>{try{return localStorage.getItem("prefs.fontFamily")||"Calibri, system-ui, Arial, sans-serif"}catch{return"Calibri, system-ui, Arial, sans-serif"}}),[L,H]=b.useState(()=>!1),[W,te]=b.useState(()=>{try{return localStorage.getItem("prefs.dragBehavior")||"swap"}catch{return"swap"}}),[ue,de]=b.useState(()=>{try{return localStorage.getItem("prefs.animationSpeed")||"normal"}catch{return"normal"}}),[Ae,me]=b.useState(()=>{var oe;try{return e&&((oe=e.user)==null?void 0:oe.chipDisplayMode)||"image+text"}catch{return"image+text"}}),q=(()=>{try{const oe=window.matchMedia,Ye=!!(oe&&(oe("(pointer: coarse)").matches||oe("(any-pointer: coarse)").matches)),Ge=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,Y=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight,ge=Math.min(Ge,Y);return Ye&&ge<=600}catch{return!1}})();b.useEffect(()=>{var Ye,Ge,Y,ge,De,Be;const oe=(()=>{try{return Number(localStorage.getItem("prefs.checklistSpacing")||"8")}catch{return 8}})();l(oe);try{const Le=localStorage.getItem("prefs.fontFamily");Le&&X(Le)}catch{}try{const Le=localStorage.getItem("prefs.noteLineSpacing")??((e&&((Ye=e.user)==null?void 0:Ye.noteLineSpacing))!=null?String(e.user.noteLineSpacing):null);Le&&p(Number(Le))}catch{}try{const Le=localStorage.getItem("prefs.noteWidth")??((e&&((Ge=e.user)==null?void 0:Ge.noteWidth))!=null?String(e.user.noteWidth):null);Le&&g(Number(Le))}catch{}try{const Le=localStorage.getItem("prefs.imageThumbSize")??((e&&((Y=e.user)==null?void 0:Y.imageThumbSize))!=null?String(e.user.imageThumbSize):null);Le&&v(Number(Le))}catch{}try{const Le=localStorage.getItem("prefs.dragBehavior")||e&&((ge=e.user)==null?void 0:ge.dragBehavior)||"swap";Le&&te(Le)}catch{}try{const Le=localStorage.getItem("prefs.animationSpeed")||e&&((De=e.user)==null?void 0:De.animationSpeed)||"normal";Le&&de(Le)}catch{}try{const Le=e&&((Be=e.user)==null?void 0:Be.chipDisplayMode)||"image+text";Le&&me(Le)}catch{}},[]);async function se(){var oe;document.documentElement.style.setProperty("--checklist-gap",`${o}px`),document.documentElement.style.setProperty("--checklist-checkbox-size",`${a}px`),document.documentElement.style.setProperty("--checklist-text-size",`${u}px`),document.documentElement.style.setProperty("--note-line-height",String(f)),q||document.documentElement.style.setProperty("--note-card-width",`${m}px`),document.documentElement.style.setProperty("--image-thumb-size",`${y}px`);try{localStorage.setItem("prefs.checklistSpacing",String(o))}catch{}try{localStorage.setItem("prefs.checkboxSize",String(a))}catch{}try{localStorage.setItem("prefs.checklistTextSize",String(u))}catch{}try{localStorage.setItem("prefs.noteLineSpacing",String(f))}catch{}if(!q)try{localStorage.setItem("prefs.noteWidth",String(m))}catch{}try{localStorage.setItem("prefs.imageThumbSize",String(y))}catch{}try{localStorage.setItem("prefs.fontFamily",z)}catch{}try{localStorage.setItem("prefs.dragBehavior",W)}catch{}try{localStorage.setItem("prefs.animationSpeed",ue)}catch{}document.documentElement.style.setProperty("--app-font-family",z);try{window.dispatchEvent(new CustomEvent("notes-grid:recalc")),window.dispatchEvent(new Event("resize"))}catch{}try{const Ye={fontFamily:z,...q?{}:{noteWidth:m},dragBehavior:W,animationSpeed:ue,checklistSpacing:o,checkboxSize:a,checklistTextSize:u,noteLineSpacing:f,chipDisplayMode:Ae,imageThumbSize:y};await((oe=e==null?void 0:e.updateMe)==null?void 0:oe.call(e,Ye))}catch{}try{localStorage.removeItem("prefs.checkboxBg"),localStorage.removeItem("prefs.checkboxBorder")}catch{}t()}function xe(){N(!0);try{const oe=getComputedStyle(document.documentElement),Ye=oe.getPropertyValue("--card").trim()||"#1e1e1e",Ge=oe.getPropertyValue("--checkbox-border-default").trim()||"#ffffff";x(Ye),k(Ge)}catch{x("#1e1e1e"),k("#ffffff")}}function Me(){t()}const[Q,Je]=b.useState(!1),[_t,J]=b.useState(null),[at,$t]=b.useState(!1),[ct,nt]=b.useState(null);async function At(oe){var Ye;try{if(J(Y=>{try{Y&&URL.revokeObjectURL(Y)}catch{}return oe?URL.createObjectURL(oe):null}),!oe)return;$t(!0);const Ge=await Bt(oe);await((Ye=e==null?void 0:e.uploadPhoto)==null?void 0:Ye.call(e,Ge)),J(Y=>{try{Y&&URL.revokeObjectURL(Y)}catch{}return null})}catch(Ge){console.error("Failed to upload photo",Ge),window.alert("Failed to upload photo"),J(Y=>{try{Y&&URL.revokeObjectURL(Y)}catch{}return null})}finally{$t(!1)}}function Bt(oe){return new Promise((Ye,Ge)=>{const Y=new FileReader;Y.onload=()=>Ye(String(Y.result||"")),Y.onerror=ge=>Ge(ge),Y.readAsDataURL(oe)})}return B.useEffect(()=>()=>{try{_t&&URL.revokeObjectURL(_t)}catch{}},[_t]),h.jsxs("div",{className:"image-dialog-backdrop",children:[h.jsxs("div",{className:"prefs-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Preferences"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsx("div",{style:{padding:12},children:ct==null?h.jsxs("div",{children:[h.jsxs("div",{style:{display:"grid",gap:10},children:[h.jsx("button",{className:"btn",onClick:()=>nt("about"),children:"About"}),h.jsx("button",{className:"btn",onClick:()=>nt("appearance"),children:"Appearance"}),!1,h.jsx("button",{className:"btn",onClick:()=>nt("drag"),children:"Drag & Animation"}),h.jsx("button",{className:"btn",onClick:()=>nt("collaborators"),children:"Collaborators"})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:Me,children:"Close"}),h.jsx("span",{style:{flex:1}}),((wt=e==null?void 0:e.user)==null?void 0:wt.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="about"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"About Freeman Notes"}),h.jsxs("div",{className:"about-hero-group",children:[h.jsxs("div",{className:"about-hero","aria-label":"Freeman Notes branding",children:[h.jsx("img",{src:r==="light"?b_:w_,alt:"Freeman Notes icon",className:"about-hero-icon"}),h.jsx("img",{src:x_,alt:"",role:"presentation",className:"about-hero-wordmark",onError:oe=>{oe.currentTarget.style.display="none"}})]}),h.jsxs("div",{className:"about-version-row","aria-label":"Current version",children:[h.jsx("img",{src:r==="light"?S_:k_,alt:"Version badge",className:"about-version-icon"}),h.jsx("span",{className:"about-version-text",children:v_})]})]}),h.jsxs("div",{className:"about-description",children:[h.jsx("p",{children:"Freeman Notes exists to prevent small thoughts from becoming resonance cascades."}),h.jsx("p",{children:"It captures ideas before they scatter, organizes them without Combine interference, and keeps Civil Protection out of your creative process."}),h.jsx("p",{children:"No manhacks. No surveillance. Just free notes, recorded and remembered on your terms."})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:Me,children:"Close"}),h.jsx("span",{style:{flex:1}}),((ce=e==null?void 0:e.user)==null?void 0:ce.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="appearance"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Appearance"}),h.jsxs("div",{style:{marginBottom:16},children:[h.jsx("h5",{style:{margin:0,color:"var(--muted)"},children:"Theme"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Appearance"}),h.jsxs("select",{value:i,onChange:oe=>s(oe.target.value),children:[h.jsx("option",{value:"dark",children:"Dark"}),h.jsx("option",{value:"light",children:"Light"}),h.jsx("option",{value:"system",children:"System"})]})]})]}),h.jsxs("div",{style:{marginBottom:16},children:[h.jsx("h5",{style:{margin:0,color:"var(--muted)"},children:"Profile Photo"}),h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[_t?h.jsx("img",{src:_t,alt:"Profile preview",style:{width:55,height:55,borderRadius:"50%",objectFit:"cover"}}):(Ee=e==null?void 0:e.user)!=null&&Ee.userImageUrl?h.jsx("img",{src:(e==null?void 0:e.user).userImageUrl,alt:"Profile",style:{width:55,height:55,borderRadius:"50%",objectFit:"cover"}}):h.jsx("div",{className:"avatar",style:{width:55,height:55,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:(((Ke=e==null?void 0:e.user)==null?void 0:Ke.name)||((ze=e==null?void 0:e.user)==null?void 0:ze.email)||"U")[0]}),h.jsx("input",{type:"file",accept:"image/*",disabled:at,onChange:oe=>{var Ye;return At(((Ye=oe.target.files)==null?void 0:Ye[0])||null)}}),at&&h.jsx("div",{style:{color:"var(--muted)",fontSize:13},children:"Uploading…"})]})]}),h.jsxs("div",{style:{display:"block"},children:[h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checklist item spacing"}),h.jsx("input",{"aria-label":"checklist spacing",type:"range",min:2,max:24,value:o,onChange:oe=>l(Number(oe.target.value))}),h.jsxs("div",{style:{width:48,textAlign:"left"},children:[o,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Note line spacing"}),h.jsx("input",{"aria-label":"note line spacing",type:"range",min:.9,max:1.8,step:.02,value:f,onChange:oe=>p(Number(oe.target.value))}),h.jsx("div",{style:{width:48,textAlign:"left"},children:f.toFixed(2)})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checkbox size"}),h.jsx("input",{"aria-label":"checkbox size",type:"range",min:10,max:36,value:a,onChange:oe=>c(Number(oe.target.value))}),h.jsxs("div",{style:{width:48,textAlign:"left"},children:[a,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Text size"}),h.jsx("input",{"aria-label":"checklist text size",type:"range",min:12,max:20,value:u,onChange:oe=>d(Number(oe.target.value))}),h.jsxs("div",{style:{width:48,textAlign:"left"},children:[u,"px"]})]}),h.jsx("div",{style:{height:10}}),q?h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start",opacity:.7},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Note width"}),h.jsx("div",{style:{color:"var(--muted)"},children:"Auto (disabled on mobile)"})]}):h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Note width"}),h.jsx("input",{"aria-label":"note width",type:"range",min:180,max:520,value:m,onChange:oe=>g(Number(oe.target.value))}),h.jsxs("div",{style:{width:64,textAlign:"left"},children:[m,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Image thumbnails"}),h.jsx("input",{"aria-label":"image thumbnail size",type:"range",min:48,max:192,step:8,value:y,onChange:oe=>v(Number(oe.target.value))}),h.jsxs("div",{style:{width:64,textAlign:"left"},children:[y,"px"]})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"App font"}),h.jsxs("select",{value:z,onChange:oe=>X(oe.target.value),children:[h.jsx("option",{value:'Inter, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial',children:"Inter"}),h.jsx("option",{value:"Calibri, system-ui, Arial, sans-serif",children:"Calibri"}),h.jsx("option",{value:"Segoe UI, system-ui, Arial, sans-serif",children:"Segoe UI"}),h.jsx("option",{value:"Roboto, system-ui, Arial, sans-serif",children:"Roboto"}),h.jsx("option",{value:"Helvetica Neue, Helvetica, Arial, sans-serif",children:"Helvetica Neue"}),h.jsx("option",{value:"Arial, Helvetica, sans-serif",children:"Arial"}),h.jsx("option",{value:"Verdana, Geneva, sans-serif",children:"Verdana"}),h.jsx("option",{value:"Tahoma, Geneva, sans-serif",children:"Tahoma"}),h.jsx("option",{value:"Trebuchet MS, Helvetica, sans-serif",children:"Trebuchet MS"}),h.jsx("option",{value:"Gill Sans, Calibri, sans-serif",children:"Gill Sans"})]})]})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((Pe=e==null?void 0:e.user)==null?void 0:Pe.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="colors"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Colors"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checkbox background"}),h.jsx("input",{"aria-label":"checkbox bg",type:"color",value:w,onChange:oe=>x(oe.target.value),style:{width:44,height:28,padding:0}})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Checkbox border"}),h.jsx("input",{"aria-label":"checkbox border",type:"color",value:E,onChange:oe=>k(oe.target.value),style:{width:44,height:28,padding:0}})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:xe,title:"Reset colors to defaults",children:"Reset colors"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((it=e==null?void 0:e.user)==null?void 0:it.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):ct==="drag"?h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Drag & Animation"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Behavior"}),h.jsx("label",{style:{color:"var(--muted)"},children:"Swap"}),h.jsx("input",{"aria-label":"drag swap",type:"radio",name:"dragBehavior",checked:W==="swap",onChange:()=>te("swap")}),h.jsx("label",{style:{color:"var(--muted)"},children:"Rearrange"}),h.jsx("input",{"aria-label":"drag rearrange",type:"radio",name:"dragBehavior",checked:W==="rearrange",onChange:()=>te("rearrange")})]}),h.jsx("div",{style:{height:10}}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Speed"}),h.jsxs("select",{"aria-label":"animation speed",value:ue,onChange:oe=>de(oe.target.value),children:[h.jsx("option",{value:"fast",children:"Fast"}),h.jsx("option",{value:"normal",children:"Normal"}),h.jsx("option",{value:"slow",children:"Slow"})]})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((ot=e==null?void 0:e.user)==null?void 0:ot.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]}):h.jsxs("div",{children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),"aria-label":"Back",children:"← Back"}),h.jsx("div",{style:{height:8}}),h.jsx("h4",{children:"Collaborators"}),h.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",justifyContent:"flex-start"},children:[h.jsx("label",{style:{color:"var(--muted)",minWidth:120},children:"Display"}),h.jsxs("select",{"aria-label":"collaborator chip display",value:Ae,onChange:oe=>me(oe.target.value),children:[h.jsx("option",{value:"image+text",children:"Image + Text"}),h.jsx("option",{value:"image",children:"Image only"}),h.jsx("option",{value:"text",children:"Text only"})]})]}),h.jsxs("div",{style:{marginTop:16,display:"flex",gap:8,justifyContent:"flex-start"},children:[h.jsx("button",{className:"btn",onClick:()=>nt(null),children:"Back"}),h.jsx("button",{className:"btn",onClick:se,children:"Save"}),h.jsx("span",{style:{flex:1}}),((xt=e==null?void 0:e.user)==null?void 0:xt.role)==="admin"&&h.jsx("button",{className:"btn",onClick:()=>Je(!0),children:"Send Invite"}),h.jsx("button",{className:"btn",onClick:()=>{var oe;try{t()}catch{}try{(oe=e==null?void 0:e.logout)==null||oe.call(e)}catch{}},children:"Sign out"})]})]})})]}),Q&&h.jsx(g_,{onClose:()=>Je(!1)})]})}function E_({onToggleSidebar:t,searchQuery:e,onSearchChange:n}){const[r,i]=b.useState(!1),{user:s}=Sr(),o=(()=>{try{return Sb()}catch{return{effective:"dark"}}})();return h.jsxs("header",{className:"app-header",children:[h.jsxs("div",{className:"header-left",children:[h.jsx("button",{className:"menu-btn","aria-label":"menu",onClick:()=>t&&t(),children:"☰"}),h.jsxs("div",{className:"brand-inline",children:[h.jsx("img",{src:o.effective==="light"?"/icons/lighticon.png":"/icons/darkicon.png",alt:"FreemanNotes icon",className:"app-icon"}),h.jsx("div",{className:"brand",children:"Freeman Notes"})]})]}),h.jsx("div",{className:"header-center",children:h.jsx("input",{className:"search",placeholder:"Search",value:e??"",onChange:l=>n&&n(l.target.value)})}),h.jsx("div",{className:"header-right",style:{position:"relative"},children:s?h.jsx(h.Fragment,{children:s.userImageUrl?h.jsx("img",{src:s.userImageUrl,alt:"User",className:"avatar",style:{width:33,height:33,borderRadius:"50%",objectFit:"cover",cursor:"pointer"},onClick:()=>i(!0)}):h.jsx("div",{className:"avatar",style:{width:33,height:33,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},onClick:()=>i(!0),children:s.name&&s.email?(s.name||s.email)[0]:""})}):null}),r&&h.jsx(C_,{onClose:()=>i(!1)})]})}const Ks={sortKey:"default",sortDir:"desc",smartFilter:"none",groupBy:"none"};function nS({selectedLabelIds:t=[],onToggleLabel:e,onClearLabels:n,collapsed:r=!1,onRequestClose:i,collectionStack:s=[],onCollectionStackChange:o,sortConfig:l=Ks,onSortConfigChange:a}){const{token:c}=Sr(),[u,d]=b.useState([]),[f,p]=b.useState(!1),[m,g]=b.useState(!1),[y,v]=b.useState(!1),[w,x]=b.useState(!1),[E,k]=b.useState(!1),[M,N]=b.useState([]),[z,X]=b.useState(!1),[L,H]=b.useState("");b.useEffect(()=>{if(!c){d([]);return}fetch("/api/labels",{headers:{Authorization:`Bearer ${c}`}}).then(Ee=>Ee.json()).then(Ee=>d(Array.isArray(Ee.labels)?Ee.labels:[])).catch(()=>d([]));const ce=()=>{fetch("/api/labels",{headers:{Authorization:`Bearer ${c}`}}).then(Ee=>Ee.json()).then(Ee=>d(Array.isArray(Ee.labels)?Ee.labels:[])).catch(()=>{})};return typeof window<"u"&&window.addEventListener("labels:refresh",ce),()=>{typeof window<"u"&&window.removeEventListener("labels:refresh",ce)}},[c]);const W=ce=>{try{const Ee={...l,...ce};a&&a(Ee)}catch{}},te=(ce,Ee)=>{if(l.sortKey!==ce){W({sortKey:ce,sortDir:Ee});return}W({sortDir:l.sortDir==="asc"?"desc":"asc"})},ue=ce=>{W({groupBy:l.groupBy===ce?"none":ce})},de=ce=>{W({smartFilter:ce})},Ae=ce=>l.sortKey===ce,me={color:"var(--muted)",opacity:.7,cursor:"not-allowed"},q=()=>{try{a&&a(Ks)}catch{}try{g(!1)}catch{}try{v(!1)}catch{}try{x(!1)}catch{}try{n&&n()}catch{}try{o&&o([])}catch{}try{p(!1)}catch{}try{k(!1)}catch{}},se=()=>{q();try{i&&i()}catch{}},xe=()=>{p(ce=>{const Ee=!ce;if(!Ee){try{n&&n()}catch{}try{q()}catch{}}return Ee})},Me=()=>{g(ce=>{const Ee=!ce;if(!Ee)try{q()}catch{}return Ee})},Q=()=>{v(ce=>{const Ee=!ce;if(!Ee)try{de("none")}catch{}return Ee})},Je=()=>{x(ce=>{const Ee=!ce;if(!Ee)try{W({groupBy:"none"})}catch{}return Ee})},_t=Array.isArray(s)&&s.length?Number(s[s.length-1].id):null,J=B.useCallback(async()=>{if(!c){N([]);return}if(!r&&E){X(!0);try{const ce=_t==null?"":`?parentId=${encodeURIComponent(String(_t))}`,Ke=await(await fetch(`/api/collections${ce}`,{headers:{Authorization:`Bearer ${c}`}})).json(),ze=Array.isArray(Ke==null?void 0:Ke.collections)?Ke.collections:[];N(ze.map(Pe=>({id:Number(Pe.id),name:String(Pe.name||""),parentId:Pe.parentId==null?null:Number(Pe.parentId),hasChildren:!!Pe.hasChildren,noteCount:typeof Pe.noteCount=="number"?Number(Pe.noteCount):void 0})).filter(Pe=>Number.isFinite(Pe.id)&&Pe.name.length))}catch{N([])}finally{X(!1)}}},[c,r,E,_t]);b.useEffect(()=>{J()},[J]);const at=()=>{k(ce=>{const Ee=!ce;if(!Ee)try{H("")}catch{}return Ee})},$t=(ce,Ee)=>{const Ke=[...Array.isArray(s)?s:[],{id:Number(ce),name:String(Ee||"")}];try{o&&o(Ke)}catch{}},ct=()=>{const ce=Array.isArray(s)?s:[];if(ce.length)try{o&&o(ce.slice(0,-1))}catch{}},nt=()=>{try{o&&o([])}catch{}},At=async()=>{const ce=String(L||"").trim();if(!(!ce||!c))try{const Ee=await fetch("/api/collections",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({name:ce,parentId:_t})});if(!Ee.ok)throw new Error(await Ee.text());try{H("")}catch{}try{window.dispatchEvent(new CustomEvent("collections:changed",{detail:{invalidateAll:!0,reason:"create"}}))}catch{}await J()}catch(Ee){window.alert("Failed to create collection: "+String(Ee))}},Bt=async(ce,Ee)=>{if(!c)return;const Ke=window.prompt("Rename collection:",Ee);if(Ke==null)return;const ze=String(Ke).trim();if(ze)try{const Pe=await fetch(`/api/collections/${encodeURIComponent(String(ce))}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({name:ze})});if(!Pe.ok)throw new Error(await Pe.text());try{window.dispatchEvent(new CustomEvent("collections:changed",{detail:{invalidateAll:!0,reason:"rename",id:Number(ce)}}))}catch{}try{const it=Array.isArray(s)?s:[],ot=it.findIndex(xt=>Number(xt.id)===Number(ce));if(ot>=0){const xt=it.slice();xt[ot]={...xt[ot],name:ze},o&&o(xt)}}catch{}await J()}catch(Pe){window.alert("Failed to rename collection: "+String(Pe))}},wt=async(ce,Ee)=>{if(!(!c||!window.confirm(`Delete collection "${Ee}"? This will delete all nested collections.`)))try{const ze=await fetch(`/api/collections/${encodeURIComponent(String(ce))}`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`}});if(!ze.ok)throw new Error(await ze.text());try{window.dispatchEvent(new CustomEvent("collections:changed",{detail:{invalidateAll:!0,reason:"delete",id:Number(ce)}}))}catch{}try{const Pe=Array.isArray(s)?s:[],it=Pe.findIndex(ot=>Number(ot.id)===Number(ce));it>=0&&o&&o(Pe.slice(0,it))}catch{}await J()}catch(ze){window.alert("Failed to delete collection: "+String(ze))}};return h.jsx("aside",{className:"sidebar"+(r?" collapsed":""),children:h.jsxs("div",{className:"sidebar-section",children:[h.jsxs("div",{className:"sidebar-item active",title:"Notes",style:{cursor:"pointer"},onClick:se,children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M6 3h9l3 3v15H6zM14 3v4h4"})})}),!r&&h.jsx("span",{className:"text",children:"Notes"})]}),h.jsxs("div",{className:"sidebar-item",title:"Reminders",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),!r&&h.jsx("span",{className:"text",children:"Reminders"})]}),h.jsxs("div",{className:"sidebar-item",onClick:xe,style:{cursor:"pointer"},title:"Labels",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M6 3h12v18l-6-4-6 4V3z"})})}),!r&&h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(f?" open":""),children:"▶"})}),"Labels"]})]}),f&&!r&&h.jsxs("div",{style:{paddingLeft:8},children:[u.length===0&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)"},children:"No labels"}),u.map(ce=>h.jsxs("label",{className:"sidebar-item",style:{display:"flex",alignItems:"center",gap:8},children:[h.jsx("input",{type:"checkbox",checked:t.includes(ce.id),onChange:()=>e&&e(ce.id)}),h.jsx("span",{children:ce.name})]},ce.id)),u.length>0&&h.jsx("button",{className:"btn",onClick:n,style:{marginTop:6},children:"Clear"})]}),h.jsxs("div",{className:"sidebar-item",onClick:Me,style:{cursor:"pointer"},title:"Sorting",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M3 18h6v-2H3v2zm0-5h12v-2H3v2zm0-7v2h18V6H3z"})})}),!r&&h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(m?" open":""),children:"▶"})}),"Sorting"]})]}),m&&!r&&h.jsxs("div",{style:{paddingLeft:8},children:[h.jsxs("div",{className:"sidebar-item",style:{cursor:"pointer",display:"flex",justifyContent:"space-between",fontWeight:l.sortKey==="createdAt"?700:void 0},onClick:()=>te("createdAt","desc"),title:"Sort by date created",children:[h.jsx("span",{className:"text",children:"Date created"}),h.jsx("span",{className:"sidebar-indicator"+(Ae("createdAt")?"":" placeholder"),"aria-hidden":!0,children:h.jsx("span",{className:"dir"+(l.sortDir==="desc"&&Ae("createdAt")?" desc":""),children:"▲"})})]}),h.jsxs("div",{className:"sidebar-item",style:{cursor:"pointer",display:"flex",justifyContent:"space-between",fontWeight:l.sortKey==="updatedAt"?700:void 0},onClick:()=>te("updatedAt","desc"),title:"Sort by date updated",children:[h.jsx("span",{className:"text",children:"Date updated"}),h.jsx("span",{className:"sidebar-indicator"+(Ae("updatedAt")?"":" placeholder"),"aria-hidden":!0,children:h.jsx("span",{className:"dir"+(l.sortDir==="desc"&&Ae("updatedAt")?" desc":""),children:"▲"})})]}),h.jsxs("div",{className:"sidebar-item",style:{cursor:"pointer",display:"flex",justifyContent:"space-between",fontWeight:l.sortKey==="title"?700:void 0},onClick:()=>te("title","asc"),title:"Sort alphabetically by title",children:[h.jsx("span",{className:"text",children:"Alphabetical"}),h.jsx("span",{className:"sidebar-indicator"+(Ae("title")?"":" placeholder"),"aria-hidden":!0,children:h.jsx("span",{className:"dir"+(l.sortDir==="desc"&&Ae("title")?" desc":""),children:"▲"})})]}),h.jsx("div",{className:"sidebar-item",onClick:Q,style:{cursor:"pointer",marginTop:4},title:"Filters",children:h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(y?" open":""),children:"▶"})}),"Filters"]})}),y&&h.jsxs("div",{style:{paddingLeft:10},children:[h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"Due soon"})}),h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"Least accessed"})}),h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"Most edited"})}),h.jsx("div",{className:"sidebar-item",style:me,title:"Coming soon",children:h.jsx("span",{className:"text",children:"“At risk”"})}),h.jsx("div",{style:{display:"none"},children:h.jsx("button",{onClick:()=>de("none"),children:"none"})})]}),h.jsx("div",{className:"sidebar-item",onClick:Je,style:{cursor:"pointer",marginTop:4},title:"Grouping",children:h.jsxs("span",{className:"text",children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(w?" open":""),children:"▶"})}),"Grouping"]})}),w&&h.jsxs("div",{style:{paddingLeft:10},children:[h.jsx("div",{className:"sidebar-item",style:{cursor:"pointer",fontWeight:l.groupBy==="week"?700:void 0},onClick:()=>ue("week"),title:"Group by week",children:h.jsx("span",{className:"text",children:"By week"})}),h.jsx("div",{className:"sidebar-item",style:{cursor:"pointer",fontWeight:l.groupBy==="month"?700:void 0},onClick:()=>ue("month"),title:"Group by month",children:h.jsx("span",{className:"text",children:"By month"})})]})]}),h.jsxs("div",{className:"sidebar-item",title:"Collections",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M3 7h6l2 2h10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"})})}),!r&&h.jsxs("span",{className:"text",style:{cursor:"pointer"},onClick:at,children:[h.jsx("span",{className:"sidebar-indicator leading",children:h.jsx("span",{className:"chev"+(E?" open":""),children:"▶"})}),"Collections"]})]}),E&&!r&&h.jsxs("div",{style:{paddingLeft:8},children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:6},children:[h.jsx("div",{style:{display:"flex",gap:6,alignItems:"center"},children:s.length>0&&h.jsxs(h.Fragment,{children:[h.jsx("button",{className:"btn",onClick:ct,title:"Back",children:"Back"}),h.jsx("button",{className:"btn",onClick:nt,title:"All notes",children:"All"})]})}),s.length>0&&h.jsx("button",{className:"btn",title:"Delete this collection",onClick:()=>{const ce=s[s.length-1];wt(Number(ce.id),String(ce.name||""))},children:"Delete"})]}),s.length>0&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)",fontSize:12,paddingLeft:0},title:"Current path",children:s.map(ce=>String(ce.name||"")).join(" / ")}),h.jsx("div",{className:"sidebar-item"+(s.length?"":" active"),style:{cursor:"pointer"},onClick:()=>{nt()},title:"Show all notes",children:h.jsx("span",{className:"text",children:"All notes"})}),z&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)"},children:"Loading…"}),!z&&M.length===0&&h.jsx("div",{className:"sidebar-item",style:{color:"var(--muted)"},children:"No collections"}),M.map(ce=>h.jsxs("div",{className:"sidebar-item",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",flex:1,minWidth:0},onClick:()=>{$t(ce.id,ce.name)},title:ce.name,children:[h.jsx("span",{className:"text",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ce.name}),typeof ce.noteCount=="number"&&h.jsxs("span",{style:{color:"var(--muted)",fontSize:12},children:["(",ce.noteCount,")"]})]}),h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[h.jsx("button",{className:"btn",title:"Rename",onClick:Ee=>{Ee.stopPropagation(),Bt(ce.id,ce.name)},children:"Rename"}),h.jsx("button",{className:"btn",title:"Delete",onClick:Ee=>{Ee.stopPropagation(),wt(ce.id,ce.name)},children:"✕"})]})]},ce.id)),h.jsxs("div",{style:{display:"flex",gap:6,marginTop:6},children:[h.jsx("input",{value:L,onChange:ce=>H(ce.target.value),placeholder:"New collection",style:{flex:1,minWidth:0,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",background:"var(--panel)",color:"var(--text)"},onKeyDown:ce=>{ce.key==="Enter"&&At()}}),h.jsx("button",{className:"btn",onClick:At,disabled:!L.trim(),children:"Add"})]})]}),h.jsxs("div",{className:"sidebar-item",title:"Archive",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M20.54 5.23L19.4 4H4.6L3.46 5.23 3 6v2h18V6l-.46-.77zM6 10v9h12V10H6zm3 2h6v2H9v-2z"})})}),!r&&h.jsx("span",{className:"text",children:"Archive"})]}),h.jsxs("div",{className:"sidebar-item",title:"Bin",children:[h.jsx("span",{className:"icon","aria-hidden":!0,children:h.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M4 7h16"}),h.jsx("path",{d:"M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12"}),h.jsx("path",{d:"M9 7V5h6v2"})]})}),!r&&h.jsx("span",{className:"text",children:"Bin"})]})]})})}const Hm=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Dc(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function Cb(t){return"nodeType"in t}function qr(t){var e,n;return t?Dc(t)?t:Cb(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Eb(t){const{Document:e}=qr(t);return t instanceof e}function Vd(t){return Dc(t)?!1:t instanceof qr(t).HTMLElement}function UA(t){return t instanceof qr(t).SVGElement}function Oc(t){return t?Dc(t)?t.document:Cb(t)?Eb(t)?t:Vd(t)||UA(t)?t.ownerDocument:document:document:document}const lo=Hm?b.useLayoutEffect:b.useEffect;function Vm(t){const e=b.useRef(t);return lo(()=>{e.current=t}),b.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{t.current=setInterval(r,i)},[]),n=b.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function cd(t,e){e===void 0&&(e=[t]);const n=b.useRef(t);return lo(()=>{n.current!==t&&(n.current=t)},e),n}function Wd(t,e){const n=b.useRef();return b.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function ap(t){const e=Vm(t),n=b.useRef(null),r=b.useCallback(i=>{i!==n.current&&(e==null||e(i,n.current)),n.current=i},[]);return[n,r]}function cp(t){const e=b.useRef();return b.useEffect(()=>{e.current=t},[t]),e.current}let dy={};function Wm(t,e){return b.useMemo(()=>{if(e)return e;const n=dy[t]==null?0:dy[t]+1;return dy[t]=n,t+"-"+n},[t,e])}function HA(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const l=Object.entries(o);for(const[a,c]of l){const u=s[a];u!=null&&(s[a]=u+t*c)}return s},{...e})}}const Ya=HA(1),up=HA(-1);function T_(t){return"clientX"in t&&"clientY"in t}function Nb(t){if(!t)return!1;const{KeyboardEvent:e}=qr(t.target);return e&&t instanceof e}function A_(t){if(!t)return!1;const{TouchEvent:e}=qr(t.target);return e&&t instanceof e}function dp(t){if(A_(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return T_(t)?{x:t.clientX,y:t.clientY}:null}const ud=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[ud.Translate.toString(t),ud.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),rS="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function M_(t){return t.matches(rS)?t:t.querySelector(rS)}const I_={display:"none"};function R_(t){let{id:e,value:n}=t;return B.createElement("div",{id:e,style:I_},n)}function D_(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return B.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function O_(){const[t,e]=b.useState("");return{announce:b.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const VA=b.createContext(null);function j_(t){const e=b.useContext(VA);b.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(t)},[t,e])}function P_(){const[t]=b.useState(()=>new Set),e=b.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[b.useCallback(r=>{let{type:i,event:s}=r;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const L_={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. - `},__={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function z_(t){let{announcements:e=__,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=L_}=t;const{announce:s,announcement:o}=O_(),l=Wm("DndLiveRegion"),[a,c]=b.useState(!1);if(b.useEffect(()=>{c(!0)},[]),j_(b.useMemo(()=>({onDragStart(d){let{active:f}=d;s(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&s(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;s(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;s(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;s(e.onDragCancel({active:f,over:p}))}}),[s,e])),!a)return null;const u=B.createElement(B.Fragment,null,B.createElement(R_,{id:r,value:i.draggable}),B.createElement(D_,{id:l,announcement:o}));return n?zn.createPortal(u,n):u}var Xn;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Xn||(Xn={}));function fp(){}function iS(t,e){return b.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function F_(){for(var t=arguments.length,e=new Array(t),n=0;n[...e].filter(r=>r!=null),[...e])}const ts=Object.freeze({x:0,y:0});function $_(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function B_(t,e){const n=dp(t);if(!n)return"0 0";const r={x:(n.x-e.left)/e.width*100,y:(n.y-e.top)/e.height*100};return r.x+"% "+r.y+"%"}function U_(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function H_(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function V_(t){let{left:e,top:n,height:r,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function W_(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function K_(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),i=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=i-r,l=s-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const a=K_(l,e);a>0&&i.push({id:o,data:{droppableContainer:s,value:a}})}}return i.sort(H_)};function q_(t,e){const{top:n,left:r,bottom:i,right:s}=e;return n<=t.y&&t.y<=i&&r<=t.x&&t.x<=s}const J_=t=>{let{droppableContainers:e,droppableRects:n,pointerCoordinates:r}=t;if(!r)return[];const i=[];for(const s of e){const{id:o}=s,l=n.get(o);if(l&&q_(r,l)){const c=V_(l).reduce((d,f)=>d+$_(r,f),0),u=Number((c/4).toFixed(4));i.push({id:o,data:{droppableContainer:s,value:u}})}}return i.sort(U_)};function G_(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function WA(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:ts}function X_(t){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),s=1;s({...o,top:o.top+t*l.y,bottom:o.bottom+t*l.y,left:o.left+t*l.x,right:o.right+t*l.x}),{...n})}}const Q_=X_(1);function KA(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Z_(t,e,n){const r=KA(e);if(!r)return t;const{scaleX:i,scaleY:s,x:o,y:l}=r,a=t.left-o-(1-i)*parseFloat(n),c=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),u=i?t.width/i:t.width,d=s?t.height/s:t.height;return{width:u,height:d,top:c,right:a+u,bottom:c+d,left:a}}const e3={ignoreTransform:!1};function Kd(t,e){e===void 0&&(e=e3);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:c,transformOrigin:u}=qr(t).getComputedStyle(t);c&&(n=Z_(n,c,u))}const{top:r,left:i,width:s,height:o,bottom:l,right:a}=n;return{top:r,left:i,width:s,height:o,bottom:l,right:a}}function sS(t){return Kd(t,{ignoreTransform:!0})}function t3(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function n3(t,e){return e===void 0&&(e=qr(t).getComputedStyle(t)),e.position==="fixed"}function r3(t,e){e===void 0&&(e=qr(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const s=e[i];return typeof s=="string"?n.test(s):!1})}function Tb(t,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Eb(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Vd(i)||UA(i)||n.includes(i))return n;const s=qr(t).getComputedStyle(i);return i!==t&&r3(i,s)&&n.push(i),n3(i,s)?n:r(i.parentNode)}return t?r(t):n}function YA(t){const[e]=Tb(t,1);return e??null}function fy(t){return!Hm||!t?null:Dc(t)?t:Cb(t)?Eb(t)||t===Oc(t).scrollingElement?window:Vd(t)?t:null:null}function qA(t){return Dc(t)?t.scrollX:t.scrollLeft}function JA(t){return Dc(t)?t.scrollY:t.scrollTop}function c0(t){return{x:qA(t),y:JA(t)}}var sr;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(sr||(sr={}));function GA(t){return!Hm||!t?!1:t===document.scrollingElement}function XA(t){const e={x:0,y:0},n=GA(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const i3={x:.2,y:.2};function s3(t,e,n,r,i){let{top:s,left:o,right:l,bottom:a}=n;r===void 0&&(r=10),i===void 0&&(i=i3);const{isTop:c,isBottom:u,isLeft:d,isRight:f}=XA(t),p={x:0,y:0},m={x:0,y:0},g={height:e.height*i.y,width:e.width*i.x};return!c&&s<=e.top+g.height?(p.y=sr.Backward,m.y=r*Math.abs((e.top+g.height-s)/g.height)):!u&&a>=e.bottom-g.height&&(p.y=sr.Forward,m.y=r*Math.abs((e.bottom-g.height-a)/g.height)),!f&&l>=e.right-g.width?(p.x=sr.Forward,m.x=r*Math.abs((e.right-g.width-l)/g.width)):!d&&o<=e.left+g.width&&(p.x=sr.Backward,m.x=r*Math.abs((e.left+g.width-o)/g.width)),{direction:p,speed:m}}function o3(t){if(t===document.scrollingElement){const{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}const{top:e,left:n,right:r,bottom:i}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:t.clientWidth,height:t.clientHeight}}function QA(t){return t.reduce((e,n)=>Ya(e,c0(n)),ts)}function l3(t){return t.reduce((e,n)=>e+qA(n),0)}function a3(t){return t.reduce((e,n)=>e+JA(n),0)}function ZA(t,e){if(e===void 0&&(e=Kd),!t)return;const{top:n,left:r,bottom:i,right:s}=e(t);YA(t)&&(i<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const c3=[["x",["left","right"],l3],["y",["top","bottom"],a3]];class Ab{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=Tb(n),i=QA(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of c3)for(const a of o)Object.defineProperty(this,a,{get:()=>{const c=l(r),u=i[s]-c;return this.rect[a]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Tu{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function u3(t){const{EventTarget:e}=qr(t);return t instanceof e?t:Oc(t)}function hy(t,e){const n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var ki;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(ki||(ki={}));function oS(t){t.preventDefault()}function d3(t){t.stopPropagation()}var gn;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(gn||(gn={}));const eM={start:[gn.Space,gn.Enter],cancel:[gn.Esc],end:[gn.Space,gn.Enter,gn.Tab]},f3=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case gn.Right:return{...n,x:n.x+25};case gn.Left:return{...n,x:n.x-25};case gn.Down:return{...n,y:n.y+25};case gn.Up:return{...n,y:n.y-25}}};class tM{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new Tu(Oc(n)),this.windowListeners=new Tu(qr(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ki.Resize,this.handleCancel),this.windowListeners.add(ki.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ki.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&ZA(r),n(ts)}handleKeyDown(e){if(Nb(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:s=eM,coordinateGetter:o=f3,scrollBehavior:l="smooth"}=i,{code:a}=e;if(s.end.includes(a)){this.handleEnd(e);return}if(s.cancel.includes(a)){this.handleCancel(e);return}const{collisionRect:c}=r.current,u=c?{x:c.left,y:c.top}:ts;this.referenceCoordinates||(this.referenceCoordinates=u);const d=o(e,{active:n,context:r.current,currentCoordinates:u});if(d){const f=up(d,u),p={x:0,y:0},{scrollableAncestors:m}=r.current;for(const g of m){const y=e.code,{isTop:v,isRight:w,isLeft:x,isBottom:E,maxScroll:k,minScroll:M}=XA(g),N=o3(g),z={x:Math.min(y===gn.Right?N.right-N.width/2:N.right,Math.max(y===gn.Right?N.left:N.left+N.width/2,d.x)),y:Math.min(y===gn.Down?N.bottom-N.height/2:N.bottom,Math.max(y===gn.Down?N.top:N.top+N.height/2,d.y))},X=y===gn.Right&&!w||y===gn.Left&&!x,L=y===gn.Down&&!E||y===gn.Up&&!v;if(X&&z.x!==d.x){const H=g.scrollLeft+f.x,W=y===gn.Right&&H<=k.x||y===gn.Left&&H>=M.x;if(W&&!f.y){g.scrollTo({left:H,behavior:l});return}W?p.x=g.scrollLeft-H:p.x=y===gn.Right?g.scrollLeft-k.x:g.scrollLeft-M.x,p.x&&g.scrollBy({left:-p.x,behavior:l});break}else if(L&&z.y!==d.y){const H=g.scrollTop+f.y,W=y===gn.Down&&H<=k.y||y===gn.Up&&H>=M.y;if(W&&!f.x){g.scrollTo({top:H,behavior:l});return}W?p.y=g.scrollTop-H:p.y=y===gn.Down?g.scrollTop-k.y:g.scrollTop-M.y,p.y&&g.scrollBy({top:-p.y,behavior:l});break}}this.handleMove(e,Ya(up(d,this.referenceCoordinates),p))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}tM.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=eM,onActivation:i}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(r.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),i==null||i({event:t.nativeEvent}),!0)}return!1}}];function lS(t){return!!(t&&"distance"in t)}function aS(t){return!!(t&&"delay"in t)}class Mb{constructor(e,n,r){var i;r===void 0&&(r=u3(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:s}=e,{target:o}=s;this.props=e,this.events=n,this.document=Oc(o),this.documentListeners=new Tu(this.document),this.listeners=new Tu(r),this.windowListeners=new Tu(qr(o)),this.initialCoordinates=(i=dp(s))!=null?i:ts,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ki.Resize,this.handleCancel),this.windowListeners.add(ki.DragStart,oS),this.windowListeners.add(ki.VisibilityChange,this.handleCancel),this.windowListeners.add(ki.ContextMenu,oS),this.documentListeners.add(ki.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(aS(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(lS(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ki.Click,d3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ki.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const a=(n=dp(e))!=null?n:ts,c=up(i,a);if(!r&&l){if(lS(l)){if(l.tolerance!=null&&hy(c,l.tolerance))return this.handleCancel();if(hy(c,l.distance))return this.handleStart()}if(aS(l)&&hy(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}e.cancelable&&e.preventDefault(),o(a)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===gn.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const h3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class nM extends Mb{constructor(e){const{event:n}=e,r=Oc(n.target);super(e,h3,r)}}nM.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const p3={move:{name:"mousemove"},end:{name:"mouseup"}};var u0;(function(t){t[t.RightClick=2]="RightClick"})(u0||(u0={}));class rM extends Mb{constructor(e){super(e,p3,Oc(e.event.target))}}rM.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===u0.RightClick?!1:(r==null||r({event:n}),!0)}}];const py={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class iM extends Mb{constructor(e){super(e,py)}static setup(){return window.addEventListener(py.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(py.move.name,e)};function e(){}}}iM.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r==null||r({event:n}),!0)}}];var Au;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(Au||(Au={}));var hp;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(hp||(hp={}));function m3(t){let{acceleration:e,activator:n=Au.Pointer,canScroll:r,draggingRect:i,enabled:s,interval:o=5,order:l=hp.TreeOrder,pointerCoordinates:a,scrollableAncestors:c,scrollableAncestorRects:u,delta:d,threshold:f}=t;const p=y3({delta:d,disabled:!s}),[m,g]=N_(),y=b.useRef({x:0,y:0}),v=b.useRef({x:0,y:0}),w=b.useMemo(()=>{switch(n){case Au.Pointer:return a?{top:a.y,bottom:a.y,left:a.x,right:a.x}:null;case Au.DraggableRect:return i}},[n,i,a]),x=b.useRef(null),E=b.useCallback(()=>{const M=x.current;if(!M)return;const N=y.current.x*v.current.x,z=y.current.y*v.current.y;M.scrollBy(N,z)},[]),k=b.useMemo(()=>l===hp.TreeOrder?[...c].reverse():c,[l,c]);b.useEffect(()=>{if(!s||!c.length||!w){g();return}for(const M of k){if((r==null?void 0:r(M))===!1)continue;const N=c.indexOf(M),z=u[N];if(!z)continue;const{direction:X,speed:L}=s3(M,z,w,e,f);for(const H of["x","y"])p[H][X[H]]||(L[H]=0,X[H]=0);if(L.x>0||L.y>0){g(),x.current=M,m(E,o),y.current=L,v.current=X;return}}y.current={x:0,y:0},v.current={x:0,y:0},g()},[e,E,r,g,s,o,JSON.stringify(w),JSON.stringify(p),m,c,k,u,JSON.stringify(f)])}const g3={x:{[sr.Backward]:!1,[sr.Forward]:!1},y:{[sr.Backward]:!1,[sr.Forward]:!1}};function y3(t){let{delta:e,disabled:n}=t;const r=cp(e);return Wd(i=>{if(n||!r||!i)return g3;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[sr.Backward]:i.x[sr.Backward]||s.x===-1,[sr.Forward]:i.x[sr.Forward]||s.x===1},y:{[sr.Backward]:i.y[sr.Backward]||s.y===-1,[sr.Forward]:i.y[sr.Forward]||s.y===1}}},[n,e,r])}function v3(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return Wd(i=>{var s;return e==null?null:(s=r??i)!=null?s:null},[r,e])}function w3(t,e){return b.useMemo(()=>t.reduce((n,r)=>{const{sensor:i}=r,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var dd;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(dd||(dd={}));var d0;(function(t){t.Optimized="optimized"})(d0||(d0={}));const cS=new Map;function b3(t,e){let{dragging:n,dependencies:r,config:i}=e;const[s,o]=b.useState(null),{frequency:l,measure:a,strategy:c}=i,u=b.useRef(t),d=y(),f=cd(d),p=b.useCallback(function(v){v===void 0&&(v=[]),!f.current&&o(w=>w===null?v:w.concat(v.filter(x=>!w.includes(x))))},[f]),m=b.useRef(null),g=Wd(v=>{if(d&&!n)return cS;if(!v||v===cS||u.current!==t||s!=null){const w=new Map;for(let x of t){if(!x)continue;if(s&&s.length>0&&!s.includes(x.id)&&x.rect.current){w.set(x.id,x.rect.current);continue}const E=x.node.current,k=E?new Ab(a(E),E):null;x.rect.current=k,k&&w.set(x.id,k)}return w}return v},[t,s,n,d,a]);return b.useEffect(()=>{u.current=t},[t]),b.useEffect(()=>{d||p()},[n,d]),b.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),b.useEffect(()=>{d||typeof l!="number"||m.current!==null||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,d,p,...r]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:s!=null};function y(){switch(c){case dd.Always:return!1;case dd.BeforeDragging:return n;default:return!n}}}function Ib(t,e){return Wd(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function x3(t,e){return Ib(t,e)}function k3(t){let{callback:e,disabled:n}=t;const r=Vm(e),i=b.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return b.useEffect(()=>()=>i==null?void 0:i.disconnect(),[i]),i}function Km(t){let{callback:e,disabled:n}=t;const r=Vm(e),i=b.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return b.useEffect(()=>()=>i==null?void 0:i.disconnect(),[i]),i}function S3(t){return new Ab(Kd(t),t)}function uS(t,e,n){e===void 0&&(e=S3);const[r,i]=b.useState(null);function s(){i(a=>{if(!t)return null;if(t.isConnected===!1){var c;return(c=a??n)!=null?c:null}const u=e(t);return JSON.stringify(a)===JSON.stringify(u)?a:u})}const o=k3({callback(a){if(t)for(const c of a){const{type:u,target:d}=c;if(u==="childList"&&d instanceof HTMLElement&&d.contains(t)){s();break}}}}),l=Km({callback:s});return lo(()=>{s(),t?(l==null||l.observe(t),o==null||o.observe(document.body,{childList:!0,subtree:!0})):(l==null||l.disconnect(),o==null||o.disconnect())},[t]),r}function C3(t){const e=Ib(t);return WA(t,e)}const dS=[];function E3(t){const e=b.useRef(t),n=Wd(r=>t?r&&r!==dS&&t&&e.current&&t.parentNode===e.current.parentNode?r:Tb(t):dS,[t]);return b.useEffect(()=>{e.current=t},[t]),n}function N3(t){const[e,n]=b.useState(null),r=b.useRef(t),i=b.useCallback(s=>{const o=fy(s.target);o&&n(l=>l?(l.set(o,c0(o)),new Map(l)):null)},[]);return b.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(a=>{const c=fy(a);return c?(c.addEventListener("scroll",i,{passive:!0}),[c,c0(c)]):null}).filter(a=>a!=null);n(l.length?new Map(l):null),r.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(a=>{const c=fy(a);c==null||c.removeEventListener("scroll",i)})}},[i,t]),b.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>Ya(s,o),ts):QA(t):ts,[t,e])}function fS(t,e){e===void 0&&(e=[]);const n=b.useRef(null);return b.useEffect(()=>{n.current=null},e),b.useEffect(()=>{const r=t!==ts;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?up(t,n.current):ts}function T3(t){b.useEffect(()=>{if(!Hm)return;const e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n==null||n()}},t.map(e=>{let{sensor:n}=e;return n}))}function A3(t,e){return b.useMemo(()=>t.reduce((n,r)=>{let{eventName:i,handler:s}=r;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function sM(t){return b.useMemo(()=>t?t3(t):null,[t])}const hS=[];function M3(t,e){e===void 0&&(e=Kd);const[n]=t,r=sM(n?qr(n):null),[i,s]=b.useState(hS);function o(){s(()=>t.length?t.map(a=>GA(a)?r:new Ab(e(a),a)):hS)}const l=Km({callback:o});return lo(()=>{l==null||l.disconnect(),o(),t.forEach(a=>l==null?void 0:l.observe(a))},[t]),i}function oM(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return Vd(e)?e:t}function I3(t){let{measure:e}=t;const[n,r]=b.useState(null),i=b.useCallback(c=>{for(const{target:u}of c)if(Vd(u)){r(d=>{const f=e(u);return d?{...d,width:f.width,height:f.height}:f});break}},[e]),s=Km({callback:i}),o=b.useCallback(c=>{const u=oM(c);s==null||s.disconnect(),u&&(s==null||s.observe(u)),r(u?e(u):null)},[e,s]),[l,a]=ap(o);return b.useMemo(()=>({nodeRef:l,rect:n,setRef:a}),[n,l,a])}const R3=[{sensor:nM,options:{}},{sensor:tM,options:{}}],D3={current:{}},bh={draggable:{measure:sS},droppable:{measure:sS,strategy:dd.WhileDragging,frequency:d0.Optimized},dragOverlay:{measure:Kd}};class Mu extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const O3={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Mu,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:fp},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:bh,measureDroppableContainers:fp,windowRect:null,measuringScheduled:!1},lM={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:fp,draggableNodes:new Map,over:null,measureDroppableContainers:fp},Yd=b.createContext(lM),aM=b.createContext(O3);function j3(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Mu}}}function P3(t,e){switch(e.type){case Xn.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Xn.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Xn.DragEnd:case Xn.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Xn.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Mu(t.droppable.containers);return i.set(r,n),{...t,droppable:{...t.droppable,containers:i}}}case Xn.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new Mu(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case Xn.UnregisterDroppable:{const{id:n,key:r}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;const s=new Mu(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function L3(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:i}=b.useContext(Yd),s=cp(r),o=cp(n==null?void 0:n.id);return b.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!Nb(s)||document.activeElement===s.target)return;const l=i.get(o);if(!l)return;const{activatorNode:a,node:c}=l;if(!a.current&&!c.current)return;requestAnimationFrame(()=>{for(const u of[a.current,c.current]){if(!u)continue;const d=M_(u);if(d){d.focus();break}}})}},[r,e,i,o,s]),null}function cM(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...r}),n):n}function _3(t){return b.useMemo(()=>({draggable:{...bh.draggable,...t==null?void 0:t.draggable},droppable:{...bh.droppable,...t==null?void 0:t.droppable},dragOverlay:{...bh.dragOverlay,...t==null?void 0:t.dragOverlay}}),[t==null?void 0:t.draggable,t==null?void 0:t.droppable,t==null?void 0:t.dragOverlay])}function z3(t){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=t;const s=b.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;lo(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const c=e==null?void 0:e.node.current;if(!c||c.isConnected===!1)return;const u=n(c),d=WA(u,r);if(o||(d.x=0),l||(d.y=0),s.current=!0,Math.abs(d.x)>0||Math.abs(d.y)>0){const f=YA(c);f&&f.scrollBy({top:d.y,left:d.x})}},[e,o,l,r,n])}const Ym=b.createContext({...ts,scaleX:1,scaleY:1});var Mo;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(Mo||(Mo={}));const F3=b.memo(function(e){var n,r,i,s;let{id:o,accessibility:l,autoScroll:a=!0,children:c,sensors:u=R3,collisionDetection:d=Y_,measuring:f,modifiers:p,...m}=e;const g=b.useReducer(P3,void 0,j3),[y,v]=g,[w,x]=P_(),[E,k]=b.useState(Mo.Uninitialized),M=E===Mo.Initialized,{draggable:{active:N,nodes:z,translate:X},droppable:{containers:L}}=y,H=N!=null?z.get(N):null,W=b.useRef({initial:null,translated:null}),te=b.useMemo(()=>{var It;return N!=null?{id:N,data:(It=H==null?void 0:H.data)!=null?It:D3,rect:W}:null},[N,H]),ce=b.useRef(null),[ue,Ae]=b.useState(null),[me,q]=b.useState(null),se=cd(m,Object.values(m)),xe=Wm("DndDescribedBy",o),Me=b.useMemo(()=>L.getEnabled(),[L]),Q=_3(f),{droppableRects:Je,measureDroppableContainers:_t,measuringScheduled:J}=b3(Me,{dragging:M,dependencies:[X.x,X.y],config:Q.droppable}),at=v3(z,N),$t=b.useMemo(()=>me?dp(me):null,[me]),ct=dn(),nt=x3(at,Q.draggable.measure);z3({activeNode:N!=null?z.get(N):null,config:ct.layoutShiftCompensation,initialRect:nt,measure:Q.draggable.measure});const At=uS(at,Q.draggable.measure,nt),Vt=uS(at?at.parentElement:null),wt=b.useRef({activatorEvent:null,active:null,activeNode:at,collisionRect:null,collisions:null,droppableRects:Je,draggableNodes:z,draggingNode:null,draggingNodeRect:null,droppableContainers:L,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ae=L.getNodeFor((n=wt.current.over)==null?void 0:n.id),Ee=I3({measure:Q.dragOverlay.measure}),Ke=(r=Ee.nodeRef.current)!=null?r:at,ze=M?(i=Ee.rect)!=null?i:At:null,Pe=!!(Ee.nodeRef.current&&Ee.rect),it=C3(Pe?null:At),ot=sM(Ke?qr(Ke):null),xt=E3(M?ae??at:null),oe=M3(xt),Ye=cM(p,{transform:{x:X.x-it.x,y:X.y-it.y,scaleX:1,scaleY:1},activatorEvent:me,active:te,activeNodeRect:At,containerNodeRect:Vt,draggingNodeRect:ze,over:wt.current.over,overlayNodeRect:Ee.rect,scrollableAncestors:xt,scrollableAncestorRects:oe,windowRect:ot}),Ge=$t?Ya($t,X):null,K=N3(xt),ge=fS(K),De=fS(K,[At]),Be=Ya(Ye,ge),Le=ze?Q_(ze,Ye):null,j=te&&Le?d({active:te,collisionRect:Le,droppableRects:Je,droppableContainers:Me,pointerCoordinates:Ge}):null,G=W_(j,"id"),[de,je]=b.useState(null),Ue=Pe?Ye:Ya(Ye,De),We=G_(Ue,(s=de==null?void 0:de.rect)!=null?s:null,At),Se=b.useRef(null),Xe=b.useCallback((It,Ot)=>{let{sensor:tn,options:ee}=Ot;if(ce.current==null)return;const re=z.get(ce.current);if(!re)return;const Oe=It.nativeEvent,Ze=new tn({active:ce.current,activeNode:re,event:Oe,options:ee,context:wt,onAbort(Ce){if(!z.get(Ce))return;const{onDragAbort:ut}=se.current,zt={id:Ce};ut==null||ut(zt),w({type:"onDragAbort",event:zt})},onPending(Ce,Fe,ut,zt){if(!z.get(Ce))return;const{onDragPending:Jt}=se.current,jt={id:Ce,constraint:Fe,initialCoordinates:ut,offset:zt};Jt==null||Jt(jt),w({type:"onDragPending",event:jt})},onStart(Ce){const Fe=ce.current;if(Fe==null)return;const ut=z.get(Fe);if(!ut)return;const{onDragStart:zt}=se.current,kt={activatorEvent:Oe,active:{id:Fe,data:ut.data,rect:W}};zn.unstable_batchedUpdates(()=>{zt==null||zt(kt),k(Mo.Initializing),v({type:Xn.DragStart,initialCoordinates:Ce,active:Fe}),w({type:"onDragStart",event:kt}),Ae(Se.current),q(Oe)})},onMove(Ce){v({type:Xn.DragMove,coordinates:Ce})},onEnd:fe(Xn.DragEnd),onCancel:fe(Xn.DragCancel)});Se.current=Ze;function fe(Ce){return async function(){const{active:ut,collisions:zt,over:kt,scrollAdjustedTranslate:Jt}=wt.current;let jt=null;if(ut&&Jt){const{cancelDrop:fn}=se.current;jt={activatorEvent:Oe,active:ut,collisions:zt,delta:Jt,over:kt},Ce===Xn.DragEnd&&typeof fn=="function"&&await Promise.resolve(fn(jt))&&(Ce=Xn.DragCancel)}ce.current=null,zn.unstable_batchedUpdates(()=>{v({type:Ce}),k(Mo.Uninitialized),je(null),Ae(null),q(null),Se.current=null;const fn=Ce===Xn.DragEnd?"onDragEnd":"onDragCancel";if(jt){const wn=se.current[fn];wn==null||wn(jt),w({type:fn,event:jt})}})}}},[z]),Tt=b.useCallback((It,Ot)=>(tn,ee)=>{const re=tn.nativeEvent,Oe=z.get(ee);if(ce.current!==null||!Oe||re.dndKit||re.defaultPrevented)return;const Ze={active:Oe};It(tn,Ot.options,Ze)===!0&&(re.dndKit={capturedBy:Ot.sensor},ce.current=ee,Xe(tn,Ot))},[z,Xe]),rt=w3(u,Tt);T3(u),lo(()=>{At&&E===Mo.Initializing&&k(Mo.Initialized)},[At,E]),b.useEffect(()=>{const{onDragMove:It}=se.current,{active:Ot,activatorEvent:tn,collisions:ee,over:re}=wt.current;if(!Ot||!tn)return;const Oe={active:Ot,activatorEvent:tn,collisions:ee,delta:{x:Be.x,y:Be.y},over:re};zn.unstable_batchedUpdates(()=>{It==null||It(Oe),w({type:"onDragMove",event:Oe})})},[Be.x,Be.y]),b.useEffect(()=>{const{active:It,activatorEvent:Ot,collisions:tn,droppableContainers:ee,scrollAdjustedTranslate:re}=wt.current;if(!It||ce.current==null||!Ot||!re)return;const{onDragOver:Oe}=se.current,Ze=ee.get(G),fe=Ze&&Ze.rect.current?{id:Ze.id,rect:Ze.rect.current,data:Ze.data,disabled:Ze.disabled}:null,Ce={active:It,activatorEvent:Ot,collisions:tn,delta:{x:re.x,y:re.y},over:fe};zn.unstable_batchedUpdates(()=>{je(fe),Oe==null||Oe(Ce),w({type:"onDragOver",event:Ce})})},[G]),lo(()=>{wt.current={activatorEvent:me,active:te,activeNode:at,collisionRect:Le,collisions:j,droppableRects:Je,draggableNodes:z,draggingNode:Ke,draggingNodeRect:ze,droppableContainers:L,over:de,scrollableAncestors:xt,scrollAdjustedTranslate:Be},W.current={initial:ze,translated:Le}},[te,at,j,Le,z,Ke,ze,Je,L,de,xt,Be]),m3({...ct,delta:X,draggingRect:Le,pointerCoordinates:Ge,scrollableAncestors:xt,scrollableAncestorRects:oe});const Wt=b.useMemo(()=>({active:te,activeNode:at,activeNodeRect:At,activatorEvent:me,collisions:j,containerNodeRect:Vt,dragOverlay:Ee,draggableNodes:z,droppableContainers:L,droppableRects:Je,over:de,measureDroppableContainers:_t,scrollableAncestors:xt,scrollableAncestorRects:oe,measuringConfiguration:Q,measuringScheduled:J,windowRect:ot}),[te,at,At,me,j,Vt,Ee,z,L,Je,de,_t,xt,oe,Q,J,ot]),Mt=b.useMemo(()=>({activatorEvent:me,activators:rt,active:te,activeNodeRect:At,ariaDescribedById:{draggable:xe},dispatch:v,draggableNodes:z,over:de,measureDroppableContainers:_t}),[me,rt,te,At,v,xe,z,de,_t]);return B.createElement(VA.Provider,{value:x},B.createElement(Yd.Provider,{value:Mt},B.createElement(aM.Provider,{value:Wt},B.createElement(Ym.Provider,{value:We},c)),B.createElement(L3,{disabled:(l==null?void 0:l.restoreFocus)===!1})),B.createElement(z_,{...l,hiddenTextDescribedById:xe}));function dn(){const It=(ue==null?void 0:ue.autoScrollEnabled)===!1,Ot=typeof a=="object"?a.enabled===!1:a===!1,tn=M&&!It&&!Ot;return typeof a=="object"?{...a,enabled:tn}:{enabled:tn}}}),$3=b.createContext(null),pS="button",B3="Draggable";function U3(t){let{id:e,data:n,disabled:r=!1,attributes:i}=t;const s=Wm(B3),{activators:o,activatorEvent:l,active:a,activeNodeRect:c,ariaDescribedById:u,draggableNodes:d,over:f}=b.useContext(Yd),{role:p=pS,roleDescription:m="draggable",tabIndex:g=0}=i??{},y=(a==null?void 0:a.id)===e,v=b.useContext(y?Ym:$3),[w,x]=ap(),[E,k]=ap(),M=A3(o,e),N=cd(n);lo(()=>(d.set(e,{id:e,key:s,node:w,activatorNode:E,data:N}),()=>{const X=d.get(e);X&&X.key===s&&d.delete(e)}),[d,e]);const z=b.useMemo(()=>({role:p,tabIndex:g,"aria-disabled":r,"aria-pressed":y&&p===pS?!0:void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[r,p,g,y,m,u.draggable]);return{active:a,activatorEvent:l,activeNodeRect:c,attributes:z,isDragging:y,listeners:r?void 0:M,node:w,over:f,setNodeRef:x,setActivatorNodeRef:k,transform:v}}function H3(){return b.useContext(aM)}const V3="Droppable",W3={timeout:25};function K3(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=t;const s=Wm(V3),{active:o,dispatch:l,over:a,measureDroppableContainers:c}=b.useContext(Yd),u=b.useRef({disabled:n}),d=b.useRef(!1),f=b.useRef(null),p=b.useRef(null),{disabled:m,updateMeasurementsFor:g,timeout:y}={...W3,...i},v=cd(g??r),w=b.useCallback(()=>{if(!d.current){d.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{c(Array.isArray(v.current)?v.current:[v.current]),p.current=null},y)},[y]),x=Km({callback:w,disabled:m||!o}),E=b.useCallback((z,X)=>{x&&(X&&(x.unobserve(X),d.current=!1),z&&x.observe(z))},[x]),[k,M]=ap(E),N=cd(e);return b.useEffect(()=>{!x||!k.current||(x.disconnect(),d.current=!1,x.observe(k.current))},[k,x]),b.useEffect(()=>(l({type:Xn.RegisterDroppable,element:{id:r,key:s,disabled:n,node:k,rect:f,data:N}}),()=>l({type:Xn.UnregisterDroppable,key:s,id:r})),[r]),b.useEffect(()=>{n!==u.current.disabled&&(l({type:Xn.SetDroppableDisabled,id:r,key:s,disabled:n}),u.current.disabled=n)},[r,s,n,l]),{active:o,rect:f,isOver:(a==null?void 0:a.id)===r,node:k,over:a,setNodeRef:M}}function Y3(t){let{animation:e,children:n}=t;const[r,i]=b.useState(null),[s,o]=b.useState(null),l=cp(n);return!n&&!r&&l&&i(l),lo(()=>{if(!s)return;const a=r==null?void 0:r.key,c=r==null?void 0:r.props.id;if(a==null||c==null){i(null);return}Promise.resolve(e(c,s)).then(()=>{i(null)})},[e,r,s]),B.createElement(B.Fragment,null,n,r?b.cloneElement(r,{ref:o}):null)}const q3={x:0,y:0,scaleX:1,scaleY:1};function J3(t){let{children:e}=t;return B.createElement(Yd.Provider,{value:lM},B.createElement(Ym.Provider,{value:q3},e))}const G3={position:"fixed",touchAction:"none"},X3=t=>Nb(t)?"transform 250ms ease":void 0,Q3=b.forwardRef((t,e)=>{let{as:n,activatorEvent:r,adjustScale:i,children:s,className:o,rect:l,style:a,transform:c,transition:u=X3}=t;if(!l)return null;const d=i?c:{...c,scaleX:1,scaleY:1},f={...G3,width:l.width,height:l.height,top:l.top,left:l.left,transform:ud.Transform.toString(d),transformOrigin:i&&r?B_(r,l):void 0,transition:typeof u=="function"?u(r):u,...a};return B.createElement(n,{className:o,style:f,ref:e},s)}),Z3=t=>e=>{let{active:n,dragOverlay:r}=e;const i={},{styles:s,className:o}=t;if(s!=null&&s.active)for(const[l,a]of Object.entries(s.active))a!==void 0&&(i[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,a));if(s!=null&&s.dragOverlay)for(const[l,a]of Object.entries(s.dragOverlay))a!==void 0&&r.node.style.setProperty(l,a);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(const[a,c]of Object.entries(i))n.node.style.setProperty(a,c);o!=null&&o.active&&n.node.classList.remove(o.active)}},e4=t=>{let{transform:{initial:e,final:n}}=t;return[{transform:ud.Transform.toString(e)},{transform:ud.Transform.toString(n)}]},t4={duration:250,easing:"ease",keyframes:e4,sideEffects:Z3({styles:{active:{opacity:"0"}}})};function n4(t){let{config:e,draggableNodes:n,droppableContainers:r,measuringConfiguration:i}=t;return Vm((s,o)=>{if(e===null)return;const l=n.get(s);if(!l)return;const a=l.node.current;if(!a)return;const c=oM(o);if(!c)return;const{transform:u}=qr(o).getComputedStyle(o),d=KA(u);if(!d)return;const f=typeof e=="function"?e:r4(e);return ZA(a,i.draggable.measure),f({active:{id:s,data:l.data,node:a,rect:i.draggable.measure(a)},draggableNodes:n,dragOverlay:{node:o,rect:i.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:i,transform:d})})}function r4(t){const{duration:e,easing:n,sideEffects:r,keyframes:i}={...t4,...t};return s=>{let{active:o,dragOverlay:l,transform:a,...c}=s;if(!e)return;const u={x:l.rect.left-o.rect.left,y:l.rect.top-o.rect.top},d={scaleX:a.scaleX!==1?o.rect.width*a.scaleX/l.rect.width:1,scaleY:a.scaleY!==1?o.rect.height*a.scaleY/l.rect.height:1},f={x:a.x-u.x,y:a.y-u.y,...d},p=i({...c,active:o,dragOverlay:l,transform:{initial:a,final:f}}),[m]=p,g=p[p.length-1];if(JSON.stringify(m)===JSON.stringify(g))return;const y=r==null?void 0:r({active:o,dragOverlay:l,...c}),v=l.node.animate(p,{duration:e,easing:n,fill:"forwards"});return new Promise(w=>{v.onfinish=()=>{y==null||y(),w()}})}}let mS=0;function i4(t){return b.useMemo(()=>{if(t!=null)return mS++,mS},[t])}const s4=B.memo(t=>{let{adjustScale:e=!1,children:n,dropAnimation:r,style:i,transition:s,modifiers:o,wrapperElement:l="div",className:a,zIndex:c=999}=t;const{activatorEvent:u,active:d,activeNodeRect:f,containerNodeRect:p,draggableNodes:m,droppableContainers:g,dragOverlay:y,over:v,measuringConfiguration:w,scrollableAncestors:x,scrollableAncestorRects:E,windowRect:k}=H3(),M=b.useContext(Ym),N=i4(d==null?void 0:d.id),z=cM(o,{activatorEvent:u,active:d,activeNodeRect:f,containerNodeRect:p,draggingNodeRect:y.rect,over:v,overlayNodeRect:y.rect,scrollableAncestors:x,scrollableAncestorRects:E,transform:M,windowRect:k}),X=Ib(f),L=n4({config:r,draggableNodes:m,droppableContainers:g,measuringConfiguration:w}),H=X?y.setRef:void 0;return B.createElement(J3,null,B.createElement(Y3,{animation:L},d&&N?B.createElement(Q3,{key:N,id:d.id,ref:H,as:l,activatorEvent:u,adjustScale:e,className:a,transition:s,rect:X,style:{zIndex:c,...i},transform:z},n):null))});/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */const{entries:uM,setPrototypeOf:gS,isFrozen:o4,getPrototypeOf:l4,getOwnPropertyDescriptor:a4}=Object;let{freeze:Ur,seal:Li,create:f0}=Object,{apply:h0,construct:p0}=typeof Reflect<"u"&&Reflect;Ur||(Ur=function(e){return e});Li||(Li=function(e){return e});h0||(h0=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:xh;gS&&gS(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(o4(e)||(e[r]=s),i=s)}t[i]=!0}return t}function p4(t){for(let e=0;e/gm),w4=Li(/\$\{[\w\W]*/gm),b4=Li(/^data-[\-\w.\u00B7-\uFFFF]+$/),x4=Li(/^aria-[\-\w]+$/),dM=Li(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),k4=Li(/^(?:\w+script|data):/i),S4=Li(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),fM=Li(/^html$/i),C4=Li(/^[a-z][.\w]*(-[.\w]+)+$/i);var kS=Object.freeze({__proto__:null,ARIA_ATTR:x4,ATTR_WHITESPACE:S4,CUSTOM_ELEMENT:C4,DATA_ATTR:b4,DOCTYPE_NAME:fM,ERB_EXPR:v4,IS_ALLOWED_URI:dM,IS_SCRIPT_OR_DATA:k4,MUSTACHE_EXPR:y4,TMPLIT_EXPR:w4});const iu={element:1,text:3,progressingInstruction:7,comment:8,document:9},E4=function(){return typeof window>"u"?null:window},N4=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},SS=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function hM(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E4();const e=$=>hM($);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==iu.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:a,NodeFilter:c,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=t,m=a.prototype,g=ru(m,"cloneNode"),y=ru(m,"remove"),v=ru(m,"nextSibling"),w=ru(m,"childNodes"),x=ru(m,"parentNode");if(typeof o=="function"){const $=n.createElement("template");$.content&&$.content.ownerDocument&&(n=$.content.ownerDocument)}let E,k="";const{implementation:M,createNodeIterator:N,createDocumentFragment:z,getElementsByTagName:X}=n,{importNode:L}=r;let H=SS();e.isSupported=typeof uM=="function"&&typeof x=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:W,ERB_EXPR:te,TMPLIT_EXPR:ce,DATA_ATTR:ue,ARIA_ATTR:Ae,IS_SCRIPT_OR_DATA:me,ATTR_WHITESPACE:q,CUSTOM_ELEMENT:se}=kS;let{IS_ALLOWED_URI:xe}=kS,Me=null;const Q=qt({},[...vS,...yy,...vy,...wy,...wS]);let Je=null;const _t=qt({},[...bS,...by,...xS,...Ff]);let J=Object.seal(f0(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),at=null,$t=null;const ct=Object.seal(f0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let nt=!0,At=!0,Vt=!1,wt=!0,ae=!1,Ee=!0,Ke=!1,ze=!1,Pe=!1,it=!1,ot=!1,xt=!1,oe=!0,Ye=!1;const Ge="user-content-";let K=!0,ge=!1,De={},Be=null;const Le=qt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let j=null;const G=qt({},["audio","video","img","source","image","track"]);let de=null;const je=qt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ue="http://www.w3.org/1998/Math/MathML",We="http://www.w3.org/2000/svg",Se="http://www.w3.org/1999/xhtml";let Xe=Se,Tt=!1,rt=null;const Wt=qt({},[Ue,We,Se],my);let Mt=qt({},["mi","mo","mn","ms","mtext"]),dn=qt({},["annotation-xml"]);const It=qt({},["title","style","font","a","script"]);let Ot=null;const tn=["application/xhtml+xml","text/html"],ee="text/html";let re=null,Oe=null;const Ze=n.createElement("form"),fe=function(S){return S instanceof RegExp||S instanceof Function},Ce=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Oe&&Oe===S)){if((!S||typeof S!="object")&&(S={}),S=ps(S),Ot=tn.indexOf(S.PARSER_MEDIA_TYPE)===-1?ee:S.PARSER_MEDIA_TYPE,re=Ot==="application/xhtml+xml"?my:xh,Me=Vi(S,"ALLOWED_TAGS")?qt({},S.ALLOWED_TAGS,re):Q,Je=Vi(S,"ALLOWED_ATTR")?qt({},S.ALLOWED_ATTR,re):_t,rt=Vi(S,"ALLOWED_NAMESPACES")?qt({},S.ALLOWED_NAMESPACES,my):Wt,de=Vi(S,"ADD_URI_SAFE_ATTR")?qt(ps(je),S.ADD_URI_SAFE_ATTR,re):je,j=Vi(S,"ADD_DATA_URI_TAGS")?qt(ps(G),S.ADD_DATA_URI_TAGS,re):G,Be=Vi(S,"FORBID_CONTENTS")?qt({},S.FORBID_CONTENTS,re):Le,at=Vi(S,"FORBID_TAGS")?qt({},S.FORBID_TAGS,re):ps({}),$t=Vi(S,"FORBID_ATTR")?qt({},S.FORBID_ATTR,re):ps({}),De=Vi(S,"USE_PROFILES")?S.USE_PROFILES:!1,nt=S.ALLOW_ARIA_ATTR!==!1,At=S.ALLOW_DATA_ATTR!==!1,Vt=S.ALLOW_UNKNOWN_PROTOCOLS||!1,wt=S.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ae=S.SAFE_FOR_TEMPLATES||!1,Ee=S.SAFE_FOR_XML!==!1,Ke=S.WHOLE_DOCUMENT||!1,it=S.RETURN_DOM||!1,ot=S.RETURN_DOM_FRAGMENT||!1,xt=S.RETURN_TRUSTED_TYPE||!1,Pe=S.FORCE_BODY||!1,oe=S.SANITIZE_DOM!==!1,Ye=S.SANITIZE_NAMED_PROPS||!1,K=S.KEEP_CONTENT!==!1,ge=S.IN_PLACE||!1,xe=S.ALLOWED_URI_REGEXP||dM,Xe=S.NAMESPACE||Se,Mt=S.MATHML_TEXT_INTEGRATION_POINTS||Mt,dn=S.HTML_INTEGRATION_POINTS||dn,J=S.CUSTOM_ELEMENT_HANDLING||{},S.CUSTOM_ELEMENT_HANDLING&&fe(S.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=S.CUSTOM_ELEMENT_HANDLING.tagNameCheck),S.CUSTOM_ELEMENT_HANDLING&&fe(S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),S.CUSTOM_ELEMENT_HANDLING&&typeof S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ae&&(At=!1),ot&&(it=!0),De&&(Me=qt({},wS),Je=[],De.html===!0&&(qt(Me,vS),qt(Je,bS)),De.svg===!0&&(qt(Me,yy),qt(Je,by),qt(Je,Ff)),De.svgFilters===!0&&(qt(Me,vy),qt(Je,by),qt(Je,Ff)),De.mathMl===!0&&(qt(Me,wy),qt(Je,xS),qt(Je,Ff))),S.ADD_TAGS&&(typeof S.ADD_TAGS=="function"?ct.tagCheck=S.ADD_TAGS:(Me===Q&&(Me=ps(Me)),qt(Me,S.ADD_TAGS,re))),S.ADD_ATTR&&(typeof S.ADD_ATTR=="function"?ct.attributeCheck=S.ADD_ATTR:(Je===_t&&(Je=ps(Je)),qt(Je,S.ADD_ATTR,re))),S.ADD_URI_SAFE_ATTR&&qt(de,S.ADD_URI_SAFE_ATTR,re),S.FORBID_CONTENTS&&(Be===Le&&(Be=ps(Be)),qt(Be,S.FORBID_CONTENTS,re)),S.ADD_FORBID_CONTENTS&&(Be===Le&&(Be=ps(Be)),qt(Be,S.ADD_FORBID_CONTENTS,re)),K&&(Me["#text"]=!0),Ke&&qt(Me,["html","head","body"]),Me.table&&(qt(Me,["tbody"]),delete at.tbody),S.TRUSTED_TYPES_POLICY){if(typeof S.TRUSTED_TYPES_POLICY.createHTML!="function")throw nu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof S.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');E=S.TRUSTED_TYPES_POLICY,k=E.createHTML("")}else E===void 0&&(E=N4(p,i)),E!==null&&typeof k=="string"&&(k=E.createHTML(""));Ur&&Ur(S),Oe=S}},Fe=qt({},[...yy,...vy,...m4]),ut=qt({},[...wy,...g4]),zt=function(S){let V=x(S);(!V||!V.tagName)&&(V={namespaceURI:Xe,tagName:"template"});const pe=xh(S.tagName),tt=xh(V.tagName);return rt[S.namespaceURI]?S.namespaceURI===We?V.namespaceURI===Se?pe==="svg":V.namespaceURI===Ue?pe==="svg"&&(tt==="annotation-xml"||Mt[tt]):!!Fe[pe]:S.namespaceURI===Ue?V.namespaceURI===Se?pe==="math":V.namespaceURI===We?pe==="math"&&dn[tt]:!!ut[pe]:S.namespaceURI===Se?V.namespaceURI===We&&!dn[tt]||V.namespaceURI===Ue&&!Mt[tt]?!1:!ut[pe]&&(It[pe]||!Fe[pe]):!!(Ot==="application/xhtml+xml"&&rt[S.namespaceURI]):!1},kt=function(S){eu(e.removed,{element:S});try{x(S).removeChild(S)}catch{y(S)}},Jt=function(S,V){try{eu(e.removed,{attribute:V.getAttributeNode(S),from:V})}catch{eu(e.removed,{attribute:null,from:V})}if(V.removeAttribute(S),S==="is")if(it||ot)try{kt(V)}catch{}else try{V.setAttribute(S,"")}catch{}},jt=function(S){let V=null,pe=null;if(Pe)S=""+S;else{const Kt=gy(S,/^[\r\n\t ]+/);pe=Kt&&Kt[0]}Ot==="application/xhtml+xml"&&Xe===Se&&(S=''+S+"");const tt=E?E.createHTML(S):S;if(Xe===Se)try{V=new f().parseFromString(tt,Ot)}catch{}if(!V||!V.documentElement){V=M.createDocument(Xe,"template",null);try{V.documentElement.innerHTML=Tt?k:tt}catch{}}const Ft=V.body||V.documentElement;return S&&pe&&Ft.insertBefore(n.createTextNode(pe),Ft.childNodes[0]||null),Xe===Se?X.call(V,Ke?"html":"body")[0]:Ke?V.documentElement:Ft},fn=function(S){return N.call(S.ownerDocument||S,S,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},wn=function(S){return S instanceof d&&(typeof S.nodeName!="string"||typeof S.textContent!="string"||typeof S.removeChild!="function"||!(S.attributes instanceof u)||typeof S.removeAttribute!="function"||typeof S.setAttribute!="function"||typeof S.namespaceURI!="string"||typeof S.insertBefore!="function"||typeof S.hasChildNodes!="function")},nn=function(S){return typeof l=="function"&&S instanceof l};function rn($,S,V){zf($,pe=>{pe.call(e,S,V,Oe)})}const Pr=function(S){let V=null;if(rn(H.beforeSanitizeElements,S,null),wn(S))return kt(S),!0;const pe=re(S.nodeName);if(rn(H.uponSanitizeElement,S,{tagName:pe,allowedTags:Me}),Ee&&S.hasChildNodes()&&!nn(S.firstElementChild)&&Lr(/<[/\w!]/g,S.innerHTML)&&Lr(/<[/\w!]/g,S.textContent)||S.nodeType===iu.progressingInstruction||Ee&&S.nodeType===iu.comment&&Lr(/<[/\w]/g,S.data))return kt(S),!0;if(!(ct.tagCheck instanceof Function&&ct.tagCheck(pe))&&(!Me[pe]||at[pe])){if(!at[pe]&&U(pe)&&(J.tagNameCheck instanceof RegExp&&Lr(J.tagNameCheck,pe)||J.tagNameCheck instanceof Function&&J.tagNameCheck(pe)))return!1;if(K&&!Be[pe]){const tt=x(S)||S.parentNode,Ft=w(S)||S.childNodes;if(Ft&&tt){const Kt=Ft.length;for(let Zt=Kt-1;Zt>=0;--Zt){const $n=g(Ft[Zt],!0);$n.__removalCount=(S.__removalCount||0)+1,tt.insertBefore($n,v(S))}}}return kt(S),!0}return S instanceof a&&!zt(S)||(pe==="noscript"||pe==="noembed"||pe==="noframes")&&Lr(/<\/no(script|embed|frames)/i,S.innerHTML)?(kt(S),!0):(ae&&S.nodeType===iu.text&&(V=S.textContent,zf([W,te,ce],tt=>{V=tu(V,tt," ")}),S.textContent!==V&&(eu(e.removed,{element:S.cloneNode()}),S.textContent=V)),rn(H.afterSanitizeElements,S,null),!1)},R=function(S,V,pe){if(oe&&(V==="id"||V==="name")&&(pe in n||pe in Ze))return!1;if(!(At&&!$t[V]&&Lr(ue,V))){if(!(nt&&Lr(Ae,V))){if(!(ct.attributeCheck instanceof Function&&ct.attributeCheck(V,S))){if(!Je[V]||$t[V]){if(!(U(S)&&(J.tagNameCheck instanceof RegExp&&Lr(J.tagNameCheck,S)||J.tagNameCheck instanceof Function&&J.tagNameCheck(S))&&(J.attributeNameCheck instanceof RegExp&&Lr(J.attributeNameCheck,V)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(V,S))||V==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&Lr(J.tagNameCheck,pe)||J.tagNameCheck instanceof Function&&J.tagNameCheck(pe))))return!1}else if(!de[V]){if(!Lr(xe,tu(pe,q,""))){if(!((V==="src"||V==="xlink:href"||V==="href")&&S!=="script"&&d4(pe,"data:")===0&&j[S])){if(!(Vt&&!Lr(me,tu(pe,q,"")))){if(pe)return!1}}}}}}}return!0},U=function(S){return S!=="annotation-xml"&&gy(S,se)},Y=function(S){rn(H.beforeSanitizeAttributes,S,null);const{attributes:V}=S;if(!V||wn(S))return;const pe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Je,forceKeepAttr:void 0};let tt=V.length;for(;tt--;){const Ft=V[tt],{name:Kt,namespaceURI:Zt,value:$n}=Ft,sn=re(Kt),A=$n;let ne=Kt==="value"?A:f4(A);if(pe.attrName=sn,pe.attrValue=ne,pe.keepAttr=!0,pe.forceKeepAttr=void 0,rn(H.uponSanitizeAttribute,S,pe),ne=pe.attrValue,Ye&&(sn==="id"||sn==="name")&&(Jt(Kt,S),ne=Ge+ne),Ee&&Lr(/((--!?|])>)|<\/(style|title|textarea)/i,ne)){Jt(Kt,S);continue}if(sn==="attributename"&&gy(ne,"href")){Jt(Kt,S);continue}if(pe.forceKeepAttr)continue;if(!pe.keepAttr){Jt(Kt,S);continue}if(!wt&&Lr(/\/>/i,ne)){Jt(Kt,S);continue}ae&&zf([W,te,ce],Z=>{ne=tu(ne,Z," ")});const we=re(S.nodeName);if(!R(we,sn,ne)){Jt(Kt,S);continue}if(E&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Zt)switch(p.getAttributeType(we,sn)){case"TrustedHTML":{ne=E.createHTML(ne);break}case"TrustedScriptURL":{ne=E.createScriptURL(ne);break}}if(ne!==A)try{Zt?S.setAttributeNS(Zt,Kt,ne):S.setAttribute(Kt,ne),wn(S)?kt(S):yS(e.removed)}catch{Jt(Kt,S)}}rn(H.afterSanitizeAttributes,S,null)},he=function $(S){let V=null;const pe=fn(S);for(rn(H.beforeSanitizeShadowDOM,S,null);V=pe.nextNode();)rn(H.uponSanitizeShadowNode,V,null),Pr(V),Y(V),V.content instanceof s&&$(V.content);rn(H.afterSanitizeShadowDOM,S,null)};return e.sanitize=function($){let S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},V=null,pe=null,tt=null,Ft=null;if(Tt=!$,Tt&&($=""),typeof $!="string"&&!nn($))if(typeof $.toString=="function"){if($=$.toString(),typeof $!="string")throw nu("dirty is not a string, aborting")}else throw nu("toString is not a function");if(!e.isSupported)return $;if(ze||Ce(S),e.removed=[],typeof $=="string"&&(ge=!1),ge){if($.nodeName){const $n=re($.nodeName);if(!Me[$n]||at[$n])throw nu("root node is forbidden and cannot be sanitized in-place")}}else if($ instanceof l)V=jt(""),pe=V.ownerDocument.importNode($,!0),pe.nodeType===iu.element&&pe.nodeName==="BODY"||pe.nodeName==="HTML"?V=pe:V.appendChild(pe);else{if(!it&&!ae&&!Ke&&$.indexOf("<")===-1)return E&&xt?E.createHTML($):$;if(V=jt($),!V)return it?null:xt?k:""}V&&Pe&&kt(V.firstChild);const Kt=fn(ge?$:V);for(;tt=Kt.nextNode();)Pr(tt),Y(tt),tt.content instanceof s&&he(tt.content);if(ge)return $;if(it){if(ot)for(Ft=z.call(V.ownerDocument);V.firstChild;)Ft.appendChild(V.firstChild);else Ft=V;return(Je.shadowroot||Je.shadowrootmode)&&(Ft=L.call(r,Ft,!0)),Ft}let Zt=Ke?V.outerHTML:V.innerHTML;return Ke&&Me["!doctype"]&&V.ownerDocument&&V.ownerDocument.doctype&&V.ownerDocument.doctype.name&&Lr(fM,V.ownerDocument.doctype.name)&&(Zt=" -`+Zt),ae&&zf([W,te,ce],$n=>{Zt=tu(Zt,$n," ")}),E&&xt?E.createHTML(Zt):Zt},e.setConfig=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ce($),ze=!0},e.clearConfig=function(){Oe=null,ze=!1},e.isValidAttribute=function($,S,V){Oe||Ce({});const pe=re($),tt=re(S);return R(pe,tt,V)},e.addHook=function($,S){typeof S=="function"&&eu(H[$],S)},e.removeHook=function($,S){if(S!==void 0){const V=c4(H[$],S);return V===-1?void 0:u4(H[$],V,1)[0]}return yS(H[$])},e.removeHooks=function($){H[$]=[]},e.removeAllHooks=function(){H=SS()},e}var ka=hM(),pM={exports:{}},mM={};/** + `},__={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function z_(t){let{announcements:e=__,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=L_}=t;const{announce:s,announcement:o}=O_(),l=Wm("DndLiveRegion"),[a,c]=b.useState(!1);if(b.useEffect(()=>{c(!0)},[]),j_(b.useMemo(()=>({onDragStart(d){let{active:f}=d;s(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&s(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;s(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;s(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;s(e.onDragCancel({active:f,over:p}))}}),[s,e])),!a)return null;const u=B.createElement(B.Fragment,null,B.createElement(R_,{id:r,value:i.draggable}),B.createElement(D_,{id:l,announcement:o}));return n?zn.createPortal(u,n):u}var Xn;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Xn||(Xn={}));function fp(){}function iS(t,e){return b.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function F_(){for(var t=arguments.length,e=new Array(t),n=0;n[...e].filter(r=>r!=null),[...e])}const ts=Object.freeze({x:0,y:0});function $_(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function B_(t,e){const n=dp(t);if(!n)return"0 0";const r={x:(n.x-e.left)/e.width*100,y:(n.y-e.top)/e.height*100};return r.x+"% "+r.y+"%"}function U_(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function H_(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function V_(t){let{left:e,top:n,height:r,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function W_(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function K_(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),i=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=i-r,l=s-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const a=K_(l,e);a>0&&i.push({id:o,data:{droppableContainer:s,value:a}})}}return i.sort(H_)};function q_(t,e){const{top:n,left:r,bottom:i,right:s}=e;return n<=t.y&&t.y<=i&&r<=t.x&&t.x<=s}const J_=t=>{let{droppableContainers:e,droppableRects:n,pointerCoordinates:r}=t;if(!r)return[];const i=[];for(const s of e){const{id:o}=s,l=n.get(o);if(l&&q_(r,l)){const c=V_(l).reduce((d,f)=>d+$_(r,f),0),u=Number((c/4).toFixed(4));i.push({id:o,data:{droppableContainer:s,value:u}})}}return i.sort(U_)};function G_(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function WA(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:ts}function X_(t){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),s=1;s({...o,top:o.top+t*l.y,bottom:o.bottom+t*l.y,left:o.left+t*l.x,right:o.right+t*l.x}),{...n})}}const Q_=X_(1);function KA(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Z_(t,e,n){const r=KA(e);if(!r)return t;const{scaleX:i,scaleY:s,x:o,y:l}=r,a=t.left-o-(1-i)*parseFloat(n),c=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),u=i?t.width/i:t.width,d=s?t.height/s:t.height;return{width:u,height:d,top:c,right:a+u,bottom:c+d,left:a}}const e3={ignoreTransform:!1};function Kd(t,e){e===void 0&&(e=e3);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:c,transformOrigin:u}=qr(t).getComputedStyle(t);c&&(n=Z_(n,c,u))}const{top:r,left:i,width:s,height:o,bottom:l,right:a}=n;return{top:r,left:i,width:s,height:o,bottom:l,right:a}}function sS(t){return Kd(t,{ignoreTransform:!0})}function t3(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function n3(t,e){return e===void 0&&(e=qr(t).getComputedStyle(t)),e.position==="fixed"}function r3(t,e){e===void 0&&(e=qr(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const s=e[i];return typeof s=="string"?n.test(s):!1})}function Tb(t,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Eb(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Vd(i)||UA(i)||n.includes(i))return n;const s=qr(t).getComputedStyle(i);return i!==t&&r3(i,s)&&n.push(i),n3(i,s)?n:r(i.parentNode)}return t?r(t):n}function YA(t){const[e]=Tb(t,1);return e??null}function fy(t){return!Hm||!t?null:Dc(t)?t:Cb(t)?Eb(t)||t===Oc(t).scrollingElement?window:Vd(t)?t:null:null}function qA(t){return Dc(t)?t.scrollX:t.scrollLeft}function JA(t){return Dc(t)?t.scrollY:t.scrollTop}function c0(t){return{x:qA(t),y:JA(t)}}var sr;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(sr||(sr={}));function GA(t){return!Hm||!t?!1:t===document.scrollingElement}function XA(t){const e={x:0,y:0},n=GA(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const i3={x:.2,y:.2};function s3(t,e,n,r,i){let{top:s,left:o,right:l,bottom:a}=n;r===void 0&&(r=10),i===void 0&&(i=i3);const{isTop:c,isBottom:u,isLeft:d,isRight:f}=XA(t),p={x:0,y:0},m={x:0,y:0},g={height:e.height*i.y,width:e.width*i.x};return!c&&s<=e.top+g.height?(p.y=sr.Backward,m.y=r*Math.abs((e.top+g.height-s)/g.height)):!u&&a>=e.bottom-g.height&&(p.y=sr.Forward,m.y=r*Math.abs((e.bottom-g.height-a)/g.height)),!f&&l>=e.right-g.width?(p.x=sr.Forward,m.x=r*Math.abs((e.right-g.width-l)/g.width)):!d&&o<=e.left+g.width&&(p.x=sr.Backward,m.x=r*Math.abs((e.left+g.width-o)/g.width)),{direction:p,speed:m}}function o3(t){if(t===document.scrollingElement){const{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}const{top:e,left:n,right:r,bottom:i}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:t.clientWidth,height:t.clientHeight}}function QA(t){return t.reduce((e,n)=>Ya(e,c0(n)),ts)}function l3(t){return t.reduce((e,n)=>e+qA(n),0)}function a3(t){return t.reduce((e,n)=>e+JA(n),0)}function ZA(t,e){if(e===void 0&&(e=Kd),!t)return;const{top:n,left:r,bottom:i,right:s}=e(t);YA(t)&&(i<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const c3=[["x",["left","right"],l3],["y",["top","bottom"],a3]];class Ab{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=Tb(n),i=QA(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of c3)for(const a of o)Object.defineProperty(this,a,{get:()=>{const c=l(r),u=i[s]-c;return this.rect[a]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Tu{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function u3(t){const{EventTarget:e}=qr(t);return t instanceof e?t:Oc(t)}function hy(t,e){const n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var ki;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(ki||(ki={}));function oS(t){t.preventDefault()}function d3(t){t.stopPropagation()}var gn;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(gn||(gn={}));const eM={start:[gn.Space,gn.Enter],cancel:[gn.Esc],end:[gn.Space,gn.Enter,gn.Tab]},f3=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case gn.Right:return{...n,x:n.x+25};case gn.Left:return{...n,x:n.x-25};case gn.Down:return{...n,y:n.y+25};case gn.Up:return{...n,y:n.y-25}}};class tM{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new Tu(Oc(n)),this.windowListeners=new Tu(qr(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ki.Resize,this.handleCancel),this.windowListeners.add(ki.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ki.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&ZA(r),n(ts)}handleKeyDown(e){if(Nb(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:s=eM,coordinateGetter:o=f3,scrollBehavior:l="smooth"}=i,{code:a}=e;if(s.end.includes(a)){this.handleEnd(e);return}if(s.cancel.includes(a)){this.handleCancel(e);return}const{collisionRect:c}=r.current,u=c?{x:c.left,y:c.top}:ts;this.referenceCoordinates||(this.referenceCoordinates=u);const d=o(e,{active:n,context:r.current,currentCoordinates:u});if(d){const f=up(d,u),p={x:0,y:0},{scrollableAncestors:m}=r.current;for(const g of m){const y=e.code,{isTop:v,isRight:w,isLeft:x,isBottom:E,maxScroll:k,minScroll:M}=XA(g),N=o3(g),z={x:Math.min(y===gn.Right?N.right-N.width/2:N.right,Math.max(y===gn.Right?N.left:N.left+N.width/2,d.x)),y:Math.min(y===gn.Down?N.bottom-N.height/2:N.bottom,Math.max(y===gn.Down?N.top:N.top+N.height/2,d.y))},X=y===gn.Right&&!w||y===gn.Left&&!x,L=y===gn.Down&&!E||y===gn.Up&&!v;if(X&&z.x!==d.x){const H=g.scrollLeft+f.x,W=y===gn.Right&&H<=k.x||y===gn.Left&&H>=M.x;if(W&&!f.y){g.scrollTo({left:H,behavior:l});return}W?p.x=g.scrollLeft-H:p.x=y===gn.Right?g.scrollLeft-k.x:g.scrollLeft-M.x,p.x&&g.scrollBy({left:-p.x,behavior:l});break}else if(L&&z.y!==d.y){const H=g.scrollTop+f.y,W=y===gn.Down&&H<=k.y||y===gn.Up&&H>=M.y;if(W&&!f.x){g.scrollTo({top:H,behavior:l});return}W?p.y=g.scrollTop-H:p.y=y===gn.Down?g.scrollTop-k.y:g.scrollTop-M.y,p.y&&g.scrollBy({top:-p.y,behavior:l});break}}this.handleMove(e,Ya(up(d,this.referenceCoordinates),p))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}tM.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=eM,onActivation:i}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(r.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),i==null||i({event:t.nativeEvent}),!0)}return!1}}];function lS(t){return!!(t&&"distance"in t)}function aS(t){return!!(t&&"delay"in t)}class Mb{constructor(e,n,r){var i;r===void 0&&(r=u3(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:s}=e,{target:o}=s;this.props=e,this.events=n,this.document=Oc(o),this.documentListeners=new Tu(this.document),this.listeners=new Tu(r),this.windowListeners=new Tu(qr(o)),this.initialCoordinates=(i=dp(s))!=null?i:ts,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ki.Resize,this.handleCancel),this.windowListeners.add(ki.DragStart,oS),this.windowListeners.add(ki.VisibilityChange,this.handleCancel),this.windowListeners.add(ki.ContextMenu,oS),this.documentListeners.add(ki.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(aS(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(lS(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ki.Click,d3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ki.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const a=(n=dp(e))!=null?n:ts,c=up(i,a);if(!r&&l){if(lS(l)){if(l.tolerance!=null&&hy(c,l.tolerance))return this.handleCancel();if(hy(c,l.distance))return this.handleStart()}if(aS(l)&&hy(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}e.cancelable&&e.preventDefault(),o(a)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===gn.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const h3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class nM extends Mb{constructor(e){const{event:n}=e,r=Oc(n.target);super(e,h3,r)}}nM.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const p3={move:{name:"mousemove"},end:{name:"mouseup"}};var u0;(function(t){t[t.RightClick=2]="RightClick"})(u0||(u0={}));class rM extends Mb{constructor(e){super(e,p3,Oc(e.event.target))}}rM.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===u0.RightClick?!1:(r==null||r({event:n}),!0)}}];const py={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class iM extends Mb{constructor(e){super(e,py)}static setup(){return window.addEventListener(py.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(py.move.name,e)};function e(){}}}iM.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r==null||r({event:n}),!0)}}];var Au;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(Au||(Au={}));var hp;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(hp||(hp={}));function m3(t){let{acceleration:e,activator:n=Au.Pointer,canScroll:r,draggingRect:i,enabled:s,interval:o=5,order:l=hp.TreeOrder,pointerCoordinates:a,scrollableAncestors:c,scrollableAncestorRects:u,delta:d,threshold:f}=t;const p=y3({delta:d,disabled:!s}),[m,g]=N_(),y=b.useRef({x:0,y:0}),v=b.useRef({x:0,y:0}),w=b.useMemo(()=>{switch(n){case Au.Pointer:return a?{top:a.y,bottom:a.y,left:a.x,right:a.x}:null;case Au.DraggableRect:return i}},[n,i,a]),x=b.useRef(null),E=b.useCallback(()=>{const M=x.current;if(!M)return;const N=y.current.x*v.current.x,z=y.current.y*v.current.y;M.scrollBy(N,z)},[]),k=b.useMemo(()=>l===hp.TreeOrder?[...c].reverse():c,[l,c]);b.useEffect(()=>{if(!s||!c.length||!w){g();return}for(const M of k){if((r==null?void 0:r(M))===!1)continue;const N=c.indexOf(M),z=u[N];if(!z)continue;const{direction:X,speed:L}=s3(M,z,w,e,f);for(const H of["x","y"])p[H][X[H]]||(L[H]=0,X[H]=0);if(L.x>0||L.y>0){g(),x.current=M,m(E,o),y.current=L,v.current=X;return}}y.current={x:0,y:0},v.current={x:0,y:0},g()},[e,E,r,g,s,o,JSON.stringify(w),JSON.stringify(p),m,c,k,u,JSON.stringify(f)])}const g3={x:{[sr.Backward]:!1,[sr.Forward]:!1},y:{[sr.Backward]:!1,[sr.Forward]:!1}};function y3(t){let{delta:e,disabled:n}=t;const r=cp(e);return Wd(i=>{if(n||!r||!i)return g3;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[sr.Backward]:i.x[sr.Backward]||s.x===-1,[sr.Forward]:i.x[sr.Forward]||s.x===1},y:{[sr.Backward]:i.y[sr.Backward]||s.y===-1,[sr.Forward]:i.y[sr.Forward]||s.y===1}}},[n,e,r])}function v3(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return Wd(i=>{var s;return e==null?null:(s=r??i)!=null?s:null},[r,e])}function w3(t,e){return b.useMemo(()=>t.reduce((n,r)=>{const{sensor:i}=r,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var dd;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(dd||(dd={}));var d0;(function(t){t.Optimized="optimized"})(d0||(d0={}));const cS=new Map;function b3(t,e){let{dragging:n,dependencies:r,config:i}=e;const[s,o]=b.useState(null),{frequency:l,measure:a,strategy:c}=i,u=b.useRef(t),d=y(),f=cd(d),p=b.useCallback(function(v){v===void 0&&(v=[]),!f.current&&o(w=>w===null?v:w.concat(v.filter(x=>!w.includes(x))))},[f]),m=b.useRef(null),g=Wd(v=>{if(d&&!n)return cS;if(!v||v===cS||u.current!==t||s!=null){const w=new Map;for(let x of t){if(!x)continue;if(s&&s.length>0&&!s.includes(x.id)&&x.rect.current){w.set(x.id,x.rect.current);continue}const E=x.node.current,k=E?new Ab(a(E),E):null;x.rect.current=k,k&&w.set(x.id,k)}return w}return v},[t,s,n,d,a]);return b.useEffect(()=>{u.current=t},[t]),b.useEffect(()=>{d||p()},[n,d]),b.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),b.useEffect(()=>{d||typeof l!="number"||m.current!==null||(m.current=setTimeout(()=>{p(),m.current=null},l))},[l,d,p,...r]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:s!=null};function y(){switch(c){case dd.Always:return!1;case dd.BeforeDragging:return n;default:return!n}}}function Ib(t,e){return Wd(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function x3(t,e){return Ib(t,e)}function k3(t){let{callback:e,disabled:n}=t;const r=Vm(e),i=b.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return b.useEffect(()=>()=>i==null?void 0:i.disconnect(),[i]),i}function Km(t){let{callback:e,disabled:n}=t;const r=Vm(e),i=b.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return b.useEffect(()=>()=>i==null?void 0:i.disconnect(),[i]),i}function S3(t){return new Ab(Kd(t),t)}function uS(t,e,n){e===void 0&&(e=S3);const[r,i]=b.useState(null);function s(){i(a=>{if(!t)return null;if(t.isConnected===!1){var c;return(c=a??n)!=null?c:null}const u=e(t);return JSON.stringify(a)===JSON.stringify(u)?a:u})}const o=k3({callback(a){if(t)for(const c of a){const{type:u,target:d}=c;if(u==="childList"&&d instanceof HTMLElement&&d.contains(t)){s();break}}}}),l=Km({callback:s});return lo(()=>{s(),t?(l==null||l.observe(t),o==null||o.observe(document.body,{childList:!0,subtree:!0})):(l==null||l.disconnect(),o==null||o.disconnect())},[t]),r}function C3(t){const e=Ib(t);return WA(t,e)}const dS=[];function E3(t){const e=b.useRef(t),n=Wd(r=>t?r&&r!==dS&&t&&e.current&&t.parentNode===e.current.parentNode?r:Tb(t):dS,[t]);return b.useEffect(()=>{e.current=t},[t]),n}function N3(t){const[e,n]=b.useState(null),r=b.useRef(t),i=b.useCallback(s=>{const o=fy(s.target);o&&n(l=>l?(l.set(o,c0(o)),new Map(l)):null)},[]);return b.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(a=>{const c=fy(a);return c?(c.addEventListener("scroll",i,{passive:!0}),[c,c0(c)]):null}).filter(a=>a!=null);n(l.length?new Map(l):null),r.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(a=>{const c=fy(a);c==null||c.removeEventListener("scroll",i)})}},[i,t]),b.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>Ya(s,o),ts):QA(t):ts,[t,e])}function fS(t,e){e===void 0&&(e=[]);const n=b.useRef(null);return b.useEffect(()=>{n.current=null},e),b.useEffect(()=>{const r=t!==ts;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?up(t,n.current):ts}function T3(t){b.useEffect(()=>{if(!Hm)return;const e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n==null||n()}},t.map(e=>{let{sensor:n}=e;return n}))}function A3(t,e){return b.useMemo(()=>t.reduce((n,r)=>{let{eventName:i,handler:s}=r;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function sM(t){return b.useMemo(()=>t?t3(t):null,[t])}const hS=[];function M3(t,e){e===void 0&&(e=Kd);const[n]=t,r=sM(n?qr(n):null),[i,s]=b.useState(hS);function o(){s(()=>t.length?t.map(a=>GA(a)?r:new Ab(e(a),a)):hS)}const l=Km({callback:o});return lo(()=>{l==null||l.disconnect(),o(),t.forEach(a=>l==null?void 0:l.observe(a))},[t]),i}function oM(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return Vd(e)?e:t}function I3(t){let{measure:e}=t;const[n,r]=b.useState(null),i=b.useCallback(c=>{for(const{target:u}of c)if(Vd(u)){r(d=>{const f=e(u);return d?{...d,width:f.width,height:f.height}:f});break}},[e]),s=Km({callback:i}),o=b.useCallback(c=>{const u=oM(c);s==null||s.disconnect(),u&&(s==null||s.observe(u)),r(u?e(u):null)},[e,s]),[l,a]=ap(o);return b.useMemo(()=>({nodeRef:l,rect:n,setRef:a}),[n,l,a])}const R3=[{sensor:nM,options:{}},{sensor:tM,options:{}}],D3={current:{}},bh={draggable:{measure:sS},droppable:{measure:sS,strategy:dd.WhileDragging,frequency:d0.Optimized},dragOverlay:{measure:Kd}};class Mu extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const O3={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Mu,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:fp},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:bh,measureDroppableContainers:fp,windowRect:null,measuringScheduled:!1},lM={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:fp,draggableNodes:new Map,over:null,measureDroppableContainers:fp},Yd=b.createContext(lM),aM=b.createContext(O3);function j3(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Mu}}}function P3(t,e){switch(e.type){case Xn.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Xn.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Xn.DragEnd:case Xn.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Xn.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Mu(t.droppable.containers);return i.set(r,n),{...t,droppable:{...t.droppable,containers:i}}}case Xn.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new Mu(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case Xn.UnregisterDroppable:{const{id:n,key:r}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;const s=new Mu(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function L3(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:i}=b.useContext(Yd),s=cp(r),o=cp(n==null?void 0:n.id);return b.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!Nb(s)||document.activeElement===s.target)return;const l=i.get(o);if(!l)return;const{activatorNode:a,node:c}=l;if(!a.current&&!c.current)return;requestAnimationFrame(()=>{for(const u of[a.current,c.current]){if(!u)continue;const d=M_(u);if(d){d.focus();break}}})}},[r,e,i,o,s]),null}function cM(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...r}),n):n}function _3(t){return b.useMemo(()=>({draggable:{...bh.draggable,...t==null?void 0:t.draggable},droppable:{...bh.droppable,...t==null?void 0:t.droppable},dragOverlay:{...bh.dragOverlay,...t==null?void 0:t.dragOverlay}}),[t==null?void 0:t.draggable,t==null?void 0:t.droppable,t==null?void 0:t.dragOverlay])}function z3(t){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=t;const s=b.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;lo(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const c=e==null?void 0:e.node.current;if(!c||c.isConnected===!1)return;const u=n(c),d=WA(u,r);if(o||(d.x=0),l||(d.y=0),s.current=!0,Math.abs(d.x)>0||Math.abs(d.y)>0){const f=YA(c);f&&f.scrollBy({top:d.y,left:d.x})}},[e,o,l,r,n])}const Ym=b.createContext({...ts,scaleX:1,scaleY:1});var Mo;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(Mo||(Mo={}));const F3=b.memo(function(e){var n,r,i,s;let{id:o,accessibility:l,autoScroll:a=!0,children:c,sensors:u=R3,collisionDetection:d=Y_,measuring:f,modifiers:p,...m}=e;const g=b.useReducer(P3,void 0,j3),[y,v]=g,[w,x]=P_(),[E,k]=b.useState(Mo.Uninitialized),M=E===Mo.Initialized,{draggable:{active:N,nodes:z,translate:X},droppable:{containers:L}}=y,H=N!=null?z.get(N):null,W=b.useRef({initial:null,translated:null}),te=b.useMemo(()=>{var It;return N!=null?{id:N,data:(It=H==null?void 0:H.data)!=null?It:D3,rect:W}:null},[N,H]),ue=b.useRef(null),[de,Ae]=b.useState(null),[me,q]=b.useState(null),se=cd(m,Object.values(m)),xe=Wm("DndDescribedBy",o),Me=b.useMemo(()=>L.getEnabled(),[L]),Q=_3(f),{droppableRects:Je,measureDroppableContainers:_t,measuringScheduled:J}=b3(Me,{dragging:M,dependencies:[X.x,X.y],config:Q.droppable}),at=v3(z,N),$t=b.useMemo(()=>me?dp(me):null,[me]),ct=dn(),nt=x3(at,Q.draggable.measure);z3({activeNode:N!=null?z.get(N):null,config:ct.layoutShiftCompensation,initialRect:nt,measure:Q.draggable.measure});const At=uS(at,Q.draggable.measure,nt),Bt=uS(at?at.parentElement:null),wt=b.useRef({activatorEvent:null,active:null,activeNode:at,collisionRect:null,collisions:null,droppableRects:Je,draggableNodes:z,draggingNode:null,draggingNodeRect:null,droppableContainers:L,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ce=L.getNodeFor((n=wt.current.over)==null?void 0:n.id),Ee=I3({measure:Q.dragOverlay.measure}),Ke=(r=Ee.nodeRef.current)!=null?r:at,ze=M?(i=Ee.rect)!=null?i:At:null,Pe=!!(Ee.nodeRef.current&&Ee.rect),it=C3(Pe?null:At),ot=sM(Ke?qr(Ke):null),xt=E3(M?ce??at:null),oe=M3(xt),Ye=cM(p,{transform:{x:X.x-it.x,y:X.y-it.y,scaleX:1,scaleY:1},activatorEvent:me,active:te,activeNodeRect:At,containerNodeRect:Bt,draggingNodeRect:ze,over:wt.current.over,overlayNodeRect:Ee.rect,scrollableAncestors:xt,scrollableAncestorRects:oe,windowRect:ot}),Ge=$t?Ya($t,X):null,Y=N3(xt),ge=fS(Y),De=fS(Y,[At]),Be=Ya(Ye,ge),Le=ze?Q_(ze,Ye):null,j=te&&Le?d({active:te,collisionRect:Le,droppableRects:Je,droppableContainers:Me,pointerCoordinates:Ge}):null,G=W_(j,"id"),[fe,je]=b.useState(null),Ue=Pe?Ye:Ya(Ye,De),We=G_(Ue,(s=fe==null?void 0:fe.rect)!=null?s:null,At),Se=b.useRef(null),Xe=b.useCallback((It,Ot)=>{let{sensor:tn,options:ee}=Ot;if(ue.current==null)return;const re=z.get(ue.current);if(!re)return;const Oe=It.nativeEvent,Ze=new tn({active:ue.current,activeNode:re,event:Oe,options:ee,context:wt,onAbort(Ce){if(!z.get(Ce))return;const{onDragAbort:ut}=se.current,zt={id:Ce};ut==null||ut(zt),w({type:"onDragAbort",event:zt})},onPending(Ce,Fe,ut,zt){if(!z.get(Ce))return;const{onDragPending:Jt}=se.current,jt={id:Ce,constraint:Fe,initialCoordinates:ut,offset:zt};Jt==null||Jt(jt),w({type:"onDragPending",event:jt})},onStart(Ce){const Fe=ue.current;if(Fe==null)return;const ut=z.get(Fe);if(!ut)return;const{onDragStart:zt}=se.current,kt={activatorEvent:Oe,active:{id:Fe,data:ut.data,rect:W}};zn.unstable_batchedUpdates(()=>{zt==null||zt(kt),k(Mo.Initializing),v({type:Xn.DragStart,initialCoordinates:Ce,active:Fe}),w({type:"onDragStart",event:kt}),Ae(Se.current),q(Oe)})},onMove(Ce){v({type:Xn.DragMove,coordinates:Ce})},onEnd:pe(Xn.DragEnd),onCancel:pe(Xn.DragCancel)});Se.current=Ze;function pe(Ce){return async function(){const{active:ut,collisions:zt,over:kt,scrollAdjustedTranslate:Jt}=wt.current;let jt=null;if(ut&&Jt){const{cancelDrop:fn}=se.current;jt={activatorEvent:Oe,active:ut,collisions:zt,delta:Jt,over:kt},Ce===Xn.DragEnd&&typeof fn=="function"&&await Promise.resolve(fn(jt))&&(Ce=Xn.DragCancel)}ue.current=null,zn.unstable_batchedUpdates(()=>{v({type:Ce}),k(Mo.Uninitialized),je(null),Ae(null),q(null),Se.current=null;const fn=Ce===Xn.DragEnd?"onDragEnd":"onDragCancel";if(jt){const wn=se.current[fn];wn==null||wn(jt),w({type:fn,event:jt})}})}}},[z]),Tt=b.useCallback((It,Ot)=>(tn,ee)=>{const re=tn.nativeEvent,Oe=z.get(ee);if(ue.current!==null||!Oe||re.dndKit||re.defaultPrevented)return;const Ze={active:Oe};It(tn,Ot.options,Ze)===!0&&(re.dndKit={capturedBy:Ot.sensor},ue.current=ee,Xe(tn,Ot))},[z,Xe]),rt=w3(u,Tt);T3(u),lo(()=>{At&&E===Mo.Initializing&&k(Mo.Initialized)},[At,E]),b.useEffect(()=>{const{onDragMove:It}=se.current,{active:Ot,activatorEvent:tn,collisions:ee,over:re}=wt.current;if(!Ot||!tn)return;const Oe={active:Ot,activatorEvent:tn,collisions:ee,delta:{x:Be.x,y:Be.y},over:re};zn.unstable_batchedUpdates(()=>{It==null||It(Oe),w({type:"onDragMove",event:Oe})})},[Be.x,Be.y]),b.useEffect(()=>{const{active:It,activatorEvent:Ot,collisions:tn,droppableContainers:ee,scrollAdjustedTranslate:re}=wt.current;if(!It||ue.current==null||!Ot||!re)return;const{onDragOver:Oe}=se.current,Ze=ee.get(G),pe=Ze&&Ze.rect.current?{id:Ze.id,rect:Ze.rect.current,data:Ze.data,disabled:Ze.disabled}:null,Ce={active:It,activatorEvent:Ot,collisions:tn,delta:{x:re.x,y:re.y},over:pe};zn.unstable_batchedUpdates(()=>{je(pe),Oe==null||Oe(Ce),w({type:"onDragOver",event:Ce})})},[G]),lo(()=>{wt.current={activatorEvent:me,active:te,activeNode:at,collisionRect:Le,collisions:j,droppableRects:Je,draggableNodes:z,draggingNode:Ke,draggingNodeRect:ze,droppableContainers:L,over:fe,scrollableAncestors:xt,scrollAdjustedTranslate:Be},W.current={initial:ze,translated:Le}},[te,at,j,Le,z,Ke,ze,Je,L,fe,xt,Be]),m3({...ct,delta:X,draggingRect:Le,pointerCoordinates:Ge,scrollableAncestors:xt,scrollableAncestorRects:oe});const Wt=b.useMemo(()=>({active:te,activeNode:at,activeNodeRect:At,activatorEvent:me,collisions:j,containerNodeRect:Bt,dragOverlay:Ee,draggableNodes:z,droppableContainers:L,droppableRects:Je,over:fe,measureDroppableContainers:_t,scrollableAncestors:xt,scrollableAncestorRects:oe,measuringConfiguration:Q,measuringScheduled:J,windowRect:ot}),[te,at,At,me,j,Bt,Ee,z,L,Je,fe,_t,xt,oe,Q,J,ot]),Mt=b.useMemo(()=>({activatorEvent:me,activators:rt,active:te,activeNodeRect:At,ariaDescribedById:{draggable:xe},dispatch:v,draggableNodes:z,over:fe,measureDroppableContainers:_t}),[me,rt,te,At,v,xe,z,fe,_t]);return B.createElement(VA.Provider,{value:x},B.createElement(Yd.Provider,{value:Mt},B.createElement(aM.Provider,{value:Wt},B.createElement(Ym.Provider,{value:We},c)),B.createElement(L3,{disabled:(l==null?void 0:l.restoreFocus)===!1})),B.createElement(z_,{...l,hiddenTextDescribedById:xe}));function dn(){const It=(de==null?void 0:de.autoScrollEnabled)===!1,Ot=typeof a=="object"?a.enabled===!1:a===!1,tn=M&&!It&&!Ot;return typeof a=="object"?{...a,enabled:tn}:{enabled:tn}}}),$3=b.createContext(null),pS="button",B3="Draggable";function U3(t){let{id:e,data:n,disabled:r=!1,attributes:i}=t;const s=Wm(B3),{activators:o,activatorEvent:l,active:a,activeNodeRect:c,ariaDescribedById:u,draggableNodes:d,over:f}=b.useContext(Yd),{role:p=pS,roleDescription:m="draggable",tabIndex:g=0}=i??{},y=(a==null?void 0:a.id)===e,v=b.useContext(y?Ym:$3),[w,x]=ap(),[E,k]=ap(),M=A3(o,e),N=cd(n);lo(()=>(d.set(e,{id:e,key:s,node:w,activatorNode:E,data:N}),()=>{const X=d.get(e);X&&X.key===s&&d.delete(e)}),[d,e]);const z=b.useMemo(()=>({role:p,tabIndex:g,"aria-disabled":r,"aria-pressed":y&&p===pS?!0:void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[r,p,g,y,m,u.draggable]);return{active:a,activatorEvent:l,activeNodeRect:c,attributes:z,isDragging:y,listeners:r?void 0:M,node:w,over:f,setNodeRef:x,setActivatorNodeRef:k,transform:v}}function H3(){return b.useContext(aM)}const V3="Droppable",W3={timeout:25};function K3(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=t;const s=Wm(V3),{active:o,dispatch:l,over:a,measureDroppableContainers:c}=b.useContext(Yd),u=b.useRef({disabled:n}),d=b.useRef(!1),f=b.useRef(null),p=b.useRef(null),{disabled:m,updateMeasurementsFor:g,timeout:y}={...W3,...i},v=cd(g??r),w=b.useCallback(()=>{if(!d.current){d.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{c(Array.isArray(v.current)?v.current:[v.current]),p.current=null},y)},[y]),x=Km({callback:w,disabled:m||!o}),E=b.useCallback((z,X)=>{x&&(X&&(x.unobserve(X),d.current=!1),z&&x.observe(z))},[x]),[k,M]=ap(E),N=cd(e);return b.useEffect(()=>{!x||!k.current||(x.disconnect(),d.current=!1,x.observe(k.current))},[k,x]),b.useEffect(()=>(l({type:Xn.RegisterDroppable,element:{id:r,key:s,disabled:n,node:k,rect:f,data:N}}),()=>l({type:Xn.UnregisterDroppable,key:s,id:r})),[r]),b.useEffect(()=>{n!==u.current.disabled&&(l({type:Xn.SetDroppableDisabled,id:r,key:s,disabled:n}),u.current.disabled=n)},[r,s,n,l]),{active:o,rect:f,isOver:(a==null?void 0:a.id)===r,node:k,over:a,setNodeRef:M}}function Y3(t){let{animation:e,children:n}=t;const[r,i]=b.useState(null),[s,o]=b.useState(null),l=cp(n);return!n&&!r&&l&&i(l),lo(()=>{if(!s)return;const a=r==null?void 0:r.key,c=r==null?void 0:r.props.id;if(a==null||c==null){i(null);return}Promise.resolve(e(c,s)).then(()=>{i(null)})},[e,r,s]),B.createElement(B.Fragment,null,n,r?b.cloneElement(r,{ref:o}):null)}const q3={x:0,y:0,scaleX:1,scaleY:1};function J3(t){let{children:e}=t;return B.createElement(Yd.Provider,{value:lM},B.createElement(Ym.Provider,{value:q3},e))}const G3={position:"fixed",touchAction:"none"},X3=t=>Nb(t)?"transform 250ms ease":void 0,Q3=b.forwardRef((t,e)=>{let{as:n,activatorEvent:r,adjustScale:i,children:s,className:o,rect:l,style:a,transform:c,transition:u=X3}=t;if(!l)return null;const d=i?c:{...c,scaleX:1,scaleY:1},f={...G3,width:l.width,height:l.height,top:l.top,left:l.left,transform:ud.Transform.toString(d),transformOrigin:i&&r?B_(r,l):void 0,transition:typeof u=="function"?u(r):u,...a};return B.createElement(n,{className:o,style:f,ref:e},s)}),Z3=t=>e=>{let{active:n,dragOverlay:r}=e;const i={},{styles:s,className:o}=t;if(s!=null&&s.active)for(const[l,a]of Object.entries(s.active))a!==void 0&&(i[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,a));if(s!=null&&s.dragOverlay)for(const[l,a]of Object.entries(s.dragOverlay))a!==void 0&&r.node.style.setProperty(l,a);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(const[a,c]of Object.entries(i))n.node.style.setProperty(a,c);o!=null&&o.active&&n.node.classList.remove(o.active)}},e4=t=>{let{transform:{initial:e,final:n}}=t;return[{transform:ud.Transform.toString(e)},{transform:ud.Transform.toString(n)}]},t4={duration:250,easing:"ease",keyframes:e4,sideEffects:Z3({styles:{active:{opacity:"0"}}})};function n4(t){let{config:e,draggableNodes:n,droppableContainers:r,measuringConfiguration:i}=t;return Vm((s,o)=>{if(e===null)return;const l=n.get(s);if(!l)return;const a=l.node.current;if(!a)return;const c=oM(o);if(!c)return;const{transform:u}=qr(o).getComputedStyle(o),d=KA(u);if(!d)return;const f=typeof e=="function"?e:r4(e);return ZA(a,i.draggable.measure),f({active:{id:s,data:l.data,node:a,rect:i.draggable.measure(a)},draggableNodes:n,dragOverlay:{node:o,rect:i.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:i,transform:d})})}function r4(t){const{duration:e,easing:n,sideEffects:r,keyframes:i}={...t4,...t};return s=>{let{active:o,dragOverlay:l,transform:a,...c}=s;if(!e)return;const u={x:l.rect.left-o.rect.left,y:l.rect.top-o.rect.top},d={scaleX:a.scaleX!==1?o.rect.width*a.scaleX/l.rect.width:1,scaleY:a.scaleY!==1?o.rect.height*a.scaleY/l.rect.height:1},f={x:a.x-u.x,y:a.y-u.y,...d},p=i({...c,active:o,dragOverlay:l,transform:{initial:a,final:f}}),[m]=p,g=p[p.length-1];if(JSON.stringify(m)===JSON.stringify(g))return;const y=r==null?void 0:r({active:o,dragOverlay:l,...c}),v=l.node.animate(p,{duration:e,easing:n,fill:"forwards"});return new Promise(w=>{v.onfinish=()=>{y==null||y(),w()}})}}let mS=0;function i4(t){return b.useMemo(()=>{if(t!=null)return mS++,mS},[t])}const s4=B.memo(t=>{let{adjustScale:e=!1,children:n,dropAnimation:r,style:i,transition:s,modifiers:o,wrapperElement:l="div",className:a,zIndex:c=999}=t;const{activatorEvent:u,active:d,activeNodeRect:f,containerNodeRect:p,draggableNodes:m,droppableContainers:g,dragOverlay:y,over:v,measuringConfiguration:w,scrollableAncestors:x,scrollableAncestorRects:E,windowRect:k}=H3(),M=b.useContext(Ym),N=i4(d==null?void 0:d.id),z=cM(o,{activatorEvent:u,active:d,activeNodeRect:f,containerNodeRect:p,draggingNodeRect:y.rect,over:v,overlayNodeRect:y.rect,scrollableAncestors:x,scrollableAncestorRects:E,transform:M,windowRect:k}),X=Ib(f),L=n4({config:r,draggableNodes:m,droppableContainers:g,measuringConfiguration:w}),H=X?y.setRef:void 0;return B.createElement(J3,null,B.createElement(Y3,{animation:L},d&&N?B.createElement(Q3,{key:N,id:d.id,ref:H,as:l,activatorEvent:u,adjustScale:e,className:a,transition:s,rect:X,style:{zIndex:c,...i},transform:z},n):null))});/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */const{entries:uM,setPrototypeOf:gS,isFrozen:o4,getPrototypeOf:l4,getOwnPropertyDescriptor:a4}=Object;let{freeze:Ur,seal:Li,create:f0}=Object,{apply:h0,construct:p0}=typeof Reflect<"u"&&Reflect;Ur||(Ur=function(e){return e});Li||(Li=function(e){return e});h0||(h0=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:xh;gS&&gS(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(o4(e)||(e[r]=s),i=s)}t[i]=!0}return t}function p4(t){for(let e=0;e/gm),w4=Li(/\$\{[\w\W]*/gm),b4=Li(/^data-[\-\w.\u00B7-\uFFFF]+$/),x4=Li(/^aria-[\-\w]+$/),dM=Li(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),k4=Li(/^(?:\w+script|data):/i),S4=Li(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),fM=Li(/^html$/i),C4=Li(/^[a-z][.\w]*(-[.\w]+)+$/i);var kS=Object.freeze({__proto__:null,ARIA_ATTR:x4,ATTR_WHITESPACE:S4,CUSTOM_ELEMENT:C4,DATA_ATTR:b4,DOCTYPE_NAME:fM,ERB_EXPR:v4,IS_ALLOWED_URI:dM,IS_SCRIPT_OR_DATA:k4,MUSTACHE_EXPR:y4,TMPLIT_EXPR:w4});const iu={element:1,text:3,progressingInstruction:7,comment:8,document:9},E4=function(){return typeof window>"u"?null:window},N4=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},SS=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function hM(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E4();const e=$=>hM($);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==iu.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:a,NodeFilter:c,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=t,m=a.prototype,g=ru(m,"cloneNode"),y=ru(m,"remove"),v=ru(m,"nextSibling"),w=ru(m,"childNodes"),x=ru(m,"parentNode");if(typeof o=="function"){const $=n.createElement("template");$.content&&$.content.ownerDocument&&(n=$.content.ownerDocument)}let E,k="";const{implementation:M,createNodeIterator:N,createDocumentFragment:z,getElementsByTagName:X}=n,{importNode:L}=r;let H=SS();e.isSupported=typeof uM=="function"&&typeof x=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:W,ERB_EXPR:te,TMPLIT_EXPR:ue,DATA_ATTR:de,ARIA_ATTR:Ae,IS_SCRIPT_OR_DATA:me,ATTR_WHITESPACE:q,CUSTOM_ELEMENT:se}=kS;let{IS_ALLOWED_URI:xe}=kS,Me=null;const Q=qt({},[...vS,...yy,...vy,...wy,...wS]);let Je=null;const _t=qt({},[...bS,...by,...xS,...Ff]);let J=Object.seal(f0(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),at=null,$t=null;const ct=Object.seal(f0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let nt=!0,At=!0,Bt=!1,wt=!0,ce=!1,Ee=!0,Ke=!1,ze=!1,Pe=!1,it=!1,ot=!1,xt=!1,oe=!0,Ye=!1;const Ge="user-content-";let Y=!0,ge=!1,De={},Be=null;const Le=qt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let j=null;const G=qt({},["audio","video","img","source","image","track"]);let fe=null;const je=qt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ue="http://www.w3.org/1998/Math/MathML",We="http://www.w3.org/2000/svg",Se="http://www.w3.org/1999/xhtml";let Xe=Se,Tt=!1,rt=null;const Wt=qt({},[Ue,We,Se],my);let Mt=qt({},["mi","mo","mn","ms","mtext"]),dn=qt({},["annotation-xml"]);const It=qt({},["title","style","font","a","script"]);let Ot=null;const tn=["application/xhtml+xml","text/html"],ee="text/html";let re=null,Oe=null;const Ze=n.createElement("form"),pe=function(S){return S instanceof RegExp||S instanceof Function},Ce=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Oe&&Oe===S)){if((!S||typeof S!="object")&&(S={}),S=ps(S),Ot=tn.indexOf(S.PARSER_MEDIA_TYPE)===-1?ee:S.PARSER_MEDIA_TYPE,re=Ot==="application/xhtml+xml"?my:xh,Me=Vi(S,"ALLOWED_TAGS")?qt({},S.ALLOWED_TAGS,re):Q,Je=Vi(S,"ALLOWED_ATTR")?qt({},S.ALLOWED_ATTR,re):_t,rt=Vi(S,"ALLOWED_NAMESPACES")?qt({},S.ALLOWED_NAMESPACES,my):Wt,fe=Vi(S,"ADD_URI_SAFE_ATTR")?qt(ps(je),S.ADD_URI_SAFE_ATTR,re):je,j=Vi(S,"ADD_DATA_URI_TAGS")?qt(ps(G),S.ADD_DATA_URI_TAGS,re):G,Be=Vi(S,"FORBID_CONTENTS")?qt({},S.FORBID_CONTENTS,re):Le,at=Vi(S,"FORBID_TAGS")?qt({},S.FORBID_TAGS,re):ps({}),$t=Vi(S,"FORBID_ATTR")?qt({},S.FORBID_ATTR,re):ps({}),De=Vi(S,"USE_PROFILES")?S.USE_PROFILES:!1,nt=S.ALLOW_ARIA_ATTR!==!1,At=S.ALLOW_DATA_ATTR!==!1,Bt=S.ALLOW_UNKNOWN_PROTOCOLS||!1,wt=S.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ce=S.SAFE_FOR_TEMPLATES||!1,Ee=S.SAFE_FOR_XML!==!1,Ke=S.WHOLE_DOCUMENT||!1,it=S.RETURN_DOM||!1,ot=S.RETURN_DOM_FRAGMENT||!1,xt=S.RETURN_TRUSTED_TYPE||!1,Pe=S.FORCE_BODY||!1,oe=S.SANITIZE_DOM!==!1,Ye=S.SANITIZE_NAMED_PROPS||!1,Y=S.KEEP_CONTENT!==!1,ge=S.IN_PLACE||!1,xe=S.ALLOWED_URI_REGEXP||dM,Xe=S.NAMESPACE||Se,Mt=S.MATHML_TEXT_INTEGRATION_POINTS||Mt,dn=S.HTML_INTEGRATION_POINTS||dn,J=S.CUSTOM_ELEMENT_HANDLING||{},S.CUSTOM_ELEMENT_HANDLING&&pe(S.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(J.tagNameCheck=S.CUSTOM_ELEMENT_HANDLING.tagNameCheck),S.CUSTOM_ELEMENT_HANDLING&&pe(S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(J.attributeNameCheck=S.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),S.CUSTOM_ELEMENT_HANDLING&&typeof S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=S.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ce&&(At=!1),ot&&(it=!0),De&&(Me=qt({},wS),Je=[],De.html===!0&&(qt(Me,vS),qt(Je,bS)),De.svg===!0&&(qt(Me,yy),qt(Je,by),qt(Je,Ff)),De.svgFilters===!0&&(qt(Me,vy),qt(Je,by),qt(Je,Ff)),De.mathMl===!0&&(qt(Me,wy),qt(Je,xS),qt(Je,Ff))),S.ADD_TAGS&&(typeof S.ADD_TAGS=="function"?ct.tagCheck=S.ADD_TAGS:(Me===Q&&(Me=ps(Me)),qt(Me,S.ADD_TAGS,re))),S.ADD_ATTR&&(typeof S.ADD_ATTR=="function"?ct.attributeCheck=S.ADD_ATTR:(Je===_t&&(Je=ps(Je)),qt(Je,S.ADD_ATTR,re))),S.ADD_URI_SAFE_ATTR&&qt(fe,S.ADD_URI_SAFE_ATTR,re),S.FORBID_CONTENTS&&(Be===Le&&(Be=ps(Be)),qt(Be,S.FORBID_CONTENTS,re)),S.ADD_FORBID_CONTENTS&&(Be===Le&&(Be=ps(Be)),qt(Be,S.ADD_FORBID_CONTENTS,re)),Y&&(Me["#text"]=!0),Ke&&qt(Me,["html","head","body"]),Me.table&&(qt(Me,["tbody"]),delete at.tbody),S.TRUSTED_TYPES_POLICY){if(typeof S.TRUSTED_TYPES_POLICY.createHTML!="function")throw nu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof S.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');E=S.TRUSTED_TYPES_POLICY,k=E.createHTML("")}else E===void 0&&(E=N4(p,i)),E!==null&&typeof k=="string"&&(k=E.createHTML(""));Ur&&Ur(S),Oe=S}},Fe=qt({},[...yy,...vy,...m4]),ut=qt({},[...wy,...g4]),zt=function(S){let V=x(S);(!V||!V.tagName)&&(V={namespaceURI:Xe,tagName:"template"});const he=xh(S.tagName),tt=xh(V.tagName);return rt[S.namespaceURI]?S.namespaceURI===We?V.namespaceURI===Se?he==="svg":V.namespaceURI===Ue?he==="svg"&&(tt==="annotation-xml"||Mt[tt]):!!Fe[he]:S.namespaceURI===Ue?V.namespaceURI===Se?he==="math":V.namespaceURI===We?he==="math"&&dn[tt]:!!ut[he]:S.namespaceURI===Se?V.namespaceURI===We&&!dn[tt]||V.namespaceURI===Ue&&!Mt[tt]?!1:!ut[he]&&(It[he]||!Fe[he]):!!(Ot==="application/xhtml+xml"&&rt[S.namespaceURI]):!1},kt=function(S){eu(e.removed,{element:S});try{x(S).removeChild(S)}catch{y(S)}},Jt=function(S,V){try{eu(e.removed,{attribute:V.getAttributeNode(S),from:V})}catch{eu(e.removed,{attribute:null,from:V})}if(V.removeAttribute(S),S==="is")if(it||ot)try{kt(V)}catch{}else try{V.setAttribute(S,"")}catch{}},jt=function(S){let V=null,he=null;if(Pe)S=""+S;else{const Kt=gy(S,/^[\r\n\t ]+/);he=Kt&&Kt[0]}Ot==="application/xhtml+xml"&&Xe===Se&&(S=''+S+"");const tt=E?E.createHTML(S):S;if(Xe===Se)try{V=new f().parseFromString(tt,Ot)}catch{}if(!V||!V.documentElement){V=M.createDocument(Xe,"template",null);try{V.documentElement.innerHTML=Tt?k:tt}catch{}}const Ft=V.body||V.documentElement;return S&&he&&Ft.insertBefore(n.createTextNode(he),Ft.childNodes[0]||null),Xe===Se?X.call(V,Ke?"html":"body")[0]:Ke?V.documentElement:Ft},fn=function(S){return N.call(S.ownerDocument||S,S,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},wn=function(S){return S instanceof d&&(typeof S.nodeName!="string"||typeof S.textContent!="string"||typeof S.removeChild!="function"||!(S.attributes instanceof u)||typeof S.removeAttribute!="function"||typeof S.setAttribute!="function"||typeof S.namespaceURI!="string"||typeof S.insertBefore!="function"||typeof S.hasChildNodes!="function")},nn=function(S){return typeof l=="function"&&S instanceof l};function rn($,S,V){zf($,he=>{he.call(e,S,V,Oe)})}const Pr=function(S){let V=null;if(rn(H.beforeSanitizeElements,S,null),wn(S))return kt(S),!0;const he=re(S.nodeName);if(rn(H.uponSanitizeElement,S,{tagName:he,allowedTags:Me}),Ee&&S.hasChildNodes()&&!nn(S.firstElementChild)&&Lr(/<[/\w!]/g,S.innerHTML)&&Lr(/<[/\w!]/g,S.textContent)||S.nodeType===iu.progressingInstruction||Ee&&S.nodeType===iu.comment&&Lr(/<[/\w]/g,S.data))return kt(S),!0;if(!(ct.tagCheck instanceof Function&&ct.tagCheck(he))&&(!Me[he]||at[he])){if(!at[he]&&U(he)&&(J.tagNameCheck instanceof RegExp&&Lr(J.tagNameCheck,he)||J.tagNameCheck instanceof Function&&J.tagNameCheck(he)))return!1;if(Y&&!Be[he]){const tt=x(S)||S.parentNode,Ft=w(S)||S.childNodes;if(Ft&&tt){const Kt=Ft.length;for(let Zt=Kt-1;Zt>=0;--Zt){const $n=g(Ft[Zt],!0);$n.__removalCount=(S.__removalCount||0)+1,tt.insertBefore($n,v(S))}}}return kt(S),!0}return S instanceof a&&!zt(S)||(he==="noscript"||he==="noembed"||he==="noframes")&&Lr(/<\/no(script|embed|frames)/i,S.innerHTML)?(kt(S),!0):(ce&&S.nodeType===iu.text&&(V=S.textContent,zf([W,te,ue],tt=>{V=tu(V,tt," ")}),S.textContent!==V&&(eu(e.removed,{element:S.cloneNode()}),S.textContent=V)),rn(H.afterSanitizeElements,S,null),!1)},I=function(S,V,he){if(oe&&(V==="id"||V==="name")&&(he in n||he in Ze))return!1;if(!(At&&!$t[V]&&Lr(de,V))){if(!(nt&&Lr(Ae,V))){if(!(ct.attributeCheck instanceof Function&&ct.attributeCheck(V,S))){if(!Je[V]||$t[V]){if(!(U(S)&&(J.tagNameCheck instanceof RegExp&&Lr(J.tagNameCheck,S)||J.tagNameCheck instanceof Function&&J.tagNameCheck(S))&&(J.attributeNameCheck instanceof RegExp&&Lr(J.attributeNameCheck,V)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(V,S))||V==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&Lr(J.tagNameCheck,he)||J.tagNameCheck instanceof Function&&J.tagNameCheck(he))))return!1}else if(!fe[V]){if(!Lr(xe,tu(he,q,""))){if(!((V==="src"||V==="xlink:href"||V==="href")&&S!=="script"&&d4(he,"data:")===0&&j[S])){if(!(Bt&&!Lr(me,tu(he,q,"")))){if(he)return!1}}}}}}}return!0},U=function(S){return S!=="annotation-xml"&&gy(S,se)},K=function(S){rn(H.beforeSanitizeAttributes,S,null);const{attributes:V}=S;if(!V||wn(S))return;const he={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Je,forceKeepAttr:void 0};let tt=V.length;for(;tt--;){const Ft=V[tt],{name:Kt,namespaceURI:Zt,value:$n}=Ft,sn=re(Kt),A=$n;let ne=Kt==="value"?A:f4(A);if(he.attrName=sn,he.attrValue=ne,he.keepAttr=!0,he.forceKeepAttr=void 0,rn(H.uponSanitizeAttribute,S,he),ne=he.attrValue,Ye&&(sn==="id"||sn==="name")&&(Jt(Kt,S),ne=Ge+ne),Ee&&Lr(/((--!?|])>)|<\/(style|title|textarea)/i,ne)){Jt(Kt,S);continue}if(sn==="attributename"&&gy(ne,"href")){Jt(Kt,S);continue}if(he.forceKeepAttr)continue;if(!he.keepAttr){Jt(Kt,S);continue}if(!wt&&Lr(/\/>/i,ne)){Jt(Kt,S);continue}ce&&zf([W,te,ue],Z=>{ne=tu(ne,Z," ")});const we=re(S.nodeName);if(!I(we,sn,ne)){Jt(Kt,S);continue}if(E&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Zt)switch(p.getAttributeType(we,sn)){case"TrustedHTML":{ne=E.createHTML(ne);break}case"TrustedScriptURL":{ne=E.createScriptURL(ne);break}}if(ne!==A)try{Zt?S.setAttributeNS(Zt,Kt,ne):S.setAttribute(Kt,ne),wn(S)?kt(S):yS(e.removed)}catch{Jt(Kt,S)}}rn(H.afterSanitizeAttributes,S,null)},le=function $(S){let V=null;const he=fn(S);for(rn(H.beforeSanitizeShadowDOM,S,null);V=he.nextNode();)rn(H.uponSanitizeShadowNode,V,null),Pr(V),K(V),V.content instanceof s&&$(V.content);rn(H.afterSanitizeShadowDOM,S,null)};return e.sanitize=function($){let S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},V=null,he=null,tt=null,Ft=null;if(Tt=!$,Tt&&($=""),typeof $!="string"&&!nn($))if(typeof $.toString=="function"){if($=$.toString(),typeof $!="string")throw nu("dirty is not a string, aborting")}else throw nu("toString is not a function");if(!e.isSupported)return $;if(ze||Ce(S),e.removed=[],typeof $=="string"&&(ge=!1),ge){if($.nodeName){const $n=re($.nodeName);if(!Me[$n]||at[$n])throw nu("root node is forbidden and cannot be sanitized in-place")}}else if($ instanceof l)V=jt(""),he=V.ownerDocument.importNode($,!0),he.nodeType===iu.element&&he.nodeName==="BODY"||he.nodeName==="HTML"?V=he:V.appendChild(he);else{if(!it&&!ce&&!Ke&&$.indexOf("<")===-1)return E&&xt?E.createHTML($):$;if(V=jt($),!V)return it?null:xt?k:""}V&&Pe&&kt(V.firstChild);const Kt=fn(ge?$:V);for(;tt=Kt.nextNode();)Pr(tt),K(tt),tt.content instanceof s&&le(tt.content);if(ge)return $;if(it){if(ot)for(Ft=z.call(V.ownerDocument);V.firstChild;)Ft.appendChild(V.firstChild);else Ft=V;return(Je.shadowroot||Je.shadowrootmode)&&(Ft=L.call(r,Ft,!0)),Ft}let Zt=Ke?V.outerHTML:V.innerHTML;return Ke&&Me["!doctype"]&&V.ownerDocument&&V.ownerDocument.doctype&&V.ownerDocument.doctype.name&&Lr(fM,V.ownerDocument.doctype.name)&&(Zt=" +`+Zt),ce&&zf([W,te,ue],$n=>{Zt=tu(Zt,$n," ")}),E&&xt?E.createHTML(Zt):Zt},e.setConfig=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ce($),ze=!0},e.clearConfig=function(){Oe=null,ze=!1},e.isValidAttribute=function($,S,V){Oe||Ce({});const he=re($),tt=re(S);return I(he,tt,V)},e.addHook=function($,S){typeof S=="function"&&eu(H[$],S)},e.removeHook=function($,S){if(S!==void 0){const V=c4(H[$],S);return V===-1?void 0:u4(H[$],V,1)[0]}return yS(H[$])},e.removeHooks=function($){H[$]=[]},e.removeAllHooks=function(){H=SS()},e}var ka=hM(),pM={exports:{}},mM={};/** * @license React * use-sync-external-store-shim.production.js * @@ -134,7 +134,7 @@ img.ProseMirror-separator { display: block; }`;function T5(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(i),i}var ag=class extends p5{constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:o2,createMappablePosition:KB},this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:i,moved:s})=>this.options.onDrop(r,i,s)),this.on("paste",({event:r,slice:i})=>this.options.onPaste(r,i)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=KI(e,this.options.autofocus);this.editorState=Fa.create({doc:e,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(t){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(t),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const t=this.editorView.dom;t!=null&&t.editor&&delete t.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(t){console.warn("Failed to remove CSS element:",t)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=T5(N5,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,e=!0){this.setOptions({editable:t}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:t=>{this.editorState=t},dispatch:t=>{this.dispatchTransaction(t)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(t,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in t)return Reflect.get(t,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(t,e){const n=XI(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(i=>{const s=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(s))}),e.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var t,e;const r=[...this.options.enableCoreExtensions?[m2,d2.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),f2,y2,v2,b2,p2,w2,h2,x2.configure({direction:this.options.textDirection})].filter(i=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[i.name]!==!1:!0):[],...this.options.extensions].filter(i=>["extension","node","mark"].includes(i==null?void 0:i.type));this.extensionManager=new lg(r,this)}createCommandManager(){this.commandManager=new ng({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=D0(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(n=>n.name!=="collaboration"),this.createExtensionManager()}}),t=D0(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),i=n?this.extensionManager.dispatchTransaction(r):r;this.editorView=new HI(t,{...e,attributes:{role:"textbox",...e==null?void 0:e.attributes},dispatchTransaction:i,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const s=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(s),this.prependClass(),this.injectCSS();const o=this.view.dom;o.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(c=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(c)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),i=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!i)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const o=n.findLast(c=>c.getMeta("focus")||c.getMeta("blur")),l=o==null?void 0:o.getMeta("focus"),a=o==null?void 0:o.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),a&&this.emit("blur",{editor:this,event:a.event,transaction:o}),!(t.getMeta("preventUpdate")||!n.some(c=>c.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return n2(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return HB(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return nx(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=` -`,textSerializers:n={}}=t||{};return t2(this.state.doc,{blockSeparator:e,textSerializers:{...rx(this.schema),...n}})}get isEmpty(){return sg(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var t,e;return(e=(t=this.editorView)==null?void 0:t.isDestroyed)!=null?e:!0}$node(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t);return new E5(e,this)}get $doc(){return this.$pos(0)}};function yc(t){return new og({find:t.find,handler:({state:e,range:n,match:r})=>{const i=an(t.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=n.from+l.indexOf(o),u=c+o.length;if(ix(n.from,n.to,e.doc).filter(p=>p.mark.type.excluded.find(g=>g===t.type&&g!==p.mark.type)).filter(p=>p.to>c).length)return null;un.from&&s.delete(n.from+a,c);const f=n.from+a+o.length;s.addMark(n.from+a,f,t.type.create(i||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function A5(t){return new og({find:t.find,handler:({state:e,range:n,match:r})=>{const i=an(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const a=t.type.create(i);if(r[1]){const c=r[0].lastIndexOf(r[1]);let u=o+c;u>l?u=l:l=u+r[1].length;const d=r[0][r[0].length-1];s.insertText(d,o+r[0].length-1),s.replaceWith(u,l,a)}else if(r[0]){const c=t.type.isInline?o:o-1;s.insert(c,t.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function j0(t){return new og({find:t.find,handler:({state:e,range:n,match:r})=>{const i=e.doc.resolve(n.from),s=an(t.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,s)},undoable:t.undoable})}function vc(t){return new og({find:t.find,handler:({state:e,range:n,match:r,chain:i})=>{const s=an(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),a=o.doc.resolve(n.from).blockRange(),c=a&&jb(a,t.type,s);if(!c)return null;if(o.wrap(a,c),t.keepMarks&&t.editor){const{selection:d,storedMarks:f}=e,{splittableMarks:p}=t.editor.extensionManager,m=f||d.$to.parentOffset&&d.$from.marks();if(m){const g=m.filter(y=>p.includes(y.type.name));o.ensureMarks(g)}}if(t.keepAttributes){const d=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(d,s).run()}const u=o.doc.resolve(n.from-1).nodeBefore;u&&u.type===t.type&&vl(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,u))&&o.join(n.from-1)},undoable:t.undoable})}function M5(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof pt){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var I5={};Xb(I5,{createAtomBlockMarkdownSpec:()=>R5,createBlockMarkdownSpec:()=>D5,createInlineMarkdownSpec:()=>P5,parseAttributes:()=>lx,parseIndentedBlocks:()=>P0,renderNestedMarkdownContent:()=>cx,serializeAttributes:()=>ax});function lx(t){if(!(t!=null&&t.trim()))return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,c=>(n.push(c),`__QUOTED_${n.length-1}__`)),i=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const c=i.map(u=>u.trim().slice(1));e.class=c.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,c,u])=>{var d;const f=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),p=n[f];p&&(e[c]=p.slice(1,-1))});const a=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return a&&a.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function ax(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function R5(t){const{nodeName:e,name:n,parseAttributes:r=lx,serializeAttributes:i=ax,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,a=n||e,c=u=>{if(!l)return u;const d={};return l.forEach(f=>{f in u&&(d[f]=u[f])}),d};return{parseMarkdown:(u,d)=>{const f={...s,...u.attributes};return d.createNode(e,f,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;const f=new RegExp(`^:::${a}(?:\\s|$)`,"m"),p=(d=u.match(f))==null?void 0:d.index;return p!==void 0?p:-1},tokenize(u,d,f){const p=new RegExp(`^:::${a}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),m=u.match(p);if(!m)return;const g=m[1]||"",y=r(g);if(!o.find(w=>!(w in y)))return{type:e,raw:m[0],attributes:y}}},renderMarkdown:u=>{const d=c(u.attrs||{}),f=i(d),p=f?` {${f}}`:"";return`:::${a}${p} :::`}}}function D5(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=lx,serializeAttributes:s=ax,defaultAttributes:o={},content:l="block",allowedAttributes:a}=t,c=n||e,u=d=>{if(!a)return d;const f={};return a.forEach(p=>{p in d&&(f[p]=d[p])}),f};return{parseMarkdown:(d,f)=>{let p;if(r){const g=r(d);p=typeof g=="string"?[{type:"text",text:g}]:g}else l==="block"?p=f.parseChildren(d.tokens||[]):p=f.parseInline(d.tokens||[]);const m={...o,...d.attributes};return f.createNode(e,m,p)},markdownTokenizer:{name:e,level:"block",start(d){var f;const p=new RegExp(`^:::${c}`,"m"),m=(f=d.match(p))==null?void 0:f.index;return m!==void 0?m:-1},tokenize(d,f,p){var m;const g=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),y=d.match(g);if(!y)return;const[v,w=""]=y,x=i(w);let E=1;const k=v.length;let M="";const N=/^:::([\w-]*)(\s.*)?/gm,z=d.slice(k);for(N.lastIndex=0;;){const X=N.exec(z);if(X===null)break;const L=X.index,H=X[1];if(!((m=X[2])!=null&&m.endsWith(":::"))){if(H)E+=1;else if(E-=1,E===0){const W=z.slice(0,L);M=W.trim();const te=d.slice(0,k+L+X[0].length);let ce=[];if(M)if(l==="block")for(ce=p.blockTokens(W),ce.forEach(ue=>{ue.text&&(!ue.tokens||ue.tokens.length===0)&&(ue.tokens=p.inlineTokens(ue.text))});ce.length>0;){const ue=ce[ce.length-1];if(ue.type==="paragraph"&&(!ue.text||ue.text.trim()===""))ce.pop();else break}else ce=p.inlineTokens(M);return{type:e,raw:te,attributes:x,content:M,tokens:ce}}}}}},renderMarkdown:(d,f)=>{const p=u(d.attrs||{}),m=s(p),g=m?` {${m}}`:"",y=f.renderChildren(d.content||[],` +`,textSerializers:n={}}=t||{};return t2(this.state.doc,{blockSeparator:e,textSerializers:{...rx(this.schema),...n}})}get isEmpty(){return sg(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var t,e;return(e=(t=this.editorView)==null?void 0:t.isDestroyed)!=null?e:!0}$node(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t);return new E5(e,this)}get $doc(){return this.$pos(0)}};function yc(t){return new og({find:t.find,handler:({state:e,range:n,match:r})=>{const i=an(t.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=n.from+l.indexOf(o),u=c+o.length;if(ix(n.from,n.to,e.doc).filter(p=>p.mark.type.excluded.find(g=>g===t.type&&g!==p.mark.type)).filter(p=>p.to>c).length)return null;un.from&&s.delete(n.from+a,c);const f=n.from+a+o.length;s.addMark(n.from+a,f,t.type.create(i||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function A5(t){return new og({find:t.find,handler:({state:e,range:n,match:r})=>{const i=an(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const a=t.type.create(i);if(r[1]){const c=r[0].lastIndexOf(r[1]);let u=o+c;u>l?u=l:l=u+r[1].length;const d=r[0][r[0].length-1];s.insertText(d,o+r[0].length-1),s.replaceWith(u,l,a)}else if(r[0]){const c=t.type.isInline?o:o-1;s.insert(c,t.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function j0(t){return new og({find:t.find,handler:({state:e,range:n,match:r})=>{const i=e.doc.resolve(n.from),s=an(t.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,s)},undoable:t.undoable})}function vc(t){return new og({find:t.find,handler:({state:e,range:n,match:r,chain:i})=>{const s=an(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),a=o.doc.resolve(n.from).blockRange(),c=a&&jb(a,t.type,s);if(!c)return null;if(o.wrap(a,c),t.keepMarks&&t.editor){const{selection:d,storedMarks:f}=e,{splittableMarks:p}=t.editor.extensionManager,m=f||d.$to.parentOffset&&d.$from.marks();if(m){const g=m.filter(y=>p.includes(y.type.name));o.ensureMarks(g)}}if(t.keepAttributes){const d=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(d,s).run()}const u=o.doc.resolve(n.from-1).nodeBefore;u&&u.type===t.type&&vl(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,u))&&o.join(n.from-1)},undoable:t.undoable})}function M5(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof pt){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var I5={};Xb(I5,{createAtomBlockMarkdownSpec:()=>R5,createBlockMarkdownSpec:()=>D5,createInlineMarkdownSpec:()=>P5,parseAttributes:()=>lx,parseIndentedBlocks:()=>P0,renderNestedMarkdownContent:()=>cx,serializeAttributes:()=>ax});function lx(t){if(!(t!=null&&t.trim()))return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,c=>(n.push(c),`__QUOTED_${n.length-1}__`)),i=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const c=i.map(u=>u.trim().slice(1));e.class=c.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,c,u])=>{var d;const f=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),p=n[f];p&&(e[c]=p.slice(1,-1))});const a=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return a&&a.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function ax(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function R5(t){const{nodeName:e,name:n,parseAttributes:r=lx,serializeAttributes:i=ax,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,a=n||e,c=u=>{if(!l)return u;const d={};return l.forEach(f=>{f in u&&(d[f]=u[f])}),d};return{parseMarkdown:(u,d)=>{const f={...s,...u.attributes};return d.createNode(e,f,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;const f=new RegExp(`^:::${a}(?:\\s|$)`,"m"),p=(d=u.match(f))==null?void 0:d.index;return p!==void 0?p:-1},tokenize(u,d,f){const p=new RegExp(`^:::${a}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),m=u.match(p);if(!m)return;const g=m[1]||"",y=r(g);if(!o.find(w=>!(w in y)))return{type:e,raw:m[0],attributes:y}}},renderMarkdown:u=>{const d=c(u.attrs||{}),f=i(d),p=f?` {${f}}`:"";return`:::${a}${p} :::`}}}function D5(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=lx,serializeAttributes:s=ax,defaultAttributes:o={},content:l="block",allowedAttributes:a}=t,c=n||e,u=d=>{if(!a)return d;const f={};return a.forEach(p=>{p in d&&(f[p]=d[p])}),f};return{parseMarkdown:(d,f)=>{let p;if(r){const g=r(d);p=typeof g=="string"?[{type:"text",text:g}]:g}else l==="block"?p=f.parseChildren(d.tokens||[]):p=f.parseInline(d.tokens||[]);const m={...o,...d.attributes};return f.createNode(e,m,p)},markdownTokenizer:{name:e,level:"block",start(d){var f;const p=new RegExp(`^:::${c}`,"m"),m=(f=d.match(p))==null?void 0:f.index;return m!==void 0?m:-1},tokenize(d,f,p){var m;const g=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),y=d.match(g);if(!y)return;const[v,w=""]=y,x=i(w);let E=1;const k=v.length;let M="";const N=/^:::([\w-]*)(\s.*)?/gm,z=d.slice(k);for(N.lastIndex=0;;){const X=N.exec(z);if(X===null)break;const L=X.index,H=X[1];if(!((m=X[2])!=null&&m.endsWith(":::"))){if(H)E+=1;else if(E-=1,E===0){const W=z.slice(0,L);M=W.trim();const te=d.slice(0,k+L+X[0].length);let ue=[];if(M)if(l==="block")for(ue=p.blockTokens(W),ue.forEach(de=>{de.text&&(!de.tokens||de.tokens.length===0)&&(de.tokens=p.inlineTokens(de.text))});ue.length>0;){const de=ue[ue.length-1];if(de.type==="paragraph"&&(!de.text||de.text.trim()===""))ue.pop();else break}else ue=p.inlineTokens(M);return{type:e,raw:te,attributes:x,content:M,tokens:ue}}}}}},renderMarkdown:(d,f)=>{const p=u(d.attrs||{}),m=s(p),g=m?` {${m}}`:"",y=f.renderChildren(d.content||[],` `);return`:::${c}${g} @@ -157,7 +157,7 @@ ${y} * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var cg=b,k6=Rb;function S6(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var C6=typeof Object.is=="function"?Object.is:S6,E6=k6.useSyncExternalStore,N6=cg.useRef,T6=cg.useEffect,A6=cg.useMemo,M6=cg.useDebugValue;E2.useSyncExternalStoreWithSelector=function(t,e,n,r,i){var s=N6(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=A6(function(){function a(p){if(!c){if(c=!0,u=p,p=r(p),i!==void 0&&o.hasValue){var m=o.value;if(i(m,p))return d=m}return d=p}if(m=d,C6(u,p))return m;var g=r(p);return i!==void 0&&i(m,g)?(u=p,m):(u=p,d=g)}var c=!1,u,d,f=n===void 0?null:n;return[function(){return a(e())},f===null?void 0:function(){return a(f())}]},[e,n,r,i]);var l=E6(t,s[0],s[1]);return T6(function(){o.hasValue=!0,o.value=l},[l]),M6(l),l};C2.exports=E2;var I6=C2.exports;const N2=["top","right","bottom","left"],_C=["start","end"],zC=N2.reduce((t,e)=>t.concat(e,e+"-"+_C[0],e+"-"+_C[1]),[]),Ms=Math.min,zr=Math.max,Mp=Math.round,Cs=t=>({x:t,y:t}),R6={left:"right",right:"left",bottom:"top",top:"bottom"},D6={start:"end",end:"start"};function L0(t,e,n){return zr(t,Ms(e,n))}function go(t,e){return typeof t=="function"?t(e):t}function _i(t){return t.split("-")[0]}function Zi(t){return t.split("-")[1]}function T2(t){return t==="x"?"y":"x"}function ux(t){return t==="y"?"height":"width"}const O6=new Set(["top","bottom"]);function ws(t){return O6.has(_i(t))?"y":"x"}function dx(t){return T2(ws(t))}function A2(t,e,n){n===void 0&&(n=!1);const r=Zi(t),i=dx(t),s=ux(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=Rp(o)),[o,Rp(o)]}function j6(t){const e=Rp(t);return[Ip(t),e,Ip(e)]}function Ip(t){return t.replace(/start|end/g,e=>D6[e])}const FC=["left","right"],$C=["right","left"],P6=["top","bottom"],L6=["bottom","top"];function _6(t,e,n){switch(t){case"top":case"bottom":return n?e?$C:FC:e?FC:$C;case"left":case"right":return e?P6:L6;default:return[]}}function z6(t,e,n,r){const i=Zi(t);let s=_6(_i(t),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),e&&(s=s.concat(s.map(Ip)))),s}function Rp(t){return t.replace(/left|right|bottom|top/g,e=>R6[e])}function F6(t){return{top:0,right:0,bottom:0,left:0,...t}}function fx(t){return typeof t!="number"?F6(t):{top:t,right:t,bottom:t,left:t}}function wc(t){const{x:e,y:n,width:r,height:i}=t;return{width:r,height:i,top:n,left:e,right:e+r,bottom:n+i,x:e,y:n}}function BC(t,e,n){let{reference:r,floating:i}=t;const s=ws(e),o=dx(e),l=ux(o),a=_i(e),c=s==="y",u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[l]/2-i[l]/2;let p;switch(a){case"top":p={x:u,y:r.y-i.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:d};break;case"left":p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}switch(Zi(e)){case"start":p[o]-=f*(n&&c?-1:1);break;case"end":p[o]+=f*(n&&c?-1:1);break}return p}async function $6(t,e){var n;e===void 0&&(e={});const{x:r,y:i,platform:s,rects:o,elements:l,strategy:a}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=go(e,t),m=fx(p),y=l[f?d==="floating"?"reference":"floating":d],v=wc(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:c,rootBoundary:u,strategy:a})),w=d==="floating"?{x:r,y:i,width:o.floating.width,height:o.floating.height}:o.reference,x=await(s.getOffsetParent==null?void 0:s.getOffsetParent(l.floating)),E=await(s.isElement==null?void 0:s.isElement(x))?await(s.getScale==null?void 0:s.getScale(x))||{x:1,y:1}:{x:1,y:1},k=wc(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:w,offsetParent:x,strategy:a}):w);return{top:(v.top-k.top+m.top)/E.y,bottom:(k.bottom-v.bottom+m.bottom)/E.y,left:(v.left-k.left+m.left)/E.x,right:(k.right-v.right+m.right)/E.x}}const B6=async(t,e,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,l=s.filter(Boolean),a=await(o.isRTL==null?void 0:o.isRTL(e));let c=await o.getElementRects({reference:t,floating:e,strategy:i}),{x:u,y:d}=BC(c,r,a),f=r,p={},m=0;for(let y=0;y({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:i,rects:s,platform:o,elements:l,middlewareData:a}=e,{element:c,padding:u=0}=go(t,e)||{};if(c==null)return{};const d=fx(u),f={x:n,y:r},p=dx(i),m=ux(p),g=await o.getDimensions(c),y=p==="y",v=y?"top":"left",w=y?"bottom":"right",x=y?"clientHeight":"clientWidth",E=s.reference[m]+s.reference[p]-f[p]-s.floating[m],k=f[p]-s.reference[p],M=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c));let N=M?M[x]:0;(!N||!await(o.isElement==null?void 0:o.isElement(M)))&&(N=l.floating[x]||s.floating[m]);const z=E/2-k/2,X=N/2-g[m]/2-1,L=Ms(d[v],X),H=Ms(d[w],X),W=L,te=N-g[m]-H,ce=N/2-g[m]/2+z,ue=L0(W,ce,te),Ae=!a.arrow&&Zi(i)!=null&&ce!==ue&&s.reference[m]/2-(ceZi(i)===t),...n.filter(i=>Zi(i)!==t)]:n.filter(i=>_i(i)===i)).filter(i=>t?Zi(i)===t||(e?Ip(i)!==i:!1):!0)}const V6=function(t){return t===void 0&&(t={}),{name:"autoPlacement",options:t,async fn(e){var n,r,i;const{rects:s,middlewareData:o,placement:l,platform:a,elements:c}=e,{crossAxis:u=!1,alignment:d,allowedPlacements:f=zC,autoAlignment:p=!0,...m}=go(t,e),g=d!==void 0||f===zC?H6(d||null,p,f):f,y=await a.detectOverflow(e,m),v=((n=o.autoPlacement)==null?void 0:n.index)||0,w=g[v];if(w==null)return{};const x=A2(w,s,await(a.isRTL==null?void 0:a.isRTL(c.floating)));if(l!==w)return{reset:{placement:g[0]}};const E=[y[_i(w)],y[x[0]],y[x[1]]],k=[...((r=o.autoPlacement)==null?void 0:r.overflows)||[],{placement:w,overflows:E}],M=g[v+1];if(M)return{data:{index:v+1,overflows:k},reset:{placement:M}};const N=k.map(L=>{const H=Zi(L.placement);return[L.placement,H&&u?L.overflows.slice(0,2).reduce((W,te)=>W+te,0):L.overflows[0],L.overflows]}).sort((L,H)=>L[1]-H[1]),X=((i=N.filter(L=>L[2].slice(0,Zi(L[0])?2:3).every(H=>H<=0))[0])==null?void 0:i[0])||N[0][0];return X!==l?{data:{index:v+1,overflows:k},reset:{placement:X}}:{}}}},W6=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:i,middlewareData:s,rects:o,initialPlacement:l,platform:a,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=go(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=_i(i),w=ws(l),x=_i(l)===l,E=await(a.isRTL==null?void 0:a.isRTL(c.floating)),k=f||(x||!g?[Rp(l)]:j6(l)),M=m!=="none";!f&&M&&k.push(...z6(l,g,m,E));const N=[l,...k],z=await a.detectOverflow(e,y),X=[];let L=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&X.push(z[v]),d){const ce=A2(i,o,E);X.push(z[ce[0]],z[ce[1]])}if(L=[...L,{placement:i,overflows:X}],!X.every(ce=>ce<=0)){var H,W;const ce=(((H=s.flip)==null?void 0:H.index)||0)+1,ue=N[ce];if(ue&&(!(d==="alignment"?w!==ws(ue):!1)||L.every(q=>ws(q.placement)===w?q.overflows[0]>0:!0)))return{data:{index:ce,overflows:L},reset:{placement:ue}};let Ae=(W=L.filter(me=>me.overflows[0]<=0).sort((me,q)=>me.overflows[1]-q.overflows[1])[0])==null?void 0:W.placement;if(!Ae)switch(p){case"bestFit":{var te;const me=(te=L.filter(q=>{if(M){const se=ws(q.placement);return se===w||se==="y"}return!0}).map(q=>[q.placement,q.overflows.filter(se=>se>0).reduce((se,xe)=>se+xe,0)]).sort((q,se)=>q[1]-se[1])[0])==null?void 0:te[0];me&&(Ae=me);break}case"initialPlacement":Ae=l;break}if(i!==Ae)return{reset:{placement:Ae}}}return{}}}};function UC(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function HC(t){return N2.some(e=>t[e]>=0)}const K6=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n,platform:r}=e,{strategy:i="referenceHidden",...s}=go(t,e);switch(i){case"referenceHidden":{const o=await r.detectOverflow(e,{...s,elementContext:"reference"}),l=UC(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:HC(l)}}}case"escaped":{const o=await r.detectOverflow(e,{...s,altBoundary:!0}),l=UC(o,n.floating);return{data:{escapedOffsets:l,escaped:HC(l)}}}default:return{}}}}};function M2(t){const e=Ms(...t.map(s=>s.left)),n=Ms(...t.map(s=>s.top)),r=zr(...t.map(s=>s.right)),i=zr(...t.map(s=>s.bottom));return{x:e,y:n,width:r-e,height:i-n}}function Y6(t){const e=t.slice().sort((i,s)=>i.y-s.y),n=[];let r=null;for(let i=0;ir.height/2?n.push([s]):n[n.length-1].push(s),r=s}return n.map(i=>wc(M2(i)))}const q6=function(t){return t===void 0&&(t={}),{name:"inline",options:t,async fn(e){const{placement:n,elements:r,rects:i,platform:s,strategy:o}=e,{padding:l=2,x:a,y:c}=go(t,e),u=Array.from(await(s.getClientRects==null?void 0:s.getClientRects(r.reference))||[]),d=Y6(u),f=wc(M2(u)),p=fx(l);function m(){if(d.length===2&&d[0].left>d[1].right&&a!=null&&c!=null)return d.find(y=>a>y.left-p.left&&ay.top-p.top&&c=2){if(ws(n)==="y"){const L=d[0],H=d[d.length-1],W=_i(n)==="top",te=L.top,ce=H.bottom,ue=W?L.left:H.left,Ae=W?L.right:H.right,me=Ae-ue,q=ce-te;return{top:te,bottom:ce,left:ue,right:Ae,width:me,height:q,x:ue,y:te}}const y=_i(n)==="left",v=zr(...d.map(L=>L.right)),w=Ms(...d.map(L=>L.left)),x=d.filter(L=>y?L.left===w:L.right===v),E=x[0].top,k=x[x.length-1].bottom,M=w,N=v,z=N-M,X=k-E;return{top:E,bottom:k,left:M,right:N,width:z,height:X,x:M,y:E}}return f}const g=await s.getElementRects({reference:{getBoundingClientRect:m},floating:r.floating,strategy:o});return i.reference.x!==g.reference.x||i.reference.y!==g.reference.y||i.reference.width!==g.reference.width||i.reference.height!==g.reference.height?{reset:{rects:g}}:{}}}},J6=new Set(["left","top"]);async function G6(t,e){const{placement:n,platform:r,elements:i}=t,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=_i(n),l=Zi(n),a=ws(n)==="y",c=J6.has(o)?-1:1,u=s&&a?-1:1,d=go(e,t);let{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return l&&typeof m=="number"&&(p=l==="end"?m*-1:m),a?{x:p*u,y:f*c}:{x:f*c,y:p*u}}const X6=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:i,y:s,placement:o,middlewareData:l}=e,a=await G6(e,t);return o===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:i+a.x,y:s+a.y,data:{...a,placement:o}}}}},Q6=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:i,platform:s}=e,{mainAxis:o=!0,crossAxis:l=!1,limiter:a={fn:v=>{let{x:w,y:x}=v;return{x:w,y:x}}},...c}=go(t,e),u={x:n,y:r},d=await s.detectOverflow(e,c),f=ws(_i(i)),p=T2(f);let m=u[p],g=u[f];if(o){const v=p==="y"?"top":"left",w=p==="y"?"bottom":"right",x=m+d[v],E=m-d[w];m=L0(x,m,E)}if(l){const v=f==="y"?"top":"left",w=f==="y"?"bottom":"right",x=g+d[v],E=g-d[w];g=L0(x,g,E)}const y=a.fn({...e,[p]:m,[f]:g});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[p]:o,[f]:l}}}}}},Z6=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:i,rects:s,platform:o,elements:l}=e,{apply:a=()=>{},...c}=go(t,e),u=await o.detectOverflow(e,c),d=_i(i),f=Zi(i),p=ws(i)==="y",{width:m,height:g}=s.floating;let y,v;d==="top"||d==="bottom"?(y=d,v=f===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(v=d,y=f==="end"?"top":"bottom");const w=g-u.top-u.bottom,x=m-u.left-u.right,E=Ms(g-u[y],w),k=Ms(m-u[v],x),M=!e.middlewareData.shift;let N=E,z=k;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(z=x),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(N=w),M&&!f){const L=zr(u.left,0),H=zr(u.right,0),W=zr(u.top,0),te=zr(u.bottom,0);p?z=m-2*(L!==0||H!==0?L+H:zr(u.left,u.right)):N=g-2*(W!==0||te!==0?W+te:zr(u.top,u.bottom))}await a({...e,availableWidth:z,availableHeight:N});const X=await o.getDimensions(l.floating);return m!==X.width||g!==X.height?{reset:{rects:!0}}:{}}}};function ug(){return typeof window<"u"}function Pc(t){return I2(t)?(t.nodeName||"").toLowerCase():"#document"}function hi(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function yo(t){var e;return(e=(I2(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function I2(t){return ug()?t instanceof Node||t instanceof hi(t).Node:!1}function ns(t){return ug()?t instanceof Element||t instanceof hi(t).Element:!1}function Is(t){return ug()?t instanceof HTMLElement||t instanceof hi(t).HTMLElement:!1}function VC(t){return!ug()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof hi(t).ShadowRoot}const eU=new Set(["inline","contents"]);function Xd(t){const{overflow:e,overflowX:n,overflowY:r,display:i}=rs(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!eU.has(i)}const tU=new Set(["table","td","th"]);function nU(t){return tU.has(Pc(t))}const rU=[":popover-open",":modal"];function dg(t){return rU.some(e=>{try{return t.matches(e)}catch{return!1}})}const iU=["transform","translate","scale","rotate","perspective"],sU=["transform","translate","scale","rotate","perspective","filter"],oU=["paint","layout","strict","content"];function hx(t){const e=px(),n=ns(t)?rs(t):t;return iU.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||sU.some(r=>(n.willChange||"").includes(r))||oU.some(r=>(n.contain||"").includes(r))}function lU(t){let e=ll(t);for(;Is(e)&&!bc(e);){if(hx(e))return e;if(dg(e))return null;e=ll(e)}return null}function px(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const aU=new Set(["html","body","#document"]);function bc(t){return aU.has(Pc(t))}function rs(t){return hi(t).getComputedStyle(t)}function fg(t){return ns(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function ll(t){if(Pc(t)==="html")return t;const e=t.assignedSlot||t.parentNode||VC(t)&&t.host||yo(t);return VC(e)?e.host:e}function R2(t){const e=ll(t);return bc(e)?t.ownerDocument?t.ownerDocument.body:t.body:Is(e)&&Xd(e)?e:R2(e)}function D2(t,e,n){var r;e===void 0&&(e=[]);const i=R2(t),s=i===((r=t.ownerDocument)==null?void 0:r.body),o=hi(i);return s?(_0(o),e.concat(o,o.visualViewport||[],Xd(i)?i:[],[])):e.concat(i,D2(i,[]))}function _0(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function O2(t){const e=rs(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const i=Is(t),s=i?t.offsetWidth:n,o=i?t.offsetHeight:r,l=Mp(n)!==s||Mp(r)!==o;return l&&(n=s,r=o),{width:n,height:r,$:l}}function j2(t){return ns(t)?t:t.contextElement}function Ga(t){const e=j2(t);if(!Is(e))return Cs(1);const n=e.getBoundingClientRect(),{width:r,height:i,$:s}=O2(e);let o=(s?Mp(n.width):n.width)/r,l=(s?Mp(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const cU=Cs(0);function P2(t){const e=hi(t);return!px()||!e.visualViewport?cU:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function uU(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==hi(t)?!1:e}function xd(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const i=t.getBoundingClientRect(),s=j2(t);let o=Cs(1);e&&(r?ns(r)&&(o=Ga(r)):o=Ga(t));const l=uU(s,n,r)?P2(s):Cs(0);let a=(i.left+l.x)/o.x,c=(i.top+l.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(s){const f=hi(s),p=r&&ns(r)?hi(r):r;let m=f,g=_0(m);for(;g&&r&&p!==m;){const y=Ga(g),v=g.getBoundingClientRect(),w=rs(g),x=v.left+(g.clientLeft+parseFloat(w.paddingLeft))*y.x,E=v.top+(g.clientTop+parseFloat(w.paddingTop))*y.y;a*=y.x,c*=y.y,u*=y.x,d*=y.y,a+=x,c+=E,m=hi(g),g=_0(m)}}return wc({width:u,height:d,x:a,y:c})}function hg(t,e){const n=fg(t).scrollLeft;return e?e.left+n:xd(yo(t)).left+n}function L2(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-hg(t,n),i=n.top+e.scrollTop;return{x:r,y:i}}function dU(t){let{elements:e,rect:n,offsetParent:r,strategy:i}=t;const s=i==="fixed",o=yo(r),l=e?dg(e.floating):!1;if(r===o||l&&s)return n;let a={scrollLeft:0,scrollTop:0},c=Cs(1);const u=Cs(0),d=Is(r);if((d||!d&&!s)&&((Pc(r)!=="body"||Xd(o))&&(a=fg(r)),Is(r))){const p=xd(r);c=Ga(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const f=o&&!d&&!s?L2(o,a):Cs(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-a.scrollLeft*c.x+u.x+f.x,y:n.y*c.y-a.scrollTop*c.y+u.y+f.y}}function fU(t){return Array.from(t.getClientRects())}function hU(t){const e=yo(t),n=fg(t),r=t.ownerDocument.body,i=zr(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=zr(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+hg(t);const l=-n.scrollTop;return rs(r).direction==="rtl"&&(o+=zr(e.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:l}}const WC=25;function pU(t,e){const n=hi(t),r=yo(t),i=n.visualViewport;let s=r.clientWidth,o=r.clientHeight,l=0,a=0;if(i){s=i.width,o=i.height;const u=px();(!u||u&&e==="fixed")&&(l=i.offsetLeft,a=i.offsetTop)}const c=hg(r);if(c<=0){const u=r.ownerDocument,d=u.body,f=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,m=Math.abs(r.clientWidth-d.clientWidth-p);m<=WC&&(s-=m)}else c<=WC&&(s+=c);return{width:s,height:o,x:l,y:a}}const mU=new Set(["absolute","fixed"]);function gU(t,e){const n=xd(t,!0,e==="fixed"),r=n.top+t.clientTop,i=n.left+t.clientLeft,s=Is(t)?Ga(t):Cs(1),o=t.clientWidth*s.x,l=t.clientHeight*s.y,a=i*s.x,c=r*s.y;return{width:o,height:l,x:a,y:c}}function KC(t,e,n){let r;if(e==="viewport")r=pU(t,n);else if(e==="document")r=hU(yo(t));else if(ns(e))r=gU(e,n);else{const i=P2(t);r={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return wc(r)}function _2(t,e){const n=ll(t);return n===e||!ns(n)||bc(n)?!1:rs(n).position==="fixed"||_2(n,e)}function yU(t,e){const n=e.get(t);if(n)return n;let r=D2(t,[]).filter(l=>ns(l)&&Pc(l)!=="body"),i=null;const s=rs(t).position==="fixed";let o=s?ll(t):t;for(;ns(o)&&!bc(o);){const l=rs(o),a=hx(o);!a&&l.position==="fixed"&&(i=null),(s?!a&&!i:!a&&l.position==="static"&&!!i&&mU.has(i.position)||Xd(o)&&!a&&_2(t,o))?r=r.filter(u=>u!==o):i=l,o=ll(o)}return e.set(t,r),r}function vU(t){let{element:e,boundary:n,rootBoundary:r,strategy:i}=t;const o=[...n==="clippingAncestors"?dg(e)?[]:yU(e,this._c):[].concat(n),r],l=o[0],a=o.reduce((c,u)=>{const d=KC(e,u,i);return c.top=zr(d.top,c.top),c.right=Ms(d.right,c.right),c.bottom=Ms(d.bottom,c.bottom),c.left=zr(d.left,c.left),c},KC(e,l,i));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}}function wU(t){const{width:e,height:n}=O2(t);return{width:e,height:n}}function bU(t,e,n){const r=Is(e),i=yo(e),s=n==="fixed",o=xd(t,!0,s,e);let l={scrollLeft:0,scrollTop:0};const a=Cs(0);function c(){a.x=hg(i)}if(r||!r&&!s)if((Pc(e)!=="body"||Xd(i))&&(l=fg(e)),r){const p=xd(e,!0,s,e);a.x=p.x+e.clientLeft,a.y=p.y+e.clientTop}else i&&c();s&&!r&&i&&c();const u=i&&!r&&!s?L2(i,l):Cs(0),d=o.left+l.scrollLeft-a.x-u.x,f=o.top+l.scrollTop-a.y-u.y;return{x:d,y:f,width:o.width,height:o.height}}function $y(t){return rs(t).position==="static"}function YC(t,e){if(!Is(t)||rs(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return yo(t)===n&&(n=n.ownerDocument.body),n}function z2(t,e){const n=hi(t);if(dg(t))return n;if(!Is(t)){let i=ll(t);for(;i&&!bc(i);){if(ns(i)&&!$y(i))return i;i=ll(i)}return n}let r=YC(t,e);for(;r&&nU(r)&&$y(r);)r=YC(r,e);return r&&bc(r)&&$y(r)&&!hx(r)?n:r||lU(t)||n}const xU=async function(t){const e=this.getOffsetParent||z2,n=this.getDimensions,r=await n(t.floating);return{reference:bU(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function kU(t){return rs(t).direction==="rtl"}const SU={convertOffsetParentRelativeRectToViewportRelativeRect:dU,getDocumentElement:yo,getClippingRect:vU,getOffsetParent:z2,getElementRects:xU,getClientRects:fU,getDimensions:wU,getScale:Ga,isElement:ns,isRTL:kU},F2=X6,$2=V6,B2=Q6,U2=W6,H2=Z6,V2=K6,W2=U6,K2=q6,Y2=(t,e,n)=>{const r=new Map,i={platform:SU,...n},s={...i.platform,_c:r};return B6(t,e,{...i,platform:s})};let z0,F0;if(typeof WeakMap<"u"){let t=new WeakMap;z0=e=>t.get(e),F0=(e,n)=>(t.set(e,n),n)}else{const t=[];let n=0;z0=r=>{for(let i=0;i(n==10&&(n=0),t[n++]=r,t[n++]=i)}var Ws=class{constructor(t,e,n,r){this.width=t,this.height=e,this.map=n,this.problems=r}findCell(t){for(let e=0;e=n){(s||(s=[])).push({type:"overlong_rowspan",pos:u,n:v-x});break}const E=i+x*e;for(let k=0;kr&&(s+=c.attrs.colspan)}}for(let o=0;o1&&(n=!0)}e==-1?e=s:e!=s&&(e=Math.max(e,s))}return e}function NU(t,e,n){t.problems||(t.problems=[]);const r={};for(let i=0;i0;e--)if(t.node(e).type.spec.tableRole=="row")return t.node(0).resolve(t.before(e+1));return null}function q2(t){const e=t.selection.$head;for(let n=e.depth;n>0;n--)if(e.node(n).type.spec.tableRole=="row")return!0;return!1}function MU(t){const e=t.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;const n=AU(e.$head)||IU(e.$head);if(n)return n;throw new RangeError(`No cell found around position ${e.head}`)}function IU(t){for(let e=t.nodeAfter,n=t.pos;e;e=e.firstChild,n++){const r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n)}for(let e=t.nodeBefore,n=t.pos;e;e=e.lastChild,n--){const r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n-e.nodeSize)}}function qC(t){return t.parent.type.spec.tableRole=="row"&&!!t.nodeAfter}function J2(t,e){return t.depth==e.depth&&t.pos>=e.start(-1)&&t.pos<=e.end(-1)}function G2(t,e,n){const r=t.node(-1),i=Ws.get(r),s=t.start(-1),o=i.nextCell(t.pos-s,e,n);return o==null?null:t.node(0).resolve(s+o)}function JC(t,e,n=1){const r={...t,colspan:t.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,n),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}var Es=class $s extends Nt{constructor(e,n=e){const r=e.node(-1),i=Ws.get(r),s=e.start(-1),o=i.rectBetween(e.pos-s,n.pos-s),l=e.node(0),a=i.cellsInRect(o).filter(u=>u!=n.pos-s);a.unshift(n.pos-s);const c=a.map(u=>{const d=r.nodeAt(u);if(!d)throw new RangeError(`No cell with offset ${u} found`);const f=s+u+1;return new qM(l.resolve(f),l.resolve(f+d.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=n}map(e,n){const r=e.resolve(n.map(this.$anchorCell.pos)),i=e.resolve(n.map(this.$headCell.pos));if(qC(r)&&qC(i)&&J2(r,i)){const s=this.$anchorCell.node(-1)!=r.node(-1);return s&&this.isRowSelection()?$s.rowSelection(r,i):s&&this.isColSelection()?$s.colSelection(r,i):new $s(r,i)}return St.between(r,i)}content(){const e=this.$anchorCell.node(-1),n=Ws.get(e),r=this.$anchorCell.start(-1),i=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),s={},o=[];for(let a=i.top;a0||y>0){let v=m.attrs;if(g>0&&(v=JC(v,0,g)),y>0&&(v=JC(v,v.colspan-y,y)),p.lefti.bottom){const v={...m.attrs,rowspan:Math.min(p.bottom,i.bottom)-Math.max(p.top,i.top)};p.top0)return!1;const r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,n=e){const r=e.node(-1),i=Ws.get(r),s=e.start(-1),o=i.findCell(e.pos-s),l=i.findCell(n.pos-s),a=e.node(0);return o.top<=l.top?(o.top>0&&(e=a.resolve(s+i.map[o.left])),l.bottom0&&(n=a.resolve(s+i.map[l.left])),o.bottom0)return!1;const o=i+this.$anchorCell.nodeAfter.attrs.colspan,l=s+this.$headCell.nodeAfter.attrs.colspan;return Math.max(o,l)==n.width}eq(e){return e instanceof $s&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,n=e){const r=e.node(-1),i=Ws.get(r),s=e.start(-1),o=i.findCell(e.pos-s),l=i.findCell(n.pos-s),a=e.node(0);return o.left<=l.left?(o.left>0&&(e=a.resolve(s+i.map[o.top*i.width])),l.right0&&(n=a.resolve(s+i.map[l.top*i.width])),o.righti.table.nodeAt(a));for(let a=0;a{const p=f+s.tableStart,m=o.doc.nodeAt(p);m&&o.setNodeMarkup(p,d,m.attrs)}),r(o)}return!0}}gx("row",{useDeprecatedLogic:!0});gx("column",{useDeprecatedLogic:!0});gx("cell",{useDeprecatedLogic:!0});function Jf(t,e){const n=t.selection;if(!(n instanceof Es))return!1;if(e){const r=t.tr,i=mx(t.schema).cell.createAndFill().content;n.forEachCell((s,o)=>{s.content.eq(i)||r.replace(r.mapping.map(o+1),r.mapping.map(o+s.nodeSize-1),new _e(i,0,0))}),r.docChanged&&e(r)}return!0}Gb({ArrowLeft:Gf("horiz",-1),ArrowRight:Gf("horiz",1),ArrowUp:Gf("vert",-1),ArrowDown:Gf("vert",1),"Shift-ArrowLeft":Xf("horiz",-1),"Shift-ArrowRight":Xf("horiz",1),"Shift-ArrowUp":Xf("vert",-1),"Shift-ArrowDown":Xf("vert",1),Backspace:Jf,"Mod-Backspace":Jf,Delete:Jf,"Mod-Delete":Jf});function Eh(t,e,n){return n.eq(t.selection)?!1:(e&&e(t.tr.setSelection(n).scrollIntoView()),!0)}function Gf(t,e){return(n,r,i)=>{if(!i)return!1;const s=n.selection;if(s instanceof Es)return Eh(n,r,Nt.near(s.$headCell,e));if(t!="horiz"&&!s.empty)return!1;const o=Z2(i,t,e);if(o==null)return!1;if(t=="horiz")return Eh(n,r,Nt.near(n.doc.resolve(s.head+e),e));{const l=n.doc.resolve(o),a=G2(l,t,e);let c;return a?c=Nt.near(a,1):e<0?c=Nt.near(n.doc.resolve(l.before(-1)),-1):c=Nt.near(n.doc.resolve(l.after(-1)),1),Eh(n,r,c)}}}function Xf(t,e){return(n,r,i)=>{if(!i)return!1;const s=n.selection;let o;if(s instanceof Es)o=s;else{const a=Z2(i,t,e);if(a==null)return!1;o=new Es(n.doc.resolve(a))}const l=G2(o.$headCell,t,e);return l?Eh(n,r,new Es(o.$anchorCell,l)):!1}}function Z2(t,e,n){if(!(t.state.selection instanceof St))return null;const{$head:r}=t.state.selection;for(let i=r.depth-1;i>=0;i--){const s=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:s.childCount))return null;if(s.type.spec.tableRole=="cell"||s.type.spec.tableRole=="header_cell"){const o=r.before(i),l=e=="vert"?n>0?"down":"up":n>0?"right":"left";return t.endOfTextblock(l)?o:null}}return null}new pn("tableColumnResizing");function OU(t,e){const n=Math.min(t.top,e.top),r=Math.max(t.bottom,e.bottom),i=Math.min(t.left,e.left),o=Math.max(t.right,e.right)-i,l=r-n,a=i,c=n;return new DOMRect(a,c,o,l)}var jU=class{constructor({editor:t,element:e,view:n,updateDelay:r=250,resizeDelay:i=60,shouldShow:s,appendTo:o,getReferencedVirtualElement:l,options:a}){this.preventHide=!1,this.isVisible=!1,this.scrollTarget=window,this.floatingUIOptions={strategy:"absolute",placement:"top",offset:8,flip:{},shift:{},arrow:!1,size:!1,autoPlacement:!1,hide:!1,inline:!1,onShow:void 0,onHide:void 0,onUpdate:void 0,onDestroy:void 0},this.shouldShow=({view:u,state:d,from:f,to:p})=>{const{doc:m,selection:g}=d,{empty:y}=g,v=!m.textBetween(f,p).length&&ex(d.selection),w=this.element.contains(document.activeElement);return!(!(u.hasFocus()||w)||y||v||!this.editor.isEditable)},this.mousedownHandler=()=>{this.preventHide=!0},this.dragstartHandler=()=>{this.hide()},this.resizeHandler=()=>{this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=window.setTimeout(()=>{this.updatePosition()},this.resizeDelay)},this.focusHandler=()=>{setTimeout(()=>this.update(this.editor.view))},this.blurHandler=({event:u})=>{var d;if(this.editor.isDestroyed){this.destroy();return}if(this.preventHide){this.preventHide=!1;return}u!=null&&u.relatedTarget&&((d=this.element.parentNode)!=null&&d.contains(u.relatedTarget))||(u==null?void 0:u.relatedTarget)!==this.editor.view.dom&&this.hide()},this.handleDebouncedUpdate=(u,d)=>{const f=!(d!=null&&d.selection.eq(u.state.selection)),p=!(d!=null&&d.doc.eq(u.state.doc));!f&&!p||(this.updateDebounceTimer&&clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=window.setTimeout(()=>{this.updateHandler(u,f,p,d)},this.updateDelay))},this.updateHandler=(u,d,f,p)=>{const{composing:m}=u;if(m||!d&&!f)return;if(!this.getShouldShow(p)){this.hide();return}this.updatePosition(),this.show()},this.transactionHandler=({transaction:u})=>{const d=u.getMeta("bubbleMenu");d==="updatePosition"?this.updatePosition():d&&typeof d=="object"&&d.type==="updateOptions"&&this.updateOptions(d.options)};var c;this.editor=t,this.element=e,this.view=n,this.updateDelay=r,this.resizeDelay=i,this.appendTo=o,this.scrollTarget=(c=a==null?void 0:a.scrollTarget)!=null?c:window,this.getReferencedVirtualElement=l,this.floatingUIOptions={...this.floatingUIOptions,...a},this.element.tabIndex=0,s&&(this.shouldShow=s),this.element.addEventListener("mousedown",this.mousedownHandler,{capture:!0}),this.view.dom.addEventListener("dragstart",this.dragstartHandler),this.editor.on("focus",this.focusHandler),this.editor.on("blur",this.blurHandler),this.editor.on("transaction",this.transactionHandler),window.addEventListener("resize",this.resizeHandler),this.scrollTarget.addEventListener("scroll",this.resizeHandler),this.update(n,n.state),this.getShouldShow()&&(this.show(),this.updatePosition())}get middlewares(){const t=[];return this.floatingUIOptions.flip&&t.push(U2(typeof this.floatingUIOptions.flip!="boolean"?this.floatingUIOptions.flip:void 0)),this.floatingUIOptions.shift&&t.push(B2(typeof this.floatingUIOptions.shift!="boolean"?this.floatingUIOptions.shift:void 0)),this.floatingUIOptions.offset&&t.push(F2(typeof this.floatingUIOptions.offset!="boolean"?this.floatingUIOptions.offset:void 0)),this.floatingUIOptions.arrow&&t.push(W2(this.floatingUIOptions.arrow)),this.floatingUIOptions.size&&t.push(H2(typeof this.floatingUIOptions.size!="boolean"?this.floatingUIOptions.size:void 0)),this.floatingUIOptions.autoPlacement&&t.push($2(typeof this.floatingUIOptions.autoPlacement!="boolean"?this.floatingUIOptions.autoPlacement:void 0)),this.floatingUIOptions.hide&&t.push(V2(typeof this.floatingUIOptions.hide!="boolean"?this.floatingUIOptions.hide:void 0)),this.floatingUIOptions.inline&&t.push(K2(typeof this.floatingUIOptions.inline!="boolean"?this.floatingUIOptions.inline:void 0)),t}get virtualElement(){var t,e,n;const{selection:r}=this.editor.state,i=(t=this.getReferencedVirtualElement)==null?void 0:t.call(this);if(i)return i;if(!((n=(e=this.view)==null?void 0:e.dom)!=null&&n.parentNode))return;const s=l2(this.view,r.from,r.to);let o={getBoundingClientRect:()=>s,getClientRects:()=>[s]};if(r instanceof pt){let l=this.view.nodeDOM(r.from);const a=l.dataset.nodeViewWrapper?l:l.querySelector("[data-node-view-wrapper]");a&&(l=a),l&&(o={getBoundingClientRect:()=>l.getBoundingClientRect(),getClientRects:()=>[l.getBoundingClientRect()]})}if(r instanceof Es){const{$anchorCell:l,$headCell:a}=r,c=l?l.pos:a.pos,u=a?a.pos:l.pos,d=this.view.nodeDOM(c),f=this.view.nodeDOM(u);if(!d||!f)return;const p=d===f?d.getBoundingClientRect():OU(d.getBoundingClientRect(),f.getBoundingClientRect());o={getBoundingClientRect:()=>p,getClientRects:()=>[p]}}return o}updatePosition(){const t=this.virtualElement;t&&Y2(t,this.element,{placement:this.floatingUIOptions.placement,strategy:this.floatingUIOptions.strategy,middleware:this.middlewares}).then(({x:e,y:n,strategy:r,middlewareData:i})=>{var s,o;if((s=i.hide)!=null&&s.referenceHidden||(o=i.hide)!=null&&o.escaped){this.element.style.visibility="hidden";return}this.element.style.visibility="visible",this.element.style.width="max-content",this.element.style.position=r,this.element.style.left=`${e}px`,this.element.style.top=`${n}px`,this.isVisible&&this.floatingUIOptions.onUpdate&&this.floatingUIOptions.onUpdate()})}update(t,e){const{state:n}=t,r=n.selection.from!==n.selection.to;if(this.updateDelay>0&&r){this.handleDebouncedUpdate(t,e);return}const i=!(e!=null&&e.selection.eq(t.state.selection)),s=!(e!=null&&e.doc.eq(t.state.doc));this.updateHandler(t,i,s,e)}getShouldShow(t){var e;const{state:n}=this.view,{selection:r}=n,{ranges:i}=r,s=Math.min(...i.map(a=>a.$from.pos)),o=Math.max(...i.map(a=>a.$to.pos));return((e=this.shouldShow)==null?void 0:e.call(this,{editor:this.editor,element:this.element,view:this.view,state:n,oldState:t,from:s,to:o}))||!1}show(){var t;if(this.isVisible)return;this.element.style.visibility="visible",this.element.style.opacity="1";const e=typeof this.appendTo=="function"?this.appendTo():this.appendTo;(t=e??this.view.dom.parentElement)==null||t.appendChild(this.element),this.floatingUIOptions.onShow&&this.floatingUIOptions.onShow(),this.isVisible=!0}hide(){this.isVisible&&(this.element.style.visibility="hidden",this.element.style.opacity="0",this.element.remove(),this.floatingUIOptions.onHide&&this.floatingUIOptions.onHide(),this.isVisible=!1)}updateOptions(t){var e;if(t.updateDelay!==void 0&&(this.updateDelay=t.updateDelay),t.resizeDelay!==void 0&&(this.resizeDelay=t.resizeDelay),t.appendTo!==void 0&&(this.appendTo=t.appendTo),t.getReferencedVirtualElement!==void 0&&(this.getReferencedVirtualElement=t.getReferencedVirtualElement),t.shouldShow!==void 0&&t.shouldShow&&(this.shouldShow=t.shouldShow),t.options!==void 0){const n=(e=t.options.scrollTarget)!=null?e:window;n!==this.scrollTarget&&(this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.scrollTarget=n,this.scrollTarget.addEventListener("scroll",this.resizeHandler)),this.floatingUIOptions={...this.floatingUIOptions,...t.options}}}destroy(){this.hide(),this.element.removeEventListener("mousedown",this.mousedownHandler,{capture:!0}),this.view.dom.removeEventListener("dragstart",this.dragstartHandler),window.removeEventListener("resize",this.resizeHandler),this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.editor.off("focus",this.focusHandler),this.editor.off("blur",this.blurHandler),this.editor.off("transaction",this.transactionHandler),this.floatingUIOptions.onDestroy&&this.floatingUIOptions.onDestroy()}},eR=t=>new hn({key:typeof t.pluginKey=="string"?new pn(t.pluginKey):t.pluginKey,view:e=>new jU({view:e,...t})});mn.create({name:"bubbleMenu",addOptions(){return{element:null,pluginKey:"bubbleMenu",updateDelay:void 0,appendTo:void 0,shouldShow:null}},addProseMirrorPlugins(){return this.options.element?[eR({pluginKey:this.options.pluginKey,editor:this.editor,element:this.options.element,updateDelay:this.options.updateDelay,options:this.options.options,appendTo:this.options.appendTo,getReferencedVirtualElement:this.options.getReferencedVirtualElement,shouldShow:this.options.shouldShow})]:[]}});var PU=class{constructor({editor:t,element:e,view:n,updateDelay:r=250,resizeDelay:i=60,options:s,appendTo:o,shouldShow:l}){this.preventHide=!1,this.isVisible=!1,this.scrollTarget=window,this.shouldShow=({view:c,state:u})=>{const{selection:d}=u,{$anchor:f,empty:p}=d,m=f.depth===1,g=f.parent.isTextblock&&!f.parent.type.spec.code&&!f.parent.textContent&&f.parent.childCount===0&&!this.getTextContent(f.parent);return!(!c.hasFocus()||!p||!m||!g||!this.editor.isEditable)},this.floatingUIOptions={strategy:"absolute",placement:"right",offset:8,flip:{},shift:{},arrow:!1,size:!1,autoPlacement:!1,hide:!1,inline:!1},this.updateHandler=(c,u,d,f)=>{const{composing:p}=c;if(p||!u&&!d)return;if(!this.getShouldShow(f)){this.hide();return}this.updatePosition(),this.show()},this.mousedownHandler=()=>{this.preventHide=!0},this.focusHandler=()=>{setTimeout(()=>this.update(this.editor.view))},this.blurHandler=({event:c})=>{var u;if(this.preventHide){this.preventHide=!1;return}c!=null&&c.relatedTarget&&((u=this.element.parentNode)!=null&&u.contains(c.relatedTarget))||(c==null?void 0:c.relatedTarget)!==this.editor.view.dom&&this.hide()},this.transactionHandler=({transaction:c})=>{const u=c.getMeta("floatingMenu");u==="updatePosition"?this.updatePosition():u&&typeof u=="object"&&u.type==="updateOptions"&&this.updateOptions(u.options)},this.resizeHandler=()=>{this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=window.setTimeout(()=>{this.updatePosition()},this.resizeDelay)};var a;this.editor=t,this.element=e,this.view=n,this.updateDelay=r,this.resizeDelay=i,this.appendTo=o,this.scrollTarget=(a=s==null?void 0:s.scrollTarget)!=null?a:window,this.floatingUIOptions={...this.floatingUIOptions,...s},this.element.tabIndex=0,l&&(this.shouldShow=l),this.element.addEventListener("mousedown",this.mousedownHandler,{capture:!0}),this.editor.on("focus",this.focusHandler),this.editor.on("blur",this.blurHandler),this.editor.on("transaction",this.transactionHandler),window.addEventListener("resize",this.resizeHandler),this.scrollTarget.addEventListener("scroll",this.resizeHandler),this.update(n,n.state),this.getShouldShow()&&(this.show(),this.updatePosition())}getTextContent(t){return t2(t,{textSerializers:rx(this.editor.schema)})}get middlewares(){const t=[];return this.floatingUIOptions.flip&&t.push(U2(typeof this.floatingUIOptions.flip!="boolean"?this.floatingUIOptions.flip:void 0)),this.floatingUIOptions.shift&&t.push(B2(typeof this.floatingUIOptions.shift!="boolean"?this.floatingUIOptions.shift:void 0)),this.floatingUIOptions.offset&&t.push(F2(typeof this.floatingUIOptions.offset!="boolean"?this.floatingUIOptions.offset:void 0)),this.floatingUIOptions.arrow&&t.push(W2(this.floatingUIOptions.arrow)),this.floatingUIOptions.size&&t.push(H2(typeof this.floatingUIOptions.size!="boolean"?this.floatingUIOptions.size:void 0)),this.floatingUIOptions.autoPlacement&&t.push($2(typeof this.floatingUIOptions.autoPlacement!="boolean"?this.floatingUIOptions.autoPlacement:void 0)),this.floatingUIOptions.hide&&t.push(V2(typeof this.floatingUIOptions.hide!="boolean"?this.floatingUIOptions.hide:void 0)),this.floatingUIOptions.inline&&t.push(K2(typeof this.floatingUIOptions.inline!="boolean"?this.floatingUIOptions.inline:void 0)),t}getShouldShow(t){var e;const{state:n}=this.view,{selection:r}=n,{ranges:i}=r,s=Math.min(...i.map(a=>a.$from.pos)),o=Math.max(...i.map(a=>a.$to.pos));return(e=this.shouldShow)==null?void 0:e.call(this,{editor:this.editor,view:this.view,state:n,oldState:t,from:s,to:o})}updateOptions(t){var e;if(t.updateDelay!==void 0&&(this.updateDelay=t.updateDelay),t.resizeDelay!==void 0&&(this.resizeDelay=t.resizeDelay),t.appendTo!==void 0&&(this.appendTo=t.appendTo),t.shouldShow!==void 0&&t.shouldShow&&(this.shouldShow=t.shouldShow),t.options!==void 0){const n=(e=t.options.scrollTarget)!=null?e:window;n!==this.scrollTarget&&(this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.scrollTarget=n,this.scrollTarget.addEventListener("scroll",this.resizeHandler)),this.floatingUIOptions={...this.floatingUIOptions,...t.options}}}updatePosition(){const{selection:t}=this.editor.state,e=l2(this.view,t.from,t.to);Y2({getBoundingClientRect:()=>e,getClientRects:()=>[e]},this.element,{placement:this.floatingUIOptions.placement,strategy:this.floatingUIOptions.strategy,middleware:this.middlewares}).then(({x:r,y:i,strategy:s,middlewareData:o})=>{var l,a;if((l=o.hide)!=null&&l.referenceHidden||(a=o.hide)!=null&&a.escaped){this.element.style.visibility="hidden";return}this.element.style.visibility="visible",this.element.style.width="max-content",this.element.style.position=s,this.element.style.left=`${r}px`,this.element.style.top=`${i}px`,this.isVisible&&this.floatingUIOptions.onUpdate&&this.floatingUIOptions.onUpdate()})}update(t,e){const n=!(e!=null&&e.selection.eq(t.state.selection)),r=!(e!=null&&e.doc.eq(t.state.doc));this.updateHandler(t,n,r,e)}show(){var t;if(this.isVisible)return;this.element.style.visibility="visible",this.element.style.opacity="1";const e=typeof this.appendTo=="function"?this.appendTo():this.appendTo;(t=e??this.view.dom.parentElement)==null||t.appendChild(this.element),this.floatingUIOptions.onShow&&this.floatingUIOptions.onShow(),this.isVisible=!0}hide(){this.isVisible&&(this.element.style.visibility="hidden",this.element.style.opacity="0",this.element.remove(),this.floatingUIOptions.onHide&&this.floatingUIOptions.onHide(),this.isVisible=!1)}destroy(){this.hide(),this.element.removeEventListener("mousedown",this.mousedownHandler,{capture:!0}),window.removeEventListener("resize",this.resizeHandler),this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.editor.off("focus",this.focusHandler),this.editor.off("blur",this.blurHandler),this.editor.off("transaction",this.transactionHandler),this.floatingUIOptions.onDestroy&&this.floatingUIOptions.onDestroy()}},tR=t=>new hn({key:typeof t.pluginKey=="string"?new pn(t.pluginKey):t.pluginKey,view:e=>new PU({view:e,...t})});mn.create({name:"floatingMenu",addOptions(){return{element:null,options:{},pluginKey:"floatingMenu",updateDelay:void 0,resizeDelay:void 0,appendTo:void 0,shouldShow:null}},addCommands(){return{updateFloatingMenuPosition:()=>({tr:t,dispatch:e})=>(e&&t.setMeta("floatingMenu","updatePosition"),!0)}},addProseMirrorPlugins(){return this.options.element?[tR({pluginKey:this.options.pluginKey,editor:this.editor,element:this.options.element,updateDelay:this.options.updateDelay,resizeDelay:this.options.resizeDelay,options:this.options.options,appendTo:this.options.appendTo,shouldShow:this.options.shouldShow})]:[]}});var LU=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},_U=({contentComponent:t})=>{const e=Rb.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return h.jsx(h.Fragment,{children:Object.values(e)})};function zU(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,r){e={...e,[n]:l_.createPortal(r.reactElement,r.element,n)},t.forEach(i=>i())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(i=>i())}}}var FU=class extends B.Component{constructor(t){var e;super(t),this.editorContentRef=B.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!((e=t.editor)!=null&&e.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var t;const e=this.props.editor;if(e&&!e.isDestroyed&&((t=e.view.dom)!=null&&t.parentNode)){if(e.contentComponent)return;const n=this.editorContentRef.current;n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n}),e.contentComponent=zU(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),e.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return h.jsxs(h.Fragment,{children:[h.jsx("div",{ref:LU(e,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&h.jsx(_U,{contentComponent:t.contentComponent})]})}},$U=b.forwardRef((t,e)=>{const n=B.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return B.createElement(FU,{key:n,innerRef:e,...t})}),Qd=B.memo($U),BU=typeof window<"u"?b.useLayoutEffect:b.useEffect,UU=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(r=>r())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function HU(t){var e;const[n]=b.useState(()=>new UU(t.editor)),r=I6.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:x6);return BU(()=>n.watch(t.editor),[t.editor,n]),b.useDebugValue(r),r}var VU=!1,$0=typeof window>"u",WU=$0||!!(typeof window<"u"&&window.next),KU=class nR{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?$0||WU?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...r)},onBlur:(...r)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...r)},onCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...r)},onDestroy:(...r)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...r)},onFocus:(...r)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...r)},onSelectionUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...r)},onTransaction:(...r)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...r)},onUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...r)},onContentError:(...r)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...r)},onDrop:(...r)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...r)},onPaste:(...r)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...r)},onDelete:(...r)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...r)}};return new ag(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((i,s)=>{var o;return i===((o=n.extensions)==null?void 0:o[s])}):e[r]===n[r])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?nR.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((r,i)=>r===e[i]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function pg(t={},e=[]){const n=b.useRef(t);n.current=t;const[r]=b.useState(()=>new KU(n)),i=Rb.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return b.useDebugValue(i),b.useEffect(r.onRender(e)),HU({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var yx=b.createContext({editor:null});yx.Consumer;var rR=()=>b.useContext(yx),YU=b.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),qU=()=>b.useContext(YU);B.forwardRef((t,e)=>{const{onDragStart:n}=qU(),r=t.as||"div";return h.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});B.createContext({markViewContentRef:()=>{}});var JU=B.forwardRef(({pluginKey:t="bubbleMenu",editor:e,updateDelay:n,resizeDelay:r,appendTo:i,shouldShow:s=null,getReferencedVirtualElement:o,options:l,children:a,...c},u)=>{const d=b.useRef(document.createElement("div"));typeof u=="function"?u(d.current):u&&(u.current=d.current);const{editor:f}=rR(),p=e||f,m={updateDelay:n,resizeDelay:r,appendTo:i,pluginKey:t,shouldShow:s,getReferencedVirtualElement:o,options:l},g=b.useRef(m);g.current=m;const[y,v]=b.useState(!1),w=b.useRef(!0);return b.useEffect(()=>{if(p!=null&&p.isDestroyed)return;if(!p){console.warn("BubbleMenu component is not rendered inside of an editor component or does not have editor prop.");return}const x=d.current;x.style.visibility="hidden",x.style.position="absolute";const E=eR({...g.current,editor:p,element:x});p.registerPlugin(E);const k=g.current.pluginKey;return w.current=!0,v(!0),()=>{v(!1),p.unregisterPlugin(k),window.requestAnimationFrame(()=>{x.parentNode&&x.parentNode.removeChild(x)})}},[p]),b.useEffect(()=>{if(!(!y||!p||p.isDestroyed)){if(w.current){w.current=!1;return}p.view.dispatch(p.state.tr.setMeta("bubbleMenu",{type:"updateOptions",options:g.current}))}},[y,p,n,r,s,l,i,o]),zn.createPortal(h.jsx("div",{...c,children:a}),d.current)}),GU=B.forwardRef(({pluginKey:t="floatingMenu",editor:e,updateDelay:n,resizeDelay:r,appendTo:i,shouldShow:s=null,options:o,children:l,...a},c)=>{const u=b.useRef(document.createElement("div"));typeof c=="function"?c(u.current):c&&(c.current=u.current);const{editor:d}=rR(),f=e||d,p={updateDelay:n,resizeDelay:r,appendTo:i,pluginKey:t,shouldShow:s,options:o},m=b.useRef(p);m.current=p;const[g,y]=b.useState(!1),v=b.useRef(!0);return b.useEffect(()=>{if(f!=null&&f.isDestroyed)return;if(!f){console.warn("FloatingMenu component is not rendered inside of an editor component or does not have editor prop.");return}const w=u.current;w.style.visibility="hidden",w.style.position="absolute";const x=tR({...m.current,editor:f,element:w});f.registerPlugin(x);const E=m.current.pluginKey;return v.current=!0,y(!0),()=>{y(!1),f.unregisterPlugin(E),window.requestAnimationFrame(()=>{w.parentNode&&w.parentNode.removeChild(w)})}},[f]),b.useEffect(()=>{if(!(!g||!f||f.isDestroyed)){if(v.current){v.current=!1;return}f.view.dispatch(f.state.tr.setMeta("floatingMenu",{type:"updateOptions",options:m.current}))}},[g,f,n,r,s,o,i]),zn.createPortal(h.jsx("div",{...a,children:l}),u.current)}),vx=b.createContext({editor:null,isReady:!1});vx.displayName="TiptapContext";var mg=()=>b.useContext(vx);function iR({instance:t,children:e}){var n;const[r,i]=b.useState((n=t==null?void 0:t.isInitialized)!=null?n:!1);b.useEffect(()=>{if(!t){i(!1);return}if(t.isInitialized){i(!0);return}const l=()=>{i(!0)};return t.on("create",l),()=>{t.off("create",l)}},[t]);const s=b.useMemo(()=>({editor:t,isReady:r}),[t,r]),o=b.useMemo(()=>({editor:t}),[t]);return h.jsx(yx.Provider,{value:o,children:h.jsx(vx.Provider,{value:s,children:e})})}iR.displayName="Tiptap";function sR({...t}){const{editor:e}=mg();return h.jsx(Qd,{editor:e,...t})}sR.displayName="Tiptap.Content";function oR({children:t}){const{isReady:e}=mg();return e?null:t}oR.displayName="Tiptap.Loading";function lR({children:t,...e}){const{editor:n}=mg();return n?h.jsx(JU,{editor:n,...e,children:t}):null}lR.displayName="Tiptap.BubbleMenu";function aR({children:t,...e}){const{editor:n}=mg();return n?h.jsx(GU,{...e,editor:n,children:t}):null}aR.displayName="Tiptap.FloatingMenu";Object.assign(iR,{Content:sR,Loading:oR,BubbleMenu:lR,FloatingMenu:aR});var Dp=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},XU=/^\s*>\s$/,QU=yi.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return Dp("blockquote",{...Yn(this.options.HTMLAttributes,t),children:Dp("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",r=[];return t.content.forEach(i=>{const l=e.renderChildren([i]).split(` + */var cg=b,k6=Rb;function S6(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var C6=typeof Object.is=="function"?Object.is:S6,E6=k6.useSyncExternalStore,N6=cg.useRef,T6=cg.useEffect,A6=cg.useMemo,M6=cg.useDebugValue;E2.useSyncExternalStoreWithSelector=function(t,e,n,r,i){var s=N6(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=A6(function(){function a(p){if(!c){if(c=!0,u=p,p=r(p),i!==void 0&&o.hasValue){var m=o.value;if(i(m,p))return d=m}return d=p}if(m=d,C6(u,p))return m;var g=r(p);return i!==void 0&&i(m,g)?(u=p,m):(u=p,d=g)}var c=!1,u,d,f=n===void 0?null:n;return[function(){return a(e())},f===null?void 0:function(){return a(f())}]},[e,n,r,i]);var l=E6(t,s[0],s[1]);return T6(function(){o.hasValue=!0,o.value=l},[l]),M6(l),l};C2.exports=E2;var I6=C2.exports;const N2=["top","right","bottom","left"],_C=["start","end"],zC=N2.reduce((t,e)=>t.concat(e,e+"-"+_C[0],e+"-"+_C[1]),[]),Ms=Math.min,zr=Math.max,Mp=Math.round,Cs=t=>({x:t,y:t}),R6={left:"right",right:"left",bottom:"top",top:"bottom"},D6={start:"end",end:"start"};function L0(t,e,n){return zr(t,Ms(e,n))}function go(t,e){return typeof t=="function"?t(e):t}function _i(t){return t.split("-")[0]}function Zi(t){return t.split("-")[1]}function T2(t){return t==="x"?"y":"x"}function ux(t){return t==="y"?"height":"width"}const O6=new Set(["top","bottom"]);function ws(t){return O6.has(_i(t))?"y":"x"}function dx(t){return T2(ws(t))}function A2(t,e,n){n===void 0&&(n=!1);const r=Zi(t),i=dx(t),s=ux(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=Rp(o)),[o,Rp(o)]}function j6(t){const e=Rp(t);return[Ip(t),e,Ip(e)]}function Ip(t){return t.replace(/start|end/g,e=>D6[e])}const FC=["left","right"],$C=["right","left"],P6=["top","bottom"],L6=["bottom","top"];function _6(t,e,n){switch(t){case"top":case"bottom":return n?e?$C:FC:e?FC:$C;case"left":case"right":return e?P6:L6;default:return[]}}function z6(t,e,n,r){const i=Zi(t);let s=_6(_i(t),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),e&&(s=s.concat(s.map(Ip)))),s}function Rp(t){return t.replace(/left|right|bottom|top/g,e=>R6[e])}function F6(t){return{top:0,right:0,bottom:0,left:0,...t}}function fx(t){return typeof t!="number"?F6(t):{top:t,right:t,bottom:t,left:t}}function wc(t){const{x:e,y:n,width:r,height:i}=t;return{width:r,height:i,top:n,left:e,right:e+r,bottom:n+i,x:e,y:n}}function BC(t,e,n){let{reference:r,floating:i}=t;const s=ws(e),o=dx(e),l=ux(o),a=_i(e),c=s==="y",u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[l]/2-i[l]/2;let p;switch(a){case"top":p={x:u,y:r.y-i.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:d};break;case"left":p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}switch(Zi(e)){case"start":p[o]-=f*(n&&c?-1:1);break;case"end":p[o]+=f*(n&&c?-1:1);break}return p}async function $6(t,e){var n;e===void 0&&(e={});const{x:r,y:i,platform:s,rects:o,elements:l,strategy:a}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=go(e,t),m=fx(p),y=l[f?d==="floating"?"reference":"floating":d],v=wc(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:c,rootBoundary:u,strategy:a})),w=d==="floating"?{x:r,y:i,width:o.floating.width,height:o.floating.height}:o.reference,x=await(s.getOffsetParent==null?void 0:s.getOffsetParent(l.floating)),E=await(s.isElement==null?void 0:s.isElement(x))?await(s.getScale==null?void 0:s.getScale(x))||{x:1,y:1}:{x:1,y:1},k=wc(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:w,offsetParent:x,strategy:a}):w);return{top:(v.top-k.top+m.top)/E.y,bottom:(k.bottom-v.bottom+m.bottom)/E.y,left:(v.left-k.left+m.left)/E.x,right:(k.right-v.right+m.right)/E.x}}const B6=async(t,e,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,l=s.filter(Boolean),a=await(o.isRTL==null?void 0:o.isRTL(e));let c=await o.getElementRects({reference:t,floating:e,strategy:i}),{x:u,y:d}=BC(c,r,a),f=r,p={},m=0;for(let y=0;y({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:i,rects:s,platform:o,elements:l,middlewareData:a}=e,{element:c,padding:u=0}=go(t,e)||{};if(c==null)return{};const d=fx(u),f={x:n,y:r},p=dx(i),m=ux(p),g=await o.getDimensions(c),y=p==="y",v=y?"top":"left",w=y?"bottom":"right",x=y?"clientHeight":"clientWidth",E=s.reference[m]+s.reference[p]-f[p]-s.floating[m],k=f[p]-s.reference[p],M=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c));let N=M?M[x]:0;(!N||!await(o.isElement==null?void 0:o.isElement(M)))&&(N=l.floating[x]||s.floating[m]);const z=E/2-k/2,X=N/2-g[m]/2-1,L=Ms(d[v],X),H=Ms(d[w],X),W=L,te=N-g[m]-H,ue=N/2-g[m]/2+z,de=L0(W,ue,te),Ae=!a.arrow&&Zi(i)!=null&&ue!==de&&s.reference[m]/2-(ueZi(i)===t),...n.filter(i=>Zi(i)!==t)]:n.filter(i=>_i(i)===i)).filter(i=>t?Zi(i)===t||(e?Ip(i)!==i:!1):!0)}const V6=function(t){return t===void 0&&(t={}),{name:"autoPlacement",options:t,async fn(e){var n,r,i;const{rects:s,middlewareData:o,placement:l,platform:a,elements:c}=e,{crossAxis:u=!1,alignment:d,allowedPlacements:f=zC,autoAlignment:p=!0,...m}=go(t,e),g=d!==void 0||f===zC?H6(d||null,p,f):f,y=await a.detectOverflow(e,m),v=((n=o.autoPlacement)==null?void 0:n.index)||0,w=g[v];if(w==null)return{};const x=A2(w,s,await(a.isRTL==null?void 0:a.isRTL(c.floating)));if(l!==w)return{reset:{placement:g[0]}};const E=[y[_i(w)],y[x[0]],y[x[1]]],k=[...((r=o.autoPlacement)==null?void 0:r.overflows)||[],{placement:w,overflows:E}],M=g[v+1];if(M)return{data:{index:v+1,overflows:k},reset:{placement:M}};const N=k.map(L=>{const H=Zi(L.placement);return[L.placement,H&&u?L.overflows.slice(0,2).reduce((W,te)=>W+te,0):L.overflows[0],L.overflows]}).sort((L,H)=>L[1]-H[1]),X=((i=N.filter(L=>L[2].slice(0,Zi(L[0])?2:3).every(H=>H<=0))[0])==null?void 0:i[0])||N[0][0];return X!==l?{data:{index:v+1,overflows:k},reset:{placement:X}}:{}}}},W6=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:i,middlewareData:s,rects:o,initialPlacement:l,platform:a,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=go(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=_i(i),w=ws(l),x=_i(l)===l,E=await(a.isRTL==null?void 0:a.isRTL(c.floating)),k=f||(x||!g?[Rp(l)]:j6(l)),M=m!=="none";!f&&M&&k.push(...z6(l,g,m,E));const N=[l,...k],z=await a.detectOverflow(e,y),X=[];let L=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&X.push(z[v]),d){const ue=A2(i,o,E);X.push(z[ue[0]],z[ue[1]])}if(L=[...L,{placement:i,overflows:X}],!X.every(ue=>ue<=0)){var H,W;const ue=(((H=s.flip)==null?void 0:H.index)||0)+1,de=N[ue];if(de&&(!(d==="alignment"?w!==ws(de):!1)||L.every(q=>ws(q.placement)===w?q.overflows[0]>0:!0)))return{data:{index:ue,overflows:L},reset:{placement:de}};let Ae=(W=L.filter(me=>me.overflows[0]<=0).sort((me,q)=>me.overflows[1]-q.overflows[1])[0])==null?void 0:W.placement;if(!Ae)switch(p){case"bestFit":{var te;const me=(te=L.filter(q=>{if(M){const se=ws(q.placement);return se===w||se==="y"}return!0}).map(q=>[q.placement,q.overflows.filter(se=>se>0).reduce((se,xe)=>se+xe,0)]).sort((q,se)=>q[1]-se[1])[0])==null?void 0:te[0];me&&(Ae=me);break}case"initialPlacement":Ae=l;break}if(i!==Ae)return{reset:{placement:Ae}}}return{}}}};function UC(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function HC(t){return N2.some(e=>t[e]>=0)}const K6=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n,platform:r}=e,{strategy:i="referenceHidden",...s}=go(t,e);switch(i){case"referenceHidden":{const o=await r.detectOverflow(e,{...s,elementContext:"reference"}),l=UC(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:HC(l)}}}case"escaped":{const o=await r.detectOverflow(e,{...s,altBoundary:!0}),l=UC(o,n.floating);return{data:{escapedOffsets:l,escaped:HC(l)}}}default:return{}}}}};function M2(t){const e=Ms(...t.map(s=>s.left)),n=Ms(...t.map(s=>s.top)),r=zr(...t.map(s=>s.right)),i=zr(...t.map(s=>s.bottom));return{x:e,y:n,width:r-e,height:i-n}}function Y6(t){const e=t.slice().sort((i,s)=>i.y-s.y),n=[];let r=null;for(let i=0;ir.height/2?n.push([s]):n[n.length-1].push(s),r=s}return n.map(i=>wc(M2(i)))}const q6=function(t){return t===void 0&&(t={}),{name:"inline",options:t,async fn(e){const{placement:n,elements:r,rects:i,platform:s,strategy:o}=e,{padding:l=2,x:a,y:c}=go(t,e),u=Array.from(await(s.getClientRects==null?void 0:s.getClientRects(r.reference))||[]),d=Y6(u),f=wc(M2(u)),p=fx(l);function m(){if(d.length===2&&d[0].left>d[1].right&&a!=null&&c!=null)return d.find(y=>a>y.left-p.left&&ay.top-p.top&&c=2){if(ws(n)==="y"){const L=d[0],H=d[d.length-1],W=_i(n)==="top",te=L.top,ue=H.bottom,de=W?L.left:H.left,Ae=W?L.right:H.right,me=Ae-de,q=ue-te;return{top:te,bottom:ue,left:de,right:Ae,width:me,height:q,x:de,y:te}}const y=_i(n)==="left",v=zr(...d.map(L=>L.right)),w=Ms(...d.map(L=>L.left)),x=d.filter(L=>y?L.left===w:L.right===v),E=x[0].top,k=x[x.length-1].bottom,M=w,N=v,z=N-M,X=k-E;return{top:E,bottom:k,left:M,right:N,width:z,height:X,x:M,y:E}}return f}const g=await s.getElementRects({reference:{getBoundingClientRect:m},floating:r.floating,strategy:o});return i.reference.x!==g.reference.x||i.reference.y!==g.reference.y||i.reference.width!==g.reference.width||i.reference.height!==g.reference.height?{reset:{rects:g}}:{}}}},J6=new Set(["left","top"]);async function G6(t,e){const{placement:n,platform:r,elements:i}=t,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=_i(n),l=Zi(n),a=ws(n)==="y",c=J6.has(o)?-1:1,u=s&&a?-1:1,d=go(e,t);let{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return l&&typeof m=="number"&&(p=l==="end"?m*-1:m),a?{x:p*u,y:f*c}:{x:f*c,y:p*u}}const X6=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:i,y:s,placement:o,middlewareData:l}=e,a=await G6(e,t);return o===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:i+a.x,y:s+a.y,data:{...a,placement:o}}}}},Q6=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:i,platform:s}=e,{mainAxis:o=!0,crossAxis:l=!1,limiter:a={fn:v=>{let{x:w,y:x}=v;return{x:w,y:x}}},...c}=go(t,e),u={x:n,y:r},d=await s.detectOverflow(e,c),f=ws(_i(i)),p=T2(f);let m=u[p],g=u[f];if(o){const v=p==="y"?"top":"left",w=p==="y"?"bottom":"right",x=m+d[v],E=m-d[w];m=L0(x,m,E)}if(l){const v=f==="y"?"top":"left",w=f==="y"?"bottom":"right",x=g+d[v],E=g-d[w];g=L0(x,g,E)}const y=a.fn({...e,[p]:m,[f]:g});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[p]:o,[f]:l}}}}}},Z6=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:i,rects:s,platform:o,elements:l}=e,{apply:a=()=>{},...c}=go(t,e),u=await o.detectOverflow(e,c),d=_i(i),f=Zi(i),p=ws(i)==="y",{width:m,height:g}=s.floating;let y,v;d==="top"||d==="bottom"?(y=d,v=f===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(v=d,y=f==="end"?"top":"bottom");const w=g-u.top-u.bottom,x=m-u.left-u.right,E=Ms(g-u[y],w),k=Ms(m-u[v],x),M=!e.middlewareData.shift;let N=E,z=k;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(z=x),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(N=w),M&&!f){const L=zr(u.left,0),H=zr(u.right,0),W=zr(u.top,0),te=zr(u.bottom,0);p?z=m-2*(L!==0||H!==0?L+H:zr(u.left,u.right)):N=g-2*(W!==0||te!==0?W+te:zr(u.top,u.bottom))}await a({...e,availableWidth:z,availableHeight:N});const X=await o.getDimensions(l.floating);return m!==X.width||g!==X.height?{reset:{rects:!0}}:{}}}};function ug(){return typeof window<"u"}function Pc(t){return I2(t)?(t.nodeName||"").toLowerCase():"#document"}function hi(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function yo(t){var e;return(e=(I2(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function I2(t){return ug()?t instanceof Node||t instanceof hi(t).Node:!1}function ns(t){return ug()?t instanceof Element||t instanceof hi(t).Element:!1}function Is(t){return ug()?t instanceof HTMLElement||t instanceof hi(t).HTMLElement:!1}function VC(t){return!ug()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof hi(t).ShadowRoot}const eU=new Set(["inline","contents"]);function Xd(t){const{overflow:e,overflowX:n,overflowY:r,display:i}=rs(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!eU.has(i)}const tU=new Set(["table","td","th"]);function nU(t){return tU.has(Pc(t))}const rU=[":popover-open",":modal"];function dg(t){return rU.some(e=>{try{return t.matches(e)}catch{return!1}})}const iU=["transform","translate","scale","rotate","perspective"],sU=["transform","translate","scale","rotate","perspective","filter"],oU=["paint","layout","strict","content"];function hx(t){const e=px(),n=ns(t)?rs(t):t;return iU.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||sU.some(r=>(n.willChange||"").includes(r))||oU.some(r=>(n.contain||"").includes(r))}function lU(t){let e=ll(t);for(;Is(e)&&!bc(e);){if(hx(e))return e;if(dg(e))return null;e=ll(e)}return null}function px(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const aU=new Set(["html","body","#document"]);function bc(t){return aU.has(Pc(t))}function rs(t){return hi(t).getComputedStyle(t)}function fg(t){return ns(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function ll(t){if(Pc(t)==="html")return t;const e=t.assignedSlot||t.parentNode||VC(t)&&t.host||yo(t);return VC(e)?e.host:e}function R2(t){const e=ll(t);return bc(e)?t.ownerDocument?t.ownerDocument.body:t.body:Is(e)&&Xd(e)?e:R2(e)}function D2(t,e,n){var r;e===void 0&&(e=[]);const i=R2(t),s=i===((r=t.ownerDocument)==null?void 0:r.body),o=hi(i);return s?(_0(o),e.concat(o,o.visualViewport||[],Xd(i)?i:[],[])):e.concat(i,D2(i,[]))}function _0(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function O2(t){const e=rs(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const i=Is(t),s=i?t.offsetWidth:n,o=i?t.offsetHeight:r,l=Mp(n)!==s||Mp(r)!==o;return l&&(n=s,r=o),{width:n,height:r,$:l}}function j2(t){return ns(t)?t:t.contextElement}function Ga(t){const e=j2(t);if(!Is(e))return Cs(1);const n=e.getBoundingClientRect(),{width:r,height:i,$:s}=O2(e);let o=(s?Mp(n.width):n.width)/r,l=(s?Mp(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const cU=Cs(0);function P2(t){const e=hi(t);return!px()||!e.visualViewport?cU:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function uU(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==hi(t)?!1:e}function xd(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const i=t.getBoundingClientRect(),s=j2(t);let o=Cs(1);e&&(r?ns(r)&&(o=Ga(r)):o=Ga(t));const l=uU(s,n,r)?P2(s):Cs(0);let a=(i.left+l.x)/o.x,c=(i.top+l.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(s){const f=hi(s),p=r&&ns(r)?hi(r):r;let m=f,g=_0(m);for(;g&&r&&p!==m;){const y=Ga(g),v=g.getBoundingClientRect(),w=rs(g),x=v.left+(g.clientLeft+parseFloat(w.paddingLeft))*y.x,E=v.top+(g.clientTop+parseFloat(w.paddingTop))*y.y;a*=y.x,c*=y.y,u*=y.x,d*=y.y,a+=x,c+=E,m=hi(g),g=_0(m)}}return wc({width:u,height:d,x:a,y:c})}function hg(t,e){const n=fg(t).scrollLeft;return e?e.left+n:xd(yo(t)).left+n}function L2(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-hg(t,n),i=n.top+e.scrollTop;return{x:r,y:i}}function dU(t){let{elements:e,rect:n,offsetParent:r,strategy:i}=t;const s=i==="fixed",o=yo(r),l=e?dg(e.floating):!1;if(r===o||l&&s)return n;let a={scrollLeft:0,scrollTop:0},c=Cs(1);const u=Cs(0),d=Is(r);if((d||!d&&!s)&&((Pc(r)!=="body"||Xd(o))&&(a=fg(r)),Is(r))){const p=xd(r);c=Ga(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const f=o&&!d&&!s?L2(o,a):Cs(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-a.scrollLeft*c.x+u.x+f.x,y:n.y*c.y-a.scrollTop*c.y+u.y+f.y}}function fU(t){return Array.from(t.getClientRects())}function hU(t){const e=yo(t),n=fg(t),r=t.ownerDocument.body,i=zr(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=zr(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+hg(t);const l=-n.scrollTop;return rs(r).direction==="rtl"&&(o+=zr(e.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:l}}const WC=25;function pU(t,e){const n=hi(t),r=yo(t),i=n.visualViewport;let s=r.clientWidth,o=r.clientHeight,l=0,a=0;if(i){s=i.width,o=i.height;const u=px();(!u||u&&e==="fixed")&&(l=i.offsetLeft,a=i.offsetTop)}const c=hg(r);if(c<=0){const u=r.ownerDocument,d=u.body,f=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,m=Math.abs(r.clientWidth-d.clientWidth-p);m<=WC&&(s-=m)}else c<=WC&&(s+=c);return{width:s,height:o,x:l,y:a}}const mU=new Set(["absolute","fixed"]);function gU(t,e){const n=xd(t,!0,e==="fixed"),r=n.top+t.clientTop,i=n.left+t.clientLeft,s=Is(t)?Ga(t):Cs(1),o=t.clientWidth*s.x,l=t.clientHeight*s.y,a=i*s.x,c=r*s.y;return{width:o,height:l,x:a,y:c}}function KC(t,e,n){let r;if(e==="viewport")r=pU(t,n);else if(e==="document")r=hU(yo(t));else if(ns(e))r=gU(e,n);else{const i=P2(t);r={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return wc(r)}function _2(t,e){const n=ll(t);return n===e||!ns(n)||bc(n)?!1:rs(n).position==="fixed"||_2(n,e)}function yU(t,e){const n=e.get(t);if(n)return n;let r=D2(t,[]).filter(l=>ns(l)&&Pc(l)!=="body"),i=null;const s=rs(t).position==="fixed";let o=s?ll(t):t;for(;ns(o)&&!bc(o);){const l=rs(o),a=hx(o);!a&&l.position==="fixed"&&(i=null),(s?!a&&!i:!a&&l.position==="static"&&!!i&&mU.has(i.position)||Xd(o)&&!a&&_2(t,o))?r=r.filter(u=>u!==o):i=l,o=ll(o)}return e.set(t,r),r}function vU(t){let{element:e,boundary:n,rootBoundary:r,strategy:i}=t;const o=[...n==="clippingAncestors"?dg(e)?[]:yU(e,this._c):[].concat(n),r],l=o[0],a=o.reduce((c,u)=>{const d=KC(e,u,i);return c.top=zr(d.top,c.top),c.right=Ms(d.right,c.right),c.bottom=Ms(d.bottom,c.bottom),c.left=zr(d.left,c.left),c},KC(e,l,i));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}}function wU(t){const{width:e,height:n}=O2(t);return{width:e,height:n}}function bU(t,e,n){const r=Is(e),i=yo(e),s=n==="fixed",o=xd(t,!0,s,e);let l={scrollLeft:0,scrollTop:0};const a=Cs(0);function c(){a.x=hg(i)}if(r||!r&&!s)if((Pc(e)!=="body"||Xd(i))&&(l=fg(e)),r){const p=xd(e,!0,s,e);a.x=p.x+e.clientLeft,a.y=p.y+e.clientTop}else i&&c();s&&!r&&i&&c();const u=i&&!r&&!s?L2(i,l):Cs(0),d=o.left+l.scrollLeft-a.x-u.x,f=o.top+l.scrollTop-a.y-u.y;return{x:d,y:f,width:o.width,height:o.height}}function $y(t){return rs(t).position==="static"}function YC(t,e){if(!Is(t)||rs(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return yo(t)===n&&(n=n.ownerDocument.body),n}function z2(t,e){const n=hi(t);if(dg(t))return n;if(!Is(t)){let i=ll(t);for(;i&&!bc(i);){if(ns(i)&&!$y(i))return i;i=ll(i)}return n}let r=YC(t,e);for(;r&&nU(r)&&$y(r);)r=YC(r,e);return r&&bc(r)&&$y(r)&&!hx(r)?n:r||lU(t)||n}const xU=async function(t){const e=this.getOffsetParent||z2,n=this.getDimensions,r=await n(t.floating);return{reference:bU(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function kU(t){return rs(t).direction==="rtl"}const SU={convertOffsetParentRelativeRectToViewportRelativeRect:dU,getDocumentElement:yo,getClippingRect:vU,getOffsetParent:z2,getElementRects:xU,getClientRects:fU,getDimensions:wU,getScale:Ga,isElement:ns,isRTL:kU},F2=X6,$2=V6,B2=Q6,U2=W6,H2=Z6,V2=K6,W2=U6,K2=q6,Y2=(t,e,n)=>{const r=new Map,i={platform:SU,...n},s={...i.platform,_c:r};return B6(t,e,{...i,platform:s})};let z0,F0;if(typeof WeakMap<"u"){let t=new WeakMap;z0=e=>t.get(e),F0=(e,n)=>(t.set(e,n),n)}else{const t=[];let n=0;z0=r=>{for(let i=0;i(n==10&&(n=0),t[n++]=r,t[n++]=i)}var Ws=class{constructor(t,e,n,r){this.width=t,this.height=e,this.map=n,this.problems=r}findCell(t){for(let e=0;e=n){(s||(s=[])).push({type:"overlong_rowspan",pos:u,n:v-x});break}const E=i+x*e;for(let k=0;kr&&(s+=c.attrs.colspan)}}for(let o=0;o1&&(n=!0)}e==-1?e=s:e!=s&&(e=Math.max(e,s))}return e}function NU(t,e,n){t.problems||(t.problems=[]);const r={};for(let i=0;i0;e--)if(t.node(e).type.spec.tableRole=="row")return t.node(0).resolve(t.before(e+1));return null}function q2(t){const e=t.selection.$head;for(let n=e.depth;n>0;n--)if(e.node(n).type.spec.tableRole=="row")return!0;return!1}function MU(t){const e=t.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;const n=AU(e.$head)||IU(e.$head);if(n)return n;throw new RangeError(`No cell found around position ${e.head}`)}function IU(t){for(let e=t.nodeAfter,n=t.pos;e;e=e.firstChild,n++){const r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n)}for(let e=t.nodeBefore,n=t.pos;e;e=e.lastChild,n--){const r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n-e.nodeSize)}}function qC(t){return t.parent.type.spec.tableRole=="row"&&!!t.nodeAfter}function J2(t,e){return t.depth==e.depth&&t.pos>=e.start(-1)&&t.pos<=e.end(-1)}function G2(t,e,n){const r=t.node(-1),i=Ws.get(r),s=t.start(-1),o=i.nextCell(t.pos-s,e,n);return o==null?null:t.node(0).resolve(s+o)}function JC(t,e,n=1){const r={...t,colspan:t.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,n),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}var Es=class $s extends Nt{constructor(e,n=e){const r=e.node(-1),i=Ws.get(r),s=e.start(-1),o=i.rectBetween(e.pos-s,n.pos-s),l=e.node(0),a=i.cellsInRect(o).filter(u=>u!=n.pos-s);a.unshift(n.pos-s);const c=a.map(u=>{const d=r.nodeAt(u);if(!d)throw new RangeError(`No cell with offset ${u} found`);const f=s+u+1;return new qM(l.resolve(f),l.resolve(f+d.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=n}map(e,n){const r=e.resolve(n.map(this.$anchorCell.pos)),i=e.resolve(n.map(this.$headCell.pos));if(qC(r)&&qC(i)&&J2(r,i)){const s=this.$anchorCell.node(-1)!=r.node(-1);return s&&this.isRowSelection()?$s.rowSelection(r,i):s&&this.isColSelection()?$s.colSelection(r,i):new $s(r,i)}return St.between(r,i)}content(){const e=this.$anchorCell.node(-1),n=Ws.get(e),r=this.$anchorCell.start(-1),i=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),s={},o=[];for(let a=i.top;a0||y>0){let v=m.attrs;if(g>0&&(v=JC(v,0,g)),y>0&&(v=JC(v,v.colspan-y,y)),p.lefti.bottom){const v={...m.attrs,rowspan:Math.min(p.bottom,i.bottom)-Math.max(p.top,i.top)};p.top0)return!1;const r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,n=e){const r=e.node(-1),i=Ws.get(r),s=e.start(-1),o=i.findCell(e.pos-s),l=i.findCell(n.pos-s),a=e.node(0);return o.top<=l.top?(o.top>0&&(e=a.resolve(s+i.map[o.left])),l.bottom0&&(n=a.resolve(s+i.map[l.left])),o.bottom0)return!1;const o=i+this.$anchorCell.nodeAfter.attrs.colspan,l=s+this.$headCell.nodeAfter.attrs.colspan;return Math.max(o,l)==n.width}eq(e){return e instanceof $s&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,n=e){const r=e.node(-1),i=Ws.get(r),s=e.start(-1),o=i.findCell(e.pos-s),l=i.findCell(n.pos-s),a=e.node(0);return o.left<=l.left?(o.left>0&&(e=a.resolve(s+i.map[o.top*i.width])),l.right0&&(n=a.resolve(s+i.map[l.top*i.width])),o.righti.table.nodeAt(a));for(let a=0;a{const p=f+s.tableStart,m=o.doc.nodeAt(p);m&&o.setNodeMarkup(p,d,m.attrs)}),r(o)}return!0}}gx("row",{useDeprecatedLogic:!0});gx("column",{useDeprecatedLogic:!0});gx("cell",{useDeprecatedLogic:!0});function Jf(t,e){const n=t.selection;if(!(n instanceof Es))return!1;if(e){const r=t.tr,i=mx(t.schema).cell.createAndFill().content;n.forEachCell((s,o)=>{s.content.eq(i)||r.replace(r.mapping.map(o+1),r.mapping.map(o+s.nodeSize-1),new _e(i,0,0))}),r.docChanged&&e(r)}return!0}Gb({ArrowLeft:Gf("horiz",-1),ArrowRight:Gf("horiz",1),ArrowUp:Gf("vert",-1),ArrowDown:Gf("vert",1),"Shift-ArrowLeft":Xf("horiz",-1),"Shift-ArrowRight":Xf("horiz",1),"Shift-ArrowUp":Xf("vert",-1),"Shift-ArrowDown":Xf("vert",1),Backspace:Jf,"Mod-Backspace":Jf,Delete:Jf,"Mod-Delete":Jf});function Eh(t,e,n){return n.eq(t.selection)?!1:(e&&e(t.tr.setSelection(n).scrollIntoView()),!0)}function Gf(t,e){return(n,r,i)=>{if(!i)return!1;const s=n.selection;if(s instanceof Es)return Eh(n,r,Nt.near(s.$headCell,e));if(t!="horiz"&&!s.empty)return!1;const o=Z2(i,t,e);if(o==null)return!1;if(t=="horiz")return Eh(n,r,Nt.near(n.doc.resolve(s.head+e),e));{const l=n.doc.resolve(o),a=G2(l,t,e);let c;return a?c=Nt.near(a,1):e<0?c=Nt.near(n.doc.resolve(l.before(-1)),-1):c=Nt.near(n.doc.resolve(l.after(-1)),1),Eh(n,r,c)}}}function Xf(t,e){return(n,r,i)=>{if(!i)return!1;const s=n.selection;let o;if(s instanceof Es)o=s;else{const a=Z2(i,t,e);if(a==null)return!1;o=new Es(n.doc.resolve(a))}const l=G2(o.$headCell,t,e);return l?Eh(n,r,new Es(o.$anchorCell,l)):!1}}function Z2(t,e,n){if(!(t.state.selection instanceof St))return null;const{$head:r}=t.state.selection;for(let i=r.depth-1;i>=0;i--){const s=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:s.childCount))return null;if(s.type.spec.tableRole=="cell"||s.type.spec.tableRole=="header_cell"){const o=r.before(i),l=e=="vert"?n>0?"down":"up":n>0?"right":"left";return t.endOfTextblock(l)?o:null}}return null}new pn("tableColumnResizing");function OU(t,e){const n=Math.min(t.top,e.top),r=Math.max(t.bottom,e.bottom),i=Math.min(t.left,e.left),o=Math.max(t.right,e.right)-i,l=r-n,a=i,c=n;return new DOMRect(a,c,o,l)}var jU=class{constructor({editor:t,element:e,view:n,updateDelay:r=250,resizeDelay:i=60,shouldShow:s,appendTo:o,getReferencedVirtualElement:l,options:a}){this.preventHide=!1,this.isVisible=!1,this.scrollTarget=window,this.floatingUIOptions={strategy:"absolute",placement:"top",offset:8,flip:{},shift:{},arrow:!1,size:!1,autoPlacement:!1,hide:!1,inline:!1,onShow:void 0,onHide:void 0,onUpdate:void 0,onDestroy:void 0},this.shouldShow=({view:u,state:d,from:f,to:p})=>{const{doc:m,selection:g}=d,{empty:y}=g,v=!m.textBetween(f,p).length&&ex(d.selection),w=this.element.contains(document.activeElement);return!(!(u.hasFocus()||w)||y||v||!this.editor.isEditable)},this.mousedownHandler=()=>{this.preventHide=!0},this.dragstartHandler=()=>{this.hide()},this.resizeHandler=()=>{this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=window.setTimeout(()=>{this.updatePosition()},this.resizeDelay)},this.focusHandler=()=>{setTimeout(()=>this.update(this.editor.view))},this.blurHandler=({event:u})=>{var d;if(this.editor.isDestroyed){this.destroy();return}if(this.preventHide){this.preventHide=!1;return}u!=null&&u.relatedTarget&&((d=this.element.parentNode)!=null&&d.contains(u.relatedTarget))||(u==null?void 0:u.relatedTarget)!==this.editor.view.dom&&this.hide()},this.handleDebouncedUpdate=(u,d)=>{const f=!(d!=null&&d.selection.eq(u.state.selection)),p=!(d!=null&&d.doc.eq(u.state.doc));!f&&!p||(this.updateDebounceTimer&&clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=window.setTimeout(()=>{this.updateHandler(u,f,p,d)},this.updateDelay))},this.updateHandler=(u,d,f,p)=>{const{composing:m}=u;if(m||!d&&!f)return;if(!this.getShouldShow(p)){this.hide();return}this.updatePosition(),this.show()},this.transactionHandler=({transaction:u})=>{const d=u.getMeta("bubbleMenu");d==="updatePosition"?this.updatePosition():d&&typeof d=="object"&&d.type==="updateOptions"&&this.updateOptions(d.options)};var c;this.editor=t,this.element=e,this.view=n,this.updateDelay=r,this.resizeDelay=i,this.appendTo=o,this.scrollTarget=(c=a==null?void 0:a.scrollTarget)!=null?c:window,this.getReferencedVirtualElement=l,this.floatingUIOptions={...this.floatingUIOptions,...a},this.element.tabIndex=0,s&&(this.shouldShow=s),this.element.addEventListener("mousedown",this.mousedownHandler,{capture:!0}),this.view.dom.addEventListener("dragstart",this.dragstartHandler),this.editor.on("focus",this.focusHandler),this.editor.on("blur",this.blurHandler),this.editor.on("transaction",this.transactionHandler),window.addEventListener("resize",this.resizeHandler),this.scrollTarget.addEventListener("scroll",this.resizeHandler),this.update(n,n.state),this.getShouldShow()&&(this.show(),this.updatePosition())}get middlewares(){const t=[];return this.floatingUIOptions.flip&&t.push(U2(typeof this.floatingUIOptions.flip!="boolean"?this.floatingUIOptions.flip:void 0)),this.floatingUIOptions.shift&&t.push(B2(typeof this.floatingUIOptions.shift!="boolean"?this.floatingUIOptions.shift:void 0)),this.floatingUIOptions.offset&&t.push(F2(typeof this.floatingUIOptions.offset!="boolean"?this.floatingUIOptions.offset:void 0)),this.floatingUIOptions.arrow&&t.push(W2(this.floatingUIOptions.arrow)),this.floatingUIOptions.size&&t.push(H2(typeof this.floatingUIOptions.size!="boolean"?this.floatingUIOptions.size:void 0)),this.floatingUIOptions.autoPlacement&&t.push($2(typeof this.floatingUIOptions.autoPlacement!="boolean"?this.floatingUIOptions.autoPlacement:void 0)),this.floatingUIOptions.hide&&t.push(V2(typeof this.floatingUIOptions.hide!="boolean"?this.floatingUIOptions.hide:void 0)),this.floatingUIOptions.inline&&t.push(K2(typeof this.floatingUIOptions.inline!="boolean"?this.floatingUIOptions.inline:void 0)),t}get virtualElement(){var t,e,n;const{selection:r}=this.editor.state,i=(t=this.getReferencedVirtualElement)==null?void 0:t.call(this);if(i)return i;if(!((n=(e=this.view)==null?void 0:e.dom)!=null&&n.parentNode))return;const s=l2(this.view,r.from,r.to);let o={getBoundingClientRect:()=>s,getClientRects:()=>[s]};if(r instanceof pt){let l=this.view.nodeDOM(r.from);const a=l.dataset.nodeViewWrapper?l:l.querySelector("[data-node-view-wrapper]");a&&(l=a),l&&(o={getBoundingClientRect:()=>l.getBoundingClientRect(),getClientRects:()=>[l.getBoundingClientRect()]})}if(r instanceof Es){const{$anchorCell:l,$headCell:a}=r,c=l?l.pos:a.pos,u=a?a.pos:l.pos,d=this.view.nodeDOM(c),f=this.view.nodeDOM(u);if(!d||!f)return;const p=d===f?d.getBoundingClientRect():OU(d.getBoundingClientRect(),f.getBoundingClientRect());o={getBoundingClientRect:()=>p,getClientRects:()=>[p]}}return o}updatePosition(){const t=this.virtualElement;t&&Y2(t,this.element,{placement:this.floatingUIOptions.placement,strategy:this.floatingUIOptions.strategy,middleware:this.middlewares}).then(({x:e,y:n,strategy:r,middlewareData:i})=>{var s,o;if((s=i.hide)!=null&&s.referenceHidden||(o=i.hide)!=null&&o.escaped){this.element.style.visibility="hidden";return}this.element.style.visibility="visible",this.element.style.width="max-content",this.element.style.position=r,this.element.style.left=`${e}px`,this.element.style.top=`${n}px`,this.isVisible&&this.floatingUIOptions.onUpdate&&this.floatingUIOptions.onUpdate()})}update(t,e){const{state:n}=t,r=n.selection.from!==n.selection.to;if(this.updateDelay>0&&r){this.handleDebouncedUpdate(t,e);return}const i=!(e!=null&&e.selection.eq(t.state.selection)),s=!(e!=null&&e.doc.eq(t.state.doc));this.updateHandler(t,i,s,e)}getShouldShow(t){var e;const{state:n}=this.view,{selection:r}=n,{ranges:i}=r,s=Math.min(...i.map(a=>a.$from.pos)),o=Math.max(...i.map(a=>a.$to.pos));return((e=this.shouldShow)==null?void 0:e.call(this,{editor:this.editor,element:this.element,view:this.view,state:n,oldState:t,from:s,to:o}))||!1}show(){var t;if(this.isVisible)return;this.element.style.visibility="visible",this.element.style.opacity="1";const e=typeof this.appendTo=="function"?this.appendTo():this.appendTo;(t=e??this.view.dom.parentElement)==null||t.appendChild(this.element),this.floatingUIOptions.onShow&&this.floatingUIOptions.onShow(),this.isVisible=!0}hide(){this.isVisible&&(this.element.style.visibility="hidden",this.element.style.opacity="0",this.element.remove(),this.floatingUIOptions.onHide&&this.floatingUIOptions.onHide(),this.isVisible=!1)}updateOptions(t){var e;if(t.updateDelay!==void 0&&(this.updateDelay=t.updateDelay),t.resizeDelay!==void 0&&(this.resizeDelay=t.resizeDelay),t.appendTo!==void 0&&(this.appendTo=t.appendTo),t.getReferencedVirtualElement!==void 0&&(this.getReferencedVirtualElement=t.getReferencedVirtualElement),t.shouldShow!==void 0&&t.shouldShow&&(this.shouldShow=t.shouldShow),t.options!==void 0){const n=(e=t.options.scrollTarget)!=null?e:window;n!==this.scrollTarget&&(this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.scrollTarget=n,this.scrollTarget.addEventListener("scroll",this.resizeHandler)),this.floatingUIOptions={...this.floatingUIOptions,...t.options}}}destroy(){this.hide(),this.element.removeEventListener("mousedown",this.mousedownHandler,{capture:!0}),this.view.dom.removeEventListener("dragstart",this.dragstartHandler),window.removeEventListener("resize",this.resizeHandler),this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.editor.off("focus",this.focusHandler),this.editor.off("blur",this.blurHandler),this.editor.off("transaction",this.transactionHandler),this.floatingUIOptions.onDestroy&&this.floatingUIOptions.onDestroy()}},eR=t=>new hn({key:typeof t.pluginKey=="string"?new pn(t.pluginKey):t.pluginKey,view:e=>new jU({view:e,...t})});mn.create({name:"bubbleMenu",addOptions(){return{element:null,pluginKey:"bubbleMenu",updateDelay:void 0,appendTo:void 0,shouldShow:null}},addProseMirrorPlugins(){return this.options.element?[eR({pluginKey:this.options.pluginKey,editor:this.editor,element:this.options.element,updateDelay:this.options.updateDelay,options:this.options.options,appendTo:this.options.appendTo,getReferencedVirtualElement:this.options.getReferencedVirtualElement,shouldShow:this.options.shouldShow})]:[]}});var PU=class{constructor({editor:t,element:e,view:n,updateDelay:r=250,resizeDelay:i=60,options:s,appendTo:o,shouldShow:l}){this.preventHide=!1,this.isVisible=!1,this.scrollTarget=window,this.shouldShow=({view:c,state:u})=>{const{selection:d}=u,{$anchor:f,empty:p}=d,m=f.depth===1,g=f.parent.isTextblock&&!f.parent.type.spec.code&&!f.parent.textContent&&f.parent.childCount===0&&!this.getTextContent(f.parent);return!(!c.hasFocus()||!p||!m||!g||!this.editor.isEditable)},this.floatingUIOptions={strategy:"absolute",placement:"right",offset:8,flip:{},shift:{},arrow:!1,size:!1,autoPlacement:!1,hide:!1,inline:!1},this.updateHandler=(c,u,d,f)=>{const{composing:p}=c;if(p||!u&&!d)return;if(!this.getShouldShow(f)){this.hide();return}this.updatePosition(),this.show()},this.mousedownHandler=()=>{this.preventHide=!0},this.focusHandler=()=>{setTimeout(()=>this.update(this.editor.view))},this.blurHandler=({event:c})=>{var u;if(this.preventHide){this.preventHide=!1;return}c!=null&&c.relatedTarget&&((u=this.element.parentNode)!=null&&u.contains(c.relatedTarget))||(c==null?void 0:c.relatedTarget)!==this.editor.view.dom&&this.hide()},this.transactionHandler=({transaction:c})=>{const u=c.getMeta("floatingMenu");u==="updatePosition"?this.updatePosition():u&&typeof u=="object"&&u.type==="updateOptions"&&this.updateOptions(u.options)},this.resizeHandler=()=>{this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=window.setTimeout(()=>{this.updatePosition()},this.resizeDelay)};var a;this.editor=t,this.element=e,this.view=n,this.updateDelay=r,this.resizeDelay=i,this.appendTo=o,this.scrollTarget=(a=s==null?void 0:s.scrollTarget)!=null?a:window,this.floatingUIOptions={...this.floatingUIOptions,...s},this.element.tabIndex=0,l&&(this.shouldShow=l),this.element.addEventListener("mousedown",this.mousedownHandler,{capture:!0}),this.editor.on("focus",this.focusHandler),this.editor.on("blur",this.blurHandler),this.editor.on("transaction",this.transactionHandler),window.addEventListener("resize",this.resizeHandler),this.scrollTarget.addEventListener("scroll",this.resizeHandler),this.update(n,n.state),this.getShouldShow()&&(this.show(),this.updatePosition())}getTextContent(t){return t2(t,{textSerializers:rx(this.editor.schema)})}get middlewares(){const t=[];return this.floatingUIOptions.flip&&t.push(U2(typeof this.floatingUIOptions.flip!="boolean"?this.floatingUIOptions.flip:void 0)),this.floatingUIOptions.shift&&t.push(B2(typeof this.floatingUIOptions.shift!="boolean"?this.floatingUIOptions.shift:void 0)),this.floatingUIOptions.offset&&t.push(F2(typeof this.floatingUIOptions.offset!="boolean"?this.floatingUIOptions.offset:void 0)),this.floatingUIOptions.arrow&&t.push(W2(this.floatingUIOptions.arrow)),this.floatingUIOptions.size&&t.push(H2(typeof this.floatingUIOptions.size!="boolean"?this.floatingUIOptions.size:void 0)),this.floatingUIOptions.autoPlacement&&t.push($2(typeof this.floatingUIOptions.autoPlacement!="boolean"?this.floatingUIOptions.autoPlacement:void 0)),this.floatingUIOptions.hide&&t.push(V2(typeof this.floatingUIOptions.hide!="boolean"?this.floatingUIOptions.hide:void 0)),this.floatingUIOptions.inline&&t.push(K2(typeof this.floatingUIOptions.inline!="boolean"?this.floatingUIOptions.inline:void 0)),t}getShouldShow(t){var e;const{state:n}=this.view,{selection:r}=n,{ranges:i}=r,s=Math.min(...i.map(a=>a.$from.pos)),o=Math.max(...i.map(a=>a.$to.pos));return(e=this.shouldShow)==null?void 0:e.call(this,{editor:this.editor,view:this.view,state:n,oldState:t,from:s,to:o})}updateOptions(t){var e;if(t.updateDelay!==void 0&&(this.updateDelay=t.updateDelay),t.resizeDelay!==void 0&&(this.resizeDelay=t.resizeDelay),t.appendTo!==void 0&&(this.appendTo=t.appendTo),t.shouldShow!==void 0&&t.shouldShow&&(this.shouldShow=t.shouldShow),t.options!==void 0){const n=(e=t.options.scrollTarget)!=null?e:window;n!==this.scrollTarget&&(this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.scrollTarget=n,this.scrollTarget.addEventListener("scroll",this.resizeHandler)),this.floatingUIOptions={...this.floatingUIOptions,...t.options}}}updatePosition(){const{selection:t}=this.editor.state,e=l2(this.view,t.from,t.to);Y2({getBoundingClientRect:()=>e,getClientRects:()=>[e]},this.element,{placement:this.floatingUIOptions.placement,strategy:this.floatingUIOptions.strategy,middleware:this.middlewares}).then(({x:r,y:i,strategy:s,middlewareData:o})=>{var l,a;if((l=o.hide)!=null&&l.referenceHidden||(a=o.hide)!=null&&a.escaped){this.element.style.visibility="hidden";return}this.element.style.visibility="visible",this.element.style.width="max-content",this.element.style.position=s,this.element.style.left=`${r}px`,this.element.style.top=`${i}px`,this.isVisible&&this.floatingUIOptions.onUpdate&&this.floatingUIOptions.onUpdate()})}update(t,e){const n=!(e!=null&&e.selection.eq(t.state.selection)),r=!(e!=null&&e.doc.eq(t.state.doc));this.updateHandler(t,n,r,e)}show(){var t;if(this.isVisible)return;this.element.style.visibility="visible",this.element.style.opacity="1";const e=typeof this.appendTo=="function"?this.appendTo():this.appendTo;(t=e??this.view.dom.parentElement)==null||t.appendChild(this.element),this.floatingUIOptions.onShow&&this.floatingUIOptions.onShow(),this.isVisible=!0}hide(){this.isVisible&&(this.element.style.visibility="hidden",this.element.style.opacity="0",this.element.remove(),this.floatingUIOptions.onHide&&this.floatingUIOptions.onHide(),this.isVisible=!1)}destroy(){this.hide(),this.element.removeEventListener("mousedown",this.mousedownHandler,{capture:!0}),window.removeEventListener("resize",this.resizeHandler),this.scrollTarget.removeEventListener("scroll",this.resizeHandler),this.editor.off("focus",this.focusHandler),this.editor.off("blur",this.blurHandler),this.editor.off("transaction",this.transactionHandler),this.floatingUIOptions.onDestroy&&this.floatingUIOptions.onDestroy()}},tR=t=>new hn({key:typeof t.pluginKey=="string"?new pn(t.pluginKey):t.pluginKey,view:e=>new PU({view:e,...t})});mn.create({name:"floatingMenu",addOptions(){return{element:null,options:{},pluginKey:"floatingMenu",updateDelay:void 0,resizeDelay:void 0,appendTo:void 0,shouldShow:null}},addCommands(){return{updateFloatingMenuPosition:()=>({tr:t,dispatch:e})=>(e&&t.setMeta("floatingMenu","updatePosition"),!0)}},addProseMirrorPlugins(){return this.options.element?[tR({pluginKey:this.options.pluginKey,editor:this.editor,element:this.options.element,updateDelay:this.options.updateDelay,resizeDelay:this.options.resizeDelay,options:this.options.options,appendTo:this.options.appendTo,shouldShow:this.options.shouldShow})]:[]}});var LU=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},_U=({contentComponent:t})=>{const e=Rb.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return h.jsx(h.Fragment,{children:Object.values(e)})};function zU(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,r){e={...e,[n]:l_.createPortal(r.reactElement,r.element,n)},t.forEach(i=>i())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(i=>i())}}}var FU=class extends B.Component{constructor(t){var e;super(t),this.editorContentRef=B.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!((e=t.editor)!=null&&e.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var t;const e=this.props.editor;if(e&&!e.isDestroyed&&((t=e.view.dom)!=null&&t.parentNode)){if(e.contentComponent)return;const n=this.editorContentRef.current;n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n}),e.contentComponent=zU(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),e.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return h.jsxs(h.Fragment,{children:[h.jsx("div",{ref:LU(e,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&h.jsx(_U,{contentComponent:t.contentComponent})]})}},$U=b.forwardRef((t,e)=>{const n=B.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return B.createElement(FU,{key:n,innerRef:e,...t})}),Qd=B.memo($U),BU=typeof window<"u"?b.useLayoutEffect:b.useEffect,UU=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(r=>r())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function HU(t){var e;const[n]=b.useState(()=>new UU(t.editor)),r=I6.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:x6);return BU(()=>n.watch(t.editor),[t.editor,n]),b.useDebugValue(r),r}var VU=!1,$0=typeof window>"u",WU=$0||!!(typeof window<"u"&&window.next),KU=class nR{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?$0||WU?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...r)},onBlur:(...r)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...r)},onCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...r)},onDestroy:(...r)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...r)},onFocus:(...r)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...r)},onSelectionUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...r)},onTransaction:(...r)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...r)},onUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...r)},onContentError:(...r)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...r)},onDrop:(...r)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...r)},onPaste:(...r)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...r)},onDelete:(...r)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...r)}};return new ag(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((i,s)=>{var o;return i===((o=n.extensions)==null?void 0:o[s])}):e[r]===n[r])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?nR.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((r,i)=>r===e[i]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function pg(t={},e=[]){const n=b.useRef(t);n.current=t;const[r]=b.useState(()=>new KU(n)),i=Rb.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return b.useDebugValue(i),b.useEffect(r.onRender(e)),HU({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var yx=b.createContext({editor:null});yx.Consumer;var rR=()=>b.useContext(yx),YU=b.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),qU=()=>b.useContext(YU);B.forwardRef((t,e)=>{const{onDragStart:n}=qU(),r=t.as||"div";return h.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});B.createContext({markViewContentRef:()=>{}});var JU=B.forwardRef(({pluginKey:t="bubbleMenu",editor:e,updateDelay:n,resizeDelay:r,appendTo:i,shouldShow:s=null,getReferencedVirtualElement:o,options:l,children:a,...c},u)=>{const d=b.useRef(document.createElement("div"));typeof u=="function"?u(d.current):u&&(u.current=d.current);const{editor:f}=rR(),p=e||f,m={updateDelay:n,resizeDelay:r,appendTo:i,pluginKey:t,shouldShow:s,getReferencedVirtualElement:o,options:l},g=b.useRef(m);g.current=m;const[y,v]=b.useState(!1),w=b.useRef(!0);return b.useEffect(()=>{if(p!=null&&p.isDestroyed)return;if(!p){console.warn("BubbleMenu component is not rendered inside of an editor component or does not have editor prop.");return}const x=d.current;x.style.visibility="hidden",x.style.position="absolute";const E=eR({...g.current,editor:p,element:x});p.registerPlugin(E);const k=g.current.pluginKey;return w.current=!0,v(!0),()=>{v(!1),p.unregisterPlugin(k),window.requestAnimationFrame(()=>{x.parentNode&&x.parentNode.removeChild(x)})}},[p]),b.useEffect(()=>{if(!(!y||!p||p.isDestroyed)){if(w.current){w.current=!1;return}p.view.dispatch(p.state.tr.setMeta("bubbleMenu",{type:"updateOptions",options:g.current}))}},[y,p,n,r,s,l,i,o]),zn.createPortal(h.jsx("div",{...c,children:a}),d.current)}),GU=B.forwardRef(({pluginKey:t="floatingMenu",editor:e,updateDelay:n,resizeDelay:r,appendTo:i,shouldShow:s=null,options:o,children:l,...a},c)=>{const u=b.useRef(document.createElement("div"));typeof c=="function"?c(u.current):c&&(c.current=u.current);const{editor:d}=rR(),f=e||d,p={updateDelay:n,resizeDelay:r,appendTo:i,pluginKey:t,shouldShow:s,options:o},m=b.useRef(p);m.current=p;const[g,y]=b.useState(!1),v=b.useRef(!0);return b.useEffect(()=>{if(f!=null&&f.isDestroyed)return;if(!f){console.warn("FloatingMenu component is not rendered inside of an editor component or does not have editor prop.");return}const w=u.current;w.style.visibility="hidden",w.style.position="absolute";const x=tR({...m.current,editor:f,element:w});f.registerPlugin(x);const E=m.current.pluginKey;return v.current=!0,y(!0),()=>{y(!1),f.unregisterPlugin(E),window.requestAnimationFrame(()=>{w.parentNode&&w.parentNode.removeChild(w)})}},[f]),b.useEffect(()=>{if(!(!g||!f||f.isDestroyed)){if(v.current){v.current=!1;return}f.view.dispatch(f.state.tr.setMeta("floatingMenu",{type:"updateOptions",options:m.current}))}},[g,f,n,r,s,o,i]),zn.createPortal(h.jsx("div",{...a,children:l}),u.current)}),vx=b.createContext({editor:null,isReady:!1});vx.displayName="TiptapContext";var mg=()=>b.useContext(vx);function iR({instance:t,children:e}){var n;const[r,i]=b.useState((n=t==null?void 0:t.isInitialized)!=null?n:!1);b.useEffect(()=>{if(!t){i(!1);return}if(t.isInitialized){i(!0);return}const l=()=>{i(!0)};return t.on("create",l),()=>{t.off("create",l)}},[t]);const s=b.useMemo(()=>({editor:t,isReady:r}),[t,r]),o=b.useMemo(()=>({editor:t}),[t]);return h.jsx(yx.Provider,{value:o,children:h.jsx(vx.Provider,{value:s,children:e})})}iR.displayName="Tiptap";function sR({...t}){const{editor:e}=mg();return h.jsx(Qd,{editor:e,...t})}sR.displayName="Tiptap.Content";function oR({children:t}){const{isReady:e}=mg();return e?null:t}oR.displayName="Tiptap.Loading";function lR({children:t,...e}){const{editor:n}=mg();return n?h.jsx(JU,{editor:n,...e,children:t}):null}lR.displayName="Tiptap.BubbleMenu";function aR({children:t,...e}){const{editor:n}=mg();return n?h.jsx(GU,{...e,editor:n,children:t}):null}aR.displayName="Tiptap.FloatingMenu";Object.assign(iR,{Content:sR,Loading:oR,BubbleMenu:lR,FloatingMenu:aR});var Dp=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},XU=/^\s*>\s$/,QU=yi.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return Dp("blockquote",{...Yn(this.options.HTMLAttributes,t),children:Dp("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",r=[];return t.content.forEach(i=>{const l=e.renderChildren([i]).split(` `).map(a=>a.trim()===""?n:`${n} ${a}`);r.push(l.join(` `))}),r.join(` ${n} @@ -182,8 +182,8 @@ ${n} `):""}),d8=yi.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:t}){return["br",Yn(this.options.HTMLAttributes,t)]},renderText(){return` `},renderMarkdown:()=>` -`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:s}=n;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,a=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&a&&o){const d=a.filter(f=>l.includes(f.type.name));c.ensureMarks(d)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),f8=yi.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,Yn(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,i="#".repeat(r);return t.content?`${i} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>j0({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),h8=yi.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",Yn(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!M5(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,i=t();return i2(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:a}=o.selection,c=a.end();if(a.nodeAfter)a.nodeAfter.isTextblock?o.setSelection(St.create(o.doc,a.pos+1)):a.nodeAfter.isBlock?o.setSelection(pt.create(o.doc,a.pos)):o.setSelection(St.create(o.doc,a.pos));else{const u=s.schema.nodes[this.options.nextNodeType]||a.parent.type.contentMatch.defaultType,d=u==null?void 0:u.create();d&&(o.insert(c,d),o.setSelection(St.create(o.doc,c+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[A5({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),p8=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,m8=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,g8=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,y8=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,v8=da.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",Yn(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[yc({find:p8,type:this.type}),yc({find:g8,type:this.type})]},addPasteRules(){return[ea({find:m8,type:this.type}),ea({find:y8,type:this.type})]}});const w8="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",b8="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",B0="numeric",U0="ascii",H0="alpha",Pu="asciinumeric",gu="alphanumeric",V0="domain",cR="emoji",x8="scheme",k8="slashscheme",Uy="whitespace";function S8(t,e){return t in e||(e[t]=[]),e[t]}function Ol(t,e,n){e[B0]&&(e[Pu]=!0,e[gu]=!0),e[U0]&&(e[Pu]=!0,e[H0]=!0),e[Pu]&&(e[gu]=!0),e[H0]&&(e[gu]=!0),e[gu]&&(e[V0]=!0),e[cR]&&(e[V0]=!0);for(const r in e){const i=S8(r,n);i.indexOf(t)<0&&i.push(t)}}function C8(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function Xr(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}Xr.groups={};Xr.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;rt.ta(e,n,r,i),Dn=(t,e,n,r,i)=>t.tr(e,n,r,i),XC=(t,e,n,r,i)=>t.ts(e,n,r,i),Ne=(t,e,n,r,i)=>t.tt(e,n,r,i),Bs="WORD",W0="UWORD",uR="ASCIINUMERICAL",dR="ALPHANUMERICAL",kd="LOCALHOST",K0="TLD",Y0="UTLD",Nh="SCHEME",Ea="SLASH_SCHEME",wx="NUM",q0="WS",bx="NL",Lu="OPENBRACE",_u="CLOSEBRACE",Op="OPENBRACKET",jp="CLOSEBRACKET",Pp="OPENPAREN",Lp="CLOSEPAREN",_p="OPENANGLEBRACKET",zp="CLOSEANGLEBRACKET",Fp="FULLWIDTHLEFTPAREN",$p="FULLWIDTHRIGHTPAREN",Bp="LEFTCORNERBRACKET",Up="RIGHTCORNERBRACKET",Hp="LEFTWHITECORNERBRACKET",Vp="RIGHTWHITECORNERBRACKET",Wp="FULLWIDTHLESSTHAN",Kp="FULLWIDTHGREATERTHAN",Yp="AMPERSAND",qp="APOSTROPHE",Jp="ASTERISK",Ro="AT",Gp="BACKSLASH",Xp="BACKTICK",Qp="CARET",Lo="COLON",xx="COMMA",Zp="DOLLAR",gs="DOT",em="EQUALS",kx="EXCLAMATION",xi="HYPHEN",zu="PERCENT",tm="PIPE",nm="PLUS",rm="POUND",Fu="QUERY",Sx="QUOTE",fR="FULLWIDTHMIDDLEDOT",Cx="SEMI",ys="SLASH",$u="TILDE",im="UNDERSCORE",hR="EMOJI",sm="SYM";var pR=Object.freeze({__proto__:null,ALPHANUMERICAL:dR,AMPERSAND:Yp,APOSTROPHE:qp,ASCIINUMERICAL:uR,ASTERISK:Jp,AT:Ro,BACKSLASH:Gp,BACKTICK:Xp,CARET:Qp,CLOSEANGLEBRACKET:zp,CLOSEBRACE:_u,CLOSEBRACKET:jp,CLOSEPAREN:Lp,COLON:Lo,COMMA:xx,DOLLAR:Zp,DOT:gs,EMOJI:hR,EQUALS:em,EXCLAMATION:kx,FULLWIDTHGREATERTHAN:Kp,FULLWIDTHLEFTPAREN:Fp,FULLWIDTHLESSTHAN:Wp,FULLWIDTHMIDDLEDOT:fR,FULLWIDTHRIGHTPAREN:$p,HYPHEN:xi,LEFTCORNERBRACKET:Bp,LEFTWHITECORNERBRACKET:Hp,LOCALHOST:kd,NL:bx,NUM:wx,OPENANGLEBRACKET:_p,OPENBRACE:Lu,OPENBRACKET:Op,OPENPAREN:Pp,PERCENT:zu,PIPE:tm,PLUS:nm,POUND:rm,QUERY:Fu,QUOTE:Sx,RIGHTCORNERBRACKET:Up,RIGHTWHITECORNERBRACKET:Vp,SCHEME:Nh,SEMI:Cx,SLASH:ys,SLASH_SCHEME:Ea,SYM:sm,TILDE:$u,TLD:K0,UNDERSCORE:im,UTLD:Y0,UWORD:W0,WORD:Bs,WS:q0});const js=/[a-z]/,lu=new RegExp("\\p{L}","u"),Hy=new RegExp("\\p{Emoji}","u"),Ps=/\d/,Vy=/\s/,QC="\r",Wy=` -`,E8="️",N8="‍",Ky="";let Qf=null,Zf=null;function T8(t=[]){const e={};Xr.groups=e;const n=new Xr;Qf==null&&(Qf=ZC(w8)),Zf==null&&(Zf=ZC(b8)),Ne(n,"'",qp),Ne(n,"{",Lu),Ne(n,"}",_u),Ne(n,"[",Op),Ne(n,"]",jp),Ne(n,"(",Pp),Ne(n,")",Lp),Ne(n,"<",_p),Ne(n,">",zp),Ne(n,"(",Fp),Ne(n,")",$p),Ne(n,"「",Bp),Ne(n,"」",Up),Ne(n,"『",Hp),Ne(n,"』",Vp),Ne(n,"<",Wp),Ne(n,">",Kp),Ne(n,"&",Yp),Ne(n,"*",Jp),Ne(n,"@",Ro),Ne(n,"`",Xp),Ne(n,"^",Qp),Ne(n,":",Lo),Ne(n,",",xx),Ne(n,"$",Zp),Ne(n,".",gs),Ne(n,"=",em),Ne(n,"!",kx),Ne(n,"-",xi),Ne(n,"%",zu),Ne(n,"|",tm),Ne(n,"+",nm),Ne(n,"#",rm),Ne(n,"?",Fu),Ne(n,'"',Sx),Ne(n,"/",ys),Ne(n,";",Cx),Ne(n,"~",$u),Ne(n,"_",im),Ne(n,"\\",Gp),Ne(n,"・",fR);const r=Dn(n,Ps,wx,{[B0]:!0});Dn(r,Ps,r);const i=Dn(r,js,uR,{[Pu]:!0}),s=Dn(r,lu,dR,{[gu]:!0}),o=Dn(n,js,Bs,{[U0]:!0});Dn(o,Ps,i),Dn(o,js,o),Dn(i,Ps,i),Dn(i,js,i);const l=Dn(n,lu,W0,{[H0]:!0});Dn(l,js),Dn(l,Ps,s),Dn(l,lu,l),Dn(s,Ps,s),Dn(s,js),Dn(s,lu,s);const a=Ne(n,Wy,bx,{[Uy]:!0}),c=Ne(n,QC,q0,{[Uy]:!0}),u=Dn(n,Vy,q0,{[Uy]:!0});Ne(n,Ky,u),Ne(c,Wy,a),Ne(c,Ky,u),Dn(c,Vy,u),Ne(u,QC),Ne(u,Wy),Dn(u,Vy,u),Ne(u,Ky,u);const d=Dn(n,Hy,hR,{[cR]:!0});Ne(d,"#"),Dn(d,Hy,d),Ne(d,E8,d);const f=Ne(d,N8);Ne(f,"#"),Dn(f,Hy,d);const p=[[js,o],[Ps,i]],m=[[js,null],[lu,l],[Ps,s]];for(let g=0;gg[0]>y[0]?1:-1);for(let g=0;g=0?w[V0]=!0:js.test(y)?Ps.test(y)?w[Pu]=!0:w[U0]=!0:w[B0]=!0,XC(n,y,y,w)}return XC(n,"localhost",kd,{ascii:!0}),n.jd=new Xr(sm),{start:n,tokens:Object.assign({groups:e},pR)}}function mR(t,e){const n=A8(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,i=[];let s=0,o=0;for(;o=0&&(d+=n[o].length,f++),c+=n[o].length,s+=n[o].length,o++;s-=d,o-=f,c-=d,i.push({t:u.t,v:e.slice(s-c,s),s:s-c,e:s})}return i}function A8(t){const e=[],n=t.length;let r=0;for(;r56319||r+1===n||(s=t.charCodeAt(r+1))<56320||s>57343?t[r]:t.slice(r,r+2);e.push(o),r+=o.length}return e}function Co(t,e,n,r,i){let s;const o=e.length;for(let l=0;l=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(r,r+s),10);o>0;o--)n.pop();r+=s}else n.push(t[r]),r++}return e}const Sd={defaultProtocol:"http",events:null,format:eE,formatHref:eE,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Ex(t,e=null){let n=Object.assign({},Sd);t&&(n=Object.assign(n,t instanceof Ex?t.o:t));const r=n.ignoreTags,i=[];for(let s=0;sn?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=Sd.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),i=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),a=t.get("target",n,e),c=t.get("rel",n,e),u=t.getObj("attributes",n,e),d=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),a&&(o.target=a),c&&(o.rel=c),u&&Object.assign(o,u),{tagName:i,attributes:o,content:s,eventListeners:d}}};function gg(t,e){class n extends gR{constructor(i,s){super(i,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const tE=gg("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),nE=gg("text"),M8=gg("nl"),eh=gg("url",{isLink:!0,toHref(t=Sd.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==kd&&t[1].t===Lo}}),bi=t=>new Xr(t);function I8({groups:t}){const e=t.domain.concat([Yp,Jp,Ro,Gp,Xp,Qp,Zp,em,xi,wx,zu,tm,nm,rm,ys,sm,$u,im]),n=[qp,Lo,xx,gs,kx,zu,Fu,Sx,Cx,_p,zp,Lu,_u,jp,Op,Pp,Lp,Fp,$p,Bp,Up,Hp,Vp,Wp,Kp],r=[Yp,qp,Jp,Gp,Xp,Qp,Zp,em,xi,Lu,_u,zu,tm,nm,rm,Fu,ys,sm,$u,im],i=bi(),s=Ne(i,$u);Ht(s,r,s),Ht(s,t.domain,s);const o=bi(),l=bi(),a=bi();Ht(i,t.domain,o),Ht(i,t.scheme,l),Ht(i,t.slashscheme,a),Ht(o,r,s),Ht(o,t.domain,o);const c=Ne(o,Ro);Ne(s,Ro,c),Ne(l,Ro,c),Ne(a,Ro,c);const u=Ne(s,gs);Ht(u,r,s),Ht(u,t.domain,s);const d=bi();Ht(c,t.domain,d),Ht(d,t.domain,d);const f=Ne(d,gs);Ht(f,t.domain,d);const p=bi(tE);Ht(f,t.tld,p),Ht(f,t.utld,p),Ne(c,kd,p);const m=Ne(d,xi);Ne(m,xi,m),Ht(m,t.domain,d),Ht(p,t.domain,d),Ne(p,gs,f),Ne(p,xi,m);const g=Ne(p,Lo);Ht(g,t.numeric,tE);const y=Ne(o,xi),v=Ne(o,gs);Ne(y,xi,y),Ht(y,t.domain,o),Ht(v,r,s),Ht(v,t.domain,o);const w=bi(eh);Ht(v,t.tld,w),Ht(v,t.utld,w),Ht(w,t.domain,o),Ht(w,r,s),Ne(w,gs,v),Ne(w,xi,y),Ne(w,Ro,c);const x=Ne(w,Lo),E=bi(eh);Ht(x,t.numeric,E);const k=bi(eh),M=bi();Ht(k,e,k),Ht(k,n,M),Ht(M,e,k),Ht(M,n,M),Ne(w,ys,k),Ne(E,ys,k);const N=Ne(l,Lo),z=Ne(a,Lo),X=Ne(z,ys),L=Ne(X,ys);Ht(l,t.domain,o),Ne(l,gs,v),Ne(l,xi,y),Ht(a,t.domain,o),Ne(a,gs,v),Ne(a,xi,y),Ht(N,t.domain,k),Ne(N,ys,k),Ne(N,Fu,k),Ht(L,t.domain,k),Ht(L,e,k),Ne(L,ys,k);const H=[[Lu,_u],[Op,jp],[Pp,Lp],[_p,zp],[Fp,$p],[Bp,Up],[Hp,Vp],[Wp,Kp]];for(let W=0;W=0&&f++,i++,u++;if(f<0)i-=u,i0&&(s.push(Yy(nE,e,o)),o=[]),i-=f,u-=f;const p=d.t,m=n.slice(i-u,i);s.push(Yy(p,e,m))}}return o.length>0&&s.push(Yy(nE,e,o)),s}function Yy(t,e,n){const r=n[0].s,i=n[n.length-1].e,s=e.slice(r,i);return new t(s,n)}const D8=typeof console<"u"&&console&&console.warn||(()=>{}),O8="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",kn={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function j8(){return Xr.groups={},kn.scanner=null,kn.parser=null,kn.tokenQueue=[],kn.pluginQueue=[],kn.customSchemes=[],kn.initialized=!1,kn}function rE(t,e=!1){if(kn.initialized&&D8(`linkifyjs: already initialized - will not register custom scheme "${t}" ${O8}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. +`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:s}=n;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,a=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&a&&o){const d=a.filter(f=>l.includes(f.type.name));c.ensureMarks(d)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),f8=yi.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,Yn(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,i="#".repeat(r);return t.content?`${i} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>j0({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),h8=yi.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",Yn(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!M5(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,i=t();return i2(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:a}=o.selection,c=a.end();if(a.nodeAfter)a.nodeAfter.isTextblock?o.setSelection(St.create(o.doc,a.pos+1)):a.nodeAfter.isBlock?o.setSelection(pt.create(o.doc,a.pos)):o.setSelection(St.create(o.doc,a.pos));else{const u=s.schema.nodes[this.options.nextNodeType]||a.parent.type.contentMatch.defaultType,d=u==null?void 0:u.create();d&&(o.insert(c,d),o.setSelection(St.create(o.doc,c+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[A5({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),p8=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,m8=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,g8=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,y8=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,v8=da.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",Yn(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[yc({find:p8,type:this.type}),yc({find:g8,type:this.type})]},addPasteRules(){return[ea({find:m8,type:this.type}),ea({find:y8,type:this.type})]}});const w8="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",b8="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",B0="numeric",U0="ascii",H0="alpha",Pu="asciinumeric",gu="alphanumeric",V0="domain",cR="emoji",x8="scheme",k8="slashscheme",Uy="whitespace";function S8(t,e){return t in e||(e[t]=[]),e[t]}function Ol(t,e,n){e[B0]&&(e[Pu]=!0,e[gu]=!0),e[U0]&&(e[Pu]=!0,e[H0]=!0),e[Pu]&&(e[gu]=!0),e[H0]&&(e[gu]=!0),e[gu]&&(e[V0]=!0),e[cR]&&(e[V0]=!0);for(const r in e){const i=S8(r,n);i.indexOf(t)<0&&i.push(t)}}function C8(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function Xr(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}Xr.groups={};Xr.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;rt.ta(e,n,r,i),Dn=(t,e,n,r,i)=>t.tr(e,n,r,i),XC=(t,e,n,r,i)=>t.ts(e,n,r,i),Ne=(t,e,n,r,i)=>t.tt(e,n,r,i),Bs="WORD",W0="UWORD",uR="ASCIINUMERICAL",dR="ALPHANUMERICAL",kd="LOCALHOST",K0="TLD",Y0="UTLD",Nh="SCHEME",Ea="SLASH_SCHEME",wx="NUM",q0="WS",bx="NL",Lu="OPENBRACE",_u="CLOSEBRACE",Op="OPENBRACKET",jp="CLOSEBRACKET",Pp="OPENPAREN",Lp="CLOSEPAREN",_p="OPENANGLEBRACKET",zp="CLOSEANGLEBRACKET",Fp="FULLWIDTHLEFTPAREN",$p="FULLWIDTHRIGHTPAREN",Bp="LEFTCORNERBRACKET",Up="RIGHTCORNERBRACKET",Hp="LEFTWHITECORNERBRACKET",Vp="RIGHTWHITECORNERBRACKET",Wp="FULLWIDTHLESSTHAN",Kp="FULLWIDTHGREATERTHAN",Yp="AMPERSAND",qp="APOSTROPHE",Jp="ASTERISK",Ro="AT",Gp="BACKSLASH",Xp="BACKTICK",Qp="CARET",Lo="COLON",xx="COMMA",Zp="DOLLAR",gs="DOT",em="EQUALS",kx="EXCLAMATION",xi="HYPHEN",zu="PERCENT",tm="PIPE",nm="PLUS",rm="POUND",Fu="QUERY",Sx="QUOTE",fR="FULLWIDTHMIDDLEDOT",Cx="SEMI",ys="SLASH",$u="TILDE",im="UNDERSCORE",hR="EMOJI",sm="SYM";var pR=Object.freeze({__proto__:null,ALPHANUMERICAL:dR,AMPERSAND:Yp,APOSTROPHE:qp,ASCIINUMERICAL:uR,ASTERISK:Jp,AT:Ro,BACKSLASH:Gp,BACKTICK:Xp,CARET:Qp,CLOSEANGLEBRACKET:zp,CLOSEBRACE:_u,CLOSEBRACKET:jp,CLOSEPAREN:Lp,COLON:Lo,COMMA:xx,DOLLAR:Zp,DOT:gs,EMOJI:hR,EQUALS:em,EXCLAMATION:kx,FULLWIDTHGREATERTHAN:Kp,FULLWIDTHLEFTPAREN:Fp,FULLWIDTHLESSTHAN:Wp,FULLWIDTHMIDDLEDOT:fR,FULLWIDTHRIGHTPAREN:$p,HYPHEN:xi,LEFTCORNERBRACKET:Bp,LEFTWHITECORNERBRACKET:Hp,LOCALHOST:kd,NL:bx,NUM:wx,OPENANGLEBRACKET:_p,OPENBRACE:Lu,OPENBRACKET:Op,OPENPAREN:Pp,PERCENT:zu,PIPE:tm,PLUS:nm,POUND:rm,QUERY:Fu,QUOTE:Sx,RIGHTCORNERBRACKET:Up,RIGHTWHITECORNERBRACKET:Vp,SCHEME:Nh,SEMI:Cx,SLASH:ys,SLASH_SCHEME:Ea,SYM:sm,TILDE:$u,TLD:K0,UNDERSCORE:im,UTLD:Y0,UWORD:W0,WORD:Bs,WS:q0});const js=/[a-z]/,lu=new RegExp("\\p{L}","u"),Hy=new RegExp("\\p{Emoji}","u"),Ps=/\d/,Vy=/\s/,QC="\r",Wy=` +`,E8="️",N8="‍",Ky="";let Qf=null,Zf=null;function T8(t=[]){const e={};Xr.groups=e;const n=new Xr;Qf==null&&(Qf=ZC(w8)),Zf==null&&(Zf=ZC(b8)),Ne(n,"'",qp),Ne(n,"{",Lu),Ne(n,"}",_u),Ne(n,"[",Op),Ne(n,"]",jp),Ne(n,"(",Pp),Ne(n,")",Lp),Ne(n,"<",_p),Ne(n,">",zp),Ne(n,"(",Fp),Ne(n,")",$p),Ne(n,"「",Bp),Ne(n,"」",Up),Ne(n,"『",Hp),Ne(n,"』",Vp),Ne(n,"<",Wp),Ne(n,">",Kp),Ne(n,"&",Yp),Ne(n,"*",Jp),Ne(n,"@",Ro),Ne(n,"`",Xp),Ne(n,"^",Qp),Ne(n,":",Lo),Ne(n,",",xx),Ne(n,"$",Zp),Ne(n,".",gs),Ne(n,"=",em),Ne(n,"!",kx),Ne(n,"-",xi),Ne(n,"%",zu),Ne(n,"|",tm),Ne(n,"+",nm),Ne(n,"#",rm),Ne(n,"?",Fu),Ne(n,'"',Sx),Ne(n,"/",ys),Ne(n,";",Cx),Ne(n,"~",$u),Ne(n,"_",im),Ne(n,"\\",Gp),Ne(n,"・",fR);const r=Dn(n,Ps,wx,{[B0]:!0});Dn(r,Ps,r);const i=Dn(r,js,uR,{[Pu]:!0}),s=Dn(r,lu,dR,{[gu]:!0}),o=Dn(n,js,Bs,{[U0]:!0});Dn(o,Ps,i),Dn(o,js,o),Dn(i,Ps,i),Dn(i,js,i);const l=Dn(n,lu,W0,{[H0]:!0});Dn(l,js),Dn(l,Ps,s),Dn(l,lu,l),Dn(s,Ps,s),Dn(s,js),Dn(s,lu,s);const a=Ne(n,Wy,bx,{[Uy]:!0}),c=Ne(n,QC,q0,{[Uy]:!0}),u=Dn(n,Vy,q0,{[Uy]:!0});Ne(n,Ky,u),Ne(c,Wy,a),Ne(c,Ky,u),Dn(c,Vy,u),Ne(u,QC),Ne(u,Wy),Dn(u,Vy,u),Ne(u,Ky,u);const d=Dn(n,Hy,hR,{[cR]:!0});Ne(d,"#"),Dn(d,Hy,d),Ne(d,E8,d);const f=Ne(d,N8);Ne(f,"#"),Dn(f,Hy,d);const p=[[js,o],[Ps,i]],m=[[js,null],[lu,l],[Ps,s]];for(let g=0;gg[0]>y[0]?1:-1);for(let g=0;g=0?w[V0]=!0:js.test(y)?Ps.test(y)?w[Pu]=!0:w[U0]=!0:w[B0]=!0,XC(n,y,y,w)}return XC(n,"localhost",kd,{ascii:!0}),n.jd=new Xr(sm),{start:n,tokens:Object.assign({groups:e},pR)}}function mR(t,e){const n=A8(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,i=[];let s=0,o=0;for(;o=0&&(d+=n[o].length,f++),c+=n[o].length,s+=n[o].length,o++;s-=d,o-=f,c-=d,i.push({t:u.t,v:e.slice(s-c,s),s:s-c,e:s})}return i}function A8(t){const e=[],n=t.length;let r=0;for(;r56319||r+1===n||(s=t.charCodeAt(r+1))<56320||s>57343?t[r]:t.slice(r,r+2);e.push(o),r+=o.length}return e}function Co(t,e,n,r,i){let s;const o=e.length;for(let l=0;l=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(r,r+s),10);o>0;o--)n.pop();r+=s}else n.push(t[r]),r++}return e}const Sd={defaultProtocol:"http",events:null,format:eE,formatHref:eE,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Ex(t,e=null){let n=Object.assign({},Sd);t&&(n=Object.assign(n,t instanceof Ex?t.o:t));const r=n.ignoreTags,i=[];for(let s=0;sn?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=Sd.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),i=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),a=t.get("target",n,e),c=t.get("rel",n,e),u=t.getObj("attributes",n,e),d=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),a&&(o.target=a),c&&(o.rel=c),u&&Object.assign(o,u),{tagName:i,attributes:o,content:s,eventListeners:d}}};function gg(t,e){class n extends gR{constructor(i,s){super(i,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const tE=gg("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),nE=gg("text"),M8=gg("nl"),eh=gg("url",{isLink:!0,toHref(t=Sd.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==kd&&t[1].t===Lo}}),bi=t=>new Xr(t);function I8({groups:t}){const e=t.domain.concat([Yp,Jp,Ro,Gp,Xp,Qp,Zp,em,xi,wx,zu,tm,nm,rm,ys,sm,$u,im]),n=[qp,Lo,xx,gs,kx,zu,Fu,Sx,Cx,_p,zp,Lu,_u,jp,Op,Pp,Lp,Fp,$p,Bp,Up,Hp,Vp,Wp,Kp],r=[Yp,qp,Jp,Gp,Xp,Qp,Zp,em,xi,Lu,_u,zu,tm,nm,rm,Fu,ys,sm,$u,im],i=bi(),s=Ne(i,$u);Vt(s,r,s),Vt(s,t.domain,s);const o=bi(),l=bi(),a=bi();Vt(i,t.domain,o),Vt(i,t.scheme,l),Vt(i,t.slashscheme,a),Vt(o,r,s),Vt(o,t.domain,o);const c=Ne(o,Ro);Ne(s,Ro,c),Ne(l,Ro,c),Ne(a,Ro,c);const u=Ne(s,gs);Vt(u,r,s),Vt(u,t.domain,s);const d=bi();Vt(c,t.domain,d),Vt(d,t.domain,d);const f=Ne(d,gs);Vt(f,t.domain,d);const p=bi(tE);Vt(f,t.tld,p),Vt(f,t.utld,p),Ne(c,kd,p);const m=Ne(d,xi);Ne(m,xi,m),Vt(m,t.domain,d),Vt(p,t.domain,d),Ne(p,gs,f),Ne(p,xi,m);const g=Ne(p,Lo);Vt(g,t.numeric,tE);const y=Ne(o,xi),v=Ne(o,gs);Ne(y,xi,y),Vt(y,t.domain,o),Vt(v,r,s),Vt(v,t.domain,o);const w=bi(eh);Vt(v,t.tld,w),Vt(v,t.utld,w),Vt(w,t.domain,o),Vt(w,r,s),Ne(w,gs,v),Ne(w,xi,y),Ne(w,Ro,c);const x=Ne(w,Lo),E=bi(eh);Vt(x,t.numeric,E);const k=bi(eh),M=bi();Vt(k,e,k),Vt(k,n,M),Vt(M,e,k),Vt(M,n,M),Ne(w,ys,k),Ne(E,ys,k);const N=Ne(l,Lo),z=Ne(a,Lo),X=Ne(z,ys),L=Ne(X,ys);Vt(l,t.domain,o),Ne(l,gs,v),Ne(l,xi,y),Vt(a,t.domain,o),Ne(a,gs,v),Ne(a,xi,y),Vt(N,t.domain,k),Ne(N,ys,k),Ne(N,Fu,k),Vt(L,t.domain,k),Vt(L,e,k),Ne(L,ys,k);const H=[[Lu,_u],[Op,jp],[Pp,Lp],[_p,zp],[Fp,$p],[Bp,Up],[Hp,Vp],[Wp,Kp]];for(let W=0;W=0&&f++,i++,u++;if(f<0)i-=u,i0&&(s.push(Yy(nE,e,o)),o=[]),i-=f,u-=f;const p=d.t,m=n.slice(i-u,i);s.push(Yy(p,e,m))}}return o.length>0&&s.push(Yy(nE,e,o)),s}function Yy(t,e,n){const r=n[0].s,i=n[n.length-1].e,s=e.slice(r,i);return new t(s,n)}const D8=typeof console<"u"&&console&&console.warn||(()=>{}),O8="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",kn={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function j8(){return Xr.groups={},kn.scanner=null,kn.parser=null,kn.tokenQueue=[],kn.pluginQueue=[],kn.customSchemes=[],kn.initialized=!1,kn}function rE(t,e=!1){if(kn.initialized&&D8(`linkifyjs: already initialized - will not register custom scheme "${t}" ${O8}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. 1. Must only contain digits, lowercase ASCII letters or "-" 2. Cannot start or end with "-" 3. "-" cannot repeat`);kn.customSchemes.push([t,e])}function P8(){kn.scanner=T8(kn.customSchemes);for(let t=0;t{const i=e.some(c=>c.docChanged)&&!n.doc.eq(r.doc),s=e.some(c=>c.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=GI(n.doc,[...e]);if(r2(l).forEach(({newRange:c})=>{const u=DB(r.doc,c,p=>p.isTextblock);let d,f;if(u.length>1)d=u[0],f=r.doc.textBetween(d.pos,d.pos+d.node.nodeSize,void 0," ");else if(u.length){const p=r.doc.textBetween(c.from,c.to," "," ");if(!_8.test(p))return;d=u[0],f=r.doc.textBetween(d.pos,c.to,void 0," ")}if(d&&f){const p=f.split(L8).filter(Boolean);if(p.length<=0)return!1;const m=p[p.length-1],g=d.pos+f.lastIndexOf(m);if(!m)return!1;const y=Nx(m).map(v=>v.toObject(t.defaultProtocol));if(!F8(y))return!1;y.filter(v=>v.isLink).map(v=>({...v,from:g+v.start+1,to:g+v.end+1})).filter(v=>r.schema.marks.code?!r.doc.rangeHasMark(v.from,v.to,r.schema.marks.code):!0).filter(v=>t.validate(v.value)).filter(v=>t.shouldAutoLink(v.value)).forEach(v=>{ix(v.from,v.to,r.doc).some(w=>w.mark.type===t.type)||o.addMark(v.from,v.to,t.type.create({href:v.href}))})}}),!!o.steps.length)return o}})}function B8(t){return new hn({key:new pn("handleClickLink"),props:{handleClick:(e,n,r)=>{var i,s;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{const a=r.target;if(!a)return!1;const c=t.editor.view.dom;o=a.closest("a"),o&&!c.contains(o)&&(o=null)}if(!o)return!1;let l=!1;if(t.enableClickSelection&&(l=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const a=n2(e.state,t.type.name),c=(i=o.href)!=null?i:a.href,u=(s=o.target)!=null?s:a.target;c&&(window.open(c,u),l=!0)}return l}}})}function U8(t){return new hn({key:new pn("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:i}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let a="";r.content.forEach(u=>{a+=u.textContent});const c=yR(a,{defaultProtocol:t.defaultProtocol}).find(u=>u.isLink&&u.value===a);return!a||!c||i!==void 0&&!i(c.value)?!1:t.editor.commands.setMark(t.type,{href:c.href})}}})}function kl(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&n.push(i)}),!t||t.replace(z8,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var vR=da.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){rE(t);return}rE(t.scheme,t.optionalSlashes)})},onDestroy(){j8()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!kl(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(t),n=/^[a-z][a-z0-9+.-]*:/i.test(t);if(e||n&&!t.includes("@"))return!0;const i=(t.includes("@")?t.split("@").pop():t).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(i)||!/\./.test(i))}}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:n=>!!kl(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:e=>!!kl(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Yn(this.options.HTMLAttributes,t),0]:["a",Yn(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n;const r=((n=t.attrs)==null?void 0:n.href)||"";return`[${e.renderChildren(t)}](${r})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return this.options.isAllowedUri(n,{defaultValidate:r=>!!kl(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:r=>!!kl(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[ea({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,i=yR(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!kl(o,n),protocols:n,defaultProtocol:r}));i.length&&i.forEach(s=>{this.options.shouldAutoLink(s.value)&&e.push({text:s.value,data:{href:s.href},index:s.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;return this.options.autolink&&t.push($8({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!kl(i,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),t.push(B8({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(U8({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),wR=vR,H8=Object.defineProperty,V8=(t,e)=>{for(var n in e)H8(t,n,{get:e[n],enumerable:!0})},W8="listItem",iE="textStyle",sE=/^\s*([-+*])\s$/,bR=yi.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:t}){return["ul",Yn(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>t.type!=="list"||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` @@ -202,9 +202,9 @@ ${p.slice(c+2)}`,d+=1;else break}e.push({indent:c,number:parseInt(l,10),content: * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) * Copyright 2025 Fonticons, Inc. */function X0(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(a){throw a},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,o=!0,l=!1;return{s:function(){n=n.call(t)},n:function(){var a=n.next();return o=a.done,a},e:function(a){l=!0,s=a},f:function(){try{o||n.return==null||n.return()}finally{if(l)throw s}}}}function Bt(t,e,n){return(e=zR(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _H(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function zH(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,s,o,l=[],a=!0,c=!1;try{if(s=(n=n.call(t)).next,e===0){if(Object(n)!==n)return;a=!1}else for(;!(a=(r=s.call(n)).done)&&(l.push(r.value),l.length!==e);a=!0);}catch(u){c=!0,i=u}finally{try{if(!a&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(c)throw i}}return l}}function FH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,o=!0,l=!1;return{s:function(){n=n.call(t)},n:function(){var a=n.next();return o=a.done,a},e:function(a){l=!0,s=a},f:function(){try{o||n.return==null||n.return()}finally{if(l)throw s}}}}function Ut(t,e,n){return(e=zR(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _H(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function zH(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,s,o,l=[],a=!0,c=!1;try{if(s=(n=n.call(t)).next,e===0){if(Object(n)!==n)return;a=!1}else for(;!(a=(r=s.call(n)).done)&&(l.push(r.value),l.length!==e);a=!0);}catch(u){c=!0,i=u}finally{try{if(!a&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(c)throw i}}return l}}function FH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function $H(){throw new TypeError(`Invalid attempt to spread non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pE(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Re(t){for(var e=1;e-1;i--){var s=n[i],o=(s.tagName||"").toUpperCase();["STYLE","LINK"].indexOf(o)>-1&&(r=s)}return Cn.head.insertBefore(e,r),t}}var R7="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";function SE(){for(var t=12,e="";t-- >0;)e+=R7[Math.random()*62|0];return e}function Lc(t){for(var e=[],n=(t||[]).length>>>0;n--;)e[n]=t[n];return e}function Lx(t){return t.classList?Lc(t.classList):(t.getAttribute("class")||"").split(" ").filter(function(e){return e})}function vD(t){return"".concat(t).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")}function D7(t){return Object.keys(t||{}).reduce(function(e,n){return e+"".concat(n,'="').concat(vD(t[n]),'" ')},"").trim()}function wg(t){return Object.keys(t||{}).reduce(function(e,n){return e+"".concat(n,": ").concat(t[n].trim(),";")},"")}function _x(t){return t.size!==bs.size||t.x!==bs.x||t.y!==bs.y||t.rotate!==bs.rotate||t.flipX||t.flipY}function O7(t){var e=t.transform,n=t.containerWidth,r=t.iconWidth,i={transform:"translate(".concat(n/2," 256)")},s="translate(".concat(e.x*32,", ").concat(e.y*32,") "),o="scale(".concat(e.size/16*(e.flipX?-1:1),", ").concat(e.size/16*(e.flipY?-1:1),") "),l="rotate(".concat(e.rotate," 0 0)"),a={transform:"".concat(s," ").concat(o," ").concat(l)},c={transform:"translate(".concat(r/2*-1," -256)")};return{outer:i,inner:a,path:c}}function j7(t){var e=t.transform,n=t.width,r=n===void 0?Z0:n,i=t.height,s=i===void 0?Z0:i,o="";return UR?o+="translate(".concat(e.x/wa-r/2,"em, ").concat(e.y/wa-s/2,"em) "):o+="translate(calc(-50% + ".concat(e.x/wa,"em), calc(-50% + ").concat(e.y/wa,"em)) "),o+="scale(".concat(e.size/wa*(e.flipX?-1:1),", ").concat(e.size/wa*(e.flipY?-1:1),") "),o+="rotate(".concat(e.rotate,"deg) "),o}var P7=`:root, :host { +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pE(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Re(t){for(var e=1;e-1;i--){var s=n[i],o=(s.tagName||"").toUpperCase();["STYLE","LINK"].indexOf(o)>-1&&(r=s)}return Cn.head.insertBefore(e,r),t}}var R7="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";function SE(){for(var t=12,e="";t-- >0;)e+=R7[Math.random()*62|0];return e}function Lc(t){for(var e=[],n=(t||[]).length>>>0;n--;)e[n]=t[n];return e}function Lx(t){return t.classList?Lc(t.classList):(t.getAttribute("class")||"").split(" ").filter(function(e){return e})}function vD(t){return"".concat(t).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")}function D7(t){return Object.keys(t||{}).reduce(function(e,n){return e+"".concat(n,'="').concat(vD(t[n]),'" ')},"").trim()}function wg(t){return Object.keys(t||{}).reduce(function(e,n){return e+"".concat(n,": ").concat(t[n].trim(),";")},"")}function _x(t){return t.size!==bs.size||t.x!==bs.x||t.y!==bs.y||t.rotate!==bs.rotate||t.flipX||t.flipY}function O7(t){var e=t.transform,n=t.containerWidth,r=t.iconWidth,i={transform:"translate(".concat(n/2," 256)")},s="translate(".concat(e.x*32,", ").concat(e.y*32,") "),o="scale(".concat(e.size/16*(e.flipX?-1:1),", ").concat(e.size/16*(e.flipY?-1:1),") "),l="rotate(".concat(e.rotate," 0 0)"),a={transform:"".concat(s," ").concat(o," ").concat(l)},c={transform:"translate(".concat(r/2*-1," -256)")};return{outer:i,inner:a,path:c}}function j7(t){var e=t.transform,n=t.width,r=n===void 0?Z0:n,i=t.height,s=i===void 0?Z0:i,o="";return UR?o+="translate(".concat(e.x/wa-r/2,"em, ").concat(e.y/wa-s/2,"em) "):o+="translate(calc(-50% + ".concat(e.x/wa,"em), calc(-50% + ").concat(e.y/wa,"em)) "),o+="scale(".concat(e.size/wa*(e.flipX?-1:1),", ").concat(e.size/wa*(e.flipY?-1:1),") "),o+="rotate(".concat(e.rotate,"deg) "),o}var P7=`:root, :host { --fa-font-solid: normal 900 1em/1 "Font Awesome 7 Free"; --fa-font-regular: normal 400 1em/1 "Font Awesome 7 Free"; --fa-font-light: normal 300 1em/1 "Font Awesome 7 Pro"; @@ -763,7 +763,7 @@ If it declares any Font Awesome CSS pseudo-elements, they will not be rendered a * Copyright 2025 Fonticons, Inc. */var lf={prefix:"fas",iconName:"palette",icon:[512,512,[127912],"f53f","M512 256c0 .9 0 1.8 0 2.7-.4 36.5-33.6 61.3-70.1 61.3L344 320c-26.5 0-48 21.5-48 48 0 3.4 .4 6.7 1 9.9 2.1 10.2 6.5 20 10.8 29.9 6.1 13.8 12.1 27.5 12.1 42 0 31.8-21.6 60.7-53.4 62-3.5 .1-7 .2-10.6 .2-141.4 0-256-114.6-256-256S114.6 0 256 0 512 114.6 512 256zM128 288a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm0-96a32 32 0 1 0 0-64 32 32 0 1 0 0 64zM288 96a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm96 96a32 32 0 1 0 0-64 32 32 0 1 0 0 64z"]},c9={prefix:"fas",iconName:"users",icon:[640,512,[],"f0c0","M320 16a104 104 0 1 1 0 208 104 104 0 1 1 0-208zM96 88a72 72 0 1 1 0 144 72 72 0 1 1 0-144zM0 416c0-70.7 57.3-128 128-128 12.8 0 25.2 1.9 36.9 5.4-32.9 36.8-52.9 85.4-52.9 138.6l0 16c0 11.4 2.4 22.2 6.7 32L32 480c-17.7 0-32-14.3-32-32l0-32zm521.3 64c4.3-9.8 6.7-20.6 6.7-32l0-16c0-53.2-20-101.8-52.9-138.6 11.7-3.5 24.1-5.4 36.9-5.4 70.7 0 128 57.3 128 128l0 32c0 17.7-14.3 32-32 32l-86.7 0zM472 160a72 72 0 1 1 144 0 72 72 0 1 1 -144 0zM160 432c0-88.4 71.6-160 160-160s160 71.6 160 160l0 16c0 17.7-14.3 32-32 32l-256 0c-17.7 0-32-14.3-32-32l0-16z"]},u9={prefix:"fas",iconName:"folder",icon:[512,512,[128193,128447,61716,"folder-blank"],"f07b","M64 448l384 0c35.3 0 64-28.7 64-64l0-240c0-35.3-28.7-64-64-64L298.7 80c-6.9 0-13.7-2.2-19.2-6.4L241.1 44.8C230 36.5 216.5 32 202.7 32L64 32C28.7 32 0 60.7 0 96L0 384c0 35.3 28.7 64 64 64z"]},d9={prefix:"fas",iconName:"tag",icon:[512,512,[127991],"f02b","M32.5 96l0 149.5c0 17 6.7 33.3 18.7 45.3l192 192c25 25 65.5 25 90.5 0L483.2 333.3c25-25 25-65.5 0-90.5l-192-192C279.2 38.7 263 32 246 32L96.5 32c-35.3 0-64 28.7-64 64zm112 16a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"]};function Hx({anchorRef:t,anchorPoint:e,itemsCount:n=4,onClose:r,onDelete:i,onMoveToCollection:s,onAddLabel:o,onUncheckAll:l,onCheckAll:a,onSetWidth:c}){const u=b.useRef(null),[d,f]=b.useState({position:"fixed",visibility:"hidden",left:0,top:0,zIndex:1e4});b.useLayoutEffect(()=>{const m=t==null?void 0:t.current,g=u.current;if(!g)return;const y=8,v=()=>{g.style.width="auto",g.style.height="auto";const x=Math.ceil(g.offsetWidth),E=Math.ceil(g.offsetHeight);return{w:x,h:E}};if(!m){const{w:x,h:E}=v();let k,M;e?(k=Math.round(e.x-x),M=Math.round(e.y-E)):(k=Math.round(window.innerWidth-x-y),M=Math.round(window.innerHeight-E-y)),kwindow.innerWidth-y&&(k=Math.max(y,window.innerWidth-x-y)),Mwindow.innerHeight-y&&(M=Math.max(y,window.innerHeight-E-y)),f({position:"fixed",left:k,top:M,visibility:"visible",zIndex:1e4,width:`${x}px`,height:`${E}px`});return}const w=m.getBoundingClientRect();requestAnimationFrame(()=>{const{w:x,h:E}=v();let k=Math.round(w.right-x),M=Math.round(w.bottom-E);kwindow.innerWidth-y&&(k=Math.max(y,window.innerWidth-x-y)),Mwindow.innerHeight-y&&(M=Math.max(y,window.innerHeight-E-y)),f({position:"fixed",left:k,top:M,visibility:"visible",zIndex:1e4,width:`${x}px`,height:`${E}px`})})},[t,e,n]),b.useLayoutEffect(()=>{function m(g){u.current&&(u.current.contains(g.target)||r())}return document.addEventListener("pointerdown",m),document.addEventListener("mousedown",m),()=>{document.removeEventListener("pointerdown",m),document.removeEventListener("mousedown",m)}},[r]);const p=h.jsxs("div",{ref:u,className:"more-menu",style:d,role:"dialog","aria-label":"More options",children:[h.jsx("button",{className:"more-item",onClick:()=>{i(),r()},children:"Delete"}),s&&h.jsx("button",{className:"more-item",onClick:()=>{s(),r()},children:"Add to collection…"}),h.jsx("button",{className:"more-item",onClick:()=>{o(),r()},children:"Add label"}),l&&h.jsx("button",{className:"more-item",onClick:()=>{l(),r()},children:"Uncheck all"}),a&&h.jsx("button",{className:"more-item",onClick:()=>{a(),r()},children:"Check all"}),h.jsx("hr",{className:"more-sep"}),h.jsxs("div",{style:{display:"grid",gap:6},children:[h.jsx("button",{className:"more-item",onClick:()=>{c(1),r()},children:"Card width: Regular"}),h.jsx("button",{className:"more-item",onClick:()=>{c(2),r()},children:"Card width: Double"}),h.jsx("button",{className:"more-item",onClick:()=>{c(3),r()},children:"Card width: Triple"})]})]});return zn.createPortal(p,document.body)}const si=()=>new Map,fw=t=>{const e=si();return t.forEach((n,r)=>{e.set(r,n)}),e},as=(t,e,n)=>{let r=t.get(e);return r===void 0&&t.set(e,r=n()),r},f9=(t,e)=>{const n=[];for(const[r,i]of t)n.push(e(i,r));return n},h9=(t,e)=>{for(const[n,r]of t)if(e(r,n))return!0;return!1},uo=()=>new Set,rv=t=>t[t.length-1],p9=(t,e)=>{for(let n=0;n{for(let n=0;n{for(let n=0;n{const n=new Array(t);for(let r=0;r{this.off(e,r),n(...i)};this.on(e,r)}off(e,n){const r=this._observers.get(e);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(e))}emit(e,n){return fo((this._observers.get(e)||si()).values()).forEach(r=>r(...n))}destroy(){this._observers=si()}}class VD{constructor(){this._observers=si()}on(e,n){as(this._observers,e,uo).add(n)}once(e,n){const r=(...i)=>{this.off(e,r),n(...i)};this.on(e,r)}off(e,n){const r=this._observers.get(e);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(e))}emit(e,n){return fo((this._observers.get(e)||si()).values()).forEach(r=>r(...n))}destroy(){this._observers=si()}}const zi=Math.floor,Rh=Math.abs,ia=(t,e)=>tt>e?t:e,g9=Math.pow,WD=t=>t!==0?t<0:1/t<0,YE=1,qE=2,iv=4,sv=8,Nd=32,to=64,Br=128,y9=1<<29,Sg=31,hw=63,Hl=127,v9=2147483647,um=Number.MAX_SAFE_INTEGER,JE=Number.MIN_SAFE_INTEGER,w9=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&zi(t)===t),KD=String.fromCharCode,b9=t=>t.toLowerCase(),x9=/^\s*/g,k9=t=>t.replace(x9,""),S9=/([A-Z])/g,GE=(t,e)=>k9(t.replace(S9,n=>`${e}${b9(n)}`)),C9=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,r=new Uint8Array(n);for(let i=0;iTd.encode(t),N9=Td?E9:C9;let Vu=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Vu&&Vu.decode(new Uint8Array).length===1&&(Vu=null);const T9=(t,e)=>m9(e,()=>t).join("");class af{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const gr=()=>new af,A9=t=>{const e=gr();return t(e),Nn(e)},Kx=t=>{let e=t.cpos;for(let n=0;n{const e=new Uint8Array(Kx(t));let n=0;for(let r=0;r{const n=t.cbuf.length;n-t.cpos{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},pw=rr,vt=(t,e)=>{for(;e>Hl;)rr(t,Br|Hl&e),e=zi(e/128);rr(t,Hl&e)},Yx=(t,e)=>{const n=WD(e);for(n&&(e=-e),rr(t,(e>hw?Br:0)|(n?to:0)|hw&e),e=zi(e/64);e>0;)rr(t,(e>Hl?Br:0)|Hl&e),e=zi(e/128)},mw=new Uint8Array(3e4),I9=mw.length/3,R9=(t,e)=>{if(e.length{const n=unescape(encodeURIComponent(e)),r=n.length;vt(t,r);for(let i=0;i{const n=t.cbuf.length,r=t.cpos,i=ia(n-r,e.length),s=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,s>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(ho(n*2,s)),t.cbuf.set(e.subarray(i)),t.cpos=s)},Ln=(t,e)=>{vt(t,e.byteLength),Cg(t,e)},qx=(t,e)=>{M9(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},O9=(t,e)=>qx(t,4).setFloat32(0,e,!1),j9=(t,e)=>qx(t,8).setFloat64(0,e,!1),P9=(t,e)=>qx(t,8).setBigInt64(0,e,!1),XE=new DataView(new ArrayBuffer(4)),L9=t=>(XE.setFloat32(0,t),XE.getFloat32(0)===t),Cc=(t,e)=>{switch(typeof e){case"string":rr(t,119),Vl(t,e);break;case"number":w9(e)&&Rh(e)<=v9?(rr(t,125),Yx(t,e)):L9(e)?(rr(t,124),O9(t,e)):(rr(t,123),j9(t,e));break;case"bigint":rr(t,122),P9(t,e);break;case"object":if(e===null)rr(t,126);else if(Sc(e)){rr(t,117),vt(t,e.length);for(let n=0;n0&&vt(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const ZE=t=>{t.count>0&&(Yx(t.encoder,t.count===1?t.s:-t.s),t.count>1&&vt(t.encoder,t.count-2))};class Dh{constructor(){this.encoder=new af,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ZE(this),this.count=1,this.s=e)}toUint8Array(){return ZE(this),Nn(this.encoder)}}const eN=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Yx(t.encoder,e),t.count>1&&vt(t.encoder,t.count-2)}};class ov{constructor(){this.encoder=new af,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(eN(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return eN(this),Nn(this.encoder)}}class _9{constructor(){this.sarr=[],this.s="",this.lensE=new Dh}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new af;return this.sarr.push(this.s),this.s="",Vl(e,this.sarr.join("")),Cg(e,this.lensE.toUint8Array()),Nn(e)}}const Rs=t=>new Error(t),Oi=()=>{throw Rs("Method unimplemented")},Dr=()=>{throw Rs("Unexpected case")},YD=Rs("Unexpected end of array"),qD=Rs("Integer out of Range");class Eg{constructor(e){this.arr=e,this.pos=0}}const xl=t=>new Eg(t),z9=t=>t.pos!==t.arr.length,F9=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Tr=t=>F9(t,Lt(t)),Ec=t=>t.arr[t.pos++],Lt=t=>{let e=0,n=1;const r=t.arr.length;for(;t.posum)throw qD}throw YD},Jx=t=>{let e=t.arr[t.pos++],n=e&hw,r=64;const i=(e&to)>0?-1:1;if(!(e&Br))return i*n;const s=t.arr.length;for(;t.posum)throw qD}throw YD},$9=t=>{let e=Lt(t);if(e===0)return"";{let n=String.fromCodePoint(Ec(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Ec(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,n+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(n))}},B9=t=>Vu.decode(Tr(t)),nl=Vu?B9:$9,Gx=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},U9=t=>Gx(t,4).getFloat32(0,!1),H9=t=>Gx(t,8).getFloat64(0,!1),V9=t=>Gx(t,8).getBigInt64(0,!1),W9=[t=>{},t=>null,Jx,U9,H9,V9,t=>!1,t=>!0,nl,t=>{const e=Lt(t),n={};for(let r=0;r{const e=Lt(t),n=[];for(let r=0;rW9[127-Ec(t)](t);class tN extends Eg{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),z9(this)?this.count=Lt(this)+1:this.count=-1),this.count--,this.s}}class Oh extends Eg{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Jx(this);const e=WD(this.s);this.count=1,e&&(this.s=-this.s,this.count=Lt(this)+2)}return this.count--,this.s}}class lv extends Eg{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Jx(this),n=e&1;this.diff=zi(e/2),this.count=1,n&&(this.count=Lt(this)+2)}return this.s+=this.diff,this.count--,this.s}}class K9{constructor(e){this.decoder=new Oh(e),this.str=nl(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const Y9=crypto.getRandomValues.bind(crypto),q9=Math.random,JD=()=>Y9(new Uint32Array(1))[0],J9=t=>t[zi(q9()*t.length)],G9="10000000-1000-4000-8000"+-1e11,X9=()=>G9.replace(/[018]/g,t=>(t^JD()&15>>t/4).toString(16)),dl=Date.now,nN=t=>new Promise(t);Promise.all.bind(Promise);const rN=t=>t===void 0?null:t;class Q9{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let GD=new Q9,Xx=!0;try{typeof localStorage<"u"&&localStorage&&(GD=localStorage,Xx=!1)}catch{}const XD=GD,Z9=t=>Xx||addEventListener("storage",t),eK=t=>Xx||removeEventListener("storage",t),Md=Symbol("Equality"),QD=(t,e)=>{var n;return t===e||!!((n=t==null?void 0:t[Md])!=null&&n.call(t,e))||!1},tK=t=>typeof t=="object",nK=Object.assign,ZD=Object.keys,rK=(t,e)=>{for(const n in t)e(t[n],n)},iK=(t,e)=>{const n=[];for(const r in t)n.push(e(t[r],r));return n},dm=t=>ZD(t).length,sK=t=>{for(const e in t)return!1;return!0},_c=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},Qx=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),oK=(t,e)=>t===e||dm(t)===dm(e)&&_c(t,(n,r)=>(n!==void 0||Qx(e,r))&&QD(e[r],n)),lK=Object.freeze,eO=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&eO(t[e])}return lK(t)},Zx=(t,e,n=0)=>{try{for(;nt,Qa=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[Md]!=null)return t[Md](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let n=0;ne.includes(t);var tO={};const fl=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",e1=typeof window<"u"&&typeof document<"u"&&!fl;let hs;const uK=()=>{if(hs===void 0)if(fl){hs=si();const t=process.argv;let e=null;for(let n=0;n{if(t.length!==0){const[e,n]=t.split("=");hs.set(`--${GE(e,"-")}`,n),hs.set(`-${GE(e,"-")}`,n)}})):hs=si();return hs},gw=t=>uK().has(t),fm=t=>rN(fl?tO[t.toUpperCase().replaceAll("-","_")]:XD.getItem(t)),nO=t=>gw("--"+t)||fm(t)!==null,dK=nO("production"),fK=fl&&cK(tO.FORCE_COLOR,["true","1","2"]),hK=fK||!gw("--no-colors")&&!nO("no-color")&&(!fl||process.stdout.isTTY)&&(!fl||gw("--color")||fm("COLORTERM")!==null||(fm("TERM")||"").includes("color")),rO=t=>new Uint8Array(t),pK=(t,e,n)=>new Uint8Array(t,e,n),mK=t=>new Uint8Array(t),gK=t=>{let e="";for(let n=0;nBuffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),vK=t=>{const e=atob(t),n=rO(e.length);for(let r=0;r{const e=Buffer.from(t,"base64");return pK(e.buffer,e.byteOffset,e.byteLength)},iO=e1?gK:yK,bK=e1?vK:wK,xK=t=>{const e=rO(t.byteLength);return e.set(t),e},kK=t=>A9(e=>Cc(e,t));class SK{constructor(e,n){this.left=e,this.right=n}}const zs=(t,e)=>new SK(t,e),iN=t=>t.next()>=.5,av=(t,e,n)=>zi(t.next()*(n+1-e)+e),sO=(t,e,n)=>zi(t.next()*(n+1-e)+e),t1=(t,e,n)=>sO(t,e,n),CK=t=>KD(t1(t,97,122)),EK=(t,e=0,n=20)=>{const r=t1(t,e,n);let i="";for(let s=0;se[t1(t,0,e.length-1)],NK=Symbol("0schema");class TK{constructor(){this._rerrs=[]}extend(e,n,r,i=null){this._rerrs.push({path:e,expected:n,has:r,message:i})}toString(){const e=[];for(let n=this._rerrs.length-1;n>0;n--){const r=this._rerrs[n];e.push(T9(" ",(this._rerrs.length-n)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(` `)}}const yw=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[Md]?QD(t,e):Sc(t)?Vx(t,n=>Wx(e,r=>yw(n,r))):tK(t)?_c(t,(n,r)=>yw(n,e[r])):!1;class jr{extends(e){let[n,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,n]=[n,r]),yw(n,r)}equals(e){return this.constructor===e.constructor&&Qa(this.shape,e.shape)}[NK](){return!0}[Md](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){Oi()}get nullable(){return zc(this,Ig)}get optional(){return new aO(this)}cast(e){return sN(e,this),e}expect(e){return sN(e,this),e}}bf(jr,"_dilutes",!1);class n1 extends jr{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n=void 0){const r=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!r&&(n==null||n.extend(null,this.shape.name,e==null?void 0:e.constructor.name,(e==null?void 0:e.constructor)!==this.shape?"Constructor match failed":"Check failed")),r}}const Jn=(t,e=null)=>new n1(t,e);Jn(n1);class r1 extends jr{constructor(e){super(),this.shape=e}check(e,n){const r=this.shape(e);return!r&&(n==null||n.extend(null,"custom prop",e==null?void 0:e.constructor.name,"failed to check custom prop")),r}}const fr=t=>new r1(t);Jn(r1);class Ng extends jr{constructor(e){super(),this.shape=e}check(e,n){const r=this.shape.some(i=>i===e);return!r&&(n==null||n.extend(null,this.shape.join(" | "),e.toString())),r}}const Tg=(...t)=>new Ng(t),oO=Jn(Ng),AK=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),lO=t=>{if(Nc.check(t))return[AK(t)];if(oO.check(t))return t.shape.map(e=>e+"");if(yO.check(t))return["[+-]?\\d+.?\\d*"];if(vO.check(t))return[".*"];if(pm.check(t))return t.shape.map(lO).flat(1);Dr()};class MK extends jr{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(lO).map(n=>`(${n.join("|")})`).join("")+"$")}check(e,n){const r=this._r.exec(e)!=null;return!r&&(n==null||n.extend(null,this._r.toString(),e.toString(),"String doesn't match string template.")),r}}Jn(MK);const IK=Symbol("optional");class aO extends jr{constructor(e){super(),this.shape=e}check(e,n){const r=e===void 0||this.shape.check(e);return!r&&(n==null||n.extend(null,"undefined (optional)","()")),r}get[IK](){return!0}}const RK=Jn(aO);class DK extends jr{check(e,n){return n==null||n.extend(null,"never",typeof e),!1}}Jn(DK);const Nm=class Nm extends jr{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}get partial(){return new Nm(this.shape,!0)}check(e,n){return e==null?(n==null||n.extend(null,"object","null"),!1):_c(this.shape,(r,i)=>{const s=this._isPartial&&!Qx(e,i)||r.check(e[i],n);return!s&&(n==null||n.extend(i.toString(),r.toString(),typeof e[i],"Object property does not match")),s})}};bf(Nm,"_dilutes",!0);let hm=Nm;const OK=t=>new hm(t),jK=Jn(hm),PK=fr(t=>t!=null&&(t.constructor===Object||t.constructor==null));class cO extends jr{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&_c(e,(r,i)=>{const s=this.shape.keys.check(i,n);return!s&&(n==null||n.extend(i+"","Record",typeof e,s?"Key doesn't match schema":"Value doesn't match value")),s&&this.shape.values.check(r,n)})}}const uO=(t,e)=>new cO(t,e),LK=Jn(cO);class dO extends jr{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&_c(this.shape,(r,i)=>{const s=r.check(e[i],n);return!s&&(n==null||n.extend(i.toString(),"Tuple",typeof r)),s})}}const _K=(...t)=>new dO(t);Jn(dO);class fO extends jr{constructor(e){super(),this.shape=e.length===1?e[0]:new Ag(e)}check(e,n){const r=Sc(e)&&Vx(e,i=>this.shape.check(i));return!r&&(n==null||n.extend(null,"Array","")),r}}const hO=(...t)=>new fO(t),zK=Jn(fO),FK=fr(t=>Sc(t));class pO extends jr{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n){const r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&(n==null||n.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),r}}const $K=(t,e=null)=>new pO(t,e);Jn(pO);const BK=$K(jr);class UK extends jr{constructor(e){super(),this.len=e.length-1,this.args=_K(...e.slice(-1)),this.res=e[this.len]}check(e,n){const r=e.constructor===Function&&e.length<=this.len;return!r&&(n==null||n.extend(null,"function",typeof e)),r}}const HK=Jn(UK),VK=fr(t=>typeof t=="function");class WK extends jr{constructor(e){super(),this.shape=e}check(e,n){const r=Vx(this.shape,i=>i.check(e,n));return!r&&(n==null||n.extend(null,"Intersectinon",typeof e)),r}}Jn(WK,t=>t.shape.length>0);class Ag extends jr{constructor(e){super(),this.shape=e}check(e,n){const r=Wx(this.shape,i=>i.check(e,n));return n==null||n.extend(null,"Union",typeof e),r}}bf(Ag,"_dilutes",!0);const zc=(...t)=>t.findIndex(e=>pm.check(e))>=0?zc(...t.map(e=>Id(e)).map(e=>pm.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Ag(t),pm=Jn(Ag),mO=()=>!0,mm=fr(mO),KK=Jn(r1,t=>t.shape===mO),i1=fr(t=>typeof t=="bigint"),YK=fr(t=>t===i1),gO=fr(t=>typeof t=="symbol");fr(t=>t===gO);const Za=fr(t=>typeof t=="number"),yO=fr(t=>t===Za),Nc=fr(t=>typeof t=="string"),vO=fr(t=>t===Nc),Mg=fr(t=>typeof t=="boolean"),qK=fr(t=>t===Mg),wO=Tg(void 0);Jn(Ng,t=>t.shape.length===1&&t.shape[0]===void 0);Tg(void 0);const Ig=Tg(null),JK=Jn(Ng,t=>t.shape.length===1&&t.shape[0]===null);Jn(Uint8Array);Jn(n1,t=>t.shape===Uint8Array);const GK=zc(Za,Nc,Ig,wO,i1,Mg,gO);(()=>{const t=hO(mm),e=uO(Nc,mm),n=zc(Za,Nc,Ig,Mg,t,e);return t.shape=n,e.shape.values=n,n})();const Id=t=>{if(BK.check(t))return t;if(PK.check(t)){const e={};for(const n in t)e[n]=Id(t[n]);return OK(e)}else{if(FK.check(t))return zc(...t.map(Id));if(GK.check(t))return Tg(t);if(VK.check(t))return Jn(t)}Dr()},sN=dK?()=>{}:(t,e)=>{const n=new TK;if(!e.check(t,n))throw Rs(`Expected value to be of type ${e.constructor.name}. -${n.toString()}`)};class XK{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Id(e),h:n}),this}else(e){return this.if(mm,e)}done(){return(e,n)=>{for(let r=0;rnew XK(t),bO=QK(mm).if(yO,(t,e)=>av(e,JE,um)).if(vO,(t,e)=>EK(e)).if(qK,(t,e)=>iN(e)).if(YK,(t,e)=>BigInt(av(e,JE,um))).if(pm,(t,e)=>xa(e,cv(e,t.shape))).if(jK,(t,e)=>{const n={};for(const r in t.shape){let i=t.shape[r];if(RK.check(i)){if(iN(e))continue;i=i.shape}n[r]=bO(i,e)}return n}).if(zK,(t,e)=>{const n=[],r=sO(e,0,42);for(let i=0;icv(e,t.shape)).if(JK,(t,e)=>null).if(HK,(t,e)=>{const n=xa(e,t.res);return()=>n}).if(KK,(t,e)=>xa(e,cv(e,[Za,Nc,Ig,wO,i1,Mg,hO(Za),uO(zc("a","b","c"),Za)]))).if(LK,(t,e)=>{const n={},r=av(e,0,3);for(let i=0;ibO(Id(e),t),cf=typeof document<"u"?document:{};fr(t=>t.nodeType===rY);typeof DOMParser<"u"&&new DOMParser;fr(t=>t.nodeType===eY);fr(t=>t.nodeType===tY);const ZK=t=>f9(t,(e,n)=>`${n}:${e};`).join(""),eY=cf.ELEMENT_NODE,tY=cf.TEXT_NODE,nY=cf.DOCUMENT_NODE,rY=cf.DOCUMENT_FRAGMENT_NODE;fr(t=>t.nodeType===nY);const iY=t=>class{constructor(n){this._=n}destroy(){t(this._)}},sY=iY(clearTimeout),xO=(t,e)=>new sY(setTimeout(e,t)),wo=Symbol,kO=wo(),SO=wo(),oY=wo(),lY=wo(),aY=wo(),CO=wo(),cY=wo(),s1=wo(),uY=wo(),dY=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],n=[];let r=0;for(;r0&&n.push(e.join(""));r{var o;t.length===1&&((o=t[0])==null?void 0:o.constructor)===Function&&(t=t[0]());const e=[],n=[],r=si();let i=[],s=0;for(;s0||c.length>0?(e.push("%c"+l),n.push(c)):e.push(l)}else break}}for(s>0&&(i=n,i.unshift(e.join("")));s{console.log(...EO(t)),TO.forEach(e=>e.print(t))},NO=(...t)=>{console.warn(...EO(t)),t.unshift(s1),TO.forEach(e=>e.print(t))},TO=uo(),AO=t=>({[Symbol.iterator](){return this},next:t}),mY=(t,e)=>AO(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),uv=(t,e)=>AO(()=>{const{done:n,value:r}=t.next();return{done:n,value:n?void 0:e(r)}});class o1{constructor(e,n){this.clock=e,this.len=n}}class Fc{constructor(){this.clients=new Map}}const hl=(t,e,n)=>e.clients.forEach((r,i)=>{const s=t.doc.store.clients.get(i);if(s!=null){const o=s[s.length-1],l=o.id.clock+o.length;for(let a=0,c=r[a];a{let n=0,r=t.length-1;for(;n<=r;){const i=zi((n+r)/2),s=t[i],o=s.clock;if(o<=e){if(e{const n=t.clients.get(e.client);return n!==void 0&&gY(n,e.clock)!==null},l1=t=>{t.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=ho(i.len,s.clock+s.len-i.clock):(r{const e=new Fc;for(let n=0;n{if(!e.clients.has(i)){const s=r.slice();for(let o=n+1;o{as(t.clients,e,()=>[]).push(new o1(n,r))},MO=()=>new Fc,IO=t=>{const e=MO();return t.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},Bc=(t,e)=>{vt(t.restEncoder,e.clients.size),fo(e.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{t.resetDsCurVal(),vt(t.restEncoder,n);const i=r.length;vt(t.restEncoder,i);for(let s=0;s{const e=new Fc,n=Lt(t.restDecoder);for(let r=0;r0){const o=as(e.clients,i,()=>[]);for(let l=0;l{const r=new Fc,i=Lt(t.restDecoder);for(let s=0;s0){const s=new sa;return vt(s.restEncoder,0),Bc(s,r),s.toUint8Array()}return null},RO=JD;class Fi extends HD{constructor({guid:e=X9(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=RO(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new $O,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=nN(c=>{this.on("load",()=>{this.isLoaded=!0,c(this)})});const a=()=>nN(c=>{const u=d=>{(d===void 0||d===!0)&&(this.off("sync",u),c())};this.on("sync",u)});this.on("sync",c=>{c===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=c===void 0||c===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=a()}load(){const e=this._item;e!==null&&!this.shouldLoad&&yn(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(fo(this.subdocs).map(e=>e.guid))}transact(e,n=null){return yn(this,e,n)}get(e,n=dr){const r=as(this.share,e,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==dr&&i!==n)if(i===dr){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,nc)}getText(e=""){return this.get(e,pl)}getMap(e=""){return this.get(e,xs)}getXmlElement(e=""){return this.get(e,Mr)}getXmlFragment(e=""){return this.get(e,oa)}toJSON(){const e={};return this.share.forEach((n,r)=>{e[r]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,fo(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Fi({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,yn(e.parent.doc,r=>{const i=n.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class DO{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Lt(this.restDecoder)}readDsLen(){return Lt(this.restDecoder)}}class OO extends DO{readLeftID(){return Ut(Lt(this.restDecoder),Lt(this.restDecoder))}readRightID(){return Ut(Lt(this.restDecoder),Lt(this.restDecoder))}readClient(){return Lt(this.restDecoder)}readInfo(){return Ec(this.restDecoder)}readString(){return nl(this.restDecoder)}readParentInfo(){return Lt(this.restDecoder)===1}readTypeRef(){return Lt(this.restDecoder)}readLen(){return Lt(this.restDecoder)}readAny(){return Ad(this.restDecoder)}readBuf(){return xK(Tr(this.restDecoder))}readJSON(){return JSON.parse(nl(this.restDecoder))}readKey(){return nl(this.restDecoder)}}class yY{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Lt(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Lt(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Tc extends yY{constructor(e){super(e),this.keys=[],Lt(e),this.keyClockDecoder=new lv(Tr(e)),this.clientDecoder=new Oh(Tr(e)),this.leftClockDecoder=new lv(Tr(e)),this.rightClockDecoder=new lv(Tr(e)),this.infoDecoder=new tN(Tr(e),Ec),this.stringDecoder=new K9(Tr(e)),this.parentInfoDecoder=new tN(Tr(e),Ec),this.typeRefDecoder=new Oh(Tr(e)),this.lenDecoder=new Oh(Tr(e))}readLeftID(){return new ec(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ec(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ad(this.restDecoder)}readBuf(){return Tr(this.restDecoder)}readJSON(){return Ad(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=ho(r,e[0].id.clock);const i=ss(e,r);vt(t.restEncoder,e.length-i),t.writeClient(n),vt(t.restEncoder,r);const s=e[i];s.write(t,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{Fn(e,s)>i&&r.set(s,i)}),df(e).forEach((i,s)=>{n.has(s)||r.set(s,0)}),vt(t.restEncoder,r.size),fo(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{vY(t,e.clients.get(i),i,s)})},wY=(t,e)=>{const n=si(),r=Lt(t.restDecoder);for(let i=0;i{const r=[];let i=fo(n.keys()).sort((p,m)=>p-m);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let p=n.get(i[i.length-1]);for(;p.refs.length===p.i;)if(i.pop(),i.length>0)p=n.get(i[i.length-1]);else return null;return p};let o=s();if(o===null)return null;const l=new $O,a=new Map,c=(p,m)=>{const g=a.get(p);(g==null||g>m)&&a.set(p,m)};let u=o.refs[o.i++];const d=new Map,f=()=>{for(const p of r){const m=p.id.client,g=n.get(m);g?(g.i--,l.clients.set(m,g.refs.slice(g.i)),n.delete(m),g.i=0,g.refs=[]):l.clients.set(m,[p]),i=i.filter(y=>y!==m)}r.length=0};for(;;){if(u.constructor!==Ai){const m=as(d,u.id.client,()=>Fn(e,u.id.client))-u.id.clock;if(m<0)r.push(u),c(u.id.client,u.id.clock-1),f();else{const g=u.getMissing(t,e);if(g!==null){r.push(u);const y=n.get(g)||{refs:[],i:0};if(y.refs.length===y.i)c(g,Fn(e,g)),f();else{u=y.refs[y.i++];continue}}else(m===0||m0)u=r.pop();else if(o!==null&&o.i0){const p=new sa;return c1(p,l,new Map),vt(p.restEncoder,0),{missing:a,update:p.toUint8Array()}}return null},xY=(t,e)=>c1(t,e.doc.store,e.beforeState),kY=(t,e,n,r=new Tc(t))=>yn(e,i=>{i.local=!1;let s=!1;const o=i.doc,l=o.store,a=wY(r,o),c=bY(i,l,a),u=l.pendingStructs;if(u){for(const[f,p]of u.missing)if(pp)&&u.missing.set(f,p)}u.update=vm([u.update,c.update])}}else l.pendingStructs=c;const d=oN(r,i,l);if(l.pendingDs){const f=new Tc(xl(l.pendingDs));Lt(f.restDecoder);const p=oN(f,i,l);d&&p?l.pendingDs=vm([d,p]):l.pendingDs=d||p}else l.pendingDs=d;if(s){const f=l.pendingStructs.update;l.pendingStructs=null,gm(i.doc,f)}},n,!1),gm=(t,e,n,r=Tc)=>{const i=xl(e);kY(i,t,n,new r(i))},SY=(t,e,n)=>gm(t,e,n,OO),CY=(t,e,n=new Map)=>{c1(t,e.store,n),Bc(t,IO(e.store))},EY=(t,e=new Uint8Array([0]),n=new sa)=>{const r=LO(e);CY(n,t,r);const i=[n.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(WY(t.store.pendingStructs.update,e)),i.length>1){if(n.constructor===uf)return HY(i.map((s,o)=>o===0?s:YY(s)));if(n.constructor===sa)return vm(i)}return i[0]},NY=(t,e)=>EY(t,e,new uf),TY=t=>{const e=new Map,n=Lt(t.restDecoder);for(let r=0;rTY(new DO(xl(t))),_O=(t,e)=>(vt(t.restEncoder,e.size),fo(e.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{vt(t.restEncoder,n),vt(t.restEncoder,r)}),t),AY=(t,e)=>_O(t,df(e.store)),MY=(t,e=new PO)=>(t instanceof Map?_O(e,t):AY(e,t),e.toUint8Array()),IY=t=>MY(t,new jO);class RY{constructor(){this.l=[]}}const lN=()=>new RY,aN=(t,e)=>t.l.push(e),cN=(t,e)=>{const n=t.l,r=n.length;t.l=n.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},zO=(t,e,n)=>Zx(t.l,[e,n]);class ec{constructor(e,n){this.client=e,this.clock=n}}const ih=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,Ut=(t,e)=>new ec(t,e),Dd=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw Dr()},Od=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class ym{constructor(e,n,r,i=0){this.type=e,this.tname=n,this.item=r,this.assoc=i}}class DY{constructor(e,n,r=0){this.type=e,this.index=n,this.assoc=r}}const OY=(t,e,n=0)=>new DY(t,e,n),sh=(t,e,n)=>{let r=null,i=null;return t._item===null?i=Dd(t):r=Ut(t._item.id.client,t._item.id.clock),new ym(r,i,e,n)},dv=(t,e,n=0)=>{let r=t._start;if(n<0){if(e===0)return sh(t,null,n);e--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>e)return sh(t,Ut(r.id.client,r.id.clock+e),n);e-=r.length}if(r.right===null&&n<0)return sh(t,r.lastId,n);r=r.right}return sh(t,null,n)},jY=(t,e)=>{const n=tc(t,e),r=e.clock-n.id.clock;return{item:n,diff:r}},PY=(t,e,n=!0)=>{const r=e.store,i=t.item,s=t.type,o=t.tname,l=t.assoc;let a=null,c=0;if(i!==null){if(Fn(r,i.client)<=i.clock)return null;const u=n?kw(r,i):jY(r,i),d=u.item;if(!(d instanceof cn))return null;if(a=d.parent,a._item===null||!a._item.deleted){c=d.deleted||!d.countable?0:u.diff+(l>=0?0:1);let f=d.left;for(;f!==null;)!f.deleted&&f.countable&&(c+=f.length),f=f.left}}else{if(o!==null)a=e.get(o);else if(s!==null){if(Fn(r,s.client)<=s.clock)return null;const{item:u}=n?kw(r,s):{item:tc(r,s)};if(u instanceof cn&&u.content instanceof cs)a=u.content.type;else return null}else throw Dr();l>=0?c=a._length:c=0}return OY(a,c,t.assoc)};class u1{constructor(e,n){this.ds=e,this.sv=n}}const FO=(t,e)=>new u1(t,e),fv=t=>FO(IO(t.store),df(t.store)),Tl=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!$c(e.ds,t.id),ww=(t,e)=>{const n=as(t.meta,ww,uo),r=t.doc.store;n.has(e)||(e.sv.forEach((i,s)=>{i{}),n.add(e))};class $O{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const df=t=>{const e=new Map;return t.clients.forEach((n,r)=>{const i=n[n.length-1];e.set(r,i.id.clock+i.length)}),e},Fn=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},BO=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==e.id.clock)throw Dr()}n.push(e)},ss=(t,e)=>{let n=0,r=t.length-1,i=t[r],s=i.id.clock;if(s===e)return r;let o=zi(e/(s+i.length-1)*r);for(;n<=r;){if(i=t[o],s=i.id.clock,s<=e){if(e{const n=t.clients.get(e.client);return n[ss(n,e.clock)]},tc=LY,bw=(t,e,n)=>{const r=ss(e,n),i=e[r];return i.id.clock{const n=t.doc.store.clients.get(e.client);return n[bw(t,n,e.clock)]},uN=(t,e,n)=>{const r=e.clients.get(n.client),i=ss(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Ti&&r.splice(i+1,0,Sm(t,s,n.clock-s.id.clock+1)),s},_Y=(t,e,n)=>{const r=t.clients.get(e.id.client);r[ss(r,e.id.clock)]=n},UO=(t,e,n,r,i)=>{if(r===0)return;const s=n+r;let o=bw(t,e,n),l;do l=e[o++],se.deleteSet.clients.size===0&&!h9(e.afterState,(n,r)=>e.beforeState.get(r)!==n)?!1:(l1(e.deleteSet),xY(t,e),Bc(t,e.deleteSet),!0),fN=(t,e,n)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&as(t.changed,e,uo).add(n)},jh=(t,e)=>{let n=t[e],r=t[e-1],i=e;for(;i>0;n=r,r=t[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof cn&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=e-i;return s&&t.splice(e+1-s,s),s},FY=(t,e,n)=>{for(const[r,i]of t.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const l=i[o],a=l.clock+l.len;for(let c=ss(s,l.clock),u=s[c];c{t.clients.forEach((n,r)=>{const i=e.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],l=ia(i.length-1,1+ss(i,o.clock+o.len-1));for(let a=l,c=i[a];a>0&&c.id.clock>=o.clock;c=i[a])a-=1+jh(i,a)}})},HO=(t,e)=>{if(el.push(()=>{(c._item===null||!c._item.deleted)&&c._callObserver(n,a)})),l.push(()=>{n.changedParentTypes.forEach((a,c)=>{c._dEH.l.length>0&&(c._item===null||!c._item.deleted)&&(a=a.filter(u=>u.target._item===null||!u.target._item.deleted),a.forEach(u=>{u.currentTarget=c,u._path=null}),a.sort((u,d)=>u.path.length-d.path.length),l.push(()=>{zO(c._dEH,a,n)}))}),l.push(()=>r.emit("afterTransaction",[n,r])),l.push(()=>{n._needFormattingCleanup&&lq(n)})}),Zx(l,[])}finally{r.gc&&FY(s,i,r.gcFilter),$Y(s,i),n.afterState.forEach((u,d)=>{const f=n.beforeState.get(d)||0;if(f!==u){const p=i.clients.get(d),m=ho(ss(p,f),1);for(let g=p.length-1;g>=m;)g-=1+jh(p,g)}});for(let u=o.length-1;u>=0;u--){const{client:d,clock:f}=o[u].id,p=i.clients.get(d),m=ss(p,f);m+11||m>0&&jh(p,m)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(pY(s1,kO,"[yjs] ",SO,CO,"Changed the client-id because another client seems to be using it."),r.clientID=RO()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new uf;dN(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new sa;dN(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:l,subdocsLoaded:a,subdocsRemoved:c}=n;(l.size>0||c.size>0||a.size>0)&&(l.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),c.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:a,added:l,removed:c},r,n]),c.forEach(u=>u.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):HO(t,e+1)}}},yn=(t,e,n=null,r=!0)=>{const i=t._transactionCleanups;let s=!1,o=null;t._transaction===null&&(s=!0,t._transaction=new zY(t,n,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{o=e(t._transaction)}finally{if(s){const l=t._transaction===i[0];t._transaction=null,l&&HO(i,0)}}return o};class BY{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const hN=(t,e,n)=>{hl(t,n.deletions,r=>{r instanceof cn&&e.scope.some(i=>i===t.doc||Od(i,r))&&v1(r,!1)})},pN=(t,e,n)=>{let r=null;const i=t.doc,s=t.scope;yn(i,l=>{for(;e.length>0&&t.currStackItem===null;){const a=i.store,c=e.pop(),u=new Set,d=[];let f=!1;hl(l,c.insertions,p=>{if(p instanceof cn){if(p.redone!==null){let{item:m,diff:g}=kw(a,p.id);g>0&&(m=Qr(l,Ut(m.id.client,m.id.clock+g))),p=m}!p.deleted&&s.some(m=>m===l.doc||Od(m,p))&&d.push(p)}}),hl(l,c.deletions,p=>{p instanceof cn&&s.some(m=>m===l.doc||Od(m,p))&&!$c(c.insertions,p.id)&&u.add(p)}),u.forEach(p=>{f=cj(l,p,u,c.insertions,t.ignoreRemoteMapChanges,t)!==null||f});for(let p=d.length-1;p>=0;p--){const m=d[p];t.deleteFilter(m)&&(m.delete(l),f=!0)}t.currStackItem=f?c:null}l.changed.forEach((a,c)=>{a.has(null)&&c._searchMarker&&(c._searchMarker.length=0)}),r=l},t);const o=t.currStackItem;if(o!=null){const l=r.changedParentTypes;t.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:t},t]),t.currStackItem=null}return o};class VO extends HD{constructor(e,{captureTimeout:n=500,captureTransaction:r=a=>!0,deleteFilter:i=()=>!0,trackedOrigins:s=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=Sc(e)?e[0].doc:e instanceof Fi?e:e.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(e),this.deleteFilter=i,s.add(this),this.trackedOrigins=s,this.captureTransaction=r,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=a=>{if(!this.captureTransaction(a)||!this.scope.some(y=>a.changedParentTypes.has(y)||y===this.doc)||!this.trackedOrigins.has(a.origin)&&(!a.origin||!this.trackedOrigins.has(a.origin.constructor)))return;const c=this.undoing,u=this.redoing,d=c?this.redoStack:this.undoStack;c?this.stopCapturing():u||this.clear(!1,!0);const f=new Fc;a.afterState.forEach((y,v)=>{const w=a.beforeState.get(v)||0,x=y-w;x>0&&Rd(f,v,w,x)});const p=dl();let m=!1;if(this.lastChange>0&&p-this.lastChange0&&!c&&!u){const y=d[d.length-1];y.deletions=vw([y.deletions,a.deleteSet]),y.insertions=vw([y.insertions,f])}else d.push(new BY(a.deleteSet,f)),m=!0;!c&&!u&&(this.lastChange=p),hl(a,a.deleteSet,y=>{y instanceof cn&&this.scope.some(v=>v===a.doc||Od(v,y))&&v1(y,!0)});const g=[{stackItem:d[d.length-1],origin:a.origin,type:c?"redo":"undo",changedParentTypes:a.changedParentTypes},this];m?this.emit("stack-item-added",g):this.emit("stack-item-updated",g)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=Sc(e)?e:[e],e.forEach(r=>{n.has(r)||(n.add(r),(r instanceof dr?r.doc!==this.doc:r!==this.doc)&&NO("[yjs#509] Not same Y.Doc"),this.scope.push(r))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,n=!0){(e&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(r=>{e&&(this.undoStack.forEach(i=>hN(r,this,i)),this.undoStack=[]),n&&(this.redoStack.forEach(i=>hN(r,this,i)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=pN(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=pN(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}function*UY(t){const e=Lt(t.restDecoder);for(let n=0;nvm(t,OO,uf),VY=(t,e)=>{if(t.constructor===Ti){const{client:n,clock:r}=t.id;return new Ti(Ut(n,r+e),t.length-e)}else if(t.constructor===Ai){const{client:n,clock:r}=t.id;return new Ai(Ut(n,r+e),t.length-e)}else{const n=t,{client:r,clock:i}=n.id;return new cn(Ut(r,i+e),null,Ut(r,i+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},vm=(t,e=Tc,n=sa)=>{if(t.length===1)return t[0];const r=t.map(u=>new e(xl(u)));let i=r.map(u=>new d1(u,!0)),s=null;const o=new n,l=new f1(o);for(;i=i.filter(f=>f.curr!==null),i.sort((f,p)=>{if(f.curr.id.client===p.curr.id.client){const m=f.curr.id.clock-p.curr.id.clock;return m===0?f.curr.constructor===p.curr.constructor?0:f.curr.constructor===Ai?1:-1:m}else return p.curr.id.client-f.curr.id.client}),i.length!==0;){const u=i[0],d=u.curr.id.client;if(s!==null){let f=u.curr,p=!1;for(;f!==null&&f.id.clock+f.length<=s.struct.id.clock+s.struct.length&&f.id.client>=s.struct.id.client;)f=u.next(),p=!0;if(f===null||f.id.client!==d||p&&f.id.clock>s.struct.id.clock+s.struct.length)continue;if(d!==s.struct.id.client)_o(l,s.struct,s.offset),s={struct:f,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Ai?s.struct.length-=m:f=VY(f,m)),s.struct.mergeWith(f)||(_o(l,s.struct,s.offset),s={struct:f,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let f=u.curr;f!==null&&f.id.client===d&&f.id.clock===s.struct.id.clock+s.struct.length&&f.constructor!==Ai;f=u.next())_o(l,s.struct,s.offset),s={struct:f,offset:0}}s!==null&&(_o(l,s.struct,s.offset),s=null),h1(l);const a=r.map(u=>a1(u)),c=vw(a);return Bc(o,c),o.toUint8Array()},WY=(t,e,n=Tc,r=sa)=>{const i=LO(e),s=new r,o=new f1(s),l=new n(xl(t)),a=new d1(l,!1);for(;a.curr;){const u=a.curr,d=u.id.client,f=i.get(d)||0;if(a.curr.constructor===Ai){a.next();continue}if(u.id.clock+u.length>f)for(_o(o,u,ho(f-u.id.clock,0)),a.next();a.curr&&a.curr.id.client===d;)_o(o,a.curr,0),a.next();else for(;a.curr&&a.curr.id.client===d&&a.curr.id.clock+a.curr.length<=f;)a.next()}h1(o);const c=a1(l);return Bc(s,c),s.toUint8Array()},WO=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Nn(t.encoder.restEncoder)}),t.encoder.restEncoder=gr(),t.written=0)},_o=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&WO(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),vt(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},h1=t=>{WO(t);const e=t.encoder.restEncoder;vt(e,t.clientStructs.length);for(let n=0;n{const i=new n(xl(t)),s=new d1(i,!1),o=new r,l=new f1(o);for(let c=s.curr;c!==null;c=s.next())_o(l,e(c),0);h1(l);const a=a1(i);return Bc(o,a),o.toUint8Array()},YY=t=>KY(t,aK,Tc,uf),mN="You must not compute changes after the event-handler fired.";class Rg{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=qY(this.currentTarget,this.target))}deletes(e){return $c(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Rs(mN);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,l;if(this.adds(s)){let a=s.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(s))if(a!==null&&this.deletes(a))o="delete",l=rv(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",l=rv(a.content.getContent())):(o="add",l=void 0)}else if(this.deletes(s))o="delete",l=rv(s.content.getContent());else return;e.set(i,{action:o,oldValue:l})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Rs(mN);const n=this.target,r=uo(),i=uo(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const a=()=>{l&&s.push(l)};for(let c=n._start;c!==null;c=c.right)c.deleted?this.deletes(c)&&!this.adds(c)&&((l===null||l.delete===void 0)&&(a(),l={delete:0}),l.delete+=c.length,i.add(c)):this.adds(c)?((l===null||l.insert===void 0)&&(a(),l={insert:[]}),l.insert=l.insert.concat(c.content.getContent()),r.add(c)):((l===null||l.retain===void 0)&&(a(),l={retain:0}),l.retain+=c.length);l!==null&&l.retain===void 0&&a()}this._changes=e}return e}}const qY=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}e=e._item.parent}return n},Ir=()=>{NO("Invalid access: Add Yjs type to a document before reading data.")},KO=80;let p1=0;class JY{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=p1++}}const GY=t=>{t.timestamp=p1++},YO=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=p1++},XY=(t,e,n)=>{if(t.length>=KO){const r=t.reduce((i,s)=>i.timestamp{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((s,o)=>Rh(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Rh(n.index-i){for(let r=t.length-1;r>=0;r--){const i=t[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){t.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=ho(e,i.index+n))}},Og=(t,e,n)=>{const r=t,i=e.changedParentTypes;for(;as(i,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;zO(r._eH,n,e)};class dr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=lN(),this._dEH=lN(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw Oi()}clone(){throw Oi()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){aN(this._eH,e)}observeDeep(e){aN(this._dEH,e)}unobserve(e){cN(this._eH,e)}unobserveDeep(e){cN(this._dEH,e)}toJSON(){}}const qO=(t,e,n)=>{t.doc??Ir(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let r=n-e;const i=[];let s=t._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let l=e;l0;l++)i.push(o[l]),r--;e=0}}s=s.right}return i},JO=t=>{t.doc??Ir();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{const n=[];let r=t._start;for(;r!==null;){if(r.countable&&Tl(r,e)){const i=r.content.getContent();for(let s=0;s{let n=0,r=t._start;for(t.doc??Ir();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return Pd(t,(r,i)=>{n.push(e(r,i,t))}),n},QY=t=>{let e=t._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),r=0,e=e.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},QO=(t,e)=>{t.doc??Ir();const n=Dg(t,e);let r=t._start;for(n!==null&&(r=n.p,e-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=n;const s=t.doc,o=s.clientID,l=s.store,a=n===null?e._start:n.right;let c=[];const u=()=>{c.length>0&&(i=new cn(Ut(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new la(c)),i.integrate(t,0),c=[])};r.forEach(d=>{if(d===null)c.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:c.push(d);break;default:switch(u(),d.constructor){case Uint8Array:case ArrayBuffer:i=new cn(Ut(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new ff(new Uint8Array(d))),i.integrate(t,0);break;case Fi:i=new cn(Ut(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new hf(d)),i.integrate(t,0);break;default:if(d instanceof dr)i=new cn(Ut(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new cs(d)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ZO=()=>Rs("Length exceeded!"),ej=(t,e,n,r)=>{if(n>e._length)throw ZO();if(n===0)return e._searchMarker&&jd(e._searchMarker,n,r.length),wm(t,e,null,r);const i=n,s=Dg(e,n);let o=e._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return wm(t,e,i,n)},tj=(t,e,n,r)=>{if(r===0)return;const i=n,s=r,o=Dg(e,n);let l=e._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(r0)throw ZO();e._searchMarker&&jd(e._searchMarker,i,-s+r)},bm=(t,e,n)=>{const r=e._map.get(n);r!==void 0&&r.delete(t)},m1=(t,e,n,r)=>{const i=e._map.get(n)||null,s=t.doc,o=s.clientID;let l;if(r==null)l=new la([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new la([r]);break;case Uint8Array:l=new ff(r);break;case Fi:l=new hf(r);break;default:if(r instanceof dr)l=new cs(r);else throw new Error("Unexpected content type")}new cn(Ut(o,Fn(s.store,o)),i,i&&i.lastId,null,null,e,n,l).integrate(t,0)},g1=(t,e)=>{t.doc??Ir();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},nj=t=>{const e={};return t.doc??Ir(),t._map.forEach((n,r)=>{n.deleted||(e[r]=n.content.getContent()[n.length-1])}),e},rj=(t,e)=>{t.doc??Ir();const n=t._map.get(e);return n!==void 0&&!n.deleted},eq=(t,e)=>{const n={};return t._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&Tl(s,e)&&(n[i]=s.content.getContent()[s.length-1])}),n},oh=t=>(t.doc??Ir(),mY(t._map.entries(),e=>!e[1].deleted));class tq extends Rg{}class nc extends dr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new nc;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new nc}clone(){const e=new nc;return e.insert(0,this.toArray().map(n=>n instanceof dr?n.clone():n)),e}get length(){return this.doc??Ir(),this._length}_callObserver(e,n){super._callObserver(e,n),Og(this,e,new tq(this,e))}insert(e,n){this.doc!==null?yn(this.doc,r=>{ej(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?yn(this.doc,n=>{ZY(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?yn(this.doc,r=>{tj(r,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return QO(this,e)}toArray(){return JO(this)}slice(e=0,n=this.length){return qO(this,e,n)}toJSON(){return this.map(e=>e instanceof dr?e.toJSON():e)}map(e){return XO(this,e)}forEach(e){Pd(this,e)}[Symbol.iterator](){return QY(this)}_write(e){e.writeTypeRef(Nq)}}const nq=t=>new nc;class rq extends Rg{constructor(e,n,r){super(e,n),this.keysChanged=r}}class xs extends dr{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new xs}clone(){const e=new xs;return this.forEach((n,r)=>{e.set(r,n instanceof dr?n.clone():n)}),e}_callObserver(e,n){Og(this,e,new rq(this,e,n))}toJSON(){this.doc??Ir();const e={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];e[r]=i instanceof dr?i.toJSON():i}}),e}get size(){return[...oh(this)].length}keys(){return uv(oh(this),e=>e[0])}values(){return uv(oh(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return uv(oh(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ir(),this._map.forEach((n,r)=>{n.deleted||e(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?yn(this.doc,n=>{bm(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?yn(this.doc,r=>{m1(r,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return g1(this,e)}has(e){return rj(this,e)}clear(){this.doc!==null?yn(this.doc,e=>{this.forEach(function(n,r,i){bm(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Tq)}}const iq=t=>new xs,Ho=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&oK(t,e);class xw{constructor(e,n,r,i){this.left=e,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Dr(),this.right.content.constructor){case qn:this.right.deleted||Uc(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const gN=(t,e,n)=>{for(;e.right!==null&&n>0;){switch(e.right.content.constructor){case qn:e.right.deleted||Uc(e.currentAttributes,e.right.content);break;default:e.right.deleted||(n{const i=new Map,s=r?Dg(e,n):null;if(s){const o=new xw(s.p.left,s.p,s.index,i);return gN(t,o,n-s.index)}else{const o=new xw(null,e._start,0,i);return gN(t,o,n)}},ij=(t,e,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===qn&&Ho(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=t.doc,s=i.clientID;r.forEach((o,l)=>{const a=n.left,c=n.right,u=new cn(Ut(s,Fn(i.store,s)),a,a&&a.lastId,c,c&&c.id,e,null,new qn(l,o));u.integrate(t,0),n.right=u,n.forward()})},Uc=(t,e)=>{const{key:n,value:r}=e;r===null?t.delete(n):t.set(n,r)},sj=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===qn&&Ho(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},oj=(t,e,n,r)=>{const i=t.doc,s=i.clientID,o=new Map;for(const l in r){const a=r[l],c=n.currentAttributes.get(l)??null;if(!Ho(c,a)){o.set(l,c);const{left:u,right:d}=n;n.right=new cn(Ut(s,Fn(i.store,s)),u,u&&u.lastId,d,d&&d.id,e,null,new qn(l,a)),n.right.integrate(t,0),n.forward()}}return o},hv=(t,e,n,r,i)=>{n.currentAttributes.forEach((f,p)=>{i[p]===void 0&&(i[p]=null)});const s=t.doc,o=s.clientID;sj(n,i);const l=oj(t,e,n,i),a=r.constructor===String?new ls(r):r instanceof dr?new cs(r):new ha(r);let{left:c,right:u,index:d}=n;e._searchMarker&&jd(e._searchMarker,n.index,a.getLength()),u=new cn(Ut(o,Fn(s.store,o)),c,c&&c.lastId,u,u&&u.id,e,null,a),u.integrate(t,0),n.right=u,n.index=d,n.forward(),ij(t,e,n,l)},yN=(t,e,n,r,i)=>{const s=t.doc,o=s.clientID;sj(n,i);const l=oj(t,e,n,i);e:for(;n.right!==null&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===qn));){if(!n.right.deleted)switch(n.right.content.constructor){case qn:{const{key:a,value:c}=n.right.content,u=i[a];if(u!==void 0){if(Ho(u,c))l.delete(a);else{if(r===0)break e;l.set(a,c)}n.right.delete(t)}else n.currentAttributes.set(a,c);break}default:r0){let a="";for(;r>0;r--)a+=` -`;n.right=new cn(Ut(o,Fn(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new ls(a)),n.right.integrate(t,0),n.forward()}ij(t,e,n,l)},lj=(t,e,n,r,i)=>{let s=e;const o=si();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===qn){const c=s.content;o.set(c.key,c)}s=s.right}let l=0,a=!1;for(;e!==s;){if(n===e&&(a=!0),!e.deleted){const c=e.content;switch(c.constructor){case qn:{const{key:u,value:d}=c,f=r.get(u)??null;(o.get(u)!==c||f===d)&&(e.delete(t),l++,!a&&(i.get(u)??null)===d&&f!==d&&(f===null?i.delete(u):i.set(u,f))),!a&&!e.deleted&&Uc(i,c);break}}}e=e.right}return l},sq=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===qn){const r=e.content.key;n.has(r)?e.delete(t):n.add(r)}e=e.left}},oq=t=>{let e=0;return yn(t.doc,n=>{let r=t._start,i=t._start,s=si();const o=fw(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case qn:Uc(o,i.content);break;default:e+=lj(n,r,i,s,o),s=fw(o),r=i;break}i=i.right}}),e},lq=t=>{const e=new Set,n=t.doc;for(const[r,i]of t.afterState.entries()){const s=t.beforeState.get(r)||0;i!==s&&UO(t,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===qn&&o.constructor!==Ti&&e.add(o.parent)})}yn(n,r=>{hl(t,t.deleteSet,i=>{if(i instanceof Ti||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===qn?e.add(s):sq(r,i)});for(const i of e)oq(i)})},vN=(t,e,n)=>{const r=n,i=fw(e.currentAttributes),s=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case cs:case ha:case ls:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];yn(e,r=>{const i=new Map,s=new Map;let o=this.target._start,l=null;const a={};let c="",u=0,d=0;const f=()=>{if(l!==null){let p=null;switch(l){case"delete":d>0&&(p={delete:d}),d=0;break;case"insert":(typeof c=="object"||c.length>0)&&(p={insert:c},i.size>0&&(p.attributes={},i.forEach((m,g)=>{m!==null&&(p.attributes[g]=m)}))),c="";break;case"retain":u>0&&(p={retain:u},sK(a)||(p.attributes=nK({},a))),u=0;break}p&&n.push(p),l=null}};for(;o!==null;){switch(o.content.constructor){case cs:case ha:this.adds(o)?this.deletes(o)||(f(),l="insert",c=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),d+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=1);break;case ls:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),c+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),d+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=o.length);break;case qn:{const{key:p,value:m}=o.content;if(this.adds(o)){if(!this.deletes(o)){const g=i.get(p)??null;Ho(g,m)?m!==null&&o.delete(r):(l==="retain"&&f(),Ho(m,s.get(p)??null)?delete a[p]:a[p]=m)}}else if(this.deletes(o)){s.set(p,m);const g=i.get(p)??null;Ho(g,m)||(l==="retain"&&f(),a[p]=g)}else if(!o.deleted){s.set(p,m);const g=a[p];g!==void 0&&(Ho(g,m)?g!==null&&o.delete(r):(l==="retain"&&f(),m===null?delete a[p]:a[p]=m))}o.deleted||(l==="insert"&&f(),Uc(i,o.content));break}}o=o.right}for(f();n.length>0;){const p=n[n.length-1];if(p.retain!==void 0&&p.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class pl extends dr{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ir(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new pl}clone(){const e=new pl;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const r=new aq(this,e,n);Og(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ir();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===ls&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?yn(this.doc,r=>{const i=new xw(null,this._start,0,new Map);for(let s=0;s0)&&hv(r,this,i,l,o.attributes||{})}else o.retain!==void 0?yN(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&vN(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,r){this.doc??Ir();const i=[],s=new Map,o=this.doc;let l="",a=this._start;function c(){if(l.length>0){const d={};let f=!1;s.forEach((m,g)=>{f=!0,d[g]=m});const p={insert:l};f&&(p.attributes=d),i.push(p),l=""}}const u=()=>{for(;a!==null;){if(Tl(a,e)||n!==void 0&&Tl(a,n))switch(a.content.constructor){case ls:{const d=s.get("ychange");e!==void 0&&!Tl(a,e)?(d===void 0||d.user!==a.id.client||d.type!=="removed")&&(c(),s.set("ychange",r?r("removed",a.id):{type:"removed"})):n!==void 0&&!Tl(a,n)?(d===void 0||d.user!==a.id.client||d.type!=="added")&&(c(),s.set("ychange",r?r("added",a.id):{type:"added"})):d!==void 0&&(c(),s.delete("ychange")),l+=a.content.str;break}case cs:case ha:{c();const d={insert:a.content.getContent()[0]};if(s.size>0){const f={};d.attributes=f,s.forEach((p,m)=>{f[m]=p})}i.push(d);break}case qn:Tl(a,e)&&(c(),Uc(s,a.content));break}a=a.right}c()};return e||n?yn(o,d=>{e&&ww(d,e),n&&ww(d,n),u()},"cleanup"):u(),i}insert(e,n,r){if(n.length<=0)return;const i=this.doc;i!==null?yn(i,s=>{const o=lh(s,this,e,!r);r||(r={},o.currentAttributes.forEach((l,a)=>{r[a]=l})),hv(s,this,o,n,r)}):this._pending.push(()=>this.insert(e,n,r))}insertEmbed(e,n,r){const i=this.doc;i!==null?yn(i,s=>{const o=lh(s,this,e,!r);hv(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(e,n,r||{}))}delete(e,n){if(n===0)return;const r=this.doc;r!==null?yn(r,i=>{vN(i,lh(i,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,r){if(n===0)return;const i=this.doc;i!==null?yn(i,s=>{const o=lh(s,this,e,!1);o.right!==null&&yN(s,this,o,n,r)}):this._pending.push(()=>this.format(e,n,r))}removeAttribute(e){this.doc!==null?yn(this.doc,n=>{bm(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?yn(this.doc,r=>{m1(r,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return g1(this,e)}getAttributes(){return nj(this)}_write(e){e.writeTypeRef(Aq)}}const cq=t=>new pl;class pv{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ir()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===Mr||n.constructor===oa)&&n._start!==null)e=n._start;else for(;e!==null;){const r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class oa extends dr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new oa}clone(){const e=new oa;return e.insert(0,this.toArray().map(n=>n instanceof dr?n.clone():n)),e}get length(){return this.doc??Ir(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new pv(this,e)}querySelector(e){e=e.toUpperCase();const r=new pv(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),fo(new pv(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Og(this,e,new fq(this,n,e))}toString(){return XO(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Pd(this,s=>{i.insertBefore(s.toDOM(e,n,r),null)}),i}insert(e,n){this.doc!==null?yn(this.doc,r=>{ej(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)yn(this.doc,r=>{const i=e&&e instanceof dr?e._item:e;wm(r,this,i,n)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Rs("Reference item not found");r.splice(i,0,...n)}}delete(e,n=1){this.doc!==null?yn(this.doc,r=>{tj(r,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return JO(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return QO(this,e)}slice(e=0,n=this.length){return qO(this,e,n)}forEach(e){Pd(this,e)}_write(e){e.writeTypeRef(Iq)}}const uq=t=>new oa;class Mr extends oa{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Mr(this.nodeName)}clone(){const e=new Mr(this.nodeName),n=this.getAttributes();return rK(n,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof dr?r.clone():r)),e}toString(){const e=this.getAttributes(),n=[],r=[];for(const l in e)r.push(l);r.sort();const i=r.length;for(let l=0;l0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?yn(this.doc,n=>{bm(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?yn(this.doc,r=>{m1(r,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return g1(this,e)}hasAttribute(e){return rj(this,e)}getAttributes(e){return e?eq(this,e):nj(this)}toDOM(e=document,n={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const l=s[o];typeof l=="string"&&i.setAttribute(o,l)}return Pd(this,o=>{i.appendChild(o.toDOM(e,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Mq),e.writeKey(this.nodeName)}}const dq=t=>new Mr(t.readKey());class fq extends Rg{constructor(e,n,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class xm extends xs{constructor(e){super(),this.hookName=e}_copy(){return new xm(this.hookName)}clone(){const e=new xm(this.hookName);return this.forEach((n,r)=>{e.set(r,n)}),e}toDOM(e=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(Rq),e.writeKey(this.hookName)}}const hq=t=>new xm(t.readKey());class oi extends pl{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new oi}clone(){const e=new oi;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const n=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,l)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Dq)}}const pq=t=>new oi;class y1{constructor(e,n){this.id=e,this.length=n}get deleted(){throw Oi()}mergeWith(e){return!1}write(e,n,r){throw Oi()}integrate(e,n){throw Oi()}}const mq=0;class Ti extends y1{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),BO(e.doc.store,this)}write(e,n){e.writeInfo(mq),e.writeLen(this.length-n)}getMissing(e,n){return null}}class ff{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ff(this.content)}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const gq=t=>new ff(t.readBuf());class Ld{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ld(this.len)}splice(e){const n=new Ld(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){Rd(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const yq=t=>new Ld(t.readLen()),aj=(t,e)=>new Fi({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class hf{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hf(aj(this.doc.guid,this.opts))}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const vq=t=>new hf(aj(t.readString(),t.readAny()));class ha{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ha(this.embed)}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const wq=t=>new ha(t.readJSON());class qn{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new qn(this.key,this.value)}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const bq=t=>new qn(t.readKey(),t.readJSON());class km{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new km(this.arr)}splice(e){const n=new km(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const r=this.arr.length;e.writeLen(r-n);for(let i=n;i{const e=t.readLen(),n=[];for(let r=0;r{const e=t.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Cq=t=>new ls(t.readString()),Eq=[nq,iq,cq,dq,uq,hq,pq],Nq=0,Tq=1,Aq=2,Mq=3,Iq=4,Rq=5,Dq=6;class cs{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new cs(this.type._copy())}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const Oq=t=>new cs(Eq[t.readTypeRef()](t)),kw=(t,e)=>{let n=e,r=0,i;do r>0&&(n=Ut(n.client,n.clock+r)),i=tc(t,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof cn);return{item:i,diff:r}},v1=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},Sm=(t,e,n)=>{const{client:r,clock:i}=e.id,s=new cn(Ut(r,i+n),e,Ut(r,i+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=Ut(e.redone.client,e.redone.clock+n)),e.right=s,s.right!==null&&(s.right.left=s),t._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=n,s},wN=(t,e)=>Wx(t,n=>$c(n.deletions,e)),cj=(t,e,n,r,i,s)=>{const o=t.doc,l=o.store,a=o.clientID,c=e.redone;if(c!==null)return Qr(t,c);let u=e.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||cj(t,u,n,r,i,s)===null))return null;for(;u.redone!==null;)u=Qr(t,u.redone)}const p=u===null?e.parent:u.content.type;if(e.parentSub===null){for(d=e.left,f=e;d!==null;){let v=d;for(;v!==null&&v.parent._item!==u;)v=v.redone===null?null:Qr(t,v.redone);if(v!==null&&v.parent._item===u){d=v;break}d=d.left}for(;f!==null;){let v=f;for(;v!==null&&v.parent._item!==u;)v=v.redone===null?null:Qr(t,v.redone);if(v!==null&&v.parent._item===u){f=v;break}f=f.right}}else if(f=null,e.right&&!i){for(d=e;d!==null&&d.right!==null&&(d.right.redone||$c(r,d.right.id)||wN(s.undoStack,d.right.id)||wN(s.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Qr(t,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(e.parentSub)||null;const m=Fn(l,a),g=Ut(a,m),y=new cn(g,d,d&&d.lastId,f,f&&f.id,p,e.parentSub,e.content.copy());return e.redone=g,v1(y,!0),y.integrate(t,0),y};class cn extends y1{constructor(e,n,r,i,s,o,l,a){super(e,a.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=l,this.redone=null,this.content=a,this.info=this.content.isCountable()?qE:0}set marker(e){(this.info&sv)>0!==e&&(this.info^=sv)}get marker(){return(this.info&sv)>0}get keep(){return(this.info&YE)>0}set keep(e){this.keep!==e&&(this.info^=YE)}get countable(){return(this.info&qE)>0}get deleted(){return(this.info&iv)>0}set deleted(e){this.deleted!==e&&(this.info^=iv)}markDeleted(){this.info|=iv}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Fn(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Fn(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ec&&this.id.client!==this.parent.client&&this.parent.clock>=Fn(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=uN(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Qr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ti||this.right&&this.right.constructor===Ti)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===cn?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===cn&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ec){const r=tc(n,this.parent);r.constructor===Ti?this.parent=null:this.parent=r.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=uN(e,e.doc.store,Ut(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),ih(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Rd(e.deleteSet,this.id.client,this.id.clock,this.length),fN(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw Dr();this.content.gc(e),n?_Y(e,this,new Ti(this.id,this.length)):this.content=new Ld(this.length)}write(e,n){const r=n>0?Ut(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Sg|(r===null?0:Br)|(i===null?0:to)|(s===null?0:Nd);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const l=this.parent;if(l._item!==void 0){const a=l._item;if(a===null){const c=Dd(l);e.writeParentInfo(!0),e.writeString(c)}else e.writeParentInfo(!1),e.writeLeftID(a.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===ec?(e.writeParentInfo(!1),e.writeLeftID(l)):Dr();s!==null&&e.writeString(s)}this.content.write(e,n)}}const uj=(t,e)=>jq[e&Sg](t),jq=[()=>{Dr()},yq,xq,gq,Cq,wq,bq,Oq,Sq,vq,()=>{Dr()}],Pq=10;class Ai extends y1{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){Dr()}write(e,n){e.writeInfo(Pq),vt(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const dj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},fj="__ $YJS$ __";dj[fj]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");dj[fj]=!0;const hj=new Map;class Lq{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:bK(n.newValue||"")}),Z9(this._onChange)}postMessage(e){XD.setItem(this.room,iO(mK(e)))}close(){eK(this._onChange)}}const _q=typeof BroadcastChannel>"u"?Lq:BroadcastChannel,w1=t=>as(hj,t,()=>{const e=uo(),n=new _q(t);return n.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:n,subs:e}}),zq=(t,e)=>(w1(t).subs.add(e),e),Fq=(t,e)=>{const n=w1(t),r=n.subs.delete(e);return r&&n.subs.size===0&&(n.bc.close(),hj.delete(t)),r},Na=(t,e,n=null)=>{const r=w1(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,n))},pj=0,b1=1,mj=2,Sw=(t,e)=>{vt(t,pj);const n=IY(e);Ln(t,n)},gj=(t,e,n)=>{vt(t,b1),Ln(t,NY(e,n))},$q=(t,e,n)=>gj(e,n,Tr(t)),yj=(t,e,n,r)=>{try{SY(e,Tr(t),n)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},Bq=(t,e)=>{vt(t,mj),Ln(t,e)},Uq=yj,Hq=(t,e,n,r,i)=>{const s=Lt(t);switch(s){case pj:$q(t,e,n);break;case b1:yj(t,n,r,i);break;case mj:Uq(t,n,r,i);break;default:throw new Error("Unknown message type")}return s},Vq=0,Wq=(t,e,n)=>{switch(Lt(t)){case Vq:n(e,nl(t))}},mv=3e4;class Kq extends VD{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=dl();this.getLocalState()!==null&&mv/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,s)=>{s!==this.clientID&&mv<=n-i.lastUpdated&&this.states.has(s)&&r.push(s)}),r.length>0&&x1(this,r,"timeout")},zi(mv/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const n=this.clientID,r=this.meta.get(n),i=r===void 0?0:r.clock+1,s=this.states.get(n);e===null?this.states.delete(n):this.states.set(n,e),this.meta.set(n,{clock:i,lastUpdated:dl()});const o=[],l=[],a=[],c=[];e===null?c.push(n):s==null?e!=null&&o.push(n):(l.push(n),Qa(s,e)||a.push(n)),(o.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:o,updated:a,removed:c},"local"]),this.emit("update",[{added:o,updated:l,removed:c},"local"])}setLocalStateField(e,n){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:n})}getStates(){return this.states}}const x1=(t,e,n)=>{const r=[];for(let i=0;i0&&(t.emit("change",[{added:[],updated:[],removed:r},n]),t.emit("update",[{added:[],updated:[],removed:r},n]))},Wu=(t,e,n=t.states)=>{const r=e.length,i=gr();vt(i,r);for(let s=0;s{const r=xl(e),i=dl(),s=[],o=[],l=[],a=[],c=Lt(r);for(let u=0;u0||l.length>0||a.length>0)&&t.emit("change",[{added:s,updated:l,removed:a},n]),(s.length>0||o.length>0||a.length>0)&&t.emit("update",[{added:s,updated:o,removed:a},n])},qq=t=>iK(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),Pl=0,vj=3,rc=1,Jq=2,pf=[];pf[Pl]=(t,e,n,r,i)=>{vt(t,Pl);const s=Hq(e,t,n.doc,n);r&&s===b1&&!n.synced&&(n.synced=!0)};pf[vj]=(t,e,n,r,i)=>{vt(t,rc),Ln(t,Wu(n.awareness,Array.from(n.awareness.getStates().keys())))};pf[rc]=(t,e,n,r,i)=>{Yq(n.awareness,Tr(e),n)};pf[Jq]=(t,e,n,r,i)=>{Wq(e,n.doc,(s,o)=>Gq(n,o))};const bN=3e4,Gq=(t,e)=>console.warn(`Permission denied to access ${t.url}. -${e}`),wj=(t,e,n)=>{const r=xl(e),i=gr(),s=Lt(r),o=t.messageHandlers[s];return o?o(i,r,t,n,s):console.error("Unable to compute message"),i},bj=t=>{if(t.shouldConnect&&t.ws===null){const e=new t._WS(t.url);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=n=>{t.wsLastMessageReceived=dl();const r=wj(t,new Uint8Array(n.data),!0);Kx(r)>1&&e.send(Nn(r))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{t.emit("connection-close",[n,t]),t.ws=null,t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,x1(t.awareness,Array.from(t.awareness.getStates().keys()).filter(r=>r!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(bj,ia(g9(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t)},e.onopen=()=>{t.wsLastMessageReceived=dl(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=gr();if(vt(n,Pl),Sw(n,t.doc),e.send(Nn(n)),t.awareness.getLocalState()!==null){const r=gr();vt(r,rc),Ln(r,Wu(t.awareness,[t.doc.clientID])),e.send(Nn(r))}},t.emit("status",[{status:"connecting"}])}},gv=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Na(t.bcChannel,e,t)};class mf extends VD{constructor(e,n,r,{connect:i=!0,awareness:s=new Kq(r),params:o={},WebSocketPolyfill:l=WebSocket,resyncInterval:a=-1,maxBackoffTime:c=2500,disableBc:u=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);const d=qq(o);this.maxBackoffTime=c,this.bcChannel=e+"/"+n,this.url=e+"/"+n+(d.length===0?"":"?"+d),this.roomname=n,this.doc=r,this._WS=l,this.awareness=s,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=pf.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=i,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=gr();vt(f,Pl),Sw(f,r),this.ws.send(Nn(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const m=wj(this,new Uint8Array(f),!1);Kx(m)>1&&Na(this.bcChannel,Nn(m),this)}},this._updateHandler=(f,p)=>{if(p!==this){const m=gr();vt(m,Pl),Bq(m,f),gv(this,Nn(m))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:m},g)=>{const y=f.concat(p).concat(m),v=gr();vt(v,rc),Ln(v,Wu(s,y)),gv(this,Nn(v))},this._exitHandler=()=>{x1(this.awareness,[r.clientID],"app closed")},fl&&typeof process<"u"&&process.on("exit",this._exitHandler),s.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&bN{try{return`ce-${(t==null?void 0:t.id)||"x"}-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`ce-${Math.random()}`}})());b.useEffect(()=>{window.dispatchEvent(new Event("freemannotes:editor-modal-open"));try{const A=c.current,ne=()=>{try{e()}catch{}};window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:A,onBack:ne}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:c.current}}))}catch{}window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}},[]);const u=b.useRef((()=>{try{return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`c${Math.random()}`}})()),d=b.useRef(null),[,f]=b.useState(0),p=b.useRef(!1),m=b.useRef(!1);B.useEffect(()=>{m.current=!1;const A=window.setTimeout(()=>{m.current=!0},160);return()=>window.clearTimeout(A)},[]);const[g,y]=b.useState(()=>(t.items||[]).map((A,ne)=>{const we=typeof(A==null?void 0:A.uid)=="string"&&A.uid?String(A.uid):typeof(A==null?void 0:A.id)=="number"?`id-${Number(A.id)}`:`init-${ne}-${Math.random().toString(36).slice(2,8)}`;return{indent:0,uid:we,key:we,...A}})),[v,w]=b.useState(!1),[x,E]=b.useState(!0),[k,M]=b.useState(null),[N,z]=b.useState(null),X=b.useRef([]),[L,H]=b.useState(null),[W,te]=b.useState(null),[ce,ue]=b.useState(t.title||""),[Ae,me]=b.useState(r??(t.viewerColor||t.color||"")),[q,se]=b.useState(!1),[xe,Me]=b.useState(!1),[Q,Je]=b.useState(!1),[_t,J]=b.useState(!1),[at,$t]=b.useState((t.images||[]).map(A=>({id:Number(A.id),url:String(A.url)}))),[ct,nt]=b.useState(!1);B.useEffect(()=>{try{const A=(t.images||[]).map(ne=>({id:Number(ne.id),url:String(ne.url)}));$t(ne=>{try{if(ne.length===A.length&&ne.every((we,Z)=>{var Ie,Ve;return Number(we.id)===Number((Ie=A[Z])==null?void 0:Ie.id)&&String(we.url)===String((Ve=A[Z])==null?void 0:Ve.url)}))return ne}catch{}return A})}catch{}},[t.images]);const[At,Vt]=b.useState(null),[wt,ae]=b.useState([]),Ee=b.useRef([]),[Ke,ze]=b.useState(!1),Pe=b.useRef(null);function it(){var we;let A=d.current;if(A&&A.isFocused)return A;const ne=typeof document<"u"&&((we=document.getSelection())==null?void 0:we.anchorNode)||null;if(ne){const Z=Ee.current.find(Ie=>{var Ve;try{return!!(Ie&&((Ve=Ie.view)!=null&&Ve.dom)&&Ie.view.dom.contains(ne))}catch{return!1}});Z&&(A=Z)}else{const Z=typeof document<"u"?document.activeElement:null;if(Z){const Ie=Ee.current.find(Ve=>{try{return!!(Ve&&Ve.view&&Ve.view.dom&&(Ve.view.dom===Z||Ve.view.dom.contains(Z)))}catch{return!1}});Ie&&(A=Ie)}}if(!A||!(A!=null&&A.isFocused)){const Z=Ee.current.find(Ie=>!!(Ie&&Ie.isFocused));Z&&(A=Z)}return A||null}function ot(A){var Rt;const ne=it();if(!ne)return;const we=(Rt=ne.state)==null?void 0:Rt.selection;if(!we)return;if(!we.empty){const be=ne.chain().focus();A==="bold"?be.toggleBold():A==="italic"?be.toggleItalic():be.toggleUnderline(),be.run();try{f(qe=>qe+1)}catch{}return}let Z=we.from,Ie=we.to;try{const be=we.$from;let qe=be.depth;for(;qe>0&&!be.node(qe).isBlock;)qe--;Z=be.start(qe),Ie=be.end(qe)}catch{}const Ve=ne.chain().focus().setTextSelection({from:Z,to:Ie});A==="bold"?Ve.toggleBold():A==="italic"?Ve.toggleItalic():Ve.toggleUnderline(),Ve.run();try{ne.chain().focus().setTextSelection(we.from).run()}catch{}try{const be=we.from;requestAnimationFrame(()=>{var qe,Dt;try{try{(Dt=(qe=ne.view)==null?void 0:qe.focus)==null||Dt.call(qe)}catch{}ne.chain().focus().setTextSelection(be).run()}catch{}})}catch{}try{f(be=>be+1)}catch{}}function xt(A){var st,ft;const ne=it();if(!ne)return!1;const we=(st=ne.state)==null?void 0:st.selection;if(!we)return!1;const Z=(((ft=ne.schema)==null?void 0:ft.marks)||{})[A];if(!Z)return!1;const Ie=we.$from;let Ve=Ie.depth;for(;Ve>0&&!Ie.node(Ve).isBlock;)Ve--;const Rt=Ie.start(Ve),be=Ie.end(Ve);let qe=!1,Dt=!0;try{ne.state.doc.nodesBetween(Rt,be,yt=>{yt&&yt.isText&&(qe=!0,Z.isInSet(yt.marks)||(Dt=!1))})}catch{}return qe&&Dt}const oe=B.useMemo(()=>new Fi,[t.id]),Ye=B.useRef(null),Ge=B.useRef(null),K=B.useRef(null),ge=B.useRef(null),De=B.useRef(!1),Be=B.useRef(!1),Le=B.useCallback(()=>{if(!Be.current){Be.current=!0;try{window.dispatchEvent(new CustomEvent("freemannotes:draft/dirty",{detail:{noteId:Number(t==null?void 0:t.id)}}))}catch{}}},[t==null?void 0:t.id]),j=b.useRef(null),G=b.useRef(null),de=b.useRef(void 0),je=b.useRef({x:0,y:0}),Ue=b.useRef(null),We=b.useRef(!1),Se=b.useRef(0),Xe=b.useRef(null),Tt=b.useRef(null),rt=b.useRef(null),Wt=b.useRef(0),Mt=b.useRef({parentId:null,makeNested:!1}),dn=b.useRef(null),[It,Ot]=b.useState(null),tn=B.useMemo(()=>{try{return typeof window<"u"&&!!window.matchMedia&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}},[]),ee=B.useMemo(()=>{const A={hoverDownPct:.7,hoverUpPct:.7,indentPx:16,ghostOverlapPct:.7,ghostOverlapUpPct:.7,ghostOverlapDownPct:.7};return tn?{...A,hoverClearMs:0,directionLockPx:0}:{...A,hoverClearMs:80,directionLockPx:6}},[tn]),re=b.useRef(0),Oe=b.useRef(0),Ze=B.useCallback(()=>`u${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,[]),fe=B.useCallback(A=>typeof A.id=="number"?A.id:A.uid||`tmp-${Math.random().toString(36).slice(2,6)}`,[]);function Ce(){const A=document.querySelector(".image-dialog .dialog-body");return A||document.querySelector(".image-dialog")}function Fe(){We.current=!1,Ue.current!=null&&(cancelAnimationFrame(Ue.current),Ue.current=null)}function ut(){if(Ue.current!=null)return;We.current=!0;const A=()=>{if(!We.current){Ue.current=null;return}const ne=Ce();if(!ne){Ue.current=requestAnimationFrame(A);return}const we=ne.getBoundingClientRect(),Z=Se.current,Ie=Math.max(56,Math.min(96,we.height*.18)),Ve=14;let Rt=0;if(Zwe.bottom-Ie){const be=Math.max(0,Math.min(1,(Z-(we.bottom-Ie))/Ie));Rt=Math.max(1,Math.round(Math.pow(be,1.65)*Ve))}Rt!==0&&(ne.scrollTop=ne.scrollTop+Rt),Ue.current=requestAnimationFrame(A)};Ue.current=requestAnimationFrame(A)}b.useEffect(()=>{const A=`note-${t.id}`,we=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/collab`,Z=new mf(we,A,oe);Ye.current=Z;const Ie=oe.getArray("checklist");Ge.current=Ie;const Ve=oe.getMap("meta");K.current=Ve;const Rt=async()=>{try{const ft=await fetch(`/api/notes/${t.id}/images`,{headers:{Authorization:`Bearer ${l}`}});if(!ft.ok)return;const yt=await ft.json(),bt=(yt&&yt.images||[]).map(mt=>({id:Number(mt.id),url:String(mt.url)}));$t(bt),i&&i(bt)}catch{}},be=()=>{try{const ft=Ve.get("imagesTick");if(!ft||!ft.t||ft.by&&String(ft.by)===String(u.current))return;Rt()}catch{}};try{Ve.observe(be)}catch{}const qe={current:!1},Dt=ft=>{if(ft){De.current=!0;try{const yt=Ge.current;if(yt&&yt.length===0&&!qe.current){const bt=(t.items||[]).map(mt=>{const Qt=new xs;typeof mt.id=="number"&&Qt.set("id",mt.id);const dt=typeof(mt==null?void 0:mt.uid)=="string"&&mt.uid?String(mt.uid):typeof(mt==null?void 0:mt.id)=="number"?`id-${Number(mt.id)}`:`u${Math.random().toString(36).slice(2,8)}`;return Qt.set("uid",dt),Qt.set("content",String(mt.content||"")),Qt.set("checked",!!mt.checked),Qt.set("indent",Number(mt.indent||0)),Qt});bt.length&&yt.insert(0,bt),qe.current=!0}}catch{}}};Z.on("sync",Dt);const st=(ft,yt)=>{try{yt&&yt.local&&Le()}catch{}try{const bt=Ie.toArray().map((dt,on)=>({id:typeof dt.get("id")=="number"?Number(dt.get("id")):void 0,uid:dt.get("uid")?String(dt.get("uid")):void 0,content:String(dt.get("content")||""),checked:!!dt.get("checked"),indent:Number(dt.get("indent")||0),key:dt.get("uid")?String(dt.get("uid")):typeof dt.get("id")=="number"?Number(dt.get("id")):`i${on}`})),mt=!!(d.current&&d.current.isFocused);((()=>{try{if(bt.length!==g.length)return!0;for(let dt=0;dt{var dt;try{const on=bt.map((Ct,Pt)=>{const ln={content:Ct.content,checked:!!Ct.checked,ord:Pt,indent:Ct.indent||0};return typeof Ct.id=="number"&&(ln.id=Ct.id),ln}),Yt=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({items:on})});if(Yt.ok){const Ct=await Yt.json(),Pt=Array.isArray(Ct.items)?Ct.items:[],ln=Ge.current;if(ln&&Pt.length===ln.length)for(let wi=0;wi{try{Ie.unobserveDeep(st)}catch{}try{Z.off("sync",Dt)}catch{}try{Ve.unobserve(be)}catch{}try{Z.destroy()}catch{}}},[t.id,l,oe]);const zt=B.useCallback(()=>{try{const A=K.current;if(!A)return;A.set("imagesTick",{t:Date.now(),by:u.current})}catch{}},[]);b.useEffect(()=>{try{$t((t.images||[]).map(A=>({id:Number(A.id),url:String(A.url)})))}catch{}},[t.images]);function kt(A,ne){var Ve;const we=ne,Z=((Ve=A[ne])==null?void 0:Ve.indent)||0;let Ie=ne+1;for(;IeZ;)Ie++;return[we,Ie]}b.useEffect(()=>{X.current=X.current.slice(0,g.length)},[g.length]),b.useEffect(()=>{requestAnimationFrame(()=>{X.current.forEach(A=>{try{A.style.height="auto",A.style.height=Math.max(22,A.scrollHeight)+"px"}catch{}})})},[g,It]);function Jt(A,ne){if(rt.current!=="vertical"||k===null)return"";const[we,Z]=kt(ne,k);return N===null||A>=we&&AZ-1&&A<=N?"shift-up":"":k>N&&A>=N&&A=0&&AZ.map((Ie,Ve)=>Ve===A?{...Ie,content:ne}:Ie));requestAnimationFrame(()=>{const Z=X.current[A];if(Z)try{Z.style.height="auto",Z.style.height=Math.max(22,Z.scrollHeight)+"px"}catch{}})}function rn(A){const ne=Ge.current;if(ne){const we=typeof A=="number"?Math.max(0,Math.min(A,ne.length)):ne.length,Z=new xs;Z.set("content",""),Z.set("checked",!1),Z.set("indent",0),Z.set("uid",Ze()),ne.insert(we,[Z]),H(we)}else y(we=>{const Z=typeof A=="number"?Math.max(0,Math.min(A,we.length)):we.length,Ie=Ze(),Ve=[...we];return Ve.splice(Z,0,{uid:Ie,content:"",checked:!1,indent:0}),Ve}),H(typeof A=="number"?A:g.length+1)}function Pr(A){const ne=Ge.current;if(ne){const we=ne.get(A);if(!we)return;const Z=!we.get("checked");if(typeof we.get("id")=="number"&&we.set("id",we.get("id")),we.set("checked",Z),Number(we.get("indent")||0)===0)for(let Ve=A+1;Ve0)Rt.set("checked",Z);else break}}else y(we=>we.map((Z,Ie)=>{if(Ie===A){const Ve=!Z.checked,Rt=Number(Z.indent||0),be={...Z,checked:Ve};if(Rt===0){const qe=[...we];qe[Ie]=be;for(let Dt=Ie+1;Dt0;Dt++)qe[Dt]={...qe[Dt],checked:Ve};return qe[Ie]}return be}return Z}))}function R(A,ne,we){const Z=Ge.current;if(!Z)return;const Ie=Math.max(0,Math.min(A,Z.length)),Rt=Math.max(Ie,Math.min(ne,Z.length))-Ie;if(Rt<=0)return;let be=Math.max(0,Math.min(we,Z.length));be>Ie&&(be=be-Rt),be<0&&(be=0),be>Z.length&&(be=Z.length);const qe=[];for(let st=0;st{const ft=new xs;return typeof st.id=="number"&&ft.set("id",st.id),st.uid&&ft.set("uid",st.uid),ft.set("content",st.content),ft.set("checked",st.checked),ft.set("indent",st.indent),ft});Z.insert(be,Dt)}function U(){Fe(),G.current&&(G.current.remove(),G.current=null),de.current&&(document.removeEventListener("dragover",de.current),de.current=void 0),document.querySelectorAll(".checklist-item.drag-source").forEach(A=>A.classList.remove("drag-source")),M(null),z(null),Ot(null),j.current&&(cancelAnimationFrame(j.current),j.current=null),Xe.current&&(clearTimeout(Xe.current),Xe.current=null),Tt.current=null,rt.current=null,Mt.current={parentId:null,makeNested:!1};try{const A=document.querySelector(".image-dialog");A&&A.style.removeProperty("--checklist-item-shift")}catch{}}async function Y(){w(!0);try{if((t.title||"")!==ce){const Ie=await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({title:ce})});if(!Ie.ok)throw new Error(await Ie.text())}const A=Ge.current,we=(A?A.toArray().map(Ie=>({id:typeof Ie.get("id")=="number"?Number(Ie.get("id")):void 0,content:String(Ie.get("content")||""),checked:!!Ie.get("checked"),indent:Number(Ie.get("indent")||0)})):g).map((Ie,Ve)=>{const Rt={content:Ie.content,checked:!!Ie.checked,ord:Ve,indent:Ie.indent||0};return typeof Ie.id=="number"&&(Rt.id=Ie.id),Rt}),Z=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({items:we})});if(!Z.ok)throw new Error(await Z.text());n&&n({items:we,title:ce}),e()}catch(A){console.error("Failed to save checklist",A),window.alert("Failed to save checklist")}finally{w(!1)}}function he(A){if(!A)return;const ne=A.replace("#",""),we=ne.length===3?ne.split("").map(bt=>bt+bt).join(""):ne;if(we.length!==6)return;const Z=parseInt(we.slice(0,2),16)/255,Ie=parseInt(we.slice(2,4),16)/255,Ve=parseInt(we.slice(4,6),16)/255,Rt=bt=>bt<=.03928?bt/12.92:Math.pow((bt+.055)/1.055,2.4),be=Rt(Z),qe=Rt(Ie),Dt=Rt(Ve),st=.2126*be+.7152*qe+.0722*Dt,ft=(1+.05)/(st+.05),yt=(st+.05)/(0+.05);return ft>=yt?"#ffffff":"#000000"}const $={},S=Ae?he(Ae)||"var(--muted)":void 0;Ae&&($["--checkbox-bg"]=Ae),S&&($["--checkbox-border"]=S),S&&($["--checkbox-stroke"]=S),Ae&&($["--checkbox-checked-bg"]=Ae),S&&($["--checkbox-checked-mark"]=S),Ae&&($.background=Ae,S&&($.color=S),$["--editor-surface"]=Ae);async function V(A){const ne=A||"";try{const we=await fetch(`/api/notes/${t.id}/prefs`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({color:ne})});if(!we.ok)throw new Error(await we.text())}catch(we){console.error("Failed to save color preference",we),window.alert("Failed to save color preference")}me(ne);try{s==null||s(ne)}catch{}}function pe(A){if(J(!1),!A)return;const ne=-Date.now();$t(we=>{const Ie=we.some(Ve=>String(Ve.url)===String(A))?we:[...we,{id:ne,url:String(A)}];return i&&i(Ie),Ie});try{nt(!0)}catch{}(async()=>{try{const we=await fetch(`/api/notes/${t.id}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({url:A})});if(!we.ok)throw new Error(await we.text());const Ie=(await we.json()).image||null;Ie&&Ie.id&&Ie.url&&($t(Ve=>{const Rt=Number(Ie.id),be=String(Ie.url),qe=Ve.map(ft=>Number(ft.id)===ne||String(ft.url)===String(A)?{id:Rt,url:be}:ft),st=qe.some(ft=>Number(ft.id)===Rt)?qe:[...qe,{id:Rt,url:be}];return i&&i(st),st}),zt())}catch(we){console.error("Failed to attach image",we),window.alert("Failed to attach image")}})()}function tt(A){ae(ne=>ne.find(we=>we.id===A.id)?ne:[...ne,A]),Je(!1),(async()=>{try{const ne=await fetch(`/api/notes/${t.id}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({email:A.email})});if(!ne.ok)throw new Error(await ne.text())}catch(ne){console.error("Failed to add collaborator",ne),window.alert("Failed to add collaborator")}})()}async function Ft(A){try{const ne=await fetch(`/api/notes/${t.id}/collaborators/${A}`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}});if(!ne.ok)throw new Error(await ne.text())}catch(ne){console.error("Failed to remove collaborator",ne),window.alert("Failed to remove collaborator")}}async function Kt(A){const ne=at,we=ne.filter(Z=>Number(Z.id)!==Number(A));$t(we),i&&i(we);try{const Z=await fetch(`/api/notes/${t.id}/images/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}});if(!Z.ok)throw new Error(await Z.text());zt()}catch(Z){console.error("Failed to delete image",Z),$t(ne),i&&i(ne),window.alert("Failed to delete image")}}function Zt(A){const ne=Ge.current;ne?A>=0&&Awe.filter((Z,Ie)=>Ie!==A))}const $n=h.jsx("div",{className:"image-dialog-backdrop",onMouseDown:A=>{A.target===A.currentTarget&&Y()},children:h.jsxs("div",{className:"image-dialog checklist-editor editor-dialog",role:"dialog","aria-modal":!0,style:{width:"min(1000px, 86vw)",...$},children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Edit checklist"}),h.jsx("div",{style:{display:"flex",gap:8,alignItems:"center"},children:h.jsx("button",{className:"icon-close",onClick:e,children:"✕"})})]}),h.jsxs("div",{className:"dialog-body",children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Checklist title",value:ce,onChange:A=>{ue(A.target.value);try{Le()}catch{}},style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",gap:8,alignItems:"center",marginBottom:0},onMouseDown:A=>A.preventDefault(),onPointerDown:A=>A.preventDefault(),onPointerUp:A=>A.preventDefault(),children:[h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:A=>{A.preventDefault(),A.stopPropagation(),p.current=!0,ot("bold")},onPointerUp:A=>{A.preventDefault(),A.stopPropagation()},onMouseDownCapture:A=>{A.preventDefault(),A.stopPropagation()},onMouseUp:A=>A.preventDefault(),onClick:()=>{if(p.current){p.current=!1;return}ot("bold")},"aria-pressed":xt("bold"),children:"B"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:A=>{A.preventDefault(),A.stopPropagation(),p.current=!0,ot("italic")},onPointerUp:A=>{A.preventDefault(),A.stopPropagation()},onMouseDownCapture:A=>{A.preventDefault(),A.stopPropagation()},onMouseUp:A=>A.preventDefault(),onClick:()=>{if(p.current){p.current=!1;return}ot("italic")},"aria-pressed":xt("italic"),children:"I"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:A=>{A.preventDefault(),A.stopPropagation(),p.current=!0,ot("underline")},onPointerUp:A=>{A.preventDefault(),A.stopPropagation()},onMouseDownCapture:A=>{A.preventDefault(),A.stopPropagation()},onMouseUp:A=>A.preventDefault(),onClick:()=>{if(p.current){p.current=!1;return}ot("underline")},"aria-pressed":xt("underline"),children:"U"})]})]}),(It??g).length===0&&h.jsx("div",{style:{marginBottom:8},children:h.jsx("button",{className:"btn",onClick:()=>rn(0),children:"Add an item"})}),(It??g).filter(A=>!A.checked).map((A,ne)=>{const we=It??g,Z=we.indexOf(A),Ie=Jt(Z,we),Ve=(()=>{try{return fe(A)}catch{return A.key??Z}})(),Rt=W!=null&&String(W)===String(Ve);return h.jsxs("div",{className:`checklist-item ${Ie}${Rt?" is-active":""}`,style:{marginLeft:(A.indent||0)*18},draggable:!1,onPointerCancel:()=>{dn.current=null},onDragOver:be=>{be.preventDefault();const Dt=be.currentTarget.getBoundingClientRect();j.current&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{if(k===null)return;if(rt.current==="horizontal"&&Tt.current){const yt=(be.clientX||0)-Tt.current.x;if(yt>ee.indentPx&&Z>0){let bt=null;for(let mt=Z-1;mt>=0;mt--)if((g[mt].indent||0)===0){bt=g[mt].id??null;break}Mt.current={parentId:bt,makeNested:!0}}else yt<-ee.indentPx?Mt.current={parentId:null,makeNested:!1}:Mt.current={parentId:null,makeNested:!1};return}let st=!1;const ft=G.current?G.current.getBoundingClientRect():null;if(ft){const bt=Math.max(0,Math.min(ft.bottom,Dt.bottom)-Math.max(ft.top,Dt.top))/(Dt.height||1),mt=(be.clientY||0)>(Oe.current||be.clientY||0);Oe.current=be.clientY||0;const Qt=mt?ee.ghostOverlapDownPct:ee.ghostOverlapUpPct;st=bt>=Qt}st?(Xe.current&&(clearTimeout(Xe.current),Xe.current=null),z(yt=>yt===Z?yt:Z)):N===Z&&Xe.current===null&&(Xe.current=window.setTimeout(()=>{z(yt=>yt===Z?null:yt),Xe.current=null},Math.max(0,ee.hoverClearMs)))})},onDrop:be=>{be.preventDefault();const qe=k!==null?k:parseInt(be.dataTransfer.getData("text/plain")||"-1",10),Dt=Z;if(qe>=0){const st=Tt.current?(be.clientX||0)-Tt.current.x:0;if(rt.current==="horizontal"||Math.abs(st)>ee.indentPx){const yt=Ge.current;if(yt){if(st>ee.indentPx){const[bt,mt]=kt(g,qe);let Qt=null;for(let dt=qe-1;dt>=0;dt--)if((g[dt].indent||0)===0){Qt=dt;break}if(bt>=0)if(Qt!=null)if(bt===Dt)for(let dt=bt;dtbt&&(on=Qt-(mt-bt)+1);on0;)on++;const Yt=dt.map(Ct=>{const Pt=new xs;return typeof Ct.id=="number"&&Pt.set("id",Ct.id),Ct.uid&&Pt.set("uid",Ct.uid),Pt.set("content",Ct.content),Pt.set("checked",Ct.checked),Pt.set("indent",1),Pt});yt.insert(on,Yt)}else for(let dt=bt;dt=0)for(let Qt=bt;Qt{N===Z&&z(null),j.current&&(cancelAnimationFrame(j.current),j.current=null)},children:[h.jsxs("div",{className:"drag-gutter",style:{cursor:"grab",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",touchAction:"none"},onMouseDown:be=>{be.preventDefault()},onPointerDown:be=>{var st,ft;try{be.preventDefault()}catch{}try{be.stopPropagation()}catch{}be.currentTarget.setPointerCapture(be.pointerId),Se.current=be.clientY;const qe=It??g,Dt=typeof((st=qe[Z])==null?void 0:st.id)=="number"?qe[Z].id:((ft=qe[Z])==null?void 0:ft.uid)??null;dn.current={active:!0,startX:be.clientX,startY:be.clientY,idx:Z,draggedId:Dt,pointerId:be.pointerId},rt.current=null,Ot(null)},onPointerMove:be=>{const qe=dn.current;if(!qe||!qe.active)return;try{be.preventDefault()}catch{}Se.current=be.clientY;const Dt=be.clientX-qe.startX,st=be.clientY-qe.startY,ft=ee.directionLockPx;if(rt.current===null&&(Math.abs(Dt)>ft||Math.abs(st)>ft)&&(rt.current=Math.abs(Dt)>Math.abs(st)?"horizontal":"vertical"),rt.current==="vertical"){if(!G.current){const mt=Array.from(document.querySelectorAll(".image-dialog .checklist-item:not(.completed)")),Qt=qe.idx??-1,on=fn(Qt,It??g),Yt=mt[on];if(Yt){const Ct=Yt.getBoundingClientRect();je.current={x:be.clientX-Ct.left,y:be.clientY-Ct.top};const Pt=Yt.cloneNode(!0);Pt.style.position="fixed",Pt.style.left=Ct.left+"px",Pt.style.top=be.clientY-(je.current.y||0)+"px",Pt.style.width=Ct.width+"px",Pt.style.pointerEvents="none",Pt.style.zIndex="9999",Pt.style.opacity="0.98",Pt.classList.add("checklist-ghost"),document.body.appendChild(Pt),G.current=Pt;try{Yt.classList.add("drag-source")}catch{}M(Qt),z(Qt),Wt.current=Ct.left;try{const ln=document.querySelector(".image-dialog");ln&&ln.style.setProperty("--checklist-item-shift",`${Math.round(Ct.height)}px`)}catch{}}}G.current&&(G.current.style.left=Wt.current+"px",G.current.style.top=be.clientY-(je.current.y||0)+"px",ut());const bt=Array.from(document.querySelectorAll(".image-dialog .checklist-item:not(.completed)"));if(bt.length){let mt=null;const Qt=G.current?G.current.getBoundingClientRect():{top:be.clientY-10,bottom:be.clientY+10},dt=be.clientY>(re.current||be.clientY);re.current=be.clientY;const on=typeof ee.ghostOverlapUpPct=="number"&&typeof ee.ghostOverlapDownPct=="number"?dt?ee.ghostOverlapDownPct:ee.ghostOverlapUpPct:ee.ghostOverlapPct;for(let Ct=0;Ct=on){mt=Ct;break}}const Yt=It??g;if(mt!=null){const Ct=wn(mt,Yt);Ct!==N&&z(Ct)}}return}const yt=ee.indentPx;if(rt.current==="horizontal"){const bt=qe.draggedId??null;if(bt==null)return;const mt=g,Qt=mt.findIndex(dt=>typeof bt=="number"?dt.id===bt:dt.uid===bt);if(Qt<0)return;if(Qt===0&&Dt>0){Ot(null);return}if(Dt>yt){const[dt,on]=kt(mt,Qt),Yt=[...mt],Ct=Yt.splice(dt,on-dt);let Pt=null;for(let ln=Qt-1;ln>=0;ln--)if((mt[ln].indent||0)===0){Pt=ln;break}if(Pt!=null){const ln=typeof mt[Pt].id=="number"?mt[Pt].id:mt[Pt].uid,wi=Yt.findIndex(us=>typeof ln=="number"?us.id===ln:us.uid===ln);let $i=wi>=0?wi+1:Math.min(dt,Yt.length);for(;$i0;)$i++;const Hc=Ct.map(us=>({...us,indent:1}));Yt.splice($i,0,...Hc)}else{let ln=Math.min(dt,Yt.length);for(;ln0;)ln++;const wi=Ct.map($i=>({...$i,indent:1}));Yt.splice(ln,0,...wi)}Ot(Yt)}else if(Dt<-yt){const[dt,on]=kt(mt,Qt),Yt=[...mt];for(let Ct=dt;Ct{try{be.currentTarget.releasePointerCapture(be.pointerId)}catch{}if(dn.current=null,It){const qe=Ge.current;if(qe)try{for(let Dt=0;Dt{const bt=yt.get("id"),mt=yt.get("uid");return typeof st.id=="number"&&typeof bt=="number"?Number(st.id)===Number(bt):st.uid&&mt?String(st.uid)===String(mt):!1});if(ft>=0){const yt=qe.get(ft);try{yt.set("indent",Number(st.indent||0))}catch{}try{yt.set("checked",!!st.checked)}catch{}try{yt.set("content",String(st.content||""))}catch{}}}}catch{}Ot(null),rt.current=null,U();return}if(rt.current==="vertical"&&k!==null){const qe=k,Dt=g,[st,ft]=kt(Dt,qe);if(N!==null){const yt=qe=st&&yt{be.stopPropagation(),Pr(Z)},onPointerDown:be=>{be.stopPropagation()},onPointerUp:be=>{be.stopPropagation()},children:A.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),h.jsx("div",{style:{flex:1},children:h.jsx(Ix,{value:A.content||"",onChange:be=>nn(Z,be),onEnter:()=>rn(Z+1),autoFocus:L===Z,onFocus:be=>{d.current=be,Ee.current[Z]=be;try{te(fe(A))}catch{}f(qe=>qe+1),L===Z&&H(null)}})}),h.jsx("button",{className:"delete-item",onClick:be=>{if(be.stopPropagation(),!(W!=null&&String(W)===String(Ve))){try{te(Ve)}catch{}try{H(Z)}catch{}return}Zt(Z)},"aria-label":"Delete item",children:"✕"})]},A.key??Z)}),h.jsxs("div",{style:{marginTop:12},children:[h.jsx("button",{className:"btn completed-toggle",onClick:()=>E(A=>!A),"aria-expanded":x,"aria-controls":`editor-completed-${t.id}`,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:x?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:[g.filter(A=>A.checked).length," completed items"]})]})}),x&&(It??g).filter(A=>A.checked).map((A,ne)=>{const Z=(It??g).indexOf(A),Ie="",Ve=(()=>{try{return fe(A)}catch{return A.key??Z}})(),Rt=(()=>{try{return W!=null&&String(W)===String(Ve)}catch{return!1}})();return h.jsxs("div",{className:`checklist-item completed ${Ie}${Rt?" is-active":""}`,style:{marginLeft:(A.indent||0)*18},draggable:!1,onClick:be=>{try{be.stopPropagation()}catch{}try{te(Ve)}catch{}},children:[h.jsx("div",{style:{width:20}}),h.jsx("div",{className:`checkbox-visual ${A.checked?"checked":""}`,onClick:()=>Pr(Z),children:A.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{style:{flex:1,textDecoration:"line-through",minWidth:0},children:h.jsx("div",{className:"rt-html",dangerouslySetInnerHTML:{__html:ka.sanitize(String(A.content||""),{USE_PROFILES:{html:!0}})}})}),h.jsx("button",{className:"delete-item",onClick:be=>{if(be.stopPropagation(),!(W!=null&&String(W)===String(Ve))){try{te(Ve)}catch{}return}Zt(Z)},"aria-label":"Delete item",children:"✕"})]},A.key??Z)})]})]}),at&&at.length>0&&h.jsxs("div",{className:"editor-images",style:{marginTop:10,marginBottom:8},children:[h.jsx("button",{type:"button",className:"btn editor-images-toggle",onClick:()=>nt(A=>!A),"aria-expanded":ct,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:ct?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:["Images (",at.length,")"]})]})}),ct&&h.jsx("div",{className:"editor-images-grid",style:{marginTop:8},children:at.map(A=>h.jsxs("div",{className:"note-image",role:"button",tabIndex:0,onClick:()=>Vt(A.url),onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),Vt(A.url))},style:{cursor:"zoom-in",position:"relative"},children:[h.jsx("img",{src:A.url,alt:"note image"}),h.jsx("button",{className:"image-delete","aria-label":"Delete image",title:"Delete image",onClick:ne=>{ne.stopPropagation(),Kt(A.id)},style:{position:"absolute",right:6,bottom:6},children:"🗑️"})]},A.id))})]}),h.jsxs("div",{className:"dialog-footer",style:{borderTop:S?`1px solid ${S}`:void 0},children:[h.jsxs("div",{className:"note-actions",style:{marginRight:"auto",display:"inline-flex",gap:8,justifyContent:"flex-start",color:S},children:[h.jsx("button",{className:"tiny palette",onClick:()=>se(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>Me(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Je(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),o&&h.jsx("button",{ref:Pe,className:"tiny editor-more",onClick:A=>{A.stopPropagation(),ze(ne=>!ne)},"aria-label":"More",title:"More",children:"⋮"})]}),h.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:[h.jsx("button",{className:"btn",onClick:e,children:"Cancel"}),h.jsx("button",{className:"btn",onClick:Y,disabled:v,children:v?"Saving...":"Save"})]})]})]})});if(typeof document<"u"){const A=zn.createPortal($n,document.body);return h.jsxs(h.Fragment,{children:[A,o&&Ke&&h.jsx(Hx,{anchorRef:Pe,itemsCount:o.onMoveToCollection?5:4,onClose:()=>ze(!1),onDelete:o.onDelete,onMoveToCollection:o.onMoveToCollection,onAddLabel:o.onAddLabel,onUncheckAll:o.onUncheckAll,onCheckAll:o.onCheckAll,onSetWidth:o.onSetWidth}),q&&h.jsx(ef,{anchorRef:void 0,onPick:V,onClose:()=>se(!1)}),xe&&h.jsx(tf,{onClose:()=>Me(!1),onSet:ne=>{Me(!1),ne&&window.alert(`Reminder set (UI-only): ${ne}`)}}),Q&&h.jsx(xc,{onClose:()=>Je(!1),onSelect:tt,current:(()=>{const ne=[];try{const we=a&&a.id?Number(a.id):void 0,Z=t.owner||null;Z&&typeof Z.id=="number"&&Z.id!==we&&ne.push({userId:Number(Z.id),email:String(Z.email||""),name:typeof Z.name=="string"?Z.name:void 0});const Ie=t.collaborators||[];for(const Ve of Ie){const Rt=Ve&&(Ve.user||{}),be=typeof Rt.id=="number"?Number(Rt.id):typeof Ve.userId=="number"?Number(Ve.userId):void 0,qe=typeof Rt.email=="string"?String(Rt.email):void 0,Dt=typeof Rt.name=="string"?String(Rt.name):void 0;be&&qe&&ne.push({collabId:Number(Ve.id),userId:be,email:qe,name:Dt})}}catch{}return ne})(),ownerId:typeof((sn=t.owner)==null?void 0:sn.id)=="number"?Number(t.owner.id):a==null?void 0:a.id,onRemove:Ft}),_t&&h.jsx(nf,{onClose:()=>J(!1),onAdd:pe}),At&&h.jsx(_R,{url:At,onClose:()=>Vt(null)})]})}return $n}var Qq=mn.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),Ac=Qq;const Zq=()=>{let t=!0;return(e,n)=>{if(t){t=!1;try{e()}finally{t=!0}}else n!==void 0&&n()}},eJ=/[\uD800-\uDBFF]/,tJ=/[\uDC00-\uDFFF]/,nJ=(t,e)=>{let n=0,r=0;for(;n0&&eJ.test(t[n-1])&&n--;r+n0&&tJ.test(t[t.length-r])&&r--,{index:n,remove:t.length-n-r,insert:e.slice(n,e.length-r)}},rJ=nJ,Ns=(t,e)=>t>>>e|t<<32-e,iJ=t=>Ns(t,2)^Ns(t,13)^Ns(t,22),sJ=t=>Ns(t,6)^Ns(t,11)^Ns(t,25),oJ=t=>Ns(t,7)^Ns(t,18)^t>>>3,lJ=t=>Ns(t,17)^Ns(t,19)^t>>>10,aJ=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),cJ=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class uJ{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(cJ),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let d=16;d<64;d++)n[d]=lJ(n[d-2])+n[d-7]+oJ(n[d-15])+n[d-16];let r=e[0],i=e[1],s=e[2],o=e[3],l=e[4],a=e[5],c=e[6],u=e[7];for(let d=0,f,p;d<64;d++)f=u+sJ(l)+(l&a^~l&c)+aJ[d]+n[d]>>>0,p=iJ(r)+(r&i^r&s^i&s)>>>0,u=c,c=a,a=l,l=o+f>>>0,o=s,s=i,i=r,r=f+p>>>0;e[0]+=r,e[1]+=i,e[2]+=s,e[3]+=o,e[4]+=l,e[5]+=a,e[6]+=c,e[7]+=u}digest(e){let n=0;for(;n+56<=e.length;){let o=0;for(;o<16&&n+3=0&&n>>(3-l)*8;return s}}const dJ=t=>new uJ().digest(t),jn=new pn("y-sync"),no=new pn("y-undo");new pn("yjs-cursor");const fJ=t=>{for(let n=6;niO(fJ(dJ(kK(t)))),Cm=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&e.sv.get(t.id.client)>t.id.clock&&!$c(e.ds,t.id),pJ=[{light:"#ecd44433",dark:"#ecd444"}],mJ=(t,e,n)=>{if(!t.has(n)){if(t.sizer.add(i)),e=e.filter(i=>!r.has(i))}t.set(n,J9(e))}return t.get(n)},gJ=(t,{colors:e=pJ,colorMapping:n=new Map,permanentUserData:r=null,onFirstRender:i=()=>{},mapping:s}={})=>{let o=!1;const l=new wJ(t,s),a=new hn({props:{editable:c=>{const u=jn.getState(c);return u.snapshot==null&&u.prevSnapshot==null}},key:jn,state:{init:(c,u)=>({type:t,doc:t.doc,binding:l,snapshot:null,prevSnapshot:null,isChangeOrigin:!1,isUndoRedoOperation:!1,addToHistory:!0,colors:e,colorMapping:n,permanentUserData:r}),apply:(c,u)=>{const d=c.getMeta(jn);if(d!==void 0){u=Object.assign({},u);for(const f in d)u[f]=d[f]}return u.addToHistory=c.getMeta("addToHistory")!==!1,u.isChangeOrigin=d!==void 0&&!!d.isChangeOrigin,u.isUndoRedoOperation=d!==void 0&&!!d.isChangeOrigin&&!!d.isUndoRedoOperation,l.prosemirrorView!==null&&d!==void 0&&(d.snapshot!=null||d.prevSnapshot!=null)&&xO(0,()=>{l.prosemirrorView!=null&&(d.restore==null?l._renderSnapshot(d.snapshot,d.prevSnapshot,u):(l._renderSnapshot(d.snapshot,d.snapshot,u),delete u.restore,delete u.snapshot,delete u.prevSnapshot,l.mux(()=>{l._prosemirrorChanged(l.prosemirrorView.state.doc)})))}),u}},view:c=>(l.initView(c),s==null&&l._forceRerender(),i(),{update:()=>{const u=a.getState(c.state);if(u.snapshot==null&&u.prevSnapshot==null&&(o||c.state.doc.content.findDiffStart(c.state.doc.type.createAndFill().content)!==null)){if(o=!0,u.addToHistory===!1&&!u.isChangeOrigin){const d=no.getState(c.state),f=d&&d.undoManager;f&&f.stopCapturing()}l.mux(()=>{u.doc.transact(d=>{d.meta.set("addToHistory",u.addToHistory),l._prosemirrorChanged(c.state.doc)},jn)})}},destroy:()=>{l.destroy()}})});return a},yJ=(t,e,n)=>{if(e!==null&&e.anchor!==null&&e.head!==null)if(e.type==="all")t.setSelection(new ri(t.doc));else if(e.type==="node"){const r=Lh(n.doc,n.type,e.anchor,n.mapping);t.setSelection(vJ(t,r))}else{const r=Lh(n.doc,n.type,e.anchor,n.mapping),i=Lh(n.doc,n.type,e.head,n.mapping);r!==null&&i!==null&&t.setSelection(St.between(t.doc.resolve(r),t.doc.resolve(i)))}},vJ=(t,e)=>{const n=t.doc.resolve(e);return n.nodeAfter?pt.create(t.doc,e):St.near(n)},Cw=(t,e)=>({type:e.selection.jsonID,anchor:Aw(e.selection.anchor,t.type,t.mapping),head:Aw(e.selection.head,t.type,t.mapping)});class wJ{constructor(e,n=new Map){this.type=e,this.prosemirrorView=null,this.mux=Zq(),this.mapping=n,this.isOMark=new Map,this._observeFunction=this._typeChanged.bind(this),this.doc=e.doc,this.beforeTransactionSelection=null,this.beforeAllTransactions=()=>{this.beforeTransactionSelection===null&&this.prosemirrorView!=null&&(this.beforeTransactionSelection=Cw(this,this.prosemirrorView.state))},this.afterAllTransactions=()=>{this.beforeTransactionSelection=null},this._domSelectionInView=null}get _tr(){return this.prosemirrorView.state.tr.setMeta("addToHistory",!1)}_isLocalCursorInView(){return this.prosemirrorView.hasFocus()?(e1&&this._domSelectionInView===null&&(xO(0,()=>{this._domSelectionInView=null}),this._domSelectionInView=this._isDomSelectionInView()),this._domSelectionInView):!1}_isDomSelectionInView(){const e=this.prosemirrorView._root.getSelection();if(e==null||e.anchorNode==null)return!1;const n=this.prosemirrorView._root.createRange();n.setStart(e.anchorNode,e.anchorOffset),n.setEnd(e.focusNode,e.focusOffset),n.getClientRects().length===0&&n.startContainer&&n.collapsed&&n.selectNodeContents(n.startContainer);const i=n.getBoundingClientRect(),s=cf.documentElement;return i.bottom>=0&&i.right>=0&&i.left<=(window.innerWidth||s.clientWidth||0)&&i.top<=(window.innerHeight||s.clientHeight||0)}renderSnapshot(e,n){n||(n=FO(MO(),new Map)),this.prosemirrorView.dispatch(this._tr.setMeta(jn,{snapshot:e,prevSnapshot:n}))}unrenderSnapshot(){this.mapping.clear(),this.mux(()=>{const e=this.type.toArray().map(r=>Ph(r,this.prosemirrorView.state.schema,this)).filter(r=>r!==null),n=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(e),0,0));n.setMeta(jn,{snapshot:null,prevSnapshot:null}),this.prosemirrorView.dispatch(n)})}_forceRerender(){this.mapping.clear(),this.mux(()=>{const e=this.beforeTransactionSelection!==null?null:this.prosemirrorView.state.selection,n=this.type.toArray().map(i=>Ph(i,this.prosemirrorView.state.schema,this)).filter(i=>i!==null),r=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(n),0,0));if(e){const i=ia(ho(e.anchor,0),r.doc.content.size),s=ia(ho(e.head,0),r.doc.content.size);r.setSelection(St.create(r.doc,i,s))}this.prosemirrorView.dispatch(r.setMeta(jn,{isChangeOrigin:!0,binding:this}))})}_renderSnapshot(e,n,r){let i=this.doc,s=this.type;if(e||(e=fv(this.doc)),e instanceof Uint8Array||n instanceof Uint8Array)if((!(e instanceof Uint8Array)||!(n instanceof Uint8Array))&&Dr(),i=new Fi({gc:!1}),gm(i,n),n=fv(i),gm(i,e),e=fv(i),s._item===null){const o=Array.from(this.doc.share.keys()).find(l=>this.doc.share.get(l)===this.type);s=i.getXmlFragment(o)}else{const o=i.store.clients.get(s._item.id.client)??[],l=ss(o,s._item.id.clock);s=o[l].content.type}this.mapping.clear(),this.mux(()=>{i.transact(o=>{const l=r.permanentUserData;l&&l.dss.forEach(d=>{hl(o,d,f=>{})});const a=(d,f)=>{const p=d==="added"?l.getUserByClientId(f.client):l.getUserByDeletedId(f);return{user:p,type:d,color:mJ(r.colorMapping,r.colors,p)}},c=GO(s,new u1(n.ds,e.sv)).map(d=>!d._item.deleted||Cm(d._item,e)||Cm(d._item,n)?Ph(d,this.prosemirrorView.state.schema,{mapping:new Map,isOMark:new Map},e,n,a):null).filter(d=>d!==null),u=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(c),0,0));this.prosemirrorView.dispatch(u.setMeta(jn,{isChangeOrigin:!0}))},jn)})}_typeChanged(e,n){if(this.prosemirrorView==null)return;const r=jn.getState(this.prosemirrorView.state);if(e.length===0||r.snapshot!=null||r.prevSnapshot!=null){this.renderSnapshot(r.snapshot,r.prevSnapshot);return}this.mux(()=>{const i=(l,a)=>this.mapping.delete(a);hl(n,n.deleteSet,l=>{if(l.constructor===cn){const a=l.content.type;a&&this.mapping.delete(a)}}),n.changed.forEach(i),n.changedParentTypes.forEach(i);const s=this.type.toArray().map(l=>xj(l,this.prosemirrorView.state.schema,this)).filter(l=>l!==null);let o=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(s),0,0));yJ(o,this.beforeTransactionSelection,this),o=o.setMeta(jn,{isChangeOrigin:!0,isUndoRedoOperation:n.origin instanceof VO}),this.beforeTransactionSelection!==null&&this._isLocalCursorInView()&&o.scrollIntoView(),this.prosemirrorView.dispatch(o)})}_prosemirrorChanged(e){this.doc.transact(()=>{Nw(this.doc,this.type,e,this),this.beforeTransactionSelection=Cw(this,this.prosemirrorView.state)},jn)}initView(e){this.prosemirrorView!=null&&this.destroy(),this.prosemirrorView=e,this.doc.on("beforeAllTransactions",this.beforeAllTransactions),this.doc.on("afterAllTransactions",this.afterAllTransactions),this.type.observeDeep(this._observeFunction)}destroy(){this.prosemirrorView!=null&&(this.prosemirrorView=null,this.type.unobserveDeep(this._observeFunction),this.doc.off("beforeAllTransactions",this.beforeAllTransactions),this.doc.off("afterAllTransactions",this.afterAllTransactions))}}const xj=(t,e,n,r,i,s)=>{const o=n.mapping.get(t);if(o===void 0){if(t instanceof Mr)return Ph(t,e,n,r,i,s);throw Oi()}return o},Ph=(t,e,n,r,i,s)=>{const o=[],l=a=>{var c,u;if(a instanceof Mr){const d=xj(a,e,n,r,i,s);d!==null&&o.push(d)}else{const d=(u=(c=a._item.right)==null?void 0:c.content)==null?void 0:u.type;d instanceof pl&&!d._item.deleted&&d._item.id.client===d.doc.clientID&&(a.applyDelta([{retain:a.length},...d.toDelta()]),d.doc.transact(p=>{d._item.delete(p)}));const f=bJ(a,e,n,r,i,s);f!==null&&f.forEach(p=>{p!==null&&o.push(p)})}};r===void 0||i===void 0?t.toArray().forEach(l):GO(t,new u1(i.ds,r.sv)).forEach(l);try{const a=t.getAttributes(r);r!==void 0&&(Cm(t._item,r)?Cm(t._item,i)||(a.ychange=s?s("added",t._item.id):{type:"added"}):a.ychange=s?s("removed",t._item.id):{type:"removed"});const c=e.node(t.nodeName,a,o);return n.mapping.set(t,c),c}catch{return t.doc.transact(c=>{t._item.delete(c)},jn),n.mapping.delete(t),null}},bJ=(t,e,n,r,i,s)=>{const o=[],l=t.toDelta(r,i,s);try{for(let a=0;a{t._item.delete(c)},jn),null}return o},xJ=(t,e)=>{const n=new oi,r=t.map(i=>({insert:i.text,attributes:Sj(i.marks,e)}));return n.applyDelta(r),e.mapping.set(n,t),n},kJ=(t,e)=>{const n=new Mr(t.type.name);for(const r in t.attrs){const i=t.attrs[r];i!==null&&r!=="ychange"&&n.setAttribute(r,i)}return n.insert(0,jg(t).map(r=>Ew(r,e))),e.mapping.set(n,t),n},Ew=(t,e)=>t instanceof Array?xJ(t,e):kJ(t,e),xN=t=>typeof t=="object"&&t!==null,k1=(t,e)=>{const n=Object.keys(t).filter(i=>t[i]!==null);let r=n.length===Object.keys(e).filter(i=>e[i]!==null).length;for(let i=0;i{const e=t.content.content,n=[];for(let r=0;r{const n=t.toDelta();return n.length===e.length&&n.every((r,i)=>r.insert===e[i].text&&ZD(r.attributes||{}).length===e[i].marks.length&&_c(r.attributes,(s,o)=>{var u;const l=S1(o),a=e[i].marks;return a.find(d=>d.type.name===l)?k1(s,(u=a.find(d=>d.type.name===l))==null?void 0:u.attrs):!1}))},_d=(t,e)=>{if(t instanceof Mr&&!(e instanceof Array)&&Tw(t,e)){const n=jg(e);return t._length===n.length&&k1(t.getAttributes(),e.attrs)&&t.toArray().every((r,i)=>_d(r,n[i]))}return t instanceof oi&&e instanceof Array&&kj(t,e)},Em=(t,e)=>t===e||t instanceof Array&&e instanceof Array&&t.length===e.length&&t.every((n,r)=>e[r]===n),kN=(t,e,n)=>{const r=t.toArray(),i=jg(e),s=i.length,o=r.length,l=ia(o,s);let a=0,c=0,u=!1;for(;a{let e="",n=t._start;const r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof ls?e+=n.content.str:n.content instanceof qn&&(r[n.content.key]=null)),n=n.right;return{str:e,nAttrs:r}},CJ=(t,e,n)=>{n.mapping.set(t,e);const{nAttrs:r,str:i}=SJ(t),s=e.map(c=>({insert:c.text,attributes:Object.assign({},r,Sj(c.marks,n))})),{insert:o,remove:l,index:a}=rJ(i,s.map(c=>c.insert).join(""));t.delete(a,l),t.insert(a,o),t.applyDelta(s.map(c=>({retain:c.insert.length,attributes:c.attributes})))},EJ=/(.*)(--[a-zA-Z0-9+/=]{8})$/,S1=t=>{var e;return((e=EJ.exec(t))==null?void 0:e[1])??t},NJ=(t,e)=>{const n=[];for(const r in t)n.push(e.mark(S1(r),t[r]));return n},Sj=(t,e)=>{const n={};return t.forEach(r=>{if(r.type.name!=="ychange"){const i=as(e.isOMark,r.type,()=>!r.type.excludes(r.type));n[i?`${r.type.name}--${hJ(r.toJSON())}`:r.type.name]=r.attrs}}),n},Nw=(t,e,n,r)=>{if(e instanceof Mr&&e.nodeName!==n.type.name)throw new Error("node name mismatch!");if(r.mapping.set(e,n),e instanceof Mr){const d=e.getAttributes(),f=n.attrs;for(const p in f)f[p]!==null?d[p]!==f[p]&&p!=="ychange"&&e.setAttribute(p,f[p]):e.removeAttribute(p);for(const p in d)f[p]===void 0&&e.removeAttribute(p)}const i=jg(n),s=i.length,o=e.toArray(),l=o.length,a=ia(s,l);let c=0,u=0;for(;c{for(;l-c-u>0&&s-c-u>0;){const f=o[c],p=i[c],m=o[l-u-1],g=i[s-u-1];if(f instanceof oi&&p instanceof Array)kj(f,p)||CJ(f,p,r),c+=1;else{let y=f instanceof Mr&&Tw(f,p),v=m instanceof Mr&&Tw(m,g);if(y&&v){const w=kN(f,p,r),x=kN(m,g,r);w.foundMappedChild&&!x.foundMappedChild?v=!1:!w.foundMappedChild&&x.foundMappedChild||w.equalityFactor0&&(e.slice(c,c+d).forEach(f=>r.mapping.delete(f)),e.delete(c,d)),c+u!(e instanceof Array)&&t.nodeName===e.type.name,Aw=(t,e,n)=>{if(t===0)return dv(e,0,-1);let r=e._first===null?null:e._first.content.type;for(;r!==null&&e!==r;){if(r instanceof oi){if(r._length>=t)return dv(r,t,-1);if(t-=r._length,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{do r=r._item===null?null:r._item.parent,t--;while(r!==e&&r!==null&&r._item!==null&&r._item.next===null);r!==null&&r!==e&&(r=r._item===null?null:r._item.next.content.type)}}else{const i=(n.get(r)||{nodeSize:0}).nodeSize;if(r._first!==null&&t1)return new ym(r._item===null?null:r._item.id,r._item===null?Dd(r):null,null);if(t-=i,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{if(t===0)return r=r._item===null?r:r._item.parent,new ym(r._item===null?null:r._item.id,r._item===null?Dd(r):null,null);do r=r._item.parent,t--;while(r!==e&&r._item.next===null);r!==e&&(r=r._item.next.content.type)}}}if(r===null)throw Dr();if(t===0&&r.constructor!==oi&&r!==e)return TJ(r._item.parent,r._item)}return dv(e,e._length,-1)},TJ=(t,e)=>{let n=null,r=null;return t._item===null?r=Dd(t):n=Ut(t._item.id.client,t._item.id.clock),new ym(n,r,e.id)},Lh=(t,e,n,r)=>{const i=PY(n,t);if(i===null||i.type!==e&&!Od(e,i.type._item))return null;let s=i.type,o=0;if(s.constructor===oi)o=i.index;else if(s._item===null||!s._item.deleted){let l=s._first,a=0;for(;a{let i;if(r instanceof oi)i=r.toDelta().map(o=>{const l={type:"text",text:o.insert};return o.attributes&&(l.marks=Object.keys(o.attributes).map(a=>{const c=o.attributes[a],d={type:S1(a)};return Object.keys(c)&&(d.attrs=c),d})),l});else if(r instanceof Mr){i={type:r.nodeName};const s=r.getAttributes();Object.keys(s).length&&(i.attrs=s);const o=r.toArray();o.length&&(i.content=o.map(n).flat())}else Dr();return i};return{type:"doc",content:e.map(n)}}const MJ=t=>{const e=no.getState(t).undoManager;if(e!=null)return e.undo(),!0},IJ=t=>{const e=no.getState(t).undoManager;if(e!=null)return e.redo(),!0},RJ=new Set(["paragraph"]),DJ=(t,e)=>!(t instanceof cn)||!(t.content instanceof cs)||!(t.content.type instanceof pl||t.content.type instanceof Mr&&e.has(t.content.type.nodeName))||t.content.type._length===0,OJ=({protectedNodes:t=RJ,trackedOrigins:e=[],undoManager:n=null}={})=>new hn({key:no,state:{init:(r,i)=>{const s=jn.getState(i),o=n||new VO(s.type,{trackedOrigins:new Set([jn].concat(e)),deleteFilter:l=>DJ(l,t),captureTransaction:l=>l.meta.get("addToHistory")!==!1});return{undoManager:o,prevSel:null,hasUndoOps:o.undoStack.length>0,hasRedoOps:o.redoStack.length>0}},apply:(r,i,s,o)=>{const l=jn.getState(o).binding,a=i.undoManager,c=a.undoStack.length>0,u=a.redoStack.length>0;return l?{undoManager:a,prevSel:Cw(l,s),hasUndoOps:c,hasRedoOps:u}:c!==i.hasUndoOps||u!==i.hasRedoOps?Object.assign({},i,{hasUndoOps:a.undoStack.length>0,hasRedoOps:a.redoStack.length>0}):i}},view:r=>{const i=jn.getState(r.state),s=no.getState(r.state).undoManager;return s.on("stack-item-added",({stackItem:o})=>{const l=i.binding;l&&o.meta.set(l,no.getState(r.state).prevSel)}),s.on("stack-item-popped",({stackItem:o})=>{const l=i.binding;l&&(l.beforeTransactionSelection=o.meta.get(l)||l.beforeTransactionSelection)}),{destroy:()=>{s.destroy()}}}});function jJ(t){return!!t.getMeta(jn)}function PJ(t,e){const n=jn.getState(t);return Lh(n.doc,n.type,e,n.binding.mapping)||0}function Cj(t,e){const n=jn.getState(t);return Aw(e,n.type,n.binding.mapping)}var _h=class Ej extends sx{constructor(e,n){super(e),this.yRelativePosition=n}static fromJSON(e){return new Ej(e.position,e.yRelativePosition)}toJSON(){return{position:this.position,yRelativePosition:this.yRelativePosition}}};function LJ(t,e){const n=Cj(e,t);return new _h(t,n)}function _J(t,e,n){const r=t instanceof _h?t.yRelativePosition:null;if(jJ(e)&&r){const o=PJ(n,r);return{position:new _h(o,r),mapResult:null}}const i=o2(t,e),s=i.position.position;return{position:new _h(s,r??Cj(n,s)),mapResult:i.mapResult}}var zJ=mn.create({name:"collaboration",priority:1e3,addOptions(){return{document:null,field:"default",fragment:null,provider:null}},addStorage(){return{isDisabled:!1}},onCreate(){this.editor.extensionManager.extensions.find(t=>t.name==="undoRedo")&&console.warn('[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-undo-redo".')},onBeforeCreate(){this.editor.utils.getUpdatedPosition=(t,e)=>_J(t,e,this.editor.state),this.editor.utils.createMappablePosition=t=>LJ(t,this.editor.state)},addCommands(){return{undo:()=>({tr:t,state:e,dispatch:n})=>(t.setMeta("preventDispatch",!0),no.getState(e).undoManager.undoStack.length===0?!1:n?MJ(e):!0),redo:()=>({tr:t,state:e,dispatch:n})=>(t.setMeta("preventDispatch",!0),no.getState(e).undoManager.redoStack.length===0?!1:n?IJ(e):!0)}},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Mod-y":()=>this.editor.commands.redo(),"Shift-Mod-z":()=>this.editor.commands.redo()}},addProseMirrorPlugins(){var t;const e=this.options.fragment?this.options.fragment:this.options.document.getXmlFragment(this.options.field),n=OJ(this.options.yUndoOptions),r=n.spec.view;n.spec.view=o=>{const{undoManager:l}=no.getState(o.state);l.restore&&(l.restore(),l.restore=()=>{});const a=r?r(o):void 0;return{destroy:()=>{const c=l.trackedOrigins.has(l),u=l._observers;l.restore=()=>{c&&l.trackedOrigins.add(l),l.doc.on("afterTransaction",l.afterTransactionHandler),l._observers=u},a!=null&&a.destroy&&a.destroy()}}};const i={...this.options.ySyncOptions,onFirstRender:this.options.onFirstRender},s=gJ(e,i);return this.editor.options.enableContentCheck&&((t=e.doc)==null||t.on("beforeTransaction",()=>{try{const o=AJ(e);if(o.content.length===0)return;this.editor.schema.nodeFromJSON(o).check()}catch(o){return this.editor.emit("contentError",{error:o,editor:this.editor,disableCollaboration:()=>{var l;(l=e.doc)==null||l.destroy(),this.storage.isDisabled=!0}}),!1}})),[s,n,this.editor.options.enableContentCheck&&new hn({key:new pn("filterInvalidContent"),filterTransaction:()=>{var o;return this.storage.isDisabled!==!1&&((o=e.doc)==null||o.destroy()),!0}})].filter(Boolean)}}),Pg=zJ;function FJ({note:t,onClose:e,onSaved:n,noteBg:r,onImagesUpdated:i,onColorChanged:s,moreMenu:o}){var Ye,Ge;const{token:l,user:a}=Sr(),c=B.useRef((()=>{try{return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`c${Math.random()}`}})()),u=B.useRef((()=>{try{return`rte-${(t==null?void 0:t.id)||"x"}-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`rte-${Math.random()}`}})());B.useEffect(()=>{window.dispatchEvent(new Event("freemannotes:editor-modal-open"));try{const K=u.current,ge=()=>{try{e()}catch{}};window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:K,onBack:ge}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:u.current}}))}catch{}window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}},[]);const[d,f]=B.useState(t.title||""),[p,m]=B.useState(!1),[g,y]=B.useState(!1),[v,w]=B.useState(!1),[x,E]=B.useState(!1),[k,M]=B.useState(!1),[N,z]=B.useState((t.images||[]).map(K=>({id:Number(K.id),url:String(K.url)}))),[X,L]=B.useState(!1),[H,W]=B.useState(null),[te,ce]=B.useState([]),[ue,Ae]=B.useState(!1),me=B.useRef(null);B.useRef(!1);const q=B.useRef(!1),se=B.useRef(!1),xe=B.useCallback(()=>{if(!se.current){se.current=!0;try{window.dispatchEvent(new CustomEvent("freemannotes:draft/dirty",{detail:{noteId:Number(t==null?void 0:t.id)}}))}catch{}}},[t==null?void 0:t.id]),Me=B.useMemo(()=>new Fi,[t.id]),Q=B.useRef(null);B.useEffect(()=>{const K=`note-${t.id}`,De=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/collab`,Be=new mf(De,K,Me);Q.current=Be;const Le=j=>{j&&(q.current=!0)};try{Be.on("sync",Le)}catch{}return()=>{try{Be.off("sync",Le)}catch{}try{Be.destroy()}catch{}}},[t.id,Me]);const Je=B.useCallback(()=>{try{Me.getMap("meta").set("imagesTick",{t:Date.now(),by:c.current})}catch{}},[Me]),_t=B.useCallback(async()=>{try{const K=await fetch(`/api/notes/${t.id}/images`,{headers:{Authorization:`Bearer ${l}`}});if(!K.ok)return;const ge=await K.json(),De=(ge&&ge.images||[]).map(Be=>({id:Number(Be.id),url:String(Be.url)}));z(De),i&&i(De)}catch{}},[t.id,l,i]);B.useEffect(()=>{const K=(()=>{try{return Me.getMap("meta")}catch{return null}})();if(!K)return;const ge=()=>{try{const De=K.get("imagesTick");if(!De||!De.t||De.by&&String(De.by)===String(c.current))return;_t()}catch{}};try{K.observe(ge)}catch{}return()=>{try{K.unobserve(ge)}catch{}}},[Me,_t]);const J=pg({extensions:[ta.configure({heading:{levels:[1,2,3]}}),wR.configure({openOnClick:!0,autolink:!0}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:Me}),yg,mn.create({name:"paragraphEnterFix",priority:1e3,addKeyboardShortcuts(){return{"Shift-Enter":()=>{const K=this.editor;return K.commands.splitBlock(),K.commands.setParagraph(),!0},"Mod-Enter":()=>{const K=this.editor;return K.commands.splitBlock(),K.commands.setParagraph(),!0}}}})],editorProps:{attributes:{class:"rt-editor"}}});function at(K){if(!J)return;const ge=J.state.selection;if(!ge||!ge.empty){J.chain().focus()[`toggle${K.charAt(0).toUpperCase()+K.slice(1)}`]().run();return}const De=ge.$from;let Be=De.depth;for(;Be>0&&!De.node(Be).isBlock;)Be--;const Le=De.start(Be),j=De.end(Be),G=J.chain().focus().setTextSelection({from:Le,to:j});K==="bold"?G.toggleBold().run():K==="italic"?G.toggleItalic().run():G.toggleUnderline().run();try{J.chain().setTextSelection(ge.from).run()}catch{}}B.useEffect(()=>{try{const K=(t.images||[]).map(ge=>({id:Number(ge.id),url:String(ge.url)}));z(ge=>{try{if(ge.length===K.length&&ge.every((De,Be)=>{var Le,j;return Number(De.id)===Number((Le=K[Be])==null?void 0:Le.id)&&String(De.url)===String((j=K[Be])==null?void 0:j.url)}))return ge}catch{}return K})}catch{}},[t.images]);const[,$t]=B.useState(0);B.useEffect(()=>{if(!J)return;const K=()=>$t(ge=>ge+1);return J.on("selectionUpdate",K),J.on("transaction",K),()=>{J.off("selectionUpdate",K),J.off("transaction",K)}},[J]);function ct(){if(!J)return;const K=window.prompt("Enter URL:");K&&J.chain().focus().extendMarkRange("link").setLink({href:K}).run()}const nt=B.useRef(null);B.useEffect(()=>{if(!J)return;const K=()=>{try{q.current&&xe()}catch{}nt.current&&window.clearTimeout(nt.current),nt.current=window.setTimeout(async()=>{try{const ge=J.getJSON();await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({body:JSON.stringify(ge),type:"TEXT"})})}catch{}},700)};return J.on("update",K),()=>{J.off("update",K),nt.current&&window.clearTimeout(nt.current)}},[J,t.id,l,xe]);async function At(){try{const K=(()=>{try{return JSON.stringify((J==null?void 0:J.getJSON())||{})}catch{return t.body||""}})();if((t.title||"")!==d){const ge=await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({title:d})});if(!ge.ok)throw new Error(await ge.text())}n&&n({title:d,body:K}),e()}catch(K){console.error("Failed to update title",K),window.alert("Failed to update title")}}function Vt(K){if(!K)return;const ge=K.replace("#",""),De=ge.length===3?ge.split("").map(Tt=>Tt+Tt).join(""):ge;if(De.length!==6)return;const Be=parseInt(De.slice(0,2),16)/255,Le=parseInt(De.slice(2,4),16)/255,j=parseInt(De.slice(4,6),16)/255,G=Tt=>Tt<=.03928?Tt/12.92:Math.pow((Tt+.055)/1.055,2.4),de=G(Be),je=G(Le),Ue=G(j),We=.2126*de+.7152*je+.0722*Ue,Se=(1+.05)/(We+.05),Xe=(We+.05)/(0+.05);return Se>=Xe?"#ffffff":"#000000"}const wt={},[ae,Ee]=B.useState(r??(t.viewerColor||t.color||"")),Ke=ae?Vt(ae)||"var(--muted)":void 0;B.useEffect(()=>{Ee(r??(t.viewerColor||t.color||""))},[r,t.viewerColor,t.color]),ae&&(wt["--checkbox-bg"]=ae,wt["--checkbox-border"]=Ke||void 0,wt["--checkbox-stroke"]=Ke||void 0,wt["--checkbox-checked-bg"]=ae,wt["--checkbox-checked-mark"]=Ke||void 0,wt["--editor-surface"]=ae,wt.background=ae,Ke&&(wt.color=Ke));async function ze(K){const ge=K||"";try{const De=await fetch(`/api/notes/${t.id}/prefs`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({color:ge})});if(!De.ok)throw new Error(await De.text())}catch(De){console.error("Failed to save color preference",De),window.alert("Failed to save color preference")}Ee(ge);try{s==null||s(ge)}catch{}}function Pe(K){if(M(!1),!K)return;const ge=-Date.now();z(De=>{const Le=De.some(j=>String(j.url)===String(K))?De:[...De,{id:ge,url:String(K)}];return i&&i(Le),Le});try{L(!0)}catch{}(async()=>{try{const De=await fetch(`/api/notes/${t.id}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({url:K})});if(!De.ok)throw new Error(await De.text());const Le=(await De.json()).image||null;Le&&Le.id&&Le.url&&(z(j=>{const G=Number(Le.id),de=String(Le.url),je=j.map(Se=>Number(Se.id)===ge||String(Se.url)===String(K)?{id:G,url:de}:Se),We=je.some(Se=>Number(Se.id)===G)?je:[...je,{id:G,url:de}];return i&&i(We),We}),Je())}catch(De){console.error("Failed to attach image",De),window.alert("Failed to attach image")}})()}function it(K){ce(ge=>ge.find(De=>De.id===K.id)?ge:[...ge,K]),E(!1),(async()=>{try{const ge=await fetch(`/api/notes/${t.id}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({email:K.email})});if(!ge.ok)throw new Error(await ge.text())}catch(ge){console.error("Failed to add collaborator",ge),window.alert("Failed to add collaborator")}})()}async function ot(K){try{const ge=await fetch(`/api/notes/${t.id}/collaborators/${K}`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}});if(!ge.ok)throw new Error(await ge.text())}catch(ge){console.error("Failed to remove collaborator",ge),window.alert("Failed to remove collaborator")}}async function xt(K){const ge=N,De=ge.filter(Be=>Number(Be.id)!==Number(K));z(De),i&&i(De);try{const Be=await $J(t.id,K,l);if(!Be.ok)throw new Error(await Be.text());Je()}catch(Be){console.error("Failed to delete image",Be),z(ge),i&&i(ge),window.alert("Failed to delete image")}}const oe=h.jsx("div",{className:"image-dialog-backdrop",onMouseDown:K=>{K.target===K.currentTarget&&At()},children:h.jsxs("div",{className:`image-dialog editor-dialog${p?" maximized":""}`,role:"dialog","aria-modal":!0,style:{width:p?"96vw":"min(1000px, 86vw)",...wt},children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Edit note"}),h.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[h.jsx("button",{className:"tiny",onClick:()=>m(K=>!K),"aria-label":"Toggle maximize",title:"Toggle maximize",children:"⤢"}),h.jsx("button",{className:"icon-close",onClick:e,children:"✕"})]})]}),h.jsxs("div",{className:"dialog-body",children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Title",value:d,onChange:K=>{f(K.target.value);try{xe()}catch{}},style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:0,marginBottom:0,overflowX:"auto",color:Ke},children:[h.jsx("button",{className:"tiny",onClick:()=>at("bold"),"aria-pressed":J==null?void 0:J.isActive("bold"),"aria-label":"Bold",title:"Bold",children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>at("italic"),"aria-pressed":J==null?void 0:J.isActive("italic"),"aria-label":"Italic",title:"Italic",children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>at("underline"),"aria-pressed":J==null?void 0:J.isActive("underline"),"aria-label":"Underline",title:"Underline",children:"U"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleHeading({level:1}).run(),"aria-pressed":J==null?void 0:J.isActive("heading",{level:1}),"aria-label":"Heading 1",title:"Heading 1",children:"H1"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleHeading({level:2}).run(),"aria-pressed":J==null?void 0:J.isActive("heading",{level:2}),"aria-label":"Heading 2",title:"Heading 2",children:"H2"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleHeading({level:3}).run(),"aria-pressed":J==null?void 0:J.isActive("heading",{level:3}),"aria-label":"Heading 3",title:"Heading 3",children:"H3"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleBulletList().run(),"aria-pressed":J==null?void 0:J.isActive("bulletList"),"aria-label":"Bulleted list",title:"Bulleted list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("circle",{cx:"5",cy:"6",r:"1.5"}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"12",r:"1.5"}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"18",r:"1.5"}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleOrderedList().run(),"aria-pressed":J==null?void 0:J.isActive("orderedList"),"aria-label":"Numbered list",title:"Numbered list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("text",{x:"3.5",y:"7",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"1."}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"13",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"2."}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"19",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"3."}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("left").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"left"}),"aria-label":"Align left",title:"Align left",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"4",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("center").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"center"}),"aria-label":"Align center",title:"Align center",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"7",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"8",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("right").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"right"}),"aria-label":"Align right",title:"Align right",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"6",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"10",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"6",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"12",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("justify").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"justify"}),"aria-label":"Justify",title:"Justify",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"9",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"17",width:"14",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:ct,"aria-label":"Insert link",title:"Insert link",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("path",{d:"M9.17 14.83a3 3 0 0 1 0-4.24l2.83-2.83a3 3 0 1 1 4.24 4.24l-.88.88",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),h.jsx("path",{d:"M14.83 9.17a3 3 0 0 1 0 4.24l-2.83 2.83a3 3 0 1 1-4.24-4.24l.88-.88",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),h.jsx("div",{onKeyDown:K=>{try{if(!(K.ctrlKey||K.metaKey)){const Be=String(K.key||"");(Be.length===1||Be==="Backspace"||Be==="Enter"||Be==="Delete")&&xe()}}catch{}if(!(!J||!(K.ctrlKey||K.metaKey))&&J.isFocused)switch(K.key.toLowerCase()){case"b":K.preventDefault(),at("bold");break;case"i":K.preventDefault(),at("italic");break;case"u":K.preventDefault(),at("underline");break;case"k":K.preventDefault(),ct();break;case"l":K.preventDefault(),J.chain().focus().setTextAlign("left").run();break;case"r":K.preventDefault(),J.chain().focus().setTextAlign("right").run();break;case"e":K.preventDefault(),J.chain().focus().setTextAlign("center").run();break;case"j":K.preventDefault(),J.chain().focus().setTextAlign("justify").run();break}},children:h.jsx(Qd,{editor:J,style:{color:Ke}})}),N&&N.length>0&&h.jsxs("div",{className:"editor-images",style:{marginTop:10},children:[h.jsx("button",{type:"button",className:"btn editor-images-toggle",onClick:()=>L(K=>!K),"aria-expanded":X,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:X?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:["Images (",N.length,")"]})]})}),X&&h.jsx("div",{className:"editor-images-grid",style:{marginTop:8},children:N.map(K=>h.jsxs("div",{className:"note-image",role:"button",tabIndex:0,onClick:()=>W(K.url),onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.preventDefault(),W(K.url))},style:{cursor:"zoom-in",position:"relative"},children:[h.jsx("img",{src:K.url,alt:"note image"}),h.jsx("button",{className:"image-delete","aria-label":"Delete image",title:"Delete image",onClick:ge=>{ge.stopPropagation(),xt(K.id)},style:{position:"absolute",right:6,bottom:6},children:"🗑️"})]},K.id))})]})]}),h.jsxs("div",{className:"dialog-footer",style:{borderTop:`1px solid ${Ke||"rgba(255,255,255,0.15)"}`},children:[h.jsxs("div",{className:"note-actions",style:{marginRight:"auto",display:"inline-flex",gap:8,justifyContent:"flex-start",color:Ke},children:[h.jsx("button",{className:"tiny palette",onClick:()=>y(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>w(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>E(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>M(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),o&&h.jsx("button",{ref:me,className:"tiny editor-more",onClick:K=>{K.stopPropagation(),Ae(ge=>!ge)},"aria-label":"More",title:"More",children:"⋮"})]}),h.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:h.jsx("button",{className:"btn",onClick:At,children:"Save"})})]})]})});if(x&&((()=>{const K=[];try{const ge=a&&a.id?Number(a.id):void 0,De=t.owner||null;De&&typeof De.id=="number"&&De.id!==ge&&K.push({userId:Number(De.id),email:String(De.email||""),name:typeof De.name=="string"?De.name:void 0});const Be=t.collaborators||[];for(const Le of Be){const j=Le&&(Le.user||{}),G=typeof j.id=="number"?Number(j.id):typeof Le.userId=="number"?Number(Le.userId):void 0,de=typeof j.email=="string"?String(j.email):void 0,je=typeof j.name=="string"?String(j.name):void 0;G&&de&&K.push({collabId:Number(Le.id),userId:G,email:de,name:je})}}catch{}return K})(),typeof((Ye=t.owner)==null?void 0:Ye.id)=="number"?Number(t.owner.id):a==null||a.id),typeof document<"u"){const K=zn.createPortal(oe,document.body);return h.jsxs(h.Fragment,{children:[K,o&&ue&&h.jsx(Hx,{anchorRef:me,itemsCount:o.onMoveToCollection?5:4,onClose:()=>Ae(!1),onDelete:o.onDelete,onMoveToCollection:o.onMoveToCollection,onAddLabel:o.onAddLabel,onSetWidth:o.onSetWidth}),g&&h.jsx(ef,{anchorRef:void 0,onPick:ze,onClose:()=>y(!1)}),v&&h.jsx(tf,{onClose:()=>w(!1),onSet:ge=>{w(!1),ge&&window.alert(`Reminder set (UI-only): ${ge}`)}}),x&&h.jsx(xc,{onClose:()=>E(!1),onSelect:it,current:(()=>{const ge=[];try{const De=a&&a.id?Number(a.id):void 0,Be=t.owner||null;Be&&typeof Be.id=="number"&&Be.id!==De&&ge.push({userId:Number(Be.id),email:String(Be.email||""),name:typeof Be.name=="string"?Be.name:void 0});const Le=t.collaborators||[];for(const j of Le){const G=j&&(j.user||{}),de=typeof G.id=="number"?Number(G.id):typeof j.userId=="number"?Number(j.userId):void 0,je=typeof G.email=="string"?String(G.email):void 0,Ue=typeof G.name=="string"?String(G.name):void 0;de&&je&&ge.push({collabId:Number(j.id),userId:de,email:je,name:Ue})}}catch{}return ge})(),ownerId:typeof((Ge=t.owner)==null?void 0:Ge.id)=="number"?Number(t.owner.id):a==null?void 0:a.id,onRemove:ot}),k&&h.jsx(nf,{onClose:()=>M(!1),onAdd:Pe}),H&&h.jsx(_R,{url:H,onClose:()=>W(null)})]})}return oe}function $J(t,e,n){return fetch(`/api/notes/${t}/images/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})}function BJ({noteId:t,onClose:e,onChanged:n}){const{token:r}=Sr(),[i,s]=B.useState([]),[o,l]=B.useState([]),[a,c]=B.useState([]),[u,d]=B.useState(!1),[f,p]=B.useState(""),[m,g]=B.useState(!1);B.useEffect(()=>{try{return window.dispatchEvent(new Event("freemannotes:editor-modal-open")),()=>{setTimeout(()=>{try{window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}catch{}},0)}}catch{return}},[]);const y=i.length?Number(i[i.length-1].id):null,v=B.useCallback(async()=>{if(!r){l([]);return}d(!0);try{const L=y==null?"":`?parentId=${encodeURIComponent(String(y))}`,W=await(await fetch(`/api/collections${L}`,{headers:{Authorization:`Bearer ${r}`}})).json(),te=Array.isArray(W==null?void 0:W.collections)?W.collections:[];l(te.map(ce=>({id:Number(ce.id),name:String(ce.name||""),parentId:ce.parentId==null?null:Number(ce.parentId),hasChildren:!!ce.hasChildren,noteCount:typeof ce.noteCount=="number"?Number(ce.noteCount):void 0})).filter(ce=>Number.isFinite(ce.id)&&ce.name.length))}catch{l([])}finally{d(!1)}},[r,y]);B.useEffect(()=>{v()},[v]);const w=B.useCallback(async()=>{if(!r){c([]);return}try{const L=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections`,{headers:{Authorization:`Bearer ${r}`}});if(!L.ok)return;const H=await L.json(),W=Array.isArray(H==null?void 0:H.collections)?H.collections:[];c(W.map(te=>({id:Number(te.id),name:String(te.name||""),parentId:te.parentId==null?null:Number(te.parentId)})).filter(te=>Number.isFinite(te.id)&&te.name.length))}catch{}},[r,t]);B.useEffect(()=>{w()},[w]),B.useEffect(()=>{const L=H=>{H.key==="Escape"&&e()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[e]);const x=B.useMemo(()=>new Set(a.map(L=>Number(L.id)).filter(L=>Number.isFinite(L))),[a]),E=B.useCallback((L,H)=>{const W=Number(L),te=Number(H);!Number.isFinite(W)||!Number.isFinite(te)||te===0||l(ce=>ce.map(ue=>Number(ue.id)!==W||typeof ue.noteCount!="number"?ue:{...ue,noteCount:Math.max(0,Number(ue.noteCount)+te)}))},[]),k=async L=>{if(!r||m||!Number.isFinite(L))return;const H=x.has(Number(L));g(!0);try{const W=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({collectionId:Number(L)})});if(!W.ok)throw new Error(await W.text());const te=await W.json(),ce=Array.isArray(te==null?void 0:te.collections)?te.collections:[];c(ce.map(ue=>({id:Number(ue.id),name:String(ue.name||""),parentId:ue.parentId==null?null:Number(ue.parentId)})).filter(ue=>Number.isFinite(ue.id)&&ue.name.length)),H||E(L,1);try{n(ce)}catch{}}catch(W){window.alert("Failed to add note to collection: "+String(W))}finally{g(!1)}},M=async L=>{if(!r||m||!Number.isFinite(L))return;const H=x.has(Number(L));g(!0);try{const W=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections/${encodeURIComponent(String(L))}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!W.ok)throw new Error(await W.text());const te=await W.json(),ce=Array.isArray(te==null?void 0:te.collections)?te.collections:[];c(ce.map(ue=>({id:Number(ue.id),name:String(ue.name||""),parentId:ue.parentId==null?null:Number(ue.parentId)})).filter(ue=>Number.isFinite(ue.id)&&ue.name.length)),H&&E(L,-1);try{n(ce)}catch{}}catch(W){window.alert("Failed to remove from collection: "+String(W))}finally{g(!1)}},N=async()=>{if(!r||m)return;const L=Array.from(new Set(a.map(H=>Number(H.id)).filter(H=>Number.isFinite(H))));g(!0);try{const H=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!H.ok)throw new Error(await H.text());c([]),L.forEach(W=>E(W,-1));try{n([])}catch{}}catch(H){window.alert("Failed to clear collections: "+String(H))}finally{g(!1)}},z=async()=>{var H;if(!r)return;const L=String(f||"").trim();if(L&&!m){g(!0);try{const W=await fetch("/api/collections",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({name:L,parentId:y})});if(!W.ok)throw new Error(await W.text());const te=await W.json(),ce=Number((H=te==null?void 0:te.collection)==null?void 0:H.id);if(Number.isFinite(ce)){try{p("")}catch{}g(!1),await k(ce);return}await v()}catch(W){window.alert("Failed to create collection: "+String(W))}finally{g(!1)}}},X=i.map(L=>L.name).join(" / ");return zn.createPortal(h.jsx("div",{style:{position:"fixed",inset:0,background:"var(--modal-backdrop, rgba(0,0,0,0.66))",zIndex:10050,display:"flex",alignItems:"center",justifyContent:"center",padding:16},onPointerDown:L=>{L.target===L.currentTarget&&(L.preventDefault(),L.stopPropagation(),setTimeout(()=>e(),0))},onClick:L=>{L.target===L.currentTarget&&(L.preventDefault(),L.stopPropagation())},children:h.jsxs("div",{role:"dialog","aria-label":"Add to collection","aria-modal":"true",style:{width:"min(520px, 100%)",maxHeight:"min(680px, 100%)",overflow:"auto",background:"var(--modal-surface, var(--panel, var(--card)))",color:"var(--text, var(--fg))",border:"1px solid var(--modal-border, var(--border, rgba(255,255,255,0.10)))",borderRadius:12,boxShadow:"0 18px 48px rgba(0,0,0,0.42)",padding:14},onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onClick:L=>L.stopPropagation(),children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[h.jsx("div",{style:{display:"flex",alignItems:"center",gap:8},children:i.length>0&&h.jsxs(h.Fragment,{children:[h.jsx("button",{className:"btn",onClick:()=>s(L=>L.slice(0,-1)),disabled:m,title:"Back",children:"Back"}),h.jsx("button",{className:"btn",onClick:()=>s([]),disabled:m,title:"Root",children:"All"})]})}),h.jsx("button",{className:"btn",onClick:e,disabled:m,children:"Done"})]}),h.jsxs("div",{style:{marginTop:10,marginBottom:10},children:[h.jsx("div",{style:{fontWeight:700},children:"Add to…"}),h.jsx("div",{style:{color:"var(--muted)",fontSize:12},children:X||"All notes"})]}),h.jsxs("div",{style:{display:"flex",gap:8,marginBottom:10},children:[y!=null&&h.jsx("button",{className:"btn",onClick:()=>{k(Number(y))},disabled:m,title:"Add to current collection",children:"Add here"}),h.jsx("button",{className:"btn",onClick:N,disabled:m,title:"Remove from all collections",children:"Remove all"})]}),h.jsxs("div",{style:{display:"grid",gap:6},children:[u&&h.jsx("div",{style:{color:"var(--muted)"},children:"Loading…"}),!u&&o.length===0&&h.jsx("div",{style:{color:"var(--muted)"},children:"No sub-collections"}),o.map(L=>h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"8px 10px",borderRadius:10,border:"1px solid var(--border)",background:"var(--panel-2, transparent)"},children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[h.jsx("button",{className:"btn",onClick:()=>s(H=>[...H,{id:L.id,name:L.name}]),disabled:m,title:"Open",children:"Open"}),h.jsxs("div",{style:{overflow:"hidden"},children:[h.jsx("div",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:L.name}),typeof L.noteCount=="number"&&h.jsxs("div",{style:{color:"var(--muted)",fontSize:12},children:[L.noteCount," notes"]})]})]}),(()=>{const H=x.has(Number(L.id));return h.jsx("button",{className:"btn",onClick:()=>{H?M(L.id):k(L.id)},disabled:m,title:H?"Remove note from this collection":"Add note to this collection",children:H?"Remove":"Add"})})()]},L.id))]}),h.jsxs("div",{style:{marginTop:12,borderTop:"1px solid var(--border)",paddingTop:10},children:[h.jsx("div",{style:{fontWeight:700,marginBottom:6},children:"New collection"}),h.jsxs("div",{style:{display:"flex",gap:8},children:[h.jsx("input",{value:f,onChange:L=>p(L.target.value),placeholder:"Name",style:{flex:1,minWidth:0,padding:"8px 10px",borderRadius:10,border:"1px solid var(--border)",background:"var(--panel)",color:"var(--text)"},onKeyDown:L=>{L.key==="Enter"&&z()},disabled:m}),h.jsx("button",{className:"btn",onClick:z,disabled:m||!f.trim(),children:"Create & add"})]})]})]})}),document.body)}function UJ({noteId:t,onClose:e,onUpdated:n}){const{token:r}=Sr(),[i,s]=b.useState([]),[o,l]=b.useState(new Set),[a,c]=b.useState(""),[u,d]=b.useState(!1);b.useEffect(()=>{r&&Promise.all([fetch("/api/labels",{headers:{Authorization:`Bearer ${r}`}}).then(y=>y.json()),fetch("/api/notes",{headers:{Authorization:`Bearer ${r}`}}).then(y=>y.json())]).then(([y,v])=>{const w=Array.isArray(y.labels)?y.labels:[];s(w);const x=(Array.isArray(v.notes)?v.notes:[]).find(k=>k.id===t),E=new Set(((x==null?void 0:x.noteLabels)||[]).map(k=>{var M;return(M=k.label)==null?void 0:M.id}).filter(k=>typeof k=="number"));l(E)}).catch(()=>{})},[r,t]),b.useEffect(()=>{try{return window.dispatchEvent(new Event("freemannotes:editor-modal-open")),()=>{setTimeout(()=>{try{window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}catch{}},0)}}catch{return}},[]);async function f(y){if(r){d(!0);try{let v={};if(typeof y=="string")v={name:y};else{const E=i.find(k=>k.id===y);if(!E)return;v={name:E.name}}const w=await fetch(`/api/notes/${t}/labels`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(v)});if(!w.ok)throw new Error(await w.text());const x=await w.json();if(x!=null&&x.label){const E=x.label,M=i.some(z=>z.id===E.id)?i:[...i,E],N=new Set(o);N.add(E.id),s(M),l(N),n&&n(M.filter(z=>N.has(z.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent("labels:refresh"))}}finally{d(!1)}}}async function p(y){if(r){d(!0);try{const v=await fetch(`/api/notes/${t}/labels/${y}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!v.ok)throw new Error(await v.text());const w=new Set(o);w.delete(y),l(w),n&&n(i.filter(x=>w.has(x.id)))}finally{d(!1)}}}async function m(y){if(!(!r||!window.confirm("Delete this label? This will remove it from all notes and from the sidebar."))){d(!0);try{const w=await fetch(`/api/labels/${y}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!w.ok)throw new Error(await w.text());const x=i.filter(k=>k.id!==y),E=new Set(o);E.delete(y),s(x),l(E),n&&n(x.filter(k=>E.has(k.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent("labels:refresh"))}finally{d(!1)}}}const g=h.jsx("div",{className:"image-dialog-backdrop",onPointerDown:y=>{y.target===y.currentTarget&&(y.preventDefault(),y.stopPropagation(),setTimeout(()=>e(),0))},onClick:y=>{y.target===y.currentTarget&&(y.preventDefault(),y.stopPropagation())},children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,style:{width:360},onPointerDown:y=>{y.stopPropagation()},onMouseDown:y=>{y.stopPropagation()},onClick:y=>{y.stopPropagation()},children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Labels"}),h.jsx("button",{className:"icon-close",onClick:e,children:"✕"})]}),h.jsxs("div",{className:"dialog-body",children:[h.jsxs("div",{style:{display:"flex",gap:8,marginBottom:8},children:[h.jsx("input",{value:a,onChange:y=>c(y.target.value),placeholder:"Create new label",className:"image-url-input"}),h.jsx("button",{className:"btn",onClick:async()=>{const y=a.trim();y&&(await f(y),c(""))},disabled:u,children:"Add"})]}),h.jsx("div",{children:i.length===0?h.jsx("div",{style:{color:"var(--muted)"},children:"No labels yet"}):i.map(y=>{const v=o.has(y.id);return h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 0",justifyContent:"space-between"},children:[h.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[h.jsx("input",{type:"checkbox",checked:v,onChange:async()=>{v?await p(y.id):await f(y.id)}}),h.jsx("span",{children:y.name})]}),h.jsx("button",{className:"tiny",onClick:()=>m(y.id),title:"Delete label","aria-label":"Delete label",style:{color:"var(--danger, #d33)"},children:"✕"})]},y.id)})})]}),h.jsx("div",{className:"dialog-footer",children:h.jsx("button",{className:"btn",onClick:()=>{n&&n(i.filter(y=>o.has(y.id))),e()},children:"Close"})})]})});return typeof document<"u"?zn.createPortal(g,document.body):g}function Fs(t){if(!t)return;const e=t.replace("#",""),n=e.length===3?e.split("").map(m=>m+m).join(""):e;if(n.length!==6)return;const r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,s=parseInt(n.slice(4,6),16)/255,o=m=>m<=.03928?m/12.92:Math.pow((m+.055)/1.055,2.4),l=o(r),a=o(i),c=o(s),u=.2126*l+.7152*a+.0722*c,d=(m,g)=>(Math.max(m,g)+.05)/(Math.min(m,g)+.05),f=d(1,u),p=d(0,u);return f>=p?"#ffffff":"#000000"}function El({note:t,onChange:e,openRequest:n,onOpenRequestHandled:r,dragHandleAttributes:i,dragHandleListeners:s}){var Pr;const o=b.useRef(null),l=b.useRef(null),a=b.useRef(null),c=b.useRef(null),u=b.useRef(null),d=b.useRef(null),f=(()=>{try{return Sb()}catch{return{effective:"dark"}}})(),[p,m]=b.useState(t.viewerColor||t.color||""),[g,y]=b.useState(t.viewerColor||t.color?Fs(t.viewerColor||t.color):void 0),[v,w]=b.useState(!1),[x,E]=b.useState(t.images||[]),[k,M]=b.useState(3),[N,z]=b.useState(t.items||[]),[X,L]=b.useState(t.title||"");B.useEffect(()=>{try{const R=(t.images||[]).map(U=>({id:Number(U.id),url:String(U.url)}));E(R)}catch{}},[t.id,t.images]);function H(R){try{e==null||e({type:"images",noteId:t.id,images:R})}catch{}}function W(R){try{e==null||e({type:"color",noteId:t.id,color:R||""})}catch{}}function te(R){E(U=>{const Y=R(U);try{setTimeout(()=>H(Y),0)}catch{}return Y})}const[ce,ue]=b.useState(!1),[Ae,me]=b.useState([]),[q,se]=b.useState(()=>(t.noteLabels||[]).map(R=>R.label).filter(R=>R&&typeof R.id=="number"&&typeof R.name=="string")),[xe,Me]=B.useState(()=>{try{const R=t.viewerCollections;return Array.isArray(R)?R.filter(U=>U&&typeof U.id=="number"&&typeof U.name=="string").map(U=>({id:Number(U.id),name:String(U.name),parentId:U.parentId==null?null:Number(U.parentId)})):[]}catch{return[]}}),[Q,Je]=b.useState(!1),[_t,J]=b.useState(null),[at,$t]=b.useState(!1),[ct,nt]=B.useState(null),[At,Vt]=B.useState({}),[wt,ae]=b.useState(!1),[Ee,Ke]=b.useState(!1),[ze,Pe]=b.useState(!1),[it,ot]=b.useState(!1),[xt,oe]=b.useState(!1),[Ye,Ge]=b.useState(!0),[K,ge]=B.useState(null),[De,Be]=b.useState(!1);B.useEffect(()=>{try{const R=t.viewerCollections;if(!Array.isArray(R)){Me([]);return}const U=R.filter(Y=>Y&&typeof Y.id=="number"&&typeof Y.name=="string").map(Y=>({id:Number(Y.id),name:String(Y.name),parentId:Y.parentId==null?null:Number(Y.parentId)}));Me(U)}catch{Me([])}},[t.id,t.viewerCollections]);const Le=B.useMemo(()=>{try{const R=window.matchMedia;return!!(R&&(R("(pointer: coarse)").matches||R("(any-pointer: coarse)").matches))}catch{return!1}},[]),j=Le?"center":"flex-start",G=B.useCallback(()=>{t.type==="CHECKLIST"||t.items&&t.items.length?ot(!0):oe(!0)},[t.type,t.items]),de=B.useRef(0);B.useEffect(()=>{const R=Number(n||0);if(R&&R!==de.current){de.current=R,G();try{r&&r(Number(t.id))}catch{}}},[n,G,r,t.id]);const je=B.useCallback(R=>{if(!R)return!1;try{return!!R.closest('button, a, input, textarea, select, [contenteditable="true"], [role="button"], .more-menu, .dropdown, .color-palette')}catch{return!1}},[]),Ue=B.useCallback((R=!1)=>{c.current==null&&(c.current=requestAnimationFrame(()=>{c.current=null;const U=l.current;if(U)try{if(!(U.scrollHeight>U.clientHeight+1)){U.style.maxHeight&&(U.style.maxHeight=""),u.current=null,d.current=null;return}const he=U.style.maxHeight;R&&he&&(U.style.maxHeight="",U.getBoundingClientRect());const $=U.clientHeight;if(!Number.isFinite($)||$<=0){R&&he&&(U.style.maxHeight=he);return}let S=0;const V=N&&N.length>0?U.querySelector(".note-item-text")??U:U,pe=parseFloat(getComputedStyle(V).lineHeight||"0");if(Number.isFinite(pe)&&pe>0&&(S=pe),!Number.isFinite(S)||S<12){he&&(U.style.maxHeight=he);return}if(R&&u.current!=null&&d.current!=null&&Math.abs(u.current-S)<.5&&Math.abs(d.current-$)<.5)return;const tt=$%S;if(tt<2||S-tt<2){R&&he&&(U.style.maxHeight=he);return}const Ft=Math.max(S,Math.floor($-tt));U.style.maxHeight=`${Ft}px`,u.current=S,d.current=$}catch{}}))},[N]);B.useEffect(()=>{const R=l.current;if(!R)return;const U=()=>{try{const S=R.scrollHeight>R.clientHeight+1;Be(S)}catch{}},Y=requestAnimationFrame(()=>{U(),Ue(!0)});let he=null;try{he=new ResizeObserver(()=>{U(),Ue()}),he.observe(R)}catch{}const $=()=>Ue(!0);return window.addEventListener("notes-grid:recalc",$),window.addEventListener("resize",$),()=>{try{cancelAnimationFrame(Y)}catch{}try{he&&he.disconnect()}catch{}try{window.removeEventListener("notes-grid:recalc",$)}catch{}try{window.removeEventListener("resize",$)}catch{}if(c.current!=null){try{cancelAnimationFrame(c.current)}catch{}c.current=null}}},[t.id,X,N.length,Ye,K,t.body,x.length,q.length,Ue]),B.useEffect(()=>{const R=a.current;if(!R)return;const U=6,Y=()=>{try{const S=getComputedStyle(document.documentElement).getPropertyValue("--image-thumb-size")||"",V=Math.max(24,parseInt(String(S).trim(),10)||96),pe=R.clientWidth||0,tt=Math.max(1,Math.floor((pe+U)/(V+U)));M(tt)}catch{}};Y();let he=null;try{he=new ResizeObserver(()=>Y()),he.observe(R)}catch{}return window.addEventListener("resize",Y),window.addEventListener("notes-grid:recalc",Y),()=>{try{he&&he.disconnect()}catch{}window.removeEventListener("resize",Y),window.removeEventListener("notes-grid:recalc",Y)}},[]);const We=b.useRef(null),{token:Se,user:Xe}=Sr(),Tt=B.useMemo(()=>{try{const R=xe.map(U=>Number(U.id)).filter(U=>Number.isFinite(U));return ct!=="collections"?"":R.join(",")}catch{return""}},[xe,ct]);B.useEffect(()=>{if(!Se||!xe.length)return;const R=Tt?Tt.split(",").map(he=>Number(he)).filter(he=>Number.isFinite(he)):[];if(!R.length)return;let U=!1;const Y=new AbortController;return(async()=>{try{const he=R.filter(V=>!At[V]);if(!he.length)return;const $=await Promise.all(he.map(async V=>{var pe,tt;try{const Ft=await fetch(`/api/collections/${V}/breadcrumb`,{headers:{Authorization:Se?`Bearer ${Se}`:""},signal:Y.signal});if(!Ft.ok)throw new Error(await Ft.text());const Kt=await Ft.json(),sn=(Array.isArray(Kt==null?void 0:Kt.breadcrumb)?Kt.breadcrumb:[]).map(A=>String((A==null?void 0:A.name)||"")).filter(Boolean).join(" / ");return[V,sn||((pe=xe.find(A=>Number(A.id)===V))==null?void 0:pe.name)||String(V)]}catch{return[V,((tt=xe.find(Ft=>Number(Ft.id)===V))==null?void 0:tt.name)||String(V)]}}));if(U)return;const S={};for(const[V,pe]of $)S[Number(V)]=String(pe||"");Vt(V=>({...V,...S}))}catch{}})(),()=>{U=!0;try{Y.abort()}catch{}}},[Se,xe,Tt,At]);const rt=B.useMemo(()=>new Fi,[t.id]),Wt=B.useRef(null),Mt=B.useRef(null);B.useEffect(()=>{const R=`note-${t.id}`,Y=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/collab`,he=new mf(Y,R,rt);Wt.current=he;const $=rt.getArray("checklist");Mt.current=$;const S=()=>{try{if($.length===0)return;const V=$.toArray().map(pe=>({id:typeof pe.get("id")=="number"?Number(pe.get("id")):void 0,content:String(pe.get("content")||""),checked:!!pe.get("checked"),indent:Number(pe.get("indent")||0)}));z(V)}catch{}};return $.observeDeep(S),he.on("sync",V=>{V&&S()}),()=>{try{$.unobserveDeep(S)}catch{}try{he.destroy()}catch{}}},[t.id,rt]),B.useEffect(()=>{if(t.type!=="TEXT"){ge(null);return}let R=null;try{R=new ag({extensions:[ta.configure({heading:{levels:[1,2,3]}}),wR.configure({openOnClick:!1,autolink:!0}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:rt})],content:""});const U=()=>{try{const $=(R==null?void 0:R.getHTML())||"",S=ka.sanitize($,{USE_PROFILES:{html:!0}});ge(S)}catch{}};R.on("update",U);const Y=Wt.current,he=$=>{$&&U()};return Y==null||Y.on("sync",he),()=>{try{R==null||R.destroy()}catch{}try{Y==null||Y.off("sync",he)}catch{}}}catch{}},[t.id,t.type,rt]);function dn(){const R=t.body||"",U=$=>$.replace(/&/g,"&").replace(//g,">"),Y=($,S)=>!S||!S.length?U($):S.reduce((V,pe)=>{var tt;switch(pe.type){case"bold":return`${V}`;case"italic":return`${V}`;case"underline":return`${V}`;case"link":{const Ft=typeof((tt=pe.attrs)==null?void 0:tt.href)=="string"?pe.attrs.href:"#";return`${V}`}default:return V}},U($)),he=($,S=!1)=>{var tt;if(!$)return"";if(Array.isArray($))return $.map(Ft=>he(Ft,S)).join("");const V=$.type;if(V==="text")return Y($.text||"",$.marks);if(V==="hardBreak")return"
";if((V==="paragraph"||V==="heading")&&(!$.content||$.content.length===0))return S?"":"

";const pe=$.content?he($.content,V==="listItem"):"";switch(V){case"paragraph":return`

${pe}

`;case"heading":{const Ft=Math.min(6,Math.max(1,Number(((tt=$.attrs)==null?void 0:tt.level)||1)));return`${pe}`}case"bulletList":return`
    ${pe}
`;case"orderedList":return`
    ${pe}
`;case"listItem":return`
  • ${pe.replace(/^

    |<\/p>$/g,"")}

  • `;case"blockquote":return`
    ${pe}
    `;case"codeBlock":return`
    ${U($.textContent||"")}
    `;default:return pe}};try{const $=JSON.parse(R),S=he($);return ka.sanitize(S,{USE_PROFILES:{html:!0}})}catch{const $=U(R).replace(/\n/g,"
    ");return ka.sanitize(`

    ${$}

    `)}}B.useEffect(()=>{const R=t.viewerColor||t.color||"";m(R||""),y(R?Fs(R):void 0)},[t.id,t.viewerColor,t.color]),B.useEffect(()=>{se((t.noteLabels||[]).map(R=>R.label).filter(R=>R&&typeof R.id=="number"&&typeof R.name=="string"))},[t.noteLabels]),B.useEffect(()=>{L(t.title||"")},[t.title]),B.useEffect(()=>{E((t.images||[]).map(R=>({id:Number(R.id),url:String(R.url)})))},[t.images]),B.useEffect(()=>{try{const R=(t.collaborators||[]).map(U=>{const Y=U&&(U.user||{});if(Y&&typeof Y.id=="number"&&typeof Y.email=="string"){const he=typeof Y.userImageUrl=="string"?String(Y.userImageUrl):typeof U.userImageUrl=="string"?String(U.userImageUrl):void 0;return{collabId:Number(U.id),userId:Number(Y.id),email:String(Y.email),name:typeof Y.name=="string"?String(Y.name):void 0,userImageUrl:he}}return null}).filter(Boolean);me(R)}catch{}},[t.collaborators]),B.useRef(null),B.useRef(!1);async function It(R){const U=R||"";try{const Y=await fetch(`/api/notes/${t.id}/prefs`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({color:U})});if(!Y.ok)throw new Error(await Y.text())}catch(Y){console.error("Failed to save color preference",Y),window.alert("Failed to save color preference")}U?(m(U),y(Fs(U))):(m(""),y("var(--muted)"));try{W(U)}catch{}ae(!1)}function Ot(R){Ke(!1),R&&(async()=>{try{const U=await fetch(`/api/notes/${t.id}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({url:R})});if(!U.ok)throw new Error(await U.text());const he=(await U.json()).image||null;he&&he.id&&he.url&&te($=>$.some(V=>Number(V.id)===Number(he.id))?$:[...$,{id:Number(he.id),url:String(he.url)}])}catch(U){console.error("Failed to attach image",U),te(Y=>Y.some($=>String($.url)===String(R))?Y:[...Y,{id:Date.now(),url:R}]),window.alert("Failed to attach image to server; showing locally")}})()}async function tn(R,U){const Y=Mt.current;if(Y){const he=Y.toArray().findIndex($=>typeof $.get("id")=="number"?Number($.get("id"))===R:!1);if(he>=0){const $=Y.get(he);if($.set("checked",U),Number($.get("indent")||0)===0)for(let V=he+1;V0)pe.set("checked",U);else break}return}}try{const he=await fetch(`/api/notes/${t.id}/items/${R}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se}`},body:JSON.stringify({checked:U})});if(!he.ok)throw new Error(await he.text());z($=>$.map(S=>S.id===R?{...S,checked:U}:S))}catch(he){console.error(he),window.alert("Failed to update checklist item — please try again.")}}function ee(R){Pe(!1),R&&window.alert(`Reminder set (UI-only): ${R}`)}function re(){const R=!v;w(R),fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({archived:R})}).then(()=>e&&e()).catch(U=>{console.error(U),window.alert("Failed to archive note")})}async function Oe(){var R;try{const U=typeof((R=t.owner)==null?void 0:R.id)=="number"?Number(t.owner.id):void 0,Y=Xe&&Xe.id?Number(Xe.id):void 0;if(U&&Y&&U!==Y){const $=Ae.find(S=>typeof S.userId=="number"&&S.userId===Y);if($&&typeof $.collabId=="number"){const S=await fetch(`/api/notes/${t.id}/collaborators/${$.collabId}`,{method:"DELETE",headers:{Authorization:Se?`Bearer ${Se}`:""}});if(!S.ok)throw new Error(await S.text());e&&e();return}window.alert("You are not the owner and could not find your collaborator entry to remove.");return}const he=await fetch(`/api/notes/${t.id}`,{method:"DELETE",headers:{Authorization:Se?`Bearer ${Se}`:""}});if(!he.ok)throw new Error(await he.text());e&&e()}catch(U){console.error(U),window.alert("Failed to delete or leave note")}}const[Ze,fe]=b.useState(!1);function Ce(){fe(!0)}async function Fe(){try{const R=(N||[]).map((Y,he)=>({id:Y.id,content:Y.content,checked:!1,ord:typeof Y.ord=="number"?Y.ord:he,indent:typeof Y.indent=="number"?Y.indent:0}));z(R);const U=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({items:R})});if(!U.ok)throw new Error(await U.text())}catch(R){console.error(R),window.alert("Failed to uncheck all items")}}async function ut(){try{const R=(N||[]).map((Y,he)=>({id:Y.id,content:Y.content,checked:!0,ord:typeof Y.ord=="number"?Y.ord:he,indent:typeof Y.indent=="number"?Y.indent:0}));z(R);const U=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({items:R})});if(!U.ok)throw new Error(await U.text())}catch(R){console.error(R),window.alert("Failed to check all items")}}function zt(R){me(U=>U.find(Y=>Y.userId===R.id)?U:[...U,{userId:R.id,email:R.email,name:R.name,userImageUrl:R.userImageUrl}]),ue(!1),(async()=>{try{const U=await fetch(`/api/notes/${t.id}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({email:R.email})});if(!U.ok)throw new Error(await U.text());const Y=await U.json(),he=Y&&(Y.collaborator||null);he&&typeof he.id=="number"&&me($=>$.map(S=>S.userId===R.id?{...S,collabId:Number(he.id)}:S))}catch(U){console.error("Failed to add collaborator",U),window.alert("Failed to add collaborator"),me(Y=>Y.filter(he=>he.userId!==R.id))}})()}async function kt(R){try{const U=await fetch(`/api/notes/${t.id}/collaborators/${R}`,{method:"DELETE",headers:{Authorization:Se?`Bearer ${Se}`:""}});if(!U.ok)throw new Error(await U.text());me(Y=>Y.filter(he=>he.collabId!==R)),e&&e()}catch(U){console.error("Failed to remove collaborator",U),window.alert("Failed to remove collaborator")}}async function Jt(R){try{const U=await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({cardSpan:R})});if(!U.ok)throw new Error(await U.text());try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}e&&e()}catch(U){console.error("Failed to set card width",U),window.alert("Failed to set card width")}}const jt=(()=>{const R=(p||"").toLowerCase().trim(),U=new Set(["#1e1e1e","#121212","#181818","#1c1c1c","#161616"]),Y=new Set(["#ffffff","#fff"]);return f.effective==="light"&&U.has(R)||f.effective==="dark"&&Y.has(R)?"":p})(),fn=jt?Fs(jt):void 0,wn=fn==="#ffffff"||fn==="var(--muted)"?"rgba(0,0,0,0.12)":"rgba(255,255,255,0.06)",nn=[];try{const R=Xe&&Xe.id?Number(Xe.id):void 0,U=t.owner||null;if(U&&typeof U.id=="number"&&U.id!==R){const Y=typeof U.name=="string"&&U.name?U.name:String(U.email||"").split("@")[0];nn.push({key:`owner-${U.id}`,userId:Number(U.id),name:Y,email:String(U.email||""),userImageUrl:typeof U.userImageUrl=="string"?String(U.userImageUrl):void 0})}for(const Y of Ae)if(typeof Y.userId=="number"&&Y.userId!==R){const he=Y.name&&Y.name.length?Y.name:String(Y.email).split("@")[0];nn.push({key:Y.collabId||`u-${Y.userId}`,userId:Number(Y.userId),name:he,email:Y.email,userImageUrl:Y.userImageUrl})}}catch{}const rn={background:jt||void 0,color:fn||void 0,opacity:v?.6:1,position:"relative","--chip-bg":wn};return jt&&(rn["--checkbox-bg"]=jt,rn["--checkbox-border"]=Fs(jt),rn["--checkbox-stroke"]=Fs(jt),rn["--checkbox-checked-bg"]=jt,rn["--checkbox-checked-mark"]=Fs(jt)),h.jsxs("article",{ref:R=>{o.current=R},className:`note-card${q.length>0?" has-labels":""}${xe.length>0?" has-collections":""}${N&&N.length>0?" has-checklist":""}`,style:rn,...X?{}:i||{},...X?{}:(()=>{const R=s||{},{onKeyDown:U,...Y}=R;return Y})(),"data-clipped":De?"1":void 0,onClick:R=>{const U=R.target;je(U)||G()},children:[h.jsx("input",{ref:We,type:"file",accept:"image/*",style:{display:"none"}}),X&&h.jsx("div",{className:"note-title",...i||{},...(()=>{const R=s||{},{onKeyDown:U,...Y}=R;return Y})(),style:{cursor:"pointer"},onClick:()=>{G()},role:"button",tabIndex:0,onKeyDown:R=>{try{const U=s==null?void 0:s.onKeyDown;typeof U=="function"&&U(R)}catch{}R.defaultPrevented||(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),G())},children:X}),(()=>{if(!(nn.length>0||q.length>0||xe.length>0))return null;const U=`note-meta-panel-${Number(t.id)}`,Y=xe.map($=>({...$,path:At[Number($.id)]||String($.name||"")})).sort(($,S)=>String($.path).localeCompare(String(S.path))),he=()=>{Le||nt(null)};return h.jsxs("div",{className:`note-meta${ct?" is-expanded":""}`,onPointerDown:$=>{$.stopPropagation()},onClick:$=>{$.stopPropagation()},onMouseLeave:he,onBlurCapture:$=>{const S=$.relatedTarget;S&&$.currentTarget.contains(S)||nt(null)},children:[h.jsxs("div",{className:"note-meta-bar",children:[nn.length>0&&h.jsxs("button",{type:"button",className:`chip chip--meta${ct==="collab"?" is-active":""}`,"aria-expanded":ct==="collab","aria-controls":U,title:"Collaborators",onMouseEnter:()=>{Le||nt("collab")},onFocus:$=>{var S,V;try{if(!((V=(S=$.currentTarget)==null?void 0:S.matches)==null?void 0:V.call(S,":focus-visible")))return}catch{}nt("collab")},onClick:$=>{$.stopPropagation(),nt(S=>S==="collab"?null:"collab")},children:[h.jsx(Xs,{icon:c9,className:"meta-fa-icon"}),h.jsx("span",{children:nn.length})]}),q.length>0&&h.jsxs("button",{type:"button",className:`chip chip--meta${ct==="labels"?" is-active":""}`,"aria-expanded":ct==="labels","aria-controls":U,title:"Labels",onMouseEnter:()=>{Le||nt("labels")},onFocus:$=>{var S,V;try{if(!((V=(S=$.currentTarget)==null?void 0:S.matches)==null?void 0:V.call(S,":focus-visible")))return}catch{}nt("labels")},onClick:$=>{$.stopPropagation(),nt(S=>S==="labels"?null:"labels")},children:[h.jsx(Xs,{icon:d9,className:"meta-fa-icon"}),h.jsx("span",{children:q.length})]}),xe.length>0&&h.jsxs("button",{type:"button",className:`chip chip--meta chip--meta-collections${ct==="collections"?" is-active":""}`,"aria-expanded":ct==="collections","aria-controls":U,title:`${xe.length} collections`,onMouseEnter:()=>{Le||nt("collections")},onFocus:$=>{var S,V;try{if(!((V=(S=$.currentTarget)==null?void 0:S.matches)==null?void 0:V.call(S,":focus-visible")))return}catch{}nt("collections")},onClick:$=>{$.stopPropagation(),nt(S=>S==="collections"?null:"collections")},children:[h.jsx(Xs,{icon:u9,className:"meta-fa-icon"}),h.jsx("span",{children:xe.length})]})]}),h.jsxs("div",{id:U,className:`note-meta-panel${ct?" is-open":""}`,role:"region","aria-label":"Note metadata",children:[ct==="collab"&&h.jsx("div",{className:"collab-chips","aria-label":"Collaborators",children:nn.map($=>{const S=(Xe==null?void 0:Xe.chipDisplayMode)||"image+text",V=(S==="image"||S==="image+text")&&!!$.userImageUrl,pe=S==="text"||S==="image+text";return h.jsxs("button",{type:"button",className:"chip",title:$.email,style:{display:"inline-flex",alignItems:"center",gap:6},onClick:tt=>{tt.stopPropagation();try{e==null||e({type:"filter:collaborator",noteId:Number(t.id),userId:Number($.userId),name:String($.name||"")})}catch{}},children:[V?h.jsx("img",{src:$.userImageUrl,alt:"",style:{width:18,height:18,borderRadius:"50%",objectFit:"cover"}}):null,pe?h.jsx("span",{children:$.name}):null]},$.key)})}),ct==="labels"&&h.jsx("div",{className:"label-chips","aria-label":"Labels",children:q.map($=>h.jsx("button",{type:"button",className:"chip",onClick:S=>{S.stopPropagation();try{e==null||e({type:"filter:labels",noteId:Number(t.id),labelId:Number($.id),labelName:String($.name||"")})}catch{}},children:$.name},$.id))}),ct==="collections"&&h.jsx("div",{className:"note-collections","aria-label":"Collections",children:h.jsx("div",{className:"note-collections-list",role:"list",children:Y.map($=>h.jsx("button",{type:"button",className:"chip note-collection-chip",title:$.path,onClick:S=>{S.stopPropagation();try{e==null||e({type:"filter:collection",noteId:Number(t.id),collectionId:Number($.id),collectionName:String($.name||"")})}catch{}},children:$.path},$.id))})})]})]})})(),h.jsx("div",{className:"note-body",ref:l,onClick:()=>{G()},children:N&&N.length>0?h.jsxs("div",{children:[h.jsx("div",{className:"note-items-list",children:N.filter(R=>!R.checked).map((R,U)=>h.jsxs("div",{className:"note-item",style:{display:"flex",gap:8,alignItems:j,marginLeft:(R.indent||0)*16},children:[h.jsx("button",{className:`note-checkbox ${R.checked?"checked":""}`,type:"button",onClick:Y=>{Y.stopPropagation(),tn(R.id,!R.checked)},"aria-pressed":!!R.checked,style:{background:"var(--checkbox-bg)",border:"2px solid var(--checkbox-border)",color:"var(--checkbox-stroke)"},children:R.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{className:"note-item-text",children:h.jsx("div",{className:"rt-html",dangerouslySetInnerHTML:{__html:ka.sanitize(String(R.content||""),{USE_PROFILES:{html:!0}})}})})]},typeof R.id=="number"?R.id:`i-${U}`))}),N.some(R=>R.checked)&&h.jsx("div",{style:{marginTop:6},children:h.jsx("button",{className:"btn completed-toggle",onClick:R=>{R.stopPropagation(),Ge(U=>!U)},"aria-expanded":Ye,"aria-controls":`completed-${t.id}`,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:Ye?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:[N.filter(R=>R.checked).length," completed items"]})]})})}),Ye&&N.some(R=>R.checked)&&h.jsx("div",{className:"note-items-list",style:{marginTop:6},children:N.filter(R=>R.checked).map((R,U)=>h.jsxs("div",{className:"note-item completed",style:{display:"flex",gap:8,alignItems:j,marginLeft:(R.indent||0)*16,opacity:.7},children:[h.jsx("button",{className:`note-checkbox ${R.checked?"checked":""}`,type:"button",onClick:Y=>{Y.stopPropagation(),tn(R.id,!R.checked)},"aria-pressed":!!R.checked,style:{background:"var(--checkbox-bg)",border:"2px solid var(--checkbox-border)",color:"var(--checkbox-stroke)"},children:R.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{className:"note-item-text",style:{textDecoration:"line-through"},children:h.jsx("div",{className:"rt-html",dangerouslySetInnerHTML:{__html:ka.sanitize(String(R.content||""),{USE_PROFILES:{html:!0}})}})})]},`c-${typeof R.id=="number"?R.id:U}`))})]}):K||t.body?h.jsx("div",{className:"note-html",dangerouslySetInnerHTML:{__html:K||dn()}}):null}),x&&x.length>0&&h.jsx("div",{className:"note-images",ref:a,children:(()=>{const R=Math.max(1,k)*3,U=x.slice(0,Math.min(x.length,R)),Y=Math.max(0,x.length-R);return U.map((he,$)=>h.jsxs("button",{className:"note-image",style:{padding:0,border:"none",background:"transparent",cursor:"pointer"},onClick:()=>{G()},children:[h.jsx("img",{src:he.url,alt:"note image"}),Y>0&&$===U.length-1&&h.jsxs("span",{className:"note-image-moreOverlay","aria-label":`${Y} more images`,children:["+",Y," more"]})]},he.id))})()}),h.jsx("div",{className:"footer-hover-zone","aria-hidden":!0}),h.jsx("div",{className:"note-footer","aria-hidden":!1,children:h.jsxs("div",{className:"note-actions",children:[h.jsx("button",{className:"tiny palette",onClick:()=>ae(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>Pe(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>ue(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Ke(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),h.jsx("button",{className:"tiny",onClick:re,"aria-label":"Archive",title:"Archive",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M20.54 5.23L19.4 4H4.6L3.46 5.23 3 6v2h18V6l-.46-.77zM6 10v9h12V10H6zm3 2h6v2H9v-2z"})})}),h.jsx("button",{className:"tiny",onClick:R=>{R.stopPropagation(),J({x:R.clientX,y:R.clientY}),Je(U=>!U)},"aria-label":"More",title:"More",children:"⋮"})]})}),Q&&h.jsx(Hx,{anchorRef:o,anchorPoint:_t,itemsCount:5,onClose:()=>Je(!1),onDelete:Oe,onMoveToCollection:()=>$t(!0),onAddLabel:Ce,onUncheckAll:Fe,onCheckAll:ut,onSetWidth:Jt}),at&&h.jsx(BJ,{noteId:Number(t.id),onClose:()=>$t(!1),onChanged:R=>{try{const U=Array.isArray(R)?R.map(Y=>({id:Number(Y.id),name:String(Y.name||""),parentId:Y.parentId==null?null:Number(Y.parentId)})).filter(Y=>Number.isFinite(Y.id)&&Y.name.length):[];Me(U)}catch{}try{e==null||e({type:"collections",noteId:Number(t.id),collections:R})}catch{}}}),Ze&&h.jsx(UJ,{noteId:t.id,onClose:()=>fe(!1),onUpdated:R=>{se(R);try{e==null||e({type:"labels",noteId:t.id,labels:R})}catch{}}}),ce&&h.jsx(xc,{onClose:()=>ue(!1),onSelect:zt,current:(()=>{const R=[],U=Xe&&Xe.id?Number(Xe.id):void 0,Y=t.owner||null;Y&&typeof Y.id=="number"&&Y.id!==U&&R.push({userId:Number(Y.id),email:String(Y.email||""),name:typeof Y.name=="string"?Y.name:void 0,userImageUrl:typeof Y.userImageUrl=="string"?String(Y.userImageUrl):void 0});for(const he of Ae)typeof he.userId=="number"&&R.push({collabId:he.collabId,userId:he.userId,email:he.email,name:he.name,userImageUrl:he.userImageUrl});return R})(),ownerId:typeof((Pr=t.owner)==null?void 0:Pr.id)=="number"?Number(t.owner.id):Xe==null?void 0:Xe.id,onRemove:kt}),wt&&h.jsx(ef,{anchorRef:o,onPick:It,onClose:()=>ae(!1)}),Ee&&h.jsx(nf,{onClose:()=>Ke(!1),onAdd:Ot}),ze&&h.jsx(tf,{onClose:()=>Pe(!1),onSet:ee}),it&&h.jsx(Xq,{note:{...t,items:N,images:x},noteBg:p,onColorChanged:R=>{try{const U=String(R||"");m(U),y(U?Fs(U):"var(--muted)"),W(U)}catch{}},onClose:()=>ot(!1),onSaved:({items:R,title:U})=>{z(R),L(U)},onImagesUpdated:R=>{te(()=>R)},moreMenu:{onDelete:Oe,onAddLabel:Ce,onMoveToCollection:()=>$t(!0),onUncheckAll:Fe,onCheckAll:ut,onSetWidth:Jt}}),xt&&h.jsx(FJ,{note:{...t,images:x},noteBg:p,onColorChanged:R=>{try{const U=String(R||"");m(U),y(U?Fs(U):"var(--muted)"),W(U)}catch{}},onClose:()=>oe(!1),onSaved:({title:R,body:U})=>{L(R),t.body=U},onImagesUpdated:R=>{te(()=>R)},moreMenu:{onDelete:Oe,onAddLabel:Ce,onMoveToCollection:()=>$t(!0),onSetWidth:Jt}})]})}function Nj(t){if(/^wss?:\/\//i.test(t))return t;const e=t.startsWith("/")?t:`/${t}`;return typeof window>"u"||!window.location?`ws://localhost${e}`:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}${e}`}function HJ({onCreated:t,openRequest:e,activeCollection:n}){const{token:r,user:i}=Sr(),[s,o]=b.useState(!1),[l,a]=b.useState("text"),[c,u]=b.useState(""),[d,f]=b.useState(""),[p,m]=b.useState(!1),g=pg({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),yg,mn.create({name:"paragraphEnterFix",priority:1e3,addKeyboardShortcuts(){return{"Shift-Enter":()=>{const j=this.editor;return j.commands.splitBlock(),j.commands.setParagraph(),!0},"Mod-Enter":()=>{const j=this.editor;return j.commands.splitBlock(),j.commands.setParagraph(),!0}}}})],content:"",editorProps:{attributes:{class:"rt-editor"}}});function y(){try{const j=window.matchMedia;if(!j)return!1;const G=j("(pointer: coarse)").matches||j("(any-pointer: coarse)").matches,de=j("(max-width: 720px)").matches;return!!(G&&de)}catch{return!1}}const v=b.useRef("");if(!v.current)try{v.current=`take-note-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{v.current=`take-note-${Math.random()}`}function w(j){if(!g)return;const G=g.state.selection;if(!G||!G.empty){g.chain().focus()[`toggle${j.charAt(0).toUpperCase()+j.slice(1)}`]().run();return}const de=G.$from;let je=de.depth;for(;je>0&&!de.node(je).isBlock;)je--;const Ue=de.start(je),We=de.end(je),Se=g.chain().focus().setTextSelection({from:Ue,to:We});j==="bold"?Se.toggleBold().run():j==="italic"?Se.toggleItalic().run():Se.toggleUnderline().run();try{g.chain().setTextSelection(G.from).run()}catch{}}const[,x]=b.useState(0);b.useEffect(()=>{if(!g)return;const j=()=>x(G=>G+1);return g.on("selectionUpdate",j),g.on("transaction",j),()=>{g.off("selectionUpdate",j),g.off("transaction",j)}},[g]);const E=b.useRef(!1),k=b.useRef(0),M=n&&Number.isFinite(Number(n.id))?Number(n.id):null,N=n&&typeof n.path=="string"?String(n.path):"",[z,X]=b.useState(!1);b.useEffect(()=>{const j=Number((e==null?void 0:e.nonce)||0);if(!j||j===k.current)return;k.current=j;const G=(e==null?void 0:e.mode)||"text";a(G);try{E.current=!0}catch{}try{X(M!=null)}catch{}o(!0),m(y()),G==="checklist"?(W(de=>de&&de.length?de:[{content:""}]),setTimeout(()=>De(0),30)):requestAnimationFrame(()=>{try{g==null||g.commands.focus("end")}catch{}})},[e==null?void 0:e.nonce,e==null?void 0:e.mode,g]);const L=b.useRef(!1);b.useEffect(()=>{try{s&&!L.current&&(L.current=!0,window.dispatchEvent(new Event("freemannotes:editor-modal-open"))),!s&&L.current&&(L.current=!1,window.dispatchEvent(new Event("freemannotes:editor-modal-close")))}catch{}},[s]),b.useEffect(()=>{if(!s)return;const j=v.current,G=()=>{try{const de=Pe.current;if(de.showImageDialog){wt(!1);return}if(de.showCollaborator){At(!1);return}if(de.showReminderPicker){ct(!1);return}if(de.showPalette){at(!1);return}}catch{}try{Ye()}catch{try{Ye()}catch{}}};try{window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:j,onBack:G}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:j}}))}catch{}}},[s]);const[H,W]=b.useState([]),[te,ce]=b.useState(!1),ue=b.useRef(null),Ae=b.useRef(null),me=b.useRef(null),q=b.useRef([]),[,se]=b.useState(0),xe=b.useRef(!1),[Me,Q]=b.useState(""),[Je,_t]=b.useState(void 0),[J,at]=b.useState(!1),[$t,ct]=b.useState(!1),[nt,At]=b.useState(!1),[Vt,wt]=b.useState(!1),[ae,Ee]=b.useState(null),[Ke,ze]=b.useState([]),Pe=b.useRef({showPalette:!1,showReminderPicker:!1,showCollaborator:!1,showImageDialog:!1});b.useEffect(()=>{Pe.current={showPalette:J,showReminderPicker:$t,showCollaborator:nt,showImageDialog:Vt}},[J,$t,nt,Vt]);function it(){var de;let j=me.current;if(j&&j.isFocused)return j;const G=typeof document<"u"&&((de=document.getSelection())==null?void 0:de.anchorNode)||null;if(G){const je=q.current.find(Ue=>{var We;try{return!!(Ue&&((We=Ue.view)!=null&&We.dom)&&Ue.view.dom.contains(G))}catch{return!1}});je&&(j=je)}else{const je=typeof document<"u"?document.activeElement:null;if(je){const Ue=q.current.find(We=>{try{return!!(We&&We.view&&We.view.dom&&(We.view.dom===je||We.view.dom.contains(je)))}catch{return!1}});Ue&&(j=Ue)}}if(!j||!(j!=null&&j.isFocused)){const je=q.current.find(Ue=>!!(Ue&&Ue.isFocused));je&&(j=je)}return j||null}function ot(j){var Tt;const G=it();if(!G)return;const de=(Tt=G.state)==null?void 0:Tt.selection;if(!de||!de.empty){const rt=G.chain().focus();j==="bold"?rt.toggleBold().run():j==="italic"?rt.toggleItalic().run():rt.toggleUnderline().run();try{const Wt=de==null?void 0:de.from;requestAnimationFrame(()=>{try{const Mt=G.chain().focus();typeof Wt=="number"&&Mt.setTextSelection(Wt),Mt.run()}catch{}})}catch{}return}const je=de.$from;let Ue=je.depth;for(;Ue>0&&!je.node(Ue).isBlock;)Ue--;const We=je.start(Ue),Se=je.end(Ue),Xe=G.chain().focus().setTextSelection({from:We,to:Se});j==="bold"?Xe.toggleBold().run():j==="italic"?Xe.toggleItalic().run():Xe.toggleUnderline().run();try{G.chain().focus().setTextSelection(de.from).run()}catch{}try{const rt=de.from;requestAnimationFrame(()=>{var Wt,Mt;try{try{(Mt=(Wt=G.view)==null?void 0:Wt.focus)==null||Mt.call(Wt)}catch{}G.chain().focus().setTextSelection(rt).run()}catch{}})}catch{}try{se(rt=>rt+1)}catch{}}function xt(j){var Wt,Mt;const G=it();if(!G)return!1;const de=(Wt=G.state)==null?void 0:Wt.selection;if(!de)return!1;const je=(((Mt=G.schema)==null?void 0:Mt.marks)||{})[j];if(!je)return!1;const Ue=de.$from;let We=Ue.depth;for(;We>0&&!Ue.node(We).isBlock;)We--;const Se=Ue.start(We),Xe=Ue.end(We);let Tt=!1,rt=!0;try{G.state.doc.nodesBetween(Se,Xe,dn=>{dn&&dn.isText&&(Tt=!0,je.isInSet(dn.marks)||(rt=!1))})}catch{}return Tt&&rt}function oe(){try{const j=!!c.trim(),G=!!Me,de=!!(ae||Ke&&Ke.length);if(l==="checklist"){const Ue=(H||[]).some(We=>!!String(We.content||"").trim()||!!We.checked);return j||G||de||Ue}const je=!!((g==null?void 0:g.getText())||"").trim();return j||G||de||je}catch{return!1}}function Ye(){try{o(!1)}catch{}try{m(!1)}catch{}try{at(!1)}catch{}try{ct(!1)}catch{}try{At(!1)}catch{}try{wt(!1)}catch{}try{u(""),f(""),W([]),Q(""),Ee(null),ze([])}catch{}try{g==null||g.commands.clearContent()}catch{}}b.useEffect(()=>{function j(de){var rt,Wt,Mt,dn,It;if(!s)return;if(E.current){E.current=!1;return}if(de.defaultPrevented)return;const je=ue.current;if(!je)return;const Ue=de.target,We=(rt=document.querySelector(".palette-popover"))==null?void 0:rt.contains(Ue),Se=(Wt=document.querySelector(".reminder-popover"))==null?void 0:Wt.contains(Ue),Xe=(Mt=document.querySelector(".collab-modal"))==null?void 0:Mt.contains(Ue),Tt=(dn=document.querySelector(".image-dialog"))==null?void 0:dn.contains(Ue);if(!(We||Se||Xe||Tt)){try{if((((It=de.composedPath)==null?void 0:It.call(de))||[]).includes(je))return}catch{}de.target instanceof Node&&je.contains(de.target)||Ye()}}function G(de){s&&de.key==="Escape"&&Ye()}return document.addEventListener("click",j),document.addEventListener("keydown",G),()=>{document.removeEventListener("click",j),document.removeEventListener("keydown",G)}},[s]);function Ge(j){if(!j)return;const G=j.replace("#",""),de=G.length===3?G.split("").map(Ot=>Ot+Ot).join(""):G;if(de.length!==6)return;const je=parseInt(de.slice(0,2),16)/255,Ue=parseInt(de.slice(2,4),16)/255,We=parseInt(de.slice(4,6),16)/255,Se=Ot=>Ot<=.03928?Ot/12.92:Math.pow((Ot+.055)/1.055,2.4),Xe=Se(je),Tt=Se(Ue),rt=Se(We),Wt=.2126*Xe+.7152*Tt+.0722*rt,Mt=(Ot,tn)=>(Math.max(Ot,tn)+.05)/(Math.min(Ot,tn)+.05),dn=Mt(1,Wt),It=Mt(0,Wt);return dn>=It?"#ffffff":"#000000"}b.useEffect(()=>{_t(Me?Ge(Me):"var(--muted)")},[Me]);function K(j,G){W(de=>de.map((je,Ue)=>Ue===j?{...je,content:G}:je))}function ge(j){W(G=>G.map((de,je)=>je===j?{...de,checked:!de.checked}:de))}function De(j){setTimeout(()=>{const G=q.current[j];try{G&&G.chain().focus().run()}catch{}},30)}async function Be(){var j;ce(!0);try{if(!r)throw new Error("Not authenticated");const G=l==="text"?(g==null?void 0:g.getJSON())||{}:{},de={title:c,body:null,type:l==="checklist"?"CHECKLIST":"TEXT",color:Me||null};l==="checklist"&&(de.items=H.map((Se,Xe)=>({content:Se.content,ord:Xe})));const je=await fetch("/api/notes",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(de)});if(!je.ok)throw new Error(await je.text());const Ue=await je.json(),We=(j=Ue==null?void 0:Ue.note)==null?void 0:j.id;if(We&&z&&M!=null)try{const Se=await fetch(`/api/notes/${We}/collections`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({collectionId:M})});if(!Se.ok)throw new Error(await Se.text())}catch(Se){console.warn("Created note but failed to add to collection",Se);try{window.alert("Note created, but failed to add it to the current collection.")}catch{}}if(We&&l==="text")try{const Se=new Fi,Xe=`note-${We}`,Tt=new mf(Nj("/collab"),Xe,Se),rt=new ag({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:Se})],content:""});await new Promise(Wt=>{Tt.on("sync",Mt=>{Mt&&Wt()})});try{rt==null||rt.commands.setContent(G)}catch{}await new Promise(Wt=>setTimeout(Wt,100));try{rt==null||rt.destroy()}catch{}try{Tt.destroy()}catch{}try{Se.destroy()}catch{}try{await fetch(`/api/notes/${We}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({body:JSON.stringify(G),type:"TEXT"})})}catch{}}catch(Se){console.warn("Failed to seed Yjs content for new note",Se)}if(We&&Ke.length)for(const Se of Ke)try{await fetch(`/api/notes/${We}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({email:Se.email})})}catch{}if(We&&ae)try{await fetch(`/api/notes/${We}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({url:ae})})}catch{}u(""),f(""),W([]),o(!1),Q(""),Ee(null),ze([]);try{X(M!=null)}catch{}g==null||g.commands.clearContent(),t&&t()}catch(G){console.error("Failed to create note",G),window.alert("Failed to create note")}finally{ce(!1)}}if(!s)return h.jsx("div",{ref:ue,children:h.jsxs("div",{className:"take-note-bar",role:"button",tabIndex:0,onMouseDown:j=>{try{j.preventDefault()}catch{}try{j.stopPropagation()}catch{}E.current=!0;try{X(M!=null)}catch{}a("text"),o(!0)},onClick:j=>{try{j.preventDefault()}catch{}try{j.stopPropagation()}catch{}E.current=!0;try{X(M!=null)}catch{}a("text"),o(!0)},onKeyDown:j=>{if(j.key==="Enter"||j.key===" "){j.preventDefault(),E.current=!0;try{X(M!=null)}catch{}a("text"),o(!0)}},children:[h.jsx("div",{style:{flex:1,padding:"10px 12px"},children:"Create a new note"}),h.jsx("div",{className:"checkbox-visual",onMouseDown:j=>{j.stopPropagation()},onClick:j=>{j.stopPropagation(),E.current=!0;try{X(M!=null)}catch{}a("checklist"),W([{content:""}]),o(!0),De(0)},"aria-label":"Start checklist",children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})})]})});const Le={};return Me&&(Le.background=Me,Le["--checkbox-bg"]=Me,Le["--checkbox-border"]="#ffffff",Le["--checkbox-checked-bg"]=Me,Le["--checkbox-checked-mark"]="#ffffff",Le["--editor-surface"]=Me),h.jsxs("div",{className:`take-note-expanded${p?" maximized":""}`,ref:ue,style:{padding:12,...Le},children:[l==="text"?h.jsxs("div",{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:h.jsx("input",{placeholder:"Title",value:c,onChange:j=>u(j.target.value),style:{fontSize:18,fontWeight:600,border:"none",background:"transparent",color:"inherit"}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:8,marginBottom:0,overflowX:"auto"},children:[h.jsx("button",{className:"tiny",onClick:()=>w("bold"),"aria-pressed":g==null?void 0:g.isActive("bold"),children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>w("italic"),"aria-pressed":g==null?void 0:g.isActive("italic"),children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>w("underline"),"aria-pressed":g==null?void 0:g.isActive("underline"),children:"U"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleHeading({level:1}).run(),"aria-pressed":g==null?void 0:g.isActive("heading",{level:1}),children:"H1"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleHeading({level:2}).run(),"aria-pressed":g==null?void 0:g.isActive("heading",{level:2}),children:"H2"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleHeading({level:3}).run(),"aria-pressed":g==null?void 0:g.isActive("heading",{level:3}),children:"H3"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleBulletList().run(),"aria-pressed":g==null?void 0:g.isActive("bulletList"),"aria-label":"Bulleted list",title:"Bulleted list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("circle",{cx:"5",cy:"6",r:"1.5"}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"12",r:"1.5"}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"18",r:"1.5"}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleOrderedList().run(),"aria-pressed":g==null?void 0:g.isActive("orderedList"),"aria-label":"Numbered list",title:"Numbered list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("text",{x:"3.5",y:"7",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"1."}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"13",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"2."}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"19",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"3."}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("left").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"left"}),"aria-label":"Align left",title:"Align left",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"4",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("center").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"center"}),"aria-label":"Align center",title:"Align center",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"7",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"8",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("right").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"right"}),"aria-label":"Align right",title:"Align right",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"6",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"10",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"6",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"12",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("justify").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"justify"}),"aria-label":"Justify",title:"Justify",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"9",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"17",width:"14",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>m(j=>!j),"aria-label":"Toggle maximize",title:"Toggle maximize",children:"⤢"})]})]}),h.jsx("div",{onKeyDown:j=>{if(!(!g||!(j.ctrlKey||j.metaKey))&&g.isFocused)switch(j.key.toLowerCase()){case"b":j.preventDefault(),w("bold");break;case"i":j.preventDefault(),w("italic");break;case"u":j.preventDefault(),w("underline");break;case"l":j.preventDefault(),g.chain().focus().setTextAlign("left").run();break;case"r":j.preventDefault(),g.chain().focus().setTextAlign("right").run();break;case"e":j.preventDefault(),g.chain().focus().setTextAlign("center").run();break;case"j":j.preventDefault(),g.chain().focus().setTextAlign("justify").run();break}},children:h.jsx(Qd,{editor:g})})]}):h.jsxs("div",{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:h.jsx("input",{placeholder:"Title",value:c,onChange:j=>u(j.target.value),style:{fontSize:18,fontWeight:600,border:"none",background:"transparent",color:"inherit"}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:8,marginBottom:0},onPointerDown:j=>j.preventDefault(),onPointerUp:j=>j.preventDefault(),children:[h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:j=>{j.preventDefault(),j.stopPropagation(),xe.current=!0,ot("bold")},onPointerUp:j=>{j.preventDefault(),j.stopPropagation()},onMouseDownCapture:j=>{j.preventDefault(),j.stopPropagation()},onMouseUp:j=>j.preventDefault(),onClick:()=>{if(xe.current){xe.current=!1;return}ot("bold")},"aria-pressed":xt("bold"),children:"B"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:j=>{j.preventDefault(),j.stopPropagation(),xe.current=!0,ot("italic")},onPointerUp:j=>{j.preventDefault(),j.stopPropagation()},onMouseDownCapture:j=>{j.preventDefault(),j.stopPropagation()},onMouseUp:j=>j.preventDefault(),onClick:()=>{if(xe.current){xe.current=!1;return}ot("italic")},"aria-pressed":xt("italic"),children:"I"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:j=>{j.preventDefault(),j.stopPropagation(),xe.current=!0,ot("underline")},onPointerUp:j=>{j.preventDefault(),j.stopPropagation()},onMouseDownCapture:j=>{j.preventDefault(),j.stopPropagation()},onMouseUp:j=>j.preventDefault(),onClick:()=>{if(xe.current){xe.current=!1;return}ot("underline")},"aria-pressed":xt("underline"),children:"U"})]})]}),h.jsxs("div",{style:{marginTop:8},children:[H.length===0&&h.jsx("div",{style:{marginBottom:8},children:h.jsx("button",{className:"btn",onPointerDown:j=>{j.preventDefault(),j.stopPropagation()},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.preventDefault(),j.stopPropagation(),W([{content:""}]),setTimeout(()=>De(0),30)},children:"Add an item"})}),H.map((j,G)=>h.jsxs("div",{className:"checklist-item",draggable:!0,onDragStart:de=>{var je;Ae.current=G,(je=de.dataTransfer)==null||je.setData("text/plain",String(G))},onDragOver:de=>de.preventDefault(),onDrop:de=>{de.preventDefault();const je=Ae.current??parseInt(de.dataTransfer.getData("text/plain")||"-1",10),Ue=G;je>=0&&je!==Ue&&W(We=>{const Se=[...We],[Xe]=Se.splice(je,1);return Se.splice(Ue,0,Xe),Se}),Ae.current=null},style:{display:"flex",gap:8,alignItems:"center"},children:[h.jsx("div",{className:"drag-handle",style:{width:20,cursor:"grab",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},"aria-hidden":!0,children:"≡"}),h.jsx("div",{className:"checkbox-visual",onClick:()=>ge(G),"aria-hidden":!0,children:j.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{style:{flex:1},children:h.jsx(Ix,{value:j.content,onChange:de=>K(G,de),onEnter:()=>{W(de=>{const je=[...de];return je.splice(G+1,0,{content:""}),je}),De(G+1)},onArrowUp:()=>De(Math.max(0,G-1)),onArrowDown:()=>De(Math.min(H.length-1,G+1)),onBackspaceEmpty:()=>{G>0&&(W(de=>{const je=[...de];return je.splice(G,1),je}),De(G-1))},onFocus:de=>{me.current=de,q.current[G]=de,se(je=>je+1)},placeholder:"",autoFocus:G===0})}),h.jsx("button",{className:"delete-item",onClick:de=>{de.stopPropagation(),W(je=>{const Ue=je.filter((Se,Xe)=>Xe!==G);if(Ue.length===0)return me.current=null,q.current=[],Ue;const We=Math.max(0,Math.min(G-1,Ue.length-1));return setTimeout(()=>De(We),30),Ue})},"aria-label":"Delete item",title:"Delete item",children:"✕"})]},G))]})]}),ae&&h.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10},children:[h.jsx("div",{className:"note-image",style:{width:96,height:72,flex:"0 0 auto"},children:h.jsx("img",{src:ae,alt:"selected",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:6,display:"block"}})}),h.jsx("div",{style:{flex:1,fontSize:13,opacity:.9},children:"1 image selected"}),h.jsx("button",{className:"btn",type:"button",onClick:()=>Ee(null),style:{padding:"6px 10px"},children:"Remove"})]}),h.jsxs("div",{className:"note-footer","aria-hidden":!1,style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:10,flexWrap:"wrap"},children:[h.jsxs("div",{style:{marginRight:"auto",display:"flex",flexDirection:"column",gap:8,minWidth:0,color:Me?Je:void 0},children:[!!M&&!!N&&h.jsxs("label",{className:"create-collection-toggle",title:N,children:[h.jsx("input",{type:"checkbox",checked:!!z,onChange:j=>X(!!j.target.checked)}),h.jsx("span",{className:"create-collection-toggle__text",children:"Add to current collection:"}),h.jsx("span",{className:"create-collection-toggle__path",children:N})]}),h.jsxs("div",{className:"note-actions",style:{display:"inline-flex",gap:8},children:[h.jsx("button",{className:"tiny palette",onClick:()=>at(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>ct(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>At(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>wt(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})})]})]}),h.jsx("button",{className:"btn",onClick:async()=>{Ye()},children:"Cancel"}),h.jsx("button",{className:"btn",onClick:Be,disabled:te||!oe(),children:te?"Saving...":"Save"})]}),J&&h.jsx(ef,{anchorRef:ue,onPick:j=>{Q(j)},onClose:()=>at(!1)}),$t&&h.jsx(tf,{onClose:()=>ct(!1),onSet:j=>{ct(!1)}}),nt&&h.jsx(xc,{onClose:()=>At(!1),onSelect:j=>{ze(G=>G.find(de=>de.id===j.id)?G:[...G,j]),At(!1)},current:(()=>{const j=i&&i.id?Number(i.id):void 0;return Ke.filter(G=>typeof G.id=="number"?G.id!==j:!0).map(G=>({userId:G.id,email:G.email}))})(),ownerId:i==null?void 0:i.id,onRemove:()=>{}}),Vt&&h.jsx(nf,{onClose:()=>wt(!1),onAdd:j=>Ee(j||null)})]})}function VJ({anchorRef:t,onClose:e,onDiscard:n}){const r=b.useRef(null),[i,s]=b.useState({position:"fixed",visibility:"hidden",left:0,top:0,zIndex:1e4});b.useLayoutEffect(()=>{const l=t==null?void 0:t.current,a=r.current;if(!a)return;const c=8,u=()=>{a.style.width="auto",a.style.height="auto";const f=Math.ceil(a.offsetWidth),p=Math.ceil(a.offsetHeight);return{w:f,h:p}};if(!l){const{w:f,h:p}=u();let m=Math.round(window.innerWidth-f-c),g=Math.round(window.innerHeight-p-c);mwindow.innerWidth-c&&(m=Math.max(c,window.innerWidth-f-c)),gwindow.innerHeight-c&&(g=Math.max(c,window.innerHeight-p-c)),s({position:"fixed",left:m,top:g,visibility:"visible",zIndex:1e4,width:`${f}px`,height:`${p}px`});return}const d=l.getBoundingClientRect();requestAnimationFrame(()=>{const{w:f,h:p}=u();let m=Math.round(d.right-f),g=Math.round(d.bottom-p);mwindow.innerWidth-c&&(m=Math.max(c,window.innerWidth-f-c)),gwindow.innerHeight-c&&(g=Math.max(c,window.innerHeight-p-c)),s({position:"fixed",left:m,top:g,visibility:"visible",zIndex:1e4,width:`${f}px`,height:`${p}px`})})},[t]),b.useLayoutEffect(()=>{function l(a){r.current&&(r.current.contains(a.target)||e())}return document.addEventListener("pointerdown",l),document.addEventListener("mousedown",l),()=>{document.removeEventListener("pointerdown",l),document.removeEventListener("mousedown",l)}},[e]);const o=h.jsx("div",{ref:r,className:"more-menu",style:i,role:"dialog","aria-label":"More options",children:h.jsx("button",{className:"more-item",onClick:()=>{n(),e()},children:"Discard"})});return zn.createPortal(o,document.body)}function WJ({open:t,mode:e,onClose:n,onCreated:r,activeCollection:i}){const{token:s,user:o}=Sr();function l(){try{return`u${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`u${Math.random()}`}}const[a,c]=B.useState(""),[u,d]=B.useState([]),[f,p]=B.useState(""),[m,g]=B.useState(void 0),[y,v]=B.useState(!1),[w,x]=B.useState(!1),[E,k]=B.useState(!1),[M,N]=B.useState(!1),[z,X]=B.useState(null),[L,H]=B.useState([]),W=i&&Number.isFinite(Number(i.id))?Number(i.id):null,te=i&&typeof i.path=="string"?String(i.path):"",[ce,ue]=B.useState(!1),[Ae,me]=B.useState(!1),q=B.useRef(null),se=B.useRef(null),[xe,Me]=B.useState(!1),Q=pg({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),yg,mn.create({name:"paragraphEnterFix",priority:1e3,addKeyboardShortcuts(){return{"Shift-Enter":()=>{const ee=this.editor;return ee.commands.splitBlock(),ee.commands.setParagraph(),!0},"Mod-Enter":()=>{const ee=this.editor;return ee.commands.splitBlock(),ee.commands.setParagraph(),!0}}}})],editorProps:{attributes:{class:"rt-editor"}},content:""}),Je=B.useRef({showPalette:!1,showReminderPicker:!1,showCollaborator:!1,showImageDialog:!1,showMore:!1});B.useEffect(()=>{Je.current={showPalette:y,showReminderPicker:w,showCollaborator:E,showImageDialog:M,showMore:xe}},[y,w,E,M,xe]);const _t=B.useRef((()=>{try{return`mcreate-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`mcreate-${Math.random()}`}})());B.useEffect(()=>{if(t){window.dispatchEvent(new Event("freemannotes:editor-modal-open"));try{const ee=_t.current,re=()=>{try{const Oe=Je.current;if(Oe.showMore){Me(!1);return}if(Oe.showImageDialog){N(!1);return}if(Oe.showCollaborator){k(!1);return}if(Oe.showReminderPicker){x(!1);return}if(Oe.showPalette){v(!1);return}}catch{}try{J()}catch{}};window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:ee,onBack:re}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:_t.current}}))}catch{}window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}}},[t]),B.useEffect(()=>{if(t){c(""),p(""),X(null),H([]),v(!1),x(!1),k(!1),N(!1),Me(!1);try{ue(W!=null)}catch{}e==="checklist"?(d([{uid:l(),content:"",checked:!1,indent:0}]),window.setTimeout(()=>Se(0),30)):(d([]),requestAnimationFrame(()=>{try{Q==null||Q.commands.focus("end")}catch{}}));try{Q==null||Q.commands.clearContent()}catch{}}},[t,e,Q]),B.useEffect(()=>{g(f?dn(f):void 0)},[f]);function J(){if(!Ae){try{de()}catch{}try{Me(!1)}catch{}try{v(!1)}catch{}try{x(!1)}catch{}try{k(!1)}catch{}try{N(!1)}catch{}try{Q==null||Q.commands.clearContent()}catch{}try{c(""),d([]),p(""),X(null),H([])}catch{}n()}}function at(){try{const ee=!!a.trim(),re=!!f,Oe=!!(z||L&&L.length);if(e==="checklist"){const fe=(u||[]).some(Ce=>!!String(Ce.content||"").trim()||!!Ce.checked);return ee||re||Oe||fe}const Ze=!!((Q==null?void 0:Q.getText())||"").trim();return ee||re||Oe||Ze}catch{return!1}}async function $t(){var ee;if(!Ae){me(!0);try{if(!s)throw new Error("Not authenticated");const re=e==="text"?(Q==null?void 0:Q.getJSON())||{}:{},Oe={title:a,body:null,type:e==="checklist"?"CHECKLIST":"TEXT",color:f||null};e==="checklist"&&(Oe.items=u.map((Fe,ut)=>({content:Fe.content,checked:!!Fe.checked,indent:typeof Fe.indent=="number"?Fe.indent:0,ord:ut})));const Ze=await fetch("/api/notes",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(Oe)});if(!Ze.ok)throw new Error(await Ze.text());const fe=await Ze.json(),Ce=(ee=fe==null?void 0:fe.note)==null?void 0:ee.id;if(Ce&&ce&&W!=null)try{const Fe=await fetch(`/api/notes/${Ce}/collections`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({collectionId:W})});if(!Fe.ok)throw new Error(await Fe.text())}catch(Fe){console.warn("Created note but failed to add to collection",Fe);try{window.alert("Note created, but failed to add it to the current collection.")}catch{}}if(Ce&&e==="text")try{const Fe=new Fi,ut=`note-${Ce}`,zt=new mf(Nj("/collab"),ut,Fe),kt=new ag({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:Fe})],content:""});await new Promise(Jt=>{zt.on("sync",jt=>{jt&&Jt()})});try{kt==null||kt.commands.setContent(re)}catch{}await new Promise(Jt=>setTimeout(Jt,100));try{kt==null||kt.destroy()}catch{}try{zt.destroy()}catch{}try{Fe.destroy()}catch{}try{await fetch(`/api/notes/${Ce}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({body:JSON.stringify(re),type:"TEXT"})})}catch{}}catch(Fe){console.warn("Failed to seed Yjs content for new note",Fe)}if(Ce&&L.length)for(const Fe of L)try{await fetch(`/api/notes/${Ce}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({email:Fe.email})})}catch{}if(Ce&&z)try{await fetch(`/api/notes/${Ce}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({url:z})})}catch{}try{Q==null||Q.commands.clearContent()}catch{}r(),n()}catch(re){console.error("Failed to create note",re),window.alert("Failed to create note")}finally{me(!1)}}}const ct=B.useRef([]),[nt,At]=B.useState(null),[Vt,wt]=B.useState(null),[ae,Ee]=B.useState(null),Ke=B.useRef(null),ze=B.useRef({x:0,y:0}),Pe=B.useRef(null),it=B.useRef(0),ot=B.useRef(null),xt=B.useRef(0),oe=B.useRef(null),Ye=B.useRef(0),Ge=B.useRef(null),K=B.useMemo(()=>{try{return typeof window<"u"&&!!window.matchMedia&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}},[]),ge=B.useMemo(()=>{const ee={directionLockPx:0,indentPx:16,ghostOverlapUpPct:.7,ghostOverlapDownPct:.7};return K?ee:{...ee,directionLockPx:6}},[K]);function De(ee,re){var Ce,Fe;const Oe=re,Ze=Number(((Ce=ee[re])==null?void 0:Ce.indent)||0);let fe=re+1;for(;feZe;)fe++;return[Oe,fe]}function Be(ee,re,Oe){d(Ze=>{const fe=[...Ze||[]],Ce=fe.slice(ee,re);fe.splice(ee,re-ee);let Fe=Oe;return Fe>ee&&(Fe=Fe-(re-ee)),Fe<0&&(Fe=0),Fe>fe.length&&(Fe=fe.length),fe.splice(Fe,0,...Ce),fe})}function Le(ee,re){if(Pe.current!=="vertical"||nt===null)return"";const[Oe,Ze]=De(re,nt);return Vt===null||ee>=Oe&&eeZe-1&&ee<=Vt?"shift-up":"":nt>Vt&&ee>=Vt&&ee{var Fe,ut;oe.current=null;const re=(Fe=Ge.current)==null?void 0:Fe.querySelector(".dialog-body");if(!re)return;const Oe=re.getBoundingClientRect(),Ze=Ye.current,fe=60,Ce=12;ZeOe.bottom-fe&&(re.scrollTop+=Ce),(ut=ot.current)!=null&&ut.active&&Pe.current==="vertical"&&Ke.current&&(oe.current=window.requestAnimationFrame(ee))};oe.current=window.requestAnimationFrame(ee)}function G(){oe.current!=null&&(window.cancelAnimationFrame(oe.current),oe.current=null)}function de(){var ee,re,Oe;if(G(),Ke.current){try{Ke.current.remove()}catch{}Ke.current=null}try{(Oe=(re=(ee=Ge.current)==null?void 0:ee.style)==null?void 0:re.removeProperty)==null||Oe.call(re,"--checklist-item-shift")}catch{}At(null),wt(null),Ee(null),ot.current=null,Pe.current=null,xt.current=0}function je(){d(ee=>[...ee||[],{uid:l(),content:"",checked:!1,indent:0}])}function Ue(ee,re){d(Oe=>(Oe||[]).map((Ze,fe)=>fe===ee?{...Ze,content:re}:Ze))}function We(ee){d(re=>{var Fe;const Oe=[...re||[]],Ze=Oe[ee];if(!Ze)return Oe;const fe=!Ze.checked,Ce=Number(Ze.indent||0);if(Oe[ee]={...Ze,checked:fe},Ce===0)for(let ut=ee+1;ut0;ut++)Oe[ut]={...Oe[ut],checked:fe};return Oe})}function Se(ee){window.setTimeout(()=>{const re=ct.current[ee];try{re&&re.chain().focus().run()}catch{}},30)}const Xe=B.useRef(null),[,Tt]=B.useState(0);function rt(){var Oe;let ee=Xe.current;if(ee&&ee.isFocused)return ee;const re=typeof document<"u"&&((Oe=document.getSelection())==null?void 0:Oe.anchorNode)||null;if(re){const Ze=ct.current.find(fe=>{var Ce;try{return!!(fe&&((Ce=fe.view)!=null&&Ce.dom)&&fe.view.dom.contains(re))}catch{return!1}});Ze&&(ee=Ze)}else{const Ze=typeof document<"u"?document.activeElement:null;if(Ze){const fe=ct.current.find(Ce=>{try{return!!(Ce&&Ce.view&&Ce.view.dom&&(Ce.view.dom===Ze||Ce.view.dom.contains(Ze)))}catch{return!1}});fe&&(ee=fe)}}if(!ee||!(ee!=null&&ee.isFocused)){const Ze=ct.current.find(fe=>!!(fe&&fe.isFocused));Ze&&(ee=Ze)}return ee||null}function Wt(ee){var Fe;const re=rt();if(!re)return;const Oe=(Fe=re.state)==null?void 0:Fe.selection;if(!Oe)return;if(!Oe.empty){const ut=re.chain().focus();ee==="bold"?ut.toggleBold():ee==="italic"?ut.toggleItalic():ut.toggleUnderline(),ut.run();try{Tt(zt=>zt+1)}catch{}return}let Ze=Oe.from,fe=Oe.to;try{const ut=Oe.$from;let zt=ut.depth;for(;zt>0&&!ut.node(zt).isBlock;)zt--;Ze=ut.start(zt),fe=ut.end(zt)}catch{}const Ce=re.chain().focus().setTextSelection({from:Ze,to:fe});ee==="bold"?Ce.toggleBold():ee==="italic"?Ce.toggleItalic():Ce.toggleUnderline(),Ce.run();try{re.chain().focus().setTextSelection(Oe.from).run()}catch{}try{Tt(ut=>ut+1)}catch{}}function Mt(ee){var Jt,jt;const re=rt();if(!re)return!1;const Oe=(Jt=re.state)==null?void 0:Jt.selection;if(!Oe)return!1;const Ze=(((jt=re.schema)==null?void 0:jt.marks)||{})[ee];if(!Ze)return!1;const fe=Oe.$from;let Ce=fe.depth;for(;Ce>0&&!fe.node(Ce).isBlock;)Ce--;const Fe=fe.start(Ce),ut=fe.end(Ce);let zt=!1,kt=!0;try{re.state.doc.nodesBetween(Fe,ut,fn=>{fn&&fn.isText&&(zt=!0,Ze.isInSet(fn.marks)||(kt=!1))})}catch{}return zt&&kt}function dn(ee){if(!ee)return;const re=ee.replace("#",""),Oe=re.length===3?re.split("").map(nn=>nn+nn).join(""):re;if(Oe.length!==6)return;const Ze=parseInt(Oe.slice(0,2),16)/255,fe=parseInt(Oe.slice(2,4),16)/255,Ce=parseInt(Oe.slice(4,6),16)/255,Fe=nn=>nn<=.03928?nn/12.92:Math.pow((nn+.055)/1.055,2.4),ut=Fe(Ze),zt=Fe(fe),kt=Fe(Ce),Jt=.2126*ut+.7152*zt+.0722*kt,jt=(nn,rn)=>(Math.max(nn,rn)+.05)/(Math.min(nn,rn)+.05),fn=jt(1,Jt),wn=jt(0,Jt);return fn>=wn?"#ffffff":"#000000"}if(!t)return null;const It={};f&&(It.background=f,It["--editor-surface"]=f);const Ot=e==="checklist"?"New checklist":"New note",tn=h.jsxs("div",{className:"image-dialog-backdrop",ref:q,onMouseDown:ee=>{if(ee.target===ee.currentTarget)try{ee.preventDefault()}catch{}},children:[h.jsxs("div",{ref:Ge,className:`image-dialog editor-dialog maximized${e==="checklist"?" checklist-editor":""}`,role:"dialog","aria-modal":!0,style:{width:"100vw",...It},children:[h.jsxs("div",{className:"dialog-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[h.jsx("button",{className:"btn",type:"button",onClick:J,disabled:Ae,children:"Cancel"}),h.jsx("strong",{children:Ot}),h.jsx("button",{className:"btn",type:"button",onClick:$t,disabled:Ae||!at(),children:Ae?"Saving…":"Save"})]}),h.jsxs("div",{className:"dialog-body",children:[e==="text"?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Title",value:a,onChange:ee=>c(ee.target.value),style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:0,marginBottom:0,overflowX:"auto",color:m||"inherit"},children:[h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleBold().run(),"aria-pressed":Q==null?void 0:Q.isActive("bold"),"aria-label":"Bold",title:"Bold",children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleItalic().run(),"aria-pressed":Q==null?void 0:Q.isActive("italic"),"aria-label":"Italic",title:"Italic",children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleUnderline().run(),"aria-pressed":Q==null?void 0:Q.isActive("underline"),"aria-label":"Underline",title:"Underline",children:"U"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleHeading({level:1}).run(),"aria-pressed":Q==null?void 0:Q.isActive("heading",{level:1}),"aria-label":"Heading 1",title:"Heading 1",children:"H1"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleHeading({level:2}).run(),"aria-pressed":Q==null?void 0:Q.isActive("heading",{level:2}),"aria-label":"Heading 2",title:"Heading 2",children:"H2"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleHeading({level:3}).run(),"aria-pressed":Q==null?void 0:Q.isActive("heading",{level:3}),"aria-label":"Heading 3",title:"Heading 3",children:"H3"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleBulletList().run(),"aria-pressed":Q==null?void 0:Q.isActive("bulletList"),"aria-label":"Bulleted list",title:"Bulleted list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("circle",{cx:"5",cy:"6",r:"1.5"}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"12",r:"1.5"}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"18",r:"1.5"}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleOrderedList().run(),"aria-pressed":Q==null?void 0:Q.isActive("orderedList"),"aria-label":"Numbered list",title:"Numbered list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("text",{x:"3.5",y:"7",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"1."}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"13",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"2."}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"19",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"3."}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().setTextAlign("left").run(),"aria-pressed":Q==null?void 0:Q.isActive({textAlign:"left"}),"aria-label":"Align left",title:"Align left",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"4",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().setTextAlign("center").run(),"aria-pressed":Q==null?void 0:Q.isActive({textAlign:"center"}),"aria-label":"Align center",title:"Align center",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"7",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"8",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().setTextAlign("right").run(),"aria-pressed":Q==null?void 0:Q.isActive({textAlign:"right"}),"aria-label":"Align right",title:"Align right",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"6",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"10",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"6",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"12",y:"17",width:"8",height:"2",rx:"1"})]})})]})]}),h.jsx(Qd,{editor:Q,style:{color:m||"inherit"}})]}):h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Title",value:a,onChange:ee=>c(ee.target.value),style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:0,marginBottom:0,overflowX:"auto",color:m||"inherit"},children:[h.jsx("button",{className:"tiny",onClick:()=>Wt("bold"),"aria-pressed":Mt("bold"),"aria-label":"Bold",title:"Bold",children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>Wt("italic"),"aria-pressed":Mt("italic"),"aria-label":"Italic",title:"Italic",children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>Wt("underline"),"aria-pressed":Mt("underline"),"aria-label":"Underline",title:"Underline",children:"U"}),h.jsx("button",{className:"btn",type:"button",onClick:()=>{je(),Se(u.length)},style:{padding:"6px 10px"},children:"Add item"})]})]}),h.jsx("div",{className:"checklist-items",children:(ae??u??[]).map((ee,re)=>{const Ze=Le(re,ae??u??[]);return h.jsxs("div",{className:`checklist-item${nt===re?" drag-source":""}${Ze?" "+Ze:""}`,style:{marginLeft:Number(ee.indent||0)*18},draggable:!1,onClick:fe=>{try{fe.stopPropagation()}catch{}},children:[h.jsxs("div",{className:"drag-gutter",style:{cursor:"grab",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",touchAction:"none"},onMouseDown:fe=>{fe.preventDefault()},onPointerDown:fe=>{try{fe.preventDefault()}catch{}try{fe.stopPropagation()}catch{}fe.currentTarget.setPointerCapture(fe.pointerId),Ye.current=fe.clientY,ot.current={active:!0,startX:fe.clientX,startY:fe.clientY,idx:re,pointerId:fe.pointerId},Pe.current=null,Ee(null)},onPointerMove:fe=>{var Jt,jt,fn,wn,nn,rn,Pr,R;const Ce=ot.current;if(!Ce||!Ce.active)return;try{fe.preventDefault()}catch{}Ye.current=fe.clientY;const Fe=fe.clientX-Ce.startX,ut=fe.clientY-Ce.startY,zt=ge.directionLockPx;if(Pe.current===null&&(Math.abs(Fe)>zt||Math.abs(ut)>zt)&&(Pe.current=Math.abs(Fe)>Math.abs(ut)?"horizontal":"vertical"),Pe.current==="vertical"){const U=Ce.idx;if(!Ke.current){const $=Array.from(((Jt=Ge.current)==null?void 0:Jt.querySelectorAll(".checklist-item"))||[])[U];if($){const S=$.getBoundingClientRect();ze.current={x:fe.clientX-S.left,y:fe.clientY-S.top};const V=$.cloneNode(!0);V.style.position="fixed",V.style.left=S.left+"px",V.style.top=fe.clientY-(ze.current.y||0)+"px",V.style.width=S.width+"px",V.style.pointerEvents="none",V.style.zIndex="9999",V.style.opacity="0.98",V.classList.add("checklist-ghost"),document.body.appendChild(V),Ke.current=V,At(U),wt(U),it.current=S.left;try{(wn=(fn=(jt=Ge.current)==null?void 0:jt.style)==null?void 0:fn.setProperty)==null||wn.call(fn,"--checklist-item-shift",`${Math.round(S.height)}px`)}catch{}}}Ke.current&&(Ke.current.style.left=it.current+"px",Ke.current.style.top=fe.clientY-(ze.current.y||0)+"px",j());const Y=Array.from(((nn=Ge.current)==null?void 0:nn.querySelectorAll(".checklist-item"))||[]);if(Y.length){let he=null;const $=Ke.current?Ke.current.getBoundingClientRect():{top:fe.clientY-10,bottom:fe.clientY+10},S=fe.clientY>(xt.current||fe.clientY);xt.current=fe.clientY;const V=S?ge.ghostOverlapDownPct:ge.ghostOverlapUpPct;for(let pe=0;pe=V){he=pe;break}}he!=null&&he!==Vt&&wt(he)}return}const kt=ge.indentPx;if(Pe.current==="horizontal"){const U=Ce.idx;if(U===0&&Fe>0){Ee(null);return}const Y=u;if(Fe>kt){const[he,$]=De(Y,U),S=[...Y],V=S.splice(he,$-he);let pe=null;for(let tt=U-1;tt>=0;tt--)if(Number(((rn=Y[tt])==null?void 0:rn.indent)||0)===0){pe=tt;break}if(pe!=null){const tt=Y[pe].uid,Ft=S.findIndex($n=>$n.uid===tt);let Kt=Ft>=0?Ft+1:Math.min(he,S.length);for(;Kt0;)Kt++;const Zt=V.map($n=>({...$n,indent:1}));S.splice(Kt,0,...Zt)}else{let tt=Math.min(he,S.length);for(;tt0;)tt++;const Ft=V.map(Kt=>({...Kt,indent:1}));S.splice(tt,0,...Ft)}Ee(S)}else if(Fe<-kt){const[he,$]=De(Y,U),S=[...Y];for(let V=he;V<$&&V{try{fe.currentTarget.releasePointerCapture(fe.pointerId)}catch{}if(ot.current=null,ae){d(ae),Ee(null),Pe.current=null,de();return}if(Pe.current==="vertical"&&nt!==null){const Ce=nt,Fe=u,[ut,zt]=De(Fe,Ce);if(Vt!==null){const kt=Ce=ut&&kt{fe.stopPropagation(),We(re)},onPointerDown:fe=>{fe.stopPropagation()},onPointerUp:fe=>{fe.stopPropagation()},children:ee.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),h.jsx("div",{style:{flex:1,minWidth:0},children:h.jsx(Ix,{value:ee.content,onChange:fe=>Ue(re,fe),onEnter:()=>{d(fe=>{const Ce=[...fe||[]];return Ce.splice(re+1,0,{uid:l(),content:"",checked:!1,indent:Number(ee.indent||0)}),Ce}),Se(re+1)},onArrowUp:()=>Se(Math.max(0,re-1)),onArrowDown:()=>Se(Math.min(u.length-1,re+1)),onBackspaceEmpty:()=>{re>0&&(d(fe=>{const Ce=[...fe||[]];return Ce.splice(re,1),Ce}),Se(re-1))},onFocus:fe=>{Xe.current=fe,ct.current[re]=fe;try{Tt(Ce=>Ce+1)}catch{}},placeholder:"",autoFocus:re===0})}),h.jsx("button",{className:"delete-item",type:"button",onClick:fe=>{fe.stopPropagation(),d(Ce=>{const Fe=(Ce||[]).filter((zt,kt)=>kt!==re);if(Fe.length===0)return Xe.current=null,ct.current=[],Fe;const ut=Math.max(0,Math.min(re-1,Fe.length-1));return window.setTimeout(()=>Se(ut),30),Fe})},"aria-label":"Delete item",title:"Delete item",children:"✕"})]},ee.uid||String(re))})})]}),z&&h.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10},children:[h.jsx("div",{className:"note-image",style:{width:96,height:72,flex:"0 0 auto"},children:h.jsx("img",{src:z,alt:"selected",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:6,display:"block"}})}),h.jsx("div",{style:{flex:1,fontSize:13,opacity:.9},children:"1 image selected"}),h.jsx("button",{className:"btn",type:"button",onClick:()=>X(null),style:{padding:"6px 10px"},children:"Remove"})]})]}),h.jsxs("div",{className:"dialog-footer",style:{display:"block"},children:[!!W&&!!te&&h.jsxs("label",{className:"create-collection-toggle",title:te,style:{margin:"0 0 10px"},children:[h.jsx("input",{type:"checkbox",checked:!!ce,onChange:ee=>ue(!!ee.target.checked)}),h.jsx("span",{className:"create-collection-toggle__text",children:"Add to current collection:"}),h.jsx("span",{className:"create-collection-toggle__path",children:te})]}),h.jsxs("div",{className:"note-actions",style:{display:"inline-flex",gap:8,justifyContent:"flex-start",color:m||"inherit"},children:[h.jsx("button",{className:"tiny palette",onClick:()=>v(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>x(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>k(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>N(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),h.jsx("button",{ref:se,className:"tiny editor-more",onClick:ee=>{ee.stopPropagation(),Me(re=>!re)},"aria-label":"More",title:"More",children:"⋮"})]})]})]}),y&&h.jsx(ef,{anchorRef:q,onPick:ee=>{p(ee)},onClose:()=>v(!1)}),w&&h.jsx(tf,{onClose:()=>x(!1),onSet:ee=>{x(!1),ee&&window.alert(`Reminder set (UI-only): ${ee}`)}}),E&&h.jsx(xc,{onClose:()=>k(!1),onSelect:ee=>{H(re=>re.find(Oe=>Oe.id===ee.id)?re:[...re,ee]),k(!1)},current:(()=>{const ee=o&&o.id?Number(o.id):void 0;return L.filter(re=>typeof re.id=="number"?re.id!==ee:!0).map(re=>({userId:re.id,email:re.email}))})(),ownerId:o==null?void 0:o.id,onRemove:()=>{}}),M&&h.jsx(nf,{onClose:()=>N(!1),onAdd:ee=>X(ee||null)}),xe&&h.jsx(VJ,{anchorRef:se,onClose:()=>Me(!1),onDiscard:J})]});return zn.createPortal(tn,document.body)}const SN=B.memo(function({note:e,setItemRef:n,isDragSource:r,isDragTarget:i,disabled:s,onChange:o,style:l}){const a=Number(e==null?void 0:e.id),{setNodeRef:c,listeners:u,attributes:d}=U3({id:a,disabled:s}),{setNodeRef:f}=K3({id:a}),p=b.useCallback(g=>{c(g),f(g),n(g,a)},[c,f,n,a]),m=(r?" note-drag-source":"")+(i?" note-drag-target":"");return h.jsx("div",{"data-note-id":a,ref:p,className:m.trim(),style:l,children:h.jsx(El,{note:e,onChange:o,dragHandleAttributes:s?void 0:d,dragHandleListeners:s?void 0:u})})});function KJ({selectedLabelIds:t=[],selectedCollectionId:e=null,collectionStack:n=[],selectedCollaboratorId:r=null,searchQuery:i="",sortConfig:s=Ks,onClearAllFilters:o,onSetSelectedLabelIds:l,onSetSelectedCollaboratorId:a,onSelectCollectionById:c,onSetCollectionStack:u,onSetSearchQuery:d,onSortConfigChange:f}){var F1;const{token:p}=Sr(),[m,g]=b.useState([]),[y,v]=b.useState(!0),[w,x]=b.useState(!1),E=b.useRef([]),[k,M]=b.useState("desktop"),N=b.useRef("desktop"),[z,X]=b.useState(1),[L,H]=b.useState(1),W=b.useRef(1),te=b.useRef(1),[ce,ue]=b.useState(0);b.useEffect(()=>{const C=()=>ue(I=>I+1),T=()=>ue(I=>Math.max(0,I-1));return window.addEventListener("freemannotes:editor-modal-open",C),window.addEventListener("freemannotes:editor-modal-close",T),()=>{window.removeEventListener("freemannotes:editor-modal-open",C),window.removeEventListener("freemannotes:editor-modal-close",T)}},[]);const Ae=ce>0;b.useEffect(()=>{const C=document.documentElement;return Ae?C.classList.add("is-editor-modal-open"):C.classList.remove("is-editor-modal-open"),()=>{try{C.classList.remove("is-editor-modal-open")}catch{}}},[Ae]),b.useEffect(()=>{if(ce<=0)return;const C=window.setTimeout(()=>{try{!!document.querySelector('[aria-modal="true"]')||ue(0)}catch{}},400);return()=>{try{window.clearTimeout(C)}catch{}}},[ce]);const me=b.useRef(new Map),q=b.useRef(0),se=b.useRef(null),xe=b.useRef(null),Me=b.useRef(!1),[Q,Je]=b.useState(!1),[_t,J]=b.useState(0),[at,$t]=b.useState("text"),[ct,nt]=b.useState(null),At=b.useMemo(()=>{const C=Array.isArray(n)?n:[];if(!C.length)return null;const T=C[C.length-1],I=Number(T==null?void 0:T.id),P=C.map(O=>String((O==null?void 0:O.name)||"")).filter(Boolean).join(" / ");return!Number.isFinite(I)||!P?null:{id:I,path:P}},[n]),Vt=b.useCallback(C=>{Je(!1),nt(C)},[]);b.useEffect(()=>{if(!Q)return;const C=T=>{try{const I=T==null?void 0:T.target;if(I&&I.closest&&I.closest(".mobile-add-note"))return}catch{}Je(!1)};return window.addEventListener("pointerdown",C,{capture:!0}),()=>{try{window.removeEventListener("pointerdown",C,{capture:!0})}catch{}}},[Q]);const wt=b.useRef(!1),ae=b.useRef(null),Ee=b.useRef(null),Ke=b.useRef(null),ze=b.useRef(-1),Pe=b.useRef([]),it=b.useRef(null),ot=b.useRef(null),xt=b.useRef(null),oe=b.useRef(null),Ye=b.useRef(null),Ge=b.useRef([]),K=b.useRef(null),ge=b.useRef(2),De=b.useRef(1),Be=b.useRef(!1),Le=b.useRef(null),j=b.useRef(null),[G,de]=b.useState(null),[je,Ue]=b.useState(null),[We,Se]=b.useState([]),Xe=b.useRef(null),Tt=b.useRef(null),[rt,Wt]=b.useState(null),[Mt,dn]=b.useState(null),It=b.useRef(null),Ot=b.useRef(null),tn=b.useRef(!1),ee=b.useRef(null),re=b.useRef(null),Oe=b.useRef(null),Ze=b.useCallback(C=>{if(!C)return null;const T=C.touches&&C.touches[0]||C.changedTouches&&C.changedTouches[0];return T&&typeof T.clientX=="number"&&typeof T.clientY=="number"?{x:T.clientX,y:T.clientY}:typeof C.clientX=="number"&&typeof C.clientY=="number"?{x:C.clientX,y:C.clientY}:null},[]),fe=b.useCallback(C=>{const T=Ze(C);T&&(ee.current=T);const I=O=>{tn.current&&(ee.current={x:O.clientX,y:O.clientY})},P=O=>{if(!tn.current)return;const _=O.touches&&O.touches[0];_&&(ee.current={x:_.clientX,y:_.clientY})};window.addEventListener("pointermove",I,{capture:!0,passive:!1}),window.addEventListener("touchmove",P,{capture:!0,passive:!0}),Oe.current=()=>{try{window.removeEventListener("pointermove",I,{capture:!0})}catch{}try{window.removeEventListener("touchmove",P,{capture:!0})}catch{}}},[Ze]),Ce=b.useCallback(()=>{try{Oe.current&&Oe.current()}catch{}Oe.current=null,ee.current=null},[]),Fe=b.useCallback(()=>{const C=document.querySelector(".main-area");if(C&&C.scrollHeight>C.clientHeight+1)return C;const T=document.scrollingElement;return T&&T.scrollHeight>T.clientHeight+1?T:null},[]),ut=b.useCallback(()=>{if(re.current!=null)return;const C=96,T=12,I=()=>{if(!tn.current){re.current=null;return}const P=ee.current;if(!P){re.current=requestAnimationFrame(I);return}const O=window.innerHeight||0,_=P.y,D=Math.max(0,O-P.y);let F=0;if(_{if(re.current!=null){try{cancelAnimationFrame(re.current)}catch{}re.current=null}},[]),[kt,Jt]=b.useState(!1),[jt,fn]=b.useState(null),[wn,nn]=b.useState(null),[rn,Pr]=b.useState(null),R=b.useRef(null),U=b.useRef(null),Y=b.useRef(null);function he(C){try{const T=(localStorage.getItem("prefs.animationSpeed")||"normal").toLowerCase(),I={fast:{resize:250,swap:250,rearrange:250},normal:{resize:600,swap:500,rearrange:480},slow:{resize:1e3,swap:1e3,rearrange:1e3}};return(I[T]||I.normal)[C]}catch{return C==="resize"?600:C==="swap"?500:480}}function $(){if(!j.current)try{const C=window.scrollX||0,T=window.scrollY||0,I=document.body;j.current={x:C,y:T,position:I.style.position||"",top:I.style.top||"",left:I.style.left||"",right:I.style.right||"",width:I.style.width||"",overflow:I.style.overflow||""},I.style.position="fixed",I.style.top=`-${T}px`,I.style.left=`-${C}px`,I.style.right="0px",I.style.width="100%",I.style.overflow="hidden"}catch{}}function S(){const C=j.current;if(C){j.current=null;try{const T=document.body;T.style.position=C.position,T.style.top=C.top,T.style.left=C.left,T.style.right=C.right,T.style.width=C.width,T.style.overflow=C.overflow,window.scrollTo(C.x,C.y)}catch{}}}b.useLayoutEffect(()=>{Ee.current=G},[G]),b.useLayoutEffect(()=>{Ke.current=je},[je]),b.useLayoutEffect(()=>{Pe.current=We;const C=We.indexOf("spacer");ze.current=C},[We]),b.useEffect(()=>{const C=document.documentElement;return G!=null?C.classList.add("is-note-rearrange-dragging"):C.classList.remove("is-note-rearrange-dragging"),()=>{try{C.classList.remove("is-note-rearrange-dragging")}catch{}}},[G]);async function V(){v(!0);try{const C=await fetch("/api/notes",{headers:{Authorization:`Bearer ${p}`}});if(!C.ok)throw new Error(await C.text());let I=(await C.json()).notes||[];try{const P=localStorage.getItem("notesOrder");if(P){const O=JSON.parse(P||"[]");if(Array.isArray(O)&&O.length){const _=new Map(I.map(le=>[le.id,le])),D=[],F=new Set;for(const le of O)_.has(le)&&!F.has(le)&&(D.push(_.get(le)),F.add(le));const ie=[];for(const le of I)F.has(le.id)||ie.push(le);I=[...ie,...D]}}}catch{}g(I);try{setTimeout(()=>window.dispatchEvent(new Event("notes-grid:recalc")),0)}catch{}}catch(C){console.error("Failed to load notes",C),g([])}finally{v(!1)}}function pe(C,T){g(I=>I.map(P=>{if(Number(P.id)!==Number(C))return P;const O=(Array.isArray(T)?T:[]).filter(_=>_&&typeof _.id=="number"&&typeof _.name=="string").map(_=>({id:_.id,label:{id:_.id,name:_.name}}));return{...P,noteLabels:O}}))}function tt(C,T){g(I=>I.map(P=>{if(Number(P.id)!==Number(C))return P;const O=(Array.isArray(T)?T:[]).filter(_=>_&&typeof _.url=="string").map(_=>({id:Number(_.id||Date.now()),url:String(_.url)}));return{...P,images:O}}))}function Ft(C,T){const I=(typeof T=="string"?T:"")||"";g(P=>P.map(O=>Number(O.id)!==Number(C)?O:{...O,viewerColor:I.length?I:null}))}function Kt(C,T){const I=(Array.isArray(T)?T:[]).filter(P=>P&&typeof P.id=="number"&&typeof P.name=="string").map(P=>({id:Number(P.id),name:String(P.name),parentId:P.parentId==null?null:Number(P.parentId)}));g(P=>P.map(O=>Number(O.id)!==Number(C)?O:{...O,viewerCollections:I}))}b.useEffect(()=>{p?V():g([])},[p]),b.useEffect(()=>{E.current=m},[m]),b.useEffect(()=>{It.current=rt},[rt]),b.useEffect(()=>{Ot.current=Mt},[Mt]);const Zt=!!(s&&s.sortKey==="default"&&s.groupBy==="none"&&s.smartFilter==="none"),$n=(()=>{try{return localStorage.getItem("prefs.dragBehavior")||"swap"}catch{return"swap"}})(),sn=Zt&&$n==="swap",A=Zt&&$n==="rearrange",ne=sn&&kt;b.useEffect(()=>{if(!sn)return;Wt(null),dn(null);const C=requestAnimationFrame(()=>{try{N1()}catch{}});return()=>{try{cancelAnimationFrame(C)}catch{}}},[sn,z,L]);function we(C){const T=st.get(C);return T?T.pinned?"pinned":"others":null}function Z(){if(U.current!=null){try{window.clearTimeout(U.current)}catch{}U.current=null}}const Ie=F_(iS(rM,{activationConstraint:{distance:6}}),iS(iM,{activationConstraint:{delay:160,tolerance:12}}));function Ve(C){var O;if(!sn)return;const T=Number(C.active.id);if(!Number.isFinite(T))return;tn.current=!0,fe(C.activatorEvent),ut(),fn(T);const I=me.current.get(T),P=(O=I==null?void 0:I.getBoundingClientRect)==null?void 0:O.call(I);P&&P.width>0&&P.height>0?Pr({width:P.width,height:P.height}):Pr(null),nn(null),R.current=null,Z(),Jt(!0)}function Rt(C){var D;if(!sn)return;const T=Number(C.active.id),I=(D=C.over)==null?void 0:D.id,P=I==null?NaN:Number(I);if(!Number.isFinite(T))return;if(!Number.isFinite(P)||T===P){(R.current!=null||wn!=null)&&(R.current=null,Z(),wn!=null&&nn(null));return}const O=we(T),_=we(P);if(!O||!_||O!==_){R.current!=null&&(R.current=null,Z(),nn(null));return}R.current!==P&&(R.current=P,Z(),nn(null),U.current=window.setTimeout(()=>{R.current===P&&nn(P)},380))}function be(){Z(),R.current=null,tn.current=!1,zt(),Ce(),fn(null),nn(null),Jt(!1),Pr(null)}b.useEffect(()=>{const C=document.documentElement;return sn&&jt!=null?C.classList.add("is-note-swap-dragging"):C.classList.remove("is-note-swap-dragging"),()=>{try{C.classList.remove("is-note-swap-dragging")}catch{}}},[sn,jt]);function qe(C){sn&&be()}function Dt(C){if(!sn)return;const T=Number(C.active.id),I=wn!=null?Number(wn):NaN,P=Number.isFinite(T)?we(T):null;if(P){const O=P==="pinned"?Xe.current:Tt.current;if(O){const _=Array.from(O.querySelectorAll(".notes-masonry-col"));Y.current={section:P,heights:_.map(D=>D.getBoundingClientRect().height)}}}be(),!(!Number.isFinite(T)||!Number.isFinite(I)||T===I||!P)&&we(I)===P&&g(O=>{const _=O.findIndex(le=>Number(le==null?void 0:le.id)===T),D=O.findIndex(le=>Number(le==null?void 0:le.id)===I);if(_<0||D<0||!!O[_].pinned!=!!O[D].pinned)return O;const F=[...O],ie=F[_];return F[_]=F[D],F[D]=ie,requestAnimationFrame(()=>{try{vf(F)}catch{}}),F})}const st=b.useMemo(()=>{const C=new Map;for(const T of m){const I=Number(T==null?void 0:T.id);Number.isFinite(I)&&C.set(I,T)}return C},[m]),ft=(C,T)=>Math.max(0,Math.min(T,Math.floor(C)));function yt(C){const T=new Map;for(const I of C){const P=me.current.get(I);P&&T.set(I,P.getBoundingClientRect())}return T}function bt(C,T){const I=[];for(const[P,O]of C.entries()){const _=me.current.get(P);if(!_)continue;const D=_.getBoundingClientRect(),F=O.left-D.left,ie=O.top-D.top;F===0&&ie===0||I.push({el:_,dx:F,dy:ie})}if(I.length){for(const P of I)P.el.style.transition="none",P.el.style.transform=`translate(${P.dx}px, ${P.dy}px)`;document.body.getBoundingClientRect();for(const P of I){const O=P.el;O.style.transition=`transform ${T}ms cubic-bezier(.2,.9,.2,1)`,O.style.transform="";const _=()=>{try{O.style.transition="",O.removeEventListener("transitionend",_)}catch{}};O.addEventListener("transitionend",_)}}}function mt(){const C=Pe.current;if(!C.length){Ge.current=[],K.current=null;return}const T=Ge.current,I=new Array(C.length),P=[];try{for(let O=0;O=D.left&&C<=D.left+D.width&&T>=D.top&&T<=D.top+D.height)return _}let P=-1,O=Number.POSITIVE_INFINITY;for(let _=0;_P&&(P=F,I=O)}return{idx:I,area:P}}function Yt(C,T,I){const P=C.filter(D=>Number(D)!==Number(T)),O=ft(I,P.length),_=[];for(let D=0;DD!=="spacer").map(D=>Number(D)).filter(D=>Number.isFinite(D))}function Pt(C){const T=Pe.current,I=T.indexOf("spacer");if(I<0)return;const P=ft(C,T.length-1);if(P===I)return;const O=Ct(T,I,P),_=yt(O),D=[...T];D.splice(I,1),D.splice(P,0,"spacer");const F=Math.max(150,Math.min(650,he("rearrange")));Le.current={before:_,ms:F},Se(D)}b.useLayoutEffect(()=>{if(G==null)return;try{mt()}catch{}const C=Le.current;if(C){Le.current=null;try{bt(C.before,C.ms)}catch{}}},[G,We]);function ln(){wt.current=!1,ae.current=null,ot.current=null,it.current=null,Ge.current=[],K.current=null,Be.current=!1,ge.current=2,De.current=1;try{document.documentElement.classList.remove("is-note-rearrange-dragging")}catch{}if(S(),Ye.current!=null){try{cancelAnimationFrame(Ye.current)}catch{}Ye.current=null}}function wi(){de(null),Ue(null),Se([]),ln();try{requestAnimationFrame(()=>{try{window.dispatchEvent(new Event("notes-grid:recalc")),window.dispatchEvent(new Event("resize"))}catch{}})}catch{}}function $i(C){if(!C)return!1;try{return!!C.closest('button, a, input, textarea, select, [contenteditable="true"], .more-menu, .dropdown, .color-palette')}catch{return!1}}function Hc(C){var O;const T=me.current.get(C),I=(O=T==null?void 0:T.dataset)==null?void 0:O.__rowspan,P=I?Number(I):NaN;return Number.isFinite(P)&&P>0?P:2}function us(C,T){if(C===T)return!0;if(!C||!T||C.length!==T.length)return!1;for(let I=0;I1);for(let _=0;_[]);const O=10,_=P.map(le=>le.left).sort((le,ye)=>le-ye),D=[];for(const le of _){const ye=D[D.length-1];(D.length===0||Math.abs(le-ye)>O)&&D.push(le)}const F=Math.max(T,D.length,1),ie=Array.from({length:F},()=>[]);for(const le of P){let ye=0,$e=1/0;for(let lt=0;ltle.sort((ye,$e)=>ye.top-$e.top).map(ye=>ye.id))}function N1(){if(sn)try{const C=E1(Xe.current),T=E1(Tt.current);C&&Wt(I=>us(I,C)?I:C),T&&dn(I=>us(I,T)?I:T)}catch{}}b.useEffect(()=>{if(!sn){Wt(null),dn(null);return}const C=window.setTimeout(()=>{N1()},0);return()=>{try{clearTimeout(C)}catch{}}},[sn,m]);const T1=b.useMemo(()=>{try{const C=Math.max(1,Number(z)||1),T=rt&&rt.length?rt.length:0;return Math.max(C,T===C?T:0,1)}catch{return 1}},[sn,rt,z]),A1=b.useMemo(()=>{try{const C=Math.max(1,Number(L)||1),T=Mt&&Mt.length?Mt.length:0;return Math.max(C,T===C?T:0,1)}catch{return 1}},[sn,Mt,L]),pa=b.useMemo(()=>!ne||!rt?null:C1(rt,T1),[ne,rt,T1,st]),ma=b.useMemo(()=>!ne||!Mt?null:C1(Mt,A1),[ne,Mt,A1,st]);function bo(C){if(!C)return 0;if(C instanceof Date)return C.getTime();const T=Date.parse(String(C));return Number.isFinite(T)?T:0}function M1(C){const T=s||Ks;if(T.sortKey==="default")return C;const I=T.sortDir==="asc"?1:-1,P=[...C];return P.sort((O,_)=>{if(T.sortKey==="createdAt")return(bo(O.createdAt)-bo(_.createdAt))*I;if(T.sortKey==="updatedAt")return(bo(O.updatedAt)-bo(_.updatedAt))*I;if(T.sortKey==="title"){const D=String(O.title||"").trim(),F=String(_.title||"").trim(),ie=D.localeCompare(F,void 0,{sensitivity:"base"});return ie!==0?ie*I:(bo(O.createdAt)-bo(_.createdAt))*-1}return 0}),P}function I1(C){const T=new Date(C),I=(T.getDay()+6)%7;return T.setHours(0,0,0,0),T.setDate(T.getDate()-I),T.getTime()}function R1(C){const T=s||Ks;if(T.groupBy==="none")return[{key:"all",title:"",notes:C,sortMs:0}];const I=new Map;if(T.groupBy==="week"){const O=I1(new Date),_=O-7*24*60*60*1e3;for(const F of C){const ie=bo(F.createdAt),le=I1(new Date(ie||0));let ye="older",$e="Older",ke=0;le>=O?(ye="thisWeek",$e="This week",ke=O):le>=_&&(ye="lastWeek",$e="Last week",ke=_);const lt=I.get(ye)||{title:$e,notes:[],sortMs:ke};lt.notes.push(F),I.set(ye,lt)}return["thisWeek","lastWeek","older"].filter(F=>I.has(F)).map(F=>({key:F,title:I.get(F).title,notes:I.get(F).notes,sortMs:I.get(F).sortMs}))}if(T.groupBy==="month"){for(const _ of C){const D=bo(_.createdAt),F=new Date(D||0),ie=F.getFullYear(),le=F.getMonth(),ye=`${ie}-${String(le+1).padStart(2,"0")}`,$e=F.toLocaleString(void 0,{month:"long",year:"numeric"}),ke=new Date(ie,le,1).getTime(),lt=I.get(ye)||{title:$e,notes:[],sortMs:ke};lt.notes.push(_),I.set(ye,lt)}const P=Array.from(I.entries()).map(([_,D])=>({key:_,title:D.title,notes:D.notes,sortMs:D.sortMs})),O=T.sortKey==="createdAt"&&T.sortDir==="asc"?1:-1;return P.sort((_,D)=>(_.sortMs-D.sortMs)*O),P}return[{key:"all",title:"",notes:C,sortMs:0}]}b.useEffect(()=>{if(Me.current){Me.current=!1;return}requestAnimationFrame(()=>{try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}})},[t,e,i,m,s==null?void 0:s.groupBy,s==null?void 0:s.sortKey,s==null?void 0:s.sortDir,s==null?void 0:s.smartFilter]),b.useEffect(()=>{if(!p)return;const C=(()=>{try{return FA().deviceKey}catch{return null}})();let T=null;try{const P=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/events?token=${encodeURIComponent(p)}`;T=new WebSocket(P),T.onmessage=O=>{try{const _=JSON.parse(String(O.data||"{}"));if(!_||!_.type)return;switch(_.type){case"note-created":V();break;case"notes-reordered":{const D=_.payload||{},ie=(Array.isArray(D.ids)?D.ids:[]).map(le=>Number(le)).filter(le=>Number.isFinite(le));if(!ie.length)break;try{localStorage.setItem("notesOrder",JSON.stringify(ie))}catch{}g(le=>{const ye=new Map;for(const He of le){const et=Number(He==null?void 0:He.id);Number.isFinite(et)&&ye.set(et,He)}const $e=new Set,ke=[];for(const He of ie){const et=ye.get(He);et&&(ke.push(et),$e.add(He))}const lt=[];for(const He of le){const et=Number(He==null?void 0:He.id);(!Number.isFinite(et)||!$e.has(et))&<.push(He)}return[...lt,...ke]});break}case"note-deleted":{const D=_.payload||{},F=Number(D.noteId);Number.isFinite(F)&&g(ie=>ie.filter(le=>Number(le.id)!==F));break}case"note-images-changed":{const D=_.payload||{},F=Number(D.noteId);if(!Number.isFinite(F))break;(async()=>{try{const ie=await fetch(`/api/notes/${F}/images`,{headers:{Authorization:`Bearer ${p}`}});if(!ie.ok)return;const le=await ie.json(),ye=Array.isArray(le==null?void 0:le.images)?le.images:[];tt(F,ye)}catch{}})();break}case"note-color-changed":{const D=_.payload||{},F=Number(D.noteId);if(!Number.isFinite(F))break;const ie=typeof D.color=="string"?String(D.color):"";Ft(F,ie);break}case"note-collections-changed":{const D=_.payload||{},F=Number(D.noteId);if(!Number.isFinite(F))break;const ie=Array.isArray(D.collections)?D.collections:[];Kt(F,ie);break}case"note-collection-changed":{V();break}case"note-shared":V();break;case"note-unshared":{const D=Number(_.noteId||_.payload&&_.payload.noteId);Number.isFinite(D)&&g(F=>F.filter(ie=>Number(ie.id)!==D));break}case"collab-removed":{const D=Number(_.noteId||_.payload&&_.payload.noteId),F=Number(_.userId||_.payload&&_.payload.userId);Number.isFinite(D)&&Number.isFinite(F)&&g(ie=>ie.map(le=>{if(Number(le.id)!==D)return le;const $e=(Array.isArray(le.collaborators)?le.collaborators:[]).filter(ke=>{const lt=ke&&(ke.user||{});return(typeof lt.id=="number"?Number(lt.id):typeof ke.userId=="number"?Number(ke.userId):void 0)!==F});return{...le,collaborators:$e}}));break}case"user-photo-updated":{const D=_.payload||{},F=Number(D.userId),ie=String(D.userImageUrl||"");Number.isFinite(F)&&g(le=>le.map(ye=>{const $e=ye.owner||null,ke=$e&&$e.id===F?{...$e,userImageUrl:ie}:$e,He=(Array.isArray(ye.collaborators)?ye.collaborators:[]).map(et=>{const Et=et&&(et.user||{});return typeof Et.id=="number"&&Number(Et.id)===F?{...et,user:{...Et,userImageUrl:ie}}:et});return{...ye,owner:ke,collaborators:He}}));break}case"user-prefs-updated":{const D=_.payload||{},F=typeof D.deviceKey=="string"&&D.deviceKey?String(D.deviceKey):null;if(F&&C&&F!==C)break;try{if(typeof D.noteWidth=="number"){document.documentElement.style.setProperty("--note-card-width",`${Number(D.noteWidth)}px`);try{localStorage.setItem("prefs.noteWidth",String(Number(D.noteWidth)))}catch{}}if(typeof D.checklistTextSize=="number"){document.documentElement.style.setProperty("--checklist-text-size",`${Number(D.checklistTextSize)}px`);try{localStorage.setItem("prefs.checklistTextSize",String(Number(D.checklistTextSize)))}catch{}}if(typeof D.noteLineSpacing=="number"){document.documentElement.style.setProperty("--note-line-height",String(Number(D.noteLineSpacing)));try{localStorage.setItem("prefs.noteLineSpacing",String(Number(D.noteLineSpacing)))}catch{}}if(typeof D.imageThumbSize=="number"){document.documentElement.style.setProperty("--image-thumb-size",`${Number(D.imageThumbSize)}px`);try{localStorage.setItem("prefs.imageThumbSize",String(Number(D.imageThumbSize)))}catch{}}if(typeof D.fontFamily=="string"&&D.fontFamily){document.documentElement.style.setProperty("--app-font-family",String(D.fontFamily));try{localStorage.setItem("prefs.fontFamily",String(D.fontFamily))}catch{}}}catch{}try{window.dispatchEvent(new Event("notes-grid:recalc")),window.dispatchEvent(new Event("resize"))}catch{}break}}}catch{}}}catch{}return()=>{try{T&&T.close()}catch{}}},[p]),b.useRef(null),b.useEffect(()=>{const C=new WeakSet,T=new WeakMap;let I=null,P=null;function O(){if(wt.current)return;const ie=(()=>{try{const En=window.matchMedia,hr=!!(En&&(En("(pointer: coarse)").matches||En("(any-pointer: coarse)").matches)),Bn=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,ai=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight,ds=Math.min(Bn,ai);if(hr){if(ds<=600)return"phone";if(ds<=1024)return ai>=Bn?"tablet-portrait":"tablet-landscape"}return"desktop"}catch{return"desktop"}})();ie!==N.current&&(N.current=ie,M(ie));const le=getComputedStyle(document.documentElement);let ye=parseInt(le.getPropertyValue("--note-card-width"))||300;const $e=parseInt(le.getPropertyValue("--gap"))||16,ke=document.querySelector(".main-area"),lt=ke?ke.clientWidth:0,He=document.querySelector(".notes-area"),et=He?He.clientWidth:0,Et=document.querySelector(".sidebar"),Gt=Et?Et.clientWidth:parseInt(le.getPropertyValue("--sidebar-width"))||220,Zn=window.innerWidth-Gt-64,er=Math.max(lt,et,Zn,0),li=Array.from(document.querySelectorAll(".notes-area .notes-grid, .notes-area .notes-masonry")),Ds=document.querySelector(".notes-area")||document.querySelector(".main-area")||document.body,tr=Ds.getBoundingClientRect(),nr=Math.floor(tr.right),wf=parseInt(getComputedStyle(Ds).paddingRight||"0")||0;for(const En of li){const hr=getComputedStyle(En),Bn=parseInt(hr.getPropertyValue("--gap"))||$e,ai=Math.floor(En.getBoundingClientRect().left),ds=nr-wf,Un=Math.max(0,ds-ai),Bi=Math.max(0,Math.min(er,Un)),Ui=Math.max(1,Math.floor((Bi+Bn)/(ye+Bn)));let Hn=Ui,ko=ye;if(ie==="phone"){const $1=(()=>{try{const Dj=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,Oj=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight;return Dj>Oj}catch{return!1}})(),Ij=$1?120:140,Rj=$1?4:2;let Wc=Math.floor((Un+Bn)/(Ij+Bn));Wc=Math.max(2,Math.min(Rj,Wc||0)),Hn=Wc,ko=Math.max(110,Math.floor((Un-Math.max(0,Wc-1)*Bn)/Wc))}else ie==="tablet-portrait"?Hn=Math.max(2,Math.min(3,Ui)):ie==="tablet-landscape"&&(Hn=Math.max(3,Math.min(4,Ui)));ie==="phone"?En.style.setProperty("--note-card-width",`${ko}px`):En.style.removeProperty("--note-card-width");const Aj=Hn*ko+Math.max(0,Hn-1)*Bn,Mj=Math.min(Aj,Un);Number(En.dataset.__cols||"0")!==Hn&&(En.style.setProperty("--cols",String(Hn)),En.dataset.__cols=String(Hn)),En.style.width=`${Mj}px`;try{En===Xe.current?W.current!==Hn&&(W.current=Hn,X(Hn)):En===Tt.current&&te.current!==Hn&&(te.current=Hn,H(Hn))}catch{}}try{window.__notesGridDebug={cardWidth:ye,gap:$e,availMain:lt,availArea:et,availFallback:Zn,avail:er,grids:li.map(En=>{const hr=getComputedStyle(En),Bn=parseInt(hr.getPropertyValue("--gap"))||$e,ai=Math.floor(En.getBoundingClientRect().left),ds=nr-wf,Un=Math.max(0,ds-ai),Bi=Math.max(0,Math.min(er,Un)),Ui=Math.max(1,Math.floor((Bi+Bn)/(ye+Bn))),Hn=Math.min(Ui*ye+Math.max(0,Ui-1)*Bn,Un);return{left:ai,rightEdge:ds,availableToRight:Un,gridAvail:Bi,gridCols:Ui,gridTotal:Hn}}),autoFit:localStorage.getItem("prefs.autoFitColumns")==="1",anim:{resizeMs:he("resize"),swapMs:he("swap"),rearrangeMs:he("rearrange")},showGuides:En=>{for(const hr of li)if(En){const Bn=parseInt(getComputedStyle(hr).getPropertyValue("--gap"))||$e,ai=ye+Bn,Un=(parseInt(le.getPropertyValue("--row"))||8)+Bn,Bi=`repeating-linear-gradient(to right, rgba(255,255,255,0.08) 0, rgba(255,255,255,0.08) 1px, transparent 1px, transparent ${ai}px)`,Ui=`repeating-linear-gradient(to bottom, rgba(255,255,255,0.08) 0, rgba(255,255,255,0.08) 1px, transparent 1px, transparent ${Un}px)`;hr.style.backgroundImage=`${Bi}, ${Ui}`,hr.style.backgroundSize=`${ai}px 100%, 100% ${Un}px`,hr.style.backgroundPosition="left top, left top"}else hr.style.backgroundImage="",hr.style.backgroundSize=""}}}catch{}try{for(const En of li){const hr=getComputedStyle(En),Bn=parseInt(hr.getPropertyValue("--row"))||parseInt(le.getPropertyValue("--row"))||8,ai=parseInt(hr.getPropertyValue("--gap"))||$e,ds=Array.from(En.querySelectorAll("[data-note-id]"));for(const Un of ds){const Bi=Un.querySelector(".note-card"),Ui=Bi?Bi.getBoundingClientRect().height:Un.getBoundingClientRect().height,Hn=Math.max(1,Math.ceil((Ui+ai)/(Bn+ai)));Un.dataset.__rowspan!==String(Hn)&&(Un.style.gridRowEnd=`span ${Hn}`,Un.dataset.__rowspan=String(Hn));try{if(I){const ko=Bi||Un;C.has(ko)||(I.observe(ko),C.add(ko),Bi&&T.set(ko,Un))}}catch{}}}}catch{}}function _(){wt.current||P==null&&(P=requestAnimationFrame(()=>{P=null,O()}))}O();const D=document.querySelector(".main-area")||document.body,F=new ResizeObserver(()=>_());F.observe(D);try{I=new ResizeObserver(ie=>{try{if(wt.current)return;const le=getComputedStyle(document.documentElement),ye=parseInt(le.getPropertyValue("--gap"))||16,$e=parseInt(getComputedStyle(document.body).getPropertyValue("--gap"))||ye;for(const ke of ie){const lt=ke.target,He=T.get(lt)||lt,et=He!=null&&He.closest?He.closest(".notes-grid, .notes-masonry"):null,Et=getComputedStyle(et||He),Gt=parseInt(Et.getPropertyValue("--row"))||parseInt(le.getPropertyValue("--row"))||8,Jr=parseInt(Et.getPropertyValue("--gap"))||$e,Zn=lt.getBoundingClientRect().height,er=Math.max(1,Math.ceil((Zn+Jr)/(Gt+Jr)));He.dataset.__rowspan!==String(er)&&(He.style.gridRowEnd=`span ${er}`,He.dataset.__rowspan=String(er))}}catch{_()}})}catch{}return window.addEventListener("resize",_),window.addEventListener("notes-grid:recalc",_),()=>{F.disconnect(),window.removeEventListener("resize",_),window.removeEventListener("notes-grid:recalc",_);try{P!=null&&cancelAnimationFrame(P)}catch{}try{I&&I.disconnect()}catch{}}},[]);const D1=b.useMemo(()=>{var T;const C=new Map;for(let I=0;I{const C=Array.isArray(t)?t:[],T=e==null?null:Number(e),I=(i||"").trim().toLowerCase(),P=ke=>{if(!C.length)return!0;const lt=(ke.noteLabels||[]).map(He=>{var et;return(et=He.label)==null?void 0:et.id}).filter(He=>typeof He=="number");return C.some(He=>lt.includes(He))},O=ke=>!!(!I||String(ke.title||"").toLowerCase().includes(I)||String(ke.body||"").toLowerCase().includes(I)||(Array.isArray(ke.items)?ke.items:[]).some(et=>String(et.content||"").toLowerCase().includes(I))||(Array.isArray(ke.noteLabels)?ke.noteLabels:[]).some(et=>{var Et;return String(((Et=et.label)==null?void 0:Et.name)||"").toLowerCase().includes(I)})),_=ke=>{var et;if(T==null||!Number.isFinite(T))return!0;const lt=Array.isArray(ke.viewerCollections)?ke.viewerCollections:[];for(const Et of lt){const Gt=Et&&typeof Et.id=="number"?Number(Et.id):null;if(Gt!=null&&Number.isFinite(Gt)&&Number(Gt)===Number(T))return!0}const He=Array.isArray(ke.noteCollections)?ke.noteCollections:[];for(const Et of He){const Gt=Et&&typeof Et.collectionId=="number"?Number(Et.collectionId):typeof((et=Et==null?void 0:Et.collection)==null?void 0:et.id)=="number"?Number(Et.collection.id):null;if(Gt!=null&&Number.isFinite(Gt)&&Number(Gt)===Number(T))return!0}return!1},D=r==null?null:Number(r),F=ke=>{var lt,He;if(D==null||!Number.isFinite(D))return!0;try{const et=typeof((lt=ke==null?void 0:ke.owner)==null?void 0:lt.id)=="number"?Number(ke.owner.id):typeof(ke==null?void 0:ke.ownerId)=="number"?Number(ke.ownerId):null;if(et!=null&&Number(et)===Number(D))return!0;const Et=Array.isArray(ke==null?void 0:ke.collaborators)?ke.collaborators:[];for(const Gt of Et){const Jr=typeof((He=Gt==null?void 0:Gt.user)==null?void 0:He.id)=="number"?Number(Gt.user.id):typeof(Gt==null?void 0:Gt.userId)=="number"?Number(Gt.userId):null;if(Jr!=null&&Number(Jr)===Number(D))return!0}}catch{}return!1},ie=m.filter(ke=>ke.pinned).filter(P).filter(_).filter(F).filter(O),le=m.filter(ke=>!ke.pinned).filter(P).filter(_).filter(F).filter(O),ye=M1(ie),$e=M1(le);return{pinned:ye,others:$e,pinnedGroups:R1(ye),otherGroups:R1($e)}},[m,t,e,r,i,s]),Vc=b.useMemo(()=>{var ie,le;const C=[],T=Array.isArray(n)?n:[],I=T.length?T.map(ye=>String(ye.name||"")).filter(Boolean).join(" / "):"";I&&C.push({id:"collection",text:`Collection: ${I}`,onClear:()=>{try{u&&u([])}catch{}}});const P=Array.isArray(t)?t:[];if(P.length){const ye=new Map;for(const ke of m){const lt=Array.isArray(ke==null?void 0:ke.noteLabels)?ke.noteLabels:[];for(const He of lt){const et=typeof((ie=He==null?void 0:He.label)==null?void 0:ie.id)=="number"?Number(He.label.id):null,Et=typeof((le=He==null?void 0:He.label)==null?void 0:le.name)=="string"?String(He.label.name):null;et!=null&&Et&&ye.set(et,Et)}}const $e=P.map(ke=>ye.get(Number(ke))||`#${Number(ke)}`).join(", ");C.push({id:"labels",text:`Labels: ${$e}`,onClear:()=>{try{l&&l([])}catch{}}})}const O=r==null?null:Number(r);if(O!=null&&Number.isFinite(O)){let ye="";try{e:for(const $e of m){const ke=$e==null?void 0:$e.owner;if(ke&&typeof ke.id=="number"&&Number(ke.id)===O){ye=String(ke.name||ke.email||O);break e}const lt=Array.isArray($e==null?void 0:$e.collaborators)?$e.collaborators:[];for(const He of lt){const et=He==null?void 0:He.user;if(et&&typeof et.id=="number"&&Number(et.id)===O){ye=String(et.name||et.email||O);break e}}}}catch{}C.push({id:"collaborator",text:`With: ${ye||String(O)}`,onClear:()=>{try{a&&a(null)}catch{}}})}const _=(i||"").trim();_&&C.push({id:"search",text:`Search: ${_}`,onClear:()=>{try{d&&d("")}catch{}}});const D=s||Ks;if(D.sortKey!=="default"){const ye=D.sortKey==="createdAt"?`Date created: ${D.sortDir==="asc"?"Ascending":"Descending"}`:D.sortKey==="updatedAt"?`Date updated: ${D.sortDir==="asc"?"Ascending":"Descending"}`:D.sortKey==="title"?`Alphabetical: ${D.sortDir==="asc"?"A→Z":"Z→A"}`:`Sort: ${String(D.sortKey)}`;C.push({id:"sort",text:ye,onClear:()=>{try{f&&f({...D,sortKey:"default",sortDir:Ks.sortDir})}catch{}}})}if(D.groupBy&&D.groupBy!=="none"&&C.push({id:"group",text:`Grouping: ${D.groupBy==="week"?"Week":D.groupBy==="month"?"Month":String(D.groupBy)}`,onClear:()=>{try{f&&f({...D,groupBy:"none"})}catch{}}}),D.smartFilter&&D.smartFilter!=="none"){const ye=D.smartFilter==="dueSoon"?"Filter: Due soon":D.smartFilter==="leastAccessed"?"Filter: Least accessed":D.smartFilter==="mostEdited"?"Filter: Most edited":D.smartFilter==="atRisk"?"Filter: At risk":`Filter: ${String(D.smartFilter)}`;C.push({id:"smartFilter",text:ye,onClear:()=>{try{f&&f({...D,smartFilter:"none"})}catch{}}})}const F=C.length>0;return{title:I||"All notes",chips:C,show:!0,hasAnyFilter:F}},[n,t,r,i,m,s,l,a,u,d,f]);b.useEffect(()=>{if(!sn)return;const C=Y.current;if(!C)return;Y.current=null;const T=C.section==="pinned"?Xe.current:Tt.current;if(!T)return;const I=Array.from(T.querySelectorAll(".notes-masonry-col"));if(!I.length)return;const P=C.heights,O=I.map(D=>D.getBoundingClientRect().height),_=he("swap");for(let D=0;D{try{F.style.transition="",F.style.height="",F.removeEventListener("transitionend",le)}catch{}};F.addEventListener("transitionend",le)}},[sn,m]);function gf(C,T){const I=new Map;me.current.forEach((P,O)=>{P&&I.set(O,P.getBoundingClientRect())}),Me.current=!0,g(P=>{const O=[...P],_=O[C],D=O[T];return!_||!D?P:(O[C]=D,O[T]=_,O)}),requestAnimationFrame(()=>{const P=new Map;me.current.forEach((O,_)=>{O&&P.set(_,O.getBoundingClientRect())}),P.forEach((O,_)=>{const D=I.get(_),F=me.current.get(_);if(!D||!F)return;const ie=D.left-O.left,le=D.top-O.top;if(ie===0&&le===0)return;F.style.transition="none",F.style.transform=`translate(${ie}px, ${le}px)`,F.getBoundingClientRect(),F.style.transition=`transform ${he("swap")}ms ease-in-out`,F.style.transform="";const ye=()=>{try{F.style.transition="",F.removeEventListener("transitionend",ye)}catch{}};F.addEventListener("transitionend",ye)})})}function yf(C,T){const I=new Map;me.current.forEach((P,O)=>{P&&I.set(O,P.getBoundingClientRect())}),Me.current=!0,g(P=>{const O=[...P];if(C<0||T<0||C>=O.length||T>=O.length)return P;const[_]=O.splice(C,1);return O.splice(T,0,_),O}),requestAnimationFrame(()=>{const P=new Map;me.current.forEach((O,_)=>{O&&P.set(_,O.getBoundingClientRect())}),P.forEach((O,_)=>{const D=I.get(_),F=me.current.get(_);if(!D||!F)return;const ie=D.left-O.left,le=D.top-O.top;if(ie===0&&le===0)return;F.style.transition="none",F.style.transform=`translate(${ie}px, ${le}px)`,F.getBoundingClientRect(),F.style.transition=`transform ${he("rearrange")}ms ease-in-out`,F.style.transform="";const ye=()=>{try{F.style.transition="",F.removeEventListener("transitionend",ye)}catch{}};F.addEventListener("transitionend",ye)})})}async function vf(C){try{localStorage.setItem("notesOrder",JSON.stringify(C.map(T=>T.id)))}catch{}if(p)try{const T=C.map(P=>P.id),I=await fetch("/api/notes/order",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({ids:T})});if(!I.ok)throw new Error(await I.text())}catch(T){console.error("Failed to persist note order to server",T)}}const xo=b.useCallback(C=>{if(C&&C.type==="filter:collection"&&typeof C.collectionId=="number"){try{a&&a(null)}catch{}try{c&&c(Number(C.collectionId),typeof C.collectionName=="string"?String(C.collectionName):void 0)}catch{}return}if(C&&C.type==="filter:collaborator"&&typeof C.userId=="number"){try{a&&a(Number(C.userId))}catch{}return}if(C&&C.type==="filter:labels"){const T=typeof C.labelId=="number"?Number(C.labelId):null;if(T!=null&&Number.isFinite(T)){try{l&&l([T])}catch{}return}if(Array.isArray(C.labelIds)){const I=C.labelIds.map(P=>Number(P)).filter(P=>Number.isFinite(P));try{l&&l(I)}catch{}return}}if(C&&C.type==="labels"&&typeof C.noteId=="number"&&Array.isArray(C.labels)){pe(C.noteId,C.labels);return}if(C&&C.type==="images"&&typeof C.noteId=="number"&&Array.isArray(C.images)){tt(C.noteId,C.images);return}if(C&&C.type==="color"&&typeof C.noteId=="number"){Ft(C.noteId,typeof C.color=="string"?String(C.color):"");return}if(C&&C.type==="collections"&&typeof C.noteId=="number"&&Array.isArray(C.collections)){Kt(C.noteId,C.collections);return}if(C&&C.type==="collection"&&typeof C.noteId=="number"){V();return}V()},[p,s,i,t,e,l,a,c]);b.useEffect(()=>{!y&&p&&x(!0)},[y,p]);const Lg=C=>{try{const T=Number((C==null?void 0:C.cardSpan)||1);return Math.max(1,Math.min(k==="phone"?2:3,Number.isFinite(T)?T:1))}catch{return 1}},_g=sn&&jt!=null&&st.get(Number(jt))||null,L1=A&&G!=null&&st.get(Number(G))||null;function _1(C,T,I,P,O){if(!A||Ae||!Zt||C.button!=null&&C.button!==0||$i(C.target)||Ee.current!=null||Be.current)return;const _=me.current.get(Number(T));if(!_)return;const D=_.getBoundingClientRect();if(!D||D.width<10||D.height<10)return;const F=String(C.pointerType||"mouse"),ie=C.pointerId??1,le=C.currentTarget;if(ae.current={noteId:Number(T),section:I,sectionIds:Array.isArray(P)?P.map(ye=>Number(ye)).filter(ye=>Number.isFinite(ye)):[],startClientX:C.clientX,startClientY:C.clientY,lastClientX:C.clientX,lastClientY:C.clientY,pointerId:ie,pointerType:F,touchArmed:!1,longPressTimerId:null,captureEl:le},ot.current={x:C.clientX,y:C.clientY},it.current=D,De.current=Math.max(1,Math.min(3,Number(O)||1)),ge.current=(()=>{var ke;const ye=(ke=_==null?void 0:_.dataset)==null?void 0:ke.__rowspan,$e=ye?Number(ye):NaN;return Number.isFinite($e)&&$e>0?$e:2})(),F==="touch"){const ye=window.setTimeout(()=>{var Et,Gt;const $e=ae.current;if(!$e||Number($e.pointerId)!==Number(ie)||Number($e.noteId)!==Number(T)||wt.current||Ee.current!=null||Be.current)return;const ke=typeof $e.lastClientX=="number"?$e.lastClientX:$e.startClientX,lt=typeof $e.lastClientY=="number"?$e.lastClientY:$e.startClientY,He=ke-$e.startClientX,et=lt-$e.startClientY;if(He*He+et*et>9){ae.current=null;return}$e.touchArmed=!0;try{(Gt=(Et=$e.captureEl)==null?void 0:Et.setPointerCapture)==null||Gt.call(Et,$e.pointerId)}catch{}zg($e.sectionIds)},220);ae.current.longPressTimerId=ye;return}}function zg(C){const T=ae.current,I=it.current;if(!T||!I)return;const P=T.noteId,O=Math.max(0,C.findIndex(_=>Number(_)===Number(P)));wt.current=!0,Jt(!0),de(P),Ue(T.section),Se(Yt(C,P,O));try{document.documentElement.classList.add("is-note-rearrange-dragging")}catch{}T.pointerType==="touch"&&$(),requestAnimationFrame(()=>{const _=xt.current;_&&(_.style.transform="translate(0px, 0px) scale(1.03)")})}function z1(C,T){const I=it.current,P=ot.current;if(!I||!P)return{dx:0,dy:0};let O=C-P.x,_=T-P.y;const D=K.current;if(!D)return{dx:O,dy:_};const F=18,ie=D.left-F,le=D.right-I.width+F,ye=D.top-F,$e=D.bottom-I.height+F,ke=I.left+O,lt=I.top+_,He=Math.min(Math.max(ke,ie),le),et=Math.min(Math.max(lt,ye),$e);return O=He-I.left,_=et-I.top,{dx:O,dy:_}}function Tj(C,T){const I=it.current,P=ot.current,O=xt.current;if(!I||!P||!O)return;const{dx:_,dy:D}=z1(C,T);O.style.transform=`translate(${_}px, ${D}px) scale(1.03)`}return b.useEffect(()=>{if(!A)return;const C=I=>{const P=ae.current;if(!P||P.pointerId!=null&&I.pointerId!=null&&Number(I.pointerId)!==Number(P.pointerId))return;P.pointerType==="touch"&&(P.lastClientX=I.clientX,P.lastClientY=I.clientY);const O=Ee.current,_=P.sectionIds;if(!(!_||!_.length)){if(O==null&&!wt.current){const D=I.clientX-P.startClientX,F=I.clientY-P.startClientY;if(P.pointerType==="touch"){const ie=Math.abs(D),le=Math.abs(F),ye=4;if(!P.touchArmed){if(ie>ye||le>ye){try{P.longPressTimerId!=null&&window.clearTimeout(P.longPressTimerId)}catch{}ae.current=null}return}zg(_)}else{if(D*D+F*F<6*6)return;zg(_)}}if(wt.current){try{I.preventDefault()}catch{}Ye.current==null&&(Ye.current=requestAnimationFrame(()=>{Ye.current=null,Tj(I.clientX,I.clientY);const D=Pe.current,F=Ge.current;if(!D.length||F.length!==D.length)return;const ie=it.current,le=ot.current;if(!ie||!le)return;const{dx:ye,dy:$e}=z1(I.clientX,I.clientY),ke=ie.left+ye,lt=ie.top+$e,He={left:ke,top:lt,right:ke+ie.width,bottom:lt+ie.height},et=ke+ie.width/2,Et=lt+ie.height/2,Gt=on(He),Jr=Gt.idx>=0&&Gt.area>0?Gt.idx:Qt(et,Et);if(Jr<0)return;const Zn=ze.current;if(Jr===Zn)return;const er=F[Zn]||null,li=F[Jr]||null;if(!er||!li)return;const Ds=li.cx-er.cx,tr=li.cy-er.cy,nr=(li.cx+er.cx)/2,wf=(li.cy+er.cy)/2,En=(et-nr)*Ds+(Et-wf)*tr,hr=Math.sqrt(Ds*Ds+tr*tr)||1,Bn=P.pointerType==="touch"?10:6;En<=Bn*hr||Pt(Jr)}))}}},T=I=>{const P=ae.current;if(!P||P.pointerId!=null&&I.pointerId!=null&&Number(I.pointerId)!==Number(P.pointerId))return;try{P.longPressTimerId!=null&&window.clearTimeout(P.longPressTimerId)}catch{}if(!wt.current||Ee.current==null){ae.current=null;return}const O=Number(Ee.current),_=Ke.current,D=Pe.current,F=D.indexOf("spacer"),ie=F>=0?D[F+1]:null,le=typeof ie=="number"?Number(ie):null;Be.current=!0;const ye=xt.current,$e=it.current,ke=Math.max(150,Math.min(650,he("rearrange"))),lt=oe.current,He=lt?lt.getBoundingClientRect():null;if(ye&&$e&&He){const Et=He.left-$e.left,Gt=He.top-$e.top;ye.style.transition=`transform ${ke}ms cubic-bezier(.2,.9,.2,1)`,ye.style.transform=`translate(${Et}px, ${Gt}px) scale(1)`}_&&g(Et=>{var li,Ds;const Gt=Et.findIndex(tr=>Number(tr==null?void 0:tr.id)===O);if(Gt<0)return Et;const Jr=Et[Gt];if(!!Jr.pinned!=(_==="pinned"))return Et;const Zn=[...Et];Zn.splice(Gt,1);let er=Zn.length;if(le!=null){const tr=Zn.findIndex(nr=>Number(nr==null?void 0:nr.id)===le);tr>=0&&(er=tr)}else if(_==="pinned"){let tr=-1;for(let nr=0;nr{try{vf(Zn)}catch{}}),Zn});const et=()=>{try{ye&&(ye.style.transition="",ye.removeEventListener("transitionend",et))}catch{}Jt(!1),wi()};ye?(ye.addEventListener("transitionend",et),window.setTimeout(et,ke+80)):et()};return window.addEventListener("pointermove",C,{capture:!0,passive:!1}),window.addEventListener("pointerup",T,{capture:!0}),window.addEventListener("pointercancel",T,{capture:!0}),()=>{try{window.removeEventListener("pointermove",C,{capture:!0})}catch{}try{window.removeEventListener("pointerup",T,{capture:!0})}catch{}try{window.removeEventListener("pointercancel",T,{capture:!0})}catch{}}},[A,Ae,p]),y&&!w?h.jsx("div",{children:"Loading notes…"}):h.jsxs("section",{className:"notes-area",children:[h.jsxs("div",{className:"take-note-sticky",children:[h.jsx(HJ,{onCreated:V,openRequest:{nonce:_t,mode:at},activeCollection:At}),Vc.show&&h.jsx("div",{className:"grid-context",role:"region","aria-label":"Current view",children:h.jsxs("div",{className:"grid-context__text",children:[h.jsxs("div",{className:"grid-context__title-row",children:[h.jsx("div",{className:"grid-context__title",children:Vc.title}),!!o&&!!Vc.hasAnyFilter&&h.jsx("button",{type:"button",className:"grid-context__clear",onClick:()=>{try{o()}catch{}},"aria-label":"Clear all filters",title:"Clear",children:"Clear"})]}),!!((F1=Vc.chips)!=null&&F1.length)&&h.jsx("div",{className:"grid-context__chips","aria-label":"Active filters",children:Vc.chips.map(C=>h.jsxs("span",{className:"grid-chip",children:[h.jsx("span",{className:"grid-chip__text",title:String(C.text||""),children:String(C.text||"")}),typeof C.onClear=="function"&&h.jsx("button",{type:"button",className:"grid-chip__clear",onClick:()=>{try{C.onClear()}catch{}},"aria-label":`Clear ${String(C.text||"filter")}`,title:"Clear",children:"×"})]},String(C.id)))})]})})]}),Q&&h.jsx("div",{className:"mobile-add-backdrop","aria-hidden":"true",onPointerDown:()=>Je(!1)}),h.jsxs("div",{className:"mobile-add-note","aria-label":"Add note",children:[Q&&h.jsxs("div",{className:"mobile-add-menu",role:"menu","aria-label":"Create",children:[h.jsxs("button",{type:"button",className:"mobile-add-menu-item",role:"menuitem",onClick:()=>Vt("text"),children:[h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:h.jsx("path",{fill:"currentColor",d:"M6 2h9l5 5v15a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Zm8 1.5V8h4.5L14 3.5ZM7 11h10v1.6H7V11Zm0 4h10v1.6H7V15Zm0 4h7v1.6H7V19Z"})}),h.jsx("span",{children:"New note"})]}),h.jsxs("button",{type:"button",className:"mobile-add-menu-item",role:"menuitem",onClick:()=>Vt("checklist"),children:[h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:h.jsx("path",{fill:"currentColor",d:"M9.2 7.2 7.9 5.9 6 7.8 5.1 6.9 4 8l2 2 3.2-3.2ZM10.5 8H20v1.6h-9.5V8Zm-1.3 6.2-1.3-1.3L6 14.8l-.9-.9L4 15l2 2 3.2-3.2ZM10.5 15H20v1.6h-9.5V15Z"})}),h.jsx("span",{children:"New checklist"})]})]}),h.jsx("button",{type:"button",className:"mobile-add-fab","aria-haspopup":"menu","aria-expanded":Q,onClick:()=>Je(C=>!C),children:"+"})]}),h.jsx(WJ,{open:ct!=null,mode:ct||"text",onClose:()=>nt(null),onCreated:V,activeCollection:At}),sn?h.jsxs(F3,{sensors:Ie,collisionDetection:J_,onDragStart:Ve,onDragOver:Rt,onDragEnd:Dt,onDragCancel:qe,children:[O1.length>0&&h.jsxs("div",{className:"notes-section",children:[h.jsx("h4",{className:"section-title",children:"Pinned"}),j1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid notes-grid--swap",ref:Xe,children:C.notes.map(T=>{const I=Lg(T),P=(O,_)=>{O?me.current.set(_,O):me.current.delete(_)};return h.jsx(SN,{note:T,setItemRef:P,style:{gridColumn:`span ${I}`},isDragSource:jt!=null&&Number(jt)===Number(T.id),isDragTarget:wn!=null&&Number(wn)===Number(T.id),disabled:Ae,onChange:xo},T.id)})})]},C.key))]}),h.jsx("div",{className:"notes-section",children:P1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid notes-grid--swap",ref:Tt,children:C.notes.map(T=>{const I=Lg(T),P=(O,_)=>{O?me.current.set(_,O):me.current.delete(_)};return h.jsx(SN,{note:T,setItemRef:P,style:{gridColumn:`span ${I}`},isDragSource:jt!=null&&Number(jt)===Number(T.id),isDragTarget:wn!=null&&Number(wn)===Number(T.id),disabled:Ae,onChange:xo},T.id)})})]},C.key))}),h.jsx(s4,{children:_g?h.jsx("div",{className:"note-drag-ghost",style:{width:rn?`${rn.width}px`:(()=>{const C=Lg(_g);return`calc(${C} * var(--note-card-width) + ${Math.max(0,C-1)} * var(--gap))`})(),height:rn?`${rn.height}px`:void 0},children:h.jsx(El,{note:_g,onChange:xo})}):null})]}):h.jsxs(h.Fragment,{children:[O1.length>0&&h.jsxs("div",{className:"notes-section",children:[h.jsx("h4",{className:"section-title",children:"Pinned"}),j1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid"+(kt?" notes-grid--manual":""),ref:Xe,children:A&&je==="pinned"&&We.length?We.map((T,I)=>{var F;if(T==="spacer")return h.jsx("div",{ref:oe,className:"note-rearrange-spacer",style:{gridColumn:`span ${De.current}`,gridRowEnd:`span ${ge.current}`,height:`${((F=it.current)==null?void 0:F.height)||0}px`}},"spacer");const P=Number(T),O=st.get(P);if(!O)return null;const _=Math.max(1,Math.min(3,Number(O.cardSpan||1))),D=(pa==null?void 0:pa.get(Number(O.id)))||null;return h.jsx("div",{"data-note-id":O.id,style:D?{gridColumnStart:D.colStart,gridColumnEnd:`span ${D.colSpan}`,gridRowStart:D.rowStart,gridRowEnd:`span ${D.rowSpan}`}:{gridColumn:`span ${_}`},ref:ie=>{ie?me.current.set(O.id,ie):me.current.delete(O.id)},children:h.jsx(El,{note:O,onChange:xo})},O.id)}):C.notes.map(T=>{const I=D1.get(Number(T.id))??-1,P=Math.max(1,Math.min(3,Number(T.cardSpan||1))),O=(pa==null?void 0:pa.get(Number(T.id)))||null,_=C.notes.map(F=>Number(F.id)).filter(F=>Number.isFinite(F)),D=A?{draggable:!1,onPointerDown:F=>_1(F,Number(T.id),"pinned",_,P)}:{draggable:Zt&&!Ae,onDragStart:F=>{Zt&&(xe.current=Number(T.id),F.dataTransfer.setData("text/plain",String(I)),se.current=I)},onDragEnd:()=>{Zt&&(se.current=null,xe.current=null)},onDragOver:F=>{if(Zt){F.preventDefault();try{const ie=localStorage.getItem("prefs.dragBehavior")||"swap",le=se.current;if(ie==="rearrange"&&le!==null&&le!==I){const ye=Date.now(),ke=F.currentTarget.getBoundingClientRect(),lt=Math.min(28,Math.floor(ke.height*.2)),He=Math.min(20,Math.floor(ke.width*.2)),et=F.clientY>ke.top+lt&&F.clientYke.left+He&&F.clientXGt&&(yf(le,I),q.current=ye,se.current=I)}}catch{}}},onDrop:F=>{if(!Zt)return;F.preventDefault();const ie=Number(F.dataTransfer.getData("text/plain")),le=Number.isFinite(ie)?ie:se.current??-1,ye=I;try{(localStorage.getItem("prefs.dragBehavior")||"swap")==="rearrange"?yf(le,ye):gf(le,ye)}catch{gf(le,ye)}requestAnimationFrame(()=>{try{vf(E.current)}catch{}}),se.current=null,xe.current=null}};return h.jsx("div",{"data-note-id":T.id,style:O?{gridColumnStart:O.colStart,gridColumnEnd:`span ${O.colSpan}`,gridRowStart:O.rowStart,gridRowEnd:`span ${O.rowSpan}`}:{gridColumn:`span ${P}`},ref:F=>{F?me.current.set(T.id,F):me.current.delete(T.id)},...D,children:h.jsx(El,{note:T,onChange:xo})},T.id)})})]},C.key))]}),h.jsx("div",{className:"notes-section",children:P1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid"+(kt?" notes-grid--manual":""),ref:Tt,children:A&&je==="others"&&We.length?We.map((T,I)=>{var F;if(T==="spacer")return h.jsx("div",{ref:oe,className:"note-rearrange-spacer",style:{gridColumn:`span ${De.current}`,gridRowEnd:`span ${ge.current}`,height:`${((F=it.current)==null?void 0:F.height)||0}px`}},"spacer");const P=Number(T),O=st.get(P);if(!O)return null;const _=Math.max(1,Math.min(3,Number(O.cardSpan||1))),D=(ma==null?void 0:ma.get(Number(O.id)))||null;return h.jsx("div",{"data-note-id":O.id,style:D?{gridColumnStart:D.colStart,gridColumnEnd:`span ${D.colSpan}`,gridRowStart:D.rowStart,gridRowEnd:`span ${D.rowSpan}`}:{gridColumn:`span ${_}`},ref:ie=>{ie?me.current.set(O.id,ie):me.current.delete(O.id)},children:h.jsx(El,{note:O,onChange:xo})},O.id)}):C.notes.map(T=>{const I=D1.get(Number(T.id))??-1,P=Math.max(1,Math.min(3,Number(T.cardSpan||1))),O=(ma==null?void 0:ma.get(Number(T.id)))||null,_=C.notes.map(F=>Number(F.id)).filter(F=>Number.isFinite(F)),D=A?{draggable:!1,onPointerDown:F=>_1(F,Number(T.id),"others",_,P)}:{draggable:Zt&&!Ae,onDragStart:F=>{Zt&&(xe.current=Number(T.id),F.dataTransfer.setData("text/plain",String(I)),se.current=I)},onDragEnd:()=>{Zt&&(se.current=null,xe.current=null)},onDragOver:F=>{if(Zt){F.preventDefault();try{const ie=localStorage.getItem("prefs.dragBehavior")||"swap",le=se.current;if(ie==="rearrange"&&le!==null&&le!==I){const ye=Date.now(),ke=F.currentTarget.getBoundingClientRect(),lt=Math.min(28,Math.floor(ke.height*.2)),He=Math.min(20,Math.floor(ke.width*.2)),et=F.clientY>ke.top+lt&&F.clientYke.left+He&&F.clientXGt&&(yf(le,I),q.current=ye,se.current=I)}}catch{}}},onDrop:F=>{if(!Zt)return;F.preventDefault();const ie=Number(F.dataTransfer.getData("text/plain")),le=Number.isFinite(ie)?ie:se.current??-1,ye=I;try{(localStorage.getItem("prefs.dragBehavior")||"swap")==="rearrange"?yf(le,ye):gf(le,ye)}catch{gf(le,ye)}requestAnimationFrame(()=>{try{vf(E.current)}catch{}}),se.current=null,xe.current=null}};return h.jsx("div",{"data-note-id":T.id,style:O?{gridColumnStart:O.colStart,gridColumnEnd:`span ${O.colSpan}`,gridRowStart:O.rowStart,gridRowEnd:`span ${O.rowSpan}`}:{gridColumn:`span ${P}`},ref:F=>{F?me.current.set(T.id,F):me.current.delete(T.id)},...D,children:h.jsx(El,{note:T,onChange:xo})},T.id)})})]},C.key))})]}),A&&L1&&it.current?zn.createPortal(h.jsx("div",{ref:xt,className:"note-rearrange-overlay",style:{position:"fixed",left:`${it.current.left}px`,top:`${it.current.top}px`,width:`${it.current.width}px`,height:`${it.current.height}px`},children:h.jsx("div",{className:"note-rearrange-overlay-inner",children:h.jsx(El,{note:L1,onChange:xo})})}),document.body):null]})}function YJ({onClose:t}){const{register:e,uploadPhoto:n}=Sr(),[r,i]=b.useState(""),[s,o]=b.useState(""),[l,a]=b.useState(""),[c,u]=b.useState(""),[d,f]=b.useState(""),[p,m]=b.useState(!1),[g,y]=b.useState(null),[v,w]=b.useState(null),[x,E]=b.useState(null),[k,M]=b.useState(null),N=l.length>0&&s===l;function z({ok:W}){return W?h.jsx("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":!0,focusable:"false",style:{color:"#4caf50"},children:h.jsx("path",{d:"M20 6L9 17l-5-5",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",strokeLinejoin:"round"})}):h.jsx("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":!0,focusable:"false",style:{color:"#ff6e6e"},children:h.jsx("path",{d:"M6 6L18 18M18 6L6 18",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",strokeLinejoin:"round"})})}async function X(W){if(W.preventDefault(),y(null),!c.trim()||!r.trim()||!s){y("All fields are required");return}if(s!==l){y("Passwords do not match");return}m(!0);try{await e(r,s,c,d||void 0);try{if(x){const te=await H(x);await n(te)}}catch{}t()}catch(te){y((te==null?void 0:te.message)??String(te))}finally{m(!1)}}function L(W){var ce;const te=((ce=W.target.files)==null?void 0:ce[0])||null;E(te);try{M(ue=>{try{ue&&URL.revokeObjectURL(ue)}catch{}return te?URL.createObjectURL(te):null})}catch{M(null)}}b.useEffect(()=>()=>{try{k&&URL.revokeObjectURL(k)}catch{}},[k]);function H(W){return new Promise((te,ce)=>{const ue=new FileReader;ue.onload=()=>te(String(ue.result||"")),ue.onerror=Ae=>ce(Ae),ue.readAsDataURL(W)})}return b.useEffect(()=>{fetch("/api/config").then(W=>W.json()).then(W=>w(!!W.userRegistrationEnabled)).catch(()=>w(!1))},[]),h.jsx("div",{className:"image-dialog-backdrop",children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Register"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsxs("form",{onSubmit:X,children:[h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Name",value:c,onChange:W=>u(W.target.value),className:"image-url-input",required:!0})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Email",value:r,onChange:W=>i(W.target.value),className:"image-url-input"})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Password",type:"password",value:s,onChange:W=>o(W.target.value),className:"image-url-input"})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Confirm password",type:"password",value:l,onChange:W=>a(W.target.value),className:"image-url-input"})}),h.jsxs("div",{style:{marginBottom:12},children:[h.jsx("label",{style:{display:"block",marginBottom:6},children:"Profile photo (optional):"}),h.jsx("input",{type:"file",accept:"image/*",onChange:L}),k&&h.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10},children:[h.jsx("img",{src:k,alt:"Selected profile preview",style:{width:64,height:64,borderRadius:"50%",objectFit:"cover"}}),h.jsx("div",{style:{color:"var(--muted)",fontSize:13},children:"Preview"})]})]}),h.jsx("div",{style:{display:"grid",rowGap:6,margin:"10px 2px 12px"},"aria-live":"polite",children:h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--muted)"},children:[h.jsx(z,{ok:N})," ",h.jsx("span",{children:"Passwords match"})]})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Invite token (optional)",value:d,onChange:W=>f(W.target.value),className:"image-url-input"})}),v===!1&&h.jsx("div",{style:{color:"salmon",marginBottom:8},children:"Registration is currently disabled — you must provide a valid invite token."}),g&&h.jsx("div",{style:{color:"salmon",marginBottom:8},children:g}),h.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[h.jsx("button",{type:"button",className:"btn",onClick:t,children:"Cancel"}),h.jsx("button",{type:"submit",className:"btn",disabled:p||!c.trim()||!r.trim()||!s||!l||!N,children:p?"Registering...":"Register"})]})]})]})})}function qJ({onClose:t}){const{login:e}=Sr(),[n,r]=b.useState(""),[i,s]=b.useState(""),[o,l]=b.useState(!1),[a,c]=b.useState(null);async function u(d){d.preventDefault(),c(null),l(!0);try{await e(n,i),t()}catch(f){c((f==null?void 0:f.message)??String(f))}finally{l(!1)}}return h.jsx("div",{className:"image-dialog-backdrop",children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Sign in"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsxs("form",{onSubmit:u,children:[h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Email",value:n,onChange:d=>r(d.target.value),className:"image-url-input"})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Password",type:"password",value:i,onChange:d=>s(d.target.value),className:"image-url-input"})}),a&&h.jsx("div",{style:{color:"salmon",marginBottom:8},children:a}),h.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[h.jsx("button",{type:"button",className:"btn",onClick:t,children:"Cancel"}),h.jsx("button",{type:"submit",className:"btn",disabled:o,children:o?"Signing in...":"Sign in"})]})]})]})})}function CN({selectedLabelIds:t,selectedCollectionId:e,collectionStack:n,selectedCollaboratorId:r,searchQuery:i,sortConfig:s,onClearAllFilters:o,onSetSelectedLabelIds:l,onSetSelectedCollaboratorId:a,onSelectCollectionById:c,onSetCollectionStack:u,onSetSearchQuery:d,onSortConfigChange:f}){const{user:p}=Sr(),[m,g]=b.useState(!1),[y,v]=b.useState(!1),[w,x]=b.useState(null);return b.useEffect(()=>{fetch("/api/config").then(E=>E.json()).then(E=>x(!!E.userRegistrationEnabled)).catch(()=>x(!1))},[]),p?h.jsx(KJ,{selectedLabelIds:t||[],selectedCollectionId:e??null,collectionStack:n||[],selectedCollaboratorId:r??null,searchQuery:i,sortConfig:s,onClearAllFilters:o,onSetSelectedLabelIds:l,onSetSelectedCollaboratorId:a,onSelectCollectionById:c,onSetCollectionStack:u,onSetSearchQuery:d,onSortConfigChange:f}):h.jsxs("div",{style:{padding:24,display:"flex",flexDirection:"column",alignItems:"center"},children:[h.jsx("h2",{children:"Welcome to FreemanNotes"}),h.jsx("p",{children:"Please sign in to view and manage your notes."}),h.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[h.jsx("button",{className:"btn",onClick:()=>v(!0),children:"Sign in"}),w&&h.jsx("button",{className:"btn",onClick:()=>g(!0),children:"Create account"})]}),m&&h.jsx(YJ,{onClose:()=>g(!1)}),y&&h.jsx(qJ,{onClose:()=>v(!1)})]})}function JJ(){return h.jsx(y_,{children:h.jsx(m_,{children:h.jsx(GJ,{})})})}function GJ(){const{user:t,token:e}=Sr(),[n,r]=B.useState([]),[i,s]=B.useState(null),[o,l]=B.useState([]),[a,c]=B.useState(!1),[u,d]=B.useState(!1),[f,p]=B.useState(!1),[m,g]=B.useState(""),[y,v]=B.useState(Ks),w=o.length?Number(o[o.length-1].id):null,x=B.useRef([]),E=B.useRef(!1),k=B.useRef(0),M=B.useRef(!1),N=B.useCallback(()=>{r([]),s(null),l([]),g(""),v(Ks)},[]),z=B.useCallback(async(H,W)=>{const te=Number(H);if(Number.isFinite(te)){if(!e){l([{id:te,name:String(W||te)}]);return}try{const ce=await fetch(`/api/collections/${encodeURIComponent(String(te))}/breadcrumb`,{headers:{Authorization:`Bearer ${e}`}});if(!ce.ok)throw new Error(await ce.text());const ue=await ce.json(),me=(Array.isArray(ue==null?void 0:ue.breadcrumb)?ue.breadcrumb:[]).map(q=>({id:Number(q.id),name:String(q.name||"")})).filter(q=>Number.isFinite(q.id)&&q.name.length);me.length?l(me):l([{id:te,name:String(W||te)}])}catch{l([{id:te,name:String(W||te)}])}}},[e]),X=H=>{r(W=>W.includes(H)?W.filter(te=>te!==H):[...W,H])},L=()=>r([]);return B.useEffect(()=>{var W,te;function H(){try{const ce=window.matchMedia,ue=!!(ce&&(ce("(pointer: coarse)").matches||ce("(any-pointer: coarse)").matches)),Ae=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,me=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight,q=Math.min(Ae,me);p(ue&&q<=600)}catch{p(!1)}}H(),window.addEventListener("resize",H);try{(W=window.visualViewport)==null||W.addEventListener("resize",H)}catch{}try{(te=window.visualViewport)==null||te.addEventListener("scroll",H)}catch{}return()=>{var ce,ue;window.removeEventListener("resize",H);try{(ce=window.visualViewport)==null||ce.removeEventListener("resize",H)}catch{}try{(ue=window.visualViewport)==null||ue.removeEventListener("scroll",H)}catch{}}},[]),B.useEffect(()=>{if(f&&!E.current){E.current=!0;try{history.replaceState({...history.state||{},__freemannotes_base:!0},document.title),history.pushState({...history.state||{},__freemannotes_sentinel:!0},document.title)}catch{}}},[f]),B.useEffect(()=>{if(!f)return;const H=x.current,W=ue=>{var Ae;try{const me=ue==null?void 0:ue.detail,q=String((me==null?void 0:me.id)||""),se=me==null?void 0:me.onBack;if(!q||typeof se!="function")return;for(let xe=H.length-1;xe>=0;xe--)((Ae=H[xe])==null?void 0:Ae.id)===q&&H.splice(xe,1);H.push({id:q,onBack:se});try{history.pushState({...history.state||{},__freemannotes_overlay:!0,__freemannotes_overlay_id:q},document.title)}catch{}}catch{}},te=ue=>{var Ae;try{const me=ue==null?void 0:ue.detail,q=String((me==null?void 0:me.id)||"");if(!q)return;for(let se=H.length-1;se>=0;se--)((Ae=H[se])==null?void 0:Ae.id)===q&&H.splice(se,1)}catch{}},ce=ue=>{var Ae;try{if(!f)return;if(H.length>0){const se=H.pop();try{(Ae=se==null?void 0:se.onBack)==null||Ae.call(se)}catch{}return}const me=ue==null?void 0:ue.state;if(!me||!!me.__freemannotes_base){if(M.current){M.current=!1;return}const se=Date.now(),xe=k.current||0;if(k.current=se,se-xe<=800&&window.confirm("Exit FreemanNotes?")){M.current=!0,window.setTimeout(()=>{var Je;try{history.back()}catch{}try{(Je=window.close)==null||Je.call(window)}catch{}},0);return}window.setTimeout(()=>{try{history.go(1)}catch{}},0)}}catch{}};return window.addEventListener("freemannotes:back/register",W),window.addEventListener("freemannotes:back/unregister",te),window.addEventListener("popstate",ce),()=>{window.removeEventListener("freemannotes:back/register",W),window.removeEventListener("freemannotes:back/unregister",te),window.removeEventListener("popstate",ce)}},[f]),B.useEffect(()=>{if(!u)return;function H(W){W.key==="Escape"&&d(!1)}return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[u]),B.useEffect(()=>{f||d(!1)},[f]),B.useEffect(()=>{if(!f)return;let H=!1,W=!1,te=!1,ce=0,ue=0,Ae=0,me=0,q=null,se=null;const xe=140,Me=24,Q=28,Je=80,_t=360,J=8,at=1.2;function $t(ze){const Pe=ze;if(!Pe)return!1;try{return Pe.closest(".note-card")?!!Pe.closest('input, textarea, select, button, a, [contenteditable="true"]'):!!Pe.closest('input, textarea, select, button, a, [contenteditable="true"], .take-note-expanded, .image-dialog, .prefs-dialog')}catch{return!1}}function ct(ze,Pe,it,ot,xt){if($t(it))return!1;let oe=!1;try{const K=it;oe=!!(K&&K.closest&&K.closest(".note-card"))}catch{}const Ye=!u&&ze<=xe&&(!oe||ze<=Me),Ge=u&&ze<=_t;return!Ye&&!Ge?!1:(ce=ze,ue=Pe,Ae=ze,me=Pe,H=!0,q=ot,se=xt,W=Ye,te=Ge,!0)}function nt(ze,Pe,it){Ae=ze,me=Pe;const ot=Ae-ce,xt=me-ue;if(Math.abs(xt)>Je&&Math.abs(xt)>Math.abs(ot)*at){H=!1,q=null,se=null,W=!1,te=!1;return}if(it&&Math.abs(ot)>J&&Math.abs(ot)>Math.abs(xt)*at&&it(),W&&ot>=Q&&Math.abs(xt)<=Je){d(!0),H=!1,q=null,se=null,W=!1,te=!1;return}if(te&&ot<=-34&&Math.abs(xt)<=Je){d(!1),H=!1,q=null,se=null,W=!1,te=!1;return}}function At(ze){var Pe,it;try{if(ze.pointerType!=="touch"||q!=null||$t(ze.target)||!ct(ze.clientX,ze.clientY,ze.target,ze.pointerId,null))return;try{(it=(Pe=ze.target)==null?void 0:Pe.setPointerCapture)==null||it.call(Pe,ze.pointerId)}catch{}}catch{}}function Vt(ze){try{if(!H||q==null||ze.pointerId!==q)return;nt(ze.clientX,ze.clientY,()=>ze.preventDefault())}catch{}}function wt(ze){try{if(q==null||ze.pointerId!==q)return}catch{}H=!1,q=null,se=null,W=!1,te=!1}function ae(ze){try{if(se!=null||q!=null||!ze.touches||ze.touches.length!==1)return;const Pe=ze.touches[0];ct(Pe.clientX,Pe.clientY,ze.target,null,Pe.identifier)}catch{}}function Ee(ze){try{if(!H||se==null)return;const Pe=Array.from(ze.touches||[]).find(it=>it.identifier===se);if(!Pe)return;nt(Pe.clientX,Pe.clientY,()=>ze.preventDefault())}catch{}}function Ke(ze){try{if(se==null||Array.from(ze.touches||[]).some(it=>it.identifier===se))return}catch{}H=!1,q=null,se=null,W=!1,te=!1}return document.addEventListener("pointerdown",At,{capture:!0}),document.addEventListener("pointermove",Vt,{capture:!0,passive:!1}),document.addEventListener("pointerup",wt,{capture:!0}),document.addEventListener("pointercancel",wt,{capture:!0}),document.addEventListener("touchstart",ae,{capture:!0,passive:!0}),document.addEventListener("touchmove",Ee,{capture:!0,passive:!1}),document.addEventListener("touchend",Ke,{capture:!0}),document.addEventListener("touchcancel",Ke,{capture:!0}),()=>{document.removeEventListener("pointerdown",At,{capture:!0}),document.removeEventListener("pointermove",Vt,{capture:!0}),document.removeEventListener("pointerup",wt,{capture:!0}),document.removeEventListener("pointercancel",wt,{capture:!0}),document.removeEventListener("touchstart",ae,{capture:!0}),document.removeEventListener("touchmove",Ee,{capture:!0}),document.removeEventListener("touchend",Ke,{capture:!0}),document.removeEventListener("touchcancel",Ke,{capture:!0})}},[f,u]),t?h.jsxs("div",{className:"app-root"+(f?" phone":"")+(u?" drawer-open":""),children:[h.jsx(E_,{onToggleSidebar:()=>{f?d(H=>!H):c(H=>!H)},searchQuery:m,onSearchChange:g}),h.jsxs("div",{className:"app-body",children:[!f&&h.jsx(nS,{selectedLabelIds:n,onToggleLabel:X,onClearLabels:L,collapsed:a,collectionStack:o,onCollectionStackChange:l,sortConfig:y,onSortConfigChange:v}),h.jsx("main",{className:"main-area",children:h.jsx(CN,{selectedLabelIds:n,selectedCollectionId:w,collectionStack:o,selectedCollaboratorId:i,searchQuery:m,sortConfig:y,onClearAllFilters:N,onSetSelectedLabelIds:r,onSetSelectedCollaboratorId:s,onSelectCollectionById:z,onSetCollectionStack:l,onSetSearchQuery:g,onSortConfigChange:v})})]}),f&&h.jsxs(h.Fragment,{children:[u&&h.jsx("div",{className:"mobile-sidebar-backdrop",role:"button","aria-label":"Close menu",tabIndex:0,onClick:()=>d(!1),onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&d(!1)}}),h.jsx("div",{className:"mobile-sidebar-drawer"+(u?" open":""),"aria-hidden":!u,children:h.jsx(nS,{selectedLabelIds:n,onToggleLabel:X,onClearLabels:L,collapsed:!1,collectionStack:o,onCollectionStackChange:l,sortConfig:y,onSortConfigChange:v,onRequestClose:()=>d(!1)})})]})]}):h.jsx("div",{className:"app-root",style:{minHeight:"100vh"},children:h.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center"},children:h.jsx(CN,{})})})}function XJ(){try{const t=document.documentElement,e={"prefs.checklistSpacing":"--checklist-gap","prefs.checkboxSize":"--checklist-checkbox-size","prefs.checklistTextSize":"--checklist-text-size","prefs.noteWidth":"--note-card-width","prefs.imageThumbSize":"--image-thumb-size","prefs.fontFamily":"--app-font-family","prefs.noteLineSpacing":"--note-line-height"},n=new Set(["prefs.checklistSpacing","prefs.checkboxSize","prefs.checklistTextSize","prefs.noteWidth","prefs.imageThumbSize"]);Object.entries(e).forEach(([r,i])=>{const s=localStorage.getItem(r);s===null||s===""||(n.has(r)?/[^0-9.-]/.test(s)?t.style.setProperty(i,s):t.style.setProperty(i,`${s}px`):t.style.setProperty(i,s))});try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}}catch(t){console.warn("Failed to apply saved prefs",t)}}XJ();try{"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(t=>{t.forEach(e=>{try{e.unregister()}catch{}})}).catch(()=>{})}catch{}const QJ=zA(document.getElementById("root"));QJ.render(h.jsx(JJ,{})); +${n.toString()}`)};class XK{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Id(e),h:n}),this}else(e){return this.if(mm,e)}done(){return(e,n)=>{for(let r=0;rnew XK(t),bO=QK(mm).if(yO,(t,e)=>av(e,JE,um)).if(vO,(t,e)=>EK(e)).if(qK,(t,e)=>iN(e)).if(YK,(t,e)=>BigInt(av(e,JE,um))).if(pm,(t,e)=>xa(e,cv(e,t.shape))).if(jK,(t,e)=>{const n={};for(const r in t.shape){let i=t.shape[r];if(RK.check(i)){if(iN(e))continue;i=i.shape}n[r]=bO(i,e)}return n}).if(zK,(t,e)=>{const n=[],r=sO(e,0,42);for(let i=0;icv(e,t.shape)).if(JK,(t,e)=>null).if(HK,(t,e)=>{const n=xa(e,t.res);return()=>n}).if(KK,(t,e)=>xa(e,cv(e,[Za,Nc,Ig,wO,i1,Mg,hO(Za),uO(zc("a","b","c"),Za)]))).if(LK,(t,e)=>{const n={},r=av(e,0,3);for(let i=0;ibO(Id(e),t),cf=typeof document<"u"?document:{};fr(t=>t.nodeType===rY);typeof DOMParser<"u"&&new DOMParser;fr(t=>t.nodeType===eY);fr(t=>t.nodeType===tY);const ZK=t=>f9(t,(e,n)=>`${n}:${e};`).join(""),eY=cf.ELEMENT_NODE,tY=cf.TEXT_NODE,nY=cf.DOCUMENT_NODE,rY=cf.DOCUMENT_FRAGMENT_NODE;fr(t=>t.nodeType===nY);const iY=t=>class{constructor(n){this._=n}destroy(){t(this._)}},sY=iY(clearTimeout),xO=(t,e)=>new sY(setTimeout(e,t)),wo=Symbol,kO=wo(),SO=wo(),oY=wo(),lY=wo(),aY=wo(),CO=wo(),cY=wo(),s1=wo(),uY=wo(),dY=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],n=[];let r=0;for(;r0&&n.push(e.join(""));r{var o;t.length===1&&((o=t[0])==null?void 0:o.constructor)===Function&&(t=t[0]());const e=[],n=[],r=si();let i=[],s=0;for(;s0||c.length>0?(e.push("%c"+l),n.push(c)):e.push(l)}else break}}for(s>0&&(i=n,i.unshift(e.join("")));s{console.log(...EO(t)),TO.forEach(e=>e.print(t))},NO=(...t)=>{console.warn(...EO(t)),t.unshift(s1),TO.forEach(e=>e.print(t))},TO=uo(),AO=t=>({[Symbol.iterator](){return this},next:t}),mY=(t,e)=>AO(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),uv=(t,e)=>AO(()=>{const{done:n,value:r}=t.next();return{done:n,value:n?void 0:e(r)}});class o1{constructor(e,n){this.clock=e,this.len=n}}class Fc{constructor(){this.clients=new Map}}const hl=(t,e,n)=>e.clients.forEach((r,i)=>{const s=t.doc.store.clients.get(i);if(s!=null){const o=s[s.length-1],l=o.id.clock+o.length;for(let a=0,c=r[a];a{let n=0,r=t.length-1;for(;n<=r;){const i=zi((n+r)/2),s=t[i],o=s.clock;if(o<=e){if(e{const n=t.clients.get(e.client);return n!==void 0&&gY(n,e.clock)!==null},l1=t=>{t.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=ho(i.len,s.clock+s.len-i.clock):(r{const e=new Fc;for(let n=0;n{if(!e.clients.has(i)){const s=r.slice();for(let o=n+1;o{as(t.clients,e,()=>[]).push(new o1(n,r))},MO=()=>new Fc,IO=t=>{const e=MO();return t.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},Bc=(t,e)=>{vt(t.restEncoder,e.clients.size),fo(e.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{t.resetDsCurVal(),vt(t.restEncoder,n);const i=r.length;vt(t.restEncoder,i);for(let s=0;s{const e=new Fc,n=Lt(t.restDecoder);for(let r=0;r0){const o=as(e.clients,i,()=>[]);for(let l=0;l{const r=new Fc,i=Lt(t.restDecoder);for(let s=0;s0){const s=new sa;return vt(s.restEncoder,0),Bc(s,r),s.toUint8Array()}return null},RO=JD;class Fi extends HD{constructor({guid:e=X9(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=RO(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new $O,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=nN(c=>{this.on("load",()=>{this.isLoaded=!0,c(this)})});const a=()=>nN(c=>{const u=d=>{(d===void 0||d===!0)&&(this.off("sync",u),c())};this.on("sync",u)});this.on("sync",c=>{c===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=c===void 0||c===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=a()}load(){const e=this._item;e!==null&&!this.shouldLoad&&yn(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(fo(this.subdocs).map(e=>e.guid))}transact(e,n=null){return yn(this,e,n)}get(e,n=dr){const r=as(this.share,e,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==dr&&i!==n)if(i===dr){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,nc)}getText(e=""){return this.get(e,pl)}getMap(e=""){return this.get(e,xs)}getXmlElement(e=""){return this.get(e,Mr)}getXmlFragment(e=""){return this.get(e,oa)}toJSON(){const e={};return this.share.forEach((n,r)=>{e[r]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,fo(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Fi({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,yn(e.parent.doc,r=>{const i=n.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class DO{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Lt(this.restDecoder)}readDsLen(){return Lt(this.restDecoder)}}class OO extends DO{readLeftID(){return Ht(Lt(this.restDecoder),Lt(this.restDecoder))}readRightID(){return Ht(Lt(this.restDecoder),Lt(this.restDecoder))}readClient(){return Lt(this.restDecoder)}readInfo(){return Ec(this.restDecoder)}readString(){return nl(this.restDecoder)}readParentInfo(){return Lt(this.restDecoder)===1}readTypeRef(){return Lt(this.restDecoder)}readLen(){return Lt(this.restDecoder)}readAny(){return Ad(this.restDecoder)}readBuf(){return xK(Tr(this.restDecoder))}readJSON(){return JSON.parse(nl(this.restDecoder))}readKey(){return nl(this.restDecoder)}}class yY{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Lt(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Lt(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Tc extends yY{constructor(e){super(e),this.keys=[],Lt(e),this.keyClockDecoder=new lv(Tr(e)),this.clientDecoder=new Oh(Tr(e)),this.leftClockDecoder=new lv(Tr(e)),this.rightClockDecoder=new lv(Tr(e)),this.infoDecoder=new tN(Tr(e),Ec),this.stringDecoder=new K9(Tr(e)),this.parentInfoDecoder=new tN(Tr(e),Ec),this.typeRefDecoder=new Oh(Tr(e)),this.lenDecoder=new Oh(Tr(e))}readLeftID(){return new ec(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ec(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ad(this.restDecoder)}readBuf(){return Tr(this.restDecoder)}readJSON(){return Ad(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=ho(r,e[0].id.clock);const i=ss(e,r);vt(t.restEncoder,e.length-i),t.writeClient(n),vt(t.restEncoder,r);const s=e[i];s.write(t,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{Fn(e,s)>i&&r.set(s,i)}),df(e).forEach((i,s)=>{n.has(s)||r.set(s,0)}),vt(t.restEncoder,r.size),fo(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{vY(t,e.clients.get(i),i,s)})},wY=(t,e)=>{const n=si(),r=Lt(t.restDecoder);for(let i=0;i{const r=[];let i=fo(n.keys()).sort((p,m)=>p-m);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let p=n.get(i[i.length-1]);for(;p.refs.length===p.i;)if(i.pop(),i.length>0)p=n.get(i[i.length-1]);else return null;return p};let o=s();if(o===null)return null;const l=new $O,a=new Map,c=(p,m)=>{const g=a.get(p);(g==null||g>m)&&a.set(p,m)};let u=o.refs[o.i++];const d=new Map,f=()=>{for(const p of r){const m=p.id.client,g=n.get(m);g?(g.i--,l.clients.set(m,g.refs.slice(g.i)),n.delete(m),g.i=0,g.refs=[]):l.clients.set(m,[p]),i=i.filter(y=>y!==m)}r.length=0};for(;;){if(u.constructor!==Ai){const m=as(d,u.id.client,()=>Fn(e,u.id.client))-u.id.clock;if(m<0)r.push(u),c(u.id.client,u.id.clock-1),f();else{const g=u.getMissing(t,e);if(g!==null){r.push(u);const y=n.get(g)||{refs:[],i:0};if(y.refs.length===y.i)c(g,Fn(e,g)),f();else{u=y.refs[y.i++];continue}}else(m===0||m0)u=r.pop();else if(o!==null&&o.i0){const p=new sa;return c1(p,l,new Map),vt(p.restEncoder,0),{missing:a,update:p.toUint8Array()}}return null},xY=(t,e)=>c1(t,e.doc.store,e.beforeState),kY=(t,e,n,r=new Tc(t))=>yn(e,i=>{i.local=!1;let s=!1;const o=i.doc,l=o.store,a=wY(r,o),c=bY(i,l,a),u=l.pendingStructs;if(u){for(const[f,p]of u.missing)if(pp)&&u.missing.set(f,p)}u.update=vm([u.update,c.update])}}else l.pendingStructs=c;const d=oN(r,i,l);if(l.pendingDs){const f=new Tc(xl(l.pendingDs));Lt(f.restDecoder);const p=oN(f,i,l);d&&p?l.pendingDs=vm([d,p]):l.pendingDs=d||p}else l.pendingDs=d;if(s){const f=l.pendingStructs.update;l.pendingStructs=null,gm(i.doc,f)}},n,!1),gm=(t,e,n,r=Tc)=>{const i=xl(e);kY(i,t,n,new r(i))},SY=(t,e,n)=>gm(t,e,n,OO),CY=(t,e,n=new Map)=>{c1(t,e.store,n),Bc(t,IO(e.store))},EY=(t,e=new Uint8Array([0]),n=new sa)=>{const r=LO(e);CY(n,t,r);const i=[n.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(WY(t.store.pendingStructs.update,e)),i.length>1){if(n.constructor===uf)return HY(i.map((s,o)=>o===0?s:YY(s)));if(n.constructor===sa)return vm(i)}return i[0]},NY=(t,e)=>EY(t,e,new uf),TY=t=>{const e=new Map,n=Lt(t.restDecoder);for(let r=0;rTY(new DO(xl(t))),_O=(t,e)=>(vt(t.restEncoder,e.size),fo(e.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{vt(t.restEncoder,n),vt(t.restEncoder,r)}),t),AY=(t,e)=>_O(t,df(e.store)),MY=(t,e=new PO)=>(t instanceof Map?_O(e,t):AY(e,t),e.toUint8Array()),IY=t=>MY(t,new jO);class RY{constructor(){this.l=[]}}const lN=()=>new RY,aN=(t,e)=>t.l.push(e),cN=(t,e)=>{const n=t.l,r=n.length;t.l=n.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},zO=(t,e,n)=>Zx(t.l,[e,n]);class ec{constructor(e,n){this.client=e,this.clock=n}}const ih=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,Ht=(t,e)=>new ec(t,e),Dd=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw Dr()},Od=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class ym{constructor(e,n,r,i=0){this.type=e,this.tname=n,this.item=r,this.assoc=i}}class DY{constructor(e,n,r=0){this.type=e,this.index=n,this.assoc=r}}const OY=(t,e,n=0)=>new DY(t,e,n),sh=(t,e,n)=>{let r=null,i=null;return t._item===null?i=Dd(t):r=Ht(t._item.id.client,t._item.id.clock),new ym(r,i,e,n)},dv=(t,e,n=0)=>{let r=t._start;if(n<0){if(e===0)return sh(t,null,n);e--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>e)return sh(t,Ht(r.id.client,r.id.clock+e),n);e-=r.length}if(r.right===null&&n<0)return sh(t,r.lastId,n);r=r.right}return sh(t,null,n)},jY=(t,e)=>{const n=tc(t,e),r=e.clock-n.id.clock;return{item:n,diff:r}},PY=(t,e,n=!0)=>{const r=e.store,i=t.item,s=t.type,o=t.tname,l=t.assoc;let a=null,c=0;if(i!==null){if(Fn(r,i.client)<=i.clock)return null;const u=n?kw(r,i):jY(r,i),d=u.item;if(!(d instanceof cn))return null;if(a=d.parent,a._item===null||!a._item.deleted){c=d.deleted||!d.countable?0:u.diff+(l>=0?0:1);let f=d.left;for(;f!==null;)!f.deleted&&f.countable&&(c+=f.length),f=f.left}}else{if(o!==null)a=e.get(o);else if(s!==null){if(Fn(r,s.client)<=s.clock)return null;const{item:u}=n?kw(r,s):{item:tc(r,s)};if(u instanceof cn&&u.content instanceof cs)a=u.content.type;else return null}else throw Dr();l>=0?c=a._length:c=0}return OY(a,c,t.assoc)};class u1{constructor(e,n){this.ds=e,this.sv=n}}const FO=(t,e)=>new u1(t,e),fv=t=>FO(IO(t.store),df(t.store)),Tl=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!$c(e.ds,t.id),ww=(t,e)=>{const n=as(t.meta,ww,uo),r=t.doc.store;n.has(e)||(e.sv.forEach((i,s)=>{i{}),n.add(e))};class $O{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const df=t=>{const e=new Map;return t.clients.forEach((n,r)=>{const i=n[n.length-1];e.set(r,i.id.clock+i.length)}),e},Fn=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},BO=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==e.id.clock)throw Dr()}n.push(e)},ss=(t,e)=>{let n=0,r=t.length-1,i=t[r],s=i.id.clock;if(s===e)return r;let o=zi(e/(s+i.length-1)*r);for(;n<=r;){if(i=t[o],s=i.id.clock,s<=e){if(e{const n=t.clients.get(e.client);return n[ss(n,e.clock)]},tc=LY,bw=(t,e,n)=>{const r=ss(e,n),i=e[r];return i.id.clock{const n=t.doc.store.clients.get(e.client);return n[bw(t,n,e.clock)]},uN=(t,e,n)=>{const r=e.clients.get(n.client),i=ss(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Ti&&r.splice(i+1,0,Sm(t,s,n.clock-s.id.clock+1)),s},_Y=(t,e,n)=>{const r=t.clients.get(e.id.client);r[ss(r,e.id.clock)]=n},UO=(t,e,n,r,i)=>{if(r===0)return;const s=n+r;let o=bw(t,e,n),l;do l=e[o++],se.deleteSet.clients.size===0&&!h9(e.afterState,(n,r)=>e.beforeState.get(r)!==n)?!1:(l1(e.deleteSet),xY(t,e),Bc(t,e.deleteSet),!0),fN=(t,e,n)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&as(t.changed,e,uo).add(n)},jh=(t,e)=>{let n=t[e],r=t[e-1],i=e;for(;i>0;n=r,r=t[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof cn&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=e-i;return s&&t.splice(e+1-s,s),s},FY=(t,e,n)=>{for(const[r,i]of t.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const l=i[o],a=l.clock+l.len;for(let c=ss(s,l.clock),u=s[c];c{t.clients.forEach((n,r)=>{const i=e.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],l=ia(i.length-1,1+ss(i,o.clock+o.len-1));for(let a=l,c=i[a];a>0&&c.id.clock>=o.clock;c=i[a])a-=1+jh(i,a)}})},HO=(t,e)=>{if(el.push(()=>{(c._item===null||!c._item.deleted)&&c._callObserver(n,a)})),l.push(()=>{n.changedParentTypes.forEach((a,c)=>{c._dEH.l.length>0&&(c._item===null||!c._item.deleted)&&(a=a.filter(u=>u.target._item===null||!u.target._item.deleted),a.forEach(u=>{u.currentTarget=c,u._path=null}),a.sort((u,d)=>u.path.length-d.path.length),l.push(()=>{zO(c._dEH,a,n)}))}),l.push(()=>r.emit("afterTransaction",[n,r])),l.push(()=>{n._needFormattingCleanup&&lq(n)})}),Zx(l,[])}finally{r.gc&&FY(s,i,r.gcFilter),$Y(s,i),n.afterState.forEach((u,d)=>{const f=n.beforeState.get(d)||0;if(f!==u){const p=i.clients.get(d),m=ho(ss(p,f),1);for(let g=p.length-1;g>=m;)g-=1+jh(p,g)}});for(let u=o.length-1;u>=0;u--){const{client:d,clock:f}=o[u].id,p=i.clients.get(d),m=ss(p,f);m+11||m>0&&jh(p,m)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(pY(s1,kO,"[yjs] ",SO,CO,"Changed the client-id because another client seems to be using it."),r.clientID=RO()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new uf;dN(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new sa;dN(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:l,subdocsLoaded:a,subdocsRemoved:c}=n;(l.size>0||c.size>0||a.size>0)&&(l.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),c.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:a,added:l,removed:c},r,n]),c.forEach(u=>u.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):HO(t,e+1)}}},yn=(t,e,n=null,r=!0)=>{const i=t._transactionCleanups;let s=!1,o=null;t._transaction===null&&(s=!0,t._transaction=new zY(t,n,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{o=e(t._transaction)}finally{if(s){const l=t._transaction===i[0];t._transaction=null,l&&HO(i,0)}}return o};class BY{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const hN=(t,e,n)=>{hl(t,n.deletions,r=>{r instanceof cn&&e.scope.some(i=>i===t.doc||Od(i,r))&&v1(r,!1)})},pN=(t,e,n)=>{let r=null;const i=t.doc,s=t.scope;yn(i,l=>{for(;e.length>0&&t.currStackItem===null;){const a=i.store,c=e.pop(),u=new Set,d=[];let f=!1;hl(l,c.insertions,p=>{if(p instanceof cn){if(p.redone!==null){let{item:m,diff:g}=kw(a,p.id);g>0&&(m=Qr(l,Ht(m.id.client,m.id.clock+g))),p=m}!p.deleted&&s.some(m=>m===l.doc||Od(m,p))&&d.push(p)}}),hl(l,c.deletions,p=>{p instanceof cn&&s.some(m=>m===l.doc||Od(m,p))&&!$c(c.insertions,p.id)&&u.add(p)}),u.forEach(p=>{f=cj(l,p,u,c.insertions,t.ignoreRemoteMapChanges,t)!==null||f});for(let p=d.length-1;p>=0;p--){const m=d[p];t.deleteFilter(m)&&(m.delete(l),f=!0)}t.currStackItem=f?c:null}l.changed.forEach((a,c)=>{a.has(null)&&c._searchMarker&&(c._searchMarker.length=0)}),r=l},t);const o=t.currStackItem;if(o!=null){const l=r.changedParentTypes;t.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:l,origin:t},t]),t.currStackItem=null}return o};class VO extends HD{constructor(e,{captureTimeout:n=500,captureTransaction:r=a=>!0,deleteFilter:i=()=>!0,trackedOrigins:s=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=Sc(e)?e[0].doc:e instanceof Fi?e:e.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(e),this.deleteFilter=i,s.add(this),this.trackedOrigins=s,this.captureTransaction=r,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=n,this.afterTransactionHandler=a=>{if(!this.captureTransaction(a)||!this.scope.some(y=>a.changedParentTypes.has(y)||y===this.doc)||!this.trackedOrigins.has(a.origin)&&(!a.origin||!this.trackedOrigins.has(a.origin.constructor)))return;const c=this.undoing,u=this.redoing,d=c?this.redoStack:this.undoStack;c?this.stopCapturing():u||this.clear(!1,!0);const f=new Fc;a.afterState.forEach((y,v)=>{const w=a.beforeState.get(v)||0,x=y-w;x>0&&Rd(f,v,w,x)});const p=dl();let m=!1;if(this.lastChange>0&&p-this.lastChange0&&!c&&!u){const y=d[d.length-1];y.deletions=vw([y.deletions,a.deleteSet]),y.insertions=vw([y.insertions,f])}else d.push(new BY(a.deleteSet,f)),m=!0;!c&&!u&&(this.lastChange=p),hl(a,a.deleteSet,y=>{y instanceof cn&&this.scope.some(v=>v===a.doc||Od(v,y))&&v1(y,!0)});const g=[{stackItem:d[d.length-1],origin:a.origin,type:c?"redo":"undo",changedParentTypes:a.changedParentTypes},this];m?this.emit("stack-item-added",g):this.emit("stack-item-updated",g)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=Sc(e)?e:[e],e.forEach(r=>{n.has(r)||(n.add(r),(r instanceof dr?r.doc!==this.doc:r!==this.doc)&&NO("[yjs#509] Not same Y.Doc"),this.scope.push(r))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,n=!0){(e&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(r=>{e&&(this.undoStack.forEach(i=>hN(r,this,i)),this.undoStack=[]),n&&(this.redoStack.forEach(i=>hN(r,this,i)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=pN(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=pN(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}function*UY(t){const e=Lt(t.restDecoder);for(let n=0;nvm(t,OO,uf),VY=(t,e)=>{if(t.constructor===Ti){const{client:n,clock:r}=t.id;return new Ti(Ht(n,r+e),t.length-e)}else if(t.constructor===Ai){const{client:n,clock:r}=t.id;return new Ai(Ht(n,r+e),t.length-e)}else{const n=t,{client:r,clock:i}=n.id;return new cn(Ht(r,i+e),null,Ht(r,i+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},vm=(t,e=Tc,n=sa)=>{if(t.length===1)return t[0];const r=t.map(u=>new e(xl(u)));let i=r.map(u=>new d1(u,!0)),s=null;const o=new n,l=new f1(o);for(;i=i.filter(f=>f.curr!==null),i.sort((f,p)=>{if(f.curr.id.client===p.curr.id.client){const m=f.curr.id.clock-p.curr.id.clock;return m===0?f.curr.constructor===p.curr.constructor?0:f.curr.constructor===Ai?1:-1:m}else return p.curr.id.client-f.curr.id.client}),i.length!==0;){const u=i[0],d=u.curr.id.client;if(s!==null){let f=u.curr,p=!1;for(;f!==null&&f.id.clock+f.length<=s.struct.id.clock+s.struct.length&&f.id.client>=s.struct.id.client;)f=u.next(),p=!0;if(f===null||f.id.client!==d||p&&f.id.clock>s.struct.id.clock+s.struct.length)continue;if(d!==s.struct.id.client)_o(l,s.struct,s.offset),s={struct:f,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Ai?s.struct.length-=m:f=VY(f,m)),s.struct.mergeWith(f)||(_o(l,s.struct,s.offset),s={struct:f,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let f=u.curr;f!==null&&f.id.client===d&&f.id.clock===s.struct.id.clock+s.struct.length&&f.constructor!==Ai;f=u.next())_o(l,s.struct,s.offset),s={struct:f,offset:0}}s!==null&&(_o(l,s.struct,s.offset),s=null),h1(l);const a=r.map(u=>a1(u)),c=vw(a);return Bc(o,c),o.toUint8Array()},WY=(t,e,n=Tc,r=sa)=>{const i=LO(e),s=new r,o=new f1(s),l=new n(xl(t)),a=new d1(l,!1);for(;a.curr;){const u=a.curr,d=u.id.client,f=i.get(d)||0;if(a.curr.constructor===Ai){a.next();continue}if(u.id.clock+u.length>f)for(_o(o,u,ho(f-u.id.clock,0)),a.next();a.curr&&a.curr.id.client===d;)_o(o,a.curr,0),a.next();else for(;a.curr&&a.curr.id.client===d&&a.curr.id.clock+a.curr.length<=f;)a.next()}h1(o);const c=a1(l);return Bc(s,c),s.toUint8Array()},WO=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Nn(t.encoder.restEncoder)}),t.encoder.restEncoder=gr(),t.written=0)},_o=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&WO(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),vt(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},h1=t=>{WO(t);const e=t.encoder.restEncoder;vt(e,t.clientStructs.length);for(let n=0;n{const i=new n(xl(t)),s=new d1(i,!1),o=new r,l=new f1(o);for(let c=s.curr;c!==null;c=s.next())_o(l,e(c),0);h1(l);const a=a1(i);return Bc(o,a),o.toUint8Array()},YY=t=>KY(t,aK,Tc,uf),mN="You must not compute changes after the event-handler fired.";class Rg{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=qY(this.currentTarget,this.target))}deletes(e){return $c(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Rs(mN);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,l;if(this.adds(s)){let a=s.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(s))if(a!==null&&this.deletes(a))o="delete",l=rv(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",l=rv(a.content.getContent())):(o="add",l=void 0)}else if(this.deletes(s))o="delete",l=rv(s.content.getContent());else return;e.set(i,{action:o,oldValue:l})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Rs(mN);const n=this.target,r=uo(),i=uo(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const a=()=>{l&&s.push(l)};for(let c=n._start;c!==null;c=c.right)c.deleted?this.deletes(c)&&!this.adds(c)&&((l===null||l.delete===void 0)&&(a(),l={delete:0}),l.delete+=c.length,i.add(c)):this.adds(c)?((l===null||l.insert===void 0)&&(a(),l={insert:[]}),l.insert=l.insert.concat(c.content.getContent()),r.add(c)):((l===null||l.retain===void 0)&&(a(),l={retain:0}),l.retain+=c.length);l!==null&&l.retain===void 0&&a()}this._changes=e}return e}}const qY=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}e=e._item.parent}return n},Ir=()=>{NO("Invalid access: Add Yjs type to a document before reading data.")},KO=80;let p1=0;class JY{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=p1++}}const GY=t=>{t.timestamp=p1++},YO=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=p1++},XY=(t,e,n)=>{if(t.length>=KO){const r=t.reduce((i,s)=>i.timestamp{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((s,o)=>Rh(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Rh(n.index-i){for(let r=t.length-1;r>=0;r--){const i=t[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){t.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=ho(e,i.index+n))}},Og=(t,e,n)=>{const r=t,i=e.changedParentTypes;for(;as(i,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;zO(r._eH,n,e)};class dr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=lN(),this._dEH=lN(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw Oi()}clone(){throw Oi()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){aN(this._eH,e)}observeDeep(e){aN(this._dEH,e)}unobserve(e){cN(this._eH,e)}unobserveDeep(e){cN(this._dEH,e)}toJSON(){}}const qO=(t,e,n)=>{t.doc??Ir(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let r=n-e;const i=[];let s=t._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let l=e;l0;l++)i.push(o[l]),r--;e=0}}s=s.right}return i},JO=t=>{t.doc??Ir();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{const n=[];let r=t._start;for(;r!==null;){if(r.countable&&Tl(r,e)){const i=r.content.getContent();for(let s=0;s{let n=0,r=t._start;for(t.doc??Ir();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return Pd(t,(r,i)=>{n.push(e(r,i,t))}),n},QY=t=>{let e=t._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),r=0,e=e.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},QO=(t,e)=>{t.doc??Ir();const n=Dg(t,e);let r=t._start;for(n!==null&&(r=n.p,e-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=n;const s=t.doc,o=s.clientID,l=s.store,a=n===null?e._start:n.right;let c=[];const u=()=>{c.length>0&&(i=new cn(Ht(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new la(c)),i.integrate(t,0),c=[])};r.forEach(d=>{if(d===null)c.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:c.push(d);break;default:switch(u(),d.constructor){case Uint8Array:case ArrayBuffer:i=new cn(Ht(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new ff(new Uint8Array(d))),i.integrate(t,0);break;case Fi:i=new cn(Ht(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new hf(d)),i.integrate(t,0);break;default:if(d instanceof dr)i=new cn(Ht(o,Fn(l,o)),i,i&&i.lastId,a,a&&a.id,e,null,new cs(d)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ZO=()=>Rs("Length exceeded!"),ej=(t,e,n,r)=>{if(n>e._length)throw ZO();if(n===0)return e._searchMarker&&jd(e._searchMarker,n,r.length),wm(t,e,null,r);const i=n,s=Dg(e,n);let o=e._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return wm(t,e,i,n)},tj=(t,e,n,r)=>{if(r===0)return;const i=n,s=r,o=Dg(e,n);let l=e._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n0&&l!==null;)l.deleted||(r0)throw ZO();e._searchMarker&&jd(e._searchMarker,i,-s+r)},bm=(t,e,n)=>{const r=e._map.get(n);r!==void 0&&r.delete(t)},m1=(t,e,n,r)=>{const i=e._map.get(n)||null,s=t.doc,o=s.clientID;let l;if(r==null)l=new la([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new la([r]);break;case Uint8Array:l=new ff(r);break;case Fi:l=new hf(r);break;default:if(r instanceof dr)l=new cs(r);else throw new Error("Unexpected content type")}new cn(Ht(o,Fn(s.store,o)),i,i&&i.lastId,null,null,e,n,l).integrate(t,0)},g1=(t,e)=>{t.doc??Ir();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},nj=t=>{const e={};return t.doc??Ir(),t._map.forEach((n,r)=>{n.deleted||(e[r]=n.content.getContent()[n.length-1])}),e},rj=(t,e)=>{t.doc??Ir();const n=t._map.get(e);return n!==void 0&&!n.deleted},eq=(t,e)=>{const n={};return t._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&Tl(s,e)&&(n[i]=s.content.getContent()[s.length-1])}),n},oh=t=>(t.doc??Ir(),mY(t._map.entries(),e=>!e[1].deleted));class tq extends Rg{}class nc extends dr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new nc;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new nc}clone(){const e=new nc;return e.insert(0,this.toArray().map(n=>n instanceof dr?n.clone():n)),e}get length(){return this.doc??Ir(),this._length}_callObserver(e,n){super._callObserver(e,n),Og(this,e,new tq(this,e))}insert(e,n){this.doc!==null?yn(this.doc,r=>{ej(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?yn(this.doc,n=>{ZY(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?yn(this.doc,r=>{tj(r,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return QO(this,e)}toArray(){return JO(this)}slice(e=0,n=this.length){return qO(this,e,n)}toJSON(){return this.map(e=>e instanceof dr?e.toJSON():e)}map(e){return XO(this,e)}forEach(e){Pd(this,e)}[Symbol.iterator](){return QY(this)}_write(e){e.writeTypeRef(Nq)}}const nq=t=>new nc;class rq extends Rg{constructor(e,n,r){super(e,n),this.keysChanged=r}}class xs extends dr{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new xs}clone(){const e=new xs;return this.forEach((n,r)=>{e.set(r,n instanceof dr?n.clone():n)}),e}_callObserver(e,n){Og(this,e,new rq(this,e,n))}toJSON(){this.doc??Ir();const e={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];e[r]=i instanceof dr?i.toJSON():i}}),e}get size(){return[...oh(this)].length}keys(){return uv(oh(this),e=>e[0])}values(){return uv(oh(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return uv(oh(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ir(),this._map.forEach((n,r)=>{n.deleted||e(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?yn(this.doc,n=>{bm(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?yn(this.doc,r=>{m1(r,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return g1(this,e)}has(e){return rj(this,e)}clear(){this.doc!==null?yn(this.doc,e=>{this.forEach(function(n,r,i){bm(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Tq)}}const iq=t=>new xs,Ho=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&oK(t,e);class xw{constructor(e,n,r,i){this.left=e,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Dr(),this.right.content.constructor){case qn:this.right.deleted||Uc(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const gN=(t,e,n)=>{for(;e.right!==null&&n>0;){switch(e.right.content.constructor){case qn:e.right.deleted||Uc(e.currentAttributes,e.right.content);break;default:e.right.deleted||(n{const i=new Map,s=r?Dg(e,n):null;if(s){const o=new xw(s.p.left,s.p,s.index,i);return gN(t,o,n-s.index)}else{const o=new xw(null,e._start,0,i);return gN(t,o,n)}},ij=(t,e,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===qn&&Ho(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=t.doc,s=i.clientID;r.forEach((o,l)=>{const a=n.left,c=n.right,u=new cn(Ht(s,Fn(i.store,s)),a,a&&a.lastId,c,c&&c.id,e,null,new qn(l,o));u.integrate(t,0),n.right=u,n.forward()})},Uc=(t,e)=>{const{key:n,value:r}=e;r===null?t.delete(n):t.set(n,r)},sj=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===qn&&Ho(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},oj=(t,e,n,r)=>{const i=t.doc,s=i.clientID,o=new Map;for(const l in r){const a=r[l],c=n.currentAttributes.get(l)??null;if(!Ho(c,a)){o.set(l,c);const{left:u,right:d}=n;n.right=new cn(Ht(s,Fn(i.store,s)),u,u&&u.lastId,d,d&&d.id,e,null,new qn(l,a)),n.right.integrate(t,0),n.forward()}}return o},hv=(t,e,n,r,i)=>{n.currentAttributes.forEach((f,p)=>{i[p]===void 0&&(i[p]=null)});const s=t.doc,o=s.clientID;sj(n,i);const l=oj(t,e,n,i),a=r.constructor===String?new ls(r):r instanceof dr?new cs(r):new ha(r);let{left:c,right:u,index:d}=n;e._searchMarker&&jd(e._searchMarker,n.index,a.getLength()),u=new cn(Ht(o,Fn(s.store,o)),c,c&&c.lastId,u,u&&u.id,e,null,a),u.integrate(t,0),n.right=u,n.index=d,n.forward(),ij(t,e,n,l)},yN=(t,e,n,r,i)=>{const s=t.doc,o=s.clientID;sj(n,i);const l=oj(t,e,n,i);e:for(;n.right!==null&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===qn));){if(!n.right.deleted)switch(n.right.content.constructor){case qn:{const{key:a,value:c}=n.right.content,u=i[a];if(u!==void 0){if(Ho(u,c))l.delete(a);else{if(r===0)break e;l.set(a,c)}n.right.delete(t)}else n.currentAttributes.set(a,c);break}default:r0){let a="";for(;r>0;r--)a+=` +`;n.right=new cn(Ht(o,Fn(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new ls(a)),n.right.integrate(t,0),n.forward()}ij(t,e,n,l)},lj=(t,e,n,r,i)=>{let s=e;const o=si();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===qn){const c=s.content;o.set(c.key,c)}s=s.right}let l=0,a=!1;for(;e!==s;){if(n===e&&(a=!0),!e.deleted){const c=e.content;switch(c.constructor){case qn:{const{key:u,value:d}=c,f=r.get(u)??null;(o.get(u)!==c||f===d)&&(e.delete(t),l++,!a&&(i.get(u)??null)===d&&f!==d&&(f===null?i.delete(u):i.set(u,f))),!a&&!e.deleted&&Uc(i,c);break}}}e=e.right}return l},sq=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===qn){const r=e.content.key;n.has(r)?e.delete(t):n.add(r)}e=e.left}},oq=t=>{let e=0;return yn(t.doc,n=>{let r=t._start,i=t._start,s=si();const o=fw(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case qn:Uc(o,i.content);break;default:e+=lj(n,r,i,s,o),s=fw(o),r=i;break}i=i.right}}),e},lq=t=>{const e=new Set,n=t.doc;for(const[r,i]of t.afterState.entries()){const s=t.beforeState.get(r)||0;i!==s&&UO(t,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===qn&&o.constructor!==Ti&&e.add(o.parent)})}yn(n,r=>{hl(t,t.deleteSet,i=>{if(i instanceof Ti||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===qn?e.add(s):sq(r,i)});for(const i of e)oq(i)})},vN=(t,e,n)=>{const r=n,i=fw(e.currentAttributes),s=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case cs:case ha:case ls:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];yn(e,r=>{const i=new Map,s=new Map;let o=this.target._start,l=null;const a={};let c="",u=0,d=0;const f=()=>{if(l!==null){let p=null;switch(l){case"delete":d>0&&(p={delete:d}),d=0;break;case"insert":(typeof c=="object"||c.length>0)&&(p={insert:c},i.size>0&&(p.attributes={},i.forEach((m,g)=>{m!==null&&(p.attributes[g]=m)}))),c="";break;case"retain":u>0&&(p={retain:u},sK(a)||(p.attributes=nK({},a))),u=0;break}p&&n.push(p),l=null}};for(;o!==null;){switch(o.content.constructor){case cs:case ha:this.adds(o)?this.deletes(o)||(f(),l="insert",c=o.content.getContent()[0],f()):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),d+=1):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=1);break;case ls:this.adds(o)?this.deletes(o)||(l!=="insert"&&(f(),l="insert"),c+=o.content.str):this.deletes(o)?(l!=="delete"&&(f(),l="delete"),d+=o.length):o.deleted||(l!=="retain"&&(f(),l="retain"),u+=o.length);break;case qn:{const{key:p,value:m}=o.content;if(this.adds(o)){if(!this.deletes(o)){const g=i.get(p)??null;Ho(g,m)?m!==null&&o.delete(r):(l==="retain"&&f(),Ho(m,s.get(p)??null)?delete a[p]:a[p]=m)}}else if(this.deletes(o)){s.set(p,m);const g=i.get(p)??null;Ho(g,m)||(l==="retain"&&f(),a[p]=g)}else if(!o.deleted){s.set(p,m);const g=a[p];g!==void 0&&(Ho(g,m)?g!==null&&o.delete(r):(l==="retain"&&f(),m===null?delete a[p]:a[p]=m))}o.deleted||(l==="insert"&&f(),Uc(i,o.content));break}}o=o.right}for(f();n.length>0;){const p=n[n.length-1];if(p.retain!==void 0&&p.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class pl extends dr{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ir(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new pl}clone(){const e=new pl;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const r=new aq(this,e,n);Og(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ir();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===ls&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?yn(this.doc,r=>{const i=new xw(null,this._start,0,new Map);for(let s=0;s0)&&hv(r,this,i,l,o.attributes||{})}else o.retain!==void 0?yN(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&vN(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,r){this.doc??Ir();const i=[],s=new Map,o=this.doc;let l="",a=this._start;function c(){if(l.length>0){const d={};let f=!1;s.forEach((m,g)=>{f=!0,d[g]=m});const p={insert:l};f&&(p.attributes=d),i.push(p),l=""}}const u=()=>{for(;a!==null;){if(Tl(a,e)||n!==void 0&&Tl(a,n))switch(a.content.constructor){case ls:{const d=s.get("ychange");e!==void 0&&!Tl(a,e)?(d===void 0||d.user!==a.id.client||d.type!=="removed")&&(c(),s.set("ychange",r?r("removed",a.id):{type:"removed"})):n!==void 0&&!Tl(a,n)?(d===void 0||d.user!==a.id.client||d.type!=="added")&&(c(),s.set("ychange",r?r("added",a.id):{type:"added"})):d!==void 0&&(c(),s.delete("ychange")),l+=a.content.str;break}case cs:case ha:{c();const d={insert:a.content.getContent()[0]};if(s.size>0){const f={};d.attributes=f,s.forEach((p,m)=>{f[m]=p})}i.push(d);break}case qn:Tl(a,e)&&(c(),Uc(s,a.content));break}a=a.right}c()};return e||n?yn(o,d=>{e&&ww(d,e),n&&ww(d,n),u()},"cleanup"):u(),i}insert(e,n,r){if(n.length<=0)return;const i=this.doc;i!==null?yn(i,s=>{const o=lh(s,this,e,!r);r||(r={},o.currentAttributes.forEach((l,a)=>{r[a]=l})),hv(s,this,o,n,r)}):this._pending.push(()=>this.insert(e,n,r))}insertEmbed(e,n,r){const i=this.doc;i!==null?yn(i,s=>{const o=lh(s,this,e,!r);hv(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(e,n,r||{}))}delete(e,n){if(n===0)return;const r=this.doc;r!==null?yn(r,i=>{vN(i,lh(i,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,r){if(n===0)return;const i=this.doc;i!==null?yn(i,s=>{const o=lh(s,this,e,!1);o.right!==null&&yN(s,this,o,n,r)}):this._pending.push(()=>this.format(e,n,r))}removeAttribute(e){this.doc!==null?yn(this.doc,n=>{bm(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?yn(this.doc,r=>{m1(r,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return g1(this,e)}getAttributes(){return nj(this)}_write(e){e.writeTypeRef(Aq)}}const cq=t=>new pl;class pv{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ir()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===Mr||n.constructor===oa)&&n._start!==null)e=n._start;else for(;e!==null;){const r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class oa extends dr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new oa}clone(){const e=new oa;return e.insert(0,this.toArray().map(n=>n instanceof dr?n.clone():n)),e}get length(){return this.doc??Ir(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new pv(this,e)}querySelector(e){e=e.toUpperCase();const r=new pv(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),fo(new pv(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Og(this,e,new fq(this,n,e))}toString(){return XO(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Pd(this,s=>{i.insertBefore(s.toDOM(e,n,r),null)}),i}insert(e,n){this.doc!==null?yn(this.doc,r=>{ej(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)yn(this.doc,r=>{const i=e&&e instanceof dr?e._item:e;wm(r,this,i,n)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Rs("Reference item not found");r.splice(i,0,...n)}}delete(e,n=1){this.doc!==null?yn(this.doc,r=>{tj(r,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return JO(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return QO(this,e)}slice(e=0,n=this.length){return qO(this,e,n)}forEach(e){Pd(this,e)}_write(e){e.writeTypeRef(Iq)}}const uq=t=>new oa;class Mr extends oa{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Mr(this.nodeName)}clone(){const e=new Mr(this.nodeName),n=this.getAttributes();return rK(n,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof dr?r.clone():r)),e}toString(){const e=this.getAttributes(),n=[],r=[];for(const l in e)r.push(l);r.sort();const i=r.length;for(let l=0;l0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?yn(this.doc,n=>{bm(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?yn(this.doc,r=>{m1(r,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return g1(this,e)}hasAttribute(e){return rj(this,e)}getAttributes(e){return e?eq(this,e):nj(this)}toDOM(e=document,n={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const l=s[o];typeof l=="string"&&i.setAttribute(o,l)}return Pd(this,o=>{i.appendChild(o.toDOM(e,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Mq),e.writeKey(this.nodeName)}}const dq=t=>new Mr(t.readKey());class fq extends Rg{constructor(e,n,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class xm extends xs{constructor(e){super(),this.hookName=e}_copy(){return new xm(this.hookName)}clone(){const e=new xm(this.hookName);return this.forEach((n,r)=>{e.set(r,n)}),e}toDOM(e=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(Rq),e.writeKey(this.hookName)}}const hq=t=>new xm(t.readKey());class oi extends pl{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new oi}clone(){const e=new oi;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const n=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,l)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Dq)}}const pq=t=>new oi;class y1{constructor(e,n){this.id=e,this.length=n}get deleted(){throw Oi()}mergeWith(e){return!1}write(e,n,r){throw Oi()}integrate(e,n){throw Oi()}}const mq=0;class Ti extends y1{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),BO(e.doc.store,this)}write(e,n){e.writeInfo(mq),e.writeLen(this.length-n)}getMissing(e,n){return null}}class ff{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ff(this.content)}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const gq=t=>new ff(t.readBuf());class Ld{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ld(this.len)}splice(e){const n=new Ld(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){Rd(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const yq=t=>new Ld(t.readLen()),aj=(t,e)=>new Fi({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class hf{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hf(aj(this.doc.guid,this.opts))}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const vq=t=>new hf(aj(t.readString(),t.readAny()));class ha{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ha(this.embed)}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const wq=t=>new ha(t.readJSON());class qn{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new qn(this.key,this.value)}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const bq=t=>new qn(t.readKey(),t.readJSON());class km{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new km(this.arr)}splice(e){const n=new km(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const r=this.arr.length;e.writeLen(r-n);for(let i=n;i{const e=t.readLen(),n=[];for(let r=0;r{const e=t.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Cq=t=>new ls(t.readString()),Eq=[nq,iq,cq,dq,uq,hq,pq],Nq=0,Tq=1,Aq=2,Mq=3,Iq=4,Rq=5,Dq=6;class cs{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new cs(this.type._copy())}splice(e){throw Oi()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const Oq=t=>new cs(Eq[t.readTypeRef()](t)),kw=(t,e)=>{let n=e,r=0,i;do r>0&&(n=Ht(n.client,n.clock+r)),i=tc(t,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof cn);return{item:i,diff:r}},v1=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},Sm=(t,e,n)=>{const{client:r,clock:i}=e.id,s=new cn(Ht(r,i+n),e,Ht(r,i+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=Ht(e.redone.client,e.redone.clock+n)),e.right=s,s.right!==null&&(s.right.left=s),t._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=n,s},wN=(t,e)=>Wx(t,n=>$c(n.deletions,e)),cj=(t,e,n,r,i,s)=>{const o=t.doc,l=o.store,a=o.clientID,c=e.redone;if(c!==null)return Qr(t,c);let u=e.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||cj(t,u,n,r,i,s)===null))return null;for(;u.redone!==null;)u=Qr(t,u.redone)}const p=u===null?e.parent:u.content.type;if(e.parentSub===null){for(d=e.left,f=e;d!==null;){let v=d;for(;v!==null&&v.parent._item!==u;)v=v.redone===null?null:Qr(t,v.redone);if(v!==null&&v.parent._item===u){d=v;break}d=d.left}for(;f!==null;){let v=f;for(;v!==null&&v.parent._item!==u;)v=v.redone===null?null:Qr(t,v.redone);if(v!==null&&v.parent._item===u){f=v;break}f=f.right}}else if(f=null,e.right&&!i){for(d=e;d!==null&&d.right!==null&&(d.right.redone||$c(r,d.right.id)||wN(s.undoStack,d.right.id)||wN(s.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Qr(t,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(e.parentSub)||null;const m=Fn(l,a),g=Ht(a,m),y=new cn(g,d,d&&d.lastId,f,f&&f.id,p,e.parentSub,e.content.copy());return e.redone=g,v1(y,!0),y.integrate(t,0),y};class cn extends y1{constructor(e,n,r,i,s,o,l,a){super(e,a.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=l,this.redone=null,this.content=a,this.info=this.content.isCountable()?qE:0}set marker(e){(this.info&sv)>0!==e&&(this.info^=sv)}get marker(){return(this.info&sv)>0}get keep(){return(this.info&YE)>0}set keep(e){this.keep!==e&&(this.info^=YE)}get countable(){return(this.info&qE)>0}get deleted(){return(this.info&iv)>0}set deleted(e){this.deleted!==e&&(this.info^=iv)}markDeleted(){this.info|=iv}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Fn(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Fn(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ec&&this.id.client!==this.parent.client&&this.parent.clock>=Fn(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=uN(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Qr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ti||this.right&&this.right.constructor===Ti)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===cn?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===cn&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ec){const r=tc(n,this.parent);r.constructor===Ti?this.parent=null:this.parent=r.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=uN(e,e.doc.store,Ht(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),ih(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Rd(e.deleteSet,this.id.client,this.id.clock,this.length),fN(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw Dr();this.content.gc(e),n?_Y(e,this,new Ti(this.id,this.length)):this.content=new Ld(this.length)}write(e,n){const r=n>0?Ht(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Sg|(r===null?0:Br)|(i===null?0:to)|(s===null?0:Nd);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const l=this.parent;if(l._item!==void 0){const a=l._item;if(a===null){const c=Dd(l);e.writeParentInfo(!0),e.writeString(c)}else e.writeParentInfo(!1),e.writeLeftID(a.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===ec?(e.writeParentInfo(!1),e.writeLeftID(l)):Dr();s!==null&&e.writeString(s)}this.content.write(e,n)}}const uj=(t,e)=>jq[e&Sg](t),jq=[()=>{Dr()},yq,xq,gq,Cq,wq,bq,Oq,Sq,vq,()=>{Dr()}],Pq=10;class Ai extends y1{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){Dr()}write(e,n){e.writeInfo(Pq),vt(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const dj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},fj="__ $YJS$ __";dj[fj]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");dj[fj]=!0;const hj=new Map;class Lq{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:bK(n.newValue||"")}),Z9(this._onChange)}postMessage(e){XD.setItem(this.room,iO(mK(e)))}close(){eK(this._onChange)}}const _q=typeof BroadcastChannel>"u"?Lq:BroadcastChannel,w1=t=>as(hj,t,()=>{const e=uo(),n=new _q(t);return n.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:n,subs:e}}),zq=(t,e)=>(w1(t).subs.add(e),e),Fq=(t,e)=>{const n=w1(t),r=n.subs.delete(e);return r&&n.subs.size===0&&(n.bc.close(),hj.delete(t)),r},Na=(t,e,n=null)=>{const r=w1(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,n))},pj=0,b1=1,mj=2,Sw=(t,e)=>{vt(t,pj);const n=IY(e);Ln(t,n)},gj=(t,e,n)=>{vt(t,b1),Ln(t,NY(e,n))},$q=(t,e,n)=>gj(e,n,Tr(t)),yj=(t,e,n,r)=>{try{SY(e,Tr(t),n)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},Bq=(t,e)=>{vt(t,mj),Ln(t,e)},Uq=yj,Hq=(t,e,n,r,i)=>{const s=Lt(t);switch(s){case pj:$q(t,e,n);break;case b1:yj(t,n,r,i);break;case mj:Uq(t,n,r,i);break;default:throw new Error("Unknown message type")}return s},Vq=0,Wq=(t,e,n)=>{switch(Lt(t)){case Vq:n(e,nl(t))}},mv=3e4;class Kq extends VD{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=dl();this.getLocalState()!==null&&mv/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,s)=>{s!==this.clientID&&mv<=n-i.lastUpdated&&this.states.has(s)&&r.push(s)}),r.length>0&&x1(this,r,"timeout")},zi(mv/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const n=this.clientID,r=this.meta.get(n),i=r===void 0?0:r.clock+1,s=this.states.get(n);e===null?this.states.delete(n):this.states.set(n,e),this.meta.set(n,{clock:i,lastUpdated:dl()});const o=[],l=[],a=[],c=[];e===null?c.push(n):s==null?e!=null&&o.push(n):(l.push(n),Qa(s,e)||a.push(n)),(o.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:o,updated:a,removed:c},"local"]),this.emit("update",[{added:o,updated:l,removed:c},"local"])}setLocalStateField(e,n){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:n})}getStates(){return this.states}}const x1=(t,e,n)=>{const r=[];for(let i=0;i0&&(t.emit("change",[{added:[],updated:[],removed:r},n]),t.emit("update",[{added:[],updated:[],removed:r},n]))},Wu=(t,e,n=t.states)=>{const r=e.length,i=gr();vt(i,r);for(let s=0;s{const r=xl(e),i=dl(),s=[],o=[],l=[],a=[],c=Lt(r);for(let u=0;u0||l.length>0||a.length>0)&&t.emit("change",[{added:s,updated:l,removed:a},n]),(s.length>0||o.length>0||a.length>0)&&t.emit("update",[{added:s,updated:o,removed:a},n])},qq=t=>iK(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),Pl=0,vj=3,rc=1,Jq=2,pf=[];pf[Pl]=(t,e,n,r,i)=>{vt(t,Pl);const s=Hq(e,t,n.doc,n);r&&s===b1&&!n.synced&&(n.synced=!0)};pf[vj]=(t,e,n,r,i)=>{vt(t,rc),Ln(t,Wu(n.awareness,Array.from(n.awareness.getStates().keys())))};pf[rc]=(t,e,n,r,i)=>{Yq(n.awareness,Tr(e),n)};pf[Jq]=(t,e,n,r,i)=>{Wq(e,n.doc,(s,o)=>Gq(n,o))};const bN=3e4,Gq=(t,e)=>console.warn(`Permission denied to access ${t.url}. +${e}`),wj=(t,e,n)=>{const r=xl(e),i=gr(),s=Lt(r),o=t.messageHandlers[s];return o?o(i,r,t,n,s):console.error("Unable to compute message"),i},bj=t=>{if(t.shouldConnect&&t.ws===null){const e=new t._WS(t.url);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=n=>{t.wsLastMessageReceived=dl();const r=wj(t,new Uint8Array(n.data),!0);Kx(r)>1&&e.send(Nn(r))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{t.emit("connection-close",[n,t]),t.ws=null,t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,x1(t.awareness,Array.from(t.awareness.getStates().keys()).filter(r=>r!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(bj,ia(g9(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t)},e.onopen=()=>{t.wsLastMessageReceived=dl(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=gr();if(vt(n,Pl),Sw(n,t.doc),e.send(Nn(n)),t.awareness.getLocalState()!==null){const r=gr();vt(r,rc),Ln(r,Wu(t.awareness,[t.doc.clientID])),e.send(Nn(r))}},t.emit("status",[{status:"connecting"}])}},gv=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Na(t.bcChannel,e,t)};class mf extends VD{constructor(e,n,r,{connect:i=!0,awareness:s=new Kq(r),params:o={},WebSocketPolyfill:l=WebSocket,resyncInterval:a=-1,maxBackoffTime:c=2500,disableBc:u=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);const d=qq(o);this.maxBackoffTime=c,this.bcChannel=e+"/"+n,this.url=e+"/"+n+(d.length===0?"":"?"+d),this.roomname=n,this.doc=r,this._WS=l,this.awareness=s,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=pf.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=i,this._resyncInterval=0,a>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const f=gr();vt(f,Pl),Sw(f,r),this.ws.send(Nn(f))}},a)),this._bcSubscriber=(f,p)=>{if(p!==this){const m=wj(this,new Uint8Array(f),!1);Kx(m)>1&&Na(this.bcChannel,Nn(m),this)}},this._updateHandler=(f,p)=>{if(p!==this){const m=gr();vt(m,Pl),Bq(m,f),gv(this,Nn(m))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:f,updated:p,removed:m},g)=>{const y=f.concat(p).concat(m),v=gr();vt(v,rc),Ln(v,Wu(s,y)),gv(this,Nn(v))},this._exitHandler=()=>{x1(this.awareness,[r.clientID],"app closed")},fl&&typeof process<"u"&&process.on("exit",this._exitHandler),s.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&bN{try{return`ce-${(t==null?void 0:t.id)||"x"}-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`ce-${Math.random()}`}})());b.useEffect(()=>{window.dispatchEvent(new Event("freemannotes:editor-modal-open"));try{const A=c.current,ne=()=>{try{e()}catch{}};window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:A,onBack:ne}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:c.current}}))}catch{}window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}},[]);const u=b.useRef((()=>{try{return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`c${Math.random()}`}})()),d=b.useRef(null),[,f]=b.useState(0),p=b.useRef(!1),m=b.useRef(!1);B.useEffect(()=>{m.current=!1;const A=window.setTimeout(()=>{m.current=!0},160);return()=>window.clearTimeout(A)},[]);const[g,y]=b.useState(()=>(t.items||[]).map((A,ne)=>{const we=typeof(A==null?void 0:A.uid)=="string"&&A.uid?String(A.uid):typeof(A==null?void 0:A.id)=="number"?`id-${Number(A.id)}`:`init-${ne}-${Math.random().toString(36).slice(2,8)}`;return{indent:0,uid:we,key:we,...A}})),[v,w]=b.useState(!1),[x,E]=b.useState(!0),[k,M]=b.useState(null),[N,z]=b.useState(null),X=b.useRef([]),[L,H]=b.useState(null),[W,te]=b.useState(null),[ue,de]=b.useState(t.title||""),[Ae,me]=b.useState(r??(t.viewerColor||t.color||"")),[q,se]=b.useState(!1),[xe,Me]=b.useState(!1),[Q,Je]=b.useState(!1),[_t,J]=b.useState(!1),[at,$t]=b.useState((t.images||[]).map(A=>({id:Number(A.id),url:String(A.url)}))),[ct,nt]=b.useState(!1);B.useEffect(()=>{try{const A=(t.images||[]).map(ne=>({id:Number(ne.id),url:String(ne.url)}));$t(ne=>{try{if(ne.length===A.length&&ne.every((we,Z)=>{var Ie,Ve;return Number(we.id)===Number((Ie=A[Z])==null?void 0:Ie.id)&&String(we.url)===String((Ve=A[Z])==null?void 0:Ve.url)}))return ne}catch{}return A})}catch{}},[t.images]);const[At,Bt]=b.useState(null),[wt,ce]=b.useState([]),Ee=b.useRef([]),[Ke,ze]=b.useState(!1),Pe=b.useRef(null);function it(){var we;let A=d.current;if(A&&A.isFocused)return A;const ne=typeof document<"u"&&((we=document.getSelection())==null?void 0:we.anchorNode)||null;if(ne){const Z=Ee.current.find(Ie=>{var Ve;try{return!!(Ie&&((Ve=Ie.view)!=null&&Ve.dom)&&Ie.view.dom.contains(ne))}catch{return!1}});Z&&(A=Z)}else{const Z=typeof document<"u"?document.activeElement:null;if(Z){const Ie=Ee.current.find(Ve=>{try{return!!(Ve&&Ve.view&&Ve.view.dom&&(Ve.view.dom===Z||Ve.view.dom.contains(Z)))}catch{return!1}});Ie&&(A=Ie)}}if(!A||!(A!=null&&A.isFocused)){const Z=Ee.current.find(Ie=>!!(Ie&&Ie.isFocused));Z&&(A=Z)}return A||null}function ot(A){var Rt;const ne=it();if(!ne)return;const we=(Rt=ne.state)==null?void 0:Rt.selection;if(!we)return;if(!we.empty){const be=ne.chain().focus();A==="bold"?be.toggleBold():A==="italic"?be.toggleItalic():be.toggleUnderline(),be.run();try{f(qe=>qe+1)}catch{}return}let Z=we.from,Ie=we.to;try{const be=we.$from;let qe=be.depth;for(;qe>0&&!be.node(qe).isBlock;)qe--;Z=be.start(qe),Ie=be.end(qe)}catch{}const Ve=ne.chain().focus().setTextSelection({from:Z,to:Ie});A==="bold"?Ve.toggleBold():A==="italic"?Ve.toggleItalic():Ve.toggleUnderline(),Ve.run();try{ne.chain().focus().setTextSelection(we.from).run()}catch{}try{const be=we.from;requestAnimationFrame(()=>{var qe,Dt;try{try{(Dt=(qe=ne.view)==null?void 0:qe.focus)==null||Dt.call(qe)}catch{}ne.chain().focus().setTextSelection(be).run()}catch{}})}catch{}try{f(be=>be+1)}catch{}}function xt(A){var st,ft;const ne=it();if(!ne)return!1;const we=(st=ne.state)==null?void 0:st.selection;if(!we)return!1;const Z=(((ft=ne.schema)==null?void 0:ft.marks)||{})[A];if(!Z)return!1;const Ie=we.$from;let Ve=Ie.depth;for(;Ve>0&&!Ie.node(Ve).isBlock;)Ve--;const Rt=Ie.start(Ve),be=Ie.end(Ve);let qe=!1,Dt=!0;try{ne.state.doc.nodesBetween(Rt,be,yt=>{yt&&yt.isText&&(qe=!0,Z.isInSet(yt.marks)||(Dt=!1))})}catch{}return qe&&Dt}const oe=B.useMemo(()=>new Fi,[t.id]),Ye=B.useRef(null),Ge=B.useRef(null),Y=B.useRef(null),ge=B.useRef(null),De=B.useRef(!1),Be=B.useRef(!1),Le=B.useCallback(()=>{if(!Be.current){Be.current=!0;try{window.dispatchEvent(new CustomEvent("freemannotes:draft/dirty",{detail:{noteId:Number(t==null?void 0:t.id)}}))}catch{}}},[t==null?void 0:t.id]),j=b.useRef(null),G=b.useRef(null),fe=b.useRef(void 0),je=b.useRef({x:0,y:0}),Ue=b.useRef(null),We=b.useRef(!1),Se=b.useRef(0),Xe=b.useRef(null),Tt=b.useRef(null),rt=b.useRef(null),Wt=b.useRef(0),Mt=b.useRef({parentId:null,makeNested:!1}),dn=b.useRef(null),[It,Ot]=b.useState(null),tn=B.useMemo(()=>{try{return typeof window<"u"&&!!window.matchMedia&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}},[]),ee=B.useMemo(()=>{const A={hoverDownPct:.7,hoverUpPct:.7,indentPx:16,ghostOverlapPct:.7,ghostOverlapUpPct:.7,ghostOverlapDownPct:.7};return tn?{...A,hoverClearMs:0,directionLockPx:0}:{...A,hoverClearMs:80,directionLockPx:6}},[tn]),re=b.useRef(0),Oe=b.useRef(0),Ze=B.useCallback(()=>`u${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,[]),pe=B.useCallback(A=>typeof A.id=="number"?A.id:A.uid||`tmp-${Math.random().toString(36).slice(2,6)}`,[]);function Ce(){const A=document.querySelector(".image-dialog .dialog-body");return A||document.querySelector(".image-dialog")}function Fe(){We.current=!1,Ue.current!=null&&(cancelAnimationFrame(Ue.current),Ue.current=null)}function ut(){if(Ue.current!=null)return;We.current=!0;const A=()=>{if(!We.current){Ue.current=null;return}const ne=Ce();if(!ne){Ue.current=requestAnimationFrame(A);return}const we=ne.getBoundingClientRect(),Z=Se.current,Ie=Math.max(56,Math.min(96,we.height*.18)),Ve=14;let Rt=0;if(Zwe.bottom-Ie){const be=Math.max(0,Math.min(1,(Z-(we.bottom-Ie))/Ie));Rt=Math.max(1,Math.round(Math.pow(be,1.65)*Ve))}Rt!==0&&(ne.scrollTop=ne.scrollTop+Rt),Ue.current=requestAnimationFrame(A)};Ue.current=requestAnimationFrame(A)}b.useEffect(()=>{const A=`note-${t.id}`,we=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/collab`,Z=new mf(we,A,oe);Ye.current=Z;const Ie=oe.getArray("checklist");Ge.current=Ie;const Ve=oe.getMap("meta");Y.current=Ve;const Rt=async()=>{try{const ft=await fetch(`/api/notes/${t.id}/images`,{headers:{Authorization:`Bearer ${l}`}});if(!ft.ok)return;const yt=await ft.json(),bt=(yt&&yt.images||[]).map(mt=>({id:Number(mt.id),url:String(mt.url)}));$t(bt),i&&i(bt)}catch{}},be=()=>{try{const ft=Ve.get("imagesTick");if(!ft||!ft.t||ft.by&&String(ft.by)===String(u.current))return;Rt()}catch{}};try{Ve.observe(be)}catch{}const qe={current:!1},Dt=ft=>{if(ft){De.current=!0;try{const yt=Ge.current;if(yt&&yt.length===0&&!qe.current){const bt=(t.items||[]).map(mt=>{const Qt=new xs;typeof mt.id=="number"&&Qt.set("id",mt.id);const dt=typeof(mt==null?void 0:mt.uid)=="string"&&mt.uid?String(mt.uid):typeof(mt==null?void 0:mt.id)=="number"?`id-${Number(mt.id)}`:`u${Math.random().toString(36).slice(2,8)}`;return Qt.set("uid",dt),Qt.set("content",String(mt.content||"")),Qt.set("checked",!!mt.checked),Qt.set("indent",Number(mt.indent||0)),Qt});bt.length&&yt.insert(0,bt),qe.current=!0}}catch{}}};Z.on("sync",Dt);const st=(ft,yt)=>{try{yt&&yt.local&&Le()}catch{}try{const bt=Ie.toArray().map((dt,on)=>({id:typeof dt.get("id")=="number"?Number(dt.get("id")):void 0,uid:dt.get("uid")?String(dt.get("uid")):void 0,content:String(dt.get("content")||""),checked:!!dt.get("checked"),indent:Number(dt.get("indent")||0),key:dt.get("uid")?String(dt.get("uid")):typeof dt.get("id")=="number"?Number(dt.get("id")):`i${on}`})),mt=!!(d.current&&d.current.isFocused);((()=>{try{if(bt.length!==g.length)return!0;for(let dt=0;dt{var dt;try{const on=bt.map((Ct,Pt)=>{const ln={content:Ct.content,checked:!!Ct.checked,ord:Pt,indent:Ct.indent||0};return typeof Ct.id=="number"&&(ln.id=Ct.id),ln}),Yt=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({items:on})});if(Yt.ok){const Ct=await Yt.json(),Pt=Array.isArray(Ct.items)?Ct.items:[],ln=Ge.current;if(ln&&Pt.length===ln.length)for(let wi=0;wi{try{Ie.unobserveDeep(st)}catch{}try{Z.off("sync",Dt)}catch{}try{Ve.unobserve(be)}catch{}try{Z.destroy()}catch{}}},[t.id,l,oe]);const zt=B.useCallback(()=>{try{const A=Y.current;if(!A)return;A.set("imagesTick",{t:Date.now(),by:u.current})}catch{}},[]);b.useEffect(()=>{try{$t((t.images||[]).map(A=>({id:Number(A.id),url:String(A.url)})))}catch{}},[t.images]);function kt(A,ne){var Ve;const we=ne,Z=((Ve=A[ne])==null?void 0:Ve.indent)||0;let Ie=ne+1;for(;IeZ;)Ie++;return[we,Ie]}b.useEffect(()=>{X.current=X.current.slice(0,g.length)},[g.length]),b.useEffect(()=>{requestAnimationFrame(()=>{X.current.forEach(A=>{try{A.style.height="auto",A.style.height=Math.max(22,A.scrollHeight)+"px"}catch{}})})},[g,It]);function Jt(A,ne){if(rt.current!=="vertical"||k===null)return"";const[we,Z]=kt(ne,k);return N===null||A>=we&&AZ-1&&A<=N?"shift-up":"":k>N&&A>=N&&A=0&&AZ.map((Ie,Ve)=>Ve===A?{...Ie,content:ne}:Ie));requestAnimationFrame(()=>{const Z=X.current[A];if(Z)try{Z.style.height="auto",Z.style.height=Math.max(22,Z.scrollHeight)+"px"}catch{}})}function rn(A){const ne=Ge.current;if(ne){const we=typeof A=="number"?Math.max(0,Math.min(A,ne.length)):ne.length,Z=new xs;Z.set("content",""),Z.set("checked",!1),Z.set("indent",0),Z.set("uid",Ze()),ne.insert(we,[Z]),H(we)}else y(we=>{const Z=typeof A=="number"?Math.max(0,Math.min(A,we.length)):we.length,Ie=Ze(),Ve=[...we];return Ve.splice(Z,0,{uid:Ie,content:"",checked:!1,indent:0}),Ve}),H(typeof A=="number"?A:g.length+1)}function Pr(A){const ne=Ge.current;if(ne){const we=ne.get(A);if(!we)return;const Z=!we.get("checked");if(typeof we.get("id")=="number"&&we.set("id",we.get("id")),we.set("checked",Z),Number(we.get("indent")||0)===0)for(let Ve=A+1;Ve0)Rt.set("checked",Z);else break}}else y(we=>we.map((Z,Ie)=>{if(Ie===A){const Ve=!Z.checked,Rt=Number(Z.indent||0),be={...Z,checked:Ve};if(Rt===0){const qe=[...we];qe[Ie]=be;for(let Dt=Ie+1;Dt0;Dt++)qe[Dt]={...qe[Dt],checked:Ve};return qe[Ie]}return be}return Z}))}function I(A,ne,we){const Z=Ge.current;if(!Z)return;const Ie=Math.max(0,Math.min(A,Z.length)),Rt=Math.max(Ie,Math.min(ne,Z.length))-Ie;if(Rt<=0)return;let be=Math.max(0,Math.min(we,Z.length));be>Ie&&(be=be-Rt),be<0&&(be=0),be>Z.length&&(be=Z.length);const qe=[];for(let st=0;st{const ft=new xs;return typeof st.id=="number"&&ft.set("id",st.id),st.uid&&ft.set("uid",st.uid),ft.set("content",st.content),ft.set("checked",st.checked),ft.set("indent",st.indent),ft});Z.insert(be,Dt)}function U(){Fe(),G.current&&(G.current.remove(),G.current=null),fe.current&&(document.removeEventListener("dragover",fe.current),fe.current=void 0),document.querySelectorAll(".checklist-item.drag-source").forEach(A=>A.classList.remove("drag-source")),M(null),z(null),Ot(null),j.current&&(cancelAnimationFrame(j.current),j.current=null),Xe.current&&(clearTimeout(Xe.current),Xe.current=null),Tt.current=null,rt.current=null,Mt.current={parentId:null,makeNested:!1};try{const A=document.querySelector(".image-dialog");A&&A.style.removeProperty("--checklist-item-shift")}catch{}}async function K(){w(!0);try{if((t.title||"")!==ue){const Ie=await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({title:ue})});if(!Ie.ok)throw new Error(await Ie.text())}const A=Ge.current,we=(A?A.toArray().map(Ie=>({id:typeof Ie.get("id")=="number"?Number(Ie.get("id")):void 0,content:String(Ie.get("content")||""),checked:!!Ie.get("checked"),indent:Number(Ie.get("indent")||0)})):g).map((Ie,Ve)=>{const Rt={content:Ie.content,checked:!!Ie.checked,ord:Ve,indent:Ie.indent||0};return typeof Ie.id=="number"&&(Rt.id=Ie.id),Rt}),Z=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({items:we})});if(!Z.ok)throw new Error(await Z.text());n&&n({items:we,title:ue}),e()}catch(A){console.error("Failed to save checklist",A),window.alert("Failed to save checklist")}finally{w(!1)}}function le(A){if(!A)return;const ne=A.replace("#",""),we=ne.length===3?ne.split("").map(bt=>bt+bt).join(""):ne;if(we.length!==6)return;const Z=parseInt(we.slice(0,2),16)/255,Ie=parseInt(we.slice(2,4),16)/255,Ve=parseInt(we.slice(4,6),16)/255,Rt=bt=>bt<=.03928?bt/12.92:Math.pow((bt+.055)/1.055,2.4),be=Rt(Z),qe=Rt(Ie),Dt=Rt(Ve),st=.2126*be+.7152*qe+.0722*Dt,ft=(1+.05)/(st+.05),yt=(st+.05)/(0+.05);return ft>=yt?"#ffffff":"#000000"}const $={},S=Ae?le(Ae)||"var(--muted)":void 0;Ae&&($["--checkbox-bg"]=Ae),S&&($["--checkbox-border"]=S),S&&($["--checkbox-stroke"]=S),Ae&&($["--checkbox-checked-bg"]=Ae),S&&($["--checkbox-checked-mark"]=S),Ae&&($.background=Ae,S&&($.color=S),$["--editor-surface"]=Ae);async function V(A){const ne=A||"";try{const we=await fetch(`/api/notes/${t.id}/prefs`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({color:ne})});if(!we.ok)throw new Error(await we.text())}catch(we){console.error("Failed to save color preference",we),window.alert("Failed to save color preference")}me(ne);try{s==null||s(ne)}catch{}}function he(A){if(J(!1),!A)return;const ne=-Date.now();$t(we=>{const Ie=we.some(Ve=>String(Ve.url)===String(A))?we:[...we,{id:ne,url:String(A)}];return i&&i(Ie),Ie});try{nt(!0)}catch{}(async()=>{try{const we=await fetch(`/api/notes/${t.id}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({url:A})});if(!we.ok)throw new Error(await we.text());const Ie=(await we.json()).image||null;Ie&&Ie.id&&Ie.url&&($t(Ve=>{const Rt=Number(Ie.id),be=String(Ie.url),qe=Ve.map(ft=>Number(ft.id)===ne||String(ft.url)===String(A)?{id:Rt,url:be}:ft),st=qe.some(ft=>Number(ft.id)===Rt)?qe:[...qe,{id:Rt,url:be}];return i&&i(st),st}),zt())}catch(we){console.error("Failed to attach image",we),window.alert("Failed to attach image")}})()}function tt(A){ce(ne=>ne.find(we=>we.id===A.id)?ne:[...ne,A]),Je(!1),(async()=>{try{const ne=await fetch(`/api/notes/${t.id}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({email:A.email})});if(!ne.ok)throw new Error(await ne.text())}catch(ne){console.error("Failed to add collaborator",ne),window.alert("Failed to add collaborator")}})()}async function Ft(A){try{const ne=await fetch(`/api/notes/${t.id}/collaborators/${A}`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}});if(!ne.ok)throw new Error(await ne.text())}catch(ne){console.error("Failed to remove collaborator",ne),window.alert("Failed to remove collaborator")}}async function Kt(A){const ne=at,we=ne.filter(Z=>Number(Z.id)!==Number(A));$t(we),i&&i(we);try{const Z=await fetch(`/api/notes/${t.id}/images/${A}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}});if(!Z.ok)throw new Error(await Z.text());zt()}catch(Z){console.error("Failed to delete image",Z),$t(ne),i&&i(ne),window.alert("Failed to delete image")}}function Zt(A){const ne=Ge.current;ne?A>=0&&Awe.filter((Z,Ie)=>Ie!==A))}const $n=h.jsx("div",{className:"image-dialog-backdrop",onMouseDown:A=>{A.target===A.currentTarget&&K()},children:h.jsxs("div",{className:"image-dialog checklist-editor editor-dialog",role:"dialog","aria-modal":!0,style:{width:"min(1000px, 86vw)",...$},children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Edit checklist"}),h.jsx("div",{style:{display:"flex",gap:8,alignItems:"center"},children:h.jsx("button",{className:"icon-close",onClick:e,children:"✕"})})]}),h.jsxs("div",{className:"dialog-body",children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Checklist title",value:ue,onChange:A=>{de(A.target.value);try{Le()}catch{}},style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",gap:8,alignItems:"center",marginBottom:0},onMouseDown:A=>A.preventDefault(),onPointerDown:A=>A.preventDefault(),onPointerUp:A=>A.preventDefault(),children:[h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:A=>{A.preventDefault(),A.stopPropagation(),p.current=!0,ot("bold")},onPointerUp:A=>{A.preventDefault(),A.stopPropagation()},onMouseDownCapture:A=>{A.preventDefault(),A.stopPropagation()},onMouseUp:A=>A.preventDefault(),onClick:()=>{if(p.current){p.current=!1;return}ot("bold")},"aria-pressed":xt("bold"),children:"B"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:A=>{A.preventDefault(),A.stopPropagation(),p.current=!0,ot("italic")},onPointerUp:A=>{A.preventDefault(),A.stopPropagation()},onMouseDownCapture:A=>{A.preventDefault(),A.stopPropagation()},onMouseUp:A=>A.preventDefault(),onClick:()=>{if(p.current){p.current=!1;return}ot("italic")},"aria-pressed":xt("italic"),children:"I"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:A=>{A.preventDefault(),A.stopPropagation(),p.current=!0,ot("underline")},onPointerUp:A=>{A.preventDefault(),A.stopPropagation()},onMouseDownCapture:A=>{A.preventDefault(),A.stopPropagation()},onMouseUp:A=>A.preventDefault(),onClick:()=>{if(p.current){p.current=!1;return}ot("underline")},"aria-pressed":xt("underline"),children:"U"})]})]}),(It??g).length===0&&h.jsx("div",{style:{marginBottom:8},children:h.jsx("button",{className:"btn",onClick:()=>rn(0),children:"Add an item"})}),(It??g).filter(A=>!A.checked).map((A,ne)=>{const we=It??g,Z=we.indexOf(A),Ie=Jt(Z,we),Ve=(()=>{try{return pe(A)}catch{return A.key??Z}})(),Rt=W!=null&&String(W)===String(Ve);return h.jsxs("div",{className:`checklist-item ${Ie}${Rt?" is-active":""}`,style:{marginLeft:(A.indent||0)*18},draggable:!1,onPointerCancel:()=>{dn.current=null},onDragOver:be=>{be.preventDefault();const Dt=be.currentTarget.getBoundingClientRect();j.current&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{if(k===null)return;if(rt.current==="horizontal"&&Tt.current){const yt=(be.clientX||0)-Tt.current.x;if(yt>ee.indentPx&&Z>0){let bt=null;for(let mt=Z-1;mt>=0;mt--)if((g[mt].indent||0)===0){bt=g[mt].id??null;break}Mt.current={parentId:bt,makeNested:!0}}else yt<-ee.indentPx?Mt.current={parentId:null,makeNested:!1}:Mt.current={parentId:null,makeNested:!1};return}let st=!1;const ft=G.current?G.current.getBoundingClientRect():null;if(ft){const bt=Math.max(0,Math.min(ft.bottom,Dt.bottom)-Math.max(ft.top,Dt.top))/(Dt.height||1),mt=(be.clientY||0)>(Oe.current||be.clientY||0);Oe.current=be.clientY||0;const Qt=mt?ee.ghostOverlapDownPct:ee.ghostOverlapUpPct;st=bt>=Qt}st?(Xe.current&&(clearTimeout(Xe.current),Xe.current=null),z(yt=>yt===Z?yt:Z)):N===Z&&Xe.current===null&&(Xe.current=window.setTimeout(()=>{z(yt=>yt===Z?null:yt),Xe.current=null},Math.max(0,ee.hoverClearMs)))})},onDrop:be=>{be.preventDefault();const qe=k!==null?k:parseInt(be.dataTransfer.getData("text/plain")||"-1",10),Dt=Z;if(qe>=0){const st=Tt.current?(be.clientX||0)-Tt.current.x:0;if(rt.current==="horizontal"||Math.abs(st)>ee.indentPx){const yt=Ge.current;if(yt){if(st>ee.indentPx){const[bt,mt]=kt(g,qe);let Qt=null;for(let dt=qe-1;dt>=0;dt--)if((g[dt].indent||0)===0){Qt=dt;break}if(bt>=0)if(Qt!=null)if(bt===Dt)for(let dt=bt;dtbt&&(on=Qt-(mt-bt)+1);on0;)on++;const Yt=dt.map(Ct=>{const Pt=new xs;return typeof Ct.id=="number"&&Pt.set("id",Ct.id),Ct.uid&&Pt.set("uid",Ct.uid),Pt.set("content",Ct.content),Pt.set("checked",Ct.checked),Pt.set("indent",1),Pt});yt.insert(on,Yt)}else for(let dt=bt;dt=0)for(let Qt=bt;Qt{N===Z&&z(null),j.current&&(cancelAnimationFrame(j.current),j.current=null)},children:[h.jsxs("div",{className:"drag-gutter",style:{cursor:"grab",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",touchAction:"none"},onMouseDown:be=>{be.preventDefault()},onPointerDown:be=>{var st,ft;try{be.preventDefault()}catch{}try{be.stopPropagation()}catch{}be.currentTarget.setPointerCapture(be.pointerId),Se.current=be.clientY;const qe=It??g,Dt=typeof((st=qe[Z])==null?void 0:st.id)=="number"?qe[Z].id:((ft=qe[Z])==null?void 0:ft.uid)??null;dn.current={active:!0,startX:be.clientX,startY:be.clientY,idx:Z,draggedId:Dt,pointerId:be.pointerId},rt.current=null,Ot(null)},onPointerMove:be=>{const qe=dn.current;if(!qe||!qe.active)return;try{be.preventDefault()}catch{}Se.current=be.clientY;const Dt=be.clientX-qe.startX,st=be.clientY-qe.startY,ft=ee.directionLockPx;if(rt.current===null&&(Math.abs(Dt)>ft||Math.abs(st)>ft)&&(rt.current=Math.abs(Dt)>Math.abs(st)?"horizontal":"vertical"),rt.current==="vertical"){if(!G.current){const mt=Array.from(document.querySelectorAll(".image-dialog .checklist-item:not(.completed)")),Qt=qe.idx??-1,on=fn(Qt,It??g),Yt=mt[on];if(Yt){const Ct=Yt.getBoundingClientRect();je.current={x:be.clientX-Ct.left,y:be.clientY-Ct.top};const Pt=Yt.cloneNode(!0);Pt.style.position="fixed",Pt.style.left=Ct.left+"px",Pt.style.top=be.clientY-(je.current.y||0)+"px",Pt.style.width=Ct.width+"px",Pt.style.pointerEvents="none",Pt.style.zIndex="9999",Pt.style.opacity="0.98",Pt.classList.add("checklist-ghost"),document.body.appendChild(Pt),G.current=Pt;try{Yt.classList.add("drag-source")}catch{}M(Qt),z(Qt),Wt.current=Ct.left;try{const ln=document.querySelector(".image-dialog");ln&&ln.style.setProperty("--checklist-item-shift",`${Math.round(Ct.height)}px`)}catch{}}}G.current&&(G.current.style.left=Wt.current+"px",G.current.style.top=be.clientY-(je.current.y||0)+"px",ut());const bt=Array.from(document.querySelectorAll(".image-dialog .checklist-item:not(.completed)"));if(bt.length){let mt=null;const Qt=G.current?G.current.getBoundingClientRect():{top:be.clientY-10,bottom:be.clientY+10},dt=be.clientY>(re.current||be.clientY);re.current=be.clientY;const on=typeof ee.ghostOverlapUpPct=="number"&&typeof ee.ghostOverlapDownPct=="number"?dt?ee.ghostOverlapDownPct:ee.ghostOverlapUpPct:ee.ghostOverlapPct;for(let Ct=0;Ct=on){mt=Ct;break}}const Yt=It??g;if(mt!=null){const Ct=wn(mt,Yt);Ct!==N&&z(Ct)}}return}const yt=ee.indentPx;if(rt.current==="horizontal"){const bt=qe.draggedId??null;if(bt==null)return;const mt=g,Qt=mt.findIndex(dt=>typeof bt=="number"?dt.id===bt:dt.uid===bt);if(Qt<0)return;if(Qt===0&&Dt>0){Ot(null);return}if(Dt>yt){const[dt,on]=kt(mt,Qt),Yt=[...mt],Ct=Yt.splice(dt,on-dt);let Pt=null;for(let ln=Qt-1;ln>=0;ln--)if((mt[ln].indent||0)===0){Pt=ln;break}if(Pt!=null){const ln=typeof mt[Pt].id=="number"?mt[Pt].id:mt[Pt].uid,wi=Yt.findIndex(us=>typeof ln=="number"?us.id===ln:us.uid===ln);let $i=wi>=0?wi+1:Math.min(dt,Yt.length);for(;$i0;)$i++;const Hc=Ct.map(us=>({...us,indent:1}));Yt.splice($i,0,...Hc)}else{let ln=Math.min(dt,Yt.length);for(;ln0;)ln++;const wi=Ct.map($i=>({...$i,indent:1}));Yt.splice(ln,0,...wi)}Ot(Yt)}else if(Dt<-yt){const[dt,on]=kt(mt,Qt),Yt=[...mt];for(let Ct=dt;Ct{try{be.currentTarget.releasePointerCapture(be.pointerId)}catch{}if(dn.current=null,It){const qe=Ge.current;if(qe)try{for(let Dt=0;Dt{const bt=yt.get("id"),mt=yt.get("uid");return typeof st.id=="number"&&typeof bt=="number"?Number(st.id)===Number(bt):st.uid&&mt?String(st.uid)===String(mt):!1});if(ft>=0){const yt=qe.get(ft);try{yt.set("indent",Number(st.indent||0))}catch{}try{yt.set("checked",!!st.checked)}catch{}try{yt.set("content",String(st.content||""))}catch{}}}}catch{}Ot(null),rt.current=null,U();return}if(rt.current==="vertical"&&k!==null){const qe=k,Dt=g,[st,ft]=kt(Dt,qe);if(N!==null){const yt=qe=st&&yt{be.stopPropagation(),Pr(Z)},onPointerDown:be=>{be.stopPropagation()},onPointerUp:be=>{be.stopPropagation()},children:A.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),h.jsx("div",{style:{flex:1},children:h.jsx(Ix,{value:A.content||"",onChange:be=>nn(Z,be),onEnter:()=>rn(Z+1),autoFocus:L===Z,onFocus:be=>{d.current=be,Ee.current[Z]=be;try{te(pe(A))}catch{}f(qe=>qe+1),L===Z&&H(null)}})}),h.jsx("button",{className:"delete-item",onClick:be=>{if(be.stopPropagation(),!(W!=null&&String(W)===String(Ve))){try{te(Ve)}catch{}try{H(Z)}catch{}return}Zt(Z)},"aria-label":"Delete item",children:"✕"})]},A.key??Z)}),h.jsxs("div",{style:{marginTop:12},children:[h.jsx("button",{className:"btn completed-toggle",onClick:()=>E(A=>!A),"aria-expanded":x,"aria-controls":`editor-completed-${t.id}`,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:x?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:[g.filter(A=>A.checked).length," completed items"]})]})}),x&&(It??g).filter(A=>A.checked).map((A,ne)=>{const Z=(It??g).indexOf(A),Ie="",Ve=(()=>{try{return pe(A)}catch{return A.key??Z}})(),Rt=(()=>{try{return W!=null&&String(W)===String(Ve)}catch{return!1}})();return h.jsxs("div",{className:`checklist-item completed ${Ie}${Rt?" is-active":""}`,style:{marginLeft:(A.indent||0)*18},draggable:!1,onClick:be=>{try{be.stopPropagation()}catch{}try{te(Ve)}catch{}},children:[h.jsx("div",{style:{width:20}}),h.jsx("div",{className:`checkbox-visual ${A.checked?"checked":""}`,onClick:()=>Pr(Z),children:A.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{style:{flex:1,textDecoration:"line-through",minWidth:0},children:h.jsx("div",{className:"rt-html",dangerouslySetInnerHTML:{__html:ka.sanitize(String(A.content||""),{USE_PROFILES:{html:!0}})}})}),h.jsx("button",{className:"delete-item",onClick:be=>{if(be.stopPropagation(),!(W!=null&&String(W)===String(Ve))){try{te(Ve)}catch{}return}Zt(Z)},"aria-label":"Delete item",children:"✕"})]},A.key??Z)})]})]}),at&&at.length>0&&h.jsxs("div",{className:"editor-images",style:{marginTop:10,marginBottom:8},children:[h.jsx("button",{type:"button",className:"btn editor-images-toggle",onClick:()=>nt(A=>!A),"aria-expanded":ct,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:ct?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:["Images (",at.length,")"]})]})}),ct&&h.jsx("div",{className:"editor-images-grid",style:{marginTop:8},children:at.map(A=>h.jsxs("div",{className:"note-image",role:"button",tabIndex:0,onClick:()=>Bt(A.url),onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),Bt(A.url))},style:{cursor:"zoom-in",position:"relative"},children:[h.jsx("img",{src:A.url,alt:"note image"}),h.jsx("button",{className:"image-delete","aria-label":"Delete image",title:"Delete image",onClick:ne=>{ne.stopPropagation(),Kt(A.id)},style:{position:"absolute",right:6,bottom:6},children:"🗑️"})]},A.id))})]}),h.jsxs("div",{className:"dialog-footer",style:{borderTop:S?`1px solid ${S}`:void 0},children:[h.jsxs("div",{className:"note-actions",style:{marginRight:"auto",display:"inline-flex",gap:8,justifyContent:"flex-start",color:S},children:[h.jsx("button",{className:"tiny palette",onClick:()=>se(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>Me(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Je(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),o&&h.jsx("button",{ref:Pe,className:"tiny editor-more",onClick:A=>{A.stopPropagation(),ze(ne=>!ne)},"aria-label":"More",title:"More",children:"⋮"})]}),h.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:[h.jsx("button",{className:"btn",onClick:e,children:"Cancel"}),h.jsx("button",{className:"btn",onClick:K,disabled:v,children:v?"Saving...":"Save"})]})]})]})});if(typeof document<"u"){const A=zn.createPortal($n,document.body);return h.jsxs(h.Fragment,{children:[A,o&&Ke&&h.jsx(Hx,{anchorRef:Pe,itemsCount:o.onMoveToCollection?5:4,onClose:()=>ze(!1),onDelete:o.onDelete,onMoveToCollection:o.onMoveToCollection,onAddLabel:o.onAddLabel,onUncheckAll:o.onUncheckAll,onCheckAll:o.onCheckAll,onSetWidth:o.onSetWidth}),q&&h.jsx(ef,{anchorRef:void 0,onPick:V,onClose:()=>se(!1)}),xe&&h.jsx(tf,{onClose:()=>Me(!1),onSet:ne=>{Me(!1),ne&&window.alert(`Reminder set (UI-only): ${ne}`)}}),Q&&h.jsx(xc,{onClose:()=>Je(!1),onSelect:tt,current:(()=>{const ne=[];try{const we=a&&a.id?Number(a.id):void 0,Z=t.owner||null;Z&&typeof Z.id=="number"&&Z.id!==we&&ne.push({userId:Number(Z.id),email:String(Z.email||""),name:typeof Z.name=="string"?Z.name:void 0});const Ie=t.collaborators||[];for(const Ve of Ie){const Rt=Ve&&(Ve.user||{}),be=typeof Rt.id=="number"?Number(Rt.id):typeof Ve.userId=="number"?Number(Ve.userId):void 0,qe=typeof Rt.email=="string"?String(Rt.email):void 0,Dt=typeof Rt.name=="string"?String(Rt.name):void 0;be&&qe&&ne.push({collabId:Number(Ve.id),userId:be,email:qe,name:Dt})}}catch{}return ne})(),ownerId:typeof((sn=t.owner)==null?void 0:sn.id)=="number"?Number(t.owner.id):a==null?void 0:a.id,onRemove:Ft}),_t&&h.jsx(nf,{onClose:()=>J(!1),onAdd:he}),At&&h.jsx(_R,{url:At,onClose:()=>Bt(null)})]})}return $n}var Qq=mn.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),Ac=Qq;const Zq=()=>{let t=!0;return(e,n)=>{if(t){t=!1;try{e()}finally{t=!0}}else n!==void 0&&n()}},eJ=/[\uD800-\uDBFF]/,tJ=/[\uDC00-\uDFFF]/,nJ=(t,e)=>{let n=0,r=0;for(;n0&&eJ.test(t[n-1])&&n--;r+n0&&tJ.test(t[t.length-r])&&r--,{index:n,remove:t.length-n-r,insert:e.slice(n,e.length-r)}},rJ=nJ,Ns=(t,e)=>t>>>e|t<<32-e,iJ=t=>Ns(t,2)^Ns(t,13)^Ns(t,22),sJ=t=>Ns(t,6)^Ns(t,11)^Ns(t,25),oJ=t=>Ns(t,7)^Ns(t,18)^t>>>3,lJ=t=>Ns(t,17)^Ns(t,19)^t>>>10,aJ=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),cJ=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class uJ{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(cJ),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let d=16;d<64;d++)n[d]=lJ(n[d-2])+n[d-7]+oJ(n[d-15])+n[d-16];let r=e[0],i=e[1],s=e[2],o=e[3],l=e[4],a=e[5],c=e[6],u=e[7];for(let d=0,f,p;d<64;d++)f=u+sJ(l)+(l&a^~l&c)+aJ[d]+n[d]>>>0,p=iJ(r)+(r&i^r&s^i&s)>>>0,u=c,c=a,a=l,l=o+f>>>0,o=s,s=i,i=r,r=f+p>>>0;e[0]+=r,e[1]+=i,e[2]+=s,e[3]+=o,e[4]+=l,e[5]+=a,e[6]+=c,e[7]+=u}digest(e){let n=0;for(;n+56<=e.length;){let o=0;for(;o<16&&n+3=0&&n>>(3-l)*8;return s}}const dJ=t=>new uJ().digest(t),jn=new pn("y-sync"),no=new pn("y-undo");new pn("yjs-cursor");const fJ=t=>{for(let n=6;niO(fJ(dJ(kK(t)))),Cm=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&e.sv.get(t.id.client)>t.id.clock&&!$c(e.ds,t.id),pJ=[{light:"#ecd44433",dark:"#ecd444"}],mJ=(t,e,n)=>{if(!t.has(n)){if(t.sizer.add(i)),e=e.filter(i=>!r.has(i))}t.set(n,J9(e))}return t.get(n)},gJ=(t,{colors:e=pJ,colorMapping:n=new Map,permanentUserData:r=null,onFirstRender:i=()=>{},mapping:s}={})=>{let o=!1;const l=new wJ(t,s),a=new hn({props:{editable:c=>{const u=jn.getState(c);return u.snapshot==null&&u.prevSnapshot==null}},key:jn,state:{init:(c,u)=>({type:t,doc:t.doc,binding:l,snapshot:null,prevSnapshot:null,isChangeOrigin:!1,isUndoRedoOperation:!1,addToHistory:!0,colors:e,colorMapping:n,permanentUserData:r}),apply:(c,u)=>{const d=c.getMeta(jn);if(d!==void 0){u=Object.assign({},u);for(const f in d)u[f]=d[f]}return u.addToHistory=c.getMeta("addToHistory")!==!1,u.isChangeOrigin=d!==void 0&&!!d.isChangeOrigin,u.isUndoRedoOperation=d!==void 0&&!!d.isChangeOrigin&&!!d.isUndoRedoOperation,l.prosemirrorView!==null&&d!==void 0&&(d.snapshot!=null||d.prevSnapshot!=null)&&xO(0,()=>{l.prosemirrorView!=null&&(d.restore==null?l._renderSnapshot(d.snapshot,d.prevSnapshot,u):(l._renderSnapshot(d.snapshot,d.snapshot,u),delete u.restore,delete u.snapshot,delete u.prevSnapshot,l.mux(()=>{l._prosemirrorChanged(l.prosemirrorView.state.doc)})))}),u}},view:c=>(l.initView(c),s==null&&l._forceRerender(),i(),{update:()=>{const u=a.getState(c.state);if(u.snapshot==null&&u.prevSnapshot==null&&(o||c.state.doc.content.findDiffStart(c.state.doc.type.createAndFill().content)!==null)){if(o=!0,u.addToHistory===!1&&!u.isChangeOrigin){const d=no.getState(c.state),f=d&&d.undoManager;f&&f.stopCapturing()}l.mux(()=>{u.doc.transact(d=>{d.meta.set("addToHistory",u.addToHistory),l._prosemirrorChanged(c.state.doc)},jn)})}},destroy:()=>{l.destroy()}})});return a},yJ=(t,e,n)=>{if(e!==null&&e.anchor!==null&&e.head!==null)if(e.type==="all")t.setSelection(new ri(t.doc));else if(e.type==="node"){const r=Lh(n.doc,n.type,e.anchor,n.mapping);t.setSelection(vJ(t,r))}else{const r=Lh(n.doc,n.type,e.anchor,n.mapping),i=Lh(n.doc,n.type,e.head,n.mapping);r!==null&&i!==null&&t.setSelection(St.between(t.doc.resolve(r),t.doc.resolve(i)))}},vJ=(t,e)=>{const n=t.doc.resolve(e);return n.nodeAfter?pt.create(t.doc,e):St.near(n)},Cw=(t,e)=>({type:e.selection.jsonID,anchor:Aw(e.selection.anchor,t.type,t.mapping),head:Aw(e.selection.head,t.type,t.mapping)});class wJ{constructor(e,n=new Map){this.type=e,this.prosemirrorView=null,this.mux=Zq(),this.mapping=n,this.isOMark=new Map,this._observeFunction=this._typeChanged.bind(this),this.doc=e.doc,this.beforeTransactionSelection=null,this.beforeAllTransactions=()=>{this.beforeTransactionSelection===null&&this.prosemirrorView!=null&&(this.beforeTransactionSelection=Cw(this,this.prosemirrorView.state))},this.afterAllTransactions=()=>{this.beforeTransactionSelection=null},this._domSelectionInView=null}get _tr(){return this.prosemirrorView.state.tr.setMeta("addToHistory",!1)}_isLocalCursorInView(){return this.prosemirrorView.hasFocus()?(e1&&this._domSelectionInView===null&&(xO(0,()=>{this._domSelectionInView=null}),this._domSelectionInView=this._isDomSelectionInView()),this._domSelectionInView):!1}_isDomSelectionInView(){const e=this.prosemirrorView._root.getSelection();if(e==null||e.anchorNode==null)return!1;const n=this.prosemirrorView._root.createRange();n.setStart(e.anchorNode,e.anchorOffset),n.setEnd(e.focusNode,e.focusOffset),n.getClientRects().length===0&&n.startContainer&&n.collapsed&&n.selectNodeContents(n.startContainer);const i=n.getBoundingClientRect(),s=cf.documentElement;return i.bottom>=0&&i.right>=0&&i.left<=(window.innerWidth||s.clientWidth||0)&&i.top<=(window.innerHeight||s.clientHeight||0)}renderSnapshot(e,n){n||(n=FO(MO(),new Map)),this.prosemirrorView.dispatch(this._tr.setMeta(jn,{snapshot:e,prevSnapshot:n}))}unrenderSnapshot(){this.mapping.clear(),this.mux(()=>{const e=this.type.toArray().map(r=>Ph(r,this.prosemirrorView.state.schema,this)).filter(r=>r!==null),n=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(e),0,0));n.setMeta(jn,{snapshot:null,prevSnapshot:null}),this.prosemirrorView.dispatch(n)})}_forceRerender(){this.mapping.clear(),this.mux(()=>{const e=this.beforeTransactionSelection!==null?null:this.prosemirrorView.state.selection,n=this.type.toArray().map(i=>Ph(i,this.prosemirrorView.state.schema,this)).filter(i=>i!==null),r=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(n),0,0));if(e){const i=ia(ho(e.anchor,0),r.doc.content.size),s=ia(ho(e.head,0),r.doc.content.size);r.setSelection(St.create(r.doc,i,s))}this.prosemirrorView.dispatch(r.setMeta(jn,{isChangeOrigin:!0,binding:this}))})}_renderSnapshot(e,n,r){let i=this.doc,s=this.type;if(e||(e=fv(this.doc)),e instanceof Uint8Array||n instanceof Uint8Array)if((!(e instanceof Uint8Array)||!(n instanceof Uint8Array))&&Dr(),i=new Fi({gc:!1}),gm(i,n),n=fv(i),gm(i,e),e=fv(i),s._item===null){const o=Array.from(this.doc.share.keys()).find(l=>this.doc.share.get(l)===this.type);s=i.getXmlFragment(o)}else{const o=i.store.clients.get(s._item.id.client)??[],l=ss(o,s._item.id.clock);s=o[l].content.type}this.mapping.clear(),this.mux(()=>{i.transact(o=>{const l=r.permanentUserData;l&&l.dss.forEach(d=>{hl(o,d,f=>{})});const a=(d,f)=>{const p=d==="added"?l.getUserByClientId(f.client):l.getUserByDeletedId(f);return{user:p,type:d,color:mJ(r.colorMapping,r.colors,p)}},c=GO(s,new u1(n.ds,e.sv)).map(d=>!d._item.deleted||Cm(d._item,e)||Cm(d._item,n)?Ph(d,this.prosemirrorView.state.schema,{mapping:new Map,isOMark:new Map},e,n,a):null).filter(d=>d!==null),u=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(c),0,0));this.prosemirrorView.dispatch(u.setMeta(jn,{isChangeOrigin:!0}))},jn)})}_typeChanged(e,n){if(this.prosemirrorView==null)return;const r=jn.getState(this.prosemirrorView.state);if(e.length===0||r.snapshot!=null||r.prevSnapshot!=null){this.renderSnapshot(r.snapshot,r.prevSnapshot);return}this.mux(()=>{const i=(l,a)=>this.mapping.delete(a);hl(n,n.deleteSet,l=>{if(l.constructor===cn){const a=l.content.type;a&&this.mapping.delete(a)}}),n.changed.forEach(i),n.changedParentTypes.forEach(i);const s=this.type.toArray().map(l=>xj(l,this.prosemirrorView.state.schema,this)).filter(l=>l!==null);let o=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new _e(ve.from(s),0,0));yJ(o,this.beforeTransactionSelection,this),o=o.setMeta(jn,{isChangeOrigin:!0,isUndoRedoOperation:n.origin instanceof VO}),this.beforeTransactionSelection!==null&&this._isLocalCursorInView()&&o.scrollIntoView(),this.prosemirrorView.dispatch(o)})}_prosemirrorChanged(e){this.doc.transact(()=>{Nw(this.doc,this.type,e,this),this.beforeTransactionSelection=Cw(this,this.prosemirrorView.state)},jn)}initView(e){this.prosemirrorView!=null&&this.destroy(),this.prosemirrorView=e,this.doc.on("beforeAllTransactions",this.beforeAllTransactions),this.doc.on("afterAllTransactions",this.afterAllTransactions),this.type.observeDeep(this._observeFunction)}destroy(){this.prosemirrorView!=null&&(this.prosemirrorView=null,this.type.unobserveDeep(this._observeFunction),this.doc.off("beforeAllTransactions",this.beforeAllTransactions),this.doc.off("afterAllTransactions",this.afterAllTransactions))}}const xj=(t,e,n,r,i,s)=>{const o=n.mapping.get(t);if(o===void 0){if(t instanceof Mr)return Ph(t,e,n,r,i,s);throw Oi()}return o},Ph=(t,e,n,r,i,s)=>{const o=[],l=a=>{var c,u;if(a instanceof Mr){const d=xj(a,e,n,r,i,s);d!==null&&o.push(d)}else{const d=(u=(c=a._item.right)==null?void 0:c.content)==null?void 0:u.type;d instanceof pl&&!d._item.deleted&&d._item.id.client===d.doc.clientID&&(a.applyDelta([{retain:a.length},...d.toDelta()]),d.doc.transact(p=>{d._item.delete(p)}));const f=bJ(a,e,n,r,i,s);f!==null&&f.forEach(p=>{p!==null&&o.push(p)})}};r===void 0||i===void 0?t.toArray().forEach(l):GO(t,new u1(i.ds,r.sv)).forEach(l);try{const a=t.getAttributes(r);r!==void 0&&(Cm(t._item,r)?Cm(t._item,i)||(a.ychange=s?s("added",t._item.id):{type:"added"}):a.ychange=s?s("removed",t._item.id):{type:"removed"});const c=e.node(t.nodeName,a,o);return n.mapping.set(t,c),c}catch{return t.doc.transact(c=>{t._item.delete(c)},jn),n.mapping.delete(t),null}},bJ=(t,e,n,r,i,s)=>{const o=[],l=t.toDelta(r,i,s);try{for(let a=0;a{t._item.delete(c)},jn),null}return o},xJ=(t,e)=>{const n=new oi,r=t.map(i=>({insert:i.text,attributes:Sj(i.marks,e)}));return n.applyDelta(r),e.mapping.set(n,t),n},kJ=(t,e)=>{const n=new Mr(t.type.name);for(const r in t.attrs){const i=t.attrs[r];i!==null&&r!=="ychange"&&n.setAttribute(r,i)}return n.insert(0,jg(t).map(r=>Ew(r,e))),e.mapping.set(n,t),n},Ew=(t,e)=>t instanceof Array?xJ(t,e):kJ(t,e),xN=t=>typeof t=="object"&&t!==null,k1=(t,e)=>{const n=Object.keys(t).filter(i=>t[i]!==null);let r=n.length===Object.keys(e).filter(i=>e[i]!==null).length;for(let i=0;i{const e=t.content.content,n=[];for(let r=0;r{const n=t.toDelta();return n.length===e.length&&n.every((r,i)=>r.insert===e[i].text&&ZD(r.attributes||{}).length===e[i].marks.length&&_c(r.attributes,(s,o)=>{var u;const l=S1(o),a=e[i].marks;return a.find(d=>d.type.name===l)?k1(s,(u=a.find(d=>d.type.name===l))==null?void 0:u.attrs):!1}))},_d=(t,e)=>{if(t instanceof Mr&&!(e instanceof Array)&&Tw(t,e)){const n=jg(e);return t._length===n.length&&k1(t.getAttributes(),e.attrs)&&t.toArray().every((r,i)=>_d(r,n[i]))}return t instanceof oi&&e instanceof Array&&kj(t,e)},Em=(t,e)=>t===e||t instanceof Array&&e instanceof Array&&t.length===e.length&&t.every((n,r)=>e[r]===n),kN=(t,e,n)=>{const r=t.toArray(),i=jg(e),s=i.length,o=r.length,l=ia(o,s);let a=0,c=0,u=!1;for(;a{let e="",n=t._start;const r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof ls?e+=n.content.str:n.content instanceof qn&&(r[n.content.key]=null)),n=n.right;return{str:e,nAttrs:r}},CJ=(t,e,n)=>{n.mapping.set(t,e);const{nAttrs:r,str:i}=SJ(t),s=e.map(c=>({insert:c.text,attributes:Object.assign({},r,Sj(c.marks,n))})),{insert:o,remove:l,index:a}=rJ(i,s.map(c=>c.insert).join(""));t.delete(a,l),t.insert(a,o),t.applyDelta(s.map(c=>({retain:c.insert.length,attributes:c.attributes})))},EJ=/(.*)(--[a-zA-Z0-9+/=]{8})$/,S1=t=>{var e;return((e=EJ.exec(t))==null?void 0:e[1])??t},NJ=(t,e)=>{const n=[];for(const r in t)n.push(e.mark(S1(r),t[r]));return n},Sj=(t,e)=>{const n={};return t.forEach(r=>{if(r.type.name!=="ychange"){const i=as(e.isOMark,r.type,()=>!r.type.excludes(r.type));n[i?`${r.type.name}--${hJ(r.toJSON())}`:r.type.name]=r.attrs}}),n},Nw=(t,e,n,r)=>{if(e instanceof Mr&&e.nodeName!==n.type.name)throw new Error("node name mismatch!");if(r.mapping.set(e,n),e instanceof Mr){const d=e.getAttributes(),f=n.attrs;for(const p in f)f[p]!==null?d[p]!==f[p]&&p!=="ychange"&&e.setAttribute(p,f[p]):e.removeAttribute(p);for(const p in d)f[p]===void 0&&e.removeAttribute(p)}const i=jg(n),s=i.length,o=e.toArray(),l=o.length,a=ia(s,l);let c=0,u=0;for(;c{for(;l-c-u>0&&s-c-u>0;){const f=o[c],p=i[c],m=o[l-u-1],g=i[s-u-1];if(f instanceof oi&&p instanceof Array)kj(f,p)||CJ(f,p,r),c+=1;else{let y=f instanceof Mr&&Tw(f,p),v=m instanceof Mr&&Tw(m,g);if(y&&v){const w=kN(f,p,r),x=kN(m,g,r);w.foundMappedChild&&!x.foundMappedChild?v=!1:!w.foundMappedChild&&x.foundMappedChild||w.equalityFactor0&&(e.slice(c,c+d).forEach(f=>r.mapping.delete(f)),e.delete(c,d)),c+u!(e instanceof Array)&&t.nodeName===e.type.name,Aw=(t,e,n)=>{if(t===0)return dv(e,0,-1);let r=e._first===null?null:e._first.content.type;for(;r!==null&&e!==r;){if(r instanceof oi){if(r._length>=t)return dv(r,t,-1);if(t-=r._length,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{do r=r._item===null?null:r._item.parent,t--;while(r!==e&&r!==null&&r._item!==null&&r._item.next===null);r!==null&&r!==e&&(r=r._item===null?null:r._item.next.content.type)}}else{const i=(n.get(r)||{nodeSize:0}).nodeSize;if(r._first!==null&&t1)return new ym(r._item===null?null:r._item.id,r._item===null?Dd(r):null,null);if(t-=i,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{if(t===0)return r=r._item===null?r:r._item.parent,new ym(r._item===null?null:r._item.id,r._item===null?Dd(r):null,null);do r=r._item.parent,t--;while(r!==e&&r._item.next===null);r!==e&&(r=r._item.next.content.type)}}}if(r===null)throw Dr();if(t===0&&r.constructor!==oi&&r!==e)return TJ(r._item.parent,r._item)}return dv(e,e._length,-1)},TJ=(t,e)=>{let n=null,r=null;return t._item===null?r=Dd(t):n=Ht(t._item.id.client,t._item.id.clock),new ym(n,r,e.id)},Lh=(t,e,n,r)=>{const i=PY(n,t);if(i===null||i.type!==e&&!Od(e,i.type._item))return null;let s=i.type,o=0;if(s.constructor===oi)o=i.index;else if(s._item===null||!s._item.deleted){let l=s._first,a=0;for(;a{let i;if(r instanceof oi)i=r.toDelta().map(o=>{const l={type:"text",text:o.insert};return o.attributes&&(l.marks=Object.keys(o.attributes).map(a=>{const c=o.attributes[a],d={type:S1(a)};return Object.keys(c)&&(d.attrs=c),d})),l});else if(r instanceof Mr){i={type:r.nodeName};const s=r.getAttributes();Object.keys(s).length&&(i.attrs=s);const o=r.toArray();o.length&&(i.content=o.map(n).flat())}else Dr();return i};return{type:"doc",content:e.map(n)}}const MJ=t=>{const e=no.getState(t).undoManager;if(e!=null)return e.undo(),!0},IJ=t=>{const e=no.getState(t).undoManager;if(e!=null)return e.redo(),!0},RJ=new Set(["paragraph"]),DJ=(t,e)=>!(t instanceof cn)||!(t.content instanceof cs)||!(t.content.type instanceof pl||t.content.type instanceof Mr&&e.has(t.content.type.nodeName))||t.content.type._length===0,OJ=({protectedNodes:t=RJ,trackedOrigins:e=[],undoManager:n=null}={})=>new hn({key:no,state:{init:(r,i)=>{const s=jn.getState(i),o=n||new VO(s.type,{trackedOrigins:new Set([jn].concat(e)),deleteFilter:l=>DJ(l,t),captureTransaction:l=>l.meta.get("addToHistory")!==!1});return{undoManager:o,prevSel:null,hasUndoOps:o.undoStack.length>0,hasRedoOps:o.redoStack.length>0}},apply:(r,i,s,o)=>{const l=jn.getState(o).binding,a=i.undoManager,c=a.undoStack.length>0,u=a.redoStack.length>0;return l?{undoManager:a,prevSel:Cw(l,s),hasUndoOps:c,hasRedoOps:u}:c!==i.hasUndoOps||u!==i.hasRedoOps?Object.assign({},i,{hasUndoOps:a.undoStack.length>0,hasRedoOps:a.redoStack.length>0}):i}},view:r=>{const i=jn.getState(r.state),s=no.getState(r.state).undoManager;return s.on("stack-item-added",({stackItem:o})=>{const l=i.binding;l&&o.meta.set(l,no.getState(r.state).prevSel)}),s.on("stack-item-popped",({stackItem:o})=>{const l=i.binding;l&&(l.beforeTransactionSelection=o.meta.get(l)||l.beforeTransactionSelection)}),{destroy:()=>{s.destroy()}}}});function jJ(t){return!!t.getMeta(jn)}function PJ(t,e){const n=jn.getState(t);return Lh(n.doc,n.type,e,n.binding.mapping)||0}function Cj(t,e){const n=jn.getState(t);return Aw(e,n.type,n.binding.mapping)}var _h=class Ej extends sx{constructor(e,n){super(e),this.yRelativePosition=n}static fromJSON(e){return new Ej(e.position,e.yRelativePosition)}toJSON(){return{position:this.position,yRelativePosition:this.yRelativePosition}}};function LJ(t,e){const n=Cj(e,t);return new _h(t,n)}function _J(t,e,n){const r=t instanceof _h?t.yRelativePosition:null;if(jJ(e)&&r){const o=PJ(n,r);return{position:new _h(o,r),mapResult:null}}const i=o2(t,e),s=i.position.position;return{position:new _h(s,r??Cj(n,s)),mapResult:i.mapResult}}var zJ=mn.create({name:"collaboration",priority:1e3,addOptions(){return{document:null,field:"default",fragment:null,provider:null}},addStorage(){return{isDisabled:!1}},onCreate(){this.editor.extensionManager.extensions.find(t=>t.name==="undoRedo")&&console.warn('[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-undo-redo".')},onBeforeCreate(){this.editor.utils.getUpdatedPosition=(t,e)=>_J(t,e,this.editor.state),this.editor.utils.createMappablePosition=t=>LJ(t,this.editor.state)},addCommands(){return{undo:()=>({tr:t,state:e,dispatch:n})=>(t.setMeta("preventDispatch",!0),no.getState(e).undoManager.undoStack.length===0?!1:n?MJ(e):!0),redo:()=>({tr:t,state:e,dispatch:n})=>(t.setMeta("preventDispatch",!0),no.getState(e).undoManager.redoStack.length===0?!1:n?IJ(e):!0)}},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Mod-y":()=>this.editor.commands.redo(),"Shift-Mod-z":()=>this.editor.commands.redo()}},addProseMirrorPlugins(){var t;const e=this.options.fragment?this.options.fragment:this.options.document.getXmlFragment(this.options.field),n=OJ(this.options.yUndoOptions),r=n.spec.view;n.spec.view=o=>{const{undoManager:l}=no.getState(o.state);l.restore&&(l.restore(),l.restore=()=>{});const a=r?r(o):void 0;return{destroy:()=>{const c=l.trackedOrigins.has(l),u=l._observers;l.restore=()=>{c&&l.trackedOrigins.add(l),l.doc.on("afterTransaction",l.afterTransactionHandler),l._observers=u},a!=null&&a.destroy&&a.destroy()}}};const i={...this.options.ySyncOptions,onFirstRender:this.options.onFirstRender},s=gJ(e,i);return this.editor.options.enableContentCheck&&((t=e.doc)==null||t.on("beforeTransaction",()=>{try{const o=AJ(e);if(o.content.length===0)return;this.editor.schema.nodeFromJSON(o).check()}catch(o){return this.editor.emit("contentError",{error:o,editor:this.editor,disableCollaboration:()=>{var l;(l=e.doc)==null||l.destroy(),this.storage.isDisabled=!0}}),!1}})),[s,n,this.editor.options.enableContentCheck&&new hn({key:new pn("filterInvalidContent"),filterTransaction:()=>{var o;return this.storage.isDisabled!==!1&&((o=e.doc)==null||o.destroy()),!0}})].filter(Boolean)}}),Pg=zJ;function FJ({note:t,onClose:e,onSaved:n,noteBg:r,onImagesUpdated:i,onColorChanged:s,moreMenu:o}){var Ye,Ge;const{token:l,user:a}=Sr(),c=B.useRef((()=>{try{return`c${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`c${Math.random()}`}})()),u=B.useRef((()=>{try{return`rte-${(t==null?void 0:t.id)||"x"}-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`rte-${Math.random()}`}})());B.useEffect(()=>{window.dispatchEvent(new Event("freemannotes:editor-modal-open"));try{const Y=u.current,ge=()=>{try{e()}catch{}};window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:Y,onBack:ge}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:u.current}}))}catch{}window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}},[]);const[d,f]=B.useState(t.title||""),[p,m]=B.useState(!1),[g,y]=B.useState(!1),[v,w]=B.useState(!1),[x,E]=B.useState(!1),[k,M]=B.useState(!1),[N,z]=B.useState((t.images||[]).map(Y=>({id:Number(Y.id),url:String(Y.url)}))),[X,L]=B.useState(!1),[H,W]=B.useState(null),[te,ue]=B.useState([]),[de,Ae]=B.useState(!1),me=B.useRef(null);B.useRef(!1);const q=B.useRef(!1),se=B.useRef(!1),xe=B.useCallback(()=>{if(!se.current){se.current=!0;try{window.dispatchEvent(new CustomEvent("freemannotes:draft/dirty",{detail:{noteId:Number(t==null?void 0:t.id)}}))}catch{}}},[t==null?void 0:t.id]),Me=B.useMemo(()=>new Fi,[t.id]),Q=B.useRef(null);B.useEffect(()=>{const Y=`note-${t.id}`,De=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/collab`,Be=new mf(De,Y,Me);Q.current=Be;const Le=j=>{j&&(q.current=!0)};try{Be.on("sync",Le)}catch{}return()=>{try{Be.off("sync",Le)}catch{}try{Be.destroy()}catch{}}},[t.id,Me]);const Je=B.useCallback(()=>{try{Me.getMap("meta").set("imagesTick",{t:Date.now(),by:c.current})}catch{}},[Me]),_t=B.useCallback(async()=>{try{const Y=await fetch(`/api/notes/${t.id}/images`,{headers:{Authorization:`Bearer ${l}`}});if(!Y.ok)return;const ge=await Y.json(),De=(ge&&ge.images||[]).map(Be=>({id:Number(Be.id),url:String(Be.url)}));z(De),i&&i(De)}catch{}},[t.id,l,i]);B.useEffect(()=>{const Y=(()=>{try{return Me.getMap("meta")}catch{return null}})();if(!Y)return;const ge=()=>{try{const De=Y.get("imagesTick");if(!De||!De.t||De.by&&String(De.by)===String(c.current))return;_t()}catch{}};try{Y.observe(ge)}catch{}return()=>{try{Y.unobserve(ge)}catch{}}},[Me,_t]);const J=pg({extensions:[ta.configure({heading:{levels:[1,2,3]}}),wR.configure({openOnClick:!0,autolink:!0}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:Me}),yg,mn.create({name:"paragraphEnterFix",priority:1e3,addKeyboardShortcuts(){return{"Shift-Enter":()=>{const Y=this.editor;return Y.commands.splitBlock(),Y.commands.setParagraph(),!0},"Mod-Enter":()=>{const Y=this.editor;return Y.commands.splitBlock(),Y.commands.setParagraph(),!0}}}})],editorProps:{attributes:{class:"rt-editor"}}});function at(Y){if(!J)return;const ge=J.state.selection;if(!ge||!ge.empty){J.chain().focus()[`toggle${Y.charAt(0).toUpperCase()+Y.slice(1)}`]().run();return}const De=ge.$from;let Be=De.depth;for(;Be>0&&!De.node(Be).isBlock;)Be--;const Le=De.start(Be),j=De.end(Be),G=J.chain().focus().setTextSelection({from:Le,to:j});Y==="bold"?G.toggleBold().run():Y==="italic"?G.toggleItalic().run():G.toggleUnderline().run();try{J.chain().setTextSelection(ge.from).run()}catch{}}B.useEffect(()=>{try{const Y=(t.images||[]).map(ge=>({id:Number(ge.id),url:String(ge.url)}));z(ge=>{try{if(ge.length===Y.length&&ge.every((De,Be)=>{var Le,j;return Number(De.id)===Number((Le=Y[Be])==null?void 0:Le.id)&&String(De.url)===String((j=Y[Be])==null?void 0:j.url)}))return ge}catch{}return Y})}catch{}},[t.images]);const[,$t]=B.useState(0);B.useEffect(()=>{if(!J)return;const Y=()=>$t(ge=>ge+1);return J.on("selectionUpdate",Y),J.on("transaction",Y),()=>{J.off("selectionUpdate",Y),J.off("transaction",Y)}},[J]);function ct(){if(!J)return;const Y=window.prompt("Enter URL:");Y&&J.chain().focus().extendMarkRange("link").setLink({href:Y}).run()}const nt=B.useRef(null);B.useEffect(()=>{if(!J)return;const Y=()=>{try{q.current&&xe()}catch{}nt.current&&window.clearTimeout(nt.current),nt.current=window.setTimeout(async()=>{try{const ge=J.getJSON();await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({body:JSON.stringify(ge),type:"TEXT"})})}catch{}},700)};return J.on("update",Y),()=>{J.off("update",Y),nt.current&&window.clearTimeout(nt.current)}},[J,t.id,l,xe]);async function At(){try{const Y=(()=>{try{return JSON.stringify((J==null?void 0:J.getJSON())||{})}catch{return t.body||""}})();if((t.title||"")!==d){const ge=await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({title:d})});if(!ge.ok)throw new Error(await ge.text())}n&&n({title:d,body:Y}),e()}catch(Y){console.error("Failed to update title",Y),window.alert("Failed to update title")}}function Bt(Y){if(!Y)return;const ge=Y.replace("#",""),De=ge.length===3?ge.split("").map(Tt=>Tt+Tt).join(""):ge;if(De.length!==6)return;const Be=parseInt(De.slice(0,2),16)/255,Le=parseInt(De.slice(2,4),16)/255,j=parseInt(De.slice(4,6),16)/255,G=Tt=>Tt<=.03928?Tt/12.92:Math.pow((Tt+.055)/1.055,2.4),fe=G(Be),je=G(Le),Ue=G(j),We=.2126*fe+.7152*je+.0722*Ue,Se=(1+.05)/(We+.05),Xe=(We+.05)/(0+.05);return Se>=Xe?"#ffffff":"#000000"}const wt={},[ce,Ee]=B.useState(r??(t.viewerColor||t.color||"")),Ke=ce?Bt(ce)||"var(--muted)":void 0;B.useEffect(()=>{Ee(r??(t.viewerColor||t.color||""))},[r,t.viewerColor,t.color]),ce&&(wt["--checkbox-bg"]=ce,wt["--checkbox-border"]=Ke||void 0,wt["--checkbox-stroke"]=Ke||void 0,wt["--checkbox-checked-bg"]=ce,wt["--checkbox-checked-mark"]=Ke||void 0,wt["--editor-surface"]=ce,wt.background=ce,Ke&&(wt.color=Ke));async function ze(Y){const ge=Y||"";try{const De=await fetch(`/api/notes/${t.id}/prefs`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({color:ge})});if(!De.ok)throw new Error(await De.text())}catch(De){console.error("Failed to save color preference",De),window.alert("Failed to save color preference")}Ee(ge);try{s==null||s(ge)}catch{}}function Pe(Y){if(M(!1),!Y)return;const ge=-Date.now();z(De=>{const Le=De.some(j=>String(j.url)===String(Y))?De:[...De,{id:ge,url:String(Y)}];return i&&i(Le),Le});try{L(!0)}catch{}(async()=>{try{const De=await fetch(`/api/notes/${t.id}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({url:Y})});if(!De.ok)throw new Error(await De.text());const Le=(await De.json()).image||null;Le&&Le.id&&Le.url&&(z(j=>{const G=Number(Le.id),fe=String(Le.url),je=j.map(Se=>Number(Se.id)===ge||String(Se.url)===String(Y)?{id:G,url:fe}:Se),We=je.some(Se=>Number(Se.id)===G)?je:[...je,{id:G,url:fe}];return i&&i(We),We}),Je())}catch(De){console.error("Failed to attach image",De),window.alert("Failed to attach image")}})()}function it(Y){ue(ge=>ge.find(De=>De.id===Y.id)?ge:[...ge,Y]),E(!1),(async()=>{try{const ge=await fetch(`/api/notes/${t.id}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({email:Y.email})});if(!ge.ok)throw new Error(await ge.text())}catch(ge){console.error("Failed to add collaborator",ge),window.alert("Failed to add collaborator")}})()}async function ot(Y){try{const ge=await fetch(`/api/notes/${t.id}/collaborators/${Y}`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}});if(!ge.ok)throw new Error(await ge.text())}catch(ge){console.error("Failed to remove collaborator",ge),window.alert("Failed to remove collaborator")}}async function xt(Y){const ge=N,De=ge.filter(Be=>Number(Be.id)!==Number(Y));z(De),i&&i(De);try{const Be=await $J(t.id,Y,l);if(!Be.ok)throw new Error(await Be.text());Je()}catch(Be){console.error("Failed to delete image",Be),z(ge),i&&i(ge),window.alert("Failed to delete image")}}const oe=h.jsx("div",{className:"image-dialog-backdrop",onMouseDown:Y=>{Y.target===Y.currentTarget&&At()},children:h.jsxs("div",{className:`image-dialog editor-dialog${p?" maximized":""}`,role:"dialog","aria-modal":!0,style:{width:p?"96vw":"min(1000px, 86vw)",...wt},children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Edit note"}),h.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[h.jsx("button",{className:"tiny",onClick:()=>m(Y=>!Y),"aria-label":"Toggle maximize",title:"Toggle maximize",children:"⤢"}),h.jsx("button",{className:"icon-close",onClick:e,children:"✕"})]})]}),h.jsxs("div",{className:"dialog-body",children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Title",value:d,onChange:Y=>{f(Y.target.value);try{xe()}catch{}},style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:0,marginBottom:0,overflowX:"auto",color:Ke},children:[h.jsx("button",{className:"tiny",onClick:()=>at("bold"),"aria-pressed":J==null?void 0:J.isActive("bold"),"aria-label":"Bold",title:"Bold",children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>at("italic"),"aria-pressed":J==null?void 0:J.isActive("italic"),"aria-label":"Italic",title:"Italic",children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>at("underline"),"aria-pressed":J==null?void 0:J.isActive("underline"),"aria-label":"Underline",title:"Underline",children:"U"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleHeading({level:1}).run(),"aria-pressed":J==null?void 0:J.isActive("heading",{level:1}),"aria-label":"Heading 1",title:"Heading 1",children:"H1"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleHeading({level:2}).run(),"aria-pressed":J==null?void 0:J.isActive("heading",{level:2}),"aria-label":"Heading 2",title:"Heading 2",children:"H2"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleHeading({level:3}).run(),"aria-pressed":J==null?void 0:J.isActive("heading",{level:3}),"aria-label":"Heading 3",title:"Heading 3",children:"H3"}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleBulletList().run(),"aria-pressed":J==null?void 0:J.isActive("bulletList"),"aria-label":"Bulleted list",title:"Bulleted list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("circle",{cx:"5",cy:"6",r:"1.5"}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"12",r:"1.5"}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"18",r:"1.5"}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().toggleOrderedList().run(),"aria-pressed":J==null?void 0:J.isActive("orderedList"),"aria-label":"Numbered list",title:"Numbered list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("text",{x:"3.5",y:"7",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"1."}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"13",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"2."}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"19",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"3."}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("left").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"left"}),"aria-label":"Align left",title:"Align left",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"4",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("center").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"center"}),"aria-label":"Align center",title:"Align center",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"7",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"8",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("right").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"right"}),"aria-label":"Align right",title:"Align right",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"6",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"10",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"6",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"12",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>J==null?void 0:J.chain().focus().setTextAlign("justify").run(),"aria-pressed":J==null?void 0:J.isActive({textAlign:"justify"}),"aria-label":"Justify",title:"Justify",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"9",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"17",width:"14",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:ct,"aria-label":"Insert link",title:"Insert link",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("path",{d:"M9.17 14.83a3 3 0 0 1 0-4.24l2.83-2.83a3 3 0 1 1 4.24 4.24l-.88.88",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),h.jsx("path",{d:"M14.83 9.17a3 3 0 0 1 0 4.24l-2.83 2.83a3 3 0 1 1-4.24-4.24l.88-.88",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),h.jsx("div",{onKeyDown:Y=>{try{if(!(Y.ctrlKey||Y.metaKey)){const Be=String(Y.key||"");(Be.length===1||Be==="Backspace"||Be==="Enter"||Be==="Delete")&&xe()}}catch{}if(!(!J||!(Y.ctrlKey||Y.metaKey))&&J.isFocused)switch(Y.key.toLowerCase()){case"b":Y.preventDefault(),at("bold");break;case"i":Y.preventDefault(),at("italic");break;case"u":Y.preventDefault(),at("underline");break;case"k":Y.preventDefault(),ct();break;case"l":Y.preventDefault(),J.chain().focus().setTextAlign("left").run();break;case"r":Y.preventDefault(),J.chain().focus().setTextAlign("right").run();break;case"e":Y.preventDefault(),J.chain().focus().setTextAlign("center").run();break;case"j":Y.preventDefault(),J.chain().focus().setTextAlign("justify").run();break}},children:h.jsx(Qd,{editor:J,style:{color:Ke}})}),N&&N.length>0&&h.jsxs("div",{className:"editor-images",style:{marginTop:10},children:[h.jsx("button",{type:"button",className:"btn editor-images-toggle",onClick:()=>L(Y=>!Y),"aria-expanded":X,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:X?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:["Images (",N.length,")"]})]})}),X&&h.jsx("div",{className:"editor-images-grid",style:{marginTop:8},children:N.map(Y=>h.jsxs("div",{className:"note-image",role:"button",tabIndex:0,onClick:()=>W(Y.url),onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.preventDefault(),W(Y.url))},style:{cursor:"zoom-in",position:"relative"},children:[h.jsx("img",{src:Y.url,alt:"note image"}),h.jsx("button",{className:"image-delete","aria-label":"Delete image",title:"Delete image",onClick:ge=>{ge.stopPropagation(),xt(Y.id)},style:{position:"absolute",right:6,bottom:6},children:"🗑️"})]},Y.id))})]})]}),h.jsxs("div",{className:"dialog-footer",style:{borderTop:`1px solid ${Ke||"rgba(255,255,255,0.15)"}`},children:[h.jsxs("div",{className:"note-actions",style:{marginRight:"auto",display:"inline-flex",gap:8,justifyContent:"flex-start",color:Ke},children:[h.jsx("button",{className:"tiny palette",onClick:()=>y(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>w(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>E(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>M(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),o&&h.jsx("button",{ref:me,className:"tiny editor-more",onClick:Y=>{Y.stopPropagation(),Ae(ge=>!ge)},"aria-label":"More",title:"More",children:"⋮"})]}),h.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:h.jsx("button",{className:"btn",onClick:At,children:"Save"})})]})]})});if(x&&((()=>{const Y=[];try{const ge=a&&a.id?Number(a.id):void 0,De=t.owner||null;De&&typeof De.id=="number"&&De.id!==ge&&Y.push({userId:Number(De.id),email:String(De.email||""),name:typeof De.name=="string"?De.name:void 0});const Be=t.collaborators||[];for(const Le of Be){const j=Le&&(Le.user||{}),G=typeof j.id=="number"?Number(j.id):typeof Le.userId=="number"?Number(Le.userId):void 0,fe=typeof j.email=="string"?String(j.email):void 0,je=typeof j.name=="string"?String(j.name):void 0;G&&fe&&Y.push({collabId:Number(Le.id),userId:G,email:fe,name:je})}}catch{}return Y})(),typeof((Ye=t.owner)==null?void 0:Ye.id)=="number"?Number(t.owner.id):a==null||a.id),typeof document<"u"){const Y=zn.createPortal(oe,document.body);return h.jsxs(h.Fragment,{children:[Y,o&&de&&h.jsx(Hx,{anchorRef:me,itemsCount:o.onMoveToCollection?5:4,onClose:()=>Ae(!1),onDelete:o.onDelete,onMoveToCollection:o.onMoveToCollection,onAddLabel:o.onAddLabel,onSetWidth:o.onSetWidth}),g&&h.jsx(ef,{anchorRef:void 0,onPick:ze,onClose:()=>y(!1)}),v&&h.jsx(tf,{onClose:()=>w(!1),onSet:ge=>{w(!1),ge&&window.alert(`Reminder set (UI-only): ${ge}`)}}),x&&h.jsx(xc,{onClose:()=>E(!1),onSelect:it,current:(()=>{const ge=[];try{const De=a&&a.id?Number(a.id):void 0,Be=t.owner||null;Be&&typeof Be.id=="number"&&Be.id!==De&&ge.push({userId:Number(Be.id),email:String(Be.email||""),name:typeof Be.name=="string"?Be.name:void 0});const Le=t.collaborators||[];for(const j of Le){const G=j&&(j.user||{}),fe=typeof G.id=="number"?Number(G.id):typeof j.userId=="number"?Number(j.userId):void 0,je=typeof G.email=="string"?String(G.email):void 0,Ue=typeof G.name=="string"?String(G.name):void 0;fe&&je&&ge.push({collabId:Number(j.id),userId:fe,email:je,name:Ue})}}catch{}return ge})(),ownerId:typeof((Ge=t.owner)==null?void 0:Ge.id)=="number"?Number(t.owner.id):a==null?void 0:a.id,onRemove:ot}),k&&h.jsx(nf,{onClose:()=>M(!1),onAdd:Pe}),H&&h.jsx(_R,{url:H,onClose:()=>W(null)})]})}return oe}function $J(t,e,n){return fetch(`/api/notes/${t}/images/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})}function BJ({noteId:t,onClose:e,onChanged:n}){const{token:r}=Sr(),[i,s]=B.useState([]),[o,l]=B.useState([]),[a,c]=B.useState([]),[u,d]=B.useState(!1),[f,p]=B.useState(""),[m,g]=B.useState(!1);B.useEffect(()=>{try{return window.dispatchEvent(new Event("freemannotes:editor-modal-open")),()=>{setTimeout(()=>{try{window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}catch{}},0)}}catch{return}},[]);const y=i.length?Number(i[i.length-1].id):null,v=B.useCallback(async()=>{if(!r){l([]);return}d(!0);try{const L=y==null?"":`?parentId=${encodeURIComponent(String(y))}`,W=await(await fetch(`/api/collections${L}`,{headers:{Authorization:`Bearer ${r}`}})).json(),te=Array.isArray(W==null?void 0:W.collections)?W.collections:[];l(te.map(ue=>({id:Number(ue.id),name:String(ue.name||""),parentId:ue.parentId==null?null:Number(ue.parentId),hasChildren:!!ue.hasChildren,noteCount:typeof ue.noteCount=="number"?Number(ue.noteCount):void 0})).filter(ue=>Number.isFinite(ue.id)&&ue.name.length))}catch{l([])}finally{d(!1)}},[r,y]);B.useEffect(()=>{v()},[v]);const w=B.useCallback(async()=>{if(!r){c([]);return}try{const L=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections`,{headers:{Authorization:`Bearer ${r}`}});if(!L.ok)return;const H=await L.json(),W=Array.isArray(H==null?void 0:H.collections)?H.collections:[];c(W.map(te=>({id:Number(te.id),name:String(te.name||""),parentId:te.parentId==null?null:Number(te.parentId)})).filter(te=>Number.isFinite(te.id)&&te.name.length))}catch{}},[r,t]);B.useEffect(()=>{w()},[w]),B.useEffect(()=>{const L=H=>{H.key==="Escape"&&e()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[e]);const x=B.useMemo(()=>new Set(a.map(L=>Number(L.id)).filter(L=>Number.isFinite(L))),[a]),E=B.useCallback((L,H)=>{const W=Number(L),te=Number(H);!Number.isFinite(W)||!Number.isFinite(te)||te===0||l(ue=>ue.map(de=>Number(de.id)!==W||typeof de.noteCount!="number"?de:{...de,noteCount:Math.max(0,Number(de.noteCount)+te)}))},[]),k=async L=>{if(!r||m||!Number.isFinite(L))return;const H=x.has(Number(L));g(!0);try{const W=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({collectionId:Number(L)})});if(!W.ok)throw new Error(await W.text());const te=await W.json(),ue=Array.isArray(te==null?void 0:te.collections)?te.collections:[];c(ue.map(de=>({id:Number(de.id),name:String(de.name||""),parentId:de.parentId==null?null:Number(de.parentId)})).filter(de=>Number.isFinite(de.id)&&de.name.length)),H||E(L,1);try{n(ue)}catch{}}catch(W){window.alert("Failed to add note to collection: "+String(W))}finally{g(!1)}},M=async L=>{if(!r||m||!Number.isFinite(L))return;const H=x.has(Number(L));g(!0);try{const W=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections/${encodeURIComponent(String(L))}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!W.ok)throw new Error(await W.text());const te=await W.json(),ue=Array.isArray(te==null?void 0:te.collections)?te.collections:[];c(ue.map(de=>({id:Number(de.id),name:String(de.name||""),parentId:de.parentId==null?null:Number(de.parentId)})).filter(de=>Number.isFinite(de.id)&&de.name.length)),H&&E(L,-1);try{n(ue)}catch{}}catch(W){window.alert("Failed to remove from collection: "+String(W))}finally{g(!1)}},N=async()=>{if(!r||m)return;const L=Array.from(new Set(a.map(H=>Number(H.id)).filter(H=>Number.isFinite(H))));g(!0);try{const H=await fetch(`/api/notes/${encodeURIComponent(String(t))}/collections`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!H.ok)throw new Error(await H.text());c([]),L.forEach(W=>E(W,-1));try{n([])}catch{}}catch(H){window.alert("Failed to clear collections: "+String(H))}finally{g(!1)}},z=async()=>{var H;if(!r)return;const L=String(f||"").trim();if(L&&!m){g(!0);try{const W=await fetch("/api/collections",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({name:L,parentId:y})});if(!W.ok)throw new Error(await W.text());const te=await W.json(),ue=Number((H=te==null?void 0:te.collection)==null?void 0:H.id);if(Number.isFinite(ue)){try{window.dispatchEvent(new CustomEvent("collections:changed",{detail:{invalidateAll:!0,reason:"create",id:ue}}))}catch{}try{p("")}catch{}g(!1),await k(ue);return}await v()}catch(W){window.alert("Failed to create collection: "+String(W))}finally{g(!1)}}},X=i.map(L=>L.name).join(" / ");return zn.createPortal(h.jsx("div",{style:{position:"fixed",inset:0,background:"var(--modal-backdrop, rgba(0,0,0,0.66))",zIndex:10050,display:"flex",alignItems:"center",justifyContent:"center",padding:16},onPointerDown:L=>{L.target===L.currentTarget&&(L.preventDefault(),L.stopPropagation(),setTimeout(()=>e(),0))},onClick:L=>{L.target===L.currentTarget&&(L.preventDefault(),L.stopPropagation())},children:h.jsxs("div",{role:"dialog","aria-label":"Add to collection","aria-modal":"true",style:{width:"min(520px, 100%)",maxHeight:"min(680px, 100%)",overflow:"auto",background:"var(--modal-surface, var(--panel, var(--card)))",color:"var(--text, var(--fg))",border:"1px solid var(--modal-border, var(--border, rgba(255,255,255,0.10)))",borderRadius:12,boxShadow:"0 18px 48px rgba(0,0,0,0.42)",padding:14},onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onClick:L=>L.stopPropagation(),children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[h.jsx("div",{style:{display:"flex",alignItems:"center",gap:8},children:i.length>0&&h.jsxs(h.Fragment,{children:[h.jsx("button",{className:"btn",onClick:()=>s(L=>L.slice(0,-1)),disabled:m,title:"Back",children:"Back"}),h.jsx("button",{className:"btn",onClick:()=>s([]),disabled:m,title:"Root",children:"All"})]})}),h.jsx("button",{className:"btn",onClick:e,disabled:m,children:"Done"})]}),h.jsxs("div",{style:{marginTop:10,marginBottom:10},children:[h.jsx("div",{style:{fontWeight:700},children:"Add to…"}),h.jsx("div",{style:{color:"var(--muted)",fontSize:12},children:X||"All notes"})]}),h.jsxs("div",{style:{display:"flex",gap:8,marginBottom:10},children:[y!=null&&h.jsx("button",{className:"btn",onClick:()=>{k(Number(y))},disabled:m,title:"Add to current collection",children:"Add here"}),h.jsx("button",{className:"btn",onClick:N,disabled:m,title:"Remove from all collections",children:"Remove all"})]}),h.jsxs("div",{style:{display:"grid",gap:6},children:[u&&h.jsx("div",{style:{color:"var(--muted)"},children:"Loading…"}),!u&&o.length===0&&h.jsx("div",{style:{color:"var(--muted)"},children:"No sub-collections"}),o.map(L=>h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"8px 10px",borderRadius:10,border:"1px solid var(--border)",background:"var(--panel-2, transparent)"},children:[h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[h.jsx("button",{className:"btn",onClick:()=>s(H=>[...H,{id:L.id,name:L.name}]),disabled:m,title:"Open",children:"Open"}),h.jsxs("div",{style:{overflow:"hidden"},children:[h.jsx("div",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:L.name}),typeof L.noteCount=="number"&&h.jsxs("div",{style:{color:"var(--muted)",fontSize:12},children:[L.noteCount," notes"]})]})]}),(()=>{const H=x.has(Number(L.id));return h.jsx("button",{className:"btn",onClick:()=>{H?M(L.id):k(L.id)},disabled:m,title:H?"Remove note from this collection":"Add note to this collection",children:H?"Remove":"Add"})})()]},L.id))]}),h.jsxs("div",{style:{marginTop:12,borderTop:"1px solid var(--border)",paddingTop:10},children:[h.jsx("div",{style:{fontWeight:700,marginBottom:6},children:"New collection"}),h.jsxs("div",{style:{display:"flex",gap:8},children:[h.jsx("input",{value:f,onChange:L=>p(L.target.value),placeholder:"Name",style:{flex:1,minWidth:0,padding:"8px 10px",borderRadius:10,border:"1px solid var(--border)",background:"var(--panel)",color:"var(--text)"},onKeyDown:L=>{L.key==="Enter"&&z()},disabled:m}),h.jsx("button",{className:"btn",onClick:z,disabled:m||!f.trim(),children:"Create & add"})]})]})]})}),document.body)}function UJ({noteId:t,onClose:e,onUpdated:n}){const{token:r}=Sr(),[i,s]=b.useState([]),[o,l]=b.useState(new Set),[a,c]=b.useState(""),[u,d]=b.useState(!1);b.useEffect(()=>{r&&Promise.all([fetch("/api/labels",{headers:{Authorization:`Bearer ${r}`}}).then(y=>y.json()),fetch("/api/notes",{headers:{Authorization:`Bearer ${r}`}}).then(y=>y.json())]).then(([y,v])=>{const w=Array.isArray(y.labels)?y.labels:[];s(w);const x=(Array.isArray(v.notes)?v.notes:[]).find(k=>k.id===t),E=new Set(((x==null?void 0:x.noteLabels)||[]).map(k=>{var M;return(M=k.label)==null?void 0:M.id}).filter(k=>typeof k=="number"));l(E)}).catch(()=>{})},[r,t]),b.useEffect(()=>{try{return window.dispatchEvent(new Event("freemannotes:editor-modal-open")),()=>{setTimeout(()=>{try{window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}catch{}},0)}}catch{return}},[]);async function f(y){if(r){d(!0);try{let v={};if(typeof y=="string")v={name:y};else{const E=i.find(k=>k.id===y);if(!E)return;v={name:E.name}}const w=await fetch(`/api/notes/${t}/labels`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(v)});if(!w.ok)throw new Error(await w.text());const x=await w.json();if(x!=null&&x.label){const E=x.label,M=i.some(z=>z.id===E.id)?i:[...i,E],N=new Set(o);N.add(E.id),s(M),l(N),n&&n(M.filter(z=>N.has(z.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent("labels:refresh"))}}finally{d(!1)}}}async function p(y){if(r){d(!0);try{const v=await fetch(`/api/notes/${t}/labels/${y}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!v.ok)throw new Error(await v.text());const w=new Set(o);w.delete(y),l(w),n&&n(i.filter(x=>w.has(x.id)))}finally{d(!1)}}}async function m(y){if(!(!r||!window.confirm("Delete this label? This will remove it from all notes and from the sidebar."))){d(!0);try{const w=await fetch(`/api/labels/${y}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!w.ok)throw new Error(await w.text());const x=i.filter(k=>k.id!==y),E=new Set(o);E.delete(y),s(x),l(E),n&&n(x.filter(k=>E.has(k.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent("labels:refresh"))}finally{d(!1)}}}const g=h.jsx("div",{className:"image-dialog-backdrop",onPointerDown:y=>{y.target===y.currentTarget&&(y.preventDefault(),y.stopPropagation(),setTimeout(()=>e(),0))},onClick:y=>{y.target===y.currentTarget&&(y.preventDefault(),y.stopPropagation())},children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,style:{width:360},onPointerDown:y=>{y.stopPropagation()},onMouseDown:y=>{y.stopPropagation()},onClick:y=>{y.stopPropagation()},children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Labels"}),h.jsx("button",{className:"icon-close",onClick:e,children:"✕"})]}),h.jsxs("div",{className:"dialog-body",children:[h.jsxs("div",{style:{display:"flex",gap:8,marginBottom:8},children:[h.jsx("input",{value:a,onChange:y=>c(y.target.value),placeholder:"Create new label",className:"image-url-input"}),h.jsx("button",{className:"btn",onClick:async()=>{const y=a.trim();y&&(await f(y),c(""))},disabled:u,children:"Add"})]}),h.jsx("div",{children:i.length===0?h.jsx("div",{style:{color:"var(--muted)"},children:"No labels yet"}):i.map(y=>{const v=o.has(y.id);return h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 0",justifyContent:"space-between"},children:[h.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[h.jsx("input",{type:"checkbox",checked:v,onChange:async()=>{v?await p(y.id):await f(y.id)}}),h.jsx("span",{children:y.name})]}),h.jsx("button",{className:"tiny",onClick:()=>m(y.id),title:"Delete label","aria-label":"Delete label",style:{color:"var(--danger, #d33)"},children:"✕"})]},y.id)})})]}),h.jsx("div",{className:"dialog-footer",children:h.jsx("button",{className:"btn",onClick:()=>{n&&n(i.filter(y=>o.has(y.id))),e()},children:"Close"})})]})});return typeof document<"u"?zn.createPortal(g,document.body):g}function Fs(t){if(!t)return;const e=t.replace("#",""),n=e.length===3?e.split("").map(m=>m+m).join(""):e;if(n.length!==6)return;const r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,s=parseInt(n.slice(4,6),16)/255,o=m=>m<=.03928?m/12.92:Math.pow((m+.055)/1.055,2.4),l=o(r),a=o(i),c=o(s),u=.2126*l+.7152*a+.0722*c,d=(m,g)=>(Math.max(m,g)+.05)/(Math.min(m,g)+.05),f=d(1,u),p=d(0,u);return f>=p?"#ffffff":"#000000"}function El({note:t,onChange:e,openRequest:n,onOpenRequestHandled:r,dragHandleAttributes:i,dragHandleListeners:s}){var Pr;const o=b.useRef(null),l=b.useRef(null),a=b.useRef(null),c=b.useRef(null),u=b.useRef(null),d=b.useRef(null),f=(()=>{try{return Sb()}catch{return{effective:"dark"}}})(),[p,m]=b.useState(t.viewerColor||t.color||""),[g,y]=b.useState(t.viewerColor||t.color?Fs(t.viewerColor||t.color):void 0),[v,w]=b.useState(!1),[x,E]=b.useState(t.images||[]),[k,M]=b.useState(3),[N,z]=b.useState(t.items||[]),[X,L]=b.useState(t.title||"");B.useEffect(()=>{try{const I=(t.images||[]).map(U=>({id:Number(U.id),url:String(U.url)}));E(I)}catch{}},[t.id,t.images]);function H(I){try{e==null||e({type:"images",noteId:t.id,images:I})}catch{}}function W(I){try{e==null||e({type:"color",noteId:t.id,color:I||""})}catch{}}function te(I){E(U=>{const K=I(U);try{setTimeout(()=>H(K),0)}catch{}return K})}const[ue,de]=b.useState(!1),[Ae,me]=b.useState([]),[q,se]=b.useState(()=>(t.noteLabels||[]).map(I=>I.label).filter(I=>I&&typeof I.id=="number"&&typeof I.name=="string")),[xe,Me]=B.useState(()=>{try{const I=t.viewerCollections;return Array.isArray(I)?I.filter(U=>U&&typeof U.id=="number"&&typeof U.name=="string").map(U=>({id:Number(U.id),name:String(U.name),parentId:U.parentId==null?null:Number(U.parentId)})):[]}catch{return[]}}),[Q,Je]=b.useState(!1),[_t,J]=b.useState(null),[at,$t]=b.useState(!1),[ct,nt]=B.useState(null),[At,Bt]=B.useState({}),[wt,ce]=b.useState(!1),[Ee,Ke]=b.useState(!1),[ze,Pe]=b.useState(!1),[it,ot]=b.useState(!1),[xt,oe]=b.useState(!1),[Ye,Ge]=b.useState(!0),[Y,ge]=B.useState(null),[De,Be]=b.useState(!1);B.useEffect(()=>{try{const I=t.viewerCollections;if(!Array.isArray(I)){Me([]);return}const U=I.filter(K=>K&&typeof K.id=="number"&&typeof K.name=="string").map(K=>({id:Number(K.id),name:String(K.name),parentId:K.parentId==null?null:Number(K.parentId)}));Me(U)}catch{Me([])}},[t.id,t.viewerCollections]);const Le=B.useMemo(()=>{try{const I=window.matchMedia;return!!(I&&(I("(pointer: coarse)").matches||I("(any-pointer: coarse)").matches))}catch{return!1}},[]),j=Le?"center":"flex-start",G=B.useCallback(()=>{t.type==="CHECKLIST"||t.items&&t.items.length?ot(!0):oe(!0)},[t.type,t.items]),fe=B.useRef(0);B.useEffect(()=>{const I=Number(n||0);if(I&&I!==fe.current){fe.current=I,G();try{r&&r(Number(t.id))}catch{}}},[n,G,r,t.id]);const je=B.useCallback(I=>{if(!I)return!1;try{return!!I.closest('button, a, input, textarea, select, [contenteditable="true"], [role="button"], .more-menu, .dropdown, .color-palette')}catch{return!1}},[]),Ue=B.useCallback((I=!1)=>{c.current==null&&(c.current=requestAnimationFrame(()=>{c.current=null;const U=l.current;if(U)try{if(!(U.scrollHeight>U.clientHeight+1)){U.style.maxHeight&&(U.style.maxHeight=""),u.current=null,d.current=null;return}const le=U.style.maxHeight;I&&le&&(U.style.maxHeight="",U.getBoundingClientRect());const $=U.clientHeight;if(!Number.isFinite($)||$<=0){I&&le&&(U.style.maxHeight=le);return}let S=0;const V=N&&N.length>0?U.querySelector(".note-item-text")??U:U,he=parseFloat(getComputedStyle(V).lineHeight||"0");if(Number.isFinite(he)&&he>0&&(S=he),!Number.isFinite(S)||S<12){le&&(U.style.maxHeight=le);return}if(I&&u.current!=null&&d.current!=null&&Math.abs(u.current-S)<.5&&Math.abs(d.current-$)<.5)return;const tt=$%S;if(tt<2||S-tt<2){I&&le&&(U.style.maxHeight=le);return}const Ft=Math.max(S,Math.floor($-tt));U.style.maxHeight=`${Ft}px`,u.current=S,d.current=$}catch{}}))},[N]);B.useEffect(()=>{const I=l.current;if(!I)return;const U=()=>{try{const S=I.scrollHeight>I.clientHeight+1;Be(S)}catch{}},K=requestAnimationFrame(()=>{U(),Ue(!0)});let le=null;try{le=new ResizeObserver(()=>{U(),Ue()}),le.observe(I)}catch{}const $=()=>Ue(!0);return window.addEventListener("notes-grid:recalc",$),window.addEventListener("resize",$),()=>{try{cancelAnimationFrame(K)}catch{}try{le&&le.disconnect()}catch{}try{window.removeEventListener("notes-grid:recalc",$)}catch{}try{window.removeEventListener("resize",$)}catch{}if(c.current!=null){try{cancelAnimationFrame(c.current)}catch{}c.current=null}}},[t.id,X,N.length,Ye,Y,t.body,x.length,q.length,Ue]),B.useEffect(()=>{const I=a.current;if(!I)return;const U=6,K=()=>{try{const S=getComputedStyle(document.documentElement).getPropertyValue("--image-thumb-size")||"",V=Math.max(24,parseInt(String(S).trim(),10)||96),he=I.clientWidth||0,tt=Math.max(1,Math.floor((he+U)/(V+U)));M(tt)}catch{}};K();let le=null;try{le=new ResizeObserver(()=>K()),le.observe(I)}catch{}return window.addEventListener("resize",K),window.addEventListener("notes-grid:recalc",K),()=>{try{le&&le.disconnect()}catch{}window.removeEventListener("resize",K),window.removeEventListener("notes-grid:recalc",K)}},[]);const We=b.useRef(null),{token:Se,user:Xe}=Sr();B.useEffect(()=>{const I=U=>{try{const K=U,le=(K==null?void 0:K.detail)||{};if(le!=null&&le.invalidateAll){Bt({});return}const $=Array.isArray(le==null?void 0:le.ids)?le.ids:Number.isFinite(Number(le==null?void 0:le.id))?[Number(le.id)]:[];if(!$.length)return;Bt(S=>{const V={...S};for(const he of $)try{delete V[Number(he)]}catch{}return V})}catch{}};try{window.addEventListener("collections:changed",I)}catch{}return()=>{try{window.removeEventListener("collections:changed",I)}catch{}}},[]);const Tt=B.useMemo(()=>{try{const I=xe.map(U=>Number(U.id)).filter(U=>Number.isFinite(U));return ct!=="collections"?"":I.join(",")}catch{return""}},[xe,ct]);B.useEffect(()=>{if(!Se||!xe.length)return;const I=Tt?Tt.split(",").map(le=>Number(le)).filter(le=>Number.isFinite(le)):[];if(!I.length)return;let U=!1;const K=new AbortController;return(async()=>{try{const le=I.filter(V=>!At[V]);if(!le.length)return;const $=await Promise.all(le.map(async V=>{var he,tt;try{const Ft=await fetch(`/api/collections/${V}/breadcrumb`,{headers:{Authorization:Se?`Bearer ${Se}`:""},signal:K.signal});if(!Ft.ok)throw new Error(await Ft.text());const Kt=await Ft.json(),sn=(Array.isArray(Kt==null?void 0:Kt.breadcrumb)?Kt.breadcrumb:[]).map(A=>String((A==null?void 0:A.name)||"")).filter(Boolean).join(" / ");return[V,sn||((he=xe.find(A=>Number(A.id)===V))==null?void 0:he.name)||String(V)]}catch{return[V,((tt=xe.find(Ft=>Number(Ft.id)===V))==null?void 0:tt.name)||String(V)]}}));if(U)return;const S={};for(const[V,he]of $)S[Number(V)]=String(he||"");Bt(V=>({...V,...S}))}catch{}})(),()=>{U=!0;try{K.abort()}catch{}}},[Se,xe,Tt,At]);const rt=B.useMemo(()=>new Fi,[t.id]),Wt=B.useRef(null),Mt=B.useRef(null);B.useEffect(()=>{const I=`note-${t.id}`,K=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/collab`,le=new mf(K,I,rt);Wt.current=le;const $=rt.getArray("checklist");Mt.current=$;const S=()=>{try{if($.length===0)return;const V=$.toArray().map(he=>({id:typeof he.get("id")=="number"?Number(he.get("id")):void 0,content:String(he.get("content")||""),checked:!!he.get("checked"),indent:Number(he.get("indent")||0)}));z(V)}catch{}};return $.observeDeep(S),le.on("sync",V=>{V&&S()}),()=>{try{$.unobserveDeep(S)}catch{}try{le.destroy()}catch{}}},[t.id,rt]),B.useEffect(()=>{if(t.type!=="TEXT"){ge(null);return}let I=null;try{I=new ag({extensions:[ta.configure({heading:{levels:[1,2,3]}}),wR.configure({openOnClick:!1,autolink:!0}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:rt})],content:""});const U=()=>{try{const $=(I==null?void 0:I.getHTML())||"",S=ka.sanitize($,{USE_PROFILES:{html:!0}});ge(S)}catch{}};I.on("update",U);const K=Wt.current,le=$=>{$&&U()};return K==null||K.on("sync",le),()=>{try{I==null||I.destroy()}catch{}try{K==null||K.off("sync",le)}catch{}}}catch{}},[t.id,t.type,rt]);function dn(){const I=t.body||"",U=$=>$.replace(/&/g,"&").replace(//g,">"),K=($,S)=>!S||!S.length?U($):S.reduce((V,he)=>{var tt;switch(he.type){case"bold":return`${V}`;case"italic":return`${V}`;case"underline":return`${V}`;case"link":{const Ft=typeof((tt=he.attrs)==null?void 0:tt.href)=="string"?he.attrs.href:"#";return`${V}`}default:return V}},U($)),le=($,S=!1)=>{var tt;if(!$)return"";if(Array.isArray($))return $.map(Ft=>le(Ft,S)).join("");const V=$.type;if(V==="text")return K($.text||"",$.marks);if(V==="hardBreak")return"
    ";if((V==="paragraph"||V==="heading")&&(!$.content||$.content.length===0))return S?"":"

    ";const he=$.content?le($.content,V==="listItem"):"";switch(V){case"paragraph":return`

    ${he}

    `;case"heading":{const Ft=Math.min(6,Math.max(1,Number(((tt=$.attrs)==null?void 0:tt.level)||1)));return`${he}`}case"bulletList":return`
      ${he}
    `;case"orderedList":return`
      ${he}
    `;case"listItem":return`
  • ${he.replace(/^

    |<\/p>$/g,"")}

  • `;case"blockquote":return`
    ${he}
    `;case"codeBlock":return`
    ${U($.textContent||"")}
    `;default:return he}};try{const $=JSON.parse(I),S=le($);return ka.sanitize(S,{USE_PROFILES:{html:!0}})}catch{const $=U(I).replace(/\n/g,"
    ");return ka.sanitize(`

    ${$}

    `)}}B.useEffect(()=>{const I=t.viewerColor||t.color||"";m(I||""),y(I?Fs(I):void 0)},[t.id,t.viewerColor,t.color]),B.useEffect(()=>{se((t.noteLabels||[]).map(I=>I.label).filter(I=>I&&typeof I.id=="number"&&typeof I.name=="string"))},[t.noteLabels]),B.useEffect(()=>{L(t.title||"")},[t.title]),B.useEffect(()=>{E((t.images||[]).map(I=>({id:Number(I.id),url:String(I.url)})))},[t.images]),B.useEffect(()=>{try{const I=(t.collaborators||[]).map(U=>{const K=U&&(U.user||{});if(K&&typeof K.id=="number"&&typeof K.email=="string"){const le=typeof K.userImageUrl=="string"?String(K.userImageUrl):typeof U.userImageUrl=="string"?String(U.userImageUrl):void 0;return{collabId:Number(U.id),userId:Number(K.id),email:String(K.email),name:typeof K.name=="string"?String(K.name):void 0,userImageUrl:le}}return null}).filter(Boolean);me(I)}catch{}},[t.collaborators]),B.useRef(null),B.useRef(!1);async function It(I){const U=I||"";try{const K=await fetch(`/api/notes/${t.id}/prefs`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({color:U})});if(!K.ok)throw new Error(await K.text())}catch(K){console.error("Failed to save color preference",K),window.alert("Failed to save color preference")}U?(m(U),y(Fs(U))):(m(""),y("var(--muted)"));try{W(U)}catch{}ce(!1)}function Ot(I){Ke(!1),I&&(async()=>{try{const U=await fetch(`/api/notes/${t.id}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({url:I})});if(!U.ok)throw new Error(await U.text());const le=(await U.json()).image||null;le&&le.id&&le.url&&te($=>$.some(V=>Number(V.id)===Number(le.id))?$:[...$,{id:Number(le.id),url:String(le.url)}])}catch(U){console.error("Failed to attach image",U),te(K=>K.some($=>String($.url)===String(I))?K:[...K,{id:Date.now(),url:I}]),window.alert("Failed to attach image to server; showing locally")}})()}async function tn(I,U){const K=Mt.current;if(K){const le=K.toArray().findIndex($=>typeof $.get("id")=="number"?Number($.get("id"))===I:!1);if(le>=0){const $=K.get(le);if($.set("checked",U),Number($.get("indent")||0)===0)for(let V=le+1;V0)he.set("checked",U);else break}return}}try{const le=await fetch(`/api/notes/${t.id}/items/${I}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se}`},body:JSON.stringify({checked:U})});if(!le.ok)throw new Error(await le.text());z($=>$.map(S=>S.id===I?{...S,checked:U}:S))}catch(le){console.error(le),window.alert("Failed to update checklist item — please try again.")}}function ee(I){Pe(!1),I&&window.alert(`Reminder set (UI-only): ${I}`)}function re(){const I=!v;w(I),fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({archived:I})}).then(()=>e&&e()).catch(U=>{console.error(U),window.alert("Failed to archive note")})}async function Oe(){var I;try{const U=typeof((I=t.owner)==null?void 0:I.id)=="number"?Number(t.owner.id):void 0,K=Xe&&Xe.id?Number(Xe.id):void 0;if(U&&K&&U!==K){const $=Ae.find(S=>typeof S.userId=="number"&&S.userId===K);if($&&typeof $.collabId=="number"){const S=await fetch(`/api/notes/${t.id}/collaborators/${$.collabId}`,{method:"DELETE",headers:{Authorization:Se?`Bearer ${Se}`:""}});if(!S.ok)throw new Error(await S.text());e&&e();return}window.alert("You are not the owner and could not find your collaborator entry to remove.");return}const le=await fetch(`/api/notes/${t.id}`,{method:"DELETE",headers:{Authorization:Se?`Bearer ${Se}`:""}});if(!le.ok)throw new Error(await le.text());e&&e()}catch(U){console.error(U),window.alert("Failed to delete or leave note")}}const[Ze,pe]=b.useState(!1);function Ce(){pe(!0)}async function Fe(){try{const I=(N||[]).map((K,le)=>({id:K.id,content:K.content,checked:!1,ord:typeof K.ord=="number"?K.ord:le,indent:typeof K.indent=="number"?K.indent:0}));z(I);const U=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({items:I})});if(!U.ok)throw new Error(await U.text())}catch(I){console.error(I),window.alert("Failed to uncheck all items")}}async function ut(){try{const I=(N||[]).map((K,le)=>({id:K.id,content:K.content,checked:!0,ord:typeof K.ord=="number"?K.ord:le,indent:typeof K.indent=="number"?K.indent:0}));z(I);const U=await fetch(`/api/notes/${t.id}/items`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({items:I})});if(!U.ok)throw new Error(await U.text())}catch(I){console.error(I),window.alert("Failed to check all items")}}function zt(I){me(U=>U.find(K=>K.userId===I.id)?U:[...U,{userId:I.id,email:I.email,name:I.name,userImageUrl:I.userImageUrl}]),de(!1),(async()=>{try{const U=await fetch(`/api/notes/${t.id}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({email:I.email})});if(!U.ok)throw new Error(await U.text());const K=await U.json(),le=K&&(K.collaborator||null);le&&typeof le.id=="number"&&me($=>$.map(S=>S.userId===I.id?{...S,collabId:Number(le.id)}:S))}catch(U){console.error("Failed to add collaborator",U),window.alert("Failed to add collaborator"),me(K=>K.filter(le=>le.userId!==I.id))}})()}async function kt(I){try{const U=await fetch(`/api/notes/${t.id}/collaborators/${I}`,{method:"DELETE",headers:{Authorization:Se?`Bearer ${Se}`:""}});if(!U.ok)throw new Error(await U.text());me(K=>K.filter(le=>le.collabId!==I)),e&&e()}catch(U){console.error("Failed to remove collaborator",U),window.alert("Failed to remove collaborator")}}async function Jt(I){try{const U=await fetch(`/api/notes/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:Se?`Bearer ${Se}`:""},body:JSON.stringify({cardSpan:I})});if(!U.ok)throw new Error(await U.text());try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}e&&e()}catch(U){console.error("Failed to set card width",U),window.alert("Failed to set card width")}}const jt=(()=>{const I=(p||"").toLowerCase().trim(),U=new Set(["#1e1e1e","#121212","#181818","#1c1c1c","#161616"]),K=new Set(["#ffffff","#fff"]);return f.effective==="light"&&U.has(I)||f.effective==="dark"&&K.has(I)?"":p})(),fn=jt?Fs(jt):void 0,wn=fn==="#ffffff"||fn==="var(--muted)"?"rgba(0,0,0,0.12)":"rgba(255,255,255,0.06)",nn=[];try{const I=Xe&&Xe.id?Number(Xe.id):void 0,U=t.owner||null;if(U&&typeof U.id=="number"&&U.id!==I){const K=typeof U.name=="string"&&U.name?U.name:String(U.email||"").split("@")[0];nn.push({key:`owner-${U.id}`,userId:Number(U.id),name:K,email:String(U.email||""),userImageUrl:typeof U.userImageUrl=="string"?String(U.userImageUrl):void 0})}for(const K of Ae)if(typeof K.userId=="number"&&K.userId!==I){const le=K.name&&K.name.length?K.name:String(K.email).split("@")[0];nn.push({key:K.collabId||`u-${K.userId}`,userId:Number(K.userId),name:le,email:K.email,userImageUrl:K.userImageUrl})}}catch{}const rn={background:jt||void 0,color:fn||void 0,opacity:v?.6:1,position:"relative","--chip-bg":wn};return jt&&(rn["--checkbox-bg"]=jt,rn["--checkbox-border"]=Fs(jt),rn["--checkbox-stroke"]=Fs(jt),rn["--checkbox-checked-bg"]=jt,rn["--checkbox-checked-mark"]=Fs(jt)),h.jsxs("article",{ref:I=>{o.current=I},className:`note-card${q.length>0?" has-labels":""}${xe.length>0?" has-collections":""}${N&&N.length>0?" has-checklist":""}`,style:rn,...X?{}:i||{},...X?{}:(()=>{const I=s||{},{onKeyDown:U,...K}=I;return K})(),"data-clipped":De?"1":void 0,onClick:I=>{const U=I.target;je(U)||G()},children:[h.jsx("input",{ref:We,type:"file",accept:"image/*",style:{display:"none"}}),X&&h.jsx("div",{className:"note-title",...i||{},...(()=>{const I=s||{},{onKeyDown:U,...K}=I;return K})(),style:{cursor:"pointer"},onClick:()=>{G()},role:"button",tabIndex:0,onKeyDown:I=>{try{const U=s==null?void 0:s.onKeyDown;typeof U=="function"&&U(I)}catch{}I.defaultPrevented||(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),G())},children:X}),(()=>{if(!(nn.length>0||q.length>0||xe.length>0))return null;const U=`note-meta-panel-${Number(t.id)}`,K=xe.map($=>({...$,path:At[Number($.id)]||String($.name||"")})).sort(($,S)=>String($.path).localeCompare(String(S.path))),le=()=>{Le||nt(null)};return h.jsxs("div",{className:`note-meta${ct?" is-expanded":""}`,onPointerDown:$=>{$.stopPropagation()},onClick:$=>{$.stopPropagation()},onMouseLeave:le,onBlurCapture:$=>{const S=$.relatedTarget;S&&$.currentTarget.contains(S)||nt(null)},children:[h.jsxs("div",{className:"note-meta-bar",children:[nn.length>0&&h.jsxs("button",{type:"button",className:`chip chip--meta${ct==="collab"?" is-active":""}`,"aria-expanded":ct==="collab","aria-controls":U,title:"Collaborators",onMouseEnter:()=>{Le||nt("collab")},onFocus:$=>{var S,V;try{if(!((V=(S=$.currentTarget)==null?void 0:S.matches)==null?void 0:V.call(S,":focus-visible")))return}catch{}nt("collab")},onClick:$=>{$.stopPropagation(),nt(S=>S==="collab"?null:"collab")},children:[h.jsx(Xs,{icon:c9,className:"meta-fa-icon"}),h.jsx("span",{children:nn.length})]}),q.length>0&&h.jsxs("button",{type:"button",className:`chip chip--meta${ct==="labels"?" is-active":""}`,"aria-expanded":ct==="labels","aria-controls":U,title:"Labels",onMouseEnter:()=>{Le||nt("labels")},onFocus:$=>{var S,V;try{if(!((V=(S=$.currentTarget)==null?void 0:S.matches)==null?void 0:V.call(S,":focus-visible")))return}catch{}nt("labels")},onClick:$=>{$.stopPropagation(),nt(S=>S==="labels"?null:"labels")},children:[h.jsx(Xs,{icon:d9,className:"meta-fa-icon"}),h.jsx("span",{children:q.length})]}),xe.length>0&&h.jsxs("button",{type:"button",className:`chip chip--meta chip--meta-collections${ct==="collections"?" is-active":""}`,"aria-expanded":ct==="collections","aria-controls":U,title:`${xe.length} collections`,onMouseEnter:()=>{Le||nt("collections")},onFocus:$=>{var S,V;try{if(!((V=(S=$.currentTarget)==null?void 0:S.matches)==null?void 0:V.call(S,":focus-visible")))return}catch{}nt("collections")},onClick:$=>{$.stopPropagation(),nt(S=>S==="collections"?null:"collections")},children:[h.jsx(Xs,{icon:u9,className:"meta-fa-icon"}),h.jsx("span",{children:xe.length})]})]}),h.jsxs("div",{id:U,className:`note-meta-panel${ct?" is-open":""}`,role:"region","aria-label":"Note metadata",children:[ct==="collab"&&h.jsx("div",{className:"collab-chips","aria-label":"Collaborators",children:nn.map($=>{const S=(Xe==null?void 0:Xe.chipDisplayMode)||"image+text",V=(S==="image"||S==="image+text")&&!!$.userImageUrl,he=S==="text"||S==="image+text";return h.jsxs("button",{type:"button",className:"chip",title:$.email,style:{display:"inline-flex",alignItems:"center",gap:6},onClick:tt=>{tt.stopPropagation();try{e==null||e({type:"filter:collaborator",noteId:Number(t.id),userId:Number($.userId),name:String($.name||"")})}catch{}},children:[V?h.jsx("img",{src:$.userImageUrl,alt:"",style:{width:18,height:18,borderRadius:"50%",objectFit:"cover"}}):null,he?h.jsx("span",{children:$.name}):null]},$.key)})}),ct==="labels"&&h.jsx("div",{className:"label-chips","aria-label":"Labels",children:q.map($=>h.jsx("button",{type:"button",className:"chip",onClick:S=>{S.stopPropagation();try{e==null||e({type:"filter:labels",noteId:Number(t.id),labelId:Number($.id),labelName:String($.name||"")})}catch{}},children:$.name},$.id))}),ct==="collections"&&h.jsx("div",{className:"note-collections","aria-label":"Collections",children:h.jsx("div",{className:"note-collections-list",role:"list",children:K.map($=>h.jsx("button",{type:"button",className:"chip note-collection-chip",title:$.path,onClick:S=>{S.stopPropagation();try{e==null||e({type:"filter:collection",noteId:Number(t.id),collectionId:Number($.id),collectionName:String($.name||"")})}catch{}},children:$.path},$.id))})})]})]})})(),h.jsx("div",{className:"note-body",ref:l,onClick:()=>{G()},children:N&&N.length>0?h.jsxs("div",{children:[h.jsx("div",{className:"note-items-list",children:N.filter(I=>!I.checked).map((I,U)=>h.jsxs("div",{className:"note-item",style:{display:"flex",gap:8,alignItems:j,marginLeft:(I.indent||0)*16},children:[h.jsx("button",{className:`note-checkbox ${I.checked?"checked":""}`,type:"button",onClick:K=>{K.stopPropagation(),tn(I.id,!I.checked)},"aria-pressed":!!I.checked,style:{background:"var(--checkbox-bg)",border:"2px solid var(--checkbox-border)",color:"var(--checkbox-stroke)"},children:I.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{className:"note-item-text",children:h.jsx("div",{className:"rt-html",dangerouslySetInnerHTML:{__html:ka.sanitize(String(I.content||""),{USE_PROFILES:{html:!0}})}})})]},typeof I.id=="number"?I.id:`i-${U}`))}),N.some(I=>I.checked)&&h.jsx("div",{style:{marginTop:6},children:h.jsx("button",{className:"btn completed-toggle",onClick:I=>{I.stopPropagation(),Ge(U=>!U)},"aria-expanded":Ye,"aria-controls":`completed-${t.id}`,children:h.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[h.jsx("span",{style:{transform:Ye?"rotate(90deg)":"rotate(0deg)",display:"inline-block"},children:"▸"}),h.jsxs("span",{children:[N.filter(I=>I.checked).length," completed items"]})]})})}),Ye&&N.some(I=>I.checked)&&h.jsx("div",{className:"note-items-list",style:{marginTop:6},children:N.filter(I=>I.checked).map((I,U)=>h.jsxs("div",{className:"note-item completed",style:{display:"flex",gap:8,alignItems:j,marginLeft:(I.indent||0)*16,opacity:.7},children:[h.jsx("button",{className:`note-checkbox ${I.checked?"checked":""}`,type:"button",onClick:K=>{K.stopPropagation(),tn(I.id,!I.checked)},"aria-pressed":!!I.checked,style:{background:"var(--checkbox-bg)",border:"2px solid var(--checkbox-border)",color:"var(--checkbox-stroke)"},children:I.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{className:"note-item-text",style:{textDecoration:"line-through"},children:h.jsx("div",{className:"rt-html",dangerouslySetInnerHTML:{__html:ka.sanitize(String(I.content||""),{USE_PROFILES:{html:!0}})}})})]},`c-${typeof I.id=="number"?I.id:U}`))})]}):Y||t.body?h.jsx("div",{className:"note-html",dangerouslySetInnerHTML:{__html:Y||dn()}}):null}),x&&x.length>0&&h.jsx("div",{className:"note-images",ref:a,children:(()=>{const I=Math.max(1,k)*3,U=x.slice(0,Math.min(x.length,I)),K=Math.max(0,x.length-I);return U.map((le,$)=>h.jsxs("button",{className:"note-image",style:{padding:0,border:"none",background:"transparent",cursor:"pointer"},onClick:()=>{G()},children:[h.jsx("img",{src:le.url,alt:"note image"}),K>0&&$===U.length-1&&h.jsxs("span",{className:"note-image-moreOverlay","aria-label":`${K} more images`,children:["+",K," more"]})]},le.id))})()}),h.jsx("div",{className:"footer-hover-zone","aria-hidden":!0}),h.jsx("div",{className:"note-footer","aria-hidden":!1,children:h.jsxs("div",{className:"note-actions",children:[h.jsx("button",{className:"tiny palette",onClick:()=>ce(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>Pe(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>de(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Ke(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),h.jsx("button",{className:"tiny",onClick:re,"aria-label":"Archive",title:"Archive",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M20.54 5.23L19.4 4H4.6L3.46 5.23 3 6v2h18V6l-.46-.77zM6 10v9h12V10H6zm3 2h6v2H9v-2z"})})}),h.jsx("button",{className:"tiny",onClick:I=>{I.stopPropagation(),J({x:I.clientX,y:I.clientY}),Je(U=>!U)},"aria-label":"More",title:"More",children:"⋮"})]})}),Q&&h.jsx(Hx,{anchorRef:o,anchorPoint:_t,itemsCount:5,onClose:()=>Je(!1),onDelete:Oe,onMoveToCollection:()=>$t(!0),onAddLabel:Ce,onUncheckAll:Fe,onCheckAll:ut,onSetWidth:Jt}),at&&h.jsx(BJ,{noteId:Number(t.id),onClose:()=>$t(!1),onChanged:I=>{try{const U=Array.isArray(I)?I.map(K=>({id:Number(K.id),name:String(K.name||""),parentId:K.parentId==null?null:Number(K.parentId)})).filter(K=>Number.isFinite(K.id)&&K.name.length):[];Me(U)}catch{}try{e==null||e({type:"collections",noteId:Number(t.id),collections:I})}catch{}}}),Ze&&h.jsx(UJ,{noteId:t.id,onClose:()=>pe(!1),onUpdated:I=>{se(I);try{e==null||e({type:"labels",noteId:t.id,labels:I})}catch{}}}),ue&&h.jsx(xc,{onClose:()=>de(!1),onSelect:zt,current:(()=>{const I=[],U=Xe&&Xe.id?Number(Xe.id):void 0,K=t.owner||null;K&&typeof K.id=="number"&&K.id!==U&&I.push({userId:Number(K.id),email:String(K.email||""),name:typeof K.name=="string"?K.name:void 0,userImageUrl:typeof K.userImageUrl=="string"?String(K.userImageUrl):void 0});for(const le of Ae)typeof le.userId=="number"&&I.push({collabId:le.collabId,userId:le.userId,email:le.email,name:le.name,userImageUrl:le.userImageUrl});return I})(),ownerId:typeof((Pr=t.owner)==null?void 0:Pr.id)=="number"?Number(t.owner.id):Xe==null?void 0:Xe.id,onRemove:kt}),wt&&h.jsx(ef,{anchorRef:o,onPick:It,onClose:()=>ce(!1)}),Ee&&h.jsx(nf,{onClose:()=>Ke(!1),onAdd:Ot}),ze&&h.jsx(tf,{onClose:()=>Pe(!1),onSet:ee}),it&&h.jsx(Xq,{note:{...t,items:N,images:x},noteBg:p,onColorChanged:I=>{try{const U=String(I||"");m(U),y(U?Fs(U):"var(--muted)"),W(U)}catch{}},onClose:()=>ot(!1),onSaved:({items:I,title:U})=>{z(I),L(U)},onImagesUpdated:I=>{te(()=>I)},moreMenu:{onDelete:Oe,onAddLabel:Ce,onMoveToCollection:()=>$t(!0),onUncheckAll:Fe,onCheckAll:ut,onSetWidth:Jt}}),xt&&h.jsx(FJ,{note:{...t,images:x},noteBg:p,onColorChanged:I=>{try{const U=String(I||"");m(U),y(U?Fs(U):"var(--muted)"),W(U)}catch{}},onClose:()=>oe(!1),onSaved:({title:I,body:U})=>{L(I),t.body=U},onImagesUpdated:I=>{te(()=>I)},moreMenu:{onDelete:Oe,onAddLabel:Ce,onMoveToCollection:()=>$t(!0),onSetWidth:Jt}})]})}function Nj(t){if(/^wss?:\/\//i.test(t))return t;const e=t.startsWith("/")?t:`/${t}`;return typeof window>"u"||!window.location?`ws://localhost${e}`:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}${e}`}function HJ({onCreated:t,openRequest:e,activeCollection:n}){const{token:r,user:i}=Sr(),[s,o]=b.useState(!1),[l,a]=b.useState("text"),[c,u]=b.useState(""),[d,f]=b.useState(""),[p,m]=b.useState(!1),g=pg({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),yg,mn.create({name:"paragraphEnterFix",priority:1e3,addKeyboardShortcuts(){return{"Shift-Enter":()=>{const j=this.editor;return j.commands.splitBlock(),j.commands.setParagraph(),!0},"Mod-Enter":()=>{const j=this.editor;return j.commands.splitBlock(),j.commands.setParagraph(),!0}}}})],content:"",editorProps:{attributes:{class:"rt-editor"}}});function y(){try{const j=window.matchMedia;if(!j)return!1;const G=j("(pointer: coarse)").matches||j("(any-pointer: coarse)").matches,fe=j("(max-width: 720px)").matches;return!!(G&&fe)}catch{return!1}}const v=b.useRef("");if(!v.current)try{v.current=`take-note-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{v.current=`take-note-${Math.random()}`}function w(j){if(!g)return;const G=g.state.selection;if(!G||!G.empty){g.chain().focus()[`toggle${j.charAt(0).toUpperCase()+j.slice(1)}`]().run();return}const fe=G.$from;let je=fe.depth;for(;je>0&&!fe.node(je).isBlock;)je--;const Ue=fe.start(je),We=fe.end(je),Se=g.chain().focus().setTextSelection({from:Ue,to:We});j==="bold"?Se.toggleBold().run():j==="italic"?Se.toggleItalic().run():Se.toggleUnderline().run();try{g.chain().setTextSelection(G.from).run()}catch{}}const[,x]=b.useState(0);b.useEffect(()=>{if(!g)return;const j=()=>x(G=>G+1);return g.on("selectionUpdate",j),g.on("transaction",j),()=>{g.off("selectionUpdate",j),g.off("transaction",j)}},[g]);const E=b.useRef(!1),k=b.useRef(0),M=n&&Number.isFinite(Number(n.id))?Number(n.id):null,N=n&&typeof n.path=="string"?String(n.path):"",[z,X]=b.useState(!1);b.useEffect(()=>{const j=Number((e==null?void 0:e.nonce)||0);if(!j||j===k.current)return;k.current=j;const G=(e==null?void 0:e.mode)||"text";a(G);try{E.current=!0}catch{}try{X(M!=null)}catch{}o(!0),m(y()),G==="checklist"?(W(fe=>fe&&fe.length?fe:[{content:""}]),setTimeout(()=>De(0),30)):requestAnimationFrame(()=>{try{g==null||g.commands.focus("end")}catch{}})},[e==null?void 0:e.nonce,e==null?void 0:e.mode,g]);const L=b.useRef(!1);b.useEffect(()=>{try{s&&!L.current&&(L.current=!0,window.dispatchEvent(new Event("freemannotes:editor-modal-open"))),!s&&L.current&&(L.current=!1,window.dispatchEvent(new Event("freemannotes:editor-modal-close")))}catch{}},[s]),b.useEffect(()=>{if(!s)return;const j=v.current,G=()=>{try{const fe=Pe.current;if(fe.showImageDialog){wt(!1);return}if(fe.showCollaborator){At(!1);return}if(fe.showReminderPicker){ct(!1);return}if(fe.showPalette){at(!1);return}}catch{}try{Ye()}catch{try{Ye()}catch{}}};try{window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:j,onBack:G}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:j}}))}catch{}}},[s]);const[H,W]=b.useState([]),[te,ue]=b.useState(!1),de=b.useRef(null),Ae=b.useRef(null),me=b.useRef(null),q=b.useRef([]),[,se]=b.useState(0),xe=b.useRef(!1),[Me,Q]=b.useState(""),[Je,_t]=b.useState(void 0),[J,at]=b.useState(!1),[$t,ct]=b.useState(!1),[nt,At]=b.useState(!1),[Bt,wt]=b.useState(!1),[ce,Ee]=b.useState(null),[Ke,ze]=b.useState([]),Pe=b.useRef({showPalette:!1,showReminderPicker:!1,showCollaborator:!1,showImageDialog:!1});b.useEffect(()=>{Pe.current={showPalette:J,showReminderPicker:$t,showCollaborator:nt,showImageDialog:Bt}},[J,$t,nt,Bt]);function it(){var fe;let j=me.current;if(j&&j.isFocused)return j;const G=typeof document<"u"&&((fe=document.getSelection())==null?void 0:fe.anchorNode)||null;if(G){const je=q.current.find(Ue=>{var We;try{return!!(Ue&&((We=Ue.view)!=null&&We.dom)&&Ue.view.dom.contains(G))}catch{return!1}});je&&(j=je)}else{const je=typeof document<"u"?document.activeElement:null;if(je){const Ue=q.current.find(We=>{try{return!!(We&&We.view&&We.view.dom&&(We.view.dom===je||We.view.dom.contains(je)))}catch{return!1}});Ue&&(j=Ue)}}if(!j||!(j!=null&&j.isFocused)){const je=q.current.find(Ue=>!!(Ue&&Ue.isFocused));je&&(j=je)}return j||null}function ot(j){var Tt;const G=it();if(!G)return;const fe=(Tt=G.state)==null?void 0:Tt.selection;if(!fe||!fe.empty){const rt=G.chain().focus();j==="bold"?rt.toggleBold().run():j==="italic"?rt.toggleItalic().run():rt.toggleUnderline().run();try{const Wt=fe==null?void 0:fe.from;requestAnimationFrame(()=>{try{const Mt=G.chain().focus();typeof Wt=="number"&&Mt.setTextSelection(Wt),Mt.run()}catch{}})}catch{}return}const je=fe.$from;let Ue=je.depth;for(;Ue>0&&!je.node(Ue).isBlock;)Ue--;const We=je.start(Ue),Se=je.end(Ue),Xe=G.chain().focus().setTextSelection({from:We,to:Se});j==="bold"?Xe.toggleBold().run():j==="italic"?Xe.toggleItalic().run():Xe.toggleUnderline().run();try{G.chain().focus().setTextSelection(fe.from).run()}catch{}try{const rt=fe.from;requestAnimationFrame(()=>{var Wt,Mt;try{try{(Mt=(Wt=G.view)==null?void 0:Wt.focus)==null||Mt.call(Wt)}catch{}G.chain().focus().setTextSelection(rt).run()}catch{}})}catch{}try{se(rt=>rt+1)}catch{}}function xt(j){var Wt,Mt;const G=it();if(!G)return!1;const fe=(Wt=G.state)==null?void 0:Wt.selection;if(!fe)return!1;const je=(((Mt=G.schema)==null?void 0:Mt.marks)||{})[j];if(!je)return!1;const Ue=fe.$from;let We=Ue.depth;for(;We>0&&!Ue.node(We).isBlock;)We--;const Se=Ue.start(We),Xe=Ue.end(We);let Tt=!1,rt=!0;try{G.state.doc.nodesBetween(Se,Xe,dn=>{dn&&dn.isText&&(Tt=!0,je.isInSet(dn.marks)||(rt=!1))})}catch{}return Tt&&rt}function oe(){try{const j=!!c.trim(),G=!!Me,fe=!!(ce||Ke&&Ke.length);if(l==="checklist"){const Ue=(H||[]).some(We=>!!String(We.content||"").trim()||!!We.checked);return j||G||fe||Ue}const je=!!((g==null?void 0:g.getText())||"").trim();return j||G||fe||je}catch{return!1}}function Ye(){try{o(!1)}catch{}try{m(!1)}catch{}try{at(!1)}catch{}try{ct(!1)}catch{}try{At(!1)}catch{}try{wt(!1)}catch{}try{u(""),f(""),W([]),Q(""),Ee(null),ze([])}catch{}try{g==null||g.commands.clearContent()}catch{}}b.useEffect(()=>{function j(fe){var rt,Wt,Mt,dn,It;if(!s)return;if(E.current){E.current=!1;return}if(fe.defaultPrevented)return;const je=de.current;if(!je)return;const Ue=fe.target,We=(rt=document.querySelector(".palette-popover"))==null?void 0:rt.contains(Ue),Se=(Wt=document.querySelector(".reminder-popover"))==null?void 0:Wt.contains(Ue),Xe=(Mt=document.querySelector(".collab-modal"))==null?void 0:Mt.contains(Ue),Tt=(dn=document.querySelector(".image-dialog"))==null?void 0:dn.contains(Ue);if(!(We||Se||Xe||Tt)){try{if((((It=fe.composedPath)==null?void 0:It.call(fe))||[]).includes(je))return}catch{}fe.target instanceof Node&&je.contains(fe.target)||Ye()}}function G(fe){s&&fe.key==="Escape"&&Ye()}return document.addEventListener("click",j),document.addEventListener("keydown",G),()=>{document.removeEventListener("click",j),document.removeEventListener("keydown",G)}},[s]);function Ge(j){if(!j)return;const G=j.replace("#",""),fe=G.length===3?G.split("").map(Ot=>Ot+Ot).join(""):G;if(fe.length!==6)return;const je=parseInt(fe.slice(0,2),16)/255,Ue=parseInt(fe.slice(2,4),16)/255,We=parseInt(fe.slice(4,6),16)/255,Se=Ot=>Ot<=.03928?Ot/12.92:Math.pow((Ot+.055)/1.055,2.4),Xe=Se(je),Tt=Se(Ue),rt=Se(We),Wt=.2126*Xe+.7152*Tt+.0722*rt,Mt=(Ot,tn)=>(Math.max(Ot,tn)+.05)/(Math.min(Ot,tn)+.05),dn=Mt(1,Wt),It=Mt(0,Wt);return dn>=It?"#ffffff":"#000000"}b.useEffect(()=>{_t(Me?Ge(Me):"var(--muted)")},[Me]);function Y(j,G){W(fe=>fe.map((je,Ue)=>Ue===j?{...je,content:G}:je))}function ge(j){W(G=>G.map((fe,je)=>je===j?{...fe,checked:!fe.checked}:fe))}function De(j){setTimeout(()=>{const G=q.current[j];try{G&&G.chain().focus().run()}catch{}},30)}async function Be(){var j;ue(!0);try{if(!r)throw new Error("Not authenticated");const G=l==="text"?(g==null?void 0:g.getJSON())||{}:{},fe={title:c,body:null,type:l==="checklist"?"CHECKLIST":"TEXT",color:Me||null};l==="checklist"&&(fe.items=H.map((Se,Xe)=>({content:Se.content,ord:Xe})));const je=await fetch("/api/notes",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(fe)});if(!je.ok)throw new Error(await je.text());const Ue=await je.json(),We=(j=Ue==null?void 0:Ue.note)==null?void 0:j.id;if(We&&z&&M!=null)try{const Se=await fetch(`/api/notes/${We}/collections`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({collectionId:M})});if(!Se.ok)throw new Error(await Se.text())}catch(Se){console.warn("Created note but failed to add to collection",Se);try{window.alert("Note created, but failed to add it to the current collection.")}catch{}}if(We&&l==="text")try{const Se=new Fi,Xe=`note-${We}`,Tt=new mf(Nj("/collab"),Xe,Se),rt=new ag({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:Se})],content:""});await new Promise(Wt=>{Tt.on("sync",Mt=>{Mt&&Wt()})});try{rt==null||rt.commands.setContent(G)}catch{}await new Promise(Wt=>setTimeout(Wt,100));try{rt==null||rt.destroy()}catch{}try{Tt.destroy()}catch{}try{Se.destroy()}catch{}try{await fetch(`/api/notes/${We}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({body:JSON.stringify(G),type:"TEXT"})})}catch{}}catch(Se){console.warn("Failed to seed Yjs content for new note",Se)}if(We&&Ke.length)for(const Se of Ke)try{await fetch(`/api/notes/${We}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({email:Se.email})})}catch{}if(We&&ce)try{await fetch(`/api/notes/${We}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({url:ce})})}catch{}u(""),f(""),W([]),o(!1),Q(""),Ee(null),ze([]);try{X(M!=null)}catch{}g==null||g.commands.clearContent(),t&&t()}catch(G){console.error("Failed to create note",G),window.alert("Failed to create note")}finally{ue(!1)}}if(!s)return h.jsx("div",{ref:de,children:h.jsxs("div",{className:"take-note-bar",role:"button",tabIndex:0,onMouseDown:j=>{try{j.preventDefault()}catch{}try{j.stopPropagation()}catch{}E.current=!0;try{X(M!=null)}catch{}a("text"),o(!0)},onClick:j=>{try{j.preventDefault()}catch{}try{j.stopPropagation()}catch{}E.current=!0;try{X(M!=null)}catch{}a("text"),o(!0)},onKeyDown:j=>{if(j.key==="Enter"||j.key===" "){j.preventDefault(),E.current=!0;try{X(M!=null)}catch{}a("text"),o(!0)}},children:[h.jsx("div",{style:{flex:1,padding:"10px 12px"},children:"Create a new note"}),h.jsx("div",{className:"checkbox-visual",onMouseDown:j=>{j.stopPropagation()},onClick:j=>{j.stopPropagation(),E.current=!0;try{X(M!=null)}catch{}a("checklist"),W([{content:""}]),o(!0),De(0)},"aria-label":"Start checklist",children:h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})})]})});const Le={};return Me&&(Le.background=Me,Le["--checkbox-bg"]=Me,Le["--checkbox-border"]="#ffffff",Le["--checkbox-checked-bg"]=Me,Le["--checkbox-checked-mark"]="#ffffff",Le["--editor-surface"]=Me),h.jsxs("div",{className:`take-note-expanded${p?" maximized":""}`,ref:de,style:{padding:12,...Le},children:[l==="text"?h.jsxs("div",{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:h.jsx("input",{placeholder:"Title",value:c,onChange:j=>u(j.target.value),style:{fontSize:18,fontWeight:600,border:"none",background:"transparent",color:"inherit"}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:8,marginBottom:0,overflowX:"auto"},children:[h.jsx("button",{className:"tiny",onClick:()=>w("bold"),"aria-pressed":g==null?void 0:g.isActive("bold"),children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>w("italic"),"aria-pressed":g==null?void 0:g.isActive("italic"),children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>w("underline"),"aria-pressed":g==null?void 0:g.isActive("underline"),children:"U"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleHeading({level:1}).run(),"aria-pressed":g==null?void 0:g.isActive("heading",{level:1}),children:"H1"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleHeading({level:2}).run(),"aria-pressed":g==null?void 0:g.isActive("heading",{level:2}),children:"H2"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleHeading({level:3}).run(),"aria-pressed":g==null?void 0:g.isActive("heading",{level:3}),children:"H3"}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleBulletList().run(),"aria-pressed":g==null?void 0:g.isActive("bulletList"),"aria-label":"Bulleted list",title:"Bulleted list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("circle",{cx:"5",cy:"6",r:"1.5"}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"12",r:"1.5"}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"18",r:"1.5"}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().toggleOrderedList().run(),"aria-pressed":g==null?void 0:g.isActive("orderedList"),"aria-label":"Numbered list",title:"Numbered list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("text",{x:"3.5",y:"7",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"1."}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"13",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"2."}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"19",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"3."}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("left").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"left"}),"aria-label":"Align left",title:"Align left",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"4",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("center").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"center"}),"aria-label":"Align center",title:"Align center",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"7",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"8",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("right").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"right"}),"aria-label":"Align right",title:"Align right",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"6",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"10",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"6",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"12",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>g==null?void 0:g.chain().focus().setTextAlign("justify").run(),"aria-pressed":g==null?void 0:g.isActive({textAlign:"justify"}),"aria-label":"Justify",title:"Justify",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"9",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"17",width:"14",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>m(j=>!j),"aria-label":"Toggle maximize",title:"Toggle maximize",children:"⤢"})]})]}),h.jsx("div",{onKeyDown:j=>{if(!(!g||!(j.ctrlKey||j.metaKey))&&g.isFocused)switch(j.key.toLowerCase()){case"b":j.preventDefault(),w("bold");break;case"i":j.preventDefault(),w("italic");break;case"u":j.preventDefault(),w("underline");break;case"l":j.preventDefault(),g.chain().focus().setTextAlign("left").run();break;case"r":j.preventDefault(),g.chain().focus().setTextAlign("right").run();break;case"e":j.preventDefault(),g.chain().focus().setTextAlign("center").run();break;case"j":j.preventDefault(),g.chain().focus().setTextAlign("justify").run();break}},children:h.jsx(Qd,{editor:g})})]}):h.jsxs("div",{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:h.jsx("input",{placeholder:"Title",value:c,onChange:j=>u(j.target.value),style:{fontSize:18,fontWeight:600,border:"none",background:"transparent",color:"inherit"}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:8,marginBottom:0},onPointerDown:j=>j.preventDefault(),onPointerUp:j=>j.preventDefault(),children:[h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:j=>{j.preventDefault(),j.stopPropagation(),xe.current=!0,ot("bold")},onPointerUp:j=>{j.preventDefault(),j.stopPropagation()},onMouseDownCapture:j=>{j.preventDefault(),j.stopPropagation()},onMouseUp:j=>j.preventDefault(),onClick:()=>{if(xe.current){xe.current=!1;return}ot("bold")},"aria-pressed":xt("bold"),children:"B"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:j=>{j.preventDefault(),j.stopPropagation(),xe.current=!0,ot("italic")},onPointerUp:j=>{j.preventDefault(),j.stopPropagation()},onMouseDownCapture:j=>{j.preventDefault(),j.stopPropagation()},onMouseUp:j=>j.preventDefault(),onClick:()=>{if(xe.current){xe.current=!1;return}ot("italic")},"aria-pressed":xt("italic"),children:"I"}),h.jsx("button",{className:"tiny",type:"button",tabIndex:-1,onPointerDownCapture:j=>{j.preventDefault(),j.stopPropagation(),xe.current=!0,ot("underline")},onPointerUp:j=>{j.preventDefault(),j.stopPropagation()},onMouseDownCapture:j=>{j.preventDefault(),j.stopPropagation()},onMouseUp:j=>j.preventDefault(),onClick:()=>{if(xe.current){xe.current=!1;return}ot("underline")},"aria-pressed":xt("underline"),children:"U"})]})]}),h.jsxs("div",{style:{marginTop:8},children:[H.length===0&&h.jsx("div",{style:{marginBottom:8},children:h.jsx("button",{className:"btn",onPointerDown:j=>{j.preventDefault(),j.stopPropagation()},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.preventDefault(),j.stopPropagation(),W([{content:""}]),setTimeout(()=>De(0),30)},children:"Add an item"})}),H.map((j,G)=>h.jsxs("div",{className:"checklist-item",draggable:!0,onDragStart:fe=>{var je;Ae.current=G,(je=fe.dataTransfer)==null||je.setData("text/plain",String(G))},onDragOver:fe=>fe.preventDefault(),onDrop:fe=>{fe.preventDefault();const je=Ae.current??parseInt(fe.dataTransfer.getData("text/plain")||"-1",10),Ue=G;je>=0&&je!==Ue&&W(We=>{const Se=[...We],[Xe]=Se.splice(je,1);return Se.splice(Ue,0,Xe),Se}),Ae.current=null},style:{display:"flex",gap:8,alignItems:"center"},children:[h.jsx("div",{className:"drag-handle",style:{width:20,cursor:"grab",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},"aria-hidden":!0,children:"≡"}),h.jsx("div",{className:"checkbox-visual",onClick:()=>ge(G),"aria-hidden":!0,children:j.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round"})})}),h.jsx("div",{style:{flex:1},children:h.jsx(Ix,{value:j.content,onChange:fe=>Y(G,fe),onEnter:()=>{W(fe=>{const je=[...fe];return je.splice(G+1,0,{content:""}),je}),De(G+1)},onArrowUp:()=>De(Math.max(0,G-1)),onArrowDown:()=>De(Math.min(H.length-1,G+1)),onBackspaceEmpty:()=>{G>0&&(W(fe=>{const je=[...fe];return je.splice(G,1),je}),De(G-1))},onFocus:fe=>{me.current=fe,q.current[G]=fe,se(je=>je+1)},placeholder:"",autoFocus:G===0})}),h.jsx("button",{className:"delete-item",onClick:fe=>{fe.stopPropagation(),W(je=>{const Ue=je.filter((Se,Xe)=>Xe!==G);if(Ue.length===0)return me.current=null,q.current=[],Ue;const We=Math.max(0,Math.min(G-1,Ue.length-1));return setTimeout(()=>De(We),30),Ue})},"aria-label":"Delete item",title:"Delete item",children:"✕"})]},G))]})]}),ce&&h.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10},children:[h.jsx("div",{className:"note-image",style:{width:96,height:72,flex:"0 0 auto"},children:h.jsx("img",{src:ce,alt:"selected",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:6,display:"block"}})}),h.jsx("div",{style:{flex:1,fontSize:13,opacity:.9},children:"1 image selected"}),h.jsx("button",{className:"btn",type:"button",onClick:()=>Ee(null),style:{padding:"6px 10px"},children:"Remove"})]}),h.jsxs("div",{className:"note-footer","aria-hidden":!1,style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:10,flexWrap:"wrap"},children:[h.jsxs("div",{style:{marginRight:"auto",display:"flex",flexDirection:"column",gap:8,minWidth:0,color:Me?Je:void 0},children:[!!M&&!!N&&h.jsxs("label",{className:"create-collection-toggle",title:N,children:[h.jsx("input",{type:"checkbox",checked:!!z,onChange:j=>X(!!j.target.checked)}),h.jsx("span",{className:"create-collection-toggle__text",children:"Add to current collection:"}),h.jsx("span",{className:"create-collection-toggle__path",children:N})]}),h.jsxs("div",{className:"note-actions",style:{display:"inline-flex",gap:8},children:[h.jsx("button",{className:"tiny palette",onClick:()=>at(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>ct(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>At(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>wt(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})})]})]}),h.jsx("button",{className:"btn",onClick:async()=>{Ye()},children:"Cancel"}),h.jsx("button",{className:"btn",onClick:Be,disabled:te||!oe(),children:te?"Saving...":"Save"})]}),J&&h.jsx(ef,{anchorRef:de,onPick:j=>{Q(j)},onClose:()=>at(!1)}),$t&&h.jsx(tf,{onClose:()=>ct(!1),onSet:j=>{ct(!1)}}),nt&&h.jsx(xc,{onClose:()=>At(!1),onSelect:j=>{ze(G=>G.find(fe=>fe.id===j.id)?G:[...G,j]),At(!1)},current:(()=>{const j=i&&i.id?Number(i.id):void 0;return Ke.filter(G=>typeof G.id=="number"?G.id!==j:!0).map(G=>({userId:G.id,email:G.email}))})(),ownerId:i==null?void 0:i.id,onRemove:()=>{}}),Bt&&h.jsx(nf,{onClose:()=>wt(!1),onAdd:j=>Ee(j||null)})]})}function VJ({anchorRef:t,onClose:e,onDiscard:n}){const r=b.useRef(null),[i,s]=b.useState({position:"fixed",visibility:"hidden",left:0,top:0,zIndex:1e4});b.useLayoutEffect(()=>{const l=t==null?void 0:t.current,a=r.current;if(!a)return;const c=8,u=()=>{a.style.width="auto",a.style.height="auto";const f=Math.ceil(a.offsetWidth),p=Math.ceil(a.offsetHeight);return{w:f,h:p}};if(!l){const{w:f,h:p}=u();let m=Math.round(window.innerWidth-f-c),g=Math.round(window.innerHeight-p-c);mwindow.innerWidth-c&&(m=Math.max(c,window.innerWidth-f-c)),gwindow.innerHeight-c&&(g=Math.max(c,window.innerHeight-p-c)),s({position:"fixed",left:m,top:g,visibility:"visible",zIndex:1e4,width:`${f}px`,height:`${p}px`});return}const d=l.getBoundingClientRect();requestAnimationFrame(()=>{const{w:f,h:p}=u();let m=Math.round(d.right-f),g=Math.round(d.bottom-p);mwindow.innerWidth-c&&(m=Math.max(c,window.innerWidth-f-c)),gwindow.innerHeight-c&&(g=Math.max(c,window.innerHeight-p-c)),s({position:"fixed",left:m,top:g,visibility:"visible",zIndex:1e4,width:`${f}px`,height:`${p}px`})})},[t]),b.useLayoutEffect(()=>{function l(a){r.current&&(r.current.contains(a.target)||e())}return document.addEventListener("pointerdown",l),document.addEventListener("mousedown",l),()=>{document.removeEventListener("pointerdown",l),document.removeEventListener("mousedown",l)}},[e]);const o=h.jsx("div",{ref:r,className:"more-menu",style:i,role:"dialog","aria-label":"More options",children:h.jsx("button",{className:"more-item",onClick:()=>{n(),e()},children:"Discard"})});return zn.createPortal(o,document.body)}function WJ({open:t,mode:e,onClose:n,onCreated:r,activeCollection:i}){const{token:s,user:o}=Sr();function l(){try{return`u${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`u${Math.random()}`}}const[a,c]=B.useState(""),[u,d]=B.useState([]),[f,p]=B.useState(""),[m,g]=B.useState(void 0),[y,v]=B.useState(!1),[w,x]=B.useState(!1),[E,k]=B.useState(!1),[M,N]=B.useState(!1),[z,X]=B.useState(null),[L,H]=B.useState([]),W=i&&Number.isFinite(Number(i.id))?Number(i.id):null,te=i&&typeof i.path=="string"?String(i.path):"",[ue,de]=B.useState(!1),[Ae,me]=B.useState(!1),q=B.useRef(null),se=B.useRef(null),[xe,Me]=B.useState(!1),Q=pg({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),yg,mn.create({name:"paragraphEnterFix",priority:1e3,addKeyboardShortcuts(){return{"Shift-Enter":()=>{const ee=this.editor;return ee.commands.splitBlock(),ee.commands.setParagraph(),!0},"Mod-Enter":()=>{const ee=this.editor;return ee.commands.splitBlock(),ee.commands.setParagraph(),!0}}}})],editorProps:{attributes:{class:"rt-editor"}},content:""}),Je=B.useRef({showPalette:!1,showReminderPicker:!1,showCollaborator:!1,showImageDialog:!1,showMore:!1});B.useEffect(()=>{Je.current={showPalette:y,showReminderPicker:w,showCollaborator:E,showImageDialog:M,showMore:xe}},[y,w,E,M,xe]);const _t=B.useRef((()=>{try{return`mcreate-${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}catch{return`mcreate-${Math.random()}`}})());B.useEffect(()=>{if(t){window.dispatchEvent(new Event("freemannotes:editor-modal-open"));try{const ee=_t.current,re=()=>{try{const Oe=Je.current;if(Oe.showMore){Me(!1);return}if(Oe.showImageDialog){N(!1);return}if(Oe.showCollaborator){k(!1);return}if(Oe.showReminderPicker){x(!1);return}if(Oe.showPalette){v(!1);return}}catch{}try{J()}catch{}};window.dispatchEvent(new CustomEvent("freemannotes:back/register",{detail:{id:ee,onBack:re}}))}catch{}return()=>{try{window.dispatchEvent(new CustomEvent("freemannotes:back/unregister",{detail:{id:_t.current}}))}catch{}window.dispatchEvent(new Event("freemannotes:editor-modal-close"))}}},[t]),B.useEffect(()=>{if(t){c(""),p(""),X(null),H([]),v(!1),x(!1),k(!1),N(!1),Me(!1);try{de(W!=null)}catch{}e==="checklist"?(d([{uid:l(),content:"",checked:!1,indent:0}]),window.setTimeout(()=>Se(0),30)):(d([]),requestAnimationFrame(()=>{try{Q==null||Q.commands.focus("end")}catch{}}));try{Q==null||Q.commands.clearContent()}catch{}}},[t,e,Q]),B.useEffect(()=>{g(f?dn(f):void 0)},[f]);function J(){if(!Ae){try{fe()}catch{}try{Me(!1)}catch{}try{v(!1)}catch{}try{x(!1)}catch{}try{k(!1)}catch{}try{N(!1)}catch{}try{Q==null||Q.commands.clearContent()}catch{}try{c(""),d([]),p(""),X(null),H([])}catch{}n()}}function at(){try{const ee=!!a.trim(),re=!!f,Oe=!!(z||L&&L.length);if(e==="checklist"){const pe=(u||[]).some(Ce=>!!String(Ce.content||"").trim()||!!Ce.checked);return ee||re||Oe||pe}const Ze=!!((Q==null?void 0:Q.getText())||"").trim();return ee||re||Oe||Ze}catch{return!1}}async function $t(){var ee;if(!Ae){me(!0);try{if(!s)throw new Error("Not authenticated");const re=e==="text"?(Q==null?void 0:Q.getJSON())||{}:{},Oe={title:a,body:null,type:e==="checklist"?"CHECKLIST":"TEXT",color:f||null};e==="checklist"&&(Oe.items=u.map((Fe,ut)=>({content:Fe.content,checked:!!Fe.checked,indent:typeof Fe.indent=="number"?Fe.indent:0,ord:ut})));const Ze=await fetch("/api/notes",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(Oe)});if(!Ze.ok)throw new Error(await Ze.text());const pe=await Ze.json(),Ce=(ee=pe==null?void 0:pe.note)==null?void 0:ee.id;if(Ce&&ue&&W!=null)try{const Fe=await fetch(`/api/notes/${Ce}/collections`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({collectionId:W})});if(!Fe.ok)throw new Error(await Fe.text())}catch(Fe){console.warn("Created note but failed to add to collection",Fe);try{window.alert("Note created, but failed to add it to the current collection.")}catch{}}if(Ce&&e==="text")try{const Fe=new Fi,ut=`note-${Ce}`,zt=new mf(Nj("/collab"),ut,Fe),kt=new ag({extensions:[ta.configure({heading:{levels:[1,2,3]}}),Ac.configure({types:["heading","paragraph"]}),Pg.configure({document:Fe})],content:""});await new Promise(Jt=>{zt.on("sync",jt=>{jt&&Jt()})});try{kt==null||kt.commands.setContent(re)}catch{}await new Promise(Jt=>setTimeout(Jt,100));try{kt==null||kt.destroy()}catch{}try{zt.destroy()}catch{}try{Fe.destroy()}catch{}try{await fetch(`/api/notes/${Ce}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({body:JSON.stringify(re),type:"TEXT"})})}catch{}}catch(Fe){console.warn("Failed to seed Yjs content for new note",Fe)}if(Ce&&L.length)for(const Fe of L)try{await fetch(`/api/notes/${Ce}/collaborators`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({email:Fe.email})})}catch{}if(Ce&&z)try{await fetch(`/api/notes/${Ce}/images`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({url:z})})}catch{}try{Q==null||Q.commands.clearContent()}catch{}r(),n()}catch(re){console.error("Failed to create note",re),window.alert("Failed to create note")}finally{me(!1)}}}const ct=B.useRef([]),[nt,At]=B.useState(null),[Bt,wt]=B.useState(null),[ce,Ee]=B.useState(null),Ke=B.useRef(null),ze=B.useRef({x:0,y:0}),Pe=B.useRef(null),it=B.useRef(0),ot=B.useRef(null),xt=B.useRef(0),oe=B.useRef(null),Ye=B.useRef(0),Ge=B.useRef(null),Y=B.useMemo(()=>{try{return typeof window<"u"&&!!window.matchMedia&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}},[]),ge=B.useMemo(()=>{const ee={directionLockPx:0,indentPx:16,ghostOverlapUpPct:.7,ghostOverlapDownPct:.7};return Y?ee:{...ee,directionLockPx:6}},[Y]);function De(ee,re){var Ce,Fe;const Oe=re,Ze=Number(((Ce=ee[re])==null?void 0:Ce.indent)||0);let pe=re+1;for(;peZe;)pe++;return[Oe,pe]}function Be(ee,re,Oe){d(Ze=>{const pe=[...Ze||[]],Ce=pe.slice(ee,re);pe.splice(ee,re-ee);let Fe=Oe;return Fe>ee&&(Fe=Fe-(re-ee)),Fe<0&&(Fe=0),Fe>pe.length&&(Fe=pe.length),pe.splice(Fe,0,...Ce),pe})}function Le(ee,re){if(Pe.current!=="vertical"||nt===null)return"";const[Oe,Ze]=De(re,nt);return Bt===null||ee>=Oe&&eeZe-1&&ee<=Bt?"shift-up":"":nt>Bt&&ee>=Bt&&ee{var Fe,ut;oe.current=null;const re=(Fe=Ge.current)==null?void 0:Fe.querySelector(".dialog-body");if(!re)return;const Oe=re.getBoundingClientRect(),Ze=Ye.current,pe=60,Ce=12;ZeOe.bottom-pe&&(re.scrollTop+=Ce),(ut=ot.current)!=null&&ut.active&&Pe.current==="vertical"&&Ke.current&&(oe.current=window.requestAnimationFrame(ee))};oe.current=window.requestAnimationFrame(ee)}function G(){oe.current!=null&&(window.cancelAnimationFrame(oe.current),oe.current=null)}function fe(){var ee,re,Oe;if(G(),Ke.current){try{Ke.current.remove()}catch{}Ke.current=null}try{(Oe=(re=(ee=Ge.current)==null?void 0:ee.style)==null?void 0:re.removeProperty)==null||Oe.call(re,"--checklist-item-shift")}catch{}At(null),wt(null),Ee(null),ot.current=null,Pe.current=null,xt.current=0}function je(){d(ee=>[...ee||[],{uid:l(),content:"",checked:!1,indent:0}])}function Ue(ee,re){d(Oe=>(Oe||[]).map((Ze,pe)=>pe===ee?{...Ze,content:re}:Ze))}function We(ee){d(re=>{var Fe;const Oe=[...re||[]],Ze=Oe[ee];if(!Ze)return Oe;const pe=!Ze.checked,Ce=Number(Ze.indent||0);if(Oe[ee]={...Ze,checked:pe},Ce===0)for(let ut=ee+1;ut0;ut++)Oe[ut]={...Oe[ut],checked:pe};return Oe})}function Se(ee){window.setTimeout(()=>{const re=ct.current[ee];try{re&&re.chain().focus().run()}catch{}},30)}const Xe=B.useRef(null),[,Tt]=B.useState(0);function rt(){var Oe;let ee=Xe.current;if(ee&&ee.isFocused)return ee;const re=typeof document<"u"&&((Oe=document.getSelection())==null?void 0:Oe.anchorNode)||null;if(re){const Ze=ct.current.find(pe=>{var Ce;try{return!!(pe&&((Ce=pe.view)!=null&&Ce.dom)&&pe.view.dom.contains(re))}catch{return!1}});Ze&&(ee=Ze)}else{const Ze=typeof document<"u"?document.activeElement:null;if(Ze){const pe=ct.current.find(Ce=>{try{return!!(Ce&&Ce.view&&Ce.view.dom&&(Ce.view.dom===Ze||Ce.view.dom.contains(Ze)))}catch{return!1}});pe&&(ee=pe)}}if(!ee||!(ee!=null&&ee.isFocused)){const Ze=ct.current.find(pe=>!!(pe&&pe.isFocused));Ze&&(ee=Ze)}return ee||null}function Wt(ee){var Fe;const re=rt();if(!re)return;const Oe=(Fe=re.state)==null?void 0:Fe.selection;if(!Oe)return;if(!Oe.empty){const ut=re.chain().focus();ee==="bold"?ut.toggleBold():ee==="italic"?ut.toggleItalic():ut.toggleUnderline(),ut.run();try{Tt(zt=>zt+1)}catch{}return}let Ze=Oe.from,pe=Oe.to;try{const ut=Oe.$from;let zt=ut.depth;for(;zt>0&&!ut.node(zt).isBlock;)zt--;Ze=ut.start(zt),pe=ut.end(zt)}catch{}const Ce=re.chain().focus().setTextSelection({from:Ze,to:pe});ee==="bold"?Ce.toggleBold():ee==="italic"?Ce.toggleItalic():Ce.toggleUnderline(),Ce.run();try{re.chain().focus().setTextSelection(Oe.from).run()}catch{}try{Tt(ut=>ut+1)}catch{}}function Mt(ee){var Jt,jt;const re=rt();if(!re)return!1;const Oe=(Jt=re.state)==null?void 0:Jt.selection;if(!Oe)return!1;const Ze=(((jt=re.schema)==null?void 0:jt.marks)||{})[ee];if(!Ze)return!1;const pe=Oe.$from;let Ce=pe.depth;for(;Ce>0&&!pe.node(Ce).isBlock;)Ce--;const Fe=pe.start(Ce),ut=pe.end(Ce);let zt=!1,kt=!0;try{re.state.doc.nodesBetween(Fe,ut,fn=>{fn&&fn.isText&&(zt=!0,Ze.isInSet(fn.marks)||(kt=!1))})}catch{}return zt&&kt}function dn(ee){if(!ee)return;const re=ee.replace("#",""),Oe=re.length===3?re.split("").map(nn=>nn+nn).join(""):re;if(Oe.length!==6)return;const Ze=parseInt(Oe.slice(0,2),16)/255,pe=parseInt(Oe.slice(2,4),16)/255,Ce=parseInt(Oe.slice(4,6),16)/255,Fe=nn=>nn<=.03928?nn/12.92:Math.pow((nn+.055)/1.055,2.4),ut=Fe(Ze),zt=Fe(pe),kt=Fe(Ce),Jt=.2126*ut+.7152*zt+.0722*kt,jt=(nn,rn)=>(Math.max(nn,rn)+.05)/(Math.min(nn,rn)+.05),fn=jt(1,Jt),wn=jt(0,Jt);return fn>=wn?"#ffffff":"#000000"}if(!t)return null;const It={};f&&(It.background=f,It["--editor-surface"]=f);const Ot=e==="checklist"?"New checklist":"New note",tn=h.jsxs("div",{className:"image-dialog-backdrop",ref:q,onMouseDown:ee=>{if(ee.target===ee.currentTarget)try{ee.preventDefault()}catch{}},children:[h.jsxs("div",{ref:Ge,className:`image-dialog editor-dialog maximized${e==="checklist"?" checklist-editor":""}`,role:"dialog","aria-modal":!0,style:{width:"100vw",...It},children:[h.jsxs("div",{className:"dialog-header",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[h.jsx("button",{className:"btn",type:"button",onClick:J,disabled:Ae,children:"Cancel"}),h.jsx("strong",{children:Ot}),h.jsx("button",{className:"btn",type:"button",onClick:$t,disabled:Ae||!at(),children:Ae?"Saving…":"Save"})]}),h.jsxs("div",{className:"dialog-body",children:[e==="text"?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Title",value:a,onChange:ee=>c(ee.target.value),style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:0,marginBottom:0,overflowX:"auto",color:m||"inherit"},children:[h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleBold().run(),"aria-pressed":Q==null?void 0:Q.isActive("bold"),"aria-label":"Bold",title:"Bold",children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleItalic().run(),"aria-pressed":Q==null?void 0:Q.isActive("italic"),"aria-label":"Italic",title:"Italic",children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleUnderline().run(),"aria-pressed":Q==null?void 0:Q.isActive("underline"),"aria-label":"Underline",title:"Underline",children:"U"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleHeading({level:1}).run(),"aria-pressed":Q==null?void 0:Q.isActive("heading",{level:1}),"aria-label":"Heading 1",title:"Heading 1",children:"H1"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleHeading({level:2}).run(),"aria-pressed":Q==null?void 0:Q.isActive("heading",{level:2}),"aria-label":"Heading 2",title:"Heading 2",children:"H2"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleHeading({level:3}).run(),"aria-pressed":Q==null?void 0:Q.isActive("heading",{level:3}),"aria-label":"Heading 3",title:"Heading 3",children:"H3"}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleBulletList().run(),"aria-pressed":Q==null?void 0:Q.isActive("bulletList"),"aria-label":"Bulleted list",title:"Bulleted list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("circle",{cx:"5",cy:"6",r:"1.5"}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"12",r:"1.5"}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("circle",{cx:"5",cy:"18",r:"1.5"}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().toggleOrderedList().run(),"aria-pressed":Q==null?void 0:Q.isActive("orderedList"),"aria-label":"Numbered list",title:"Numbered list",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("text",{x:"3.5",y:"7",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"1."}),h.jsx("rect",{x:"9",y:"5",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"13",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"2."}),h.jsx("rect",{x:"9",y:"11",width:"10",height:"2",rx:"1"}),h.jsx("text",{x:"3.5",y:"19",fontSize:"6",fontFamily:"system-ui, Arial",fill:"currentColor",children:"3."}),h.jsx("rect",{x:"9",y:"17",width:"10",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().setTextAlign("left").run(),"aria-pressed":Q==null?void 0:Q.isActive({textAlign:"left"}),"aria-label":"Align left",title:"Align left",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"4",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"4",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().setTextAlign("center").run(),"aria-pressed":Q==null?void 0:Q.isActive({textAlign:"center"}),"aria-label":"Align center",title:"Align center",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"5",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"7",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"5",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"8",y:"17",width:"8",height:"2",rx:"1"})]})}),h.jsx("button",{className:"tiny",onClick:()=>Q==null?void 0:Q.chain().focus().setTextAlign("right").run(),"aria-pressed":Q==null?void 0:Q.isActive({textAlign:"right"}),"aria-label":"Align right",title:"Align right",children:h.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:[h.jsx("rect",{x:"6",y:"5",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"10",y:"9",width:"10",height:"2",rx:"1"}),h.jsx("rect",{x:"6",y:"13",width:"14",height:"2",rx:"1"}),h.jsx("rect",{x:"12",y:"17",width:"8",height:"2",rx:"1"})]})})]})]}),h.jsx(Qd,{editor:Q,style:{color:m||"inherit"}})]}):h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"rt-sticky-header",children:[h.jsx("div",{style:{display:"flex",gap:12,marginBottom:8},children:h.jsx("input",{placeholder:"Title",value:a,onChange:ee=>c(ee.target.value),style:{flex:1,background:"transparent",border:"none",color:"inherit",fontWeight:600,fontSize:18}})}),h.jsxs("div",{className:"rt-toolbar",style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",marginTop:0,marginBottom:0,overflowX:"auto",color:m||"inherit"},children:[h.jsx("button",{className:"tiny",onClick:()=>Wt("bold"),"aria-pressed":Mt("bold"),"aria-label":"Bold",title:"Bold",children:"B"}),h.jsx("button",{className:"tiny",onClick:()=>Wt("italic"),"aria-pressed":Mt("italic"),"aria-label":"Italic",title:"Italic",children:"I"}),h.jsx("button",{className:"tiny",onClick:()=>Wt("underline"),"aria-pressed":Mt("underline"),"aria-label":"Underline",title:"Underline",children:"U"}),h.jsx("button",{className:"btn",type:"button",onClick:()=>{je(),Se(u.length)},style:{padding:"6px 10px"},children:"Add item"})]})]}),h.jsx("div",{className:"checklist-items",children:(ce??u??[]).map((ee,re)=>{const Ze=Le(re,ce??u??[]);return h.jsxs("div",{className:`checklist-item${nt===re?" drag-source":""}${Ze?" "+Ze:""}`,style:{marginLeft:Number(ee.indent||0)*18},draggable:!1,onClick:pe=>{try{pe.stopPropagation()}catch{}},children:[h.jsxs("div",{className:"drag-gutter",style:{cursor:"grab",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",touchAction:"none"},onMouseDown:pe=>{pe.preventDefault()},onPointerDown:pe=>{try{pe.preventDefault()}catch{}try{pe.stopPropagation()}catch{}pe.currentTarget.setPointerCapture(pe.pointerId),Ye.current=pe.clientY,ot.current={active:!0,startX:pe.clientX,startY:pe.clientY,idx:re,pointerId:pe.pointerId},Pe.current=null,Ee(null)},onPointerMove:pe=>{var Jt,jt,fn,wn,nn,rn,Pr,I;const Ce=ot.current;if(!Ce||!Ce.active)return;try{pe.preventDefault()}catch{}Ye.current=pe.clientY;const Fe=pe.clientX-Ce.startX,ut=pe.clientY-Ce.startY,zt=ge.directionLockPx;if(Pe.current===null&&(Math.abs(Fe)>zt||Math.abs(ut)>zt)&&(Pe.current=Math.abs(Fe)>Math.abs(ut)?"horizontal":"vertical"),Pe.current==="vertical"){const U=Ce.idx;if(!Ke.current){const $=Array.from(((Jt=Ge.current)==null?void 0:Jt.querySelectorAll(".checklist-item"))||[])[U];if($){const S=$.getBoundingClientRect();ze.current={x:pe.clientX-S.left,y:pe.clientY-S.top};const V=$.cloneNode(!0);V.style.position="fixed",V.style.left=S.left+"px",V.style.top=pe.clientY-(ze.current.y||0)+"px",V.style.width=S.width+"px",V.style.pointerEvents="none",V.style.zIndex="9999",V.style.opacity="0.98",V.classList.add("checklist-ghost"),document.body.appendChild(V),Ke.current=V,At(U),wt(U),it.current=S.left;try{(wn=(fn=(jt=Ge.current)==null?void 0:jt.style)==null?void 0:fn.setProperty)==null||wn.call(fn,"--checklist-item-shift",`${Math.round(S.height)}px`)}catch{}}}Ke.current&&(Ke.current.style.left=it.current+"px",Ke.current.style.top=pe.clientY-(ze.current.y||0)+"px",j());const K=Array.from(((nn=Ge.current)==null?void 0:nn.querySelectorAll(".checklist-item"))||[]);if(K.length){let le=null;const $=Ke.current?Ke.current.getBoundingClientRect():{top:pe.clientY-10,bottom:pe.clientY+10},S=pe.clientY>(xt.current||pe.clientY);xt.current=pe.clientY;const V=S?ge.ghostOverlapDownPct:ge.ghostOverlapUpPct;for(let he=0;he=V){le=he;break}}le!=null&&le!==Bt&&wt(le)}return}const kt=ge.indentPx;if(Pe.current==="horizontal"){const U=Ce.idx;if(U===0&&Fe>0){Ee(null);return}const K=u;if(Fe>kt){const[le,$]=De(K,U),S=[...K],V=S.splice(le,$-le);let he=null;for(let tt=U-1;tt>=0;tt--)if(Number(((rn=K[tt])==null?void 0:rn.indent)||0)===0){he=tt;break}if(he!=null){const tt=K[he].uid,Ft=S.findIndex($n=>$n.uid===tt);let Kt=Ft>=0?Ft+1:Math.min(le,S.length);for(;Kt0;)Kt++;const Zt=V.map($n=>({...$n,indent:1}));S.splice(Kt,0,...Zt)}else{let tt=Math.min(le,S.length);for(;tt0;)tt++;const Ft=V.map(Kt=>({...Kt,indent:1}));S.splice(tt,0,...Ft)}Ee(S)}else if(Fe<-kt){const[le,$]=De(K,U),S=[...K];for(let V=le;V<$&&V{try{pe.currentTarget.releasePointerCapture(pe.pointerId)}catch{}if(ot.current=null,ce){d(ce),Ee(null),Pe.current=null,fe();return}if(Pe.current==="vertical"&&nt!==null){const Ce=nt,Fe=u,[ut,zt]=De(Fe,Ce);if(Bt!==null){const kt=Ce=ut&&kt{pe.stopPropagation(),We(re)},onPointerDown:pe=>{pe.stopPropagation()},onPointerUp:pe=>{pe.stopPropagation()},children:ee.checked&&h.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,focusable:"false",children:h.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),h.jsx("div",{style:{flex:1,minWidth:0},children:h.jsx(Ix,{value:ee.content,onChange:pe=>Ue(re,pe),onEnter:()=>{d(pe=>{const Ce=[...pe||[]];return Ce.splice(re+1,0,{uid:l(),content:"",checked:!1,indent:Number(ee.indent||0)}),Ce}),Se(re+1)},onArrowUp:()=>Se(Math.max(0,re-1)),onArrowDown:()=>Se(Math.min(u.length-1,re+1)),onBackspaceEmpty:()=>{re>0&&(d(pe=>{const Ce=[...pe||[]];return Ce.splice(re,1),Ce}),Se(re-1))},onFocus:pe=>{Xe.current=pe,ct.current[re]=pe;try{Tt(Ce=>Ce+1)}catch{}},placeholder:"",autoFocus:re===0})}),h.jsx("button",{className:"delete-item",type:"button",onClick:pe=>{pe.stopPropagation(),d(Ce=>{const Fe=(Ce||[]).filter((zt,kt)=>kt!==re);if(Fe.length===0)return Xe.current=null,ct.current=[],Fe;const ut=Math.max(0,Math.min(re-1,Fe.length-1));return window.setTimeout(()=>Se(ut),30),Fe})},"aria-label":"Delete item",title:"Delete item",children:"✕"})]},ee.uid||String(re))})})]}),z&&h.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10},children:[h.jsx("div",{className:"note-image",style:{width:96,height:72,flex:"0 0 auto"},children:h.jsx("img",{src:z,alt:"selected",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:6,display:"block"}})}),h.jsx("div",{style:{flex:1,fontSize:13,opacity:.9},children:"1 image selected"}),h.jsx("button",{className:"btn",type:"button",onClick:()=>X(null),style:{padding:"6px 10px"},children:"Remove"})]})]}),h.jsxs("div",{className:"dialog-footer",style:{display:"block"},children:[!!W&&!!te&&h.jsxs("label",{className:"create-collection-toggle",title:te,style:{margin:"0 0 10px"},children:[h.jsx("input",{type:"checkbox",checked:!!ue,onChange:ee=>de(!!ee.target.checked)}),h.jsx("span",{className:"create-collection-toggle__text",children:"Add to current collection:"}),h.jsx("span",{className:"create-collection-toggle__path",children:te})]}),h.jsxs("div",{className:"note-actions",style:{display:"inline-flex",gap:8,justifyContent:"flex-start",color:m||"inherit"},children:[h.jsx("button",{className:"tiny palette",onClick:()=>v(!0),"aria-label":"Change color",title:"Change color",children:h.jsx(Xs,{icon:lf,className:"palette-svg"})}),h.jsx("button",{className:"tiny",onClick:()=>x(!0),"aria-label":"Reminder",title:"Reminder",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M12 22c1.1 0 2-.9 2-2h-4a2 2 0 0 0 2 2z"}),h.jsx("path",{d:"M18 8V7a6 6 0 1 0-12 0v1c0 3.5-2 5-2 5h16s-2-1.5-2-5z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>k(!0),"aria-label":"Collaborators",title:"Collaborators",children:h.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[h.jsx("path",{d:"M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"}),h.jsx("path",{d:"M6 14c-1.66 0-3 1.34-3 3v1h9.5c-.2-.63-.5-1.23-.9-1.76C11.7 15.6 9.9 14 6 14z"}),h.jsx("path",{d:"M20 16v2h-2v2h-2v-2h-2v-2h2v-2h2v2z"})]})}),h.jsx("button",{className:"tiny",onClick:()=>N(!0),"aria-label":"Add image",title:"Add image",children:h.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:h.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5C3.9 3 3 3.9 3 5v14h18zM8.5 13.5l2.5 3L14.5 12l4.5 7H5l3.5-5.5z"})})}),h.jsx("button",{ref:se,className:"tiny editor-more",onClick:ee=>{ee.stopPropagation(),Me(re=>!re)},"aria-label":"More",title:"More",children:"⋮"})]})]})]}),y&&h.jsx(ef,{anchorRef:q,onPick:ee=>{p(ee)},onClose:()=>v(!1)}),w&&h.jsx(tf,{onClose:()=>x(!1),onSet:ee=>{x(!1),ee&&window.alert(`Reminder set (UI-only): ${ee}`)}}),E&&h.jsx(xc,{onClose:()=>k(!1),onSelect:ee=>{H(re=>re.find(Oe=>Oe.id===ee.id)?re:[...re,ee]),k(!1)},current:(()=>{const ee=o&&o.id?Number(o.id):void 0;return L.filter(re=>typeof re.id=="number"?re.id!==ee:!0).map(re=>({userId:re.id,email:re.email}))})(),ownerId:o==null?void 0:o.id,onRemove:()=>{}}),M&&h.jsx(nf,{onClose:()=>N(!1),onAdd:ee=>X(ee||null)}),xe&&h.jsx(VJ,{anchorRef:se,onClose:()=>Me(!1),onDiscard:J})]});return zn.createPortal(tn,document.body)}const SN=B.memo(function({note:e,setItemRef:n,isDragSource:r,isDragTarget:i,disabled:s,onChange:o,style:l}){const a=Number(e==null?void 0:e.id),{setNodeRef:c,listeners:u,attributes:d}=U3({id:a,disabled:s}),{setNodeRef:f}=K3({id:a}),p=b.useCallback(g=>{c(g),f(g),n(g,a)},[c,f,n,a]),m=(r?" note-drag-source":"")+(i?" note-drag-target":"");return h.jsx("div",{"data-note-id":a,ref:p,className:m.trim(),style:l,children:h.jsx(El,{note:e,onChange:o,dragHandleAttributes:s?void 0:d,dragHandleListeners:s?void 0:u})})});function KJ({selectedLabelIds:t=[],selectedCollectionId:e=null,collectionStack:n=[],selectedCollaboratorId:r=null,searchQuery:i="",sortConfig:s=Ks,onClearAllFilters:o,onSetSelectedLabelIds:l,onSetSelectedCollaboratorId:a,onSelectCollectionById:c,onSetCollectionStack:u,onSetSearchQuery:d,onSortConfigChange:f}){var F1;const{token:p}=Sr(),[m,g]=b.useState([]),[y,v]=b.useState(!0),[w,x]=b.useState(!1),E=b.useRef([]),[k,M]=b.useState("desktop"),N=b.useRef("desktop"),[z,X]=b.useState(1),[L,H]=b.useState(1),W=b.useRef(1),te=b.useRef(1),[ue,de]=b.useState(0);b.useEffect(()=>{const C=()=>de(R=>R+1),T=()=>de(R=>Math.max(0,R-1));return window.addEventListener("freemannotes:editor-modal-open",C),window.addEventListener("freemannotes:editor-modal-close",T),()=>{window.removeEventListener("freemannotes:editor-modal-open",C),window.removeEventListener("freemannotes:editor-modal-close",T)}},[]);const Ae=ue>0;b.useEffect(()=>{const C=document.documentElement;return Ae?C.classList.add("is-editor-modal-open"):C.classList.remove("is-editor-modal-open"),()=>{try{C.classList.remove("is-editor-modal-open")}catch{}}},[Ae]),b.useEffect(()=>{if(ue<=0)return;const C=window.setTimeout(()=>{try{!!document.querySelector('[aria-modal="true"]')||de(0)}catch{}},400);return()=>{try{window.clearTimeout(C)}catch{}}},[ue]);const me=b.useRef(new Map),q=b.useRef(0),se=b.useRef(null),xe=b.useRef(null),Me=b.useRef(!1),[Q,Je]=b.useState(!1),[_t,J]=b.useState(0),[at,$t]=b.useState("text"),[ct,nt]=b.useState(null),At=b.useMemo(()=>{const C=Array.isArray(n)?n:[];if(!C.length)return null;const T=C[C.length-1],R=Number(T==null?void 0:T.id),P=C.map(O=>String((O==null?void 0:O.name)||"")).filter(Boolean).join(" / ");return!Number.isFinite(R)||!P?null:{id:R,path:P}},[n]),Bt=b.useCallback(C=>{Je(!1),nt(C)},[]);b.useEffect(()=>{if(!Q)return;const C=T=>{try{const R=T==null?void 0:T.target;if(R&&R.closest&&R.closest(".mobile-add-note"))return}catch{}Je(!1)};return window.addEventListener("pointerdown",C,{capture:!0}),()=>{try{window.removeEventListener("pointerdown",C,{capture:!0})}catch{}}},[Q]);const wt=b.useRef(!1),ce=b.useRef(null),Ee=b.useRef(null),Ke=b.useRef(null),ze=b.useRef(-1),Pe=b.useRef([]),it=b.useRef(null),ot=b.useRef(null),xt=b.useRef(null),oe=b.useRef(null),Ye=b.useRef(null),Ge=b.useRef([]),Y=b.useRef(null),ge=b.useRef(2),De=b.useRef(1),Be=b.useRef(!1),Le=b.useRef(null),j=b.useRef(null),[G,fe]=b.useState(null),[je,Ue]=b.useState(null),[We,Se]=b.useState([]),Xe=b.useRef(null),Tt=b.useRef(null),[rt,Wt]=b.useState(null),[Mt,dn]=b.useState(null),It=b.useRef(null),Ot=b.useRef(null),tn=b.useRef(!1),ee=b.useRef(null),re=b.useRef(null),Oe=b.useRef(null),Ze=b.useCallback(C=>{if(!C)return null;const T=C.touches&&C.touches[0]||C.changedTouches&&C.changedTouches[0];return T&&typeof T.clientX=="number"&&typeof T.clientY=="number"?{x:T.clientX,y:T.clientY}:typeof C.clientX=="number"&&typeof C.clientY=="number"?{x:C.clientX,y:C.clientY}:null},[]),pe=b.useCallback(C=>{const T=Ze(C);T&&(ee.current=T);const R=O=>{tn.current&&(ee.current={x:O.clientX,y:O.clientY})},P=O=>{if(!tn.current)return;const _=O.touches&&O.touches[0];_&&(ee.current={x:_.clientX,y:_.clientY})};window.addEventListener("pointermove",R,{capture:!0,passive:!1}),window.addEventListener("touchmove",P,{capture:!0,passive:!0}),Oe.current=()=>{try{window.removeEventListener("pointermove",R,{capture:!0})}catch{}try{window.removeEventListener("touchmove",P,{capture:!0})}catch{}}},[Ze]),Ce=b.useCallback(()=>{try{Oe.current&&Oe.current()}catch{}Oe.current=null,ee.current=null},[]),Fe=b.useCallback(()=>{const C=document.querySelector(".main-area");if(C&&C.scrollHeight>C.clientHeight+1)return C;const T=document.scrollingElement;return T&&T.scrollHeight>T.clientHeight+1?T:null},[]),ut=b.useCallback(()=>{if(re.current!=null)return;const C=96,T=12,R=()=>{if(!tn.current){re.current=null;return}const P=ee.current;if(!P){re.current=requestAnimationFrame(R);return}const O=window.innerHeight||0,_=P.y,D=Math.max(0,O-P.y);let F=0;if(_{if(re.current!=null){try{cancelAnimationFrame(re.current)}catch{}re.current=null}},[]),[kt,Jt]=b.useState(!1),[jt,fn]=b.useState(null),[wn,nn]=b.useState(null),[rn,Pr]=b.useState(null),I=b.useRef(null),U=b.useRef(null),K=b.useRef(null);function le(C){try{const T=(localStorage.getItem("prefs.animationSpeed")||"normal").toLowerCase(),R={fast:{resize:250,swap:250,rearrange:250},normal:{resize:600,swap:500,rearrange:480},slow:{resize:1e3,swap:1e3,rearrange:1e3}};return(R[T]||R.normal)[C]}catch{return C==="resize"?600:C==="swap"?500:480}}function $(){if(!j.current)try{const C=window.scrollX||0,T=window.scrollY||0,R=document.body;j.current={x:C,y:T,position:R.style.position||"",top:R.style.top||"",left:R.style.left||"",right:R.style.right||"",width:R.style.width||"",overflow:R.style.overflow||""},R.style.position="fixed",R.style.top=`-${T}px`,R.style.left=`-${C}px`,R.style.right="0px",R.style.width="100%",R.style.overflow="hidden"}catch{}}function S(){const C=j.current;if(C){j.current=null;try{const T=document.body;T.style.position=C.position,T.style.top=C.top,T.style.left=C.left,T.style.right=C.right,T.style.width=C.width,T.style.overflow=C.overflow,window.scrollTo(C.x,C.y)}catch{}}}b.useLayoutEffect(()=>{Ee.current=G},[G]),b.useLayoutEffect(()=>{Ke.current=je},[je]),b.useLayoutEffect(()=>{Pe.current=We;const C=We.indexOf("spacer");ze.current=C},[We]),b.useEffect(()=>{const C=document.documentElement;return G!=null?C.classList.add("is-note-rearrange-dragging"):C.classList.remove("is-note-rearrange-dragging"),()=>{try{C.classList.remove("is-note-rearrange-dragging")}catch{}}},[G]);async function V(){v(!0);try{const C=await fetch("/api/notes",{headers:{Authorization:`Bearer ${p}`}});if(!C.ok)throw new Error(await C.text());let R=(await C.json()).notes||[];try{const P=localStorage.getItem("notesOrder");if(P){const O=JSON.parse(P||"[]");if(Array.isArray(O)&&O.length){const _=new Map(R.map(ae=>[ae.id,ae])),D=[],F=new Set;for(const ae of O)_.has(ae)&&!F.has(ae)&&(D.push(_.get(ae)),F.add(ae));const ie=[];for(const ae of R)F.has(ae.id)||ie.push(ae);R=[...ie,...D]}}}catch{}g(R);try{setTimeout(()=>window.dispatchEvent(new Event("notes-grid:recalc")),0)}catch{}}catch(C){console.error("Failed to load notes",C),g([])}finally{v(!1)}}function he(C,T){g(R=>R.map(P=>{if(Number(P.id)!==Number(C))return P;const O=(Array.isArray(T)?T:[]).filter(_=>_&&typeof _.id=="number"&&typeof _.name=="string").map(_=>({id:_.id,label:{id:_.id,name:_.name}}));return{...P,noteLabels:O}}))}function tt(C,T){g(R=>R.map(P=>{if(Number(P.id)!==Number(C))return P;const O=(Array.isArray(T)?T:[]).filter(_=>_&&typeof _.url=="string").map(_=>({id:Number(_.id||Date.now()),url:String(_.url)}));return{...P,images:O}}))}function Ft(C,T){const R=(typeof T=="string"?T:"")||"";g(P=>P.map(O=>Number(O.id)!==Number(C)?O:{...O,viewerColor:R.length?R:null}))}function Kt(C,T){const R=(Array.isArray(T)?T:[]).filter(P=>P&&typeof P.id=="number"&&typeof P.name=="string").map(P=>({id:Number(P.id),name:String(P.name),parentId:P.parentId==null?null:Number(P.parentId)}));g(P=>P.map(O=>Number(O.id)!==Number(C)?O:{...O,viewerCollections:R}))}b.useEffect(()=>{p?V():g([])},[p]),b.useEffect(()=>{E.current=m},[m]),b.useEffect(()=>{It.current=rt},[rt]),b.useEffect(()=>{Ot.current=Mt},[Mt]);const Zt=!!(s&&s.sortKey==="default"&&s.groupBy==="none"&&s.smartFilter==="none"),$n=(()=>{try{return localStorage.getItem("prefs.dragBehavior")||"swap"}catch{return"swap"}})(),sn=Zt&&$n==="swap",A=Zt&&$n==="rearrange",ne=sn&&kt;b.useEffect(()=>{if(!sn)return;Wt(null),dn(null);const C=requestAnimationFrame(()=>{try{N1()}catch{}});return()=>{try{cancelAnimationFrame(C)}catch{}}},[sn,z,L]);function we(C){const T=st.get(C);return T?T.pinned?"pinned":"others":null}function Z(){if(U.current!=null){try{window.clearTimeout(U.current)}catch{}U.current=null}}const Ie=F_(iS(rM,{activationConstraint:{distance:6}}),iS(iM,{activationConstraint:{delay:160,tolerance:12}}));function Ve(C){var O;if(!sn)return;const T=Number(C.active.id);if(!Number.isFinite(T))return;tn.current=!0,pe(C.activatorEvent),ut(),fn(T);const R=me.current.get(T),P=(O=R==null?void 0:R.getBoundingClientRect)==null?void 0:O.call(R);P&&P.width>0&&P.height>0?Pr({width:P.width,height:P.height}):Pr(null),nn(null),I.current=null,Z(),Jt(!0)}function Rt(C){var D;if(!sn)return;const T=Number(C.active.id),R=(D=C.over)==null?void 0:D.id,P=R==null?NaN:Number(R);if(!Number.isFinite(T))return;if(!Number.isFinite(P)||T===P){(I.current!=null||wn!=null)&&(I.current=null,Z(),wn!=null&&nn(null));return}const O=we(T),_=we(P);if(!O||!_||O!==_){I.current!=null&&(I.current=null,Z(),nn(null));return}I.current!==P&&(I.current=P,Z(),nn(null),U.current=window.setTimeout(()=>{I.current===P&&nn(P)},380))}function be(){Z(),I.current=null,tn.current=!1,zt(),Ce(),fn(null),nn(null),Jt(!1),Pr(null)}b.useEffect(()=>{const C=document.documentElement;return sn&&jt!=null?C.classList.add("is-note-swap-dragging"):C.classList.remove("is-note-swap-dragging"),()=>{try{C.classList.remove("is-note-swap-dragging")}catch{}}},[sn,jt]);function qe(C){sn&&be()}function Dt(C){if(!sn)return;const T=Number(C.active.id),R=wn!=null?Number(wn):NaN,P=Number.isFinite(T)?we(T):null;if(P){const O=P==="pinned"?Xe.current:Tt.current;if(O){const _=Array.from(O.querySelectorAll(".notes-masonry-col"));K.current={section:P,heights:_.map(D=>D.getBoundingClientRect().height)}}}be(),!(!Number.isFinite(T)||!Number.isFinite(R)||T===R||!P)&&we(R)===P&&g(O=>{const _=O.findIndex(ae=>Number(ae==null?void 0:ae.id)===T),D=O.findIndex(ae=>Number(ae==null?void 0:ae.id)===R);if(_<0||D<0||!!O[_].pinned!=!!O[D].pinned)return O;const F=[...O],ie=F[_];return F[_]=F[D],F[D]=ie,requestAnimationFrame(()=>{try{vf(F)}catch{}}),F})}const st=b.useMemo(()=>{const C=new Map;for(const T of m){const R=Number(T==null?void 0:T.id);Number.isFinite(R)&&C.set(R,T)}return C},[m]),ft=(C,T)=>Math.max(0,Math.min(T,Math.floor(C)));function yt(C){const T=new Map;for(const R of C){const P=me.current.get(R);P&&T.set(R,P.getBoundingClientRect())}return T}function bt(C,T){const R=[];for(const[P,O]of C.entries()){const _=me.current.get(P);if(!_)continue;const D=_.getBoundingClientRect(),F=O.left-D.left,ie=O.top-D.top;F===0&&ie===0||R.push({el:_,dx:F,dy:ie})}if(R.length){for(const P of R)P.el.style.transition="none",P.el.style.transform=`translate(${P.dx}px, ${P.dy}px)`;document.body.getBoundingClientRect();for(const P of R){const O=P.el;O.style.transition=`transform ${T}ms cubic-bezier(.2,.9,.2,1)`,O.style.transform="";const _=()=>{try{O.style.transition="",O.removeEventListener("transitionend",_)}catch{}};O.addEventListener("transitionend",_)}}}function mt(){const C=Pe.current;if(!C.length){Ge.current=[],Y.current=null;return}const T=Ge.current,R=new Array(C.length),P=[];try{for(let O=0;O=D.left&&C<=D.left+D.width&&T>=D.top&&T<=D.top+D.height)return _}let P=-1,O=Number.POSITIVE_INFINITY;for(let _=0;_P&&(P=F,R=O)}return{idx:R,area:P}}function Yt(C,T,R){const P=C.filter(D=>Number(D)!==Number(T)),O=ft(R,P.length),_=[];for(let D=0;DD!=="spacer").map(D=>Number(D)).filter(D=>Number.isFinite(D))}function Pt(C){const T=Pe.current,R=T.indexOf("spacer");if(R<0)return;const P=ft(C,T.length-1);if(P===R)return;const O=Ct(T,R,P),_=yt(O),D=[...T];D.splice(R,1),D.splice(P,0,"spacer");const F=Math.max(150,Math.min(650,le("rearrange")));Le.current={before:_,ms:F},Se(D)}b.useLayoutEffect(()=>{if(G==null)return;try{mt()}catch{}const C=Le.current;if(C){Le.current=null;try{bt(C.before,C.ms)}catch{}}},[G,We]);function ln(){wt.current=!1,ce.current=null,ot.current=null,it.current=null,Ge.current=[],Y.current=null,Be.current=!1,ge.current=2,De.current=1;try{document.documentElement.classList.remove("is-note-rearrange-dragging")}catch{}if(S(),Ye.current!=null){try{cancelAnimationFrame(Ye.current)}catch{}Ye.current=null}}function wi(){fe(null),Ue(null),Se([]),ln();try{requestAnimationFrame(()=>{try{window.dispatchEvent(new Event("notes-grid:recalc")),window.dispatchEvent(new Event("resize"))}catch{}})}catch{}}function $i(C){if(!C)return!1;try{return!!C.closest('button, a, input, textarea, select, [contenteditable="true"], .more-menu, .dropdown, .color-palette')}catch{return!1}}function Hc(C){var O;const T=me.current.get(C),R=(O=T==null?void 0:T.dataset)==null?void 0:O.__rowspan,P=R?Number(R):NaN;return Number.isFinite(P)&&P>0?P:2}function us(C,T){if(C===T)return!0;if(!C||!T||C.length!==T.length)return!1;for(let R=0;R1);for(let _=0;_[]);const O=10,_=P.map(ae=>ae.left).sort((ae,ye)=>ae-ye),D=[];for(const ae of _){const ye=D[D.length-1];(D.length===0||Math.abs(ae-ye)>O)&&D.push(ae)}const F=Math.max(T,D.length,1),ie=Array.from({length:F},()=>[]);for(const ae of P){let ye=0,$e=1/0;for(let lt=0;ltae.sort((ye,$e)=>ye.top-$e.top).map(ye=>ye.id))}function N1(){if(sn)try{const C=E1(Xe.current),T=E1(Tt.current);C&&Wt(R=>us(R,C)?R:C),T&&dn(R=>us(R,T)?R:T)}catch{}}b.useEffect(()=>{if(!sn){Wt(null),dn(null);return}const C=window.setTimeout(()=>{N1()},0);return()=>{try{clearTimeout(C)}catch{}}},[sn,m]);const T1=b.useMemo(()=>{try{const C=Math.max(1,Number(z)||1),T=rt&&rt.length?rt.length:0;return Math.max(C,T===C?T:0,1)}catch{return 1}},[sn,rt,z]),A1=b.useMemo(()=>{try{const C=Math.max(1,Number(L)||1),T=Mt&&Mt.length?Mt.length:0;return Math.max(C,T===C?T:0,1)}catch{return 1}},[sn,Mt,L]),pa=b.useMemo(()=>!ne||!rt?null:C1(rt,T1),[ne,rt,T1,st]),ma=b.useMemo(()=>!ne||!Mt?null:C1(Mt,A1),[ne,Mt,A1,st]);function bo(C){if(!C)return 0;if(C instanceof Date)return C.getTime();const T=Date.parse(String(C));return Number.isFinite(T)?T:0}function M1(C){const T=s||Ks;if(T.sortKey==="default")return C;const R=T.sortDir==="asc"?1:-1,P=[...C];return P.sort((O,_)=>{if(T.sortKey==="createdAt")return(bo(O.createdAt)-bo(_.createdAt))*R;if(T.sortKey==="updatedAt")return(bo(O.updatedAt)-bo(_.updatedAt))*R;if(T.sortKey==="title"){const D=String(O.title||"").trim(),F=String(_.title||"").trim(),ie=D.localeCompare(F,void 0,{sensitivity:"base"});return ie!==0?ie*R:(bo(O.createdAt)-bo(_.createdAt))*-1}return 0}),P}function I1(C){const T=new Date(C),R=(T.getDay()+6)%7;return T.setHours(0,0,0,0),T.setDate(T.getDate()-R),T.getTime()}function R1(C){const T=s||Ks;if(T.groupBy==="none")return[{key:"all",title:"",notes:C,sortMs:0}];const R=new Map;if(T.groupBy==="week"){const O=I1(new Date),_=O-7*24*60*60*1e3;for(const F of C){const ie=bo(F.createdAt),ae=I1(new Date(ie||0));let ye="older",$e="Older",ke=0;ae>=O?(ye="thisWeek",$e="This week",ke=O):ae>=_&&(ye="lastWeek",$e="Last week",ke=_);const lt=R.get(ye)||{title:$e,notes:[],sortMs:ke};lt.notes.push(F),R.set(ye,lt)}return["thisWeek","lastWeek","older"].filter(F=>R.has(F)).map(F=>({key:F,title:R.get(F).title,notes:R.get(F).notes,sortMs:R.get(F).sortMs}))}if(T.groupBy==="month"){for(const _ of C){const D=bo(_.createdAt),F=new Date(D||0),ie=F.getFullYear(),ae=F.getMonth(),ye=`${ie}-${String(ae+1).padStart(2,"0")}`,$e=F.toLocaleString(void 0,{month:"long",year:"numeric"}),ke=new Date(ie,ae,1).getTime(),lt=R.get(ye)||{title:$e,notes:[],sortMs:ke};lt.notes.push(_),R.set(ye,lt)}const P=Array.from(R.entries()).map(([_,D])=>({key:_,title:D.title,notes:D.notes,sortMs:D.sortMs})),O=T.sortKey==="createdAt"&&T.sortDir==="asc"?1:-1;return P.sort((_,D)=>(_.sortMs-D.sortMs)*O),P}return[{key:"all",title:"",notes:C,sortMs:0}]}b.useEffect(()=>{if(Me.current){Me.current=!1;return}requestAnimationFrame(()=>{try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}})},[t,e,i,m,s==null?void 0:s.groupBy,s==null?void 0:s.sortKey,s==null?void 0:s.sortDir,s==null?void 0:s.smartFilter]),b.useEffect(()=>{if(!p)return;const C=(()=>{try{return FA().deviceKey}catch{return null}})();let T=null;try{const P=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/events?token=${encodeURIComponent(p)}`;T=new WebSocket(P),T.onmessage=O=>{try{const _=JSON.parse(String(O.data||"{}"));if(!_||!_.type)return;switch(_.type){case"note-created":V();break;case"notes-reordered":{const D=_.payload||{},ie=(Array.isArray(D.ids)?D.ids:[]).map(ae=>Number(ae)).filter(ae=>Number.isFinite(ae));if(!ie.length)break;try{localStorage.setItem("notesOrder",JSON.stringify(ie))}catch{}g(ae=>{const ye=new Map;for(const He of ae){const et=Number(He==null?void 0:He.id);Number.isFinite(et)&&ye.set(et,He)}const $e=new Set,ke=[];for(const He of ie){const et=ye.get(He);et&&(ke.push(et),$e.add(He))}const lt=[];for(const He of ae){const et=Number(He==null?void 0:He.id);(!Number.isFinite(et)||!$e.has(et))&<.push(He)}return[...lt,...ke]});break}case"note-deleted":{const D=_.payload||{},F=Number(D.noteId);Number.isFinite(F)&&g(ie=>ie.filter(ae=>Number(ae.id)!==F));break}case"note-images-changed":{const D=_.payload||{},F=Number(D.noteId);if(!Number.isFinite(F))break;(async()=>{try{const ie=await fetch(`/api/notes/${F}/images`,{headers:{Authorization:`Bearer ${p}`}});if(!ie.ok)return;const ae=await ie.json(),ye=Array.isArray(ae==null?void 0:ae.images)?ae.images:[];tt(F,ye)}catch{}})();break}case"note-color-changed":{const D=_.payload||{},F=Number(D.noteId);if(!Number.isFinite(F))break;const ie=typeof D.color=="string"?String(D.color):"";Ft(F,ie);break}case"note-collections-changed":{const D=_.payload||{},F=Number(D.noteId);if(!Number.isFinite(F))break;const ie=Array.isArray(D.collections)?D.collections:[];Kt(F,ie);break}case"note-collection-changed":{V();break}case"note-shared":V();break;case"note-unshared":{const D=Number(_.noteId||_.payload&&_.payload.noteId);Number.isFinite(D)&&g(F=>F.filter(ie=>Number(ie.id)!==D));break}case"collab-removed":{const D=Number(_.noteId||_.payload&&_.payload.noteId),F=Number(_.userId||_.payload&&_.payload.userId);Number.isFinite(D)&&Number.isFinite(F)&&g(ie=>ie.map(ae=>{if(Number(ae.id)!==D)return ae;const $e=(Array.isArray(ae.collaborators)?ae.collaborators:[]).filter(ke=>{const lt=ke&&(ke.user||{});return(typeof lt.id=="number"?Number(lt.id):typeof ke.userId=="number"?Number(ke.userId):void 0)!==F});return{...ae,collaborators:$e}}));break}case"user-photo-updated":{const D=_.payload||{},F=Number(D.userId),ie=String(D.userImageUrl||"");Number.isFinite(F)&&g(ae=>ae.map(ye=>{const $e=ye.owner||null,ke=$e&&$e.id===F?{...$e,userImageUrl:ie}:$e,He=(Array.isArray(ye.collaborators)?ye.collaborators:[]).map(et=>{const Et=et&&(et.user||{});return typeof Et.id=="number"&&Number(Et.id)===F?{...et,user:{...Et,userImageUrl:ie}}:et});return{...ye,owner:ke,collaborators:He}}));break}case"user-prefs-updated":{const D=_.payload||{},F=typeof D.deviceKey=="string"&&D.deviceKey?String(D.deviceKey):null;if(F&&C&&F!==C)break;try{if(typeof D.noteWidth=="number"){document.documentElement.style.setProperty("--note-card-width",`${Number(D.noteWidth)}px`);try{localStorage.setItem("prefs.noteWidth",String(Number(D.noteWidth)))}catch{}}if(typeof D.checklistTextSize=="number"){document.documentElement.style.setProperty("--checklist-text-size",`${Number(D.checklistTextSize)}px`);try{localStorage.setItem("prefs.checklistTextSize",String(Number(D.checklistTextSize)))}catch{}}if(typeof D.noteLineSpacing=="number"){document.documentElement.style.setProperty("--note-line-height",String(Number(D.noteLineSpacing)));try{localStorage.setItem("prefs.noteLineSpacing",String(Number(D.noteLineSpacing)))}catch{}}if(typeof D.imageThumbSize=="number"){document.documentElement.style.setProperty("--image-thumb-size",`${Number(D.imageThumbSize)}px`);try{localStorage.setItem("prefs.imageThumbSize",String(Number(D.imageThumbSize)))}catch{}}if(typeof D.fontFamily=="string"&&D.fontFamily){document.documentElement.style.setProperty("--app-font-family",String(D.fontFamily));try{localStorage.setItem("prefs.fontFamily",String(D.fontFamily))}catch{}}}catch{}try{window.dispatchEvent(new Event("notes-grid:recalc")),window.dispatchEvent(new Event("resize"))}catch{}break}}}catch{}}}catch{}return()=>{try{T&&T.close()}catch{}}},[p]),b.useRef(null),b.useEffect(()=>{const C=new WeakSet,T=new WeakMap;let R=null,P=null;function O(){if(wt.current)return;const ie=(()=>{try{const En=window.matchMedia,hr=!!(En&&(En("(pointer: coarse)").matches||En("(any-pointer: coarse)").matches)),Bn=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,ai=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight,ds=Math.min(Bn,ai);if(hr){if(ds<=600)return"phone";if(ds<=1024)return ai>=Bn?"tablet-portrait":"tablet-landscape"}return"desktop"}catch{return"desktop"}})();ie!==N.current&&(N.current=ie,M(ie));const ae=getComputedStyle(document.documentElement);let ye=parseInt(ae.getPropertyValue("--note-card-width"))||300;const $e=parseInt(ae.getPropertyValue("--gap"))||16,ke=document.querySelector(".main-area"),lt=ke?ke.clientWidth:0,He=document.querySelector(".notes-area"),et=He?He.clientWidth:0,Et=document.querySelector(".sidebar"),Gt=Et?Et.clientWidth:parseInt(ae.getPropertyValue("--sidebar-width"))||220,Zn=window.innerWidth-Gt-64,er=Math.max(lt,et,Zn,0),li=Array.from(document.querySelectorAll(".notes-area .notes-grid, .notes-area .notes-masonry")),Ds=document.querySelector(".notes-area")||document.querySelector(".main-area")||document.body,tr=Ds.getBoundingClientRect(),nr=Math.floor(tr.right),wf=parseInt(getComputedStyle(Ds).paddingRight||"0")||0;for(const En of li){const hr=getComputedStyle(En),Bn=parseInt(hr.getPropertyValue("--gap"))||$e,ai=Math.floor(En.getBoundingClientRect().left),ds=nr-wf,Un=Math.max(0,ds-ai),Bi=Math.max(0,Math.min(er,Un)),Ui=Math.max(1,Math.floor((Bi+Bn)/(ye+Bn)));let Hn=Ui,ko=ye;if(ie==="phone"){const $1=(()=>{try{const Dj=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,Oj=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight;return Dj>Oj}catch{return!1}})(),Ij=$1?120:140,Rj=$1?4:2;let Wc=Math.floor((Un+Bn)/(Ij+Bn));Wc=Math.max(2,Math.min(Rj,Wc||0)),Hn=Wc,ko=Math.max(110,Math.floor((Un-Math.max(0,Wc-1)*Bn)/Wc))}else ie==="tablet-portrait"?Hn=Math.max(2,Math.min(3,Ui)):ie==="tablet-landscape"&&(Hn=Math.max(3,Math.min(4,Ui)));ie==="phone"?En.style.setProperty("--note-card-width",`${ko}px`):En.style.removeProperty("--note-card-width");const Aj=Hn*ko+Math.max(0,Hn-1)*Bn,Mj=Math.min(Aj,Un);Number(En.dataset.__cols||"0")!==Hn&&(En.style.setProperty("--cols",String(Hn)),En.dataset.__cols=String(Hn)),En.style.width=`${Mj}px`;try{En===Xe.current?W.current!==Hn&&(W.current=Hn,X(Hn)):En===Tt.current&&te.current!==Hn&&(te.current=Hn,H(Hn))}catch{}}try{window.__notesGridDebug={cardWidth:ye,gap:$e,availMain:lt,availArea:et,availFallback:Zn,avail:er,grids:li.map(En=>{const hr=getComputedStyle(En),Bn=parseInt(hr.getPropertyValue("--gap"))||$e,ai=Math.floor(En.getBoundingClientRect().left),ds=nr-wf,Un=Math.max(0,ds-ai),Bi=Math.max(0,Math.min(er,Un)),Ui=Math.max(1,Math.floor((Bi+Bn)/(ye+Bn))),Hn=Math.min(Ui*ye+Math.max(0,Ui-1)*Bn,Un);return{left:ai,rightEdge:ds,availableToRight:Un,gridAvail:Bi,gridCols:Ui,gridTotal:Hn}}),autoFit:localStorage.getItem("prefs.autoFitColumns")==="1",anim:{resizeMs:le("resize"),swapMs:le("swap"),rearrangeMs:le("rearrange")},showGuides:En=>{for(const hr of li)if(En){const Bn=parseInt(getComputedStyle(hr).getPropertyValue("--gap"))||$e,ai=ye+Bn,Un=(parseInt(ae.getPropertyValue("--row"))||8)+Bn,Bi=`repeating-linear-gradient(to right, rgba(255,255,255,0.08) 0, rgba(255,255,255,0.08) 1px, transparent 1px, transparent ${ai}px)`,Ui=`repeating-linear-gradient(to bottom, rgba(255,255,255,0.08) 0, rgba(255,255,255,0.08) 1px, transparent 1px, transparent ${Un}px)`;hr.style.backgroundImage=`${Bi}, ${Ui}`,hr.style.backgroundSize=`${ai}px 100%, 100% ${Un}px`,hr.style.backgroundPosition="left top, left top"}else hr.style.backgroundImage="",hr.style.backgroundSize=""}}}catch{}try{for(const En of li){const hr=getComputedStyle(En),Bn=parseInt(hr.getPropertyValue("--row"))||parseInt(ae.getPropertyValue("--row"))||8,ai=parseInt(hr.getPropertyValue("--gap"))||$e,ds=Array.from(En.querySelectorAll("[data-note-id]"));for(const Un of ds){const Bi=Un.querySelector(".note-card"),Ui=Bi?Bi.getBoundingClientRect().height:Un.getBoundingClientRect().height,Hn=Math.max(1,Math.ceil((Ui+ai)/(Bn+ai)));Un.dataset.__rowspan!==String(Hn)&&(Un.style.gridRowEnd=`span ${Hn}`,Un.dataset.__rowspan=String(Hn));try{if(R){const ko=Bi||Un;C.has(ko)||(R.observe(ko),C.add(ko),Bi&&T.set(ko,Un))}}catch{}}}}catch{}}function _(){wt.current||P==null&&(P=requestAnimationFrame(()=>{P=null,O()}))}O();const D=document.querySelector(".main-area")||document.body,F=new ResizeObserver(()=>_());F.observe(D);try{R=new ResizeObserver(ie=>{try{if(wt.current)return;const ae=getComputedStyle(document.documentElement),ye=parseInt(ae.getPropertyValue("--gap"))||16,$e=parseInt(getComputedStyle(document.body).getPropertyValue("--gap"))||ye;for(const ke of ie){const lt=ke.target,He=T.get(lt)||lt,et=He!=null&&He.closest?He.closest(".notes-grid, .notes-masonry"):null,Et=getComputedStyle(et||He),Gt=parseInt(Et.getPropertyValue("--row"))||parseInt(ae.getPropertyValue("--row"))||8,Jr=parseInt(Et.getPropertyValue("--gap"))||$e,Zn=lt.getBoundingClientRect().height,er=Math.max(1,Math.ceil((Zn+Jr)/(Gt+Jr)));He.dataset.__rowspan!==String(er)&&(He.style.gridRowEnd=`span ${er}`,He.dataset.__rowspan=String(er))}}catch{_()}})}catch{}return window.addEventListener("resize",_),window.addEventListener("notes-grid:recalc",_),()=>{F.disconnect(),window.removeEventListener("resize",_),window.removeEventListener("notes-grid:recalc",_);try{P!=null&&cancelAnimationFrame(P)}catch{}try{R&&R.disconnect()}catch{}}},[]);const D1=b.useMemo(()=>{var T;const C=new Map;for(let R=0;R{const C=Array.isArray(t)?t:[],T=e==null?null:Number(e),R=(i||"").trim().toLowerCase(),P=ke=>{if(!C.length)return!0;const lt=(ke.noteLabels||[]).map(He=>{var et;return(et=He.label)==null?void 0:et.id}).filter(He=>typeof He=="number");return C.some(He=>lt.includes(He))},O=ke=>!!(!R||String(ke.title||"").toLowerCase().includes(R)||String(ke.body||"").toLowerCase().includes(R)||(Array.isArray(ke.items)?ke.items:[]).some(et=>String(et.content||"").toLowerCase().includes(R))||(Array.isArray(ke.noteLabels)?ke.noteLabels:[]).some(et=>{var Et;return String(((Et=et.label)==null?void 0:Et.name)||"").toLowerCase().includes(R)})),_=ke=>{var et;if(T==null||!Number.isFinite(T))return!0;const lt=Array.isArray(ke.viewerCollections)?ke.viewerCollections:[];for(const Et of lt){const Gt=Et&&typeof Et.id=="number"?Number(Et.id):null;if(Gt!=null&&Number.isFinite(Gt)&&Number(Gt)===Number(T))return!0}const He=Array.isArray(ke.noteCollections)?ke.noteCollections:[];for(const Et of He){const Gt=Et&&typeof Et.collectionId=="number"?Number(Et.collectionId):typeof((et=Et==null?void 0:Et.collection)==null?void 0:et.id)=="number"?Number(Et.collection.id):null;if(Gt!=null&&Number.isFinite(Gt)&&Number(Gt)===Number(T))return!0}return!1},D=r==null?null:Number(r),F=ke=>{var lt,He;if(D==null||!Number.isFinite(D))return!0;try{const et=typeof((lt=ke==null?void 0:ke.owner)==null?void 0:lt.id)=="number"?Number(ke.owner.id):typeof(ke==null?void 0:ke.ownerId)=="number"?Number(ke.ownerId):null;if(et!=null&&Number(et)===Number(D))return!0;const Et=Array.isArray(ke==null?void 0:ke.collaborators)?ke.collaborators:[];for(const Gt of Et){const Jr=typeof((He=Gt==null?void 0:Gt.user)==null?void 0:He.id)=="number"?Number(Gt.user.id):typeof(Gt==null?void 0:Gt.userId)=="number"?Number(Gt.userId):null;if(Jr!=null&&Number(Jr)===Number(D))return!0}}catch{}return!1},ie=m.filter(ke=>ke.pinned).filter(P).filter(_).filter(F).filter(O),ae=m.filter(ke=>!ke.pinned).filter(P).filter(_).filter(F).filter(O),ye=M1(ie),$e=M1(ae);return{pinned:ye,others:$e,pinnedGroups:R1(ye),otherGroups:R1($e)}},[m,t,e,r,i,s]),Vc=b.useMemo(()=>{var ie,ae;const C=[],T=Array.isArray(n)?n:[],R=T.length?T.map(ye=>String(ye.name||"")).filter(Boolean).join(" / "):"";R&&C.push({id:"collection",text:`Collection: ${R}`,onClear:()=>{try{u&&u([])}catch{}}});const P=Array.isArray(t)?t:[];if(P.length){const ye=new Map;for(const ke of m){const lt=Array.isArray(ke==null?void 0:ke.noteLabels)?ke.noteLabels:[];for(const He of lt){const et=typeof((ie=He==null?void 0:He.label)==null?void 0:ie.id)=="number"?Number(He.label.id):null,Et=typeof((ae=He==null?void 0:He.label)==null?void 0:ae.name)=="string"?String(He.label.name):null;et!=null&&Et&&ye.set(et,Et)}}const $e=P.map(ke=>ye.get(Number(ke))||`#${Number(ke)}`).join(", ");C.push({id:"labels",text:`Labels: ${$e}`,onClear:()=>{try{l&&l([])}catch{}}})}const O=r==null?null:Number(r);if(O!=null&&Number.isFinite(O)){let ye="";try{e:for(const $e of m){const ke=$e==null?void 0:$e.owner;if(ke&&typeof ke.id=="number"&&Number(ke.id)===O){ye=String(ke.name||ke.email||O);break e}const lt=Array.isArray($e==null?void 0:$e.collaborators)?$e.collaborators:[];for(const He of lt){const et=He==null?void 0:He.user;if(et&&typeof et.id=="number"&&Number(et.id)===O){ye=String(et.name||et.email||O);break e}}}}catch{}C.push({id:"collaborator",text:`With: ${ye||String(O)}`,onClear:()=>{try{a&&a(null)}catch{}}})}const _=(i||"").trim();_&&C.push({id:"search",text:`Search: ${_}`,onClear:()=>{try{d&&d("")}catch{}}});const D=s||Ks;if(D.sortKey!=="default"){const ye=D.sortKey==="createdAt"?`Date created: ${D.sortDir==="asc"?"Ascending":"Descending"}`:D.sortKey==="updatedAt"?`Date updated: ${D.sortDir==="asc"?"Ascending":"Descending"}`:D.sortKey==="title"?`Alphabetical: ${D.sortDir==="asc"?"A→Z":"Z→A"}`:`Sort: ${String(D.sortKey)}`;C.push({id:"sort",text:ye,onClear:()=>{try{f&&f({...D,sortKey:"default",sortDir:Ks.sortDir})}catch{}}})}if(D.groupBy&&D.groupBy!=="none"&&C.push({id:"group",text:`Grouping: ${D.groupBy==="week"?"Week":D.groupBy==="month"?"Month":String(D.groupBy)}`,onClear:()=>{try{f&&f({...D,groupBy:"none"})}catch{}}}),D.smartFilter&&D.smartFilter!=="none"){const ye=D.smartFilter==="dueSoon"?"Filter: Due soon":D.smartFilter==="leastAccessed"?"Filter: Least accessed":D.smartFilter==="mostEdited"?"Filter: Most edited":D.smartFilter==="atRisk"?"Filter: At risk":`Filter: ${String(D.smartFilter)}`;C.push({id:"smartFilter",text:ye,onClear:()=>{try{f&&f({...D,smartFilter:"none"})}catch{}}})}const F=C.length>0;return{title:R||"All notes",chips:C,show:!0,hasAnyFilter:F}},[n,t,r,i,m,s,l,a,u,d,f]);b.useEffect(()=>{if(!sn)return;const C=K.current;if(!C)return;K.current=null;const T=C.section==="pinned"?Xe.current:Tt.current;if(!T)return;const R=Array.from(T.querySelectorAll(".notes-masonry-col"));if(!R.length)return;const P=C.heights,O=R.map(D=>D.getBoundingClientRect().height),_=le("swap");for(let D=0;D{try{F.style.transition="",F.style.height="",F.removeEventListener("transitionend",ae)}catch{}};F.addEventListener("transitionend",ae)}},[sn,m]);function gf(C,T){const R=new Map;me.current.forEach((P,O)=>{P&&R.set(O,P.getBoundingClientRect())}),Me.current=!0,g(P=>{const O=[...P],_=O[C],D=O[T];return!_||!D?P:(O[C]=D,O[T]=_,O)}),requestAnimationFrame(()=>{const P=new Map;me.current.forEach((O,_)=>{O&&P.set(_,O.getBoundingClientRect())}),P.forEach((O,_)=>{const D=R.get(_),F=me.current.get(_);if(!D||!F)return;const ie=D.left-O.left,ae=D.top-O.top;if(ie===0&&ae===0)return;F.style.transition="none",F.style.transform=`translate(${ie}px, ${ae}px)`,F.getBoundingClientRect(),F.style.transition=`transform ${le("swap")}ms ease-in-out`,F.style.transform="";const ye=()=>{try{F.style.transition="",F.removeEventListener("transitionend",ye)}catch{}};F.addEventListener("transitionend",ye)})})}function yf(C,T){const R=new Map;me.current.forEach((P,O)=>{P&&R.set(O,P.getBoundingClientRect())}),Me.current=!0,g(P=>{const O=[...P];if(C<0||T<0||C>=O.length||T>=O.length)return P;const[_]=O.splice(C,1);return O.splice(T,0,_),O}),requestAnimationFrame(()=>{const P=new Map;me.current.forEach((O,_)=>{O&&P.set(_,O.getBoundingClientRect())}),P.forEach((O,_)=>{const D=R.get(_),F=me.current.get(_);if(!D||!F)return;const ie=D.left-O.left,ae=D.top-O.top;if(ie===0&&ae===0)return;F.style.transition="none",F.style.transform=`translate(${ie}px, ${ae}px)`,F.getBoundingClientRect(),F.style.transition=`transform ${le("rearrange")}ms ease-in-out`,F.style.transform="";const ye=()=>{try{F.style.transition="",F.removeEventListener("transitionend",ye)}catch{}};F.addEventListener("transitionend",ye)})})}async function vf(C){try{localStorage.setItem("notesOrder",JSON.stringify(C.map(T=>T.id)))}catch{}if(p)try{const T=C.map(P=>P.id),R=await fetch("/api/notes/order",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({ids:T})});if(!R.ok)throw new Error(await R.text())}catch(T){console.error("Failed to persist note order to server",T)}}const xo=b.useCallback(C=>{if(C&&C.type==="filter:collection"&&typeof C.collectionId=="number"){try{a&&a(null)}catch{}try{c&&c(Number(C.collectionId),typeof C.collectionName=="string"?String(C.collectionName):void 0)}catch{}return}if(C&&C.type==="filter:collaborator"&&typeof C.userId=="number"){try{a&&a(Number(C.userId))}catch{}return}if(C&&C.type==="filter:labels"){const T=typeof C.labelId=="number"?Number(C.labelId):null;if(T!=null&&Number.isFinite(T)){try{l&&l([T])}catch{}return}if(Array.isArray(C.labelIds)){const R=C.labelIds.map(P=>Number(P)).filter(P=>Number.isFinite(P));try{l&&l(R)}catch{}return}}if(C&&C.type==="labels"&&typeof C.noteId=="number"&&Array.isArray(C.labels)){he(C.noteId,C.labels);return}if(C&&C.type==="images"&&typeof C.noteId=="number"&&Array.isArray(C.images)){tt(C.noteId,C.images);return}if(C&&C.type==="color"&&typeof C.noteId=="number"){Ft(C.noteId,typeof C.color=="string"?String(C.color):"");return}if(C&&C.type==="collections"&&typeof C.noteId=="number"&&Array.isArray(C.collections)){Kt(C.noteId,C.collections);return}if(C&&C.type==="collection"&&typeof C.noteId=="number"){V();return}V()},[p,s,i,t,e,l,a,c]);b.useEffect(()=>{!y&&p&&x(!0)},[y,p]);const Lg=C=>{try{const T=Number((C==null?void 0:C.cardSpan)||1);return Math.max(1,Math.min(k==="phone"?2:3,Number.isFinite(T)?T:1))}catch{return 1}},_g=sn&&jt!=null&&st.get(Number(jt))||null,L1=A&&G!=null&&st.get(Number(G))||null;function _1(C,T,R,P,O){if(!A||Ae||!Zt||C.button!=null&&C.button!==0||$i(C.target)||Ee.current!=null||Be.current)return;const _=me.current.get(Number(T));if(!_)return;const D=_.getBoundingClientRect();if(!D||D.width<10||D.height<10)return;const F=String(C.pointerType||"mouse"),ie=C.pointerId??1,ae=C.currentTarget;if(ce.current={noteId:Number(T),section:R,sectionIds:Array.isArray(P)?P.map(ye=>Number(ye)).filter(ye=>Number.isFinite(ye)):[],startClientX:C.clientX,startClientY:C.clientY,lastClientX:C.clientX,lastClientY:C.clientY,pointerId:ie,pointerType:F,touchArmed:!1,longPressTimerId:null,captureEl:ae},ot.current={x:C.clientX,y:C.clientY},it.current=D,De.current=Math.max(1,Math.min(3,Number(O)||1)),ge.current=(()=>{var ke;const ye=(ke=_==null?void 0:_.dataset)==null?void 0:ke.__rowspan,$e=ye?Number(ye):NaN;return Number.isFinite($e)&&$e>0?$e:2})(),F==="touch"){const ye=window.setTimeout(()=>{var Et,Gt;const $e=ce.current;if(!$e||Number($e.pointerId)!==Number(ie)||Number($e.noteId)!==Number(T)||wt.current||Ee.current!=null||Be.current)return;const ke=typeof $e.lastClientX=="number"?$e.lastClientX:$e.startClientX,lt=typeof $e.lastClientY=="number"?$e.lastClientY:$e.startClientY,He=ke-$e.startClientX,et=lt-$e.startClientY;if(He*He+et*et>9){ce.current=null;return}$e.touchArmed=!0;try{(Gt=(Et=$e.captureEl)==null?void 0:Et.setPointerCapture)==null||Gt.call(Et,$e.pointerId)}catch{}zg($e.sectionIds)},220);ce.current.longPressTimerId=ye;return}}function zg(C){const T=ce.current,R=it.current;if(!T||!R)return;const P=T.noteId,O=Math.max(0,C.findIndex(_=>Number(_)===Number(P)));wt.current=!0,Jt(!0),fe(P),Ue(T.section),Se(Yt(C,P,O));try{document.documentElement.classList.add("is-note-rearrange-dragging")}catch{}T.pointerType==="touch"&&$(),requestAnimationFrame(()=>{const _=xt.current;_&&(_.style.transform="translate(0px, 0px) scale(1.03)")})}function z1(C,T){const R=it.current,P=ot.current;if(!R||!P)return{dx:0,dy:0};let O=C-P.x,_=T-P.y;const D=Y.current;if(!D)return{dx:O,dy:_};const F=18,ie=D.left-F,ae=D.right-R.width+F,ye=D.top-F,$e=D.bottom-R.height+F,ke=R.left+O,lt=R.top+_,He=Math.min(Math.max(ke,ie),ae),et=Math.min(Math.max(lt,ye),$e);return O=He-R.left,_=et-R.top,{dx:O,dy:_}}function Tj(C,T){const R=it.current,P=ot.current,O=xt.current;if(!R||!P||!O)return;const{dx:_,dy:D}=z1(C,T);O.style.transform=`translate(${_}px, ${D}px) scale(1.03)`}return b.useEffect(()=>{if(!A)return;const C=R=>{const P=ce.current;if(!P||P.pointerId!=null&&R.pointerId!=null&&Number(R.pointerId)!==Number(P.pointerId))return;P.pointerType==="touch"&&(P.lastClientX=R.clientX,P.lastClientY=R.clientY);const O=Ee.current,_=P.sectionIds;if(!(!_||!_.length)){if(O==null&&!wt.current){const D=R.clientX-P.startClientX,F=R.clientY-P.startClientY;if(P.pointerType==="touch"){const ie=Math.abs(D),ae=Math.abs(F),ye=4;if(!P.touchArmed){if(ie>ye||ae>ye){try{P.longPressTimerId!=null&&window.clearTimeout(P.longPressTimerId)}catch{}ce.current=null}return}zg(_)}else{if(D*D+F*F<6*6)return;zg(_)}}if(wt.current){try{R.preventDefault()}catch{}Ye.current==null&&(Ye.current=requestAnimationFrame(()=>{Ye.current=null,Tj(R.clientX,R.clientY);const D=Pe.current,F=Ge.current;if(!D.length||F.length!==D.length)return;const ie=it.current,ae=ot.current;if(!ie||!ae)return;const{dx:ye,dy:$e}=z1(R.clientX,R.clientY),ke=ie.left+ye,lt=ie.top+$e,He={left:ke,top:lt,right:ke+ie.width,bottom:lt+ie.height},et=ke+ie.width/2,Et=lt+ie.height/2,Gt=on(He),Jr=Gt.idx>=0&&Gt.area>0?Gt.idx:Qt(et,Et);if(Jr<0)return;const Zn=ze.current;if(Jr===Zn)return;const er=F[Zn]||null,li=F[Jr]||null;if(!er||!li)return;const Ds=li.cx-er.cx,tr=li.cy-er.cy,nr=(li.cx+er.cx)/2,wf=(li.cy+er.cy)/2,En=(et-nr)*Ds+(Et-wf)*tr,hr=Math.sqrt(Ds*Ds+tr*tr)||1,Bn=P.pointerType==="touch"?10:6;En<=Bn*hr||Pt(Jr)}))}}},T=R=>{const P=ce.current;if(!P||P.pointerId!=null&&R.pointerId!=null&&Number(R.pointerId)!==Number(P.pointerId))return;try{P.longPressTimerId!=null&&window.clearTimeout(P.longPressTimerId)}catch{}if(!wt.current||Ee.current==null){ce.current=null;return}const O=Number(Ee.current),_=Ke.current,D=Pe.current,F=D.indexOf("spacer"),ie=F>=0?D[F+1]:null,ae=typeof ie=="number"?Number(ie):null;Be.current=!0;const ye=xt.current,$e=it.current,ke=Math.max(150,Math.min(650,le("rearrange"))),lt=oe.current,He=lt?lt.getBoundingClientRect():null;if(ye&&$e&&He){const Et=He.left-$e.left,Gt=He.top-$e.top;ye.style.transition=`transform ${ke}ms cubic-bezier(.2,.9,.2,1)`,ye.style.transform=`translate(${Et}px, ${Gt}px) scale(1)`}_&&g(Et=>{var li,Ds;const Gt=Et.findIndex(tr=>Number(tr==null?void 0:tr.id)===O);if(Gt<0)return Et;const Jr=Et[Gt];if(!!Jr.pinned!=(_==="pinned"))return Et;const Zn=[...Et];Zn.splice(Gt,1);let er=Zn.length;if(ae!=null){const tr=Zn.findIndex(nr=>Number(nr==null?void 0:nr.id)===ae);tr>=0&&(er=tr)}else if(_==="pinned"){let tr=-1;for(let nr=0;nr{try{vf(Zn)}catch{}}),Zn});const et=()=>{try{ye&&(ye.style.transition="",ye.removeEventListener("transitionend",et))}catch{}Jt(!1),wi()};ye?(ye.addEventListener("transitionend",et),window.setTimeout(et,ke+80)):et()};return window.addEventListener("pointermove",C,{capture:!0,passive:!1}),window.addEventListener("pointerup",T,{capture:!0}),window.addEventListener("pointercancel",T,{capture:!0}),()=>{try{window.removeEventListener("pointermove",C,{capture:!0})}catch{}try{window.removeEventListener("pointerup",T,{capture:!0})}catch{}try{window.removeEventListener("pointercancel",T,{capture:!0})}catch{}}},[A,Ae,p]),y&&!w?h.jsx("div",{children:"Loading notes…"}):h.jsxs("section",{className:"notes-area",children:[h.jsxs("div",{className:"take-note-sticky",children:[h.jsx(HJ,{onCreated:V,openRequest:{nonce:_t,mode:at},activeCollection:At}),Vc.show&&h.jsx("div",{className:"grid-context",role:"region","aria-label":"Current view",children:h.jsxs("div",{className:"grid-context__text",children:[h.jsxs("div",{className:"grid-context__title-row",children:[h.jsx("div",{className:"grid-context__title",children:Vc.title}),!!o&&!!Vc.hasAnyFilter&&h.jsx("button",{type:"button",className:"grid-context__clear",onClick:()=>{try{o()}catch{}},"aria-label":"Clear all filters",title:"Clear",children:"Clear"})]}),!!((F1=Vc.chips)!=null&&F1.length)&&h.jsx("div",{className:"grid-context__chips","aria-label":"Active filters",children:Vc.chips.map(C=>h.jsxs("span",{className:"grid-chip",children:[h.jsx("span",{className:"grid-chip__text",title:String(C.text||""),children:String(C.text||"")}),typeof C.onClear=="function"&&h.jsx("button",{type:"button",className:"grid-chip__clear",onClick:()=>{try{C.onClear()}catch{}},"aria-label":`Clear ${String(C.text||"filter")}`,title:"Clear",children:"×"})]},String(C.id)))})]})})]}),Q&&h.jsx("div",{className:"mobile-add-backdrop","aria-hidden":"true",onPointerDown:()=>Je(!1)}),h.jsxs("div",{className:"mobile-add-note","aria-label":"Add note",children:[Q&&h.jsxs("div",{className:"mobile-add-menu",role:"menu","aria-label":"Create",children:[h.jsxs("button",{type:"button",className:"mobile-add-menu-item",role:"menuitem",onClick:()=>Bt("text"),children:[h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:h.jsx("path",{fill:"currentColor",d:"M6 2h9l5 5v15a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Zm8 1.5V8h4.5L14 3.5ZM7 11h10v1.6H7V11Zm0 4h10v1.6H7V15Zm0 4h7v1.6H7V19Z"})}),h.jsx("span",{children:"New note"})]}),h.jsxs("button",{type:"button",className:"mobile-add-menu-item",role:"menuitem",onClick:()=>Bt("checklist"),children:[h.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24","aria-hidden":!0,focusable:"false",children:h.jsx("path",{fill:"currentColor",d:"M9.2 7.2 7.9 5.9 6 7.8 5.1 6.9 4 8l2 2 3.2-3.2ZM10.5 8H20v1.6h-9.5V8Zm-1.3 6.2-1.3-1.3L6 14.8l-.9-.9L4 15l2 2 3.2-3.2ZM10.5 15H20v1.6h-9.5V15Z"})}),h.jsx("span",{children:"New checklist"})]})]}),h.jsx("button",{type:"button",className:"mobile-add-fab","aria-haspopup":"menu","aria-expanded":Q,onClick:()=>Je(C=>!C),children:"+"})]}),h.jsx(WJ,{open:ct!=null,mode:ct||"text",onClose:()=>nt(null),onCreated:V,activeCollection:At}),sn?h.jsxs(F3,{sensors:Ie,collisionDetection:J_,onDragStart:Ve,onDragOver:Rt,onDragEnd:Dt,onDragCancel:qe,children:[O1.length>0&&h.jsxs("div",{className:"notes-section",children:[h.jsx("h4",{className:"section-title",children:"Pinned"}),j1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid notes-grid--swap",ref:Xe,children:C.notes.map(T=>{const R=Lg(T),P=(O,_)=>{O?me.current.set(_,O):me.current.delete(_)};return h.jsx(SN,{note:T,setItemRef:P,style:{gridColumn:`span ${R}`},isDragSource:jt!=null&&Number(jt)===Number(T.id),isDragTarget:wn!=null&&Number(wn)===Number(T.id),disabled:Ae,onChange:xo},T.id)})})]},C.key))]}),h.jsx("div",{className:"notes-section",children:P1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid notes-grid--swap",ref:Tt,children:C.notes.map(T=>{const R=Lg(T),P=(O,_)=>{O?me.current.set(_,O):me.current.delete(_)};return h.jsx(SN,{note:T,setItemRef:P,style:{gridColumn:`span ${R}`},isDragSource:jt!=null&&Number(jt)===Number(T.id),isDragTarget:wn!=null&&Number(wn)===Number(T.id),disabled:Ae,onChange:xo},T.id)})})]},C.key))}),h.jsx(s4,{children:_g?h.jsx("div",{className:"note-drag-ghost",style:{width:rn?`${rn.width}px`:(()=>{const C=Lg(_g);return`calc(${C} * var(--note-card-width) + ${Math.max(0,C-1)} * var(--gap))`})(),height:rn?`${rn.height}px`:void 0},children:h.jsx(El,{note:_g,onChange:xo})}):null})]}):h.jsxs(h.Fragment,{children:[O1.length>0&&h.jsxs("div",{className:"notes-section",children:[h.jsx("h4",{className:"section-title",children:"Pinned"}),j1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid"+(kt?" notes-grid--manual":""),ref:Xe,children:A&&je==="pinned"&&We.length?We.map((T,R)=>{var F;if(T==="spacer")return h.jsx("div",{ref:oe,className:"note-rearrange-spacer",style:{gridColumn:`span ${De.current}`,gridRowEnd:`span ${ge.current}`,height:`${((F=it.current)==null?void 0:F.height)||0}px`}},"spacer");const P=Number(T),O=st.get(P);if(!O)return null;const _=Math.max(1,Math.min(3,Number(O.cardSpan||1))),D=(pa==null?void 0:pa.get(Number(O.id)))||null;return h.jsx("div",{"data-note-id":O.id,style:D?{gridColumnStart:D.colStart,gridColumnEnd:`span ${D.colSpan}`,gridRowStart:D.rowStart,gridRowEnd:`span ${D.rowSpan}`}:{gridColumn:`span ${_}`},ref:ie=>{ie?me.current.set(O.id,ie):me.current.delete(O.id)},children:h.jsx(El,{note:O,onChange:xo})},O.id)}):C.notes.map(T=>{const R=D1.get(Number(T.id))??-1,P=Math.max(1,Math.min(3,Number(T.cardSpan||1))),O=(pa==null?void 0:pa.get(Number(T.id)))||null,_=C.notes.map(F=>Number(F.id)).filter(F=>Number.isFinite(F)),D=A?{draggable:!1,onPointerDown:F=>_1(F,Number(T.id),"pinned",_,P)}:{draggable:Zt&&!Ae,onDragStart:F=>{Zt&&(xe.current=Number(T.id),F.dataTransfer.setData("text/plain",String(R)),se.current=R)},onDragEnd:()=>{Zt&&(se.current=null,xe.current=null)},onDragOver:F=>{if(Zt){F.preventDefault();try{const ie=localStorage.getItem("prefs.dragBehavior")||"swap",ae=se.current;if(ie==="rearrange"&&ae!==null&&ae!==R){const ye=Date.now(),ke=F.currentTarget.getBoundingClientRect(),lt=Math.min(28,Math.floor(ke.height*.2)),He=Math.min(20,Math.floor(ke.width*.2)),et=F.clientY>ke.top+lt&&F.clientYke.left+He&&F.clientXGt&&(yf(ae,R),q.current=ye,se.current=R)}}catch{}}},onDrop:F=>{if(!Zt)return;F.preventDefault();const ie=Number(F.dataTransfer.getData("text/plain")),ae=Number.isFinite(ie)?ie:se.current??-1,ye=R;try{(localStorage.getItem("prefs.dragBehavior")||"swap")==="rearrange"?yf(ae,ye):gf(ae,ye)}catch{gf(ae,ye)}requestAnimationFrame(()=>{try{vf(E.current)}catch{}}),se.current=null,xe.current=null}};return h.jsx("div",{"data-note-id":T.id,style:O?{gridColumnStart:O.colStart,gridColumnEnd:`span ${O.colSpan}`,gridRowStart:O.rowStart,gridRowEnd:`span ${O.rowSpan}`}:{gridColumn:`span ${P}`},ref:F=>{F?me.current.set(T.id,F):me.current.delete(T.id)},...D,children:h.jsx(El,{note:T,onChange:xo})},T.id)})})]},C.key))]}),h.jsx("div",{className:"notes-section",children:P1.map(C=>h.jsxs("div",{children:[C.title&&C.key!=="all"&&h.jsx("h5",{className:"section-title",style:{marginTop:10,marginBottom:6,color:"var(--muted)"},children:C.title}),h.jsx("div",{className:"notes-grid"+(kt?" notes-grid--manual":""),ref:Tt,children:A&&je==="others"&&We.length?We.map((T,R)=>{var F;if(T==="spacer")return h.jsx("div",{ref:oe,className:"note-rearrange-spacer",style:{gridColumn:`span ${De.current}`,gridRowEnd:`span ${ge.current}`,height:`${((F=it.current)==null?void 0:F.height)||0}px`}},"spacer");const P=Number(T),O=st.get(P);if(!O)return null;const _=Math.max(1,Math.min(3,Number(O.cardSpan||1))),D=(ma==null?void 0:ma.get(Number(O.id)))||null;return h.jsx("div",{"data-note-id":O.id,style:D?{gridColumnStart:D.colStart,gridColumnEnd:`span ${D.colSpan}`,gridRowStart:D.rowStart,gridRowEnd:`span ${D.rowSpan}`}:{gridColumn:`span ${_}`},ref:ie=>{ie?me.current.set(O.id,ie):me.current.delete(O.id)},children:h.jsx(El,{note:O,onChange:xo})},O.id)}):C.notes.map(T=>{const R=D1.get(Number(T.id))??-1,P=Math.max(1,Math.min(3,Number(T.cardSpan||1))),O=(ma==null?void 0:ma.get(Number(T.id)))||null,_=C.notes.map(F=>Number(F.id)).filter(F=>Number.isFinite(F)),D=A?{draggable:!1,onPointerDown:F=>_1(F,Number(T.id),"others",_,P)}:{draggable:Zt&&!Ae,onDragStart:F=>{Zt&&(xe.current=Number(T.id),F.dataTransfer.setData("text/plain",String(R)),se.current=R)},onDragEnd:()=>{Zt&&(se.current=null,xe.current=null)},onDragOver:F=>{if(Zt){F.preventDefault();try{const ie=localStorage.getItem("prefs.dragBehavior")||"swap",ae=se.current;if(ie==="rearrange"&&ae!==null&&ae!==R){const ye=Date.now(),ke=F.currentTarget.getBoundingClientRect(),lt=Math.min(28,Math.floor(ke.height*.2)),He=Math.min(20,Math.floor(ke.width*.2)),et=F.clientY>ke.top+lt&&F.clientYke.left+He&&F.clientXGt&&(yf(ae,R),q.current=ye,se.current=R)}}catch{}}},onDrop:F=>{if(!Zt)return;F.preventDefault();const ie=Number(F.dataTransfer.getData("text/plain")),ae=Number.isFinite(ie)?ie:se.current??-1,ye=R;try{(localStorage.getItem("prefs.dragBehavior")||"swap")==="rearrange"?yf(ae,ye):gf(ae,ye)}catch{gf(ae,ye)}requestAnimationFrame(()=>{try{vf(E.current)}catch{}}),se.current=null,xe.current=null}};return h.jsx("div",{"data-note-id":T.id,style:O?{gridColumnStart:O.colStart,gridColumnEnd:`span ${O.colSpan}`,gridRowStart:O.rowStart,gridRowEnd:`span ${O.rowSpan}`}:{gridColumn:`span ${P}`},ref:F=>{F?me.current.set(T.id,F):me.current.delete(T.id)},...D,children:h.jsx(El,{note:T,onChange:xo})},T.id)})})]},C.key))})]}),A&&L1&&it.current?zn.createPortal(h.jsx("div",{ref:xt,className:"note-rearrange-overlay",style:{position:"fixed",left:`${it.current.left}px`,top:`${it.current.top}px`,width:`${it.current.width}px`,height:`${it.current.height}px`},children:h.jsx("div",{className:"note-rearrange-overlay-inner",children:h.jsx(El,{note:L1,onChange:xo})})}),document.body):null]})}function YJ({onClose:t}){const{register:e,uploadPhoto:n}=Sr(),[r,i]=b.useState(""),[s,o]=b.useState(""),[l,a]=b.useState(""),[c,u]=b.useState(""),[d,f]=b.useState(""),[p,m]=b.useState(!1),[g,y]=b.useState(null),[v,w]=b.useState(null),[x,E]=b.useState(null),[k,M]=b.useState(null),N=l.length>0&&s===l;function z({ok:W}){return W?h.jsx("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":!0,focusable:"false",style:{color:"#4caf50"},children:h.jsx("path",{d:"M20 6L9 17l-5-5",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",strokeLinejoin:"round"})}):h.jsx("svg",{viewBox:"0 0 24 24",width:18,height:18,"aria-hidden":!0,focusable:"false",style:{color:"#ff6e6e"},children:h.jsx("path",{d:"M6 6L18 18M18 6L6 18",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",strokeLinejoin:"round"})})}async function X(W){if(W.preventDefault(),y(null),!c.trim()||!r.trim()||!s){y("All fields are required");return}if(s!==l){y("Passwords do not match");return}m(!0);try{await e(r,s,c,d||void 0);try{if(x){const te=await H(x);await n(te)}}catch{}t()}catch(te){y((te==null?void 0:te.message)??String(te))}finally{m(!1)}}function L(W){var ue;const te=((ue=W.target.files)==null?void 0:ue[0])||null;E(te);try{M(de=>{try{de&&URL.revokeObjectURL(de)}catch{}return te?URL.createObjectURL(te):null})}catch{M(null)}}b.useEffect(()=>()=>{try{k&&URL.revokeObjectURL(k)}catch{}},[k]);function H(W){return new Promise((te,ue)=>{const de=new FileReader;de.onload=()=>te(String(de.result||"")),de.onerror=Ae=>ue(Ae),de.readAsDataURL(W)})}return b.useEffect(()=>{fetch("/api/config").then(W=>W.json()).then(W=>w(!!W.userRegistrationEnabled)).catch(()=>w(!1))},[]),h.jsx("div",{className:"image-dialog-backdrop",children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Register"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsxs("form",{onSubmit:X,children:[h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Name",value:c,onChange:W=>u(W.target.value),className:"image-url-input",required:!0})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Email",value:r,onChange:W=>i(W.target.value),className:"image-url-input"})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Password",type:"password",value:s,onChange:W=>o(W.target.value),className:"image-url-input"})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Confirm password",type:"password",value:l,onChange:W=>a(W.target.value),className:"image-url-input"})}),h.jsxs("div",{style:{marginBottom:12},children:[h.jsx("label",{style:{display:"block",marginBottom:6},children:"Profile photo (optional):"}),h.jsx("input",{type:"file",accept:"image/*",onChange:L}),k&&h.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10},children:[h.jsx("img",{src:k,alt:"Selected profile preview",style:{width:64,height:64,borderRadius:"50%",objectFit:"cover"}}),h.jsx("div",{style:{color:"var(--muted)",fontSize:13},children:"Preview"})]})]}),h.jsx("div",{style:{display:"grid",rowGap:6,margin:"10px 2px 12px"},"aria-live":"polite",children:h.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--muted)"},children:[h.jsx(z,{ok:N})," ",h.jsx("span",{children:"Passwords match"})]})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Invite token (optional)",value:d,onChange:W=>f(W.target.value),className:"image-url-input"})}),v===!1&&h.jsx("div",{style:{color:"salmon",marginBottom:8},children:"Registration is currently disabled — you must provide a valid invite token."}),g&&h.jsx("div",{style:{color:"salmon",marginBottom:8},children:g}),h.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[h.jsx("button",{type:"button",className:"btn",onClick:t,children:"Cancel"}),h.jsx("button",{type:"submit",className:"btn",disabled:p||!c.trim()||!r.trim()||!s||!l||!N,children:p?"Registering...":"Register"})]})]})]})})}function qJ({onClose:t}){const{login:e}=Sr(),[n,r]=b.useState(""),[i,s]=b.useState(""),[o,l]=b.useState(!1),[a,c]=b.useState(null);async function u(d){d.preventDefault(),c(null),l(!0);try{await e(n,i),t()}catch(f){c((f==null?void 0:f.message)??String(f))}finally{l(!1)}}return h.jsx("div",{className:"image-dialog-backdrop",children:h.jsxs("div",{className:"image-dialog",role:"dialog","aria-modal":!0,children:[h.jsxs("div",{className:"dialog-header",children:[h.jsx("strong",{children:"Sign in"}),h.jsx("button",{className:"icon-close",onClick:t,children:"✕"})]}),h.jsxs("form",{onSubmit:u,children:[h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Email",value:n,onChange:d=>r(d.target.value),className:"image-url-input"})}),h.jsx("div",{style:{marginBottom:8},children:h.jsx("input",{placeholder:"Password",type:"password",value:i,onChange:d=>s(d.target.value),className:"image-url-input"})}),a&&h.jsx("div",{style:{color:"salmon",marginBottom:8},children:a}),h.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[h.jsx("button",{type:"button",className:"btn",onClick:t,children:"Cancel"}),h.jsx("button",{type:"submit",className:"btn",disabled:o,children:o?"Signing in...":"Sign in"})]})]})]})})}function CN({selectedLabelIds:t,selectedCollectionId:e,collectionStack:n,selectedCollaboratorId:r,searchQuery:i,sortConfig:s,onClearAllFilters:o,onSetSelectedLabelIds:l,onSetSelectedCollaboratorId:a,onSelectCollectionById:c,onSetCollectionStack:u,onSetSearchQuery:d,onSortConfigChange:f}){const{user:p}=Sr(),[m,g]=b.useState(!1),[y,v]=b.useState(!1),[w,x]=b.useState(null);return b.useEffect(()=>{fetch("/api/config").then(E=>E.json()).then(E=>x(!!E.userRegistrationEnabled)).catch(()=>x(!1))},[]),p?h.jsx(KJ,{selectedLabelIds:t||[],selectedCollectionId:e??null,collectionStack:n||[],selectedCollaboratorId:r??null,searchQuery:i,sortConfig:s,onClearAllFilters:o,onSetSelectedLabelIds:l,onSetSelectedCollaboratorId:a,onSelectCollectionById:c,onSetCollectionStack:u,onSetSearchQuery:d,onSortConfigChange:f}):h.jsxs("div",{style:{padding:24,display:"flex",flexDirection:"column",alignItems:"center"},children:[h.jsx("h2",{children:"Welcome to FreemanNotes"}),h.jsx("p",{children:"Please sign in to view and manage your notes."}),h.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[h.jsx("button",{className:"btn",onClick:()=>v(!0),children:"Sign in"}),w&&h.jsx("button",{className:"btn",onClick:()=>g(!0),children:"Create account"})]}),m&&h.jsx(YJ,{onClose:()=>g(!1)}),y&&h.jsx(qJ,{onClose:()=>v(!1)})]})}function JJ(){return h.jsx(y_,{children:h.jsx(m_,{children:h.jsx(GJ,{})})})}function GJ(){const{user:t,token:e}=Sr(),[n,r]=B.useState([]),[i,s]=B.useState(null),[o,l]=B.useState([]),[a,c]=B.useState(!1),[u,d]=B.useState(!1),[f,p]=B.useState(!1),[m,g]=B.useState(""),[y,v]=B.useState(Ks),w=o.length?Number(o[o.length-1].id):null,x=B.useRef([]),E=B.useRef(!1),k=B.useRef(0),M=B.useRef(!1),N=B.useCallback(()=>{r([]),s(null),l([]),g(""),v(Ks)},[]),z=B.useCallback(async(H,W)=>{const te=Number(H);if(Number.isFinite(te)){if(!e){l([{id:te,name:String(W||te)}]);return}try{const ue=await fetch(`/api/collections/${encodeURIComponent(String(te))}/breadcrumb`,{headers:{Authorization:`Bearer ${e}`}});if(!ue.ok)throw new Error(await ue.text());const de=await ue.json(),me=(Array.isArray(de==null?void 0:de.breadcrumb)?de.breadcrumb:[]).map(q=>({id:Number(q.id),name:String(q.name||"")})).filter(q=>Number.isFinite(q.id)&&q.name.length);me.length?l(me):l([{id:te,name:String(W||te)}])}catch{l([{id:te,name:String(W||te)}])}}},[e]),X=H=>{r(W=>W.includes(H)?W.filter(te=>te!==H):[...W,H])},L=()=>r([]);return B.useEffect(()=>{var W,te;function H(){try{const ue=window.matchMedia,de=!!(ue&&(ue("(pointer: coarse)").matches||ue("(any-pointer: coarse)").matches)),Ae=window.visualViewport&&typeof window.visualViewport.width=="number"?window.visualViewport.width:window.innerWidth,me=window.visualViewport&&typeof window.visualViewport.height=="number"?window.visualViewport.height:window.innerHeight,q=Math.min(Ae,me);p(de&&q<=600)}catch{p(!1)}}H(),window.addEventListener("resize",H);try{(W=window.visualViewport)==null||W.addEventListener("resize",H)}catch{}try{(te=window.visualViewport)==null||te.addEventListener("scroll",H)}catch{}return()=>{var ue,de;window.removeEventListener("resize",H);try{(ue=window.visualViewport)==null||ue.removeEventListener("resize",H)}catch{}try{(de=window.visualViewport)==null||de.removeEventListener("scroll",H)}catch{}}},[]),B.useEffect(()=>{if(f&&!E.current){E.current=!0;try{history.replaceState({...history.state||{},__freemannotes_base:!0},document.title),history.pushState({...history.state||{},__freemannotes_sentinel:!0},document.title)}catch{}}},[f]),B.useEffect(()=>{if(!f)return;const H=x.current,W=de=>{var Ae;try{const me=de==null?void 0:de.detail,q=String((me==null?void 0:me.id)||""),se=me==null?void 0:me.onBack;if(!q||typeof se!="function")return;for(let xe=H.length-1;xe>=0;xe--)((Ae=H[xe])==null?void 0:Ae.id)===q&&H.splice(xe,1);H.push({id:q,onBack:se});try{history.pushState({...history.state||{},__freemannotes_overlay:!0,__freemannotes_overlay_id:q},document.title)}catch{}}catch{}},te=de=>{var Ae;try{const me=de==null?void 0:de.detail,q=String((me==null?void 0:me.id)||"");if(!q)return;for(let se=H.length-1;se>=0;se--)((Ae=H[se])==null?void 0:Ae.id)===q&&H.splice(se,1)}catch{}},ue=de=>{var Ae;try{if(!f)return;if(H.length>0){const se=H.pop();try{(Ae=se==null?void 0:se.onBack)==null||Ae.call(se)}catch{}return}const me=de==null?void 0:de.state;if(!me||!!me.__freemannotes_base){if(M.current){M.current=!1;return}const se=Date.now(),xe=k.current||0;if(k.current=se,se-xe<=800&&window.confirm("Exit FreemanNotes?")){M.current=!0,window.setTimeout(()=>{var Je;try{history.back()}catch{}try{(Je=window.close)==null||Je.call(window)}catch{}},0);return}window.setTimeout(()=>{try{history.go(1)}catch{}},0)}}catch{}};return window.addEventListener("freemannotes:back/register",W),window.addEventListener("freemannotes:back/unregister",te),window.addEventListener("popstate",ue),()=>{window.removeEventListener("freemannotes:back/register",W),window.removeEventListener("freemannotes:back/unregister",te),window.removeEventListener("popstate",ue)}},[f]),B.useEffect(()=>{if(!u)return;function H(W){W.key==="Escape"&&d(!1)}return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[u]),B.useEffect(()=>{f||d(!1)},[f]),B.useEffect(()=>{if(!f)return;let H=!1,W=!1,te=!1,ue=0,de=0,Ae=0,me=0,q=null,se=null;const xe=140,Me=24,Q=28,Je=80,_t=360,J=8,at=1.2;function $t(ze){const Pe=ze;if(!Pe)return!1;try{return Pe.closest(".note-card")?!!Pe.closest('input, textarea, select, button, a, [contenteditable="true"]'):!!Pe.closest('input, textarea, select, button, a, [contenteditable="true"], .take-note-expanded, .image-dialog, .prefs-dialog')}catch{return!1}}function ct(ze,Pe,it,ot,xt){if($t(it))return!1;let oe=!1;try{const Y=it;oe=!!(Y&&Y.closest&&Y.closest(".note-card"))}catch{}const Ye=!u&&ze<=xe&&(!oe||ze<=Me),Ge=u&&ze<=_t;return!Ye&&!Ge?!1:(ue=ze,de=Pe,Ae=ze,me=Pe,H=!0,q=ot,se=xt,W=Ye,te=Ge,!0)}function nt(ze,Pe,it){Ae=ze,me=Pe;const ot=Ae-ue,xt=me-de;if(Math.abs(xt)>Je&&Math.abs(xt)>Math.abs(ot)*at){H=!1,q=null,se=null,W=!1,te=!1;return}if(it&&Math.abs(ot)>J&&Math.abs(ot)>Math.abs(xt)*at&&it(),W&&ot>=Q&&Math.abs(xt)<=Je){d(!0),H=!1,q=null,se=null,W=!1,te=!1;return}if(te&&ot<=-34&&Math.abs(xt)<=Je){d(!1),H=!1,q=null,se=null,W=!1,te=!1;return}}function At(ze){var Pe,it;try{if(ze.pointerType!=="touch"||q!=null||$t(ze.target)||!ct(ze.clientX,ze.clientY,ze.target,ze.pointerId,null))return;try{(it=(Pe=ze.target)==null?void 0:Pe.setPointerCapture)==null||it.call(Pe,ze.pointerId)}catch{}}catch{}}function Bt(ze){try{if(!H||q==null||ze.pointerId!==q)return;nt(ze.clientX,ze.clientY,()=>ze.preventDefault())}catch{}}function wt(ze){try{if(q==null||ze.pointerId!==q)return}catch{}H=!1,q=null,se=null,W=!1,te=!1}function ce(ze){try{if(se!=null||q!=null||!ze.touches||ze.touches.length!==1)return;const Pe=ze.touches[0];ct(Pe.clientX,Pe.clientY,ze.target,null,Pe.identifier)}catch{}}function Ee(ze){try{if(!H||se==null)return;const Pe=Array.from(ze.touches||[]).find(it=>it.identifier===se);if(!Pe)return;nt(Pe.clientX,Pe.clientY,()=>ze.preventDefault())}catch{}}function Ke(ze){try{if(se==null||Array.from(ze.touches||[]).some(it=>it.identifier===se))return}catch{}H=!1,q=null,se=null,W=!1,te=!1}return document.addEventListener("pointerdown",At,{capture:!0}),document.addEventListener("pointermove",Bt,{capture:!0,passive:!1}),document.addEventListener("pointerup",wt,{capture:!0}),document.addEventListener("pointercancel",wt,{capture:!0}),document.addEventListener("touchstart",ce,{capture:!0,passive:!0}),document.addEventListener("touchmove",Ee,{capture:!0,passive:!1}),document.addEventListener("touchend",Ke,{capture:!0}),document.addEventListener("touchcancel",Ke,{capture:!0}),()=>{document.removeEventListener("pointerdown",At,{capture:!0}),document.removeEventListener("pointermove",Bt,{capture:!0}),document.removeEventListener("pointerup",wt,{capture:!0}),document.removeEventListener("pointercancel",wt,{capture:!0}),document.removeEventListener("touchstart",ce,{capture:!0}),document.removeEventListener("touchmove",Ee,{capture:!0}),document.removeEventListener("touchend",Ke,{capture:!0}),document.removeEventListener("touchcancel",Ke,{capture:!0})}},[f,u]),t?h.jsxs("div",{className:"app-root"+(f?" phone":"")+(u?" drawer-open":""),children:[h.jsx(E_,{onToggleSidebar:()=>{f?d(H=>!H):c(H=>!H)},searchQuery:m,onSearchChange:g}),h.jsxs("div",{className:"app-body",children:[!f&&h.jsx(nS,{selectedLabelIds:n,onToggleLabel:X,onClearLabels:L,collapsed:a,collectionStack:o,onCollectionStackChange:l,sortConfig:y,onSortConfigChange:v}),h.jsx("main",{className:"main-area",children:h.jsx(CN,{selectedLabelIds:n,selectedCollectionId:w,collectionStack:o,selectedCollaboratorId:i,searchQuery:m,sortConfig:y,onClearAllFilters:N,onSetSelectedLabelIds:r,onSetSelectedCollaboratorId:s,onSelectCollectionById:z,onSetCollectionStack:l,onSetSearchQuery:g,onSortConfigChange:v})})]}),f&&h.jsxs(h.Fragment,{children:[u&&h.jsx("div",{className:"mobile-sidebar-backdrop",role:"button","aria-label":"Close menu",tabIndex:0,onClick:()=>d(!1),onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&d(!1)}}),h.jsx("div",{className:"mobile-sidebar-drawer"+(u?" open":""),"aria-hidden":!u,children:h.jsx(nS,{selectedLabelIds:n,onToggleLabel:X,onClearLabels:L,collapsed:!1,collectionStack:o,onCollectionStackChange:l,sortConfig:y,onSortConfigChange:v,onRequestClose:()=>d(!1)})})]})]}):h.jsx("div",{className:"app-root",style:{minHeight:"100vh"},children:h.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center"},children:h.jsx(CN,{})})})}function XJ(){try{const t=document.documentElement,e={"prefs.checklistSpacing":"--checklist-gap","prefs.checkboxSize":"--checklist-checkbox-size","prefs.checklistTextSize":"--checklist-text-size","prefs.noteWidth":"--note-card-width","prefs.imageThumbSize":"--image-thumb-size","prefs.fontFamily":"--app-font-family","prefs.noteLineSpacing":"--note-line-height"},n=new Set(["prefs.checklistSpacing","prefs.checkboxSize","prefs.checklistTextSize","prefs.noteWidth","prefs.imageThumbSize"]);Object.entries(e).forEach(([r,i])=>{const s=localStorage.getItem(r);s===null||s===""||(n.has(r)?/[^0-9.-]/.test(s)?t.style.setProperty(i,s):t.style.setProperty(i,`${s}px`):t.style.setProperty(i,s))});try{window.dispatchEvent(new Event("notes-grid:recalc"))}catch{}}catch(t){console.warn("Failed to apply saved prefs",t)}}XJ();try{"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(t=>{t.forEach(e=>{try{e.unregister()}catch{}})}).catch(()=>{})}catch{}const QJ=zA(document.getElementById("root"));QJ.render(h.jsx(JJ,{})); diff --git a/client-dist/index.html b/client-dist/index.html index 5419be5..71c59be 100644 --- a/client-dist/index.html +++ b/client-dist/index.html @@ -1,16 +1,15 @@ - - - - - - FreemanNotes - - - + + + + + + FreemanNotes — Phase 1 + + + - - -
    - - - + + +
    + + diff --git a/client/src/components/MoveToCollectionModal.tsx b/client/src/components/MoveToCollectionModal.tsx index 945c513..bb63bfb 100644 --- a/client/src/components/MoveToCollectionModal.tsx +++ b/client/src/components/MoveToCollectionModal.tsx @@ -200,6 +200,9 @@ export default function MoveToCollectionModal({ const data = await res.json(); const createdId = Number((data as any)?.collection?.id); if (Number.isFinite(createdId)) { + try { + window.dispatchEvent(new CustomEvent('collections:changed', { detail: { invalidateAll: true, reason: 'create', id: createdId } })); + } catch {} try { setCreatingName(''); } catch {} setBusy(false); await addTo(createdId); diff --git a/client/src/components/NoteCard.tsx b/client/src/components/NoteCard.tsx index 0cdf1ba..53c590c 100644 --- a/client/src/components/NoteCard.tsx +++ b/client/src/components/NoteCard.tsx @@ -346,6 +346,33 @@ export default function NoteCard({ const fileRef = useRef(null); const { token, user } = useAuth(); + React.useEffect(() => { + const onCollectionsChanged = (ev: Event) => { + try { + const ce = ev as CustomEvent; + const detail = ce?.detail || {}; + if (detail?.invalidateAll) { + setCollectionPathById({}); + return; + } + const ids = Array.isArray(detail?.ids) ? detail.ids : (Number.isFinite(Number(detail?.id)) ? [Number(detail.id)] : []); + if (!ids.length) return; + setCollectionPathById((prev) => { + const next = { ...prev }; + for (const id of ids) { + try { delete (next as any)[Number(id)]; } catch {} + } + return next; + }); + } catch {} + }; + + try { window.addEventListener('collections:changed', onCollectionsChanged as any); } catch {} + return () => { + try { window.removeEventListener('collections:changed', onCollectionsChanged as any); } catch {} + }; + }, []); + const neededCollectionIdsKey = React.useMemo(() => { try { const ids = viewerCollections diff --git a/client/src/components/Sidebar.tsx b/client/src/components/Sidebar.tsx index b79e405..a3dc301 100644 --- a/client/src/components/Sidebar.tsx +++ b/client/src/components/Sidebar.tsx @@ -218,6 +218,10 @@ export default function Sidebar({ }); if (!res.ok) throw new Error(await res.text()); try { setNewCollectionName(''); } catch {} + // New collections can affect breadcrumb paths and descendant display. + try { + window.dispatchEvent(new CustomEvent('collections:changed', { detail: { invalidateAll: true, reason: 'create' } })); + } catch {} await refreshCollections(); } catch (err) { window.alert('Failed to create collection: ' + String(err)); @@ -237,6 +241,10 @@ export default function Sidebar({ body: JSON.stringify({ name: next }), }); if (!res.ok) throw new Error(await res.text()); + // Notify other UI surfaces (e.g., note collection chips) to invalidate any cached paths. + try { + window.dispatchEvent(new CustomEvent('collections:changed', { detail: { invalidateAll: true, reason: 'rename', id: Number(id) } })); + } catch {} // Update stack display names if needed. try { const stack = Array.isArray(collectionStack) ? collectionStack : []; @@ -260,6 +268,10 @@ export default function Sidebar({ try { const res = await fetch(`/api/collections/${encodeURIComponent(String(id))}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } }); if (!res.ok) throw new Error(await res.text()); + // Deleting can invalidate any cached breadcrumb paths for this subtree. + try { + window.dispatchEvent(new CustomEvent('collections:changed', { detail: { invalidateAll: true, reason: 'delete', id: Number(id) } })); + } catch {} // If we deleted the current path (or an ancestor), pop back to root. try { const stack = Array.isArray(collectionStack) ? collectionStack : [];