diff --git a/CHANGELOG.md b/CHANGELOG.md
index f718845..a2130ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## [2.2.0] - 2025-12-26
+
+### Added
+- File upload support with drag-and-drop and paste handling
+
+
+
## [2.1.1] - 2025-12-13
### Added
diff --git a/README.md b/README.md
index 7a9aaed..9650c37 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# OverType
-A lightweight markdown editor library with perfect WYSIWYG alignment using an invisible textarea overlay technique. Includes optional toolbar. ~95KB minified with all features.
+A lightweight markdown editor library with perfect WYSIWYG alignment using an invisible textarea overlay technique. Includes optional toolbar. ~98KB minified with all features.
## Live Examples
@@ -19,7 +19,7 @@ A lightweight markdown editor library with perfect WYSIWYG alignment using an in
- ⌨️ **Keyboard shortcuts** - Common markdown shortcuts (Cmd/Ctrl+B for bold, etc.)
- 📱 **Mobile optimized** - Responsive design with mobile-specific styles
- 🔄 **DOM persistence aware** - Recovers from existing DOM (perfect for HyperClay and similar platforms)
-- 🚀 **Lightweight** - ~95KB minified
+- 🚀 **Lightweight** - ~98KB minified
- 🎯 **Optional toolbar** - Clean, minimal toolbar with all essential formatting
- ✨ **Smart shortcuts** - Keyboard shortcuts with selection preservation
- 📝 **Smart list continuation** - GitHub-style automatic list continuation on Enter
@@ -35,7 +35,7 @@ We overlap an invisible textarea on top of styled output, giving the illusion of
| Feature | OverType | HyperMD | Milkdown | TUI Editor | EasyMDE |
|---------|----------|---------|----------|------------|---------|
-| **Size** | ~95KB | 364.02 KB | 344.51 KB | 560.99 KB | 323.69 KB |
+| **Size** | ~98KB | 364.02 KB | 344.51 KB | 560.99 KB | 323.69 KB |
| **Dependencies** | Bundled | CodeMirror | ProseMirror + plugins | Multiple libs | CodeMirror |
| **Setup** | Single file | Complex config | Build step required | Complex config | Moderate |
| **Approach** | Invisible textarea | ContentEditable | ContentEditable | ContentEditable | CodeMirror |
@@ -355,6 +355,52 @@ function MarkdownEditor({ value, onChange }) {
}
```
+### File Upload
+
+When enabled, users can paste or drag-and-drop files into the editor. A placeholder is inserted while the file is uploaded asynchronously.
+
+```javascript
+const [editor] = new OverType('#editor', {
+ fileUpload: {
+ enabled: true,
+ onInsertFile: async (file) => {
+ // Upload file to server here
+ const formData = new FormData();
+ formData.append('file', file);
+ const response = await fetch('/api/upload', {
+ method: 'POST',
+ body: formData
+ });
+ const data = await response.json();
+ // Return markdown to insert
+ return ``;
+ }
+ }
+});
+```
+
+Files can also be uploaded in batch mode by setting `fileUpload.batch` to `true`. In this mode, all files dropped or pasted at once are sent together in a single call to `onInsertFile`, which receives an array of files and should return an array of corresponding markdown strings.
+
+```javascript
+const [editor] = new OverType('#editor', {
+ fileUpload: {
+ enabled: true,
+ batch: true, // Enable batch upload
+ onInsertFile: async (files) => {
+ const formData = new FormData();
+ files.forEach(file => formData.append('file[]', file));
+ const response = await fetch('/api/upload', {
+ method: 'POST',
+ body: formData
+ });
+ const data = await response.json();
+ // Return array of markdown strings
+ return data.urls.map((url, index) => `![${files[index].name}](${url})`);
+ }
+ }
+});
+```
+
### Standalone Parser
Import and use the markdown parser without the full editor for server-side rendering, static site generation, or browser extensions:
@@ -473,7 +519,22 @@ new OverType(target, options)
// Callbacks
onChange: (value, instance) => {},
- onKeydown: (event, instance) => {}
+ onKeydown: (event, instance) => {},
+
+ // File Upload
+ fileUpload: {
+ enabled: false, // Enable/disable file upload
+ maxSize: 10 * 1024 * 1024, // Defaults to 10 MB
+ mimeTypes: [], // Allowed mime types. Default is all files allowed
+ onInsertFile: async (file) => {
+ // Callback when placeholder is inserted into editor
+ // Upload to server here
+ // (e.g await fetch('/api/upload'))
+
+ // Return the markdown that should replace the placeholder
+ return `})`;
+ },
+ }
}
```
@@ -775,6 +836,7 @@ Special thanks to:
- [1951FDG](https://github.com/1951FDG) - Reported unordered list rendering bug ([#74](https://github.com/panphora/overtype/issues/74)), suggested showStats() API improvement ([#77](https://github.com/panphora/overtype/issues/77))
- [nodesocket](https://github.com/nodesocket) - Reported toolbarButtons export issues ([#73](https://github.com/panphora/overtype/issues/73), [#78](https://github.com/panphora/overtype/issues/78))
- [Travis Bell](https://github.com/travisbell) - Reported keyboard shortcuts bug in ESM build ([#80](https://github.com/panphora/overtype/issues/80))
+- [Richard Leek](https://github.com/sorokya) - Added file upload feature ([#27](https://github.com/panphora/overtype/issues/27))
### TypeScript & Framework Support
- [merlinz01](https://github.com/merlinz01) - Contributed TypeScript declaration file ([#20](https://github.com/panphora/overtype/pull/20))
diff --git a/dist/overtype-webcomponent.esm.js b/dist/overtype-webcomponent.esm.js
index 9a3574e..a9cb13a 100644
--- a/dist/overtype-webcomponent.esm.js
+++ b/dist/overtype-webcomponent.esm.js
@@ -1,5 +1,5 @@
/**
- * OverType v2.1.0
+ * OverType v2.2.0
* A lightweight markdown editor library with perfect WYSIWYG alignment
* @license MIT
* @author David Miranda
@@ -3704,8 +3704,116 @@ var _OverType = class _OverType {
this.toolbar.destroy();
this.toolbar = null;
}
+ if (this.options.fileUpload && !this.fileUploadInitialized) {
+ this._initFileUpload();
+ } else if (!this.options.fileUpload && this.fileUploadInitialized) {
+ this._destroyFileUpload();
+ }
this.updatePreview();
}
+ _initFileUpload() {
+ const options = this.options.fileUpload;
+ if (!options)
+ return;
+ if (!options.enabled)
+ return;
+ options.maxSize = options.maxSize || 10 * 1024 * 1024;
+ options.mimeTypes = options.mimeTypes || [];
+ options.batch = options.batch || false;
+ if (!options.onInsertFile || typeof options.onInsertFile !== "function") {
+ console.warn("OverType: fileUpload.onInsertFile callback is required for file uploads.");
+ return;
+ }
+ this._boundHandleFilePaste = this._handleFilePaste.bind(this);
+ this._boundHandleFileDrop = this._handleFileDrop.bind(this);
+ this._boundHandleDragOver = this._handleDragOver.bind(this);
+ this.textarea.addEventListener("paste", this._boundHandleFilePaste);
+ this.textarea.addEventListener("drop", this._boundHandleFileDrop);
+ this.textarea.addEventListener("dragover", this._boundHandleDragOver);
+ this.fileUploadInitialized = true;
+ }
+ _handleFilePaste(e) {
+ var _a, _b;
+ if (!((_b = (_a = e == null ? void 0 : e.clipboardData) == null ? void 0 : _a.files) == null ? void 0 : _b.length))
+ return;
+ e.preventDefault();
+ this._handleDataTransfer(e.clipboardData);
+ }
+ _handleFileDrop(e) {
+ var _a, _b;
+ if (!((_b = (_a = e == null ? void 0 : e.dataTransfer) == null ? void 0 : _a.files) == null ? void 0 : _b.length))
+ return;
+ e.preventDefault();
+ this._handleDataTransfer(e.dataTransfer);
+ }
+ _handleDataTransfer(dataTransfer) {
+ var _a;
+ const files = [];
+ for (const file of dataTransfer.files) {
+ if (file.size > this.options.fileUpload.maxSize) {
+ continue;
+ }
+ if (((_a = this.options.fileUpload.mimeTypes) == null ? void 0 : _a.length) > 0 && !this.options.fileUpload.mimeTypes.includes(file.type)) {
+ continue;
+ }
+ const prefix = this._isImageFile(file.type) ? "!" : "";
+ const placeholder = `${prefix}[Uploading ${file.name}...]()`;
+ this.insertAtCursor(`${placeholder}
+`);
+ if (this.options.fileUpload.batch) {
+ files.push({ file, placeholder });
+ continue;
+ }
+ this.options.fileUpload.onInsertFile(file).then((text) => {
+ this.textarea.value = this.textarea.value.replace(placeholder, text);
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }, (error) => {
+ console.error("OverType: File upload failed", error);
+ this.textarea.value = this.textarea.value.replace(placeholder, "[Upload failed]()");
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ if (this.options.fileUpload.batch && files.length > 0) {
+ this.options.fileUpload.onInsertFile(files.map((f) => f.file)).then((texts) => {
+ texts.forEach((text, index) => {
+ this.textarea.value = this.textarea.value.replace(files[index].placeholder, text);
+ });
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }, (error) => {
+ console.error("OverType: File upload failed", error);
+ files.forEach(({ placeholder }) => {
+ this.textarea.value = this.textarea.value.replace(placeholder, "[Upload failed]()");
+ });
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ }
+ _isImageFile(type) {
+ return type.startsWith("image/");
+ }
+ _handleDragOver(e) {
+ e.preventDefault();
+ }
+ _destroyFileUpload() {
+ this.textarea.removeEventListener("paste", this._boundHandleFilePaste || this._handleFilePaste);
+ this.textarea.removeEventListener("dragover", this._boundHandleDragOver || this._handleDragOver);
+ this.textarea.removeEventListener("drop", this._boundHandleFileDrop || this._handleFileDrop);
+ this._boundHandleFilePaste = null;
+ this._boundHandleFileDrop = null;
+ this._boundHandleDragOver = null;
+ this.fileUploadInitialized = false;
+ }
+ insertAtCursor(text) {
+ const start = this.textarea.selectionStart;
+ const end = this.textarea.selectionEnd;
+ if (!document.execCommand("insertText", false, text)) {
+ const before = this.textarea.value.slice(0, start);
+ const after = this.textarea.value.slice(end);
+ this.textarea.value = before + text + after;
+ this.textarea.setSelectionRange(start + text.length, start + text.length);
+ }
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }
/**
* Update preview with parsed markdown
*/
@@ -4044,6 +4152,12 @@ var _OverType = class _OverType {
this.toolbar = null;
this._createToolbar();
}
+ if (this.fileUploadInitialized) {
+ this._destroyFileUpload();
+ }
+ if (this.options.fileUpload) {
+ this._initFileUpload();
+ }
this._applyOptions();
this.updatePreview();
}
diff --git a/dist/overtype-webcomponent.js b/dist/overtype-webcomponent.js
index a1e631b..ef8d9de 100644
--- a/dist/overtype-webcomponent.js
+++ b/dist/overtype-webcomponent.js
@@ -1,5 +1,5 @@
/**
- * OverType v2.1.0
+ * OverType v2.2.0
* A lightweight markdown editor library with perfect WYSIWYG alignment
* @license MIT
* @author David Miranda
@@ -3727,8 +3727,116 @@ ${blockSuffix}` : suffix;
this.toolbar.destroy();
this.toolbar = null;
}
+ if (this.options.fileUpload && !this.fileUploadInitialized) {
+ this._initFileUpload();
+ } else if (!this.options.fileUpload && this.fileUploadInitialized) {
+ this._destroyFileUpload();
+ }
this.updatePreview();
}
+ _initFileUpload() {
+ const options = this.options.fileUpload;
+ if (!options)
+ return;
+ if (!options.enabled)
+ return;
+ options.maxSize = options.maxSize || 10 * 1024 * 1024;
+ options.mimeTypes = options.mimeTypes || [];
+ options.batch = options.batch || false;
+ if (!options.onInsertFile || typeof options.onInsertFile !== "function") {
+ console.warn("OverType: fileUpload.onInsertFile callback is required for file uploads.");
+ return;
+ }
+ this._boundHandleFilePaste = this._handleFilePaste.bind(this);
+ this._boundHandleFileDrop = this._handleFileDrop.bind(this);
+ this._boundHandleDragOver = this._handleDragOver.bind(this);
+ this.textarea.addEventListener("paste", this._boundHandleFilePaste);
+ this.textarea.addEventListener("drop", this._boundHandleFileDrop);
+ this.textarea.addEventListener("dragover", this._boundHandleDragOver);
+ this.fileUploadInitialized = true;
+ }
+ _handleFilePaste(e) {
+ var _a, _b;
+ if (!((_b = (_a = e == null ? void 0 : e.clipboardData) == null ? void 0 : _a.files) == null ? void 0 : _b.length))
+ return;
+ e.preventDefault();
+ this._handleDataTransfer(e.clipboardData);
+ }
+ _handleFileDrop(e) {
+ var _a, _b;
+ if (!((_b = (_a = e == null ? void 0 : e.dataTransfer) == null ? void 0 : _a.files) == null ? void 0 : _b.length))
+ return;
+ e.preventDefault();
+ this._handleDataTransfer(e.dataTransfer);
+ }
+ _handleDataTransfer(dataTransfer) {
+ var _a;
+ const files = [];
+ for (const file of dataTransfer.files) {
+ if (file.size > this.options.fileUpload.maxSize) {
+ continue;
+ }
+ if (((_a = this.options.fileUpload.mimeTypes) == null ? void 0 : _a.length) > 0 && !this.options.fileUpload.mimeTypes.includes(file.type)) {
+ continue;
+ }
+ const prefix = this._isImageFile(file.type) ? "!" : "";
+ const placeholder = `${prefix}[Uploading ${file.name}...]()`;
+ this.insertAtCursor(`${placeholder}
+`);
+ if (this.options.fileUpload.batch) {
+ files.push({ file, placeholder });
+ continue;
+ }
+ this.options.fileUpload.onInsertFile(file).then((text) => {
+ this.textarea.value = this.textarea.value.replace(placeholder, text);
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }, (error) => {
+ console.error("OverType: File upload failed", error);
+ this.textarea.value = this.textarea.value.replace(placeholder, "[Upload failed]()");
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ if (this.options.fileUpload.batch && files.length > 0) {
+ this.options.fileUpload.onInsertFile(files.map((f) => f.file)).then((texts) => {
+ texts.forEach((text, index) => {
+ this.textarea.value = this.textarea.value.replace(files[index].placeholder, text);
+ });
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }, (error) => {
+ console.error("OverType: File upload failed", error);
+ files.forEach(({ placeholder }) => {
+ this.textarea.value = this.textarea.value.replace(placeholder, "[Upload failed]()");
+ });
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ }
+ _isImageFile(type) {
+ return type.startsWith("image/");
+ }
+ _handleDragOver(e) {
+ e.preventDefault();
+ }
+ _destroyFileUpload() {
+ this.textarea.removeEventListener("paste", this._boundHandleFilePaste || this._handleFilePaste);
+ this.textarea.removeEventListener("dragover", this._boundHandleDragOver || this._handleDragOver);
+ this.textarea.removeEventListener("drop", this._boundHandleFileDrop || this._handleFileDrop);
+ this._boundHandleFilePaste = null;
+ this._boundHandleFileDrop = null;
+ this._boundHandleDragOver = null;
+ this.fileUploadInitialized = false;
+ }
+ insertAtCursor(text) {
+ const start = this.textarea.selectionStart;
+ const end = this.textarea.selectionEnd;
+ if (!document.execCommand("insertText", false, text)) {
+ const before = this.textarea.value.slice(0, start);
+ const after = this.textarea.value.slice(end);
+ this.textarea.value = before + text + after;
+ this.textarea.setSelectionRange(start + text.length, start + text.length);
+ }
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }
/**
* Update preview with parsed markdown
*/
@@ -4067,6 +4175,12 @@ ${blockSuffix}` : suffix;
this.toolbar = null;
this._createToolbar();
}
+ if (this.fileUploadInitialized) {
+ this._destroyFileUpload();
+ }
+ if (this.options.fileUpload) {
+ this._initFileUpload();
+ }
this._applyOptions();
this.updatePreview();
}
diff --git a/dist/overtype-webcomponent.min.js b/dist/overtype-webcomponent.min.js
index f7b24ef..47bf29d 100644
--- a/dist/overtype-webcomponent.min.js
+++ b/dist/overtype-webcomponent.min.js
@@ -1,19 +1,19 @@
/**
- * OverType v2.1.0
+ * OverType v2.2.0
* A lightweight markdown editor library with perfect WYSIWYG alignment
* @license MIT
* @author David Miranda
* https://github.com/panphora/overtype
*/
-var OverTypeEditor=(()=>{var j=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ue=(n,e,t)=>e in n?j(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var De=(n,e)=>{for(var t in e)j(n,t,{get:e[t],enumerable:!0})},qe=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Re(e))!Ve.call(n,o)&&o!==t&&j(n,o,{get:()=>e[o],enumerable:!(i=Fe(e,o))||i.enumerable});return n};var We=n=>qe(j({},"__esModule",{value:!0}),n);var E=(n,e,t)=>(Ue(n,typeof e!="symbol"?e+"":e,t),t);var ct={};De(ct,{default:()=>lt});var L=class{static resetLinkIndex(){this.linkIndex=0}static setCodeHighlighter(e){this.codeHighlighter=e}static setCustomSyntax(e){this.customSyntax=e}static applyCustomSyntax(e){return this.customSyntax?this.customSyntax(e):e}static escapeHtml(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,i=>t[i])}static preserveIndentation(e,t){let o=t.match(/^(\s*)/)[1].replace(/ /g," ");return e.replace(/^\s*/,o)}static parseHeader(e){return e.replace(/^(#{1,3})\s(.+)$/,(t,i,o)=>{let r=i.length;return`${i} ${o} `})}static parseHorizontalRule(e){return e.match(/^(-{3,}|\*{3,}|_{3,})$/)?`
${e}
`:null}static parseBlockquote(e){return e.replace(/^> (.+)$/,(t,i)=>`> ${i} `)}static parseBulletList(e){return e.replace(/^((?: )*)([-*+])\s(.+)$/,(t,i,o,r)=>`${i}${o} ${r} `)}static parseTaskList(e,t=!1){return e.replace(/^((?: )*)-\s+\[([ xX])\]\s+(.+)$/,(i,o,r,s)=>{if(t){let a=r.toLowerCase()==="x";return`${o} ${s} `}else return`${o}- [${r}] ${s} `})}static parseNumberedList(e){return e.replace(/^((?: )*)(\d+\.)\s(.+)$/,(t,i,o,r)=>`${i}${o} ${r} `)}static parseCodeBlock(e){return/^`{3}[^`]*$/.test(e)?`${e}
`:null}static parseBold(e){return e=e.replace(/\*\*(.+?)\*\*/g,'** $1** '),e=e.replace(/__(.+?)__/g,'__ $1__ '),e}static parseItalic(e){return e=e.replace(new RegExp("(?])\\*(?!\\*)(.+?)(?* $1* '),e=e.replace(new RegExp("(?<=^|\\s)_(?!_)(.+?)(?_ $1_ '),e}static parseStrikethrough(e){return e=e.replace(new RegExp("(?~~ $1~~ '),e=e.replace(new RegExp("(?~ $1~ '),e}static parseInlineCode(e){return e.replace(new RegExp("(?$1 $2$3 ')}static sanitizeUrl(e){let t=e.trim(),i=t.toLowerCase(),r=["http://","https://","mailto:","ftp://","ftps://"].some(a=>i.startsWith(a)),s=t.startsWith("/")||t.startsWith("#")||t.startsWith("?")||t.startsWith(".")||!t.includes(":")&&!t.includes("//");return r||s?e:"#"}static parseLinks(e){return e.replace(/\[(.+?)\]\((.+?)\)/g,(t,i,o)=>{let r=`--link-${this.linkIndex++}`;return`[ ${i}](${o}) `})}static identifyAndProtectSanctuaries(e){let t=new Map,i=0,o=e,r=[],s=/\[([^\]]+)\]\(([^)]+)\)/g,a;for(;(a=s.exec(e))!==null;){let h=a.index+a[0].indexOf("](")+2,u=h+a[2].length;r.push({start:h,end:u})}let c=new RegExp("(?p>=f.start&&h<=f.end)||l.push({match:d[0],index:d.index,openTicks:d[1],content:d[2],closeTicks:d[3]})}return l.sort((p,h)=>h.index-p.index),l.forEach(p=>{let h=`\uE000${i++}\uE001`;t.set(h,{type:"code",original:p.match,openTicks:p.openTicks,content:p.content,closeTicks:p.closeTicks}),o=o.substring(0,p.index)+h+o.substring(p.index+p.match.length)}),o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(p,h,u)=>{let f=`\uE000${i++}\uE001`;return t.set(f,{type:"link",original:p,linkText:h,url:u}),f}),{protectedText:o,sanctuaries:t}}static restoreAndTransformSanctuaries(e,t){return Array.from(t.keys()).sort((o,r)=>{let s=e.indexOf(o),a=e.indexOf(r);return s-a}).forEach(o=>{let r=t.get(o),s;if(r.type==="code")s=`${r.openTicks} ${r.content}${r.closeTicks} `;else if(r.type==="link"){let a=r.linkText;t.forEach((l,p)=>{if(a.includes(p)&&l.type==="code"){let h=`${l.openTicks} ${l.content}${l.closeTicks} `;a=a.replace(p,h)}}),a=this.parseStrikethrough(a),a=this.parseBold(a),a=this.parseItalic(a);let c=`--link-${this.linkIndex++}`;s=`[ ${a}](${r.url}) `}e=e.replace(o,s)}),e}static parseInlineElements(e){let{protectedText:t,sanctuaries:i}=this.identifyAndProtectSanctuaries(e),o=t;return o=this.parseStrikethrough(o),o=this.parseBold(o),o=this.parseItalic(o),o=this.restoreAndTransformSanctuaries(o,i),o}static parseLine(e,t=!1){let i=this.escapeHtml(e);i=this.preserveIndentation(i,e);let o=this.parseHorizontalRule(i);if(o)return o;let r=this.parseCodeBlock(i);return r||(i=this.parseHeader(i),i=this.parseBlockquote(i),i=this.parseTaskList(i,t),i=this.parseBulletList(i),i=this.parseNumberedList(i),i=this.parseInlineElements(i),i.trim()===""?"
":`${i}
`)}static parse(e,t=-1,i=!1,o,r=!1){this.resetLinkIndex();let s=e.split(`
+var OverTypeEditor=(()=>{var N=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var Ve=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var De=(n,e)=>{for(var t in e)N(n,t,{get:e[t],enumerable:!0})},qe=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Re(e))!Ue.call(n,o)&&o!==t&&N(n,o,{get:()=>e[o],enumerable:!(i=je(e,o))||i.enumerable});return n};var We=n=>qe(N({},"__esModule",{value:!0}),n);var _=(n,e,t)=>(Ve(n,typeof e!="symbol"?e+"":e,t),t);var ct={};De(ct,{default:()=>lt});var L=class{static resetLinkIndex(){this.linkIndex=0}static setCodeHighlighter(e){this.codeHighlighter=e}static setCustomSyntax(e){this.customSyntax=e}static applyCustomSyntax(e){return this.customSyntax?this.customSyntax(e):e}static escapeHtml(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,i=>t[i])}static preserveIndentation(e,t){let o=t.match(/^(\s*)/)[1].replace(/ /g," ");return e.replace(/^\s*/,o)}static parseHeader(e){return e.replace(/^(#{1,3})\s(.+)$/,(t,i,o)=>{let r=i.length;return`${i} ${o} `})}static parseHorizontalRule(e){return e.match(/^(-{3,}|\*{3,}|_{3,})$/)?`${e}
`:null}static parseBlockquote(e){return e.replace(/^> (.+)$/,(t,i)=>`> ${i} `)}static parseBulletList(e){return e.replace(/^((?: )*)([-*+])\s(.+)$/,(t,i,o,r)=>`${i}${o} ${r} `)}static parseTaskList(e,t=!1){return e.replace(/^((?: )*)-\s+\[([ xX])\]\s+(.+)$/,(i,o,r,s)=>{if(t){let a=r.toLowerCase()==="x";return`${o} ${s} `}else return`${o}- [${r}] ${s} `})}static parseNumberedList(e){return e.replace(/^((?: )*)(\d+\.)\s(.+)$/,(t,i,o,r)=>`${i}${o} ${r} `)}static parseCodeBlock(e){return/^`{3}[^`]*$/.test(e)?`${e}
`:null}static parseBold(e){return e=e.replace(/\*\*(.+?)\*\*/g,'** $1** '),e=e.replace(/__(.+?)__/g,'__ $1__ '),e}static parseItalic(e){return e=e.replace(new RegExp("(?])\\*(?!\\*)(.+?)(?* $1* '),e=e.replace(new RegExp("(?<=^|\\s)_(?!_)(.+?)(?_ $1_ '),e}static parseStrikethrough(e){return e=e.replace(new RegExp("(?~~ $1~~ '),e=e.replace(new RegExp("(?~ $1~ '),e}static parseInlineCode(e){return e.replace(new RegExp("(?$1 $2$3 ')}static sanitizeUrl(e){let t=e.trim(),i=t.toLowerCase(),r=["http://","https://","mailto:","ftp://","ftps://"].some(a=>i.startsWith(a)),s=t.startsWith("/")||t.startsWith("#")||t.startsWith("?")||t.startsWith(".")||!t.includes(":")&&!t.includes("//");return r||s?e:"#"}static parseLinks(e){return e.replace(/\[(.+?)\]\((.+?)\)/g,(t,i,o)=>{let r=`--link-${this.linkIndex++}`;return`[ ${i}](${o}) `})}static identifyAndProtectSanctuaries(e){let t=new Map,i=0,o=e,r=[],s=/\[([^\]]+)\]\(([^)]+)\)/g,a;for(;(a=s.exec(e))!==null;){let h=a.index+a[0].indexOf("](")+2,u=h+a[2].length;r.push({start:h,end:u})}let c=new RegExp("(?p>=f.start&&h<=f.end)||l.push({match:d[0],index:d.index,openTicks:d[1],content:d[2],closeTicks:d[3]})}return l.sort((p,h)=>h.index-p.index),l.forEach(p=>{let h=`\uE000${i++}\uE001`;t.set(h,{type:"code",original:p.match,openTicks:p.openTicks,content:p.content,closeTicks:p.closeTicks}),o=o.substring(0,p.index)+h+o.substring(p.index+p.match.length)}),o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(p,h,u)=>{let f=`\uE000${i++}\uE001`;return t.set(f,{type:"link",original:p,linkText:h,url:u}),f}),{protectedText:o,sanctuaries:t}}static restoreAndTransformSanctuaries(e,t){return Array.from(t.keys()).sort((o,r)=>{let s=e.indexOf(o),a=e.indexOf(r);return s-a}).forEach(o=>{let r=t.get(o),s;if(r.type==="code")s=`${r.openTicks} ${r.content}${r.closeTicks} `;else if(r.type==="link"){let a=r.linkText;t.forEach((l,p)=>{if(a.includes(p)&&l.type==="code"){let h=`${l.openTicks} ${l.content}${l.closeTicks} `;a=a.replace(p,h)}}),a=this.parseStrikethrough(a),a=this.parseBold(a),a=this.parseItalic(a);let c=`--link-${this.linkIndex++}`;s=`[ ${a}](${r.url}) `}e=e.replace(o,s)}),e}static parseInlineElements(e){let{protectedText:t,sanctuaries:i}=this.identifyAndProtectSanctuaries(e),o=t;return o=this.parseStrikethrough(o),o=this.parseBold(o),o=this.parseItalic(o),o=this.restoreAndTransformSanctuaries(o,i),o}static parseLine(e,t=!1){let i=this.escapeHtml(e);i=this.preserveIndentation(i,e);let o=this.parseHorizontalRule(i);if(o)return o;let r=this.parseCodeBlock(i);return r||(i=this.parseHeader(i),i=this.parseBlockquote(i),i=this.parseTaskList(i,t),i=this.parseBulletList(i),i=this.parseNumberedList(i),i=this.parseInlineElements(i),i.trim()===""?"
":`${i}
`)}static parse(e,t=-1,i=!1,o,r=!1){this.resetLinkIndex();let s=e.split(`
`),a=!1,d=s.map((l,p)=>{if(i&&p===t)return`${this.escapeHtml(l)||" "}
`;if(/^```[^`]*$/.test(l))return a=!a,this.applyCustomSyntax(this.parseLine(l,r));if(a){let u=this.escapeHtml(l);return`${this.preserveIndentation(u,l)||" "}
`}return this.applyCustomSyntax(this.parseLine(l,r))}).join("");return this.postProcessHTML(d,o)}static postProcessHTML(e,t){if(typeof document>"u"||!document)return this.postProcessHTMLManual(e,t);let i=document.createElement("div");i.innerHTML=e;let o=null,r=null,s=null,a=!1,c=Array.from(i.children);for(let d=0;d0&&(s._codeContent+=`
`);let f=l.textContent.replace(/\u00A0/g," ");s._codeContent+=f,u.textContent.length>0&&(u.textContent+=`
`),u.textContent+=f,l.remove();continue}let h=null;if(l.tagName==="DIV"&&(h=l.querySelector("li")),h){let u=h.classList.contains("bullet-list"),f=h.classList.contains("ordered-list");if(!u&&!f){o=null,r=null;continue}let m=u?"ul":"ol";(!o||r!==m)&&(o=document.createElement(m),i.insertBefore(o,l),r=m);let g=[];for(let v of l.childNodes)if(v.nodeType===3&&v.textContent.match(/^\u00A0+$/))g.push(v.cloneNode(!0));else if(v===h)break;g.forEach(v=>{h.insertBefore(v,h.firstChild)}),o.appendChild(h),l.remove()}else o=null,r=null}return i.innerHTML}static postProcessHTMLManual(e,t){let i=e;i=i.replace(/((?:(?: )*
.*?<\/li><\/div>\s*)+)/gs,r=>{let s=r.match(/(?: )*
.*?<\/li><\/div>/gs)||[];return s.length>0?""+s.map(c=>{let d=c.match(/((?: )*)
.*?<\/li>/);if(d&&l){let p=d[1];return l[0].replace(/ /,` ${p}`)}return l?l[0]:""}).filter(Boolean).join("")+"":r}),i=i.replace(/((?:(?: )*
.*?<\/li><\/div>\s*)+)/gs,r=>{let s=r.match(/(?: )*
.*?<\/li><\/div>/gs)||[];return s.length>0?""+s.map(c=>{let d=c.match(/((?: )*)
.*?<\/li>/);if(d&&l){let p=d[1];return l[0].replace(/ /,` ${p}`)}return l?l[0]:""}).filter(Boolean).join("")+"":r});let o=/(```[^<]*)<\/span><\/div>(.*?)(```)<\/span><\/div>/gs;return i=i.replace(o,(r,s,a,c)=>{let l=(a.match(/(.*?)<\/div>/gs)||[]).map(g=>g.replace(/
(.*?)<\/div>/s,"$1").replace(/ /g," ")).join(`
`),p=s.slice(3).trim(),h=p?` class="language-${p}"`:"",u=l,f=t||this.codeHighlighter;if(f)try{let g=l.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),v=f(g,p);v&&typeof v.then=="function"?console.warn("Async highlighters are not supported in Node.js (non-DOM) context. Use synchronous highlighters for server-side rendering."):v&&typeof v=="string"&&v.trim()&&(u=v)}catch(g){console.warn("Code highlighting failed:",g)}let m=`
${s}
`;return m+=`
${u}`,m+=`
${c}
`,m}),i}static getListContext(e,t){let i=e.split(`
`),o=0,r=0,s=0;for(let h=0;h
=t){r=h,s=o;break}o+=u+1}let a=i[r],c=s+a.length,d=a.match(this.LIST_PATTERNS.checkbox);if(d)return{inList:!0,listType:"checkbox",indent:d[1],marker:"-",checked:d[2]==="x",content:d[3],lineStart:s,lineEnd:c,markerEndPos:s+d[1].length+d[2].length+5};let l=a.match(this.LIST_PATTERNS.bullet);if(l)return{inList:!0,listType:"bullet",indent:l[1],marker:l[2],content:l[3],lineStart:s,lineEnd:c,markerEndPos:s+l[1].length+l[2].length+1};let p=a.match(this.LIST_PATTERNS.numbered);return p?{inList:!0,listType:"numbered",indent:p[1],marker:parseInt(p[2]),content:p[3],lineStart:s,lineEnd:c,markerEndPos:s+p[1].length+p[2].length+2}:{inList:!1,listType:null,indent:"",marker:null,content:a,lineStart:s,lineEnd:c,markerEndPos:s}}static createNewListItem(e){switch(e.listType){case"bullet":return`${e.indent}${e.marker} `;case"numbered":return`${e.indent}${e.marker+1}. `;case"checkbox":return`${e.indent}- [ ] `;default:return""}}static renumberLists(e){let t=e.split(`
`),i=new Map,o=!1;return t.map(s=>{let a=s.match(this.LIST_PATTERNS.numbered);if(a){let c=a[1],d=c.length,l=a[3];o||i.clear();let p=(i.get(d)||0)+1;i.set(d,p);for(let[h]of i)h>d&&i.delete(h);return o=!0,`${c}${p}. ${l}`}else return(s.trim()===""||!s.match(/^\s/))&&(o=!1,i.clear()),s}).join(`
-`)}};E(L,"linkIndex",0),E(L,"codeHighlighter",null),E(L,"customSyntax",null),E(L,"LIST_PATTERNS",{bullet:/^(\s*)([-*+])\s+(.*)$/,numbered:/^(\s*)(\d+)\.\s+(.*)$/,checkbox:/^(\s*)-\s+\[([ x])\]\s+(.*)$/});var z=class{constructor(e){this.editor=e}handleKeydown(e){if(!(navigator.platform.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey))return!1;let o=null;switch(e.key.toLowerCase()){case"b":e.shiftKey||(o="toggleBold");break;case"i":e.shiftKey||(o="toggleItalic");break;case"k":e.shiftKey||(o="insertLink");break;case"7":e.shiftKey&&(o="toggleNumberedList");break;case"8":e.shiftKey&&(o="toggleBulletList");break}return o?(e.preventDefault(),this.editor.performAction(o,e),!0):!1}destroy(){}};var M={name:"solar",colors:{bgPrimary:"#faf0ca",bgSecondary:"#ffffff",text:"#0d3b66",textPrimary:"#0d3b66",textSecondary:"#5a7a9b",h1:"#f95738",h2:"#ee964b",h3:"#3d8a51",strong:"#ee964b",em:"#f95738",del:"#ee964b",link:"#0d3b66",code:"#0d3b66",codeBg:"rgba(244, 211, 94, 0.4)",blockquote:"#5a7a9b",hr:"#5a7a9b",syntaxMarker:"rgba(13, 59, 102, 0.52)",syntax:"#999999",cursor:"#f95738",selection:"rgba(244, 211, 94, 0.4)",listMarker:"#ee964b",rawLine:"#5a7a9b",border:"#e0e0e0",hoverBg:"#f0f0f0",primary:"#0d3b66",toolbarBg:"#ffffff",toolbarIcon:"#0d3b66",toolbarHover:"#f5f5f5",toolbarActive:"#faf0ca"}},Y={name:"cave",colors:{bgPrimary:"#141E26",bgSecondary:"#1D2D3E",text:"#c5dde8",textPrimary:"#c5dde8",textSecondary:"#9fcfec",h1:"#d4a5ff",h2:"#f6ae2d",h3:"#9fcfec",strong:"#f6ae2d",em:"#9fcfec",del:"#f6ae2d",link:"#9fcfec",code:"#c5dde8",codeBg:"#1a232b",blockquote:"#9fcfec",hr:"#c5dde8",syntaxMarker:"rgba(159, 207, 236, 0.73)",syntax:"#7a8c98",cursor:"#f26419",selection:"rgba(51, 101, 138, 0.4)",listMarker:"#f6ae2d",rawLine:"#9fcfec",border:"#2a3f52",hoverBg:"#243546",primary:"#9fcfec",toolbarBg:"#1D2D3E",toolbarIcon:"#c5dde8",toolbarHover:"#243546",toolbarActive:"#2a3f52"}},ee={solar:M,cave:Y,light:M,dark:Y};function T(n){return typeof n=="string"?{...ee[n]||ee.solar,name:n}:n}function B(n){let e=[];for(let[t,i]of Object.entries(n)){let o=t.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`--${o}: ${i};`)}return e.join(`
-`)}function te(n,e={}){return{...n,colors:{...n.colors,...e}}}function F(n={}){let{fontSize:e="14px",lineHeight:t=1.6,fontFamily:i='"SF Mono", SFMono-Regular, Menlo, Monaco, "Cascadia Code", Consolas, "Roboto Mono", "Noto Sans Mono", "Droid Sans Mono", "Ubuntu Mono", "DejaVu Sans Mono", "Liberation Mono", "Courier New", Courier, monospace',padding:o="20px",theme:r=null,mobile:s={}}=n,a=Object.keys(s).length>0?`
+`)}};_(L,"linkIndex",0),_(L,"codeHighlighter",null),_(L,"customSyntax",null),_(L,"LIST_PATTERNS",{bullet:/^(\s*)([-*+])\s+(.*)$/,numbered:/^(\s*)(\d+)\.\s+(.*)$/,checkbox:/^(\s*)-\s+\[([ x])\]\s+(.*)$/});var z=class{constructor(e){this.editor=e}handleKeydown(e){if(!(navigator.platform.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey))return!1;let o=null;switch(e.key.toLowerCase()){case"b":e.shiftKey||(o="toggleBold");break;case"i":e.shiftKey||(o="toggleItalic");break;case"k":e.shiftKey||(o="insertLink");break;case"7":e.shiftKey&&(o="toggleNumberedList");break;case"8":e.shiftKey&&(o="toggleBulletList");break}return o?(e.preventDefault(),this.editor.performAction(o,e),!0):!1}destroy(){}};var $={name:"solar",colors:{bgPrimary:"#faf0ca",bgSecondary:"#ffffff",text:"#0d3b66",textPrimary:"#0d3b66",textSecondary:"#5a7a9b",h1:"#f95738",h2:"#ee964b",h3:"#3d8a51",strong:"#ee964b",em:"#f95738",del:"#ee964b",link:"#0d3b66",code:"#0d3b66",codeBg:"rgba(244, 211, 94, 0.4)",blockquote:"#5a7a9b",hr:"#5a7a9b",syntaxMarker:"rgba(13, 59, 102, 0.52)",syntax:"#999999",cursor:"#f95738",selection:"rgba(244, 211, 94, 0.4)",listMarker:"#ee964b",rawLine:"#5a7a9b",border:"#e0e0e0",hoverBg:"#f0f0f0",primary:"#0d3b66",toolbarBg:"#ffffff",toolbarIcon:"#0d3b66",toolbarHover:"#f5f5f5",toolbarActive:"#faf0ca"}},Y={name:"cave",colors:{bgPrimary:"#141E26",bgSecondary:"#1D2D3E",text:"#c5dde8",textPrimary:"#c5dde8",textSecondary:"#9fcfec",h1:"#d4a5ff",h2:"#f6ae2d",h3:"#9fcfec",strong:"#f6ae2d",em:"#9fcfec",del:"#f6ae2d",link:"#9fcfec",code:"#c5dde8",codeBg:"#1a232b",blockquote:"#9fcfec",hr:"#c5dde8",syntaxMarker:"rgba(159, 207, 236, 0.73)",syntax:"#7a8c98",cursor:"#f26419",selection:"rgba(51, 101, 138, 0.4)",listMarker:"#f6ae2d",rawLine:"#9fcfec",border:"#2a3f52",hoverBg:"#243546",primary:"#9fcfec",toolbarBg:"#1D2D3E",toolbarIcon:"#c5dde8",toolbarHover:"#243546",toolbarActive:"#2a3f52"}},ee={solar:$,cave:Y,light:$,dark:Y};function T(n){return typeof n=="string"?{...ee[n]||ee.solar,name:n}:n}function B(n){let e=[];for(let[t,i]of Object.entries(n)){let o=t.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`--${o}: ${i};`)}return e.join(`
+`)}function te(n,e={}){return{...n,colors:{...n.colors,...e}}}function j(n={}){let{fontSize:e="14px",lineHeight:t=1.6,fontFamily:i='"SF Mono", SFMono-Regular, Menlo, Monaco, "Cascadia Code", Consolas, "Roboto Mono", "Noto Sans Mono", "Droid Sans Mono", "Ubuntu Mono", "DejaVu Sans Mono", "Liberation Mono", "Courier New", Courier, monospace',padding:o="20px",theme:r=null,mobile:s={}}=n,a=Object.keys(s).length>0?`
@media (max-width: 640px) {
.overtype-wrapper .overtype-input,
.overtype-wrapper .overtype-preview {
@@ -861,28 +861,28 @@ var OverTypeEditor=(()=>{var j=Object.defineProperty;var Fe=Object.getOwnPropert
}
${a}
- `}var Ke=Object.defineProperty,ie=Object.getOwnPropertySymbols,Ze=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable,ne=(n,e,t)=>e in n?Ke(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,oe=(n,e)=>{for(var t in e||(e={}))Ze.call(e,t)&&ne(n,t,e[t]);if(ie)for(var t of ie(e))Je.call(e,t)&&ne(n,t,e[t]);return n},_={bold:{prefix:"**",suffix:"**",trimFirst:!0},italic:{prefix:"_",suffix:"_",trimFirst:!0},code:{prefix:"`",suffix:"`",blockPrefix:"```",blockSuffix:"```"},link:{prefix:"[",suffix:"](url)",replaceNext:"url",scanFor:"https?://"},bulletList:{prefix:"- ",multiline:!0,unorderedList:!0},numberedList:{prefix:"1. ",multiline:!0,orderedList:!0},quote:{prefix:"> ",multiline:!0,surroundWithNewlines:!0},taskList:{prefix:"- [ ] ",multiline:!0,surroundWithNewlines:!0},header1:{prefix:"# "},header2:{prefix:"## "},header3:{prefix:"### "},header4:{prefix:"#### "},header5:{prefix:"##### "},header6:{prefix:"###### "}};function Ge(){return{prefix:"",suffix:"",blockPrefix:"",blockSuffix:"",multiline:!1,replaceNext:"",prefixSpace:!1,scanFor:"",surroundWithNewlines:!1,orderedList:!1,unorderedList:!1,trimFirst:!1}}function H(n){return oe(oe({},Ge()),n)}var V=!1;function Qe(){return V}function y(n,e,t){V&&(console.group(`\u{1F50D} ${n}`),console.log(e),t&&console.log("Data:",t),console.groupEnd())}function R(n,e){if(!V)return;let t=n.value.slice(n.selectionStart,n.selectionEnd);console.group(`\u{1F4CD} Selection: ${e}`),console.log("Position:",`${n.selectionStart}-${n.selectionEnd}`),console.log("Selected text:",JSON.stringify(t)),console.log("Length:",t.length);let i=n.value.slice(Math.max(0,n.selectionStart-10),n.selectionStart),o=n.value.slice(n.selectionEnd,Math.min(n.value.length,n.selectionEnd+10));console.log("Context:",JSON.stringify(i)+"[SELECTION]"+JSON.stringify(o)),console.groupEnd()}function le(n){V&&(console.group("\u{1F4DD} Result"),console.log("Text to insert:",JSON.stringify(n.text)),console.log("New selection:",`${n.selectionStart}-${n.selectionEnd}`),console.groupEnd())}var A=null;function I(n,{text:e,selectionStart:t,selectionEnd:i}){let o=Qe();o&&(console.group("\u{1F527} insertText"),console.log("Current selection:",`${n.selectionStart}-${n.selectionEnd}`),console.log("Text to insert:",JSON.stringify(e)),console.log("New selection to set:",t,"-",i)),n.focus();let r=n.selectionStart,s=n.selectionEnd,a=n.value.slice(0,r),c=n.value.slice(s);o&&(console.log("Before text (last 20):",JSON.stringify(a.slice(-20))),console.log("After text (first 20):",JSON.stringify(c.slice(0,20))),console.log("Selected text being replaced:",JSON.stringify(n.value.slice(r,s))));let d=n.value,l=r!==s;if(A===null||A===!0){n.contentEditable="true";try{A=document.execCommand("insertText",!1,e),o&&console.log("execCommand returned:",A,"for text with",e.split(`
+ `}var Ke=Object.defineProperty,ie=Object.getOwnPropertySymbols,Ze=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable,ne=(n,e,t)=>e in n?Ke(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,oe=(n,e)=>{for(var t in e||(e={}))Ze.call(e,t)&&ne(n,t,e[t]);if(ie)for(var t of ie(e))Je.call(e,t)&&ne(n,t,e[t]);return n},E={bold:{prefix:"**",suffix:"**",trimFirst:!0},italic:{prefix:"_",suffix:"_",trimFirst:!0},code:{prefix:"`",suffix:"`",blockPrefix:"```",blockSuffix:"```"},link:{prefix:"[",suffix:"](url)",replaceNext:"url",scanFor:"https?://"},bulletList:{prefix:"- ",multiline:!0,unorderedList:!0},numberedList:{prefix:"1. ",multiline:!0,orderedList:!0},quote:{prefix:"> ",multiline:!0,surroundWithNewlines:!0},taskList:{prefix:"- [ ] ",multiline:!0,surroundWithNewlines:!0},header1:{prefix:"# "},header2:{prefix:"## "},header3:{prefix:"### "},header4:{prefix:"#### "},header5:{prefix:"##### "},header6:{prefix:"###### "}};function Ge(){return{prefix:"",suffix:"",blockPrefix:"",blockSuffix:"",multiline:!1,replaceNext:"",prefixSpace:!1,scanFor:"",surroundWithNewlines:!1,orderedList:!1,unorderedList:!1,trimFirst:!1}}function H(n){return oe(oe({},Ge()),n)}var U=!1;function Qe(){return U}function y(n,e,t){U&&(console.group(`\u{1F50D} ${n}`),console.log(e),t&&console.log("Data:",t),console.groupEnd())}function R(n,e){if(!U)return;let t=n.value.slice(n.selectionStart,n.selectionEnd);console.group(`\u{1F4CD} Selection: ${e}`),console.log("Position:",`${n.selectionStart}-${n.selectionEnd}`),console.log("Selected text:",JSON.stringify(t)),console.log("Length:",t.length);let i=n.value.slice(Math.max(0,n.selectionStart-10),n.selectionStart),o=n.value.slice(n.selectionEnd,Math.min(n.value.length,n.selectionEnd+10));console.log("Context:",JSON.stringify(i)+"[SELECTION]"+JSON.stringify(o)),console.groupEnd()}function le(n){U&&(console.group("\u{1F4DD} Result"),console.log("Text to insert:",JSON.stringify(n.text)),console.log("New selection:",`${n.selectionStart}-${n.selectionEnd}`),console.groupEnd())}var A=null;function M(n,{text:e,selectionStart:t,selectionEnd:i}){let o=Qe();o&&(console.group("\u{1F527} insertText"),console.log("Current selection:",`${n.selectionStart}-${n.selectionEnd}`),console.log("Text to insert:",JSON.stringify(e)),console.log("New selection to set:",t,"-",i)),n.focus();let r=n.selectionStart,s=n.selectionEnd,a=n.value.slice(0,r),c=n.value.slice(s);o&&(console.log("Before text (last 20):",JSON.stringify(a.slice(-20))),console.log("After text (first 20):",JSON.stringify(c.slice(0,20))),console.log("Selected text being replaced:",JSON.stringify(n.value.slice(r,s))));let d=n.value,l=r!==s;if(A===null||A===!0){n.contentEditable="true";try{A=document.execCommand("insertText",!1,e),o&&console.log("execCommand returned:",A,"for text with",e.split(`
`).length,"lines")}catch(p){A=!1,o&&console.log("execCommand threw error:",p)}n.contentEditable="false"}if(o&&(console.log("canInsertText before:",A),console.log("execCommand result:",A)),A){let p=a+e+c,h=n.value;o&&(console.log("Expected length:",p.length),console.log("Actual length:",h.length)),h!==p&&o&&(console.log("execCommand changed the value but not as expected"),console.log("Expected:",JSON.stringify(p.slice(0,100))),console.log("Actual:",JSON.stringify(h.slice(0,100))))}if(!A)if(o&&console.log("Using manual insertion"),n.value===d){o&&console.log("Value unchanged, doing manual replacement");try{document.execCommand("ms-beginUndoUnit")}catch(p){}n.value=a+e+c;try{document.execCommand("ms-endUndoUnit")}catch(p){}n.dispatchEvent(new CustomEvent("input",{bubbles:!0,cancelable:!0}))}else o&&console.log("Value was changed by execCommand, skipping manual insertion");o&&console.log("Setting selection range:",t,i),t!=null&&i!=null?n.setSelectionRange(t,i):n.setSelectionRange(r,n.selectionEnd),o&&(console.log("Final value length:",n.value.length),console.groupEnd())}function re(n){return n.trim().split(`
`).length>1}function Xe(n,e){let t=e;for(;n[t]&&n[t-1]!=null&&!n[t-1].match(/\s/);)t--;return t}function Ye(n,e,t){let i=e,o=t?/\n/:/\s/;for(;n[i]&&!n[i].match(o);)i++;return i}function ce(n){let e=n.value.split(`
`),t=0;for(let i=0;i=t&&n.selectionStart=t&&n.selectionEnd0&&s[a-1]!==`
+`.repeat(2-s)),{newlinesToAppend:a,newlinesToPrepend:c}}function V(n,e,t={}){let i=n.selectionStart,o=n.selectionEnd,r=i===o,s=n.value,a=i;for(;a>0&&s[a-1]!==`
`;)a--;if(r){let d=i;for(;d0?`${s}
`:o,v=re(m)&&a&&a.length>0?`
-${a}`:r;if(d){let S=n.value[n.selectionStart-1];n.selectionStart!==0&&S!=null&&!S.match(/\s/)&&(g=` ${g}`)}m=et(n,g,v,e.multiline);let b=n.selectionStart,x=n.selectionEnd,$=c&&c.length>0&&v.indexOf(c)>-1&&m.length>0;if(p){let S=Z(n);t=S.newlinesToAppend,i=S.newlinesToPrepend,g=t+o,v+=i}if(m.startsWith(g)&&m.endsWith(v)){let S=m.slice(g.length,m.length-v.length);if(u===f){let C=u-g.length;C=Math.max(C,b),C=Math.min(C,b+S.length),b=x=C}else x=b+S.length;return{text:S,selectionStart:b,selectionEnd:x}}else if($)if(l&&l.length>0&&m.match(l)){v=v.replace(c,m);let S=g+v;return b=x=b+g.length,{text:S,selectionStart:b,selectionEnd:x}}else{let S=g+m+v;return b=b+g.length+m.length+v.indexOf(c),x=b+c.length,{text:S,selectionStart:b,selectionEnd:x}}else{let S=g+m+v;b=u+g.length,x=f+g.length;let C=m.match(/^\s*|\s*$/g);if(h&&C){let Q=C[0]||"",X=C[1]||"";S=Q+g+m.trim()+v+X,b+=Q.length,x-=X.length}return{text:S,selectionStart:b,selectionEnd:x}}}function pe(n,e){let{prefix:t,suffix:i,surroundWithNewlines:o}=e,r=n.value.slice(n.selectionStart,n.selectionEnd),s=n.selectionStart,a=n.selectionEnd,c=r.split(`
+${a}`:r;if(d){let S=n.value[n.selectionStart-1];n.selectionStart!==0&&S!=null&&!S.match(/\s/)&&(g=` ${g}`)}m=et(n,g,v,e.multiline);let b=n.selectionStart,x=n.selectionEnd,I=c&&c.length>0&&v.indexOf(c)>-1&&m.length>0;if(p){let S=Z(n);t=S.newlinesToAppend,i=S.newlinesToPrepend,g=t+o,v+=i}if(m.startsWith(g)&&m.endsWith(v)){let S=m.slice(g.length,m.length-v.length);if(u===f){let C=u-g.length;C=Math.max(C,b),C=Math.min(C,b+S.length),b=x=C}else x=b+S.length;return{text:S,selectionStart:b,selectionEnd:x}}else if(I)if(l&&l.length>0&&m.match(l)){v=v.replace(c,m);let S=g+v;return b=x=b+g.length,{text:S,selectionStart:b,selectionEnd:x}}else{let S=g+m+v;return b=b+g.length+m.length+v.indexOf(c),x=b+c.length,{text:S,selectionStart:b,selectionEnd:x}}else{let S=g+m+v;b=u+g.length,x=f+g.length;let C=m.match(/^\s*|\s*$/g);if(h&&C){let Q=C[0]||"",X=C[1]||"";S=Q+g+m.trim()+v+X,b+=Q.length,x-=X.length}return{text:S,selectionStart:b,selectionEnd:x}}}function pe(n,e){let{prefix:t,suffix:i,surroundWithNewlines:o}=e,r=n.value.slice(n.selectionStart,n.selectionEnd),s=n.selectionStart,a=n.selectionEnd,c=r.split(`
`);if(c.every(l=>l.startsWith(t)&&(!i||l.endsWith(i))))r=c.map(l=>{let p=l.slice(t.length);return i&&(p=p.slice(0,p.length-i.length)),p}).join(`
`),a=s+r.length;else if(r=c.map(l=>t+l+(i||"")).join(`
`),o){let{newlinesToAppend:l,newlinesToPrepend:p}=Z(n);s+=l.length,a=s+r.length,r=l+r+p}return{text:r,selectionStart:s,selectionEnd:a}}function se(n){let e=n.split(`
`),t=/^\d+\.\s+/,i=e.every(r=>t.test(r)),o=e;return i&&(o=e.map(r=>r.replace(t,""))),{text:o.join(`
`),processed:i}}function ae(n){let e=n.split(`
`),t="- ",i=e.every(r=>r.startsWith(t)),o=e;return i&&(o=e.map(r=>r.slice(t.length))),{text:o.join(`
-`),processed:i}}function N(n,e){return e?"- ":`${n+1}. `}function tt(n,e){let t,i,o;return n.orderedList?(t=se(e),i=ae(t.text),o=i.text):(t=ae(e),i=se(t.text),o=i.text),[t,i,o]}function it(n,e){let t=n.selectionStart===n.selectionEnd,i=n.selectionStart,o=n.selectionEnd;ce(n);let r=n.value.slice(n.selectionStart,n.selectionEnd),[s,a,c]=tt(e,r),d=c.split(`
-`).map((m,g)=>`${N(g,e.unorderedList)}${m}`),l=d.reduce((m,g,v)=>m+N(v,e.unorderedList).length,0),p=d.reduce((m,g,v)=>m+N(v,!e.unorderedList).length,0);if(s.processed)return t?(i=Math.max(i-N(0,e.unorderedList).length,0),o=i):(i=n.selectionStart,o=n.selectionEnd-l),{text:c,selectionStart:i,selectionEnd:o};let{newlinesToAppend:h,newlinesToPrepend:u}=Z(n),f=h+d.join(`
-`)+u;return t?(i=Math.max(i+N(0,e.unorderedList).length+h.length,0),o=i):a.processed?(i=Math.max(n.selectionStart+h.length,0),o=n.selectionEnd+h.length+l-p):(i=Math.max(n.selectionStart+h.length,0),o=n.selectionEnd+h.length+l),{text:f,selectionStart:i,selectionEnd:o}}function de(n,e){let t=U(n,i=>it(i,e),{adjustSelection:(i,o,r,s)=>{let a=n.value.slice(s,n.selectionEnd),c=/^\d+\.\s+/,d=/^- /,l=c.test(a),p=d.test(a),h=e.orderedList&&l||e.unorderedList&&p;if(o===r)if(h){let u=a.match(e.orderedList?c:d),f=u?u[0].length:0;return{start:Math.max(o-f,s),end:Math.max(o-f,s)}}else if(l||p){let u=a.match(l?c:d),f=u?u[0].length:0,g=(e.unorderedList?2:3)-f;return{start:o+g,end:o+g}}else{let u=e.unorderedList?2:3;return{start:o+u,end:o+u}}else if(h){let u=a.match(e.orderedList?c:d),f=u?u[0].length:0;return{start:Math.max(o-f,s),end:Math.max(r-f,s)}}else if(l||p){let u=a.match(l?c:d),f=u?u[0].length:0,g=(e.unorderedList?2:3)-f;return{start:o+g,end:r+g}}else{let u=e.unorderedList?2:3;return{start:o+u,end:r+u}}}});I(n,t)}function nt(n){if(!n)return[];let e=[],{selectionStart:t,selectionEnd:i,value:o}=n,r=o.split(`
-`),s=0,a="";for(let p of r){if(t>=s&&t<=s+p.length){a=p;break}s+=p.length+1}a.startsWith("- ")&&(a.startsWith("- [ ] ")||a.startsWith("- [x] ")?e.push("task-list"):e.push("bullet-list")),/^\d+\.\s/.test(a)&&e.push("numbered-list"),a.startsWith("> ")&&e.push("quote"),a.startsWith("# ")&&e.push("header"),a.startsWith("## ")&&e.push("header-2"),a.startsWith("### ")&&e.push("header-3");let c=Math.max(0,t-10),d=Math.min(o.length,i+10),l=o.slice(c,d);if(l.includes("**")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100)),u=p.lastIndexOf("**"),f=h.indexOf("**");u!==-1&&f!==-1&&e.push("bold")}if(l.includes("_")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100)),u=p.lastIndexOf("_"),f=h.indexOf("_");u!==-1&&f!==-1&&e.push("italic")}if(l.includes("`")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100));p.includes("`")&&h.includes("`")&&e.push("code")}if(l.includes("[")&&l.includes("]")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100)),u=p.lastIndexOf("["),f=h.indexOf("]");u!==-1&&f!==-1&&o.slice(i+f+1,i+f+10).startsWith("(")&&e.push("link")}return e}function he(n){if(!n||n.disabled||n.readOnly)return;y("toggleBold","Starting"),R(n,"Before");let e=H(_.bold),t=D(n,e);le(t),I(n,t),R(n,"After")}function ue(n){if(!n||n.disabled||n.readOnly)return;let e=H(_.italic),t=D(n,e);I(n,t)}function me(n){if(!n||n.disabled||n.readOnly)return;let e=H(_.code),t=D(n,e);I(n,t)}function fe(n,e={}){if(!n||n.disabled||n.readOnly)return;let t=n.value.slice(n.selectionStart,n.selectionEnd),i=H(_.link);if(t&&t.match(/^https?:\/\//)&&!e.url?(i.suffix=`](${t})`,i.replaceNext=""):e.url&&(i.suffix=`](${e.url})`,i.replaceNext=""),e.text&&!t){let s=n.selectionStart;n.value=n.value.slice(0,s)+e.text+n.value.slice(s),n.selectionStart=s,n.selectionEnd=s+e.text.length}let r=D(n,i);I(n,r)}function ge(n){if(!n||n.disabled||n.readOnly)return;let e=H(_.bulletList);de(n,e)}function ve(n){if(!n||n.disabled||n.readOnly)return;let e=H(_.numberedList);de(n,e)}function ye(n){if(!n||n.disabled||n.readOnly)return;y("toggleQuote","Starting"),R(n,"Initial");let e=H(_.quote),t=U(n,i=>pe(i,e),{prefix:e.prefix});le(t),I(n,t),R(n,"Final")}function J(n){if(!n||n.disabled||n.readOnly)return;let e=H(_.taskList),t=U(n,i=>pe(i,e),{prefix:e.prefix});I(n,t)}function G(n,e=1,t=!1){if(!n||n.disabled||n.readOnly)return;(e<1||e>6)&&(e=1),y("insertHeader","============ START ============"),y("insertHeader",`Level: ${e}, Toggle: ${t}`),y("insertHeader",`Initial cursor: ${n.selectionStart}-${n.selectionEnd}`);let i=`header${e===1?"1":e}`,o=H(_[i]||_.header1);y("insertHeader",`Style prefix: "${o.prefix}"`);let r=n.value,s=n.selectionStart,a=n.selectionEnd,c=s;for(;c>0&&r[c-1]!==`
+`),processed:i}}function F(n,e){return e?"- ":`${n+1}. `}function tt(n,e){let t,i,o;return n.orderedList?(t=se(e),i=ae(t.text),o=i.text):(t=ae(e),i=se(t.text),o=i.text),[t,i,o]}function it(n,e){let t=n.selectionStart===n.selectionEnd,i=n.selectionStart,o=n.selectionEnd;ce(n);let r=n.value.slice(n.selectionStart,n.selectionEnd),[s,a,c]=tt(e,r),d=c.split(`
+`).map((m,g)=>`${F(g,e.unorderedList)}${m}`),l=d.reduce((m,g,v)=>m+F(v,e.unorderedList).length,0),p=d.reduce((m,g,v)=>m+F(v,!e.unorderedList).length,0);if(s.processed)return t?(i=Math.max(i-F(0,e.unorderedList).length,0),o=i):(i=n.selectionStart,o=n.selectionEnd-l),{text:c,selectionStart:i,selectionEnd:o};let{newlinesToAppend:h,newlinesToPrepend:u}=Z(n),f=h+d.join(`
+`)+u;return t?(i=Math.max(i+F(0,e.unorderedList).length+h.length,0),o=i):a.processed?(i=Math.max(n.selectionStart+h.length,0),o=n.selectionEnd+h.length+l-p):(i=Math.max(n.selectionStart+h.length,0),o=n.selectionEnd+h.length+l),{text:f,selectionStart:i,selectionEnd:o}}function de(n,e){let t=V(n,i=>it(i,e),{adjustSelection:(i,o,r,s)=>{let a=n.value.slice(s,n.selectionEnd),c=/^\d+\.\s+/,d=/^- /,l=c.test(a),p=d.test(a),h=e.orderedList&&l||e.unorderedList&&p;if(o===r)if(h){let u=a.match(e.orderedList?c:d),f=u?u[0].length:0;return{start:Math.max(o-f,s),end:Math.max(o-f,s)}}else if(l||p){let u=a.match(l?c:d),f=u?u[0].length:0,g=(e.unorderedList?2:3)-f;return{start:o+g,end:o+g}}else{let u=e.unorderedList?2:3;return{start:o+u,end:o+u}}else if(h){let u=a.match(e.orderedList?c:d),f=u?u[0].length:0;return{start:Math.max(o-f,s),end:Math.max(r-f,s)}}else if(l||p){let u=a.match(l?c:d),f=u?u[0].length:0,g=(e.unorderedList?2:3)-f;return{start:o+g,end:r+g}}else{let u=e.unorderedList?2:3;return{start:o+u,end:r+u}}}});M(n,t)}function nt(n){if(!n)return[];let e=[],{selectionStart:t,selectionEnd:i,value:o}=n,r=o.split(`
+`),s=0,a="";for(let p of r){if(t>=s&&t<=s+p.length){a=p;break}s+=p.length+1}a.startsWith("- ")&&(a.startsWith("- [ ] ")||a.startsWith("- [x] ")?e.push("task-list"):e.push("bullet-list")),/^\d+\.\s/.test(a)&&e.push("numbered-list"),a.startsWith("> ")&&e.push("quote"),a.startsWith("# ")&&e.push("header"),a.startsWith("## ")&&e.push("header-2"),a.startsWith("### ")&&e.push("header-3");let c=Math.max(0,t-10),d=Math.min(o.length,i+10),l=o.slice(c,d);if(l.includes("**")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100)),u=p.lastIndexOf("**"),f=h.indexOf("**");u!==-1&&f!==-1&&e.push("bold")}if(l.includes("_")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100)),u=p.lastIndexOf("_"),f=h.indexOf("_");u!==-1&&f!==-1&&e.push("italic")}if(l.includes("`")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100));p.includes("`")&&h.includes("`")&&e.push("code")}if(l.includes("[")&&l.includes("]")){let p=o.slice(Math.max(0,t-100),t),h=o.slice(i,Math.min(o.length,i+100)),u=p.lastIndexOf("["),f=h.indexOf("]");u!==-1&&f!==-1&&o.slice(i+f+1,i+f+10).startsWith("(")&&e.push("link")}return e}function he(n){if(!n||n.disabled||n.readOnly)return;y("toggleBold","Starting"),R(n,"Before");let e=H(E.bold),t=D(n,e);le(t),M(n,t),R(n,"After")}function ue(n){if(!n||n.disabled||n.readOnly)return;let e=H(E.italic),t=D(n,e);M(n,t)}function me(n){if(!n||n.disabled||n.readOnly)return;let e=H(E.code),t=D(n,e);M(n,t)}function fe(n,e={}){if(!n||n.disabled||n.readOnly)return;let t=n.value.slice(n.selectionStart,n.selectionEnd),i=H(E.link);if(t&&t.match(/^https?:\/\//)&&!e.url?(i.suffix=`](${t})`,i.replaceNext=""):e.url&&(i.suffix=`](${e.url})`,i.replaceNext=""),e.text&&!t){let s=n.selectionStart;n.value=n.value.slice(0,s)+e.text+n.value.slice(s),n.selectionStart=s,n.selectionEnd=s+e.text.length}let r=D(n,i);M(n,r)}function ge(n){if(!n||n.disabled||n.readOnly)return;let e=H(E.bulletList);de(n,e)}function ve(n){if(!n||n.disabled||n.readOnly)return;let e=H(E.numberedList);de(n,e)}function ye(n){if(!n||n.disabled||n.readOnly)return;y("toggleQuote","Starting"),R(n,"Initial");let e=H(E.quote),t=V(n,i=>pe(i,e),{prefix:e.prefix});le(t),M(n,t),R(n,"Final")}function J(n){if(!n||n.disabled||n.readOnly)return;let e=H(E.taskList),t=V(n,i=>pe(i,e),{prefix:e.prefix});M(n,t)}function G(n,e=1,t=!1){if(!n||n.disabled||n.readOnly)return;(e<1||e>6)&&(e=1),y("insertHeader","============ START ============"),y("insertHeader",`Level: ${e}, Toggle: ${t}`),y("insertHeader",`Initial cursor: ${n.selectionStart}-${n.selectionEnd}`);let i=`header${e===1?"1":e}`,o=H(E[i]||E.header1);y("insertHeader",`Style prefix: "${o.prefix}"`);let r=n.value,s=n.selectionStart,a=n.selectionEnd,c=s;for(;c>0&&r[c-1]!==`
`;)c--;let d=a;for(;d{let v=g.value.slice(g.selectionStart,g.selectionEnd);y("insertHeader",`Line in operation: "${v}"`);let b=v.replace(/^#{1,6}\s*/,"");y("insertHeader",`Cleaned line: "${b}"`);let x;return f?(y("insertHeader","ACTION: Toggling OFF - removing header"),x=b):h>0?(y("insertHeader",`ACTION: Replacing H${h} with H${e}`),x=o.prefix+b):(y("insertHeader","ACTION: Adding new header"),x=o.prefix+b),y("insertHeader",`New line: "${x}"`),{text:x,selectionStart:g.selectionStart,selectionEnd:g.selectionEnd}},{prefix:o.prefix,adjustSelection:(g,v,b,x)=>{if(y("insertHeader","Adjusting selection:"),y("insertHeader",` - isRemoving param: ${g}`),y("insertHeader",` - shouldToggleOff: ${f}`),y("insertHeader",` - selStart: ${v}, selEnd: ${b}`),y("insertHeader",` - lineStartPos: ${x}`),f){let $=Math.max(v-u,x);return y("insertHeader",` - Removing header, adjusting by -${u}`),{start:$,end:v===b?$:Math.max(b-u,x)}}else if(u>0){let $=o.prefix.length-u;return y("insertHeader",` - Replacing header, adjusting by ${$}`),{start:v+$,end:b+$}}else return y("insertHeader",` - Adding header, adjusting by +${o.prefix.length}`),{start:v+o.prefix.length,end:b+o.prefix.length}}});y("insertHeader",`Final result: text="${m.text}", cursor=${m.selectionStart}-${m.selectionEnd}`),y("insertHeader","============ END ============"),I(n,m)}function be(n){G(n,1,!0)}function we(n){G(n,2,!0)}function xe(n){G(n,3,!0)}function ke(n){return nt(n)}var q=class{constructor(e,t={}){this.editor=e,this.container=null,this.buttons={},this.toolbarButtons=t.toolbarButtons||[]}create(){this.container=document.createElement("div"),this.container.className="overtype-toolbar",this.container.setAttribute("role","toolbar"),this.container.setAttribute("aria-label","Formatting toolbar"),this.toolbarButtons.forEach(e=>{if(e.name==="separator"){let t=this.createSeparator();this.container.appendChild(t)}else{let t=this.createButton(e);this.buttons[e.name]=t,this.container.appendChild(t)}}),this.editor.container.insertBefore(this.container,this.editor.wrapper)}createSeparator(){let e=document.createElement("div");return e.className="overtype-toolbar-separator",e.setAttribute("role","separator"),e}createButton(e){let t=document.createElement("button");return t.className="overtype-toolbar-button",t.type="button",t.setAttribute("data-button",e.name),t.title=e.title||"",t.setAttribute("aria-label",e.title||e.name),t.innerHTML=this.sanitizeSVG(e.icon||""),e.name==="viewMode"?(t.classList.add("has-dropdown"),t.dataset.dropdown="true",t.addEventListener("click",i=>{i.preventDefault(),this.toggleViewModeDropdown(t)}),t):(t._clickHandler=i=>{i.preventDefault();let o=e.actionId||e.name;this.editor.performAction(o,i)},t.addEventListener("click",t._clickHandler),t)}async handleAction(e){if(e&&typeof e=="object"&&typeof e.action=="function"){this.editor.textarea.focus();try{return await e.action({editor:this.editor,getValue:()=>this.editor.getValue(),setValue:t=>this.editor.setValue(t),event:null}),!0}catch(t){return console.error(`Action "${e.name}" error:`,t),this.editor.wrapper.dispatchEvent(new CustomEvent("button-error",{detail:{buttonName:e.name,error:t}})),!1}}return typeof e=="string"?this.editor.performAction(e,null):!1}sanitizeSVG(e){return typeof e!="string"?"":e.replace(/