@blankdotpage/cake 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +54 -0
  2. package/dist/cake/clipboard.d.ts +1 -0
  3. package/dist/cake/core/mapping/cursor-source-map.d.ts +32 -0
  4. package/dist/cake/core/runtime.d.ts +121 -0
  5. package/dist/cake/core/types.d.ts +42 -0
  6. package/dist/cake/dom/dom-map.d.ts +21 -0
  7. package/dist/cake/dom/dom-selection.d.ts +4 -0
  8. package/dist/cake/dom/render.d.ts +14 -0
  9. package/dist/cake/dom/types.d.ts +10 -0
  10. package/dist/cake/engine/cake-engine.d.ts +208 -0
  11. package/dist/cake/engine/selection/selection-geometry-dom.d.ts +23 -0
  12. package/dist/cake/engine/selection/selection-geometry.d.ts +23 -0
  13. package/dist/cake/engine/selection/selection-layout-dom.d.ts +30 -0
  14. package/dist/cake/engine/selection/selection-layout.d.ts +54 -0
  15. package/dist/cake/engine/selection/selection-navigation.d.ts +21 -0
  16. package/dist/cake/engine/selection/visible-text.d.ts +4 -0
  17. package/dist/cake/extensions/blockquote/blockquote.d.ts +2 -0
  18. package/dist/cake/extensions/bold/bold.d.ts +2 -0
  19. package/dist/cake/extensions/bundles.d.ts +2 -0
  20. package/dist/cake/extensions/combined-emphasis/combined-emphasis.d.ts +2 -0
  21. package/dist/cake/extensions/heading/heading.d.ts +2 -0
  22. package/dist/cake/extensions/image/image.d.ts +2 -0
  23. package/dist/cake/extensions/index.d.ts +13 -0
  24. package/dist/cake/extensions/italic/italic.d.ts +2 -0
  25. package/dist/cake/extensions/link/link-popover.d.ts +10 -0
  26. package/dist/cake/extensions/link/link.d.ts +2 -0
  27. package/dist/cake/extensions/list/list-ast.d.ts +50 -0
  28. package/dist/cake/extensions/list/list.d.ts +2 -0
  29. package/dist/cake/extensions/overlay-types.d.ts +31 -0
  30. package/dist/cake/extensions/pipe-link/pipe-link.d.ts +2 -0
  31. package/dist/cake/extensions/scrollbar/index.d.ts +2 -0
  32. package/dist/cake/extensions/strikethrough/strikethrough.d.ts +2 -0
  33. package/dist/cake/extensions/types.d.ts +5 -0
  34. package/dist/cake/index.d.ts +1 -0
  35. package/dist/cake/react/CakeEditor.d.ts +8 -0
  36. package/dist/cake/shared/platform.d.ts +2 -0
  37. package/dist/cake/shared/segmenter.d.ts +12 -0
  38. package/dist/cake/shared/url.d.ts +2 -0
  39. package/dist/cake/shared/word-break.d.ts +18 -0
  40. package/dist/cake/test/harness.d.ts +53 -0
  41. package/dist/codemirror/markdown-commands.d.ts +12 -0
  42. package/dist/editor.d.ts +83 -0
  43. package/dist/index.d.ts +4 -0
  44. package/dist/index.js +92 -0
  45. package/package.json +52 -0
package/dist/index.js ADDED
@@ -0,0 +1,92 @@
1
+ (function(q,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("react"),require("react-dom"),require("lucide-react"),require("turndown"),require("@codemirror/state")):typeof define=="function"&&define.amd?define(["exports","react","react-dom","lucide-react","turndown","@codemirror/state"],_):(q=typeof globalThis<"u"?globalThis:q||self,_(q.Cake={},q.require$$0,q.reactDom,q.lucideReact,q.TurndownService,q.state))})(this,function(q,_,rr,je,ir,lt){"use strict";var We={exports:{}},Oe={};/**
2
+ * @license React
3
+ * react-jsx-dev-runtime.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var xn;function or(){if(xn)return Oe;xn=1;var e=Symbol.for("react.fragment");return Oe.Fragment=e,Oe.jsxDEV=void 0,Oe}var Me={};/**
10
+ * @license React
11
+ * react-jsx-dev-runtime.development.js
12
+ *
13
+ * Copyright (c) Facebook, Inc. and its affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var kn;function sr(){return kn||(kn=1,process.env.NODE_ENV!=="production"&&function(){var e=_,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),s=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),g=Symbol.for("react.offscreen"),p=Symbol.iterator,k="@@iterator";function b(h){if(h===null||typeof h!="object")return null;var v=p&&h[p]||h[k];return typeof v=="function"?v:null}var w=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function u(h){{for(var v=arguments.length,B=new Array(v>1?v-1:0),U=1;U<v;U++)B[U-1]=arguments[U];E("error",h,B)}}function E(h,v,B){{var U=w.ReactDebugCurrentFrame,Y=U.getStackAddendum();Y!==""&&(v+="%s",B=B.concat([Y]));var X=B.map(function(V){return String(V)});X.unshift("Warning: "+v),Function.prototype.apply.call(console[h],console,X)}}var C=!1,L=!1,T=!1,A=!1,D=!1,j;j=Symbol.for("react.module.reference");function Z(h){return!!(typeof h=="string"||typeof h=="function"||h===r||h===o||D||h===i||h===c||h===d||A||h===g||C||L||T||typeof h=="object"&&h!==null&&(h.$$typeof===f||h.$$typeof===m||h.$$typeof===s||h.$$typeof===a||h.$$typeof===l||h.$$typeof===j||h.getModuleId!==void 0))}function K(h,v,B){var U=h.displayName;if(U)return U;var Y=v.displayName||v.name||"";return Y!==""?B+"("+Y+")":B}function z(h){return h.displayName||"Context"}function J(h){if(h==null)return null;if(typeof h.tag=="number"&&u("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof h=="function")return h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case r:return"Fragment";case n:return"Portal";case o:return"Profiler";case i:return"StrictMode";case c:return"Suspense";case d:return"SuspenseList"}if(typeof h=="object")switch(h.$$typeof){case a:var v=h;return z(v)+".Consumer";case s:var B=h;return z(B._context)+".Provider";case l:return K(h,h.render,"ForwardRef");case m:var U=h.displayName||null;return U!==null?U:J(h.type)||"Memo";case f:{var Y=h,X=Y._payload,V=Y._init;try{return J(V(X))}catch{return null}}}return null}var tt=Object.assign,st=0,ht,fe,te,de,Le,Re,Kt;function At(){}At.__reactDisabledLog=!0;function Yt(){{if(st===0){ht=console.log,fe=console.info,te=console.warn,de=console.error,Le=console.group,Re=console.groupCollapsed,Kt=console.groupEnd;var h={configurable:!0,enumerable:!0,value:At,writable:!0};Object.defineProperties(console,{info:h,log:h,warn:h,error:h,group:h,groupCollapsed:h,groupEnd:h})}st++}}function pn(){{if(st--,st===0){var h={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:tt({},h,{value:ht}),info:tt({},h,{value:fe}),warn:tt({},h,{value:te}),error:tt({},h,{value:de}),group:tt({},h,{value:Le}),groupCollapsed:tt({},h,{value:Re}),groupEnd:tt({},h,{value:Kt})})}st<0&&u("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var he=w.ReactCurrentDispatcher,ee;function pe(h,v,B){{if(ee===void 0)try{throw Error()}catch(Y){var U=Y.stack.trim().match(/\n( *(at )?)/);ee=U&&U[1]||""}return`
18
+ `+ee+h}}var Nt=!1,ne;{var gn=typeof WeakMap=="function"?WeakMap:Map;ne=new gn}function Ve(h,v){if(!h||Nt)return"";{var B=ne.get(h);if(B!==void 0)return B}var U;Nt=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=he.current,he.current=null,Yt();try{if(v){var V=function(){throw Error()};if(Object.defineProperty(V.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(V,[])}catch(yt){U=yt}Reflect.construct(h,[],V)}else{try{V.call()}catch(yt){U=yt}h.call(V.prototype)}}else{try{throw Error()}catch(yt){U=yt}h()}}catch(yt){if(yt&&U&&typeof yt.stack=="string"){for(var W=yt.stack.split(`
19
+ `),ot=U.stack.split(`
20
+ `),et=W.length-1,nt=ot.length-1;et>=1&&nt>=0&&W[et]!==ot[nt];)nt--;for(;et>=1&&nt>=0;et--,nt--)if(W[et]!==ot[nt]){if(et!==1||nt!==1)do if(et--,nt--,nt<0||W[et]!==ot[nt]){var mt=`
21
+ `+W[et].replace(" at new "," at ");return h.displayName&&mt.includes("<anonymous>")&&(mt=mt.replace("<anonymous>",h.displayName)),typeof h=="function"&&ne.set(h,mt),mt}while(et>=1&&nt>=0);break}}}finally{Nt=!1,he.current=X,pn(),Error.prepareStackTrace=Y}var xe=h?h.displayName||h.name:"",se=xe?pe(xe):"";return typeof h=="function"&&ne.set(h,se),se}function mn(h,v,B){return Ve(h,!1)}function Ce(h){var v=h.prototype;return!!(v&&v.isReactComponent)}function y(h,v,B){if(h==null)return"";if(typeof h=="function")return Ve(h,Ce(h));if(typeof h=="string")return pe(h);switch(h){case c:return pe("Suspense");case d:return pe("SuspenseList")}if(typeof h=="object")switch(h.$$typeof){case l:return mn(h.render);case m:return y(h.type,v,B);case f:{var U=h,Y=U._payload,X=U._init;try{return y(X(Y),v,B)}catch{}}}return""}var x=Object.prototype.hasOwnProperty,S={},I=w.ReactDebugCurrentFrame;function R(h){if(h){var v=h._owner,B=y(h.type,h._source,v?v.type:null);I.setExtraStackFrame(B)}else I.setExtraStackFrame(null)}function O(h,v,B,U,Y){{var X=Function.call.bind(x);for(var V in h)if(X(h,V)){var W=void 0;try{if(typeof h[V]!="function"){var ot=Error((U||"React class")+": "+B+" type `"+V+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof h[V]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw ot.name="Invariant Violation",ot}W=h[V](v,V,U,B,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(et){W=et}W&&!(W instanceof Error)&&(R(Y),u("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",U||"React class",B,V,typeof W),R(null)),W instanceof Error&&!(W.message in S)&&(S[W.message]=!0,R(Y),u("Failed %s type: %s",B,W.message),R(null))}}}var P=Array.isArray;function M(h){return P(h)}function F(h){{var v=typeof Symbol=="function"&&Symbol.toStringTag,B=v&&h[Symbol.toStringTag]||h.constructor.name||"Object";return B}}function N(h){try{return $(h),!1}catch{return!0}}function $(h){return""+h}function H(h){if(N(h))return u("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",F(h)),$(h)}var G=w.ReactCurrentOwner,kt={key:!0,ref:!0,__self:!0,__source:!0},ft,St,pt;pt={};function gt(h){if(x.call(h,"ref")){var v=Object.getOwnPropertyDescriptor(h,"ref").get;if(v&&v.isReactWarning)return!1}return h.ref!==void 0}function dt(h){if(x.call(h,"key")){var v=Object.getOwnPropertyDescriptor(h,"key").get;if(v&&v.isReactWarning)return!1}return h.key!==void 0}function ge(h,v){if(typeof h.ref=="string"&&G.current&&v&&G.current.stateNode!==v){var B=J(G.current.type);pt[B]||(u('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',J(G.current.type),h.ref),pt[B]=!0)}}function rt(h,v){{var B=function(){ft||(ft=!0,u("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",v))};B.isReactWarning=!0,Object.defineProperty(h,"key",{get:B,configurable:!0})}}function Gt(h,v){{var B=function(){St||(St=!0,u("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",v))};B.isReactWarning=!0,Object.defineProperty(h,"ref",{get:B,configurable:!0})}}var Xt=function(h,v,B,U,Y,X,V){var W={$$typeof:t,type:h,key:v,ref:B,props:V,_owner:X};return W._store={},Object.defineProperty(W._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(W,"_self",{configurable:!1,enumerable:!1,writable:!1,value:U}),Object.defineProperty(W,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.freeze&&(Object.freeze(W.props),Object.freeze(W)),W};function Ft(h,v,B,U,Y){{var X,V={},W=null,ot=null;B!==void 0&&(H(B),W=""+B),dt(v)&&(H(v.key),W=""+v.key),gt(v)&&(ot=v.ref,ge(v,Y));for(X in v)x.call(v,X)&&!kt.hasOwnProperty(X)&&(V[X]=v[X]);if(h&&h.defaultProps){var et=h.defaultProps;for(X in et)V[X]===void 0&&(V[X]=et[X])}if(W||ot){var nt=typeof h=="function"?h.displayName||h.name||"Unknown":h;W&&rt(V,nt),ot&&Gt(V,nt)}return Xt(h,W,ot,Y,U,G.current,V)}}var re=w.ReactCurrentOwner,me=w.ReactDebugCurrentFrame;function Mt(h){if(h){var v=h._owner,B=y(h.type,h._source,v?v.type:null);me.setExtraStackFrame(B)}else me.setExtraStackFrame(null)}var It;It=!1;function Jt(h){return typeof h=="object"&&h!==null&&h.$$typeof===t}function ie(){{if(re.current){var h=J(re.current.type);if(h)return`
22
+
23
+ Check the render method of \``+h+"`."}return""}}function ve(h){{if(h!==void 0){var v=h.fileName.replace(/^.*[\\\/]/,""),B=h.lineNumber;return`
24
+
25
+ Check your code at `+v+":"+B+"."}return""}}var oe={};function bt(h){{var v=ie();if(!v){var B=typeof h=="string"?h:h.displayName||h.name;B&&(v=`
26
+
27
+ Check the top-level render call using <`+B+">.")}return v}}function wt(h,v){{if(!h._store||h._store.validated||h.key!=null)return;h._store.validated=!0;var B=bt(v);if(oe[B])return;oe[B]=!0;var U="";h&&h._owner&&h._owner!==re.current&&(U=" It was passed a child from "+J(h._owner.type)+"."),Mt(h),u('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',B,U),Mt(null)}}function Et(h,v){{if(typeof h!="object")return;if(M(h))for(var B=0;B<h.length;B++){var U=h[B];Jt(U)&&wt(U,v)}else if(Jt(h))h._store&&(h._store.validated=!0);else if(h){var Y=b(h);if(typeof Y=="function"&&Y!==h.entries)for(var X=Y.call(h),V;!(V=X.next()).done;)Jt(V.value)&&wt(V.value,v)}}}function Te(h){{var v=h.type;if(v==null||typeof v=="string")return;var B;if(typeof v=="function")B=v.propTypes;else if(typeof v=="object"&&(v.$$typeof===l||v.$$typeof===m))B=v.propTypes;else return;if(B){var U=J(v);O(B,h.props,"prop",U,h)}else if(v.PropTypes!==void 0&&!It){It=!0;var Y=J(v);u("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof v.getDefaultProps=="function"&&!v.getDefaultProps.isReactClassApproved&&u("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ut(h){{for(var v=Object.keys(h.props),B=0;B<v.length;B++){var U=v[B];if(U!=="children"&&U!=="key"){Mt(h),u("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",U),Mt(null);break}}h.ref!==null&&(Mt(h),u("Invalid attribute `ref` supplied to `React.Fragment`."),Mt(null))}}var ye={};function _t(h,v,B,U,Y,X){{var V=Z(h);if(!V){var W="";(h===void 0||typeof h=="object"&&h!==null&&Object.keys(h).length===0)&&(W+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var ot=ve(Y);ot?W+=ot:W+=ie();var et;h===null?et="null":M(h)?et="array":h!==void 0&&h.$$typeof===t?(et="<"+(J(h.type)||"Unknown")+" />",W=" Did you accidentally export a JSX literal instead of a component?"):et=typeof h,u("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",et,W)}var nt=Ft(h,v,B,Y,X);if(nt==null)return nt;if(V){var mt=v.children;if(mt!==void 0)if(U)if(M(mt)){for(var xe=0;xe<mt.length;xe++)Et(mt[xe],h);Object.freeze&&Object.freeze(mt)}else u("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Et(mt,h)}if(x.call(v,"key")){var se=J(h),yt=Object.keys(v).filter(function(Ji){return Ji!=="key"}),yn=yt.length>0?"{key: someKey, "+yt.join(": ..., ")+": ...}":"{key: someKey}";if(!ye[se+yn]){var Xi=yt.length>0?"{"+yt.join(": ..., ")+": ...}":"{}";u(`A props object containing a "key" prop is being spread into JSX:
28
+ let props = %s;
29
+ <%s {...props} />
30
+ React keys must be passed directly to JSX without using spread:
31
+ let props = %s;
32
+ <%s key={someKey} {...props} />`,yn,se,Xi,se),ye[se+yn]=!0}}return h===r?Ut(nt):Te(nt),nt}}var $t=_t;Me.Fragment=r,Me.jsxDEV=$t}()),Me}process.env.NODE_ENV==="production"?We.exports=or():We.exports=sr();var Q=We.exports;const ar=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Ht(e){return Array.from(ar.segment(e))}function lr(e,t="en"){const n=new Intl.Segmenter(t,{granularity:"word"});return Array.from(n.segment(e)).map(r=>({...r,isWordLike:r.isWordLike??!1}))}function cr(e,t){return{cursorLength:t,boundaries:e,cursorToSource(n,r){const i=e[n];if(!i)throw new Error(`Cursor offset out of bounds: ${n}`);return r==="backward"?i.sourceBackward:i.sourceForward},sourceToCursor(n,r){if(n<=0)return{cursorOffset:0,affinity:r};const i=e.length-1,o=e[i];if(n>=o.sourceForward)return{cursorOffset:i,affinity:r};for(let s=0;s<e.length;s+=1){const a=e[s];if(!(n>a.sourceForward))return n<a.sourceBackward?r==="forward"?{cursorOffset:s,affinity:"forward"}:{cursorOffset:Math.max(0,s-1),affinity:"backward"}:{cursorOffset:s,affinity:r}}return{cursorOffset:i,affinity:r}}}}class ct{constructor(){this.sourceParts=[],this.boundaries=[{sourceBackward:0,sourceForward:0}],this.cursorLength=0,this.sourceLengthValue=0}appendSourceOnly(t){if(!t)return;this.sourceParts.push(t),this.sourceLengthValue+=t.length;const n=this.boundaries[this.boundaries.length-1];n.sourceForward+=t.length}appendText(t){if(t)for(const n of Ht(t)){this.sourceParts.push(n.segment),this.sourceLengthValue+=n.segment.length;const r=this.sourceLengthValue;this.cursorLength+=1,this.boundaries.push({sourceBackward:r,sourceForward:r})}}appendCursorAtom(t,n=1){if(n<1)return;this.sourceParts.push(t),this.sourceLengthValue+=t.length;const r=this.sourceLengthValue;for(let i=0;i<n;i+=1)this.cursorLength+=1,this.boundaries.push({sourceBackward:r,sourceForward:r})}appendSerialized(t){if(!t.source&&t.map.cursorLength===0)return;const n=this.sourceLengthValue,r=t.map.boundaries[0];if(r){const i=this.boundaries[this.boundaries.length-1];i.sourceBackward+=r.sourceBackward,i.sourceForward+=r.sourceForward}t.source&&(this.sourceParts.push(t.source),this.sourceLengthValue+=t.source.length);for(let i=1;i<t.map.boundaries.length;i+=1){const o=t.map.boundaries[i];this.cursorLength+=1,this.boundaries.push({sourceBackward:n+o.sourceBackward,sourceForward:n+o.sourceForward})}}build(){return{source:this.sourceParts.join(""),map:cr(this.boundaries,this.cursorLength)}}}const wn={start:0,end:0,affinity:"forward"};function ur(e){const t=new Map;for(const y of e){const x=y.toggleInline;if(x)for(const S of x.markers)t.set(S,x.kind)}const n=new Map;for(const y of e){const x=y.inlineWrapperAffinity;if(x)for(const S of x)n.has(S.kind)||n.set(S.kind,S.inclusive)}const r=y=>n.get(y)??!0,i={parseInline:(y,x,S)=>s(y,x,S),serializeInline:y=>d(y),serializeBlock:y=>c(y)};function o(y,x){for(const S of e){if(!S.parseBlock)continue;const I=S.parseBlock(y,x,i);if(I)return I}return fr(y,x,i)}function s(y,x,S){const I=[];let R=x;for(;R<S;){let O=!1;for(const P of e){if(!P.parseInline)continue;const M=P.parseInline(y,R,S,i);if(M){I.push(M.inline),R=M.nextPos,O=!0;break}}if(!O){const P=dr(y,R,S);I.push(P.inline),R=P.nextPos}}return I}function a(y){const x=[];let S=0;for(;S<y.length;){const I=o(y,S);x.push(I.block),S=I.nextPos,y[S]===`
33
+ `&&(S+=1)}return y.length===0&&x.push({type:"paragraph",content:[]}),y.endsWith(`
34
+ `)&&x.push({type:"paragraph",content:[]}),{type:"doc",blocks:x}}function l(y){const x=new ct,S=y.blocks;return S.forEach((I,R)=>{const O=c(I);x.appendSerialized(O),R<S.length-1&&x.appendText(`
35
+ `)}),x.build()}function c(y){for(const x of e){if(!x.serializeBlock)continue;const S=x.serializeBlock(y,i);if(S)return S}return y.type==="paragraph"?hr(y,d):y.type==="block-wrapper"?gr(y,c):{source:"",map:new ct().build().map}}function d(y){for(const x of e){if(!x.serializeInline)continue;const S=x.serializeInline(y,i);if(S)return S}if(y.type==="text"){const x=new ct;return x.appendText(y.text),x.build()}return y.type==="inline-wrapper"?pr(y,d):{source:"",map:new ct().build().map}}function m(y){return{type:"doc",blocks:y.blocks.map(x=>f(x)).filter(x=>x!==null)}}function f(y){let x=y;for(const S of e)if(S.normalizeBlock){const I=S.normalizeBlock(x);if(I===null)return null;x=I}return x.type==="paragraph"?{...x,content:x.content.map(S=>p(S)).filter(S=>S!==null)}:x.type==="block-wrapper"?{...x,blocks:x.blocks.map(S=>f(S)).filter(S=>S!==null)}:x}function g(y){let x=y;for(const S of e){if(!S.normalizeInline)continue;const I=S.normalizeInline(x);if(I===null)return null;x=I}return x}function p(y){const x=g(y);if(!x)return null;let S=x;return S.type==="inline-wrapper"&&(S={...S,children:S.children.map(I=>p(I)).filter(I=>I!==null)}),g(S)}function k(y,x=wn){const S=a(y),I=m(S),R=l(I);return{source:R.source,selection:x,map:R.map,doc:I,runtime:Ce}}function b(y,x=wn){const S=m(y),I=l(S);return{source:I.source,selection:x,map:I.map,doc:S,runtime:Ce}}function w(y,x){for(const I of e){if(!I.onEdit)continue;const R=I.onEdit(y,x);if(R)return k(R.source,R.selection)}const S=Pe(x.selection);if(y.type==="insert"||y.type==="delete-backward"||y.type==="delete-forward"||y.type==="insert-line-break"){const I=u(y,x.doc,S);if(!I)return x;const R=b(I.doc),O=I.nextAffinity??"forward",P=R.map.cursorToSource(I.nextCursor,O),M=k(R.source),F=M.map.sourceToCursor(P,O);return{...M,selection:{start:F.cursorOffset,end:F.cursorOffset,affinity:F.affinity}}}return y.type==="indent"||y.type==="outdent"||y.type==="toggle-bullet-list"||y.type==="toggle-numbered-list"?x:y.type==="toggle-inline"?gn(x,y.marker):x}function u(y,x,S){const I=C(x);if(I.length===0)return null;const R=E(I),O=Math.max(0,Math.min(R,Math.min(S.start,S.end))),P=Math.max(0,Math.min(R,Math.max(S.start,S.end))),M=S.affinity??"forward";if(y.type==="delete-backward"&&O===0&&P===0)return{doc:x,nextCursor:0,nextAffinity:"backward"};if(y.type==="delete-forward"&&O===R&&P===R)return{doc:x,nextCursor:R,nextAffinity:"forward"};const F=y.type==="insert"?y.text:y.type==="insert-line-break"?`
36
+ `:"",N=y.type==="delete-backward"&&O===P?O===0?{start:0,end:0}:{start:O-1,end:O}:y.type==="delete-forward"&&O===P?O===R?{start:O,end:O}:{start:O,end:O+1}:{start:O,end:P},H=y.type==="insert"&&F.length>0&&N.start===N.end&&A(I,N.start)==="​"?{start:N.start,end:Math.min(R,N.start+1)}:N,G=L(I,H.start),kt=L(I,H.end),ft=I[G.lineIndex],St=I[kt.lineIndex];if(!ft||!St||!ne(ft.parentPath,St.parentPath)||ft.indexInParent>St.indexInParent)return null;const pt=ft.parentPath,gt=pe(x.blocks,pt),dt=ft.indexInParent,ge=St.indexInParent,rt=gt[dt],Gt=gt[ge];if(!rt||!Gt)return null;if(O===P){if(y.type==="insert-line-break"&&rt.type==="block-atom"){const U=[...gt.slice(0,dt+1),{type:"paragraph",content:[]},...gt.slice(dt+1)],Y={...x,blocks:Nt(x.blocks,pt,()=>U)},X=C(Y),V=T(X),W=Math.min(X.length-1,G.lineIndex+1);return{doc:Y,nextCursor:V[W]??0,nextAffinity:"forward"}}if(y.type==="delete-backward"&&rt.type==="block-atom"){const U=gt.filter((et,nt)=>nt!==dt),Y=U.length>0?U:[{type:"paragraph",content:[]}],X={...x,blocks:Nt(x.blocks,pt,()=>Y)},V=C(X),W=T(V),ot=Math.min(V.length-1,G.lineIndex);return{doc:X,nextCursor:W[ot]??0,nextAffinity:"forward"}}if(y.type==="delete-backward"&&rt.type==="paragraph"&&G.offsetInLine===0&&G.lineIndex>0){const U=I[G.lineIndex-1];if(U&&U.block.type==="block-atom"&&ne(U.parentPath,ft.parentPath)&&U.indexInParent===ft.indexInParent-1){const Y=U.indexInParent,X=ft.indexInParent,V=gt.slice(),W=V[Y];V[Y]=V[X],V[X]=W;const ot={...x,blocks:Nt(x.blocks,pt,()=>V)},et=C(ot),nt=T(et),mt=Math.max(0,G.lineIndex-1);return{doc:ot,nextCursor:nt[mt]??0,nextAffinity:"forward"}}}}if(rt.type!=="paragraph"||Gt.type!=="paragraph")return null;const Xt=z(rt),Ft=ge===dt?Xt:z(Gt),[re]=st(Xt,G.offsetInLine),[,me]=st(Ft,kt.offsetInLine),It=H.start!==H.end?he(I,H.start,H.end,x):fe(Xt,G.offsetInLine,M),Jt=a(F),ie=C(Jt),ve=Jt.blocks,oe=E(ie),bt=pn({baseMarks:It,beforeRuns:re,afterRuns:me,insertBlocks:ve}),wt=[...gt.slice(0,dt),...bt,...gt.slice(ge+1)],Et={...x,blocks:Nt(x.blocks,pt,()=>wt)},Te=E(C(Et)),Ut=Math.max(0,Math.min(Te,H.start+oe)),ye=C(Et),_t=de(Et,Ut),$t=y.type==="delete-backward"?"backward":y.type==="delete-forward"?"forward":y.type==="insert"&&H.start===H.end?M:"forward";let h=y.type==="insert"?Re(_t.left,_t.right,$t):Le(_t.left,_t.right,$t);const v=L(ye,Ut),B=T(ye);return v.lineIndex>0&&v.offsetInLine===0&&Ut===(B[v.lineIndex]??0)&&(h="forward"),{doc:Et,nextCursor:Ut,nextAffinity:h}}function E(y){let x=0;for(const S of y)x+=S.cursorLength,S.hasNewline&&(x+=1);return x}function C(y){const x=[],S=(I,R)=>{I.forEach((O,P)=>{const M=[...R,P];if(O.type==="block-wrapper"){S(O.blocks,M);return}x.push({path:M,block:O})})};return S(y.blocks,[]),x.length===0?[{path:[0],parentPath:[],indexInParent:0,block:{type:"paragraph",content:[]},text:"",cursorLength:0,hasNewline:!1}]:x.map((I,R)=>{const O=I.path.slice(0,-1),P=I.path[I.path.length-1]??0,M=D(I.block);return{path:I.path,parentPath:O,indexInParent:P,block:I.block,text:M,cursorLength:Ht(M).length,hasNewline:R<x.length-1}})}function L(y,x){var O;const S=E(y),I=Math.max(0,Math.min(x,S));let R=0;for(let P=0;P<y.length;P+=1){const M=y[P],F=R+M.cursorLength;if(I<=F||P===y.length-1)return{lineIndex:P,offsetInLine:Math.max(0,Math.min(I-R,M.cursorLength))};if(R=F+(M.hasNewline?1:0),M.hasNewline&&I===R)return{lineIndex:Math.min(y.length-1,P+1),offsetInLine:0}}return{lineIndex:y.length-1,offsetInLine:((O=y[y.length-1])==null?void 0:O.cursorLength)??0}}function T(y){const x=[];let S=0;for(const I of y)x.push(S),S+=I.cursorLength+(I.hasNewline?1:0);return x}function A(y,x){var O;const S=L(y,x),I=y[S.lineIndex];return!I||S.offsetInLine>=I.cursorLength?null:((O=Array.from(Ht(I.text))[S.offsetInLine])==null?void 0:O.segment)??null}function D(y){return y.type==="paragraph"?y.content.map(j).join(""):y.type==="block-atom"?"":y.type==="block-wrapper"?y.blocks.map(D).join(`
37
+ `):""}function j(y){return y.type==="text"?y.text:y.type==="inline-wrapper"?y.children.map(j).join(""):y.type==="inline-atom"?" ":""}function Z(y){if(y==null)return"";if(typeof y!="object")return JSON.stringify(y);if(Array.isArray(y))return`[${y.map(Z).join(",")}]`;const x=y;return`{${Object.keys(x).sort().map(R=>`${JSON.stringify(R)}:${Z(x[R])}`).join(",")}}`}function K(y,x){const S=x?Z(x):"";return`${y}:${S}`}function z(y){const x=[],S=[],I=O=>{if(!O)return;const P=S.slice(),M=x[x.length-1];if(M&&J(M.marks,P)){M.text+=O;return}x.push({text:O,marks:P})},R=O=>{if(O.type==="text"){I(O.text);return}if(O.type==="inline-atom"){I(" ");return}if(O.type==="inline-wrapper"){const P=O.data,M={kind:O.kind,data:P,key:K(O.kind,P)};S.push(M);for(const F of O.children)R(F);S.pop()}};for(const O of y.content)R(O);return x}function J(y,x){var S,I;if(y.length!==x.length)return!1;for(let R=0;R<y.length;R+=1)if(((S=y[R])==null?void 0:S.key)!==((I=x[R])==null?void 0:I.key))return!1;return!0}function tt(y,x,S){const[I,R]=st(y,x),[O,P]=st(R,Math.max(0,S-x));return{before:I,selected:O,after:P}}function st(y,x){const S=[],I=[];let R=Math.max(0,x);for(let O=0;O<y.length;O+=1){const P=y[O],M=Array.from(Ht(P.text)),F=M.length;if(R===0)return I.push(P,...y.slice(O+1)),[S,I];if(R>=F){S.push(P),R-=F;continue}const N=M.slice(0,R).map(H=>H.segment).join(""),$=M.slice(R).map(H=>H.segment).join("");return N&&S.push({...P,text:N}),$&&I.push({...P,text:$}),I.push(...y.slice(O+1)),[S,I]}return[S,I]}function ht(y){var S,I,R,O;if(y.length===0)return[];let x=((S=y[0])==null?void 0:S.marks)??[];for(let P=1;P<y.length;P+=1){const M=((I=y[P])==null?void 0:I.marks)??[],F=Math.min(x.length,M.length);let N=0;for(;N<F&&((R=x[N])==null?void 0:R.key)===((O=M[N])==null?void 0:O.key);N+=1);if(x=x.slice(0,N),x.length===0)return[]}return x}function fe(y,x,S){const I=x>0?te(y,x-1):null,R=te(y,x);return S==="backward"?I??[]:R??[]}function te(y,x){if(x<0)return null;let S=x;for(const I of y){const R=Array.from(Ht(I.text));if(S<R.length)return I.marks;S-=R.length}return null}function de(y,x){const S=C(y),I=L(S,x),R=S[I.lineIndex];if(!R)return{left:[],right:[]};const O=ee(y.blocks,R.path);if(!O||O.type!=="paragraph")return{left:[],right:[]};const P=z(O),M=I.offsetInLine>0?te(P,I.offsetInLine-1):null,F=te(P,I.offsetInLine);return{left:M??[],right:F??[]}}function Le(y,x,S){return Kt(y,x)&&x.length>y.length?"forward":Kt(x,y)&&y.length>x.length?"backward":S}function Re(y,x,S){return Kt(x,y)&&y.length>x.length&&y.slice(x.length).some(R=>!r(R.kind))?"forward":Le(y,x,S)}function Kt(y,x){var S,I;if(y.length>x.length)return!1;for(let R=0;R<y.length;R+=1)if(((S=y[R])==null?void 0:S.key)!==((I=x[R])==null?void 0:I.key))return!1;return!0}function At(y){const x=[];for(const S of y){if(!S.text)continue;const I=x[x.length-1];if(I&&J(I.marks,S.marks)){I.text+=S.text;continue}x.push(S)}return x}function Yt(y){var M,F;const x=[],S=[],I=()=>{var N;return S.length===0?x:((N=S[S.length-1])==null?void 0:N.children)??x},R=N=>{for(;S.length>N;)S.pop()},O=(N,$)=>{for(let H=$;H<N.length;H+=1){const G=N[H];if(!G)continue;const kt={type:"inline-wrapper",kind:G.kind,data:G.data,children:[]};I().push(kt),S.push({mark:G,children:kt.children})}};let P=[];for(const N of y){const $=N.marks,H=Math.min(P.length,$.length);let G=0;for(;G<H&&((M=P[G])==null?void 0:M.key)===((F=$[G])==null?void 0:F.key);G+=1);R(G),P=P.slice(0,G),O($,G),P=$,N.text&&I().push({type:"text",text:N.text})}return R(0),x}function pn(y){const{baseMarks:x,beforeRuns:S,afterRuns:I,insertBlocks:R}=y,O=R.findIndex(F=>F.type==="paragraph"),P=(()=>{var F;for(let N=R.length-1;N>=0;N-=1)if(((F=R[N])==null?void 0:F.type)==="paragraph")return N;return-1})();if(O===-1||P===-1){const F=At([...S,...I]);return[{type:"paragraph",content:Yt(F)},...R]}const M=[];return R.forEach((F,N)=>{if(F.type!=="paragraph"){M.push(F);return}const $=z(F).map(H=>({...H,marks:[...x,...H.marks]}));if(N===O&&N===P){const H=At([...S,...$,...I]);M.push({...F,content:Yt(H)});return}if(N===O){const H=At([...S,...$]);M.push({...F,content:Yt(H)});return}if(N===P){const H=At([...$,...I]);M.push({...F,content:Yt(H)});return}M.push({...F,content:Yt(At($))})}),M}function he(y,x,S,I){if(x===S)return[];const R=L(y,x),O=L(y,S),P=[];for(let M=R.lineIndex;M<=O.lineIndex;M+=1){const F=y[M];if(!F)continue;const N=ee(I.blocks,F.path);if(!N||N.type!=="paragraph")continue;const $=z(N),H=M===R.lineIndex?R.offsetInLine:0,G=M===O.lineIndex?O.offsetInLine:F.cursorLength;P.push(...tt($,H,G).selected)}return ht(P)}function ee(y,x){let S=null,I=y;for(let R=0;R<x.length;R+=1){const O=x[R]??0;if(S=I[O]??null,!S)return null;if(S.type==="block-wrapper")I=S.blocks;else if(R<x.length-1)return null}return S}function pe(y,x){let S=y;for(const I of x){const R=S[I];if(!R||R.type!=="block-wrapper")return S;S=R.blocks}return S}function Nt(y,x,S){if(x.length===0)return S(y);const[I,...R]=x,O=y[I];if(!O||O.type!=="block-wrapper")return y;const P=Nt(O.blocks,R,S);return y.map((M,F)=>F===I?{...O,blocks:P}:M)}function ne(y,x){if(y.length!==x.length)return!1;for(let S=0;S<y.length;S+=1)if(y[S]!==x[S])return!1;return!0}function gn(y,x){const S=Pe(y.selection),I=y.source,R=y.map;if(S.start===S.end){const rt=S.start,Gt=x.length,Xt=t.get(x)??null;if(Xt){const bt=de(y.doc,rt);if(Kt(bt.right,bt.left)&&bt.left.length>bt.right.length){const wt=bt.left.slice(bt.right.length);if(wt.some(Et=>Et.kind===Xt)){if(wt.length>1){const Et="​",Te=R.cursorToSource(rt,"forward"),Ut=R.cursorToSource(rt,"backward"),_t=I.slice(Ut,Te).indexOf(x);if(_t!==-1){const $t=Ut+_t+Gt,h=I.slice(0,$t)+Et+I.slice($t),v=k(h),B=$t,U=v.map.sourceToCursor(B,"forward");return{...v,selection:{start:U.cursorOffset,end:U.cursorOffset,affinity:"forward"}}}}return{...y,selection:{start:rt,end:rt,affinity:"forward"}}}}}const Ft="​",re=R.cursorToSource(rt,"forward"),me=R.cursorToSource(rt,"backward"),Mt=(()=>{const bt=[re,me];for(const wt of bt){if(I[wt]===Ft)return wt;if(wt>0&&I[wt-1]===Ft)return wt-1}return null})(),It=Mt??R.cursorToSource(rt,S.affinity??"forward"),Jt=Mt!==null?I.slice(0,It)+x+Ft+x+I.slice(It+Ft.length):I.slice(0,It)+x+Ft+x+I.slice(It),ie=k(Jt),ve=It+Gt,oe=ie.map.sourceToCursor(ve,"forward");return{...ie,selection:{start:oe.cursorOffset,end:oe.cursorOffset,affinity:"forward"}}}const O=Math.min(S.start,S.end),P=Math.max(S.start,S.end),M=R.cursorToSource(O,"forward"),F=R.cursorToSource(P,"backward"),N=I.slice(M,F),$=x.length,H=t.get(x)??null,G=H?he(C(y.doc),O,P,y.doc):[],kt=H!==null&&G.some(rt=>rt.kind===H),ft=H?kt:!0,St=$>0&&M>=$&&I.slice(M-$,M)===x&&I.slice(F,F+$)===x,pt=N.startsWith(x)&&N.endsWith(x)&&N.length>=$*2,gt=ft&&(St||pt);let dt;if(gt)if(St)dt=I.slice(0,M-$)+N+I.slice(F+$);else{const rt=N.slice($,-$);dt=I.slice(0,M)+rt+I.slice(F)}else{const rt=x+N+x;dt=I.slice(0,M)+rt+I.slice(F)}return{...k(dt),selection:{start:O,end:P,affinity:S.affinity??"forward"}}}function Ve(y,x,S){const I=Pe(x),R=y.map.cursorLength,O=Math.max(0,Math.min(R,I.start)),P=Math.max(0,Math.min(R,I.end)),M=(S==null?void 0:S.kind)??"programmatic";let F=I.affinity??"forward";if(O===P){const N=de(y.doc,O);M==="keyboard"?F=Re(N.left,N.right,F):M==="dom"&&F==="backward"&&Kt(N.right,N.left)&&N.left.length>N.right.length&&N.left.slice(N.right.length).some(H=>!r(H.kind))&&(F="forward")}return{...y,selection:{start:O,end:P,affinity:F}}}function mn(y,x){const S=Pe(x),I=C(y.doc),R=E(I),O=Math.max(0,Math.min(R,Math.min(S.start,S.end))),P=Math.max(0,Math.min(R,Math.max(S.start,S.end)));if(O===P)return"";const M=L(I,O),F=L(I,P),N=[];for(let H=M.lineIndex;H<=F.lineIndex;H+=1){const G=I[H];if(!G)continue;const kt=ee(y.doc.blocks,G.path);if(!kt||kt.type!=="paragraph")continue;const ft=z(kt),St=H===M.lineIndex?M.offsetInLine:0,pt=H===F.lineIndex?F.offsetInLine:G.cursorLength,gt=tt(ft,St,pt).selected,dt=Yt(At(gt));N.push({type:"paragraph",content:dt})}const $={blocks:N.length>0?N:[{type:"paragraph",content:[]}]};return l(m($)).source}const Ce={extensions:e,parse:a,serialize:l,createState:k,updateSelection:Ve,serializeSelection:mn,applyEdit:w};return Ce}function fr(e,t,n){let r=e.indexOf(`
38
+ `,t);return r===-1&&(r=e.length),{block:{type:"paragraph",content:n.parseInline(e,t,r)},nextPos:r}}function dr(e,t,n){const r=Ht(e.slice(t,n))[0],i=r?r.segment:e[t]??"";return{inline:{type:"text",text:i},nextPos:t+i.length}}function hr(e,t){const n=new ct;for(const r of e.content){const i=t(r);n.appendSerialized(i)}return n.build()}function pr(e,t){const n=new ct;for(const r of e.children){const i=t(r);n.appendSerialized(i)}return n.build()}function gr(e,t){const n=new ct;return e.blocks.forEach((r,i)=>{const o=t(r);n.appendSerialized(o),i<e.blocks.length-1&&n.appendText(`
39
+ `)}),n.build()}function Pe(e){if(e.start<=e.end)return e;const t=e.start!==e.end;return{...e,start:e.end,end:e.start,affinity:t?"backward":e.affinity}}function mr(e,t){const n=Ht(e.data),r=[0];for(const o of n)r.push(o.index+o.segment.length);const i=t+n.length;return{node:e,cursorStart:t,cursorEnd:i,boundaryOffsets:r}}function yr(e,t){if(t<=0)return 0;for(let n=1;n<e.length;n+=1){const r=e[n];if(t<r)return n-1;if(t===r)return n}return e.length-1}function xr(e){const t=new Map,n=new Map;e.forEach((o,s)=>{n.set(o.node,s)});for(const o of e)t.set(o.node,o);function r(o,s){if(e.length===0)return null;for(let l=0;l<e.length;l+=1){const c=e[l],d=l>0?e[l-1]:null,m=l+1<e.length?e[l+1]:null;if(o<c.cursorStart){if(!d)return{node:c.node,offset:c.boundaryOffsets[0]};const f=d.boundaryOffsets[d.boundaryOffsets.length-1];return s==="backward"?{node:d.node,offset:f}:{node:c.node,offset:c.boundaryOffsets[0]}}if(o===c.cursorStart&&d&&s==="backward")return{node:d.node,offset:d.boundaryOffsets[d.boundaryOffsets.length-1]};if(o<=c.cursorEnd){if(o===c.cursorEnd&&s==="forward"&&m&&m.cursorStart===o)return{node:m.node,offset:m.boundaryOffsets[0]};const f=Math.max(0,o-c.cursorStart),g=Math.min(f,c.boundaryOffsets.length-1);return{node:c.node,offset:c.boundaryOffsets[g]}}}const a=e[e.length-1];return{node:a.node,offset:a.boundaryOffsets[a.boundaryOffsets.length-1]}}function i(o,s){const a=t.get(o);if(!a)return null;const l=n.get(o),c=yr(a.boundaryOffsets,s),d=a.cursorStart+c,m=s===0,f=s===a.boundaryOffsets[a.boundaryOffsets.length-1],g=a.boundaryOffsets.length>1,p=l!==void 0&&l+1<e.length,k=l!==void 0&&l>0;let b="forward";return f&&g&&p?b="backward":m&&k&&(b="forward"),{cursorOffset:d,affinity:b}}return{runs:e,domAtCursor:r,cursorAtDom:i}}function Sn(e){return e?Array.isArray(e)?e:[e]:[]}function kr(e,t,n){const r=[];let i=0,o=0;function s(f){const g=mr(f,i);return i=g.cursorEnd,r.push(g),g}const a={renderInline:l,renderBlock:c,renderBlocks:d,createTextRun:s,getLineIndex:()=>o,incrementLineIndex:()=>{o+=1}};function l(f){for(const g of t){const p=g.renderInline;if(!p)continue;const k=p(f,a);if(k)return Sn(k)}if(f.type==="text"){const g=document.createElement("span");g.className="cake-text";const p=document.createTextNode(f.text);return s(p),g.append(p),[g]}if(f.type==="inline-wrapper"){const g=document.createElement("span");g.setAttribute("data-inline",f.kind);for(const p of f.children)for(const k of l(p))g.append(k);return[g]}if(f.type==="inline-atom"){const g=document.createElement("span");g.setAttribute("data-inline-atom",f.kind);const p=document.createTextNode(" ");return s(p),g.append(p),[g]}return[]}function c(f){for(const g of t){const p=g.renderBlock;if(!p)continue;const k=p(f,a);if(k)return Sn(k)}if(f.type==="paragraph"){const g=document.createElement("div");if(g.setAttribute("data-block","paragraph"),g.setAttribute("data-line-index",String(a.getLineIndex())),g.classList.add("cake-line"),g.dataset.lineKind="paragraph",a.incrementLineIndex(),f.content.length===0){const p=document.createTextNode("");s(p),g.append(p),g.append(document.createElement("br"))}else{const p=Be(f.content);for(const k of p)for(const b of l(k))g.append(b)}return[g]}if(f.type==="block-wrapper"){const g=document.createElement("div");g.setAttribute("data-block-wrapper",f.kind);for(const p of d(f.blocks))g.append(p);return[g]}if(f.type==="block-atom"){const g=document.createElement("div");return g.setAttribute("data-block-atom",f.kind),g.setAttribute("data-line-index",String(a.getLineIndex())),g.classList.add("cake-line"),a.incrementLineIndex(),[g]}return[]}function d(f){const g=[];return f.forEach((p,k)=>{g.push(...c(p)),k<f.length-1&&(i+=1)}),g}const m=[];for(const f of d(e.blocks))m.push(f);return{content:m,map:xr(r)}}function Be(e){const t=[];let n="";const r=()=>{n&&(t.push({type:"text",text:n}),n="")};for(const i of e){if(i.type==="text"){n+=i.text;continue}if(r(),i.type==="inline-wrapper"){t.push({...i,children:Be(i.children)});continue}t.push(i)}return r(),t}function wr(e,t){const n=window.getSelection();if(!n)return;const r=e.start===e.end;let i=e.start,o=e.end,s=!0;r||(e.start>e.end?(i=e.start,o=e.end,s=!1):e.affinity==="backward"?(i=e.end,o=e.start,s=!1):(i=e.start,o=e.end,s=!0));const a=r?e.affinity??"forward":s?"forward":"backward",l=r?e.affinity??"forward":s?"backward":"forward",c=In(t,i,a,r),d=In(t,o,l,r),m=t.domAtCursor(i,c),f=t.domAtCursor(o,d);if(!m||!f)return;if(n.removeAllRanges(),r){n.collapse(m.node,m.offset);return}const g=n;if(typeof g.setBaseAndExtent=="function"){g.setBaseAndExtent(m.node,m.offset,f.node,f.offset);return}if(typeof n.extend=="function"){n.collapse(m.node,m.offset),n.extend(f.node,f.offset);return}const p=document.createRange(),k=s?m:f,b=s?f:m;p.setStart(k.node,k.offset),p.setEnd(b.node,b.offset),n.addRange(p)}function Qt(e){const t=window.getSelection();if(!t||t.rangeCount===0)return null;const n=bn(t.anchorNode,t.anchorOffset),r=bn(t.focusNode,t.focusOffset);if(!n||!r)return null;const i=e.cursorAtDom(n.node,n.offset),o=e.cursorAtDom(r.node,r.offset);return!i||!o?null:i.cursorOffset===o.cursorOffset?{start:i.cursorOffset,end:i.cursorOffset,affinity:o.affinity}:i.cursorOffset<o.cursorOffset?{start:i.cursorOffset,end:o.cursorOffset,affinity:"forward"}:{start:o.cursorOffset,end:i.cursorOffset,affinity:"backward"}}function bn(e,t){if(!e)return null;if(e instanceof Text)return{node:e,offset:t};if(!(e instanceof Element))return null;const n=e.childNodes;if(n.length===0)return null;if(t<=0){const s=Ln(n,0);return s?{node:s,offset:0}:null}if(t>=n.length){const s=Rn(n,n.length-1);return s?{node:s,offset:s.data.length}:null}const r=En(n[t]);if(r)return{node:r,offset:0};const i=Rn(n,t-1);if(i)return{node:i,offset:i.data.length};const o=Ln(n,t+1);return o?{node:o,offset:0}:null}function In(e,t,n,r){return r||n!=="backward"||!Sr(e,t)?n:"forward"}function Sr(e,t){const n=e.runs;for(let r=1;r<n.length;r+=1){const i=n[r],o=n[r-1];if(t>o.cursorEnd&&t<=i.cursorStart)return i.cursorStart>o.cursorEnd}return!1}function En(e){if(e instanceof Text)return e;const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT).nextNode();return n instanceof Text?n:null}function br(e){if(e instanceof Text)return e;const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let n=null,r=t.nextNode();for(;r;)r instanceof Text&&(n=r),r=t.nextNode();return n}function Ln(e,t){for(let n=Math.max(0,t);n<e.length;n+=1){const r=En(e[n]);if(r)return r}return null}function Rn(e,t){for(let n=Math.min(e.length-1,t);n>=0;n-=1){const r=br(e[n]);if(r)return r}return null}const Zt="bold",Ke={name:"bold",toggleInline:{kind:Zt,markers:["**"]},keybindings:[{key:"b",meta:!0,command:{type:"toggle-inline",marker:"**"}},{key:"b",ctrl:!0,command:{type:"toggle-inline",marker:"**"}}],inlineWrapperAffinity:[{kind:Zt,inclusive:!0}],parseInline(e,t,n,r){if(e.slice(t,t+3)==="***"){const s=e.indexOf("***",t+3);if(s!==-1&&s<n){const a=r.parseInline(e,t+3,s);return{inline:{type:"inline-wrapper",kind:Zt,children:[{type:"inline-wrapper",kind:"italic",children:a}]},nextPos:s+3}}}if(e.slice(t,t+2)!=="**")return null;let i=e.indexOf("**",t+2);if(i===-1||i>=n)return null;e.slice(i,i+3)==="***"&&i+1<n&&Ir(e,t+2,i)%2===1&&(i+=1);const o=r.parseInline(e,t+2,i);return{inline:{type:"inline-wrapper",kind:Zt,children:o},nextPos:i+2}},serializeInline(e,t){if(e.type!=="inline-wrapper"||e.kind!==Zt)return null;const n=new ct;n.appendSourceOnly("**");for(const r of e.children){const i=t.serializeInline(r);n.appendSerialized(i)}return n.appendSourceOnly("**"),n.build()},normalizeInline(e){return e.type!=="inline-wrapper"||e.kind!==Zt?e:e.children.length===0?null:e},renderInline(e,t){if(e.type!=="inline-wrapper"||e.kind!==Zt)return null;const n=document.createElement("strong");for(const r of e.children)for(const i of t.renderInline(r))n.append(i);return n}};function Ir(e,t,n){let r=0;for(let i=t;i<n;i+=1){if(e[i]!=="*")continue;const o=i>t?e[i-1]:"",s=i+1<n?e[i+1]:"";o==="*"||s==="*"||(r+=1)}return r}const Er="bold",Lr="italic",Rr=["***","___"],Ye={name:"combined-emphasis",parseInline(e,t,n,r){const i=Rr.find(l=>e.slice(t,t+3)===l);if(!i)return null;const o=i[0];if(e[t+3]===o)return null;const s=e.indexOf(i,t+3);if(s===-1||s>=n||s===t+3&&s+3<n)return null;const a=r.parseInline(e,t+3,s);return{inline:{type:"inline-wrapper",kind:Er,children:[{type:"inline-wrapper",kind:Lr,children:a}]},nextPos:s+3}}};function ke(e){const t=e.trim();return!t||t.startsWith("http")?t:`https://${t}`}function Cr(e){const t=e.trim();if(!t||t.includes(" ")||t.includes(`
40
+ `)||t.includes(" "))return!1;const n=t;if(!(n.includes("://")||n.startsWith("www.")||n.startsWith("localhost")||n.includes(".")))return!1;try{const i=ke(n),o=new URL(i);return o.protocol==="http:"||o.protocol==="https:"}catch{return!1}}function vr(e){return e instanceof Element?e.closest("a.cake-link"):null}function Cn(e){const t=e.toOverlayRect(e.anchor.getBoundingClientRect());return{top:t.top+t.height+6,left:t.left}}function Tr(e){const{container:t,contentRoot:n,toOverlayRect:r}=e,i=_.useRef(null),o=_.useRef(null),s=_.useRef(null),[a,l]=_.useState({status:"closed"}),c=a.status==="open"?a.isEditing:!1,d=_.useCallback(()=>{i.current=null,l({status:"closed"})},[]),m=_.useCallback(()=>{if(a.status!=="open")return;const L=i.current;if(!L||!L.isConnected){d();return}l(T=>T.status!=="open"?T:{...T,position:Cn({anchor:L,toOverlayRect:r})})},[d,a.status,r]),f=_.useCallback((L,T)=>{i.current=L;const A=L.getAttribute("href")??"";l({status:"open",url:A,isEditing:(T==null?void 0:T.isEditing)??!1,draftUrl:A,position:Cn({anchor:L,toOverlayRect:r})})},[r]);_.useEffect(()=>{a.status==="open"&&m()},[m,a.status,c]),_.useEffect(()=>{var L;a.status!=="open"||!c||(L=s.current)==null||L.focus()},[a.status,c]),_.useEffect(()=>{function L(T){const A=vr(T.target);if(!A){d();return}const D=A.getAttribute("href")??"";if(T.metaKey||T.ctrlKey){D&&window.open(ke(D),"_blank","noopener,noreferrer");return}T.preventDefault(),f(A)}return n.addEventListener("click",L),()=>{n.removeEventListener("click",L)}},[d,n,f]),_.useEffect(()=>{function L(T){var j,Z;const A=T,D=(j=A.detail)==null?void 0:j.link;!D||!(D instanceof HTMLAnchorElement)||f(D,{isEditing:(Z=A.detail)==null?void 0:Z.isEditing})}return n.addEventListener("cake-link-popover-open",L),()=>{n.removeEventListener("cake-link-popover-open",L)}},[n,f]),_.useEffect(()=>{if(a.status==="open")return t.addEventListener("scroll",m,{passive:!0}),window.addEventListener("resize",m),()=>{t.removeEventListener("scroll",m),window.removeEventListener("resize",m)}},[t,m,a.status]);const g=_.useCallback(L=>{L.stopPropagation(),!(L.target instanceof HTMLInputElement)&&L.preventDefault()},[]);if(a.status!=="open")return null;const p=ke(a.url),k=()=>{l(L=>L.status!=="open"?L:{...L,isEditing:!0,draftUrl:L.url})},b=()=>{l(L=>L.status!=="open"?L:{...L,isEditing:!1,draftUrl:L.url})},w=()=>{var j;if(a.status!=="open")return;const T=(((j=s.current)==null?void 0:j.value)??a.draftUrl).trim();if(!T){d();return}const A=ke(T),D=i.current;D==null||D.setAttribute("href",A),l({status:"open",url:A,isEditing:!1,draftUrl:A,position:a.position})},u=()=>{window.open(p,"_blank","noopener,noreferrer")},E=()=>{d()},C=L=>{L.stopPropagation(),L.key==="Enter"?(L.preventDefault(),w()):L.key==="Escape"&&(L.preventDefault(),b())};return Q.jsxDEV("div",{className:"cake-link-popover",ref:o,style:{top:a.position.top,left:a.position.left,pointerEvents:"auto"},onMouseDown:g,onClick:L=>L.stopPropagation(),children:a.isEditing?Q.jsxDEV("form",{className:"cake-link-editor",onSubmit:L=>{L.preventDefault(),w()},children:[Q.jsxDEV("input",{className:"cake-link-input",type:"text",value:a.draftUrl,ref:s,onChange:L=>{l(T=>T.status!=="open"?T:{...T,draftUrl:L.target.value})},onKeyDown:C,placeholder:"https://"},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:280,columnNumber:11},this),Q.jsxDEV("button",{type:"submit",className:"cake-link-save",children:"Save"},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:296,columnNumber:11},this),Q.jsxDEV("button",{type:"button",className:"cake-link-cancel",onClick:b,children:"Cancel"},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:299,columnNumber:11},this)]},void 0,!0,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:273,columnNumber:9},this):Q.jsxDEV(Q.Fragment,{children:[Q.jsxDEV("div",{className:"cake-link-url",title:p,children:p},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:309,columnNumber:11},this),Q.jsxDEV("div",{className:"cake-link-actions",children:[Q.jsxDEV("button",{type:"button",className:"cake-link-icon-action",onClick:k,title:"Edit link","aria-label":"Edit link",children:Q.jsxDEV(je.Pencil,{className:"cake-link-icon"},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:320,columnNumber:15},this)},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:313,columnNumber:13},this),Q.jsxDEV("button",{type:"button",className:"cake-link-icon-action",onClick:u,title:"Open link","aria-label":"Open link",children:Q.jsxDEV(je.ExternalLink,{className:"cake-link-icon"},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:329,columnNumber:15},this)},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:322,columnNumber:13},this),Q.jsxDEV("button",{type:"button",className:"cake-link-icon-action",onClick:E,title:"Remove link","aria-label":"Remove link",children:Q.jsxDEV(je.Unlink,{className:"cake-link-icon"},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:338,columnNumber:15},this)},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:331,columnNumber:13},this)]},void 0,!0,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:312,columnNumber:11},this)]},void 0,!0,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:308,columnNumber:9},this)},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link-popover.tsx",lineNumber:261,columnNumber:5},this)}function Or(e,t){const n=[];let r=t.container.top,i=0;e.forEach(s=>{const a=t.measureLine({lineIndex:s.lineIndex,lineText:s.text,lineLength:s.cursorLength,lineHasNewline:s.hasNewline,top:r});n.push({lineIndex:s.lineIndex,lineStartOffset:i,lineLength:s.cursorLength,lineHasNewline:s.hasNewline,lineBox:a.lineBox,rows:a.rows}),r=a.lineBox.top+a.lineBox.height,i+=s.cursorLength+(s.hasNewline?1:0)});const o=Math.max(t.container.height,r-t.container.top);return{container:{...t.container,height:o},lines:n}}function it(e){const t=vn(e.blocks);return t.map((n,r)=>{const i=Pr(n.text),o=Math.max(0,i.length-1);return{lineIndex:r,text:n.text,cursorLength:o,hasNewline:r<t.length-1,cursorToCodeUnit:i,isAtomic:n.isAtomic}})}function vn(e){const t=[];return e.forEach(n=>{t.push(...Mr(n))}),t.length===0&&t.push({text:"",isAtomic:!1}),t}function Mr(e){return e.type==="paragraph"?[{text:e.content.map(Tn).join(""),isAtomic:!1}]:e.type==="block-wrapper"?vn(e.blocks):e.type==="block-atom"?[{text:"",isAtomic:!0}]:[]}function at(e){const t=[];let n=0;return e.forEach(r=>{t.push(n),n+=r.cursorLength,r.hasNewline&&(n+=1)}),t}function ut(e,t){if(e.length===0)return{lineIndex:0,offsetInLine:0};const n=at(e),r=n[n.length-1]+e[e.length-1].cursorLength,i=Math.max(0,Math.min(t,r));for(let s=0;s<e.length;s+=1){const a=n[s],l=a+e[s].cursorLength;if(i<=l||s===e.length-1)return{lineIndex:s,offsetInLine:i-a}}const o=e.length-1;return{lineIndex:o,offsetInLine:e[o].cursorLength}}function Tn(e){return e.type==="text"?e.text:e.type==="inline-wrapper"?e.children.map(Tn).join(""):e.type==="inline-atom"?" ":""}function Pr(e){const t=Ht(e),n=[0];for(const r of t)n.push(r.index+r.segment.length);return n.length===0&&n.push(0),n}function Br(e,t){const n=e.cursorToCodeUnit[e.cursorToCodeUnit.length-1]??0,r=Math.max(0,Math.min(t,n));for(let i=0;i<e.cursorToCodeUnit.length;i+=1){if(e.cursorToCodeUnit[i]===r)return i;if(e.cursorToCodeUnit[i]>r)return Math.max(0,i-1)}return e.cursorLength}function ae(e){return e.length===0?"":e.map(t=>t.text).join(`
41
+ `)}function we(e,t){if(e.length===0)return 0;const n=Math.max(0,t),r=at(e);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o],a=i,l=a+s.text.length;if(n<=l||o===e.length-1){const c=Math.max(0,Math.min(n-a,s.text.length)),d=Br(s,c);return(r[o]??0)+d}if(i=l+(s.hasNewline?1:0),s.hasNewline&&n===i)return(r[o]??0)+s.cursorLength+1}return null}function zt(e,t){if(e.length===0)return 0;const n=at(e),{lineIndex:r,offsetInLine:i}=ut(e,t);let o=0;for(let c=0;c<e.length;c+=1){const d=e[c];if(c===r){const m=Math.max(0,Math.min(i,d.cursorLength));return o+(d.cursorToCodeUnit[m]??0)}o+=d.text.length+(d.hasNewline?1:0)}const s=e[e.length-1],a=n[n.length-1]??0,l=Math.max(0,t-a);return o+(s.cursorToCodeUnit[l]??s.text.length)}const Se="link",Ge={name:"link",inlineWrapperAffinity:[{kind:Se,inclusive:!1}],keybindings:[{key:"u",meta:!0,shift:!0,command:e=>e.selection.start===e.selection.end?null:{type:"wrap-link",openPopover:!0}},{key:"u",ctrl:!0,shift:!0,command:e=>e.selection.start===e.selection.end?null:{type:"wrap-link",openPopover:!0}}],onEdit(e,t){if(e.type!=="wrap-link")return null;const n=t.selection,r=Math.min(n.start,n.end),i=Math.max(n.start,n.end);if(r===i)return null;const o=t.map.cursorToSource(r,"forward"),s=t.map.cursorToSource(i,"backward");if(o===s)return null;const a=t.source.slice(o,s),l=e.url??"",c=`[${a}](${l})`;return{source:t.source.slice(0,o)+c+t.source.slice(s),selection:{start:i,end:i,affinity:"backward"}}},onPasteText(e,t){if(!Cr(e))return null;const n=ke(e.trim()),r=t.selection,i=Math.min(r.start,r.end),o=Math.max(r.start,r.end);if(i!==o){const a=it(t.doc),l=ae(a),c=zt(a,i),d=zt(a,o);return{type:"insert",text:`[${l.slice(c,d)}](${n})`}}return{type:"insert",text:`[${n}](${n})`}},parseInline(e,t,n,r){if(e[t]!=="[")return null;const i=e.indexOf("](",t+1);if(i===-1||i>=n)return null;const o=e.indexOf(")",i+2);if(o===-1||o>=n)return null;const s=t+1,a=i,l=i+2,c=o,d=r.parseInline(e,s,a),m=e.slice(l,c);return{inline:{type:"inline-wrapper",kind:Se,children:d,data:{url:m}},nextPos:o+1}},serializeInline(e,t){var i;if(e.type!=="inline-wrapper"||e.kind!==Se)return null;const n=new ct;n.appendSourceOnly("[");for(const o of e.children){const s=t.serializeInline(o);n.appendSerialized(s)}n.appendSourceOnly("](");const r=typeof((i=e.data)==null?void 0:i.url)=="string"?e.data.url:"";return n.appendSourceOnly(r),n.appendSourceOnly(")"),n.build()},normalizeInline(e){return e.type!=="inline-wrapper"||e.kind!==Se?e:e.children.length===0?null:e},renderInline(e,t){var i;if(e.type!=="inline-wrapper"||e.kind!==Se)return null;const n=document.createElement("a");n.className="cake-link";const r=typeof((i=e.data)==null?void 0:i.url)=="string"?e.data.url:"";n.setAttribute("href",r);for(const o of e.children)for(const s of t.renderInline(o))n.append(s);return n},renderOverlay(e){return!e.contentRoot||!e.toOverlayRect?null:Q.jsxDEV(Tr,{container:e.container,contentRoot:e.contentRoot,toOverlayRect:e.toOverlayRect},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/link/link.tsx",lineNumber:179,columnNumber:7},this)}},De="pipe-link",Xe={name:"pipe-link",parseInline(e,t,n){if(e[t]!=="|")return null;const r=e.indexOf("|",t+1);if(r===-1||r>=n)return null;const i=e.indexOf("|",r+1);if(i===-1||i>=n)return null;const o=e.slice(t+1,r),s=e.slice(r+1,i);return!o||!s?null:{inline:{type:"inline-wrapper",kind:De,children:[{type:"text",text:o}],data:{url:s}},nextPos:i+1}},serializeInline(e,t){var i;if(e.type!=="inline-wrapper"||e.kind!==De)return null;const n=new ct;n.appendSourceOnly("|");for(const o of e.children){const s=t.serializeInline(o);n.appendSerialized(s)}n.appendSourceOnly("|");const r=typeof((i=e.data)==null?void 0:i.url)=="string"?e.data.url:"";return n.appendSourceOnly(r),n.appendSourceOnly("|"),n.build()},normalizeInline(e){return e.type!=="inline-wrapper"||e.kind!==De?e:e.children.length===0?null:e},renderInline(e,t){var i;if(e.type!=="inline-wrapper"||e.kind!==De)return null;const n=document.createElement("a"),r=typeof((i=e.data)==null?void 0:i.url)=="string"?e.data.url:"";n.setAttribute("href",r),n.className="cake-link cake-pipe-link";for(const o of e.children)for(const s of t.renderInline(o))n.append(s);return n}},Je="blockquote",Vt="> ",$e={name:"blockquote",parseBlock(e,t,n){if(e.slice(t,t+Vt.length)!==Vt)return null;const r=[];let i=t;for(;i<e.length&&e.slice(i,i+Vt.length)===Vt;){let o=e.indexOf(`
42
+ `,i);o===-1&&(o=e.length);const s=i+Vt.length,l={type:"paragraph",content:n.parseInline(e,s,o)};if(r.push(l),o>=e.length){i=o;break}const c=o+1;if(e.slice(c,c+Vt.length)===Vt){i=c;continue}i=o;break}return{block:{type:"block-wrapper",kind:Je,blocks:r},nextPos:i}},serializeBlock(e,t){if(e.type!=="block-wrapper"||e.kind!==Je)return null;const n=new ct;return e.blocks.forEach((r,i)=>{n.appendSourceOnly(Vt);const o=t.serializeBlock(r);n.appendSerialized(o),i<e.blocks.length-1&&n.appendText(`
43
+ `)}),n.build()},renderBlock(e,t){if(e.type!=="block-wrapper"||e.kind!==Je)return null;const n=document.createElement("blockquote");for(const r of t.renderBlocks(e.blocks))n.append(r);return n}},le="italic",Qe={name:"italic",toggleInline:{kind:le,markers:["*","_"]},keybindings:[{key:"i",meta:!0,command:{type:"toggle-inline",marker:"*"}},{key:"i",ctrl:!0,command:{type:"toggle-inline",marker:"*"}}],inlineWrapperAffinity:[{kind:le,inclusive:!0}],parseInline(e,t,n,r){const i=e[t];if(i!=="_"&&i!=="*"||i==="*"&&e[t+1]==="*"||i==="*"&&t>0&&e[t-1]==="*")return null;const o=e.indexOf(i,t+1);if(o===-1||o>=n||o===t+1&&o+1<n)return null;const s=r.parseInline(e,t+1,o);return{inline:{type:"inline-wrapper",kind:le,children:s},nextPos:o+1}},serializeInline(e,t){if(e.type!=="inline-wrapper"||e.kind!==le)return null;const n=new ct;n.appendSourceOnly("*");for(const r of e.children){const i=t.serializeInline(r);n.appendSerialized(i)}return n.appendSourceOnly("*"),n.build()},normalizeInline(e){return e.type!=="inline-wrapper"||e.kind!==le?e:e.children.length===0?null:e},renderInline(e,t){if(e.type!=="inline-wrapper"||e.kind!==le)return null;const n=document.createElement("em");for(const r of e.children)for(const i of t.renderInline(r))n.append(i);return n}},Ae="heading",On=/^(#{1,3}) /;function Ze(e,t){let n=t;for(;n>0&&e[n-1]!==`
44
+ `;)n--;return n}function Dr(e){const{source:t,selection:n,map:r}=e;if(n.start!==n.end)return null;const i=n.start,o=r.cursorToSource(i,"forward"),s=Ze(t,o),l=t.slice(s).match(On);if(!l)return null;const c=l[0],d=s+c.length;return o!==d?null:{source:t.slice(0,s)+t.slice(d),selection:{start:i,end:i,affinity:"forward"}}}function Ar(e,t){const{source:n,selection:r,map:i,runtime:o}=e,s=t.replace(/\r\n/g,`
45
+ `).replace(/\r/g,`
46
+ `);if(!s.includes(`
47
+ `))return null;const a=Math.min(r.start,r.end),l=Math.max(r.start,r.end),c=a===l,d=c?i.cursorToSource(a,r.affinity??"forward"):i.cursorToSource(a,"forward"),m=c?d:i.cursorToSource(l,"backward"),f=Ze(n,d);let g=n.indexOf(`
48
+ `,f);if(g===-1&&(g=n.length),m>g)return null;const k=n.slice(f,g).match(On);if(!k)return null;const b=k[0],w=f+b.length;if(d<w)return null;const u=n.slice(0,d)+s+n.slice(m),E=d+s.length,L=o.createState(u).map.sourceToCursor(E,"forward");return{source:u,selection:{start:L.cursorOffset,end:L.cursorOffset,affinity:L.affinity}}}const qe={name:"heading",onEdit(e,t){if(e.type==="delete-backward")return Dr(t);if(e.type==="insert"){const m=Ar(t,e.text);if(m)return m}if(e.type!=="insert"||e.text!==" ")return null;const{source:n,selection:r,map:i}=t;if(r.start!==r.end)return null;const o=r.start,s=i.cursorToSource(o,r.affinity??"forward"),a=Ze(n,s),l=n.slice(a,s);if(!l||l.length>3||!/^[#]+$/.test(l)||s!==a+l.length)return null;const c=n.slice(0,s)+" "+n.slice(s),d=o-l.length;return{source:c,selection:{start:d,end:d,affinity:"forward"}}},parseBlock(e,t,n){let r=e.indexOf(`
49
+ `,t);r===-1&&(r=e.length);let i=t,o=0;for(;i<r&&e[i]==="#"&&o<3;)o+=1,i+=1;if(o===0||i>=r||e[i]!==" ")return null;const s=i+1,l={type:"paragraph",content:n.parseInline(e,s,r)};return{block:{type:"block-wrapper",kind:Ae,blocks:[l],data:{level:o}},nextPos:r}},serializeBlock(e,t){var a;if(e.type!=="block-wrapper"||e.kind!==Ae)return null;const n=typeof((a=e.data)==null?void 0:a.level)=="number"?e.data.level:1,r=Math.max(1,Math.min(3,n)),i=`${"#".repeat(r)} `,o=new ct;o.appendSourceOnly(i);const s=e.blocks[0];return s&&o.appendSerialized(t.serializeBlock(s)),o.build()},normalizeBlock(e){return e.type!=="block-wrapper"||e.kind!==Ae?e:e.blocks.length===0?{...e,blocks:[{type:"paragraph",content:[]}]}:e},renderBlock(e,t){var s;if(e.type!=="block-wrapper"||e.kind!==Ae)return null;const n=typeof((s=e.data)==null?void 0:s.level)=="number"?e.data.level:1,r=Math.max(1,Math.min(3,n)),i=document.createElement("div");i.setAttribute("data-block","paragraph"),i.setAttribute("data-line-index",String(t.getLineIndex())),i.classList.add("cake-line","is-heading",`is-heading-${r}`),i.dataset.lineKind="heading",i.dataset.headingLevel=String(r),t.incrementLineIndex();const o=e.blocks[0];if((o==null?void 0:o.type)==="paragraph"&&o.content.length>0){const a=Be(o.content);for(const l of a)for(const c of t.renderInline(l))i.append(c)}else{i.dataset.headingPlaceholder=`Heading ${r}`;const a=document.createTextNode("");t.createTextRun(a),i.append(a)}return i}},qt="image",Nr=/^!\[([^\]]*)\]\(([^)]*)\)$/,Fr=/^!\[uploading:([^\]]+)\]\(\)$/,Ur="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";function Mn(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.status==="uploading"&&typeof t.id=="string"||t.status==="ready"&&typeof t.alt=="string"&&typeof t.url=="string"}const tn={name:"image",parseBlock(e,t){let n=e.indexOf(`
50
+ `,t);n===-1&&(n=e.length);const r=e.slice(t,n).trim(),i=r.match(Fr);if(i)return{block:{type:"block-atom",kind:qt,data:{status:"uploading",id:i[1]}},nextPos:n};const o=r.match(Nr);return o?{block:{type:"block-atom",kind:qt,data:{status:"ready",alt:o[1],url:o[2]}},nextPos:n}:null},serializeBlock(e,t){if(e.type!=="block-atom"||e.kind!==qt)return null;let n="";Mn(e.data)&&(e.data.status==="uploading"?n=`![uploading:${e.data.id}]()`:n=`![${e.data.alt}](${e.data.url})`);const r=new ct;return r.appendSourceOnly(n),r.build()},normalizeBlock(e){return e.type!=="block-atom"||e.kind!==qt,e},renderBlock(e,t){if(e.type!=="block-atom"||e.kind!==qt)return null;const n=document.createElement("div");if(n.setAttribute("data-block-atom",qt),n.setAttribute("data-block-extension",qt),n.setAttribute("data-line-index",String(t.getLineIndex())),n.classList.add("cake-line"),t.incrementLineIndex(),n.setAttribute("contenteditable","false"),Mn(e.data))if(e.data.status==="uploading"){const r=document.createElement("div");r.dataset.testid="image-upload-skeleton",r.className="cake-image-skeleton animate-pulse bg-gray-200 dark:bg-gray-700 rounded",r.style.width="300px",r.style.height="200px",n.appendChild(r);const i=document.createElement("img");i.src=Ur,i.alt="",i.className="cake-image",n.appendChild(i)}else{const r=document.createElement("img");r.src=e.data.url,r.alt=e.data.alt,r.className="cake-image",n.appendChild(r)}return n}},en=/^(\s*)([-*+]|\d+\.)( )(.*)$/,Pn=2;function _r(e){return/^\d+\.$/.test(e)?"numbered":"bullet"}function Bn(e){const t=e.match(en);if(!t)return{type:"plain",content:e};const n=Math.floor(t[1].length/Pn),r=_r(t[2]),i=t[4]??"";return{type:"list-item",item:{indent:n,markerType:r,content:i}}}function Lt(e,t,n){return{lines:e.slice(t,n).split(`
51
+ `).map(Bn),startOffset:t,endOffset:n}}function Rt(e,t=1){const n=new Map;return n.set(0,t),e.lines.map(r=>{if(r.type==="plain")return r.content.trim()===""&&n.clear(),r.content;const{item:i}=r,o=" ".repeat(i.indent*Pn);if(i.markerType==="bullet")return`${o}- ${i.content}`;const s=n.get(i.indent)??1;n.set(i.indent,s+1);for(const[a]of n)a>i.indent&&n.delete(a);return`${o}${s}. ${i.content}`}).join(`
52
+ `)}function Dn(e,t){const n=e.lines[t];if(n.type!=="list-item")return e;const r=[...e.lines];return r[t]={type:"plain",content:n.item.content},{...e,lines:r}}function Ct(e,t){const n=e.split(`
53
+ `);let r=0;for(let s=0;s<n.length;s++){const a=r,l=r+n[s].length;if(t>=a&&t<=l)return{lineIndex:s,lineStart:a,lineEnd:l,line:n[s],offsetInLine:t-a};r=l+1}const i=n[n.length-1]??"",o=e.length-i.length;return{lineIndex:n.length-1,lineStart:o,lineEnd:e.length,line:i,offsetInLine:t-o}}function ce(e){const t=e.match(en);return t?t[1].length+t[2].length+t[3].length:null}function xt(e){return en.test(e)}function Pt(e){const t=Bn(e);return t.type!=="list-item"?null:t.item}function Hr(e,t){const n=e.split(`
54
+ `);let r=0;for(let i=0;i<t&&i<n.length;i++){const o=Pt(n[i]);o&&o.markerType==="numbered"&&o.indent===0&&r++}return r}const zr=/^(\s*)([-*+]|\d+\.)( )(.*)$/;function An(e){const t=e.match(zr);if(!t)return null;const n=t[1],r=t[2],i=t[3],o=t[4]??"",s=/^\d+\.$/.test(r)?Number.parseInt(r,10):null,a=`${n}${r}${i}`;return{indent:n,marker:r,number:s,space:i,content:o,prefix:a}}function Ne(e){return e.split(`
55
+ `)}function vt(e,t){const n=e.split(`
56
+ `),r=n[t];if(!xt(r))return null;let i=t;for(;i>0;){const l=n[i-1];if(!xt(l))break;i--}let o=t;for(;o<n.length-1;){const l=n[o+1];if(!xt(l))break;o++}let s=0;for(let l=0;l<i;l++)s+=n[l].length+1;let a=s;for(let l=i;l<=o;l++)a+=n[l].length,l<o&&(a+=1);return{startOffset:s,endOffset:a,lineIndexInBlock:t-i}}function Nn(e,t,n,r,i){const o=vt(e,t);if(!o)return null;const s=Lt(e,o.startOffset,o.endOffset),a=n(s,o.lineIndexInBlock),l=Rt(a),c=e.slice(0,o.startOffset)+l+e.slice(o.endOffset),d=r(e,c,o.startOffset,i);return{source:c,selection:d}}function Fe(e,t){const n=Ct(e,t.start),r=Ct(e,Math.max(t.start,t.end-1));return{startLine:n.lineIndex,endLine:r.lineIndex}}function Vr(e){const{source:t,selection:n,map:r,runtime:i}=e;let o=t,s=n.start,a=r.cursorToSource(s,"forward");if(n.start!==n.end){const[K,z]=n.start<=n.end?[n.start,n.end]:[n.end,n.start],J=r.cursorToSource(K,"backward"),tt=r.cursorToSource(z,"forward");o=t.slice(0,J)+t.slice(tt),s=K,a=J}const l=Ct(o,a),c=Pt(l.line);if(!c)return null;const d=ce(l.line);if(d===null)return null;if(l.offsetInLine===0){const K=o.slice(0,a)+`
57
+ `+o.slice(a),J=i.createState(K).map.sourceToCursor(a+1,"forward");return{source:K,selection:{start:J.cursorOffset,end:J.cursorOffset,affinity:"forward"}}}if(c.content.trim()===""){const K=Nn(o,l.lineIndex,(tt,st)=>Dn(tt,st),()=>({start:l.lineStart,end:l.lineStart,affinity:"forward"}),{start:a,end:a,affinity:"forward"});if(!K)return null;const J=i.createState(K.source).map.sourceToCursor(K.selection.start,"forward");return{source:K.source,selection:{start:J.cursorOffset,end:J.cursorOffset,affinity:"forward"}}}const m=l.lineStart+d,f=o.slice(m,a),g=o.slice(a,l.lineEnd),p=vt(o,l.lineIndex);if(!p)return null;const k=Lt(o,p.startOffset,p.endOffset),b=k.lines[p.lineIndexInBlock];if(b.type!=="list-item")return null;const w=[...k.lines];w[p.lineIndexInBlock]={type:"list-item",item:{...b.item,content:f}};const u={indent:b.item.indent,markerType:b.item.markerType,content:g};w.splice(p.lineIndexInBlock+1,0,{type:"list-item",item:u});const E={...k,lines:w},C=Rt(E),L=o.slice(0,p.startOffset)+C+o.slice(p.endOffset),T=L.split(`
58
+ `);let A=0;for(let K=0;K<l.lineIndex+1;K++)A+=T[K].length+1;const D=ce(T[l.lineIndex+1])??0;A+=D;const Z=i.createState(L).map.sourceToCursor(A,"forward");return{source:L,selection:{start:Z.cursorOffset,end:Z.cursorOffset,affinity:"forward"}}}function jr(e){const{source:t,selection:n,map:r,runtime:i}=e,o=(m,f,g="forward")=>{const p=i.createState(m),k=p.map.sourceToCursor(f,g);return{source:p.source,selection:{start:k.cursorOffset,end:k.cursorOffset,affinity:"forward"}}},s=m=>{const f=i.createState(m.source),g=f.map.sourceToCursor(m.selection.start,"forward"),p=f.map.sourceToCursor(m.selection.end,"backward");return{source:f.source,selection:{start:g.cursorOffset,end:p.cursorOffset,affinity:"forward"}}};if(n.start!==n.end){const m=Math.min(n.start,n.end),f=Math.max(n.start,n.end),g=r.cursorToSource(m,"backward"),p=r.cursorToSource(f,"forward"),k=Ct(t,g);if(!xt(k.line))return null;const b=Ct(t,Math.max(0,p-1)),w=k.lineIndex===b.lineIndex,u=k.offsetInLine===0&&p===k.lineEnd,E=t.split(`
59
+ `),C=k.lineIndex===E.length-1;if(!w||!u||!C)return null;const L=k.lineStart>0&&t[k.lineStart-1]===`
60
+ `?k.lineStart-1:k.lineStart,T=t.slice(0,L)+t.slice(p);return o(T,L,"forward")}const a=n.start;if(a===0)return null;const l=r.cursorToSource(a,"backward"),c=Ct(t,l),d=ce(c.line);if(d===null){if(c.offsetInLine===0&&c.lineIndex>0){const f=t.split(`
61
+ `)[c.lineIndex-1];if(xt(f)){const g=t.slice(0,c.lineStart-1)+t.slice(c.lineStart),p=vt(g,c.lineIndex-1);if(p){const k=Lt(g,p.startOffset,p.endOffset),b=Rt(k),w=g.slice(0,p.startOffset)+b+g.slice(p.endOffset);return o(w,c.lineStart-1,"forward")}}}return null}if(c.offsetInLine===d){const m=Nn(t,c.lineIndex,(f,g)=>Dn(f,g),()=>({start:c.lineStart,end:c.lineStart,affinity:"forward"}),n);return m?s(m):null}if(c.offsetInLine===0&&c.lineIndex>0){const m=t.split(`
62
+ `),f=m[c.lineIndex-1],g=Pt(c.line),p=Pt(f);if(g&&!p){const k=t.slice(0,c.lineStart-1)+t.slice(c.lineStart);let w=Ct(k,c.lineStart-1).lineIndex;const u=k.split(`
63
+ `);for(;w<u.length&&!xt(u[w]);)w++;if(w<u.length){const E=vt(k,w);if(E){const C=Lt(k,E.startOffset,E.endOffset),L=Rt(C),T=k.slice(0,E.startOffset)+L+k.slice(E.endOffset);return o(T,c.lineStart-1,"forward")}}return o(k,c.lineStart-1,"forward")}if(g&&p){let k=0;for(let A=0;A<c.lineIndex-1;A++)k+=m[A].length+1;const b=ce(f)??0,w=k+b+p.content.length,u=p.content+(g.content?" "+g.content:""),E=f.slice(0,b)+u,C=[...m];C[c.lineIndex-1]=E,C.splice(c.lineIndex,1);const L=C.join(`
64
+ `),T=vt(L,c.lineIndex-1);if(T){const A=Lt(L,T.startOffset,T.endOffset),D=Rt(A),j=L.slice(0,T.startOffset)+D+L.slice(T.endOffset);return o(j,w,"forward")}return o(L,w,"forward")}return null}return null}function Wr(e){const{source:t,selection:n,map:r,runtime:i}=e;if(n.start!==n.end)return null;const o=n.start;if(o>=r.cursorLength)return null;const s=r.cursorToSource(o,"forward"),a=Ct(t,s);if(s===a.lineEnd&&s<t.length){const l=t.split(`
65
+ `),c=a.lineIndex+1;if(c<l.length){const d=l[c];if(xt(a.line)||xt(d)){const m=t.slice(0,s)+t.slice(s+1),f=vt(m,a.lineIndex);if(f){const g=Lt(m,f.startOffset,f.endOffset),p=Rt(g),k=m.slice(0,f.startOffset)+p+m.slice(f.endOffset),b=i.createState(k),w=b.map.sourceToCursor(s,"forward");return{source:b.source,selection:{start:w.cursorOffset,end:w.cursorOffset,affinity:"forward"}}}}}}return null}function Kr(e){const{source:t,selection:n}=e,{startLine:r,endLine:i}=Fe(t,n),o=Ne(t);let s=!1;for(let g=r;g<=i;g++)if(xt(o[g])){s=!0;break}if(!s)return null;const a=[...o];for(let g=r;g<=i;g++)xt(o[g])&&(a[g]=" "+o[g]);let l=a.join(`
66
+ `);const c=vt(l,r);if(c){const g=Lt(l,c.startOffset,c.endOffset),p=Rt(g);l=l.slice(0,c.startOffset)+p+l.slice(c.endOffset)}const d=i-r+1,m=n.start+2,f=n.end+d*2;return{source:l,selection:{start:m,end:f,affinity:"forward"}}}function Yr(e){const{source:t,selection:n}=e,{startLine:r,endLine:i}=Fe(t,n),o=Ne(t);let s=!1;for(let w=r;w<=i;w++)if(xt(o[w])){s=!0;break}if(!s)return null;const a=[...o];let l=0;for(let w=r;w<=i;w++){const u=o[w],E=Pt(u);if(E)if(E.indent>0)a[w]=u.slice(2),l+=2;else{const C=ce(u)??0;a[w]=E.content,l+=C}}let c=a.join(`
67
+ `),d=-1;const m=a.findIndex((w,u)=>u>=r&&u<=i?!1:xt(w));if(m>=0){const w=vt(c,m);if(w){d=w.endOffset;const u=Lt(c,w.startOffset,w.endOffset),E=Rt(u);c=c.slice(0,w.startOffset)+E+c.slice(w.endOffset)}}for(let w=i+1;w<a.length;w++)if(xt(a[w])){const u=vt(c,w);if(u&&u.startOffset>=d){const E=Lt(c,u.startOffset,u.endOffset),C=Hr(c,w)+1,L=Rt(E,C);c=c.slice(0,u.startOffset)+L+c.slice(u.endOffset)}break}const f=Ct(t,n.start),g=Pt(o[r]),p=g&&g.indent===0,k=p?f.lineStart:Math.max(f.lineStart,n.start-2),b=p?f.lineStart:Math.max(k,n.end-l);return{source:c,selection:{start:k,end:b,affinity:"forward"}}}function Fn(e,t){const{source:n,selection:r}=e,{startLine:i,endLine:o}=Fe(n,r),s=Ne(n),c=t?/^(\s*)([-*+])( )/:/^(\s*)(\d+)\.( )/;let d=!0,m=!1;for(let w=i;w<=o;w++){const u=s[w];if(u.trim()!==""&&(m=!0,!c.test(u))){d=!1;break}}if(!m)return null;const f=[...s];let g=1;if(d)for(let w=i;w<=o;w++){const u=s[w];if(u.trim()==="")continue;const E=Pt(u);E&&(f[w]=E.content)}else for(let w=i;w<=o;w++){const u=s[w];if(u.trim()==="")continue;const E=Pt(u),C=u.match(/^(\s*)/),L=C?C[1]:"",T=Math.floor(L.length/2);let A;E?A=E.content:A=u.slice(L.length);let D;t?D=" ".repeat(T)+"- ":(D=" ".repeat(T)+`${g}. `,g++),f[w]=D+A}let p=f.join(`
68
+ `);if(!d&&!t){const w=vt(p,i);if(w){const u=Lt(p,w.startOffset,w.endOffset),E=Rt(u);p=p.slice(0,w.startOffset)+E+p.slice(w.endOffset)}}let k=0;for(let w=0;w<i;w++)k+=f[w].length+1;let b=k;for(let w=i;w<=o;w++)b+=f[w].length,w<o&&(b+=1);return{source:p,selection:{start:k,end:b,affinity:"forward"}}}function Gr(e,t){const{source:n,selection:r}=e;if(r.start===r.end||t!=="-"&&t!=="*"&&t!=="+")return null;const{startLine:i,endLine:o}=Fe(n,r),s=Ne(n);let a=0;for(let u=0;u<i;u++)a+=s[u].length+1;let l=a;for(let u=i;u<=o;u++)l+=s[u].length+(u<o?1:0);const c=Math.min(r.start,r.end),d=Math.max(r.start,r.end);if(!(c===a)||!(d===l))return null;const g=[...s];for(let u=i;u<=o;u++){const E=s[u];if(E.trim()==="")continue;const C=Pt(E),L=E.match(/^(\s*)/),T=L?L[1]:"",A=Math.floor(T.length/2);let D;C?D=C.content:D=E.slice(T.length);const j=" ".repeat(A)+`${t} `;g[u]=j+D}const p=g.join(`
69
+ `);let k=0;for(let u=0;u<i;u++)k+=g[u].length+1;const b=g[i],w=ce(b)??0;return k+=w,{source:p,selection:{start:k,end:k,affinity:"forward"}}}function Xr(e,t){const{source:n,selection:r}=e;if(r.start!==r.end)return Gr(e,t);if(t!=="-"&&t!=="*"&&t!=="+")return null;const i=r.start,o=Ct(n,i),s=An(o.line);if(!s||s.number!==null)return null;const a=s.indent.length;if(o.offsetInLine>a||s.marker===t)return null;const l=s.indent+t+s.space+s.content;return{source:n.slice(0,o.lineStart)+l+n.slice(o.lineStart+o.line.length),selection:{start:i+1,end:i+1,affinity:"forward"}}}function Jr(e){if(e.type!=="paragraph")return null;let t="";for(const n of e.content)if(n.type==="text")t+=n.text;else if(n.type==="inline-wrapper")for(const r of n.children)r.type==="text"&&(t+=r.text);else n.type==="inline-atom"&&(t+=" ");return t}const nn={name:"list",keybindings:[{key:"8",meta:!0,shift:!0,command:{type:"toggle-bullet-list"}},{key:"8",ctrl:!0,shift:!0,command:{type:"toggle-bullet-list"}},{key:"7",meta:!0,shift:!0,command:{type:"toggle-numbered-list"}},{key:"7",ctrl:!0,shift:!0,command:{type:"toggle-numbered-list"}}],onEdit(e,t){return e.type==="insert-line-break"?Vr(t):e.type==="delete-backward"?jr(t):e.type==="delete-forward"?Wr(t):e.type==="indent"?Kr(t):e.type==="outdent"?Yr(t):e.type==="toggle-bullet-list"?Fn(t,!0):e.type==="toggle-numbered-list"?Fn(t,!1):e.type==="insert"&&e.text.length===1?Xr(t,e.text):null},renderBlock(e,t){if(e.type!=="paragraph")return null;const n=Jr(e);if(!n)return null;const r=An(n);if(!r)return null;const i=document.createElement("div");i.setAttribute("data-block","paragraph"),i.setAttribute("data-line-index",String(t.getLineIndex())),i.classList.add("cake-line","is-list"),t.incrementLineIndex();const o=Math.floor(r.indent.length/2);o>0&&i.style.setProperty("--cake-list-indent",`${o*2}ch`);const s=`${r.marker}${r.space}`;if(i.style.setProperty("--cake-list-marker",`${s.length}ch`),e.content.length===0){const a=document.createTextNode("");t.createTextRun(a),i.append(a),i.append(document.createElement("br"))}else{const a=Be(e.content);for(const l of a)for(const c of t.renderInline(l))i.append(c)}return i}},Un=30,$r=500,rn=8;function Qr({container:e}){const[t,n]=_.useState({scrollTop:0,scrollHeight:0,clientHeight:0}),[r,i]=_.useState(!1),[o,s]=_.useState(!1),[a,l]=_.useState(!1),c=_.useRef(null),d=_.useRef(null),{scrollTop:m,scrollHeight:f,clientHeight:g}=t,p=f>g,k=g-rn*2,b=p?g/f*k:0,w=Math.min(k,Math.max(Un,b)),u=f-g,E=u>0?rn+m/u*(k-w):rn;_.useEffect(()=>{function j(){n({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Z(){j(),l(!0),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{l(!1)},$r)}j(),e.addEventListener("scroll",Z),window.addEventListener("resize",j);let K=null,z=null,J=null;const tt=()=>{if(!K)return;const st=e.querySelector(".cake-content");st!==J&&(J&&K.unobserve(J),J=st,J&&K.observe(J))};return typeof ResizeObserver<"u"&&(K=new ResizeObserver(j),K.observe(e),tt()),typeof MutationObserver<"u"&&(z=new MutationObserver(()=>{tt(),j()}),z.observe(e,{childList:!0,subtree:!0,characterData:!0})),()=>{e.removeEventListener("scroll",Z),window.removeEventListener("resize",j),K==null||K.disconnect(),z==null||z.disconnect(),d.current&&clearTimeout(d.current)}},[e]);const C=_.useCallback(j=>{if(j.target!==j.currentTarget)return;const Z=j.currentTarget.getBoundingClientRect(),J=(j.clientY-Z.top)/k*u;e.scrollTop=Math.max(0,Math.min(J,u))},[e,k,u]),L=_.useCallback(j=>{j.preventDefault(),j.stopPropagation(),i(!0),c.current={scrollTop:e.scrollTop,clientY:j.clientY}},[e]);if(_.useEffect(()=>{if(!r)return;const j=document.body.style.userSelect;document.body.style.userSelect="none";function Z(z){if(z.preventDefault(),z.stopPropagation(),!c.current)return;const J=z.clientY-c.current.clientY,tt=k-w,ht=(tt>0?J/tt:0)*u;e.scrollTop=Math.max(0,Math.min(c.current.scrollTop+ht,u))}function K(z){z.preventDefault(),z.stopPropagation(),i(!1),c.current=null}return document.addEventListener("mousemove",Z,{capture:!0}),document.addEventListener("mouseup",K,{capture:!0}),()=>{document.removeEventListener("mousemove",Z,{capture:!0}),document.removeEventListener("mouseup",K,{capture:!0}),document.body.style.userSelect=j}},[r,e,k,w,u]),!p||k<Un)return null;const T=r||o||a,A={position:"absolute",top:0,right:0,bottom:0,width:"12px",height:g,pointerEvents:"auto"},D={position:"absolute",right:"2px",width:"6px",borderRadius:"9999px",height:w,top:E,opacity:T?1:0};return Q.jsxDEV("div",{"data-testid":"custom-scrollbar","aria-hidden":"true",className:"pointer-events-auto absolute top-0 right-0 bottom-0 z-50 w-3",style:A,onClick:C,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),children:Q.jsxDEV("div",{"data-testid":"scrollbar-thumb",className:`absolute right-0.5 w-1.5 cursor-pointer rounded-full transition-opacity duration-150 ${r?"bg-black/50 dark:bg-white/50":"bg-black/30 dark:bg-white/30"}`,style:D,onMouseDown:L},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/scrollbar/index.tsx",lineNumber:230,columnNumber:7},this)},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/scrollbar/index.tsx",lineNumber:221,columnNumber:5},this)}const Zr={type:"overlay",name:"scrollbar",render(e){return Q.jsxDEV(Qr,{container:e.container},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/extensions/scrollbar/index.tsx",lineNumber:248,columnNumber:12},this)}},ue="strikethrough",on={name:"strikethrough",toggleInline:{kind:ue,markers:["~~"]},keybindings:[{key:"x",meta:!0,shift:!0,command:{type:"toggle-inline",marker:"~~"}},{key:"x",ctrl:!0,shift:!0,command:{type:"toggle-inline",marker:"~~"}}],inlineWrapperAffinity:[{kind:ue,inclusive:!0}],parseInline(e,t,n,r){if(e.slice(t,t+2)!=="~~")return null;const i=e.indexOf("~~",t+2);if(i===-1||i>=n||i===t+2&&i+2<n)return null;const o=r.parseInline(e,t+2,i);return{inline:{type:"inline-wrapper",kind:ue,children:o},nextPos:i+2}},serializeInline(e,t){if(e.type!=="inline-wrapper"||e.kind!==ue)return null;const n=new ct;n.appendSourceOnly("~~");for(const r of e.children){const i=t.serializeInline(r);n.appendSerialized(i)}return n.appendSourceOnly("~~"),n.build()},normalizeInline(e){return e.type!=="inline-wrapper"||e.kind!==ue?e:e.children.length===0?null:e},renderInline(e,t){if(e.type!=="inline-wrapper"||e.kind!==ue)return null;const n=document.createElement("s");for(const r of e.children)for(const i of t.renderInline(r))n.append(i);return n}},_n=[$e,qe,nn,Ye,Ke,Qe,on,Xe,Ge,tn];function jt(e){return{top:e.rect.top-e.containerRect.top+e.scroll.top,left:e.rect.left-e.containerRect.left+e.scroll.left,width:e.rect.width,height:e.rect.height}}function qr(e){var o,s,a,l;if(e.length===0)return null;let t=((o=e[0])==null?void 0:o.left)??0,n=((s=e[0])==null?void 0:s.top)??0,r=t+(((a=e[0])==null?void 0:a.width)??0),i=n+(((l=e[0])==null?void 0:l.height)??0);return e.forEach(c=>{const d=c.left+c.width,m=c.top+c.height;t=Math.min(t,c.left),n=Math.min(n,c.top),r=Math.max(r,d),i=Math.max(i,m)}),new DOMRect(t,n,r-t,i-n)}function ti(e,t){const n=e.top+e.height,r=t.top+t.height;return e.top<r&&t.top<n}function ei(e){if(e.length===0)return[];const t=[...e].sort((r,i)=>r.top===i.top?r.left-i.left:r.top-i.top),n=[];return t.forEach(r=>{const i=n[n.length-1];if(i&&ti(i,r)){n[n.length-1]=qr([i,r])??i;return}n.push(r)}),n}function Ue(e,t){if(e.length===0)return 0;const n=Math.max(0,Math.min(t,e.length-1));return e[n]??0}function ni(e){if(e.lineLength<=0)return null;const t=Ue(e.cursorToCodeUnit,e.offset),n=Ue(e.cursorToCodeUnit,Math.min(e.offset+1,e.lineLength)),r=Tt(e.lineElement,t),i=Tt(e.lineElement,n),o=document.createRange();o.setStart(r.node,r.offset),o.setEnd(i.node,i.offset);const s=o.getClientRects();if(s.length>0)return s[0]??null;const a=o.getBoundingClientRect();return a.width===0&&a.height===0?null:a}function ri(e){if(e.lineLength===0)return[{startOffset:0,endOffset:0,rect:{...jt({rect:e.lineRect,containerRect:e.containerRect,scroll:e.scroll}),width:0}}];const t=document.createRange(),n=Tt(e.lineElement,0),r=Tt(e.lineElement,e.codeUnitLength);t.setStart(n.node,n.offset),t.setEnd(r.node,r.offset);const i=ei(Array.from(t.getClientRects())),o=jt({rect:e.lineRect,containerRect:e.containerRect,scroll:e.scroll}),s=ni({lineElement:e.lineElement,offset:0,lineLength:e.lineLength,cursorToCodeUnit:e.cursorToCodeUnit}),a=(s==null?void 0:s.width)??0;if(i.length===0||a<=0){const d=[{startOffset:0,endOffset:e.lineLength,rect:o}];return d.length===1?[{...d[0],rect:{...d[0].rect,top:o.top,height:o.height}}]:d}let l=0;const c=i.map((d,m)=>{const f=e.lineLength-l,g=m===i.length-1,p=Math.max(1,Math.round(d.width/a)),k=g?f:Math.min(f,p),b={startOffset:l,endOffset:l+k,rect:jt({rect:d,containerRect:e.containerRect,scroll:e.scroll})};return l+=k,b});return c.length>0&&(c[c.length-1]={...c[c.length-1],endOffset:e.lineLength}),c.length===1&&(c[0]={...c[0],rect:{...c[0].rect,top:o.top,height:o.height}}),c}function ii(e){const t=e.container.getBoundingClientRect();return Number.isFinite(t.width)?{container:{top:0,left:0,width:t.width,height:t.height},measureLine:({lineIndex:n,lineLength:r,top:i})=>{const o=e.lines[n],s=e.container.getBoundingClientRect(),a={top:e.container.scrollTop,left:e.container.scrollLeft},l=be(e.root,n);if(!l||!o)return{lineBox:{top:i,left:0,width:s.width,height:0},rows:[]};const c=l.getBoundingClientRect();return{lineBox:jt({rect:c,containerRect:s,scroll:a}),rows:ri({lineElement:l,lineLength:r,lineRect:c,containerRect:s,scroll:a,cursorToCodeUnit:o.cursorToCodeUnit,codeUnitLength:o.text.length})}}}:null}function Hn(e){const t=ii({root:e.root,container:e.container,lines:e.lines});return t?Or(e.lines,t):null}function be(e,t){return e.querySelector(`[data-line-index="${t}"]`)}function oi(e){return document.createTreeWalker(e,NodeFilter.SHOW_TEXT)}function Tt(e,t){var o;const n=oi(e);let r=t,i=n.nextNode();for(;i;){const s=((o=i.textContent)==null?void 0:o.length)??0;if(r<=s)return{node:i,offset:r};r-=s,i=n.nextNode()}return e.textContent?{node:e,offset:e.childNodes.length}:{node:e,offset:0}}function si(e){const{root:t,container:n,lines:r}=e,i=n.getBoundingClientRect(),o=n.scrollLeft;return(s,a)=>{const l=be(t,s),c=r[s];if(!l||!c)return null;const d=Ue(c.cursorToCodeUnit,a),m=Tt(l,d),f=document.createRange();f.setStart(m.node,m.offset),f.setEnd(m.node,m.offset);const g=f.getClientRects();if(g.length>0)return g[0].left-i.left+o;const p=f.getBoundingClientRect();return p.width===0&&p.left!==0?p.left-i.left+o:null}}function Ie(e,t){return Ue(e,t)}function zn(e){return e.left+e.width}function Vn(e,t,n){const r=e.rows.length;if(r<=1)return{top:e.lineBox.top,height:e.lineBox.height};const i=e.lineBox.height;if(!Number.isFinite(i)||i<=0)return{top:n.rect.top,height:n.rect.height};const o=i/r;return!Number.isFinite(o)||o<=0?{top:n.rect.top,height:n.rect.height}:{top:e.lineBox.top+o*t,height:o}}function sn(e,t,n,r){const i=Math.max(e.startOffset,Math.min(t,e.endOffset));if(r){const a=r(n,i);if(a!==null)return a}const o=e.endOffset-e.startOffset;if(o<=0)return e.rect.left;const s=e.rect.width/o;return e.rect.left+s*(i-e.startOffset)}function ai(e,t){for(let n=0;n<e.length;n+=1)if(t<e[n].endOffset)return n;return Math.max(0,e.length-1)}function li(e,t){for(let n=e.length-1;n>=0;n-=1)if(t>e[n].startOffset)return n;return 0}function ci(e,t,n){const r=Math.min(t.start,t.end),i=Math.max(t.start,t.end);if(r===i)return[];const o=[];return e.lines.forEach(s=>{const a=s.lineStartOffset+s.lineLength,l=Math.max(0,Math.min(r-s.lineStartOffset,s.lineLength)),c=Math.max(0,Math.min(i-s.lineStartOffset,s.lineLength)),d=r<=a&&i>a&&s.lineHasNewline,m=r<s.lineStartOffset;if(!(l<c||d))return;const g=s.lineBox.left,p=zn(s.lineBox);if(s.lineLength===0){const b=Math.max(1,s.lineBox.width);o.push({top:s.lineBox.top,left:g,width:b,height:s.lineBox.height});return}if(s.rows.length===0)return;if(l===c&&d){const b=ai(s.rows,l),w=s.rows[b]??s.rows[s.rows.length-1],u=Vn(s,b,w),E=Math.max(sn(w,l,s.lineIndex,n),g),C=Math.max(1,p-E);o.push({top:u.top,left:E,width:C,height:u.height});return}const k=li(s.rows,c);s.rows.forEach((b,w)=>{const u=Math.max(l,b.startOffset),E=Math.min(c,b.endOffset);if(u>=E)return;const C=Vn(s,w,b),L=l<=b.startOffset;let A=L?(d||m)&&L?g:b.rect.left:sn(b,u,s.lineIndex,n);A=Math.max(A,g);const D=w===k,j=d||m&&!D,Z=!D&&E===b.endOffset;let K=j||Z?p:D?sn(b,E,s.lineIndex,n):zn(b.rect);K=Math.max(K,A);const z=Math.max(1,K-A);o.push({top:C.top,left:A,width:z,height:C.height})})}),o}function jn(e){const t=e.caretRect.height>0?e.caretRect.height:e.lineRect.height,n=e.lineHeight??t,r=e.lineRect.height>0?Math.max(0,e.lineRect.height-e.padding.top-e.padding.bottom):0,i=e.lineLength===0?e.nearestTextCaretHeight??e.fontSize??(r>0?r:null)??n:null,o=e.lineLength===0?i??n:e.caretRect.height>0?e.caretRect.height:n,s=r>0?e.lineRect.top+e.padding.top+(r-o)/2:e.lineRect.top+(e.lineRect.height-o)/2,a=e.lineLength===0?s:e.caretRect.height>0?e.caretRect.top:e.lineRect.top,l=e.lineLength===0?e.lineRect.left:e.caretRect.left;return{top:a,left:l,width:0,height:o}}function ui(e){const{root:t,container:n,docLines:r,selection:i}=e,o=i.start<=i.end?i:{start:i.end,end:i.start,affinity:i.affinity},s=fi(o)?Hn({lines:r,root:t,container:n}):null,a=n.getBoundingClientRect(),l={top:n.scrollTop,left:n.scrollLeft},c=ut(r,o.start);if(!(o.start!==o.end)){const b=r[c.lineIndex],w=be(t,c.lineIndex);if(!b||!w)return{selectionRects:[],caretRect:null,focusRect:null};const u=_e({lineElement:w,lineInfo:b,offsetInLine:c.offsetInLine,affinity:i.affinity??"forward"});if(!u)return{selectionRects:[],caretRect:null,focusRect:null};const E={lineRect:jt({rect:u.lineRect,containerRect:a,scroll:l}),caretRect:jt({rect:u.rect,containerRect:a,scroll:l}),lineLength:b.cursorLength,lineHeight:Wn(w),fontSize:Kn(w),padding:Yn(w),nearestTextCaretHeight:Gn(t,r,c.lineIndex)},C=jn(E);return{selectionRects:[],caretRect:C,focusRect:C}}if(!s)return{selectionRects:[],caretRect:null,focusRect:null};const m=si({root:t,container:n,lines:r}),f=o.affinity==="backward"?o.start:o.end,g=ut(r,f),p=be(t,g.lineIndex);let k=null;if(p){const b=r[g.lineIndex];if(b){const w=_e({lineElement:p,lineInfo:b,offsetInLine:g.offsetInLine,affinity:i.affinity??"forward"});if(w){const u={lineRect:jt({rect:w.lineRect,containerRect:a,scroll:l}),caretRect:jt({rect:w.rect,containerRect:a,scroll:l}),lineLength:b.cursorLength,lineHeight:Wn(p),fontSize:Kn(p),padding:Yn(p),nearestTextCaretHeight:Gn(t,r,g.lineIndex)};k=jn(u)}}}return{selectionRects:ci(s,o,m),caretRect:null,focusRect:k}}function fi(e){return e.start!==e.end}function _e(e){const{lineElement:t,lineInfo:n,offsetInLine:r,affinity:i}=e,o=Math.max(0,Math.min(r,n.cursorLength)),s=Ie(n.cursorToCodeUnit,o),a=Tt(t,s),l=document.createRange();if(l.setStart(a.node,a.offset),l.setEnd(a.node,a.offset),typeof l.getBoundingClientRect!="function")return null;const c=t.getBoundingClientRect(),d=l.getClientRects();let m;if(d.length>1&&i==="backward"){m=d[0];for(let f=1;f<d.length;f+=1)d[f].top<m.top&&(m=d[f])}else m=l.getBoundingClientRect();if(n.cursorLength>0){const f=o>0,g=o<n.cursorLength;let p=null,k=null;if(f){const E=Tt(t,Ie(n.cursorToCodeUnit,o-1)),C=Tt(t,Ie(n.cursorToCodeUnit,o)),L=document.createRange();L.setStart(E.node,E.offset),L.setEnd(C.node,C.offset);const T=L.getClientRects();T.length>0&&(p=T[T.length-1])}if(g){const E=Tt(t,Ie(n.cursorToCodeUnit,o)),C=Tt(t,Ie(n.cursorToCodeUnit,o+1)),L=document.createRange();L.setStart(E.node,E.offset),L.setEnd(C.node,C.offset);const T=L.getClientRects();T.length>0&&(k=T[0])}const b=p&&k&&Math.abs(p.top-k.top)>5;let w=null,u=!1;if(b&&i==="backward"&&p?(w=p,u=!0):k?(w=k,u=!1):p&&(w=p,u=!0),w&&w.height>0){const E=u?w.right:w.left;m=new DOMRect(E,w.top,0,w.height)}}return m.height===0&&c.height===0?null:{rect:m,lineRect:c}}function Wn(e){const t=window.getComputedStyle(e),n=t.lineHeight.trim();if(n==="normal"){const o=Number.parseFloat(t.fontSize);return!Number.isFinite(o)||o<=0?null:o*1.2}const r=Number.parseFloat(n);if(!Number.isFinite(r)||r<=0)return null;if(!/[a-z%]+$/i.test(n)){const o=Number.parseFloat(t.fontSize);return!Number.isFinite(o)||o<=0?null:r*o}return r}function Kn(e){const t=window.getComputedStyle(e).fontSize,n=Number.parseFloat(t);return!Number.isFinite(n)||n<=0?null:n}function Yn(e){const t=window.getComputedStyle(e),n=Number.parseFloat(t.paddingTop),r=Number.parseFloat(t.paddingBottom);return{top:Number.isFinite(n)?n:0,bottom:Number.isFinite(r)?r:0}}function Gn(e,t,n){for(let r=1;r<t.length;r+=1){const i=n-r,o=n+r,s=[i,o];for(const a of s){if(a<0||a>=t.length)continue;const l=t[a];if(!l||l.cursorLength===0)continue;const c=be(e,a);if(!c)continue;const d=_e({lineElement:c,lineInfo:l,offsetInLine:0});if(d!=null&&d.rect.height&&d.rect.height>0)return d.rect.height}}return null}function an(e){return e.left+e.width}function Ee(e,t,n){return Math.max(t,Math.min(e,n))}function Xn(e){return e.start===e.end?e.affinity??"backward":e.affinity??"forward"}function di(e){return e.start===e.end?{anchor:e.start,focus:e.start}:Xn(e)==="backward"?{anchor:e.end,focus:e.start}:{anchor:e.start,focus:e.end}}function hi(e,t,n){if(e.length===0)return 0;for(let r=0;r<e.length;r+=1){const i=e[r];if(t===i.startOffset)return n==="backward"&&r>0?r-1:r;if(t===i.endOffset)return n==="forward"&&r+1<e.length?r+1:r;if(t>i.startOffset&&t<i.endOffset)return r}return e.length-1}function Jn(e){return{startOffset:0,endOffset:e.lineLength,rect:e.lineBox}}function pi(e){const{row:t,offsetInLine:n}=e,r=an(t.rect),i=Ee(n,t.startOffset,t.endOffset);if(t.endOffset<=t.startOffset||t.rect.width<=0)return t.rect.left;if(i===t.endOffset)return r;const o=t.endOffset-t.startOffset,s=(i-t.startOffset)/o;return t.rect.left+t.rect.width*s}function gi(e){const{row:t,x:n}=e,r=an(t.rect);if(n<=t.rect.left)return{offsetInLine:t.startOffset,affinity:"forward"};if(n>=r)return{offsetInLine:t.endOffset,affinity:"backward"};const i=t.endOffset-t.startOffset;if(i<=0||t.rect.width<=0)return{offsetInLine:t.startOffset,affinity:"forward"};const o=(n-t.rect.left)/t.rect.width,s=t.startOffset+o*i,a=Math.round(s);return{offsetInLine:Ee(a,t.startOffset,t.endOffset),affinity:"forward"}}function $n(e){var r;const t=e.direction==="down"?1:-1;let n=e.fromLineIndex+t;for(;n>=0&&n<e.lines.length;){if(!((r=e.lines[n])!=null&&r.isAtomic))return n;n+=t}return null}function mi(e){const{lines:t,layout:n,direction:r}=e;if(n.lines.length===0||t.length===0)return null;const i=Xn(e.selection),{anchor:o,focus:s}=di(e.selection),a=ut(t,s),l=n.lines[a.lineIndex];if(!l)return null;const c=l.rows.length>0?l.rows:[Jn(l)];let d=e.focusRowIndex??hi(c,a.offsetInLine,i);d=Ee(d,0,Math.max(0,c.length-1));const m=c[d]??c[c.length-1];if(!m)return null;const f=e.goalX??pi({row:m,offsetInLine:a.offsetInLine});let g=a.lineIndex,p=d;if(r==="up")if(d>0)p=d-1;else{const D=$n({lines:t,fromLineIndex:a.lineIndex,direction:"up"});if(D===null)return null;g=D,p=Number.POSITIVE_INFINITY}else if(d+1<c.length)p=d+1;else{const D=$n({lines:t,fromLineIndex:a.lineIndex,direction:"down"});if(D===null)return null;g=D,p=0}const k=n.lines[g];if(!k)return null;const b=k.rows.length>0?k.rows:[Jn(k)],w=p===Number.POSITIVE_INFINITY?Math.max(0,b.length-1):Ee(p,0,Math.max(0,b.length-1)),u=b[w]??b[b.length-1];if(!u)return null;const E=k.lineStartOffset,C=E+k.lineLength;if(e.hitTestCursorAt){const D=u.rect.top+u.rect.height/2,j=u.rect.left,Z=an(u.rect),K=Z-j>1?Ee(f,j+.5,Z-.5):f;let z=e.hitTestCursorAt(K,D);if(z&&z.cursorOffset===s)for(let tt=0;tt<80;tt+=1){const st=K-(tt+1)*1;if(st<=j+.5)break;const ht=e.hitTestCursorAt(st,D),fe=(ht==null?void 0:ht.caretTop)===void 0||Math.abs(ht.caretTop-u.rect.top)<=2;if(ht&&ht.cursorOffset!==s&&fe){z=ht;break}}const J=(z==null?void 0:z.caretTop)===void 0||Math.abs(z.caretTop-u.rect.top)<=2;if(z&&J&&z.cursorOffset>=E&&z.cursorOffset<=C)return{selection:o===s?{start:z.cursorOffset,end:z.cursorOffset,affinity:z.affinity}:{start:o,end:z.cursorOffset,affinity:z.affinity},goalX:f}}const L=gi({row:u,x:f}),T=E+L.offsetInLine;return{selection:o===s?{start:T,end:T,affinity:L.affinity}:{start:o,end:T,affinity:L.affinity},goalX:f}}function yi(){if(typeof navigator>"u")return"linux";const e=navigator.platform;return/Mac|iPhone|iPad|iPod/.test(e)?"mac":/Win/.test(e)?"windows":"linux"}function xi(){return yi()==="mac"}function ln(e){return lr(e).map(t=>({segment:t.segment,index:t.index,isWordLike:t.isWordLike??!1}))}function ki(e){return/^\s+$/.test(e)}function wi(e){return/^[\p{P}\p{S}]+$/u.test(e)}function Ot(e){return e.isWordLike?!0:!(ki(e.segment)||wi(e.segment))}function Si(e,t){if(e.length===0)return{start:0,end:0};const n=Math.max(0,Math.min(t,e.length)),r=ln(e);for(let i=0;i<r.length;i+=1){const o=r[i],s=o.index+o.segment.length;if(n>=o.index&&n<s)return{start:o.index,end:s};if(n===s&&i===r.length-1)return{start:o.index,end:s}}if(r.length>0){const i=r[r.length-1];return{start:i.index,end:i.index+i.segment.length}}return{start:0,end:0}}function bi(e,t){const n=e.length;if(n===0)return{start:0,end:0};let i=Math.max(0,Math.min(t,n));return i>=n&&(i=n-1),(e[i]??"")===`
70
+ `&&i>0&&(i=i-1),Si(e,i)}function Ii(e,t){if(t<=0||e.length===0)return 0;const n=Math.min(t,e.length),r=ln(e);let i=-1;for(let o=r.length-1;o>=0;o-=1){const s=r[o];if(s.index+s.segment.length<=n){if(Ot(s)){i=o;break}i=o-1;break}if(s.index<n&&Ot(s)){i=o;break}}for(let o=i;o>=0;o-=1){const s=r[o];if(!Ot(s))continue;let a=s.index;for(let l=o-1;l>=0;l-=1){const c=r[l];if(!Ot(c)||c.index+c.segment.length!==a)break;a=c.index}return a}return 0}function Ei(e,t){if(t>=e.length||e.length===0)return e.length;const n=Math.max(0,t),r=ln(e);for(let i=0;i<r.length;i+=1){const o=r[i],s=o.index+o.segment.length;if(o.index<=n&&n<s){if(Ot(o)){let a=s;for(let l=i+1;l<r.length;l+=1){const c=r[l];if(!Ot(c)||c.index!==a)break;a=c.index+c.segment.length}return a}for(let a=i+1;a<r.length;a+=1)if(Ot(r[a])){let l=r[a].index+r[a].segment.length;for(let c=a+1;c<r.length;c+=1){const d=r[c];if(!Ot(d)||d.index!==l)break;l=d.index+d.segment.length}return l}return e.length}if(o.index>n&&Ot(o)){let a=s;for(let l=i+1;l<r.length;l+=1){const c=r[l];if(!Ot(c)||c.index!==a)break;a=c.index+c.segment.length}return a}}return e.length}const cn=new ir({headingStyle:"atx",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full"});cn.addRule("strikethrough",{filter:["del","s"],replacement:e=>`~~${e}~~`}),cn.addRule("codeBlock",{filter:"pre",replacement:(e,t)=>{const n=t.querySelector("code");if(n){const i=(n.className||"").match(/language-(\w+)/);return`
71
+ \`\`\`${i?i[1]:""}
72
+ ${n.textContent??""}
73
+ \`\`\`
74
+ `}return`
75
+ \`\`\`
76
+ ${e}
77
+ \`\`\`
78
+ `}});function Li(e){const t=e.trim();return t?cn.turndown(t):""}const Ri={start:0,end:0,affinity:"forward"},Ci=50,vi=500,Ti=100;class Qn{constructor(t){this.originalCaretRangeFromPoint=null,this.patchedCaretRangeFromPoint=null,this.contentRoot=null,this.domMap=null,this.isApplyingSelection=!1,this.isComposing=!1,this.beforeInputHandled=!1,this.beforeInputResetId=null,this.keydownHandledBeforeInput=!1,this.suppressSelectionChange=!1,this.suppressSelectionChangeResetId=null,this.ignoreTouchNativeSelectionUntil=null,this.blockTrustedTextDrag=!1,this.selectedAtomicLineIndex=null,this.lastAppliedSelection=null,this.compositionCommit=!1,this.compositionCommitTimeoutId=null,this.overlayRoot=null,this.caretElement=null,this.caretBlinkTimeoutId=null,this.overlayUpdateId=null,this.scrollCaretIntoViewId=null,this.extensionsRoot=null,this.placeholderRoot=null,this.lastFocusRect=null,this.verticalNavGoalX=null,this.history={undoStack:[],redoStack:[],lastEditAt:0,lastKind:null},this.pendingClickHit=null,this.handleBeforeInputBound=this.handleBeforeInput.bind(this),this.handleInputBound=this.handleInput.bind(this),this.handleCompositionStartBound=this.handleCompositionStart.bind(this),this.handleCompositionEndBound=this.handleCompositionEnd.bind(this),this.handleSelectionChangeBound=this.handleSelectionChange.bind(this),this.handleScrollBound=this.handleScroll.bind(this),this.handleResizeBound=this.handleResize.bind(this),this.handleClickBound=this.handleClick.bind(this),this.handleKeyDownBound=this.handleKeyDown.bind(this),this.handlePasteBound=this.handlePaste.bind(this),this.handleCopyBound=this.handleCopy.bind(this),this.handleCutBound=this.handleCut.bind(this),this.handlePointerDownBound=this.handlePointerDown.bind(this),this.handlePointerMoveBound=this.handlePointerMove.bind(this),this.handlePointerUpBound=this.handlePointerUp.bind(this),this.handleDragStartBound=this.handleDragStart.bind(this),this.handleDragOverBound=this.handleDragOver.bind(this),this.handleDropBound=this.handleDrop.bind(this),this.handleDragEndBound=this.handleDragEnd.bind(this),this.dragState=null,this.dropIndicator=null,this.textDragState=null,this.selectionDragState=null,this.pointerDownPosition=null,this.hasMovedSincePointerDown=!1,this.container=t.container,this.extensions=t.extensions??_n,this.runtime=ur(this.extensions),this.state=this.runtime.createState(t.value,t.selection??Ri),this.onChange=t.onChange,this.onSelectionChange=t.onSelectionChange,this.readOnly=t.readOnly??!1,this.spellCheckEnabled=t.spellCheckEnabled??!0,this.render(),this.attachListeners(),this.installCaretRangeFromPointShim()}get state(){return this._state}set state(t){this._state=t}isEventTargetInContentRoot(t){return t===this.container?!0:this.contentRoot?t instanceof Node&&(t===this.contentRoot||this.contentRoot.contains(t)):!1}destroy(){this.detachListeners(),this.uninstallCaretRangeFromPointShim(),this.clearCaretBlinkTimer(),this.overlayUpdateId!==null&&(window.cancelAnimationFrame(this.overlayUpdateId),this.overlayUpdateId=null),this.scrollCaretIntoViewId!==null&&(window.cancelAnimationFrame(this.scrollCaretIntoViewId),this.scrollCaretIntoViewId=null)}setReadOnly(t){this.readOnly=t,this.updateContentRootAttributes()}setSpellCheckEnabled(t){this.spellCheckEnabled=t,this.updateContentRootAttributes()}getValue(){return this.state.source}getSelection(){return this.state.selection}getFocusRect(){return this.lastFocusRect}getContainer(){return this.container}getContentRoot(){return this.contentRoot}getOverlayRoot(){return this.extensionsRoot}syncPlaceholder(){this.updatePlaceholder()}insertText(t){this.readOnly||t&&this.applyEdit({type:"insert",text:t})}replaceText(t,n){var o;if(this.readOnly||!t)return;const r=this.state.source.indexOf(t);if(r===-1)return;const i=this.state.source.slice(0,r)+n+this.state.source.slice(r+t.length);this.recordHistory("replace"),this.state=this.runtime.createState(i,this.state.selection),this.render(),(o=this.onChange)==null||o.call(this,this.state.source,this.state.selection),this.scheduleOverlayUpdate(),this.scheduleScrollCaretIntoView()}setSelection(t){this.state=this.runtime.updateSelection(this.state,t,{kind:"programmatic"}),this.isComposing||this.applySelection(this.state.selection)}setValue({value:t,selection:n}){const r=n??this.state.selection;t===this.state.source&&n===void 0||(this.state=this.runtime.createState(t,r),this.render())}focus(t){t&&!this.hasFocus()&&this.setSelection(t),(this.contentRoot??this.container).focus()}blur(){(this.contentRoot??this.container).blur()}hasFocus(){const t=document.activeElement;return t?this.contentRoot?t===this.contentRoot||this.contentRoot.contains(t):t===this.container||this.container.contains(t):!1}selectAll(){const t=this.state.map.cursorLength;this.setSelection({start:0,end:t,affinity:"forward"})}undo(){var n;const t=this.history.undoStack.pop();t&&(this.history.redoStack.push({source:this.state.source,selection:this.state.selection}),this.history.lastKind=null,this.state=this.runtime.createState(t.source,t.selection),this.render(),(n=this.onChange)==null||n.call(this,this.state.source,this.state.selection))}redo(){var n;const t=this.history.redoStack.pop();t&&(this.history.undoStack.push({source:this.state.source,selection:this.state.selection}),this.history.lastKind=null,this.state=this.runtime.createState(t.source,t.selection),this.render(),(n=this.onChange)==null||n.call(this,this.state.source,this.state.selection))}canUndo(){return this.history.undoStack.length>0}canRedo(){return this.history.redoStack.length>0}executeCommand(t){var i;const n=t.type==="wrap-link"&&t.openPopover,r=this.runtime.applyEdit(t,this.state);return r===this.state?!1:(this.recordHistory(t.type),this.state=r,this.render(),(i=this.onChange)==null||i.call(this,this.state.source,this.state.selection),this.scheduleScrollCaretIntoView(),n&&queueMicrotask(()=>{this.openLinkPopoverForSelection(!0)}),!0)}attachListeners(){this.container.addEventListener("beforeinput",this.handleBeforeInputBound),this.container.addEventListener("input",this.handleInputBound),this.container.addEventListener("compositionstart",this.handleCompositionStartBound),this.container.addEventListener("compositionend",this.handleCompositionEndBound),document.addEventListener("selectionchange",this.handleSelectionChangeBound),this.container.addEventListener("scroll",this.handleScrollBound),window.addEventListener("resize",this.handleResizeBound),this.container.addEventListener("click",this.handleClickBound),this.container.addEventListener("keydown",this.handleKeyDownBound),this.container.addEventListener("paste",this.handlePasteBound),this.container.addEventListener("copy",this.handleCopyBound),this.container.addEventListener("cut",this.handleCutBound),this.container.addEventListener("pointerdown",this.handlePointerDownBound),this.container.addEventListener("pointermove",this.handlePointerMoveBound),this.container.addEventListener("pointerup",this.handlePointerUpBound)}attachDragListeners(){this.contentRoot&&(this.contentRoot.addEventListener("dragstart",this.handleDragStartBound),this.contentRoot.addEventListener("dragover",this.handleDragOverBound),this.contentRoot.addEventListener("drop",this.handleDropBound),this.contentRoot.addEventListener("dragend",this.handleDragEndBound))}detachDragListeners(){this.contentRoot&&(this.contentRoot.removeEventListener("dragstart",this.handleDragStartBound),this.contentRoot.removeEventListener("dragover",this.handleDragOverBound),this.contentRoot.removeEventListener("drop",this.handleDropBound),this.contentRoot.removeEventListener("dragend",this.handleDragEndBound))}detachListeners(){this.container.removeEventListener("beforeinput",this.handleBeforeInputBound),this.container.removeEventListener("input",this.handleInputBound),this.container.removeEventListener("compositionstart",this.handleCompositionStartBound),this.container.removeEventListener("compositionend",this.handleCompositionEndBound),document.removeEventListener("selectionchange",this.handleSelectionChangeBound),this.container.removeEventListener("scroll",this.handleScrollBound),window.removeEventListener("resize",this.handleResizeBound),this.container.removeEventListener("click",this.handleClickBound),this.container.removeEventListener("keydown",this.handleKeyDownBound),this.container.removeEventListener("paste",this.handlePasteBound),this.container.removeEventListener("copy",this.handleCopyBound),this.container.removeEventListener("cut",this.handleCutBound),this.container.removeEventListener("pointerdown",this.handlePointerDownBound),this.container.removeEventListener("pointermove",this.handlePointerMoveBound),this.container.removeEventListener("pointerup",this.handlePointerUpBound),this.detachDragListeners()}installCaretRangeFromPointShim(){const t=document;if(typeof t.caretRangeFromPoint!="function"||this.patchedCaretRangeFromPoint)return;this.originalCaretRangeFromPoint=t.caretRangeFromPoint.bind(document);const n=(r,i)=>{var u;const o=this.originalCaretRangeFromPoint,s=o?o(r,i):null,a=(s==null?void 0:s.startContainer)??null;if(a instanceof HTMLElement?a.closest("[data-line-index]"):(u=a==null?void 0:a.parentElement)==null?void 0:u.closest("[data-line-index]"))return s;const c=this.container.getBoundingClientRect();if(!(r>=c.left&&r<=c.right&&i>=c.top&&i<=c.bottom)||!this.domMap)return s;const m=document;let f=null,g=0;if(typeof m.caretPositionFromPoint=="function"){const E=m.caretPositionFromPoint(r,i);f=(E==null?void 0:E.offsetNode)??null,g=(E==null?void 0:E.offset)??0}else if(o){const E=o(r,i);f=(E==null?void 0:E.startContainer)??null,g=(E==null?void 0:E.startOffset)??0}let p=null;if(f instanceof Text?p={node:f,offset:g}:f instanceof Element&&(p=un(f,g)),!p)return s;const k=this.domMap.cursorAtDom(p.node,p.offset);if(!k)return s;const b=this.domMap.domAtCursor(k.cursorOffset,k.affinity);if(!b)return s;const w=document.createRange();return w.setStart(b.node,b.offset),w.setEnd(b.node,b.offset),w};this.patchedCaretRangeFromPoint=n,t.caretRangeFromPoint=n}uninstallCaretRangeFromPointShim(){if(!this.originalCaretRangeFromPoint||!this.patchedCaretRangeFromPoint)return;const t=document;t.caretRangeFromPoint===this.patchedCaretRangeFromPoint&&(t.caretRangeFromPoint=this.originalCaretRangeFromPoint),this.originalCaretRangeFromPoint=null,this.patchedCaretRangeFromPoint=null}render(){if(!this.contentRoot){window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.contentRoot=document.createElement("div"),this.contentRoot.className="cake-content",this.updateContentRootAttributes();const i=this.ensureOverlayRoot(),o=this.ensureExtensionsRoot();this.container.replaceChildren(this.contentRoot,i,o),this.attachDragListeners()}const{content:t,map:n}=kr(this.state.doc,this.extensions,this.contentRoot);this.contentRoot.replaceChildren(...t),this.domMap=n,this.updateExtensionsOverlayPosition(),this.isComposing||this.applySelection(this.state.selection),this.updatePlaceholder(),this.scheduleOverlayUpdate()}isEmptyParagraphDoc(){const t=this.state.doc.blocks;if(t.length!==1)return!1;const n=t[0];if(!n||n.type!=="paragraph")return!1;const r=i=>i.type==="text"?i.text.length>0:i.type==="inline-wrapper"?i.children.some(r):i.type==="inline-atom";return!n.content.some(r)}updatePlaceholder(){const t=this.container.dataset.placeholder,n=!!t&&this.isEmptyParagraphDoc();if(this.placeholderRoot||(this.placeholderRoot=document.createElement("div"),this.placeholderRoot.className="cake-placeholder"),!n){this.placeholderRoot.isConnected&&this.placeholderRoot.remove(),this.placeholderRoot.textContent="";return}this.placeholderRoot.textContent=t??"",this.syncPlaceholderPadding(),this.placeholderRoot.isConnected||this.container.prepend(this.placeholderRoot)}syncPlaceholderPadding(){if(!this.placeholderRoot)return;const t=window.getComputedStyle(this.container);this.placeholderRoot.style.paddingTop=t.paddingTop,this.placeholderRoot.style.paddingRight=t.paddingRight,this.placeholderRoot.style.paddingBottom=t.paddingBottom,this.placeholderRoot.style.paddingLeft=t.paddingLeft}updateContentRootAttributes(){this.contentRoot&&(this.contentRoot.contentEditable=this.readOnly?"false":"true",this.contentRoot.spellcheck=this.spellCheckEnabled)}applySelection(t){this.contentRoot&&this.domMap&&(this.isApplyingSelection=!0,wr(t,this.domMap),this.lastAppliedSelection=Qt(this.domMap)??t,queueMicrotask(()=>{this.isApplyingSelection=!1}),this.scheduleOverlayUpdate())}handleSelectionChange(){var l;if(this.isComposing||this.ignoreTouchNativeSelectionUntil!==null&&performance.now()<this.ignoreTouchNativeSelectionUntil||this.suppressSelectionChange||this.isApplyingSelection)return;const t=window.getSelection();if(!t||t.rangeCount===0)return;const n=t.anchorNode,r=t.focusNode;if(!n||!r||!this.container.contains(n)&&!this.container.contains(r)||!this.domMap)return;const i=Qt(this.domMap);if(!i||this.lastAppliedSelection&&Oi(i,this.lastAppliedSelection)||this.lastAppliedSelection&&i.start===this.lastAppliedSelection.start&&i.end===this.lastAppliedSelection.end&&i.affinity!==this.lastAppliedSelection.affinity)return;const o=this.state.selection;if(o.start===i.start&&o.end===i.end&&o.affinity===i.affinity){this.lastAppliedSelection=i;return}const a=this.adjustSelectionForAtomicBlocks(i,o);this.selectedAtomicLineIndex=null,this.state=this.runtime.updateSelection(this.state,a,{kind:"dom"}),(l=this.onSelectionChange)==null||l.call(this,this.state.selection),this.scheduleOverlayUpdate(),this.scheduleScrollCaretIntoView(),(a.start!==i.start||a.end!==i.end)&&this.applySelection(a)}syncSelectionFromDom(){var n;if(this.isComposing||!this.domMap)return;const t=Qt(this.domMap);t&&(this.selectedAtomicLineIndex=null,this.state=this.runtime.updateSelection(this.state,t,{kind:"dom"}),(n=this.onSelectionChange)==null||n.call(this,this.state.selection),this.lastAppliedSelection=this.state.selection,this.scheduleOverlayUpdate(),this.scheduleScrollCaretIntoView())}adjustSelectionForAtomicBlocks(t,n){if(t.start!==t.end)return t;const r=it(this.state.doc),i=at(r),{lineIndex:o}=ut(r,t.start),s=r[o];if(!s||!s.isAtomic)return t;const a=n.start===n.end&&t.start<n.start?"backward":"forward",l=i[o]??0,c=l+s.cursorLength+(s.hasNewline?1:0);if(a==="forward"){const d=o===r.length-1,m=c;return{...t,start:m,end:m}}else{if(o===0)return{...t,start:0,end:0};const d=l-1;return{...t,start:d,end:d}}}getAtomicBlockSelectionFromClick(t){const n=t.target;if(!(n instanceof HTMLElement))return null;const r=n.closest("[data-block-atom]");if(!r)return null;const i=r.getAttribute("data-line-index");if(i===null)return null;const o=parseInt(i,10);if(Number.isNaN(o))return null;const s=it(this.state.doc),a=s[o];if(!a||!a.isAtomic)return null;const c=at(s)[o]??0,d=c+a.cursorLength+(a.hasNewline?1:0);return{lineIndex:o,selection:{start:c,end:d,affinity:"forward"}}}handleClick(t){var i,o,s,a;if(this.isComposing||this.ignoreTouchNativeSelectionUntil!==null&&performance.now()<this.ignoreTouchNativeSelectionUntil||!this.contentRoot||!this.domMap||!this.isEventTargetInContentRoot(t.target))return;if(t.detail===1&&!this.hasMovedSincePointerDown){if(t.shiftKey)return;const l=this.getAtomicBlockSelectionFromClick(t);if(l){const d=l.selection;this.pendingClickHit=null,t.preventDefault(),this.state=this.runtime.updateSelection(this.state,d,{kind:"dom"}),this.applySelection(this.state.selection),(i=this.onSelectionChange)==null||i.call(this,this.state.selection),this.scheduleOverlayUpdate(),this.selectedAtomicLineIndex=l.lineIndex,this.suppressSelectionChange=!1;return}const c=this.pendingClickHit??this.hitTestFromClientPoint(t.clientX,t.clientY);if(this.pendingClickHit=null,c){const d={start:c.cursorOffset,end:c.cursorOffset,affinity:c.affinity};this.state=this.runtime.updateSelection(this.state,d,{kind:"dom"}),this.applySelection(this.state.selection),(o=this.onSelectionChange)==null||o.call(this,this.state.selection),this.scheduleOverlayUpdate()}this.suppressSelectionChange=!1;return}this.pendingClickHit=null;const n=this.hitTestFromClientPoint(t.clientX,t.clientY);if(!n)return;const r=it(this.state.doc);if(t.detail===2){const l=ae(r),c=zt(r,n.cursorOffset),d=bi(l,c),m=we(r,d.start),f=we(r,d.end);if(m===null||f===null){this.suppressSelectionChange=!1;return}const g={start:m,end:f,affinity:"forward"};t.preventDefault(),this.state=this.runtime.updateSelection(this.state,g,{kind:"dom"}),this.applySelection(this.state.selection),(s=this.onSelectionChange)==null||s.call(this,this.state.selection),this.suppressSelectionChange=!1;return}if(t.detail>=3){const l=at(r),{lineIndex:c}=ut(r,n.cursorOffset),d=r[c];if(!d){this.suppressSelectionChange=!1;return}const m=l[c]??0,f=m+d.cursorLength+(d.hasNewline?1:0),g={start:m,end:f,affinity:"forward"};t.preventDefault(),this.state=this.runtime.updateSelection(this.state,g,{kind:"dom"}),this.applySelection(this.state.selection),(a=this.onSelectionChange)==null||a.call(this,this.state.selection),this.suppressSelectionChange=!1}}handleKeyDown(t){if(this.isComposing||!this.isEventTargetInContentRoot(t.target))return;const n=xi(),r=n?t.metaKey:t.ctrlKey;if(r&&t.key.toLowerCase()==="z"){t.preventDefault(),t.shiftKey?this.redo():this.undo();return}if(r&&t.key==="y"&&!n){t.preventDefault(),this.redo();return}if(r&&t.key==="Enter"){t.preventDefault(),this.keydownHandledBeforeInput=!0,this.applyEdit({type:"insert-line-break"}),queueMicrotask(()=>{this.keydownHandledBeforeInput=!1});return}const i=n&&t.metaKey,o=n?t.altKey:t.ctrlKey,s=t.shiftKey;if(i&&t.key==="Backspace"){t.preventDefault(),this.keydownHandledBeforeInput=!0,this.deleteToVisualRowStart(),queueMicrotask(()=>{this.keydownHandledBeforeInput=!1});return}if(t.key==="ArrowLeft"){if(this.verticalNavGoalX=null,i){const c=s?this.extendSelectionToVisualRowStart():this.moveSelectionToVisualRowStart();c&&(t.preventDefault(),this.applySelectionUpdate(c,"keyboard"));return}if(o){t.preventDefault();const c=s?this.extendSelectionByWord("backward"):this.moveSelectionByWord("backward");this.applySelectionUpdate(c,"keyboard");return}if(s){t.preventDefault();const c=this.state.map.cursorLength,d=ze(this.state.selection,c),{anchor:m,focus:f}=Wt(d),g=this.moveOffsetByChar(f,"backward")??f;this.applySelectionUpdate(Dt(m,g,"backward"),"keyboard");return}const l=this.moveSelectionByChar("backward");if(l){t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}return}if(t.key==="ArrowRight"){if(this.verticalNavGoalX=null,i){const c=s?this.extendSelectionToVisualRowEnd():this.moveSelectionToVisualRowEnd();c&&(t.preventDefault(),this.applySelectionUpdate(c,"keyboard"));return}if(o){t.preventDefault();const c=s?this.extendSelectionByWord("forward"):this.moveSelectionByWord("forward");this.applySelectionUpdate(c,"keyboard");return}if(s){t.preventDefault();const c=this.state.map.cursorLength,d=ze(this.state.selection,c),{anchor:m,focus:f}=Wt(d),g=this.moveOffsetByChar(f,"forward")??f;this.applySelectionUpdate(Dt(m,g,"forward"),"keyboard");return}const l=this.moveSelectionByChar("forward");if(l){t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}return}if(t.key==="ArrowUp"){if(i){const l=s?this.extendSelectionToDocumentStart():{start:0,end:0,affinity:"backward"};t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}if(s){const l=this.extendFullLineSelectionByLine("up");if(l){t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}}if(!s){const l=this.moveSelectionVertically("up");if(l){t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}}return}if(t.key==="ArrowDown"){if(i){const l=this.state.map.cursorLength,c=s?this.extendSelectionToDocumentEnd():{start:l,end:l,affinity:"forward"};t.preventDefault(),this.applySelectionUpdate(c,"keyboard");return}if(s){const l=this.extendFullLineSelectionByLine("down");if(l){t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}}if(!s){const l=this.moveSelectionVertically("down");if(l){t.preventDefault(),this.applySelectionUpdate(l,"keyboard");return}}return}if(t.key==="Tab"){this.verticalNavGoalX=null,t.preventDefault(),this.keydownHandledBeforeInput=!0,t.shiftKey?this.handleOutdent():this.handleIndent(),queueMicrotask(()=>{this.keydownHandledBeforeInput=!1});return}const a=this.resolveExtensionKeybinding(t);if(a){this.verticalNavGoalX=null,t.preventDefault(),this.keydownHandledBeforeInput=!0,this.executeCommand(a),queueMicrotask(()=>{this.keydownHandledBeforeInput=!1});return}}resolveExtensionKeybinding(t){for(const n of this.extensions){const r=n.keybindings;if(r)for(const i of r){if(i.key!==t.key||i.meta!==void 0&&i.meta!==t.metaKey||i.ctrl!==void 0&&i.ctrl!==t.ctrlKey||i.alt!==void 0&&i.alt!==t.altKey||i.shift!==void 0&&i.shift!==t.shiftKey)continue;const o=typeof i.command=="function"?i.command(this.state):i.command;if(o)return o}}return null}handleCopy(t){if(!this.isEventTargetInContentRoot(t.target))return;const n=t.clipboardData;if(!n)return;const r=this.runtime.serializeSelection(this.state,this.state.selection);r&&(t.preventDefault(),n.setData("text/plain",r))}handleCut(t){this.readOnly||this.isEventTargetInContentRoot(t.target)&&(this.handleCopy(t),this.state.selection.start!==this.state.selection.end&&this.applyEdit({type:"delete-backward"}))}handlePaste(t){if(this.readOnly||!this.isEventTargetInContentRoot(t.target))return;const n=t.clipboardData,r=(n==null?void 0:n.getData("text/html"))??"";if(r){const o=Li(r);if(o){t.preventDefault(),this.applyEdit({type:"insert",text:o});return}}t.preventDefault();const i=(n==null?void 0:n.getData("text/plain"))??"";if(i){for(const o of this.extensions){const s=o.onPasteText;if(!s)continue;const a=s(i,this.state);if(a){a.type==="insert"||a.type==="insert-line-break"||a.type==="delete-backward"||a.type==="delete-forward"?this.applyEdit(a):this.executeCommand(a);return}}this.applyEdit({type:"insert",text:i})}}handleBeforeInput(t){if(this.readOnly||this.isComposing||t.isComposing){(t.inputType==="insertReplacementText"||t.inputType==="insertText")&&console.log("[SPELLCHECK] beforeinput ignored (readonly/composing)",{inputType:t.inputType,data:t.data,cancelable:t.cancelable,isComposing:this.isComposing,eventIsComposing:t.isComposing,readOnly:this.readOnly});return}if(!this.isEventTargetInContentRoot(t.target)){(t.inputType==="insertReplacementText"||t.inputType==="insertText")&&console.log("[SPELLCHECK] beforeinput ignored (target outside editor)",{inputType:t.inputType,data:t.data,cancelable:t.cancelable,target:t.target});return}if(this.keydownHandledBeforeInput){this.keydownHandledBeforeInput=!1,(t.inputType==="insertReplacementText"||t.inputType==="insertText")&&console.log("[SPELLCHECK] beforeinput skipped (keydownHandledBeforeInput)",{inputType:t.inputType,data:t.data,cancelable:t.cancelable}),t.preventDefault();return}const n=this.resolveBeforeInputIntent(t);if(!n){(t.inputType==="insertReplacementText"||t.inputType==="insertText")&&console.log("[SPELLCHECK] beforeinput: no intent",{inputType:t.inputType,data:t.data,cancelable:t.cancelable});return}if(t.inputType==="insertReplacementText"||t.inputType==="insertText"&&n.type==="replace-text"){const r=this.state.selection,i=r.start===r.end?r.start:Math.max(r.start,r.end),o=this.state.source.slice(Math.max(0,i-24),Math.min(this.state.source.length,i+24));console.log("[SPELLCHECK] beforeinput: resolved intent",{inputType:t.inputType,data:t.data,cancelable:t.cancelable,intent:n,currentSelection:this.state.selection,sourcePreviewAroundFocus:o})}t.preventDefault(),(t.inputType==="insertReplacementText"||t.inputType==="insertText"&&n.type==="replace-text")&&console.log("[SPELLCHECK] beforeinput: after preventDefault",{inputType:t.inputType,defaultPrevented:t.defaultPrevented}),this.markBeforeInputHandled(),this.suppressSelectionChangeForTick(),this.applyInputIntent(n)}applyInputIntent(t){if(t.type==="noop"){this.scheduleOverlayUpdate();return}if(t.type==="insert-text"){this.applyEdit({type:"insert",text:t.text});return}if(t.type==="insert-line-break"){this.applyEdit({type:"insert-line-break"});return}if(t.type==="delete-backward"){this.applyEdit({type:"delete-backward"});return}if(t.type==="delete-forward"){this.applyEdit({type:"delete-forward"});return}if(t.type==="replace-text"){this.state=this.runtime.updateSelection(this.state,t.selection,{kind:"dom"}),this.applyEdit({type:"insert",text:t.text});return}if(t.type==="undo"){this.undo();return}if(t.type==="redo"){this.redo();return}}handleInput(t){if(!(t instanceof InputEvent))return;if(!this.isEventTargetInContentRoot(t.target)){t.inputType==="insertReplacementText"&&console.log("[SPELLCHECK] input ignored (target outside editor)",{inputType:t.inputType,data:t.data,target:t.target});return}if(this.beforeInputHandled){t.inputType==="insertReplacementText"&&console.log("[SPELLCHECK] input ignored (handled via beforeinput)",{inputType:t.inputType,data:t.data});return}if(this.compositionCommit&&t.inputType==="insertText"){this.clearCompositionCommit();return}if(this.isComposing||t.isComposing||Mi(t.inputType)||t.inputType==="historyUndo"||t.inputType==="historyRedo"||!this.domMap)return;const n=Qt(this.domMap);n&&this.reconcileDomChanges(n)}handleCompositionStart(t){this.isEventTargetInContentRoot(t.target)&&(this.isComposing=!0,this.clearCompositionCommit())}handleCompositionEnd(t){if(!this.isEventTargetInContentRoot(t.target))return;this.isComposing=!1;const n=this.domMap?Qt(this.domMap)??this.state.selection:this.state.selection;this.reconcileDomChanges(n)||this.setSelection(n),this.markCompositionCommit(),this.scheduleOverlayUpdate()}resolveBeforeInputIntent(t){var r,i;const n=t.inputType;if(n==="insertText"){const o=t.data??"";if(!o)return null;const s=this.selectionFromTargetRangesWithStatus(t);if(s.status==="valid"){const a=s.selection;if(a.start!==a.end)return{type:"replace-text",text:o,selection:a}}return{type:"insert-text",text:o}}if(n==="insertLineBreak"||n==="insertParagraph")return{type:"insert-line-break"};if(n==="insertFromPaste"){const o=t.data??((r=t.dataTransfer)==null?void 0:r.getData("text/plain"))??((i=t.dataTransfer)==null?void 0:i.getData("text"))??"";return o?{type:"insert-text",text:o}:null}if(n==="deleteContentBackward"||n==="deleteByCut"||n==="deleteByLineBoundary")return{type:"delete-backward"};if(n==="deleteContentForward")return{type:"delete-forward"};if(n==="insertReplacementText"){if(t.data===null)return null;const o=this.selectionFromTargetRangesWithStatus(t);if(o.status==="invalid")return{type:"noop"};const s=o.status==="valid"?o.selection:this.state.selection;return{type:"replace-text",text:t.data??"",selection:s}}return n==="historyUndo"?{type:"undo"}:n==="historyRedo"?{type:"redo"}:null}selectionFromTargetRangesWithStatus(t){const n=t.inputType==="insertReplacementText";if(!t.getTargetRanges)return n&&console.log("[SPELLCHECK][targetRanges] missing getTargetRanges()",{inputType:t.inputType,data:t.data,cancelable:t.cancelable}),{status:"none"};const r=t.getTargetRanges();if(!r||r.length===0)return n&&console.log("[SPELLCHECK][targetRanges] no ranges",{inputType:t.inputType,data:t.data,cancelable:t.cancelable}),{status:"none"};const i=r[0];if((n||t.inputType==="insertText")&&console.log("[SPELLCHECK][targetRanges] raw range",{inputType:t.inputType,data:t.data,cancelable:t.cancelable,startContainer:i.startContainer instanceof Element?i.startContainer.tagName:i.startContainer.nodeName,startOffset:i.startOffset,endContainer:i.endContainer instanceof Element?i.endContainer.tagName:i.endContainer.nodeName,endOffset:i.endOffset,startContained:this.container.contains(i.startContainer),endContained:this.container.contains(i.endContainer)}),!this.container.contains(i.startContainer)||!this.container.contains(i.endContainer))return{status:"invalid"};const o=this.cursorFromDom(i.startContainer,i.startOffset),s=this.cursorFromDom(i.endContainer,i.endOffset);if(!o||!s)return(n||t.inputType==="insertText")&&console.log("[SPELLCHECK][targetRanges] cursorFromDom failed",{inputType:t.inputType,data:t.data,cancelable:t.cancelable,start:o,end:s}),{status:"invalid"};const a=o.cursorOffset===s.cursorOffset?s.affinity:"forward";return{status:"valid",selection:{start:o.cursorOffset,end:s.cursorOffset,affinity:a}}}cursorFromDom(t,n){var i,o;if(t instanceof Text)return((i=this.domMap)==null?void 0:i.cursorAtDom(t,n))??null;if(!(t instanceof Element))return null;const r=un(t,n);return r?((o=this.domMap)==null?void 0:o.cursorAtDom(r.node,r.offset))??null:null}applyEdit(t){var o;if(t.type==="delete-backward"&&this.handleBackspaceAfterAtomicBlock()||(t.type==="delete-backward"||t.type==="delete-forward")&&this.handleDeleteAtomicBlockSelection())return;const n=this.state.selection.start!==this.state.selection.end,r=t.type==="insert"&&n?"replace":t.type;this.recordHistory(r);const i=this.runtime.applyEdit(t,this.state);this.selectedAtomicLineIndex=null,this.state=i,this.render(),(o=this.onChange)==null||o.call(this,this.state.source,this.state.selection),this.state.selection.start===this.state.selection.end?this.flushOverlayUpdate():this.scheduleOverlayUpdate(),this.scheduleScrollCaretIntoView()}handleDeleteAtomicBlockSelection(){var d;if(this.selectedAtomicLineIndex===null)return!1;const t=this.selectedAtomicLineIndex,n=it(this.state.doc),r=at(n),i=n[t];if(!i||!i.isAtomic)return this.selectedAtomicLineIndex=null,!1;const o=r[t]??0,s=this.state.source;let a=0;for(let m=0;m<t;m+=1){const f=s.indexOf(`
79
+ `,a);if(f===-1)return!1;a=f+1}let l=s.indexOf(`
80
+ `,a);l===-1?(a>0&&(a-=1),l=s.length):l+=1;const c=s.slice(0,a)+s.slice(l);return this.recordHistory("delete-backward"),this.state=this.runtime.createState(c,{start:o,end:o,affinity:"forward"}),this.render(),(d=this.onChange)==null||d.call(this,this.state.source,this.state.selection),this.flushOverlayUpdate(),this.scheduleScrollCaretIntoView(),this.selectedAtomicLineIndex=null,!0}handleBackspaceAfterAtomicBlock(){var w;const t=this.state.selection;if(t.start!==t.end)return!1;const n=it(this.state.doc),i=at(n).findIndex(u=>u===t.start);if(i===-1)return!1;const o=i>0?n[i-1]:null,s=n[i]??null,a=i+1<n.length?n[i+1]:null;let l=null,c=null;if(o!=null&&o.isAtomic)l=i-1,c=i;else if(s!=null&&s.isAtomic&&a&&!a.isAtomic)l=i,c=i+1;else return!1;const d=this.state.source.split(`
81
+ `);if(l<0||c<0||l>=d.length||c>=d.length)return!1;const m=d[l],f=d[c];if(m===void 0||f===void 0)return!1;d[l]=f,d[c]=m;const g=d.join(`
82
+ `),p=this.runtime.createState(g),b=at(it(p.doc))[l]??0;return this.recordHistory("delete-backward"),this.state={...p,selection:{start:b,end:b,affinity:"forward"}},this.render(),(w=this.onChange)==null||w.call(this,this.state.source,this.state.selection),this.flushOverlayUpdate(),this.scheduleScrollCaretIntoView(),!0}recordHistory(t){const n=Date.now(),r=n-this.history.lastEditAt;t===this.history.lastKind&&r<vi||(this.history.undoStack.push({source:this.state.source,selection:this.state.selection}),this.history.undoStack.length>Ti&&this.history.undoStack.shift(),this.history.redoStack=[]),this.history.lastEditAt=n,this.history.lastKind=t}applySelectionUpdate(t,n="programmatic"){var r;n!=="keyboard"&&(this.verticalNavGoalX=null),this.selectedAtomicLineIndex=null,this.state=this.runtime.updateSelection(this.state,t,{kind:n}),this.isComposing||this.applySelection(this.state.selection),(r=this.onSelectionChange)==null||r.call(this,this.state.selection),this.state.selection.start===this.state.selection.end&&this.flushOverlayUpdate(),this.scheduleScrollCaretIntoView()}getLayoutForNavigation(){if(!this.contentRoot)return null;const t=it(this.state.doc),n=Hn({lines:t,root:this.contentRoot,container:this.container});return n?{lines:t,layout:n}:null}moveSelectionByChar(t){const n=this.state.selection;if(n.start!==n.end){const o=t==="forward"?Math.max(n.start,n.end):Math.min(n.start,n.end);return{start:o,end:o,affinity:t}}const r=n.start,i=this.moveOffsetByChar(r,t);return i===null?null:{start:i,end:i,affinity:t}}moveOffsetByChar(t,n){const r=this.state.map.cursorLength,i=it(this.state.doc),o=at(i);let s;if(n==="forward"){if(t>=r)return null;s=t+1}else{if(t<=0)return null;s=t-1}const{lineIndex:a}=ut(i,s),l=i[a];if(l&&l.isAtomic){const c=o[a]??0,d=c+l.cursorLength+(l.hasNewline?1:0);s=n==="forward"?d:c>0?c-1:0}return Math.max(0,Math.min(s,r))}moveSelectionVertically(t){const n=this.getLayoutForNavigation();if(!n)return null;const{lines:r,layout:i}=n;this.lastFocusRect||this.flushOverlayUpdate(),this.verticalNavGoalX===null&&this.lastFocusRect&&(this.verticalNavGoalX=this.lastFocusRect.left);const{focus:o}=Wt(this.state.selection),s=ut(r,o),a=i.lines[s.lineIndex];let l;if(a!=null&&a.rows.length&&this.lastFocusRect){const g=this.lastFocusRect.top;let p=0,k=Number.POSITIVE_INFINITY;for(let b=0;b<a.rows.length;b+=1){const w=a.rows[b];if(!w)continue;const u=Math.abs(w.rect.top-g);u<k&&(k=u,p=b)}l=p}const c=this.container.getBoundingClientRect(),d=this.container.scrollLeft,m=this.container.scrollTop,f=mi({lines:r,layout:i,selection:this.state.selection,direction:t,goalX:this.verticalNavGoalX,focusRowIndex:l,hitTestCursorAt:(g,p)=>{const k=this.hitTestFromClientPoint(c.left+g-d,c.top+p-m);if(!k||!this.contentRoot)return null;const b=ut(r,k.cursorOffset),w=r[b.lineIndex],u=this.contentRoot.querySelector(`[data-line-index="${b.lineIndex}"]`);if(!w||!(u instanceof HTMLElement))return{cursorOffset:k.cursorOffset,affinity:k.affinity};const E=_e({lineElement:u,lineInfo:w,offsetInLine:b.offsetInLine,affinity:k.affinity}),C=(E==null?void 0:E.rect.top)!==void 0?E.rect.top-c.top+m:void 0;return{cursorOffset:k.cursorOffset,affinity:k.affinity,caretTop:C}}});return f?(this.verticalNavGoalX=f.goalX,f.selection):null}moveSelectionToVisualRowStart(){const t=this.getLayoutForNavigation();if(!t)return{start:0,end:0,affinity:"backward"};const{lines:n,layout:r}=t,i=this.state.selection,o=i.start===i.end?i.start:Math.min(i.start,i.end),{rowStart:s}=Bt({lines:n,layout:r,offset:o,affinity:"backward"});let a=s;return o===s&&o>0&&(a=Bt({lines:n,layout:r,offset:o-1,affinity:"backward"}).rowStart),{start:a,end:a,affinity:"forward"}}moveSelectionToVisualRowEnd(){const t=this.getLayoutForNavigation();if(!t){const l=this.state.map.cursorLength;return{start:l,end:l,affinity:"forward"}}const{lines:n,layout:r}=t,i=this.state.selection,o=i.start===i.end?i.start:Math.max(i.start,i.end),{rowEnd:s}=Bt({lines:n,layout:r,offset:o,affinity:"forward"});let a=s;return o===s&&o<this.state.map.cursorLength&&(a=Bt({lines:n,layout:r,offset:o+1,affinity:"forward"}).rowEnd),{start:a,end:a,affinity:"backward"}}extendSelectionToVisualRowStart(){const t=this.state.selection,{anchor:n,focus:r}=Wt(t),i=dn(t),o=this.getLayoutForNavigation();if(!o)return Dt(n,0,"backward");const{lines:s,layout:a}=o,{rowStart:l}=Bt({lines:s,layout:a,offset:r,affinity:i});let c=l;return r===l&&r>0&&(c=Bt({lines:s,layout:a,offset:r-1,affinity:"backward"}).rowStart),Dt(n,c,"backward")}extendSelectionToVisualRowEnd(){const t=this.state.selection,{anchor:n,focus:r}=Wt(t),i=dn(t),o=this.getLayoutForNavigation();if(!o)return Dt(n,this.state.map.cursorLength,"forward");const{lines:s,layout:a}=o,{rowEnd:l}=Bt({lines:s,layout:a,offset:r,affinity:i});let c=l;return r===l&&r<this.state.map.cursorLength&&(c=Bt({lines:s,layout:a,offset:r+1,affinity:"forward"}).rowEnd),Dt(n,c,"forward")}extendSelectionToDocumentStart(){const{anchor:t}=Wt(this.state.selection);return Dt(t,0,"backward")}extendSelectionToDocumentEnd(){const{anchor:t}=Wt(this.state.selection);return Dt(t,this.state.map.cursorLength,"forward")}extendFullLineSelectionByLine(t){const n=this.state.selection;if(n.start===n.end)return null;const r=it(this.state.doc),i=at(r),o=Math.min(n.start,n.end),s=Math.max(n.start,n.end),a=this.detectFullLineSelection(o,s,r,i);if(!a)return null;if(t==="up"){if(a.startLineIndex<=0)return null;const p=a.startLineIndex-1,k=a.endLineIndex,b=i[p]??0,w=r[k],u=i[k]??0,E=w?u+w.cursorLength+(w.hasNewline?1:0):s;return{start:b,end:E,affinity:"forward"}}if(a.endLineIndex>=r.length-1)return null;const l=a.startLineIndex,c=a.endLineIndex+1,d=i[l]??0,m=r[c],f=i[c]??0,g=m?f+m.cursorLength+(m.hasNewline?1:0):s;return{start:d,end:g,affinity:"forward"}}moveSelectionByWord(t){const n=this.state.map.cursorLength,r=ze(this.state.selection,n);if(r.start!==r.end){const o=t==="backward"?r.start:r.end;return{start:o,end:o,affinity:t}}const i=this.moveOffsetByWord(r.start,t);return{start:i,end:i,affinity:t}}extendSelectionByWord(t){const n=this.state.map.cursorLength,r=ze(this.state.selection,n),{anchor:i,focus:o}=Wt(r),s=this.moveOffsetByWord(o,t);return s===o?r:Dt(i,s,t)}moveOffsetByWord(t,n){const r=it(this.state.doc),i=ae(r);if(!i)return 0;const o=zt(r,t),s=n==="backward"?Ii(i,o):Ei(i,o);return we(r,s)??t}deleteToVisualRowStart(){const t=this.state.selection,n=it(this.state.doc),{lineIndex:r,offsetInLine:i}=ut(n,t.start);if(!n[r])return;const a=at(n)[r]??0,l=i===0,c=t.start===t.end;if(c&&l){this.applyEdit({type:"delete-backward"});return}const d=this.getLayoutForNavigation();if(!d){const k={start:a,end:t.end,affinity:"forward"};this.state={...this.state,selection:k},this.applyEdit({type:"delete-backward"});return}const{layout:m}=d,{rowStart:f}=Bt({lines:n,layout:m,offset:t.start,affinity:"backward"}),g=t.start===f;if(c&&g){this.applyEdit({type:"delete-backward"});return}const p={start:f,end:t.end,affinity:"forward"};this.state={...this.state,selection:p},this.applyEdit({type:"delete-backward"})}handleIndent(){var C,L;const t=this.state.selection,n=it(this.state.doc),r=" ",i=t.start===t.end,o=ut(n,t.start).lineIndex,s=ut(n,Math.max(t.start,t.end-1)).lineIndex,a=s>o,l=this.state.source.split(`
83
+ `),c=l[o]??"";if(/^(\s*)([-*+]|\d+\.)(\s+)/.test(c)){this.recordHistory("edit");const T=this.runtime.applyEdit({type:"indent"},this.state);this.state=T,this.render(),(C=this.onChange)==null||C.call(this,this.state.source,this.state.selection),this.scheduleOverlayUpdate();return}if(i){const A=at(n)[o]??0;if(t.start-A>0){this.applyEdit({type:"insert",text:r});return}}if(!a&&!i){this.applyEdit({type:"insert",text:r});return}!a&&i&&this.recordHistory("edit");let f=this.state.source,g=0;const p=[];let k=0;for(let T=0;T<l.length;T++)p.push(k),k+=l[T].length,T<l.length-1&&(k+=1);for(let T=o;T<=s;T++){const A=p[T]+g;f=f.slice(0,A)+r+f.slice(A),g+=r.length}const b=t.start+r.length,w=s-o+1,u=t.end+r.length*w,E={start:b,end:u,affinity:"forward"};this.state=this.runtime.createState(f,E),this.render(),(L=this.onChange)==null||L.call(this,this.state.source,this.state.selection),this.scheduleOverlayUpdate()}handleOutdent(){var E,C;const t=this.state.selection,n=it(this.state.doc),r=" ",i=ut(n,t.start).lineIndex,o=ut(n,Math.max(t.start,t.end-1)).lineIndex,s=this.state.source.split(`
84
+ `),a=s[i]??"";if(/^(\s*)([-*+]|\d+\.)(\s+)/.test(a)){this.recordHistory("edit");const L=this.runtime.applyEdit({type:"outdent"},this.state);L.source!==this.state.source&&(this.state=L,this.render(),(E=this.onChange)==null||E.call(this,this.state.source,this.state.selection),this.scheduleOverlayUpdate());return}let d=this.state.source,m=0;const f=[];let g=0;for(let L=0;L<s.length;L++)f.push(g),g+=s[L].length,L<s.length-1&&(g+=1);const p=[];for(let L=i;L<=o;L++){const T=f[L]-m,A=d.slice(T,d.indexOf(`
85
+ `,T)===-1?d.length:d.indexOf(`
86
+ `,T));let D=0;A.startsWith(r)?D=r.length:(A.startsWith(" ")||A.startsWith(" "))&&(D=1),D>0&&(d=d.slice(0,T)+d.slice(T+D),m+=D),p.push(D)}if(m===0)return;const k=p[0]??0,b=Math.max(0,t.start-k),w=Math.max(0,t.end-m),u={start:b,end:w,affinity:"forward"};this.state=this.runtime.createState(d,u),this.render(),(C=this.onChange)==null||C.call(this,this.state.source,this.state.selection),this.scheduleOverlayUpdate()}readDomText(){if(!this.contentRoot)return this.state.source;const t=Array.from(this.contentRoot.querySelectorAll('[data-block="paragraph"]'));return t.length===0?this.contentRoot.textContent??"":t.map(r=>r.textContent??"").join(`
87
+ `)}reconcileDomChanges(t){var C,L;const n=this.readDomText(),r=it(this.state.doc),i=ae(r);if(n===i)return!1;this.recordHistory("reconcile");let o=0;const s=Math.min(n.length,i.length);for(;o<s&&n[o]===i[o];)o++;let a=0;for(;a<s-o&&n[n.length-1-a]===i[i.length-1-a];)a++;const l=n.slice(o,n.length-a),c=we(r,o),d=we(r,i.length-a);if(c===null||d===null)return this.state=this.runtime.createState(n,t),this.render(),(C=this.onChange)==null||C.call(this,this.state.source,this.state.selection),!0;const m=this.state.map;let f,g;if(c===d){const T=this.resolveCollapsedReconcileAffinity(c)??t.affinity??"forward",A=m.cursorToSource(c,T);f=A,g=A}else{const T=m.cursorToSource(c,"forward"),A=m.cursorToSource(d,"backward");f=Math.min(T,A),g=Math.max(T,A)}const p=this.state.source,k=p.slice(0,f)+l+p.slice(g),b=this.runtime.createState(k),w=c+l.length,u=Math.min(w,b.map.cursorLength),E={start:u,end:u,affinity:t.affinity??"forward"};return this.state={...b,selection:E},this.render(),(L=this.onChange)==null||L.call(this,this.state.source,this.state.selection),!0}resolveCollapsedReconcileAffinity(t){if(!this.domMap)return null;const n=window.getSelection();if(!n||n.rangeCount===0)return null;const r=n.getRangeAt(0);if(!r.collapsed||!(r.startContainer instanceof Text))return null;const i=this.domMap.domAtCursor(t,"backward");if((i==null?void 0:i.node)===r.startContainer)return"backward";const o=this.domMap.domAtCursor(t,"forward");return(o==null?void 0:o.node)===r.startContainer?"forward":null}markBeforeInputHandled(){this.beforeInputHandled=!0,this.beforeInputResetId!==null&&window.cancelAnimationFrame(this.beforeInputResetId),this.beforeInputResetId=window.requestAnimationFrame(()=>{this.beforeInputHandled=!1,this.beforeInputResetId=null})}suppressSelectionChangeForTick(){this.suppressSelectionChange=!0,this.suppressSelectionChangeResetId!==null&&window.cancelAnimationFrame(this.suppressSelectionChangeResetId),this.suppressSelectionChangeResetId=window.requestAnimationFrame(()=>{this.suppressSelectionChange=!1,this.suppressSelectionChangeResetId=null})}markCompositionCommit(){this.compositionCommit=!0,this.compositionCommitTimeoutId!==null&&window.clearTimeout(this.compositionCommitTimeoutId),this.compositionCommitTimeoutId=window.setTimeout(()=>{this.clearCompositionCommit()},Ci)}clearCompositionCommit(){this.compositionCommit=!1,this.compositionCommitTimeoutId!==null&&(window.clearTimeout(this.compositionCommitTimeoutId),this.compositionCommitTimeoutId=null)}handleScroll(){this.scheduleOverlayUpdate(),this.updateExtensionsOverlayPosition()}handleResize(){this.scheduleOverlayUpdate()}openLinkPopoverForSelection(t){var l;if(!this.contentRoot||!this.domMap)return;const n=this.state.selection,r=n.start===n.end?n.start:Math.max(n.start,n.end),i=n.affinity??"forward",o=this.domMap.domAtCursor(r,i);if(!o)return;const s=((l=o.node.parentElement)==null?void 0:l.closest("a.cake-link"))??this.contentRoot.querySelector("a.cake-link");if(!s||!(s instanceof HTMLAnchorElement))return;const a=new CustomEvent("cake-link-popover-open",{bubbles:!0,detail:{link:s,isEditing:t}});this.contentRoot.dispatchEvent(a)}scheduleOverlayUpdate(){this.isComposing||this.overlayUpdateId===null&&(this.overlayUpdateId=window.requestAnimationFrame(()=>{this.overlayUpdateId=null,this.updateSelectionOverlay()}))}flushOverlayUpdate(){this.isComposing||(this.overlayUpdateId!==null&&(window.cancelAnimationFrame(this.overlayUpdateId),this.overlayUpdateId=null),this.updateSelectionOverlay())}ensureOverlayRoot(){if(this.overlayRoot)return this.overlayRoot;const t=document.createElement("div");t.className="cake-selection-overlay",t.setAttribute("aria-hidden","true"),t.contentEditable="false",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.userSelect="none",t.style.setProperty("-webkit-user-select","none"),t.style.zIndex="2";const n=document.createElement("div");return n.className="cake-caret",n.style.display="none",t.append(n),this.overlayRoot=t,this.caretElement=n,t}ensureExtensionsRoot(){if(this.extensionsRoot)return this.extensionsRoot;const t=document.createElement("div");return t.className="cake-extension-overlay",t.contentEditable="false",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.userSelect="none",t.style.setProperty("-webkit-user-select","none"),t.style.zIndex="50",t.style.overflow="hidden",this.extensionsRoot=t,t}updateExtensionsOverlayPosition(){if(!this.extensionsRoot)return;const t=this.container.scrollTop,n=this.container.scrollLeft;if(t===0&&n===0){this.extensionsRoot.style.transform="";return}this.extensionsRoot.style.transform=`translate(${n}px, ${t}px)`}updateSelectionOverlay(){if(this.isComposing||!this.overlayRoot||!this.contentRoot)return;const t=it(this.state.doc),n=ui({root:this.contentRoot,container:this.container,docLines:t,selection:this.state.selection});this.lastFocusRect=n.focusRect,this.syncSelectionRects(n.selectionRects),n.caretRect?(this.updateCaret({top:n.caretRect.top,left:n.caretRect.left,height:n.caretRect.height}),this.markCaretActive()):this.updateCaret(null)}syncSelectionRects(t){if(!this.overlayRoot||!this.caretElement)return;Array.from(this.overlayRoot.querySelectorAll(".cake-selection-rect")).forEach(i=>i.remove());const r=document.createDocumentFragment();t.forEach(i=>{const o=document.createElement("div");o.className="cake-selection-rect",o.style.top=`${i.top}px`,o.style.left=`${i.left}px`,o.style.width=`${i.width}px`,o.style.height=`${i.height}px`,r.append(o)}),this.overlayRoot.insertBefore(r,this.caretElement)}updateCaret(t){if(this.caretElement){if(!t){this.caretElement.style.display="none",this.stopCaretBlink();return}this.caretElement.style.display="",this.caretElement.style.top=`${t.top}px`,this.caretElement.style.left=`${t.left}px`,this.caretElement.style.height=`${t.height}px`}}markCaretActive(){this.caretElement&&(this.clearCaretBlinkTimer(),this.caretElement.classList.remove("is-blinking"),this.caretBlinkTimeoutId=window.setTimeout(()=>{var t;this.caretBlinkTimeoutId=null,(t=this.caretElement)==null||t.classList.add("is-blinking")},80))}stopCaretBlink(){this.caretElement&&(this.clearCaretBlinkTimer(),this.caretElement.classList.remove("is-blinking"))}clearCaretBlinkTimer(){this.caretBlinkTimeoutId!==null&&(window.clearTimeout(this.caretBlinkTimeoutId),this.caretBlinkTimeoutId=null)}scheduleScrollCaretIntoView(){this.isComposing||this.scrollCaretIntoViewId===null&&(this.scrollCaretIntoViewId=window.requestAnimationFrame(()=>{this.scrollCaretIntoViewId=null,this.scrollCaretIntoView()}))}scrollCaretIntoView(){if(this.isComposing||!this.contentRoot)return;const t=this.lastFocusRect;if(!t)return;const n=this.container;if(n.clientHeight<=0)return;const r=window.getComputedStyle(this.contentRoot),i=Number.parseFloat(r.paddingTop)||0,o=Number.parseFloat(r.paddingBottom)||0,s=n.scrollTop,a=s+n.clientHeight,l=t.top,c=t.top+t.height;let d=s;if(l<s+i)d=l-i;else if(c>a-o)d=c-n.clientHeight+o;else return;const m=Math.max(0,n.scrollHeight-n.clientHeight),f=Math.max(0,Math.min(d,m));Math.abs(f-n.scrollTop)>.5&&(n.scrollTop=f)}hitTestFromClientPoint(t,n){var c,d;let r=null,i=0,o=!1;const s=Bi(t,n);if(s)r=s.offsetNode,i=s.offset;else{const m=Di(t,n);m&&(r=m.startContainer,i=m.startOffset)}if(!r||!this.container.contains(r)){const m=this.findClosestLineByY(n),f=m?He(m):null;if(f){r=f;const g=fn(f,t,n);i=g.offset,o=g.pastRowEnd}}if(!r||!this.container.contains(r))return null;const a=r instanceof Element?r.closest(".cake-line"):(c=r.parentElement)==null?void 0:c.closest(".cake-line");if(a){const m=a.getBoundingClientRect();if(n<m.top||n>m.bottom){const g=this.findClosestLineByY(n);if(g&&g!==a){const p=He(g);if(p){r=p;const k=fn(p,t,n);i=k.offset,o=k.pastRowEnd}}}}if(r instanceof Element){const m=un(r,i);m&&(r=m.node,i=m.offset)}if(r instanceof Text){const m=fn(r,t,n);i=m.offset,o=m.pastRowEnd}if(!o){const m=r instanceof Element?r.closest(".cake-line"):(d=r.parentElement)==null?void 0:d.closest(".cake-line");if(m){const f=m.getBoundingClientRect();o=t>f.right}}const l=this.cursorFromDom(r,i);return l?o?{cursorOffset:l.cursorOffset,affinity:"backward"}:l:null}handlePointerDown(t){var g;if(!this.isEventTargetInContentRoot(t.target)||(this.hasMovedSincePointerDown=!1,this.pointerDownPosition={x:t.clientX,y:t.clientY},this.pendingClickHit=null,this.readOnly)||t.button!==0||!this.contentRoot)return;if(t.pointerType==="touch"){this.ignoreTouchNativeSelectionUntil=performance.now()+750,this.suppressSelectionChangeForTick(),t.preventDefault();return}const n=this.state.selection;this.blockTrustedTextDrag=!1;const r=t.target;if(r instanceof HTMLElement){const p=r.closest("[data-block-atom]"),k=(p==null?void 0:p.getAttribute("data-line-index"))??null;if(k!==null){const b=Number.parseInt(k,10),w=it(this.state.doc),u=w[b];if(u!=null&&u.isAtomic){const C=at(w)[b]??0,L=C+u.cursorLength+(u.hasNewline?1:0),T={start:C,end:L,affinity:"forward"};t.preventDefault(),t.stopPropagation(),this.pendingClickHit=null,this.suppressSelectionChange=!0,this.state={...this.state,selection:T},this.applySelection(T),(g=this.onSelectionChange)==null||g.call(this,T),this.flushOverlayUpdate(),this.selectedAtomicLineIndex=b,this.dragState={isDragging:!0,startLineIndex:b,endLineIndex:b,pointerId:t.pointerId,hasMoved:!1};try{this.contentRoot.setPointerCapture(t.pointerId)}catch{}return}}}if(n.start===n.end&&!t.shiftKey){this.suppressSelectionChange=!0;const p=this.hitTestFromClientPoint(t.clientX,t.clientY);p&&(this.pendingClickHit=p);return}this.suppressSelectionChange=!1;const i=Math.min(n.start,n.end),o=Math.max(n.start,n.end),s=this.hitTestFromClientPoint(t.clientX,t.clientY);if(!s)return;if(!(s.cursorOffset>=i&&s.cursorOffset<=o)){this.blockTrustedTextDrag=!1;return}const l=it(this.state.doc),c=at(l);let d=-1;for(let p=0;p<c.length;p++){const k=c[p];if(k===i){d=p;break}if(p>0&&k===i+1){d=p;break}}let m=-1;for(let p=0;p<l.length;p++){const k=c[p]??0;if(k>=o)continue;const b=l[p],w=k+b.cursorLength;(o===w||o===w+1)&&(m=p)}if(!(d!==-1&&m!==-1&&m>=d)){t.preventDefault(),t.stopPropagation(),this.blockTrustedTextDrag=!0,this.suppressSelectionChange=!1,this.selectionDragState={pointerId:t.pointerId,anchorOffset:s.cursorOffset};try{this.contentRoot.setPointerCapture(t.pointerId)}catch{}return}t.preventDefault(),t.stopPropagation(),this.suppressSelectionChange=!0,this.dragState={isDragging:!0,startLineIndex:d,endLineIndex:m,pointerId:t.pointerId,hasMoved:!1};try{this.contentRoot.setPointerCapture(t.pointerId)}catch{}}handlePointerMove(t){var r;if(this.pointerDownPosition&&!this.hasMovedSincePointerDown){const i=t.clientX-this.pointerDownPosition.x,o=t.clientY-this.pointerDownPosition.y;Math.sqrt(i*i+o*o)>=5&&(this.hasMovedSincePointerDown=!0,this.pendingClickHit=null,(r=this.dragState)!=null&&r.isDragging||(this.suppressSelectionChange=!1))}if(this.selectionDragState){if(t.pointerId!==this.selectionDragState.pointerId)return;const i=this.hitTestFromClientPoint(t.clientX,t.clientY);if(!i)return;this.applySelectionUpdate({start:this.selectionDragState.anchorOffset,end:i.cursorOffset,affinity:i.affinity});return}!this.dragState||!this.dragState.isDragging||t.pointerId===this.dragState.pointerId&&(this.dragState.hasMoved=!0,this.showDropIndicator(t.clientY))}handlePointerUp(t){if(this.blockTrustedTextDrag=!1,this.pendingClickHit&&(this.pendingClickHit=null,this.suppressSelectionChange=!1),this.selectionDragState){if(t.pointerId!==this.selectionDragState.pointerId)return;if(this.selectionDragState=null,this.contentRoot)try{this.contentRoot.releasePointerCapture(t.pointerId)}catch{}if(this.suppressSelectionChange=!1,!this.hasMovedSincePointerDown){const a=this.hitTestFromClientPoint(t.clientX,t.clientY);a&&this.applySelectionUpdate({start:a.cursorOffset,end:a.cursorOffset,affinity:a.affinity})}return}if(!this.dragState||!this.dragState.isDragging){this.hasMovedSincePointerDown&&queueMicrotask(()=>{this.syncSelectionFromDom(),this.flushOverlayUpdate()});return}if(t.pointerId!==this.dragState.pointerId)return;const{startLineIndex:n,endLineIndex:r,hasMoved:i}=this.dragState;if(this.contentRoot)try{this.contentRoot.releasePointerCapture(t.pointerId)}catch{}if(this.hideDropIndicator(),this.dragState=null,this.suppressSelectionChange=!1,!i)return;const o=this.calculateDropLineIndex(t.clientY);o===null||!(o<n||o>r+1)||this.moveLines(n,r,o)}showDropIndicator(t){if(!this.contentRoot)return;if(!this.dropIndicator){const s=document.createElement("div");s.className="cake-drop-indicator",s.style.position="absolute",s.style.left="0",s.style.right="0",s.style.height="2px",s.style.background="var(--accent-color, #0066cc)",s.style.pointerEvents="none",s.style.zIndex="1000",this.dropIndicator=s}const n=this.container.getBoundingClientRect(),r=this.container.scrollTop,i=this.contentRoot.querySelectorAll("[data-line-index]");let o=0;for(const s of i){const a=s.getBoundingClientRect(),l=(a.top+a.bottom)/2;if(t>=l)o=a.bottom-n.top+r;else break}if(i.length>0){const a=i[0].getBoundingClientRect();t<(a.top+a.bottom)/2&&(o=a.top-n.top+r)}this.dropIndicator.style.top=`${o-1}px`,this.dropIndicator.parentElement||this.container.appendChild(this.dropIndicator)}hideDropIndicator(){var t;(t=this.dropIndicator)!=null&&t.parentElement&&this.dropIndicator.remove()}findClosestLineByY(t){if(!this.contentRoot)return null;const n=this.contentRoot.querySelectorAll("[data-line-index]");if(n.length===0)return null;let r=null,i=1/0;for(const o of n){const s=o.getBoundingClientRect(),a=(s.top+s.bottom)/2,l=Math.abs(t-a);l<i&&(i=l,r=o)}return r}calculateDropLineIndex(t){if(!this.contentRoot)return null;const n=this.contentRoot.querySelectorAll("[data-line-index]"),r=this.state.doc.blocks.length;if(n.length===0)return 0;let i=0;for(const o of n){const s=o.getBoundingClientRect(),a=parseInt(o.getAttribute("data-line-index")??"0",10),l=(s.top+s.bottom)/2;t>=l&&(i=a+1)}return Math.min(i,r)}detectFullLineSelection(t,n,r,i){let o=-1;for(let l=0;l<i.length;l++){const c=i[l];if(c===t){o=l;break}if(l>0&&c===t+1){o=l;break}}let s=-1;for(let l=0;l<r.length;l++){const c=i[l]??0;if(c>=n)continue;const d=r[l],m=c+d.cursorLength;(n===m||n===m+1)&&(s=l)}return o!==-1&&s!==-1&&s>=o?{startLineIndex:o,endLineIndex:s}:null}moveLines(t,n,r){var f;const o=this.state.source.split(`
88
+ `),s=o.length;if(t<0||n>=s||t>n||r<0||r>s)return;const a=o.slice(t,n+1),l=a.length;let c;r<=t?c=[...o.slice(0,r),...a,...o.slice(r,t),...o.slice(n+1)]:c=[...o.slice(0,t),...o.slice(n+1,r),...a,...o.slice(r)];const d=c.join(`
89
+ `);let m;if(r<=t)m=c.slice(0,r).join(`
90
+ `).length,r>0&&(m+=1);else{const g=r-l;m=c.slice(0,g).join(`
91
+ `).length,g>0&&(m+=1)}this.recordHistory("move"),this.state=this.runtime.createState(d,{start:m,end:m,affinity:"forward"}),this.render(),(f=this.onChange)==null||f.call(this,this.state.source,this.state.selection)}handleDragStart(t){if(this.readOnly)return;if(t.isTrusted&&this.blockTrustedTextDrag){t.preventDefault();return}let n=this.state.selection,r=Math.min(n.start,n.end),i=Math.max(n.start,n.end);if(r===i&&this.domMap){const p=Qt(this.domMap);p&&p.start!==p.end&&(n=p,r=Math.min(p.start,p.end),i=Math.max(p.start,p.end))}if(r===i)return;const o=it(this.state.doc),s=ae(o),a=zt(o,r),l=zt(o,i),c=s.slice(a,l),d=this.state.map,m=d.cursorToSource(r,"backward"),f=d.cursorToSource(i,"forward"),g=this.state.source.slice(m,f);this.textDragState={selection:{start:r,end:i,affinity:n.affinity},plainText:c,sourceText:g},t.dataTransfer&&(t.dataTransfer.setData("text/plain",c),t.dataTransfer.effectAllowed="move")}handleDragOver(t){this.readOnly||(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect=this.textDragState?"move":"copy"))}handleDrop(t){var d,m;if(this.readOnly)return;const n=t.dataTransfer;if(this.dataTransferHasImageFile(n)){this.textDragState=null;return}const i=this.hitTestFromClientPoint(t.clientX,t.clientY);if(!i){this.textDragState=null;return}t.preventDefault(),t.stopPropagation();const o=i.cursorOffset;let s=this.textDragState;if(this.textDragState=null,!s){let f=this.state.selection;if(f.start===f.end&&this.domMap){const g=Qt(this.domMap);g&&g.start!==g.end&&(f=g)}if(f.start!==f.end){const g=Math.min(f.start,f.end),p=Math.max(f.start,f.end),k=it(this.state.doc),b=ae(k),w=zt(k,g),u=zt(k,p),E=b.slice(w,u),C=this.state.map,L=C.cursorToSource(g,"backward"),T=C.cursorToSource(p,"forward"),A=this.state.source.slice(L,T);s={selection:{start:g,end:p,affinity:f.affinity},plainText:E,sourceText:A}}}if(s){const f=s.selection.start,g=s.selection.end;if(o>=f&&o<=g)return;const p=it(this.state.doc),k=at(p),b=this.detectFullLineSelection(f,g,p,k);if(b){const A=this.calculateDropLineIndex(t.clientY);if(A===null||!(A<b.startLineIndex||A>b.endLineIndex+1))return;this.moveLines(b.startLineIndex,b.endLineIndex,A);return}this.recordHistory("drag_drop");const w=g-f,u=o>g?o-w:o,E=this.runtime.createState(this.state.source,{start:f,end:g,affinity:"forward"}),C=this.runtime.applyEdit({type:"insert",text:""},E),L=this.runtime.createState(C.source,{start:u,end:u,affinity:"forward"}),T=this.runtime.applyEdit({type:"insert",text:s.sourceText},L);this.state=T,this.render(),(d=this.onChange)==null||d.call(this,this.state.source,this.state.selection);return}const a=(n==null?void 0:n.getData("text/plain"))??"";if(!a)return;this.recordHistory("paste");const l=this.runtime.createState(this.state.source,{start:o,end:o,affinity:"forward"}),c=this.runtime.applyEdit({type:"insert",text:a},l);this.state=c,this.render(),(m=this.onChange)==null||m.call(this,this.state.source,this.state.selection)}handleDragEnd(){this.textDragState=null}dataTransferHasImageFile(t){if(!t)return!1;if(t.files)for(let n=0;n<t.files.length;n++){const r=t.files[n];if(r&&r.type.startsWith("image/"))return!0}if(t.items)for(let n=0;n<t.items.length;n++){const r=t.items[n];if(r.kind==="file"&&r.type.startsWith("image/"))return!0}return!1}}function Oi(e,t){return e.start===t.start&&e.end===t.end&&e.affinity===t.affinity}function Mi(e){return e==="insertCompositionText"||e==="compositionend"}function un(e,t){const n=e.childNodes;if(n.length===0)return null;if(t<=0){const s=Zn(n,0);return s?{node:s,offset:0}:null}if(t>=n.length){const s=tr(n,n.length-1);return s?{node:s,offset:s.data.length}:null}const r=He(n[t]);if(r)return{node:r,offset:0};const i=tr(n,t-1);if(i)return{node:i,offset:i.data.length};const o=Zn(n,t+1);return o?{node:o,offset:0}:null}function He(e){if(e instanceof Text)return e;const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT).nextNode();return n instanceof Text?n:null}function Pi(e){if(e instanceof Text)return e;const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let n=null,r=t.nextNode();for(;r;)r instanceof Text&&(n=r),r=t.nextNode();return n}function Zn(e,t){for(let n=Math.max(0,t);n<e.length;n+=1){const r=He(e[n]);if(r)return r}return null}function fn(e,t,n){const r=e.textContent??"";if(r.length===0)return{offset:0,pastRowEnd:!1};let i=0,o=1/0,s=1/0,a=0,l=0;const c=new Map,d=document.createRange();let m=null;for(let p=0;p<=r.length;p+=1){p<r.length?(d.setStart(e,p),d.setEnd(e,p+1)):(d.setStart(e,p),d.setEnd(e,p));let k=d.getClientRects();if(k.length===0&&p===r.length&&m&&(k=[new DOMRect(m.right,m.top,0,m.height)]),k.length===0)continue;p<r.length&&(m=k[0]);let b=k[0];for(let D=1;D<k.length;D+=1){const j=k[D],Z=b.top+b.height/2,K=j.top+j.height/2;Math.abs(n-K)<Math.abs(n-Z)&&(b=j)}const w=Math.round(b.top);if(!c.has(w))c.set(w,{startOffset:p,endOffset:p,left:b.left,right:b.right,top:b.top,bottom:b.bottom});else{const D=c.get(w);D&&(D.startOffset=Math.min(D.startOffset,p),D.endOffset=Math.max(D.endOffset,p),D.left=Math.min(D.left,b.left),D.right=Math.max(D.right,b.right),D.top=Math.min(D.top,b.top),D.bottom=Math.max(D.bottom,b.bottom))}const u=b.top+b.height/2,E=Math.abs(n-u),L=n>=b.top&&n<=b.bottom,T=b.left,A=Math.abs(t-T);L?A<=o&&(o=A,i=p,a=T,l=b.top,s=E):(E<s||E===s&&A<o)&&(s=E,o=A,i=p,a=T,l=b.top)}let f=null;for(const p of c.values())if(n>=p.top&&n<=p.bottom){f=p;break}if(!f){let p=1/0;for(const k of c.values()){const b=k.top+(k.bottom-k.top)/2,w=Math.abs(n-b);w<p&&(p=w,f=k)}}if(f){if(t<f.left)i=f.startOffset,a=f.left,l=f.top;else if(t>f.right)i=f.endOffset,a=f.right,l=f.top;else if(n<f.top||n>f.bottom){let p=1/0;const k=document.createRange();for(let b=f.startOffset;b<=f.endOffset;b+=1){b<r.length?(k.setStart(e,b),k.setEnd(e,b+1)):(k.setStart(e,b),k.setEnd(e,b));const w=k.getClientRects();if(w.length===0)continue;const u=w[0],E=Math.abs(t-u.left);E<=p&&(p=E,i=b,a=u.left,l=f.top)}}}const g=f!==null&&t>f.right&&Math.abs(n-l)<1;return Math.abs(t-a)<=2&&i<r.length&&r[i]===`
92
+ `&&(i=Math.max(0,i-1)),{offset:i,pastRowEnd:g}}function Bi(e,t){const n=document;return typeof n.caretPositionFromPoint=="function"?n.caretPositionFromPoint(e,t):null}function Di(e,t){return typeof document.caretRangeFromPoint=="function"?document.caretRangeFromPoint(e,t):null}function Bt(e){const{lines:t,layout:n,offset:r,affinity:i}=e;if(!n||n.lines.length===0)return{rowStart:0,rowEnd:0};const o=ut(t,r),s=n.lines[o.lineIndex];if(!s)return{rowStart:0,rowEnd:0};if(s.rows.length===0)return{rowStart:s.lineStartOffset,rowEnd:s.lineStartOffset+s.lineLength};const a=Ai(s.rows,o.offsetInLine,i),l=s.rows[a]??s.rows[s.rows.length-1];return{rowStart:s.lineStartOffset+l.startOffset,rowEnd:s.lineStartOffset+l.endOffset}}function Ai(e,t,n){if(e.length===0)return 0;for(let r=0;r<e.length;r+=1){const i=e[r];if(t===i.startOffset)return n==="backward"&&r>0?r-1:r;if(t===i.endOffset)return n==="forward"&&r+1<e.length?r+1:r;if(t>i.startOffset&&t<i.endOffset)return r}return e.length-1}function dn(e){return e.start===e.end?e.affinity??"backward":e.affinity??"forward"}function ze(e,t){const n=qn(e.start,t),r=qn(e.end,t),i=n<=r?{start:n,end:r}:{start:r,end:n};return e.affinity?{...i,affinity:e.affinity}:i}function Wt(e){return e.start===e.end?{anchor:e.start,focus:e.start}:dn(e)==="backward"?{anchor:e.end,focus:e.start}:{anchor:e.start,focus:e.end}}function Dt(e,t,n){return e===t?{start:t,end:t,affinity:n}:e<t?{start:e,end:t,affinity:"forward"}:{start:t,end:e,affinity:"backward"}}function qn(e,t){return Math.max(0,Math.min(e,t))}function tr(e,t){for(let n=Math.min(e.length-1,t);n>=0;n-=1){const r=Pi(e[n]);if(r)return r}return null}const Ni=[{name:"blockquote",extensions:[$e]},{name:"heading",extensions:[qe]},{name:"list",extensions:[nn]},{name:"combined-emphasis",extensions:[Ye]},{name:"bold",extensions:[Ke]},{name:"italic",extensions:[Qe]},{name:"strikethrough",extensions:[on]},{name:"pipe-link",extensions:[Xe]},{name:"link",extensions:[Ge]},{name:"image",extensions:[tn]}],Fi=({state:e,dispatch:t})=>{const n=e.changeByRange(r=>{const i=e.sliceDoc(r.from-2,r.from)==="**",o=e.sliceDoc(r.to,r.to+2)==="**",s=[];s.push(i?{from:r.from-2,to:r.from,insert:""}:{from:r.from,insert:"**"}),s.push(o?{from:r.to,to:r.to+2,insert:""}:{from:r.to,insert:"**"});const a=i?-2:2,l=o?-2:2;return{changes:s,range:lt.EditorSelection.range(r.from+a,r.to+l)}});return t(e.update(n,{scrollIntoView:!0,annotations:lt.Transaction.userEvent.of("input")})),!0},Ui=({state:e,dispatch:t})=>{const n=e.changeByRange(r=>{const i=e.sliceDoc(r.from-1,r.from)==="*",o=e.sliceDoc(r.to,r.to+1)==="*",s=[];s.push(i?{from:r.from-1,to:r.from,insert:""}:{from:r.from,insert:"*"}),s.push(o?{from:r.to,to:r.to+1,insert:""}:{from:r.to,insert:"*"});const a=i?-1:1,l=o?-1:1;return{changes:s,range:lt.EditorSelection.range(r.from+a,r.to+l)}});return t(e.update(n,{scrollIntoView:!0,annotations:lt.Transaction.userEvent.of("input")})),!0},_i=({state:e,dispatch:t})=>{const n=e.changeByRange(r=>{const i=e.sliceDoc(r.from-2,r.from)==="~~",o=e.sliceDoc(r.to,r.to+2)==="~~",s=[];s.push(i?{from:r.from-2,to:r.from,insert:""}:{from:r.from,insert:"~~"}),s.push(o?{from:r.to,to:r.to+2,insert:""}:{from:r.to,insert:"~~"});const a=i?-2:2,l=o?-2:2;return{changes:s,range:lt.EditorSelection.range(r.from+a,r.to+l)}});return t(e.update(n,{scrollIntoView:!0,annotations:lt.Transaction.userEvent.of("input")})),!0},Hi=({state:e,dispatch:t})=>{const n=e.changeByRange(r=>{const i=[],o=e.sliceDoc(r.from,r.to),s=/^\[([^\]]*)\]\(([^)]*)\)$/,a=o.match(s);if(a){const l=a[1];return i.push({from:r.from,to:r.to,insert:l}),{changes:i,range:lt.EditorSelection.range(r.from,r.from+l.length)}}else{i.push({from:r.from,insert:"["}),i.push({from:r.to,insert:"]()"});const l=r.to+3;return{changes:i,range:lt.EditorSelection.cursor(l)}}});return t(e.update(n,{scrollIntoView:!0,annotations:lt.Transaction.userEvent.of("input")})),!0},er=/^(\s*)([-*+]|(\d+)\.)(\s+)(.*)/,zi=({state:e,dispatch:t})=>{const n=e.changeByRange(r=>{const i=[];if(r.from===r.to)return i.push({from:r.from,insert:"-"}),{changes:i,range:lt.EditorSelection.cursor(r.from+1)};const o=e.doc.lineAt(r.from),s=e.doc.lineAt(r.to);let a=0;for(let l=o.number;l<=s.number;l++){const c=e.doc.line(l),d=c.text,m=d.match(er);if(m){const[,f,,g,p]=m;if(g){const k=f.length+g.length+1+p.length,b=`${f}- `;i.push({from:c.from,to:c.from+k,insert:b}),a+=b.length-k}}else{const f=d.match(/^(\s*)/),g=f?f[1]:"";i.push({from:c.from+g.length,insert:"- "}),a+=2}}return{changes:i,range:lt.EditorSelection.range(r.from,r.to+a)}});return t(e.update(n,{scrollIntoView:!0,annotations:lt.Transaction.userEvent.of("input")})),!0},Vi=({state:e,dispatch:t})=>{const n=e.changeByRange(r=>{const i=[];if(r.from===r.to)return i.push({from:r.from,insert:"1. "}),{changes:i,range:lt.EditorSelection.cursor(r.from+3)};const o=e.doc.lineAt(r.from),s=e.doc.lineAt(r.to);let a=1,l=0;for(let c=o.number;c<=s.number;c++){const d=e.doc.line(c),m=d.text,f=m.match(er);if(f){const[,g,p,k,b]=f;if(k){const w=g.length+k.length+1+b.length,u=`${g}${a}. `;i.push({from:d.from,to:d.from+w,insert:u}),l+=u.length-w,a++}else{const w=g.length+p.length+b.length,u=`${g}${a}. `;i.push({from:d.from,to:d.from+w,insert:u}),l+=u.length-w,a++}}else{const g=m.match(/^(\s*)/),p=g?g[1]:"",k=`${a}. `;i.push({from:d.from+p.length,insert:k}),l+=k.length,a++}}return{changes:i,range:lt.EditorSelection.range(r.from,r.to+l)}});return t(e.update(n,{scrollIntoView:!0,annotations:lt.Transaction.userEvent.of("input")})),!0};function hn(e){return e?{start:e.start,end:e.end,affinity:e.affinity}:{start:0,end:0,affinity:"forward"}}const ji="**",Wi="*",Ki="~~";function Yi(e){return e===Fi?{type:"toggle-inline",marker:ji}:e===Ui?{type:"toggle-inline",marker:Wi}:e===_i?{type:"toggle-inline",marker:Ki}:e===Hi?{type:"wrap-link",openPopover:!0}:e===zi?{type:"toggle-bullet-list"}:e===Vi?{type:"toggle-numbered-list"}:null}const nr=_.forwardRef(function(t,n){const r=_.useRef(null),i=_.useRef(null),o=_.useRef(t.onChange),s=_.useRef(t.onSelectionChange),a=_.useRef(null),l=_.useRef(null),[c,d]=_.useState(null),[m,f]=_.useState(null),g=_.useRef(t.extensionBundles??Ni),p=_.useMemo(()=>(t.extensions??[]).filter(u=>u.type==="overlay"),[t.extensions]);_.useEffect(()=>{o.current=t.onChange,s.current=t.onSelectionChange},[t.onChange,t.onSelectionChange]),_.useEffect(()=>{var u;(u=i.current)==null||u.syncPlaceholder()},[t.placeholder]),_.useEffect(()=>{const u=r.current;if(!u)return;const E=new Qn({container:u,value:t.value??t.initialValue??"",selection:t.selection??void 0,extensions:g.current.flatMap(C=>C.extensions),readOnly:t.disabled??!1,spellCheckEnabled:t.settings.spellCheckEnabled,onChange:(C,L)=>{var T;a.current=C,l.current=L,o.current(C),(T=s.current)==null||T.call(s,L.start,L.end,L.affinity)},onSelectionChange:C=>{var L;l.current=C,(L=s.current)==null||L.call(s,C.start,C.end,C.affinity)}});return i.current=E,d(E.getOverlayRoot()),f(E.getContentRoot()),()=>{E.destroy(),i.current=null,d(null),f(null)}},[]),_.useEffect(()=>{const u=i.current;u&&u.setReadOnly(t.disabled??!1)},[t.disabled]),_.useEffect(()=>{const u=i.current;u&&u.setSpellCheckEnabled(t.settings.spellCheckEnabled)},[t.settings.spellCheckEnabled]),_.useEffect(()=>{const u=i.current;if(!u)return;const E=t.value??t.initialValue??"",C=t.selection?hn(t.selection):void 0;a.current!==E&&u.setValue({value:E,selection:C})},[t.value,t.initialValue,t.selection]),_.useImperativeHandle(n,()=>({element:r.current,focus:u=>{var C;const E=u!=null&&u.selection?hn(u.selection):void 0;(C=i.current)==null||C.focus(E)},blur:()=>{var u;(u=i.current)==null||u.blur()},hasFocus:()=>{var u;return((u=i.current)==null?void 0:u.hasFocus())??!1},selectAll:()=>{var u;(u=i.current)==null||u.selectAll()},executeCommand:u=>{if(!i.current)return!1;const E=Yi(u);return E?i.current.executeCommand(E):!1},applyUpdate:u=>{if(!i.current)return;const E=i.current,C=u.selection?hn(u.selection):void 0;if(u.value!==void 0){E.setValue({value:u.value,selection:C}),u.focus&&E.focus(C);return}if(u.selection){if(!C)return;E.setSelection(C),u.focus&&E.focus(C);return}u.focus&&E.focus()},getValue:()=>{var u;return((u=i.current)==null?void 0:u.getValue())??t.value??""},getSelectedText:()=>null,getSelectedMarkdown:()=>null,getDocSelectionRange:()=>{var E;const u=(E=i.current)==null?void 0:E.getSelection();return u?{start:u.start,end:u.end}:null},getDocTextBetween:()=>null}),[t.value]);const k=t.style?{...t.style}:{};k.position||(k.position="relative");const b=t.className?`cake ${t.className}`:"cake",w=c&&r.current&&m?{container:r.current,contentRoot:m,overlayRoot:c,toOverlayRect:u=>{var C;const E=(C=r.current)==null?void 0:C.getBoundingClientRect();return E?{top:u.top-E.top,left:u.left-E.left,width:u.width,height:u.height}:{top:u.top,left:u.left,width:u.width,height:u.height}},insertText:u=>{var E;(E=i.current)==null||E.insertText(u)},replaceText:(u,E)=>{var C;(C=i.current)==null||C.replaceText(u,E)},getSelection:()=>{var C;const u=(C=i.current)==null?void 0:C.getSelection();if(!u)return null;const E=u.start===u.end?u.start:Math.max(u.start,u.end);return{start:E,end:E}}}:null;return Q.jsxDEV(Q.Fragment,{children:[Q.jsxDEV("div",{ref:r,className:b,style:k,"data-placeholder":t.placeholder,onBlur:u=>{var E;(E=t.onBlur)==null||E.call(t,u.nativeEvent)}},void 0,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/react/CakeEditor.tsx",lineNumber:323,columnNumber:7},this),c&&w?rr.createPortal(Q.jsxDEV(Q.Fragment,{children:[g.current.flatMap(u=>u.extensions.map(E=>E.renderOverlay?Q.jsxDEV(_.Fragment,{children:E.renderOverlay(w)},`${u.name}:${E.name}`,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/react/CakeEditor.tsx",lineNumber:338,columnNumber:21},this):null)),p.map(u=>Q.jsxDEV(_.Fragment,{children:u.render(w)},u.name,!1,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/react/CakeEditor.tsx",lineNumber:346,columnNumber:19},this))]},void 0,!0,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/react/CakeEditor.tsx",lineNumber:334,columnNumber:13},this),c):null]},void 0,!0,{fileName:"/Users/moboudra/dev/blankpage/cake/src/cake/react/CakeEditor.tsx",lineNumber:322,columnNumber:5},this)});nr.displayName="CakeEditor";const Gi={theme:"light",spellCheckEnabled:!1,fullScreenEnabled:!1,showUpgradeSuccessModal:!0,counterVisible:!1,goalType:null,goalValue:null};q.CakeEditor=nr,q.CakeEngine=Qn,q.blockquoteExtension=$e,q.boldExtension=Ke,q.bundledExtensions=_n,q.combinedEmphasisExtension=Ye,q.defaultEditorSettings=Gi,q.headingExtension=qe,q.imageExtension=tn,q.italicExtension=Qe,q.linkExtension=Ge,q.listExtension=nn,q.pipeLinkExtension=Xe,q.scrollbarExtension=Zr,q.strikethroughExtension=on,Object.defineProperty(q,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@blankdotpage/cake",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "dev": "vite",
20
+ "build": "vite build && tsc -p tsconfig.build.json",
21
+ "test": "vitest run",
22
+ "test:browser": "vitest run --project browser",
23
+ "typecheck": "tsc -p tsconfig.json --noEmit",
24
+ "lint": "eslint .",
25
+ "check": "npm run test && npm run build",
26
+ "demo": "npm --workspace demo run dev"
27
+ },
28
+ "dependencies": {
29
+ "@codemirror/state": "^6.4.1",
30
+ "lucide-react": "^0.395.0",
31
+ "react": "^18.3.1",
32
+ "react-dom": "^18.3.1",
33
+ "turndown": "^7.2.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^20.12.7",
37
+ "@types/react": "^18.3.5",
38
+ "@types/react-dom": "^18.3.0",
39
+ "@types/turndown": "^5.0.5",
40
+ "@vitejs/plugin-react": "^4.3.1",
41
+ "@vitest/browser": "^4.0.17",
42
+ "@vitest/browser-playwright": "^4.0.17",
43
+ "playwright": "^1.46.0",
44
+ "typescript": "^5.5.4",
45
+ "vite": "^5.4.1",
46
+ "vitest": "^4.0.17",
47
+ "vitest-browser-react": "^2.0.2"
48
+ },
49
+ "workspaces": [
50
+ "demo"
51
+ ]
52
+ }