overtype 1.2.0 → 1.2.2
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.
- package/README.md +23 -3
- package/dist/overtype.cjs +851 -977
- package/dist/overtype.cjs.map +4 -4
- package/dist/overtype.esm.js +53 -30
- package/dist/overtype.esm.js.map +2 -2
- package/dist/overtype.js +53 -30
- package/dist/overtype.js.map +2 -2
- package/dist/overtype.min.js +45 -39
- package/package.json +5 -2
- package/src/overtype.js +33 -28
- package/src/parser.js +48 -19
- package/src/styles.js +6 -0
package/dist/overtype.min.js
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* OverType v1.2.
|
|
2
|
+
* OverType v1.2.2
|
|
3
3
|
* A lightweight markdown editor library with perfect WYSIWYG alignment
|
|
4
4
|
* @license MIT
|
|
5
5
|
* @author Demo User
|
|
6
6
|
* https://github.com/demo/overtype
|
|
7
7
|
*/
|
|
8
|
-
var OverType=(()=>{var N=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var ze=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Ne=(n,e)=>{for(var t in e)N(n,t,{get:e[t],enumerable:!0})},je=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Pe(e))!Oe.call(n,i)&&i!==t&&N(n,i,{get:()=>e[i],enumerable:!(o=Ie(e,i))||o.enumerable});return n};var Fe=n=>je(N({},"__esModule",{value:!0}),n);var B=(n,e,t)=>(ze(n,typeof e!="symbol"?e+"":e,t),t);var Ye={};Ne(Ye,{OverType:()=>S,default:()=>Xe});var
|
|
9
|
-
`).map((
|
|
10
|
-
`);let h=d.
|
|
11
|
-
`)
|
|
12
|
-
`).length,"lines")}catch(c){E=!1,i&&console.log("execCommand threw error:",c)}n.contentEditable="false"}if(i&&(console.log("canInsertText before:",E),console.log("execCommand result:",E)),E){let c=
|
|
8
|
+
var OverType=(()=>{var N=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var ze=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Ne=(n,e)=>{for(var t in e)N(n,t,{get:e[t],enumerable:!0})},je=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Pe(e))!Oe.call(n,i)&&i!==t&&N(n,i,{get:()=>e[i],enumerable:!(o=Ie(e,i))||o.enumerable});return n};var Fe=n=>je(N({},"__esModule",{value:!0}),n);var B=(n,e,t)=>(ze(n,typeof e!="symbol"?e+"":e,t),t);var Ye={};Ne(Ye,{OverType:()=>S,default:()=>Xe});var H=class{static resetLinkIndex(){this.linkIndex=0}static escapeHtml(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,o=>t[o])}static preserveIndentation(e,t){let i=t.match(/^(\s*)/)[1].replace(/ /g," ");return e.replace(/^\s*/,i)}static parseHeader(e){return e.replace(/^(#{1,3})\s(.+)$/,(t,o,i)=>{let r=o.length;return`<h${r}><span class="syntax-marker">${o} </span>${i}</h${r}>`})}static parseHorizontalRule(e){return e.match(/^(-{3,}|\*{3,}|_{3,})$/)?`<div><span class="hr-marker">${e}</span></div>`:null}static parseBlockquote(e){return e.replace(/^> (.+)$/,(t,o)=>`<span class="blockquote"><span class="syntax-marker">></span> ${o}</span>`)}static parseBulletList(e){return e.replace(/^((?: )*)([-*])\s(.+)$/,(t,o,i,r)=>`${o}<li class="bullet-list"><span class="syntax-marker">${i} </span>${r}</li>`)}static parseNumberedList(e){return e.replace(/^((?: )*)(\d+\.)\s(.+)$/,(t,o,i,r)=>`${o}<li class="ordered-list"><span class="syntax-marker">${i} </span>${r}</li>`)}static parseCodeBlock(e){return/^`{3}[^`]*$/.test(e)?`<div><span class="code-fence">${e}</span></div>`:null}static parseBold(e){return e=e.replace(/\*\*(.+?)\*\*/g,'<strong><span class="syntax-marker">**</span>$1<span class="syntax-marker">**</span></strong>'),e=e.replace(/__(.+?)__/g,'<strong><span class="syntax-marker">__</span>$1<span class="syntax-marker">__</span></strong>'),e}static parseItalic(e){return e=e.replace(new RegExp("(?<!\\*)\\*(?!\\*)(.+?)(?<!\\*)\\*(?!\\*)","g"),'<em><span class="syntax-marker">*</span>$1<span class="syntax-marker">*</span></em>'),e=e.replace(new RegExp("(?<!_)_(?!_)(.+?)(?<!_)_(?!_)","g"),'<em><span class="syntax-marker">_</span>$1<span class="syntax-marker">_</span></em>'),e}static parseInlineCode(e){return e.replace(new RegExp("(?<!`)(`+)(?!`)((?:(?!\\1).)+?)(\\1)(?!`)","g"),'<code><span class="syntax-marker">$1</span>$2<span class="syntax-marker">$3</span></code>')}static sanitizeUrl(e){let t=e.trim(),o=t.toLowerCase(),r=["http://","https://","mailto:","ftp://","ftps://"].some(l=>o.startsWith(l)),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,o,i)=>{let r=`--link-${this.linkIndex++}`;return`<a href="${this.sanitizeUrl(i)}" style="anchor-name: ${r}"><span class="syntax-marker">[</span>${o}<span class="syntax-marker url-part">](${i})</span></a>`})}static parseInlineElements(e){let t=e;t=this.parseInlineCode(t);let o=new Map;return t=t.replace(/(<code>.*?<\/code>)/g,i=>{let r=`\uE000${o.size}\uE001`;return o.set(r,i),r}),t=this.parseLinks(t),t=t.replace(/(<a[^>]*>.*?<\/a>)/g,i=>{let r=`\uE000${o.size}\uE001`;return o.set(r,i),r}),t=this.parseBold(t),t=this.parseItalic(t),o.forEach((i,r)=>{t=t.replace(r,i)}),t}static parseLine(e){let t=this.escapeHtml(e);t=this.preserveIndentation(t,e);let o=this.parseHorizontalRule(t);if(o)return o;let i=this.parseCodeBlock(t);return i||(t=this.parseHeader(t),t=this.parseBlockquote(t),t=this.parseBulletList(t),t=this.parseNumberedList(t),t=this.parseInlineElements(t),t.trim()===""?"<div> </div>":`<div>${t}</div>`)}static parse(e,t=-1,o=!1){this.resetLinkIndex();let i=e.split(`
|
|
9
|
+
`),r=!1,l=i.map((a,d)=>{if(o&&d===t)return`<div class="raw-line">${this.escapeHtml(a)||" "}</div>`;if(/^```[^`]*$/.test(a))return r=!r,this.parseLine(a);if(r){let c=this.escapeHtml(a);return`<div>${this.preserveIndentation(c,a)||" "}</div>`}return this.parseLine(a)}).join("");return this.postProcessHTML(l)}static postProcessHTML(e){if(typeof document>"u"||!document)return this.postProcessHTMLManual(e);let t=document.createElement("div");t.innerHTML=e;let o=null,i=null,r=null,s=!1,l=Array.from(t.children);for(let a=0;a<l.length;a++){let d=l[a];if(!d.parentNode)continue;let p=d.querySelector(".code-fence");if(p){let u=p.textContent;if(u.startsWith("```"))if(s){s=!1,r=null;continue}else{s=!0,r=document.createElement("pre");let h=document.createElement("code");r.appendChild(h),r.className="code-block";let m=u.slice(3).trim();m&&(h.className=`language-${m}`),t.insertBefore(r,d.nextSibling),r._codeElement=h;continue}}if(s&&r&&d.tagName==="DIV"&&!d.querySelector(".code-fence")){let u=r._codeElement||r.querySelector("code");u.textContent.length>0&&(u.textContent+=`
|
|
10
|
+
`);let h=d.textContent.replace(/\u00A0/g," ");u.textContent+=h,d.remove();continue}let c=null;if(d.tagName==="DIV"&&(c=d.querySelector("li")),c){let u=c.classList.contains("bullet-list"),h=c.classList.contains("ordered-list");if(!u&&!h){o=null,i=null;continue}let m=u?"ul":"ol";(!o||i!==m)&&(o=document.createElement(m),t.insertBefore(o,d),i=m),o.appendChild(c),d.remove()}else o=null,i=null}return t.innerHTML}static postProcessHTMLManual(e){let t=e;t=t.replace(/((?:<div>(?: )*<li class="bullet-list">.*?<\/li><\/div>\s*)+)/gs,i=>{let r=i.match(/<li class="bullet-list">.*?<\/li>/gs)||[];return r.length>0?"<ul>"+r.join("")+"</ul>":i}),t=t.replace(/((?:<div>(?: )*<li class="ordered-list">.*?<\/li><\/div>\s*)+)/gs,i=>{let r=i.match(/<li class="ordered-list">.*?<\/li>/gs)||[];return r.length>0?"<ol>"+r.join("")+"</ol>":i});let o=/<div><span class="code-fence">(```[^<]*)<\/span><\/div>(.*?)<div><span class="code-fence">(```)<\/span><\/div>/gs;return t=t.replace(o,(i,r,s,l)=>{let d=(s.match(/<div>(.*?)<\/div>/gs)||[]).map(h=>h.replace(/<div>(.*?)<\/div>/s,"$1").replace(/ /g," ")).join(`
|
|
11
|
+
`),p=r.slice(3).trim(),c=p?` class="language-${p}"`:"",u=`<div><span class="code-fence">${r}</span></div>`;return u+=`<pre class="code-block"><code${c}>${d}</code></pre>`,u+=`<div><span class="code-fence">${l}</span></div>`,u}),t}};B(H,"linkIndex",0);var _e=Object.defineProperty,Y=Object.getOwnPropertySymbols,Re=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable,ee=(n,e,t)=>e in n?_e(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,te=(n,e)=>{for(var t in e||(e={}))Re.call(e,t)&&ee(n,t,e[t]);if(Y)for(var t of Y(e))Ve.call(e,t)&&ee(n,t,e[t]);return n},L={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 De(){return{prefix:"",suffix:"",blockPrefix:"",blockSuffix:"",multiline:!1,replaceNext:"",prefixSpace:!1,scanFor:"",surroundWithNewlines:!1,orderedList:!1,unorderedList:!1,trimFirst:!1}}function T(n){return te(te({},De()),n)}var F=!1;function qe(){return F}function v(n,e,t){F&&(console.group(`\u{1F50D} ${n}`),console.log(e),t&&console.log("Data:",t),console.groupEnd())}function j(n,e){if(!F)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 o=n.value.slice(Math.max(0,n.selectionStart-10),n.selectionStart),i=n.value.slice(n.selectionEnd,Math.min(n.value.length,n.selectionEnd+10));console.log("Context:",JSON.stringify(o)+"[SELECTION]"+JSON.stringify(i)),console.groupEnd()}function re(n){F&&(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 E=null;function M(n,{text:e,selectionStart:t,selectionEnd:o}){let i=qe();i&&(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,"-",o)),n.focus();let r=n.selectionStart,s=n.selectionEnd,l=n.value.slice(0,r),a=n.value.slice(s);i&&(console.log("Before text (last 20):",JSON.stringify(l.slice(-20))),console.log("After text (first 20):",JSON.stringify(a.slice(0,20))),console.log("Selected text being replaced:",JSON.stringify(n.value.slice(r,s))));let d=n.value,p=r!==s;if(E===null||E===!0){n.contentEditable="true";try{E=document.execCommand("insertText",!1,e),i&&console.log("execCommand returned:",E,"for text with",e.split(`
|
|
12
|
+
`).length,"lines")}catch(c){E=!1,i&&console.log("execCommand threw error:",c)}n.contentEditable="false"}if(i&&(console.log("canInsertText before:",E),console.log("execCommand result:",E)),E){let c=l+e+a,u=n.value;i&&(console.log("Expected length:",c.length),console.log("Actual length:",u.length)),u!==c&&i&&(console.log("execCommand changed the value but not as expected"),console.log("Expected:",JSON.stringify(c.slice(0,100))),console.log("Actual:",JSON.stringify(u.slice(0,100))))}if(!E)if(i&&console.log("Using manual insertion"),n.value===d){i&&console.log("Value unchanged, doing manual replacement");try{document.execCommand("ms-beginUndoUnit")}catch(c){}n.value=l+e+a;try{document.execCommand("ms-endUndoUnit")}catch(c){}n.dispatchEvent(new CustomEvent("input",{bubbles:!0,cancelable:!0}))}else i&&console.log("Value was changed by execCommand, skipping manual insertion");i&&console.log("Setting selection range:",t,o),t!=null&&o!=null?n.setSelectionRange(t,o):n.setSelectionRange(r,n.selectionEnd),i&&(console.log("Final value length:",n.value.length),console.groupEnd())}function ne(n){return n.trim().split(`
|
|
13
13
|
`).length>1}function We(n,e){let t=e;for(;n[t]&&n[t-1]!=null&&!n[t-1].match(/\s/);)t--;return t}function Ue(n,e,t){let o=e,i=t?/\n/:/\s/;for(;n[o]&&!n[o].match(i);)o++;return o}function se(n){let e=n.value.split(`
|
|
14
|
-
`),t=0;for(let o=0;o<e.length;o++){let i=e[o].length+1;n.selectionStart>=t&&n.selectionStart<t+i&&(n.selectionStart=t),n.selectionEnd>=t&&n.selectionEnd<t+i&&(o===e.length-1?n.selectionEnd=Math.min(t+e[o].length,n.value.length):n.selectionEnd=t+i-1),t+=i}}function Ke(n,e,t,o=!1){if(n.selectionStart===n.selectionEnd)n.selectionStart=We(n.value,n.selectionStart),n.selectionEnd=Ue(n.value,n.selectionEnd,o);else{let i=n.selectionStart-e.length,r=n.selectionEnd+t.length,
|
|
15
|
-
`.repeat(2-r)),t.match(/\S/)&&
|
|
16
|
-
`.repeat(2-
|
|
17
|
-
`;)
|
|
18
|
-
`;)d++;n.selectionStart=
|
|
19
|
-
`:i,w=ne(g)&&
|
|
20
|
-
${
|
|
21
|
-
`);if(
|
|
22
|
-
`),s
|
|
23
|
-
`),i){let{newlinesToAppend:p,newlinesToPrepend:c}=J(n);
|
|
14
|
+
`),t=0;for(let o=0;o<e.length;o++){let i=e[o].length+1;n.selectionStart>=t&&n.selectionStart<t+i&&(n.selectionStart=t),n.selectionEnd>=t&&n.selectionEnd<t+i&&(o===e.length-1?n.selectionEnd=Math.min(t+e[o].length,n.value.length):n.selectionEnd=t+i-1),t+=i}}function Ke(n,e,t,o=!1){if(n.selectionStart===n.selectionEnd)n.selectionStart=We(n.value,n.selectionStart),n.selectionEnd=Ue(n.value,n.selectionEnd,o);else{let i=n.selectionStart-e.length,r=n.selectionEnd+t.length,s=n.value.slice(i,n.selectionStart)===e,l=n.value.slice(n.selectionEnd,r)===t;s&&l&&(n.selectionStart=i,n.selectionEnd=r)}return n.value.slice(n.selectionStart,n.selectionEnd)}function J(n){let e=n.value.slice(0,n.selectionStart),t=n.value.slice(n.selectionEnd),o=e.match(/\n*$/),i=t.match(/^\n*/),r=o?o[0].length:0,s=i?i[0].length:0,l="",a="";return e.match(/\S/)&&r<2&&(l=`
|
|
15
|
+
`.repeat(2-r)),t.match(/\S/)&&s<2&&(a=`
|
|
16
|
+
`.repeat(2-s)),{newlinesToAppend:l,newlinesToPrepend:a}}function _(n,e,t={}){let o=n.selectionStart,i=n.selectionEnd,r=o===i,s=n.value,l=o;for(;l>0&&s[l-1]!==`
|
|
17
|
+
`;)l--;if(r){let d=o;for(;d<s.length&&s[d]!==`
|
|
18
|
+
`;)d++;n.selectionStart=l,n.selectionEnd=d}else se(n);let a=e(n);if(t.adjustSelection){let p=n.value.slice(n.selectionStart,n.selectionEnd).startsWith(t.prefix),c=t.adjustSelection(p,o,i,l);a.selectionStart=c.start,a.selectionEnd=c.end}else if(t.prefix){let p=n.value.slice(n.selectionStart,n.selectionEnd).startsWith(t.prefix);r?p?(a.selectionStart=Math.max(o-t.prefix.length,l),a.selectionEnd=a.selectionStart):(a.selectionStart=o+t.prefix.length,a.selectionEnd=a.selectionStart):p?(a.selectionStart=Math.max(o-t.prefix.length,l),a.selectionEnd=Math.max(i-t.prefix.length,l)):(a.selectionStart=o+t.prefix.length,a.selectionEnd=i+t.prefix.length)}return a}function R(n,e){let t,o,{prefix:i,suffix:r,blockPrefix:s,blockSuffix:l,replaceNext:a,prefixSpace:d,scanFor:p,surroundWithNewlines:c,trimFirst:u}=e,h=n.selectionStart,m=n.selectionEnd,g=n.value.slice(n.selectionStart,n.selectionEnd),f=ne(g)&&s&&s.length>0?`${s}
|
|
19
|
+
`:i,w=ne(g)&&l&&l.length>0?`
|
|
20
|
+
${l}`:r;if(d){let x=n.value[n.selectionStart-1];n.selectionStart!==0&&x!=null&&!x.match(/\s/)&&(f=` ${f}`)}g=Ke(n,f,w,e.multiline);let y=n.selectionStart,k=n.selectionEnd,A=a&&a.length>0&&w.indexOf(a)>-1&&g.length>0;if(c){let x=J(n);t=x.newlinesToAppend,o=x.newlinesToPrepend,f=t+i,w+=o}if(g.startsWith(f)&&g.endsWith(w)){let x=g.slice(f.length,g.length-w.length);if(h===m){let C=h-f.length;C=Math.max(C,y),C=Math.min(C,y+x.length),y=k=C}else k=y+x.length;return{text:x,selectionStart:y,selectionEnd:k}}else if(A)if(p&&p.length>0&&g.match(p)){w=w.replace(a,g);let x=f+w;return y=k=y+f.length,{text:x,selectionStart:y,selectionEnd:k}}else{let x=f+g+w;return y=y+f.length+g.length+w.indexOf(a),k=y+a.length,{text:x,selectionStart:y,selectionEnd:k}}else{let x=f+g+w;y=h+f.length,k=m+f.length;let C=g.match(/^\s*|\s*$/g);if(u&&C){let G=C[0]||"",X=C[1]||"";x=G+f+g.trim()+w+X,y+=G.length,k-=X.length}return{text:x,selectionStart:y,selectionEnd:k}}}function ae(n,e){let{prefix:t,suffix:o,surroundWithNewlines:i}=e,r=n.value.slice(n.selectionStart,n.selectionEnd),s=n.selectionStart,l=n.selectionEnd,a=r.split(`
|
|
21
|
+
`);if(a.every(p=>p.startsWith(t)&&(!o||p.endsWith(o))))r=a.map(p=>{let c=p.slice(t.length);return o&&(c=c.slice(0,c.length-o.length)),c}).join(`
|
|
22
|
+
`),l=s+r.length;else if(r=a.map(p=>t+p+(o||"")).join(`
|
|
23
|
+
`),i){let{newlinesToAppend:p,newlinesToPrepend:c}=J(n);s+=p.length,l=s+r.length,r=p+r+c}return{text:r,selectionStart:s,selectionEnd:l}}function oe(n){let e=n.split(`
|
|
24
24
|
`),t=/^\d+\.\s+/,o=e.every(r=>t.test(r)),i=e;return o&&(i=e.map(r=>r.replace(t,""))),{text:i.join(`
|
|
25
25
|
`),processed:o}}function ie(n){let e=n.split(`
|
|
26
26
|
`),t="- ",o=e.every(r=>r.startsWith(t)),i=e;return o&&(i=e.map(r=>r.slice(t.length))),{text:i.join(`
|
|
27
|
-
`),processed:o}}function P(n,e){return e?"- ":`${n+1}. `}function Ze(n,e){let t,o,i;return n.orderedList?(t=oe(e),o=ie(t.text),i=o.text):(t=ie(e),o=oe(t.text),i=o.text),[t,o,i]}function Je(n,e){let t=n.selectionStart===n.selectionEnd,o=n.selectionStart,i=n.selectionEnd;se(n);let r=n.value.slice(n.selectionStart,n.selectionEnd),[
|
|
28
|
-
`).map((g,f)=>`${P(f,e.unorderedList)}${g}`),p=d.reduce((g,f,w)=>g+P(w,e.unorderedList).length,0),c=d.reduce((g,f,w)=>g+P(w,!e.unorderedList).length,0);if(
|
|
29
|
-
`)+h;return t?(o=Math.max(o+P(0,e.unorderedList).length+u.length,0),i=o):
|
|
30
|
-
`),
|
|
31
|
-
`;)
|
|
32
|
-
`;)d++;let p=r.slice(
|
|
33
|
-
`)}function we(n,e={}){return{...n,colors:{...n.colors,...e}}}function be(n={}){let{fontSize:e="14px",lineHeight:t=1.6,fontFamily:o='"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:i="20px",theme:r=null,mobile:
|
|
27
|
+
`),processed:o}}function P(n,e){return e?"- ":`${n+1}. `}function Ze(n,e){let t,o,i;return n.orderedList?(t=oe(e),o=ie(t.text),i=o.text):(t=ie(e),o=oe(t.text),i=o.text),[t,o,i]}function Je(n,e){let t=n.selectionStart===n.selectionEnd,o=n.selectionStart,i=n.selectionEnd;se(n);let r=n.value.slice(n.selectionStart,n.selectionEnd),[s,l,a]=Ze(e,r),d=a.split(`
|
|
28
|
+
`).map((g,f)=>`${P(f,e.unorderedList)}${g}`),p=d.reduce((g,f,w)=>g+P(w,e.unorderedList).length,0),c=d.reduce((g,f,w)=>g+P(w,!e.unorderedList).length,0);if(s.processed)return t?(o=Math.max(o-P(0,e.unorderedList).length,0),i=o):(o=n.selectionStart,i=n.selectionEnd-p),{text:a,selectionStart:o,selectionEnd:i};let{newlinesToAppend:u,newlinesToPrepend:h}=J(n),m=u+d.join(`
|
|
29
|
+
`)+h;return t?(o=Math.max(o+P(0,e.unorderedList).length+u.length,0),i=o):l.processed?(o=Math.max(n.selectionStart+u.length,0),i=n.selectionEnd+u.length+p-c):(o=Math.max(n.selectionStart+u.length,0),i=n.selectionEnd+u.length+p),{text:m,selectionStart:o,selectionEnd:i}}function le(n,e){let t=_(n,o=>Je(o,e),{adjustSelection:(o,i,r,s)=>{let l=n.value.slice(s,n.selectionEnd),a=/^\d+\.\s+/,d=/^- /,p=a.test(l),c=d.test(l),u=e.orderedList&&p||e.unorderedList&&c;if(i===r)if(u){let h=l.match(e.orderedList?a:d),m=h?h[0].length:0;return{start:Math.max(i-m,s),end:Math.max(i-m,s)}}else if(p||c){let h=l.match(p?a:d),m=h?h[0].length:0,f=(e.unorderedList?2:3)-m;return{start:i+f,end:i+f}}else{let h=e.unorderedList?2:3;return{start:i+h,end:i+h}}else if(u){let h=l.match(e.orderedList?a:d),m=h?h[0].length:0;return{start:Math.max(i-m,s),end:Math.max(r-m,s)}}else if(p||c){let h=l.match(p?a:d),m=h?h[0].length:0,f=(e.unorderedList?2:3)-m;return{start:i+f,end:r+f}}else{let h=e.unorderedList?2:3;return{start:i+h,end:r+h}}}});M(n,t)}function Qe(n){if(!n)return[];let e=[],{selectionStart:t,selectionEnd:o,value:i}=n,r=i.split(`
|
|
30
|
+
`),s=0,l="";for(let c of r){if(t>=s&&t<=s+c.length){l=c;break}s+=c.length+1}l.startsWith("- ")&&(l.startsWith("- [ ] ")||l.startsWith("- [x] ")?e.push("task-list"):e.push("bullet-list")),/^\d+\.\s/.test(l)&&e.push("numbered-list"),l.startsWith("> ")&&e.push("quote"),l.startsWith("# ")&&e.push("header"),l.startsWith("## ")&&e.push("header-2"),l.startsWith("### ")&&e.push("header-3");let a=Math.max(0,t-10),d=Math.min(i.length,o+10),p=i.slice(a,d);if(p.includes("**")){let c=i.slice(Math.max(0,t-100),t),u=i.slice(o,Math.min(i.length,o+100)),h=c.lastIndexOf("**"),m=u.indexOf("**");h!==-1&&m!==-1&&e.push("bold")}if(p.includes("_")){let c=i.slice(Math.max(0,t-100),t),u=i.slice(o,Math.min(i.length,o+100)),h=c.lastIndexOf("_"),m=u.indexOf("_");h!==-1&&m!==-1&&e.push("italic")}if(p.includes("`")){let c=i.slice(Math.max(0,t-100),t),u=i.slice(o,Math.min(i.length,o+100));c.includes("`")&&u.includes("`")&&e.push("code")}if(p.includes("[")&&p.includes("]")){let c=i.slice(Math.max(0,t-100),t),u=i.slice(o,Math.min(i.length,o+100)),h=c.lastIndexOf("["),m=u.indexOf("]");h!==-1&&m!==-1&&i.slice(o+m+1,o+m+10).startsWith("(")&&e.push("link")}return e}function V(n){if(!n||n.disabled||n.readOnly)return;v("toggleBold","Starting"),j(n,"Before");let e=T(L.bold),t=R(n,e);re(t),M(n,t),j(n,"After")}function D(n){if(!n||n.disabled||n.readOnly)return;let e=T(L.italic),t=R(n,e);M(n,t)}function ce(n){if(!n||n.disabled||n.readOnly)return;let e=T(L.code),t=R(n,e);M(n,t)}function q(n,e={}){if(!n||n.disabled||n.readOnly)return;let t=n.value.slice(n.selectionStart,n.selectionEnd),o=T(L.link);if(t&&t.match(/^https?:\/\//)&&!e.url?(o.suffix=`](${t})`,o.replaceNext=""):e.url&&(o.suffix=`](${e.url})`,o.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=R(n,o);M(n,r)}function W(n){if(!n||n.disabled||n.readOnly)return;let e=T(L.bulletList);le(n,e)}function U(n){if(!n||n.disabled||n.readOnly)return;let e=T(L.numberedList);le(n,e)}function pe(n){if(!n||n.disabled||n.readOnly)return;v("toggleQuote","Starting"),j(n,"Initial");let e=T(L.quote),t=_(n,o=>ae(o,e),{prefix:e.prefix});re(t),M(n,t),j(n,"Final")}function de(n){if(!n||n.disabled||n.readOnly)return;let e=T(L.taskList),t=_(n,o=>ae(o,e),{prefix:e.prefix});M(n,t)}function Q(n,e=1,t=!1){if(!n||n.disabled||n.readOnly)return;(e<1||e>6)&&(e=1),v("insertHeader","============ START ============"),v("insertHeader",`Level: ${e}, Toggle: ${t}`),v("insertHeader",`Initial cursor: ${n.selectionStart}-${n.selectionEnd}`);let o=`header${e===1?"1":e}`,i=T(L[o]||L.header1);v("insertHeader",`Style prefix: "${i.prefix}"`);let r=n.value,s=n.selectionStart,l=n.selectionEnd,a=s;for(;a>0&&r[a-1]!==`
|
|
31
|
+
`;)a--;let d=l;for(;d<r.length&&r[d]!==`
|
|
32
|
+
`;)d++;let p=r.slice(a,d);v("insertHeader",`Current line (before): "${p}"`);let c=p.match(/^(#{1,6})\s*/),u=c?c[1].length:0,h=c?c[0].length:0;v("insertHeader","Existing header check:"),v("insertHeader",` - Match: ${c?`"${c[0]}"`:"none"}`),v("insertHeader",` - Existing level: ${u}`),v("insertHeader",` - Existing prefix length: ${h}`),v("insertHeader",` - Target level: ${e}`);let m=t&&u===e;v("insertHeader",`Should toggle OFF: ${m} (toggle=${t}, existingLevel=${u}, level=${e})`);let g=_(n,f=>{let w=f.value.slice(f.selectionStart,f.selectionEnd);v("insertHeader",`Line in operation: "${w}"`);let y=w.replace(/^#{1,6}\s*/,"");v("insertHeader",`Cleaned line: "${y}"`);let k;return m?(v("insertHeader","ACTION: Toggling OFF - removing header"),k=y):u>0?(v("insertHeader",`ACTION: Replacing H${u} with H${e}`),k=i.prefix+y):(v("insertHeader","ACTION: Adding new header"),k=i.prefix+y),v("insertHeader",`New line: "${k}"`),{text:k,selectionStart:f.selectionStart,selectionEnd:f.selectionEnd}},{prefix:i.prefix,adjustSelection:(f,w,y,k)=>{if(v("insertHeader","Adjusting selection:"),v("insertHeader",` - isRemoving param: ${f}`),v("insertHeader",` - shouldToggleOff: ${m}`),v("insertHeader",` - selStart: ${w}, selEnd: ${y}`),v("insertHeader",` - lineStartPos: ${k}`),m){let A=Math.max(w-h,k);return v("insertHeader",` - Removing header, adjusting by -${h}`),{start:A,end:w===y?A:Math.max(y-h,k)}}else if(h>0){let A=i.prefix.length-h;return v("insertHeader",` - Replacing header, adjusting by ${A}`),{start:w+A,end:y+A}}else return v("insertHeader",` - Adding header, adjusting by +${i.prefix.length}`),{start:w+i.prefix.length,end:y+i.prefix.length}}});v("insertHeader",`Final result: text="${g.text}", cursor=${g.selectionStart}-${g.selectionEnd}`),v("insertHeader","============ END ============"),M(n,g)}function he(n){Q(n,1,!0)}function ue(n){Q(n,2,!0)}function me(n){Q(n,3,!0)}function fe(n){return Qe(n)}var O=class{constructor(e){this.editor=e,this.textarea=e.textarea}handleKeydown(e){if(!(navigator.platform.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey))return!1;let i=null;switch(e.key.toLowerCase()){case"b":e.shiftKey||(i="toggleBold");break;case"i":e.shiftKey||(i="toggleItalic");break;case"k":e.shiftKey||(i="insertLink");break;case"7":e.shiftKey&&(i="toggleNumberedList");break;case"8":e.shiftKey&&(i="toggleBulletList");break}return i?(e.preventDefault(),this.editor.toolbar?this.editor.toolbar.handleAction(i):this.handleAction(i),!0):!1}async handleAction(e){let t=this.textarea;if(t){t.focus();try{switch(e){case"toggleBold":V(t);break;case"toggleItalic":D(t);break;case"insertLink":q(t);break;case"toggleBulletList":W(t);break;case"toggleNumberedList":U(t);break}t.dispatchEvent(new Event("input",{bubbles:!0}))}catch(o){console.error("Error in markdown action:",o)}}}destroy(){}};var $={name:"solar",colors:{bgPrimary:"#faf0ca",bgSecondary:"#ffffff",text:"#0d3b66",h1:"#f95738",h2:"#ee964b",h3:"#3d8a51",strong:"#ee964b",em:"#f95738",link:"#0d3b66",code:"#0d3b66",codeBg:"rgba(244, 211, 94, 0.4)",blockquote:"#5a7a9b",hr:"#5a7a9b",syntaxMarker:"rgba(13, 59, 102, 0.52)",cursor:"#f95738",selection:"rgba(244, 211, 94, 0.4)",listMarker:"#ee964b",toolbarBg:"#ffffff",toolbarBorder:"rgba(13, 59, 102, 0.15)",toolbarIcon:"#0d3b66",toolbarHover:"#f5f5f5",toolbarActive:"#faf0ca"}},ve={name:"cave",colors:{bgPrimary:"#141E26",bgSecondary:"#1D2D3E",text:"#c5dde8",h1:"#d4a5ff",h2:"#f6ae2d",h3:"#9fcfec",strong:"#f6ae2d",em:"#9fcfec",link:"#9fcfec",code:"#c5dde8",codeBg:"#1a232b",blockquote:"#9fcfec",hr:"#c5dde8",syntaxMarker:"rgba(159, 207, 236, 0.73)",cursor:"#f26419",selection:"rgba(51, 101, 138, 0.4)",listMarker:"#f6ae2d",toolbarBg:"#1D2D3E",toolbarBorder:"rgba(197, 221, 232, 0.1)",toolbarIcon:"#c5dde8",toolbarHover:"#243546",toolbarActive:"#2a3f52"}},ye={solar:$,cave:ve,light:$,dark:ve};function I(n){return typeof n=="string"?{...ye[n]||ye.solar,name:n}:n}function z(n){let e=[];for(let[t,o]of Object.entries(n)){let i=t.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`--${i}: ${o};`)}return e.join(`
|
|
33
|
+
`)}function we(n,e={}){return{...n,colors:{...n.colors,...e}}}function be(n={}){let{fontSize:e="14px",lineHeight:t=1.6,fontFamily:o='"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:i="20px",theme:r=null,mobile:s={}}=n,l=Object.keys(s).length>0?`
|
|
34
34
|
@media (max-width: 640px) {
|
|
35
35
|
.overtype-wrapper .overtype-input,
|
|
36
36
|
.overtype-wrapper .overtype-preview {
|
|
37
|
-
${Object.entries(
|
|
37
|
+
${Object.entries(s).map(([d,p])=>`${d.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${p} !important;`).join(`
|
|
38
38
|
`)}
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
`:"",
|
|
41
|
+
`:"",a=r&&r.colors?z(r.colors):"";return`
|
|
42
42
|
/* OverType Editor Styles */
|
|
43
43
|
|
|
44
44
|
/* Middle-ground CSS Reset - Prevent parent styles from leaking in */
|
|
@@ -78,9 +78,15 @@ ${s}`:r;if(d){let x=n.value[n.selectionStart-1];n.selectionStart!==0&&x!=null&&!
|
|
|
78
78
|
position: relative !important; /* Override reset - needed for absolute children */
|
|
79
79
|
overflow: visible !important; /* Allow dropdown to overflow container */
|
|
80
80
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
|
|
81
|
-
|
|
81
|
+
text-align: left !important;
|
|
82
|
+
${a?`
|
|
82
83
|
/* Theme Variables */
|
|
83
|
-
${
|
|
84
|
+
${a}`:""}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/* Force left alignment for all elements in the editor */
|
|
88
|
+
.overtype-container .overtype-wrapper * {
|
|
89
|
+
text-align: left !important;
|
|
84
90
|
}
|
|
85
91
|
|
|
86
92
|
/* Auto-resize mode styles */
|
|
@@ -797,7 +803,7 @@ ${s}`:r;if(d){let x=n.value[n.selectionStart-1];n.selectionStart!==0&&x!=null&&!
|
|
|
797
803
|
height: 2px !important;
|
|
798
804
|
}
|
|
799
805
|
|
|
800
|
-
${
|
|
806
|
+
${l}
|
|
801
807
|
`}var ke=`<svg viewBox="0 0 18 18">
|
|
802
808
|
<path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5,4H9.5A2.5,2.5,0,0,1,12,6.5v0A2.5,2.5,0,0,1,9.5,9H5A0,0,0,0,1,5,9V4A0,0,0,0,1,5,4Z"></path>
|
|
803
809
|
<path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5,9h5.5A2.5,2.5,0,0,1,13,11.5v0A2.5,2.5,0,0,1,10.5,14H5a0,0,0,0,1,0,0V9A0,0,0,0,1,5,9Z"></path>
|
|
@@ -819,14 +825,14 @@ ${s}`:r;if(d){let x=n.value[n.selectionStart-1];n.selectionStart!==0&&x!=null&&!
|
|
|
819
825
|
<polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" points="5 7 3 9 5 11"></polyline>
|
|
820
826
|
<polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" points="13 7 15 9 13 11"></polyline>
|
|
821
827
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="10" x2="8" y1="5" y2="13"></line>
|
|
822
|
-
</svg>`,
|
|
828
|
+
</svg>`,Ae=`<svg viewBox="0 0 18 18">
|
|
823
829
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="4" y2="4"></line>
|
|
824
830
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="9" y2="9"></line>
|
|
825
831
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="14" y2="14"></line>
|
|
826
832
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="4" y2="4"></line>
|
|
827
833
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="9" y2="9"></line>
|
|
828
834
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="14" y2="14"></line>
|
|
829
|
-
</svg>`,
|
|
835
|
+
</svg>`,He=`<svg viewBox="0 0 18 18">
|
|
830
836
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="4" y2="4"></line>
|
|
831
837
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="9" y2="9"></line>
|
|
832
838
|
<line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="14" y2="14"></line>
|
|
@@ -847,7 +853,7 @@ ${s}`:r;if(d){let x=n.value[n.selectionStart-1];n.selectionStart!==0&&x!=null&&!
|
|
|
847
853
|
</svg>`,Be=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
848
854
|
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" fill="none"></path>
|
|
849
855
|
<circle cx="12" cy="12" r="3" fill="none"></circle>
|
|
850
|
-
</svg>`;var K=class{constructor(e){this.editor=e,this.container=null,this.buttons={}}create(){this.container=document.createElement("div"),this.container.className="overtype-toolbar",this.container.setAttribute("role","toolbar"),this.container.setAttribute("aria-label","Text formatting"),[{name:"bold",icon:ke,title:"Bold (Ctrl+B)",action:"toggleBold"},{name:"italic",icon:xe,title:"Italic (Ctrl+I)",action:"toggleItalic"},{separator:!0},{name:"h1",icon:Le,title:"Heading 1",action:"insertH1"},{name:"h2",icon:Se,title:"Heading 2",action:"insertH2"},{name:"h3",icon:Ce,title:"Heading 3",action:"insertH3"},{separator:!0},{name:"link",icon:Ee,title:"Insert Link (Ctrl+K)",action:"insertLink"},{name:"code",icon:Te,title:"Code (Ctrl+`)",action:"toggleCode"},{separator:!0},{name:"quote",icon:Me,title:"Quote",action:"toggleQuote"},{separator:!0},{name:"bulletList",icon:
|
|
856
|
+
</svg>`;var K=class{constructor(e){this.editor=e,this.container=null,this.buttons={}}create(){this.container=document.createElement("div"),this.container.className="overtype-toolbar",this.container.setAttribute("role","toolbar"),this.container.setAttribute("aria-label","Text formatting"),[{name:"bold",icon:ke,title:"Bold (Ctrl+B)",action:"toggleBold"},{name:"italic",icon:xe,title:"Italic (Ctrl+I)",action:"toggleItalic"},{separator:!0},{name:"h1",icon:Le,title:"Heading 1",action:"insertH1"},{name:"h2",icon:Se,title:"Heading 2",action:"insertH2"},{name:"h3",icon:Ce,title:"Heading 3",action:"insertH3"},{separator:!0},{name:"link",icon:Ee,title:"Insert Link (Ctrl+K)",action:"insertLink"},{name:"code",icon:Te,title:"Code (Ctrl+`)",action:"toggleCode"},{separator:!0},{name:"quote",icon:Me,title:"Quote",action:"toggleQuote"},{separator:!0},{name:"bulletList",icon:Ae,title:"Bullet List",action:"toggleBulletList"},{name:"orderedList",icon:He,title:"Numbered List",action:"toggleNumberedList"},{name:"taskList",icon:$e,title:"Task List",action:"toggleTaskList"},{separator:!0},{name:"viewMode",icon:Be,title:"View mode",action:"toggle-view-menu",hasDropdown:!0}].forEach(i=>{if(i.separator){let r=document.createElement("div");r.className="overtype-toolbar-separator",r.setAttribute("role","separator"),this.container.appendChild(r)}else{let r=this.createButton(i);this.buttons[i.name]=r,this.container.appendChild(r)}});let t=this.editor.element.querySelector(".overtype-container"),o=this.editor.element.querySelector(".overtype-wrapper");return t&&o&&t.insertBefore(this.container,o),this.container}createButton(e){let t=document.createElement("button");return t.className="overtype-toolbar-button",t.type="button",t.title=e.title,t.setAttribute("aria-label",e.title),t.setAttribute("data-action",e.action),t.innerHTML=e.icon,e.hasDropdown&&(t.classList.add("has-dropdown"),e.name==="viewMode"&&(this.viewModeButton=t)),t.addEventListener("click",o=>{o.preventDefault(),this.handleAction(e.action,t)}),t}async handleAction(e,t){let o=this.editor.textarea;if(o){if(e==="toggle-view-menu"){this.toggleViewDropdown(t);return}o.focus();try{switch(e){case"toggleBold":V(o);break;case"toggleItalic":D(o);break;case"insertH1":he(o);break;case"insertH2":ue(o);break;case"insertH3":me(o);break;case"insertLink":q(o);break;case"toggleCode":ce(o);break;case"toggleBulletList":W(o);break;case"toggleNumberedList":U(o);break;case"toggleQuote":pe(o);break;case"toggleTaskList":de(o);break;case"toggle-plain":let i=this.editor.container.classList.contains("plain-mode");this.editor.showPlainTextarea(!i);break}o.dispatchEvent(new Event("input",{bubbles:!0}))}catch(i){console.error("Error loading markdown-actions:",i)}}}async updateButtonStates(){let e=this.editor.textarea;if(e)try{let t=fe(e);Object.entries(this.buttons).forEach(([o,i])=>{let r=!1;switch(o){case"bold":r=t.includes("bold");break;case"italic":r=t.includes("italic");break;case"code":r=!1;break;case"bulletList":r=t.includes("bullet-list");break;case"orderedList":r=t.includes("numbered-list");break;case"quote":r=t.includes("quote");break;case"taskList":r=t.includes("task-list");break;case"h1":r=t.includes("header");break;case"h2":r=t.includes("header-2");break;case"h3":r=t.includes("header-3");break;case"togglePlain":r=!this.editor.container.classList.contains("plain-mode");break}i.classList.toggle("active",r),i.setAttribute("aria-pressed",r.toString())})}catch(t){}}toggleViewDropdown(e){let t=document.querySelector(".overtype-dropdown-menu");if(t){t.remove(),e.classList.remove("dropdown-active"),document.removeEventListener("click",this.handleDocumentClick);return}let o=this.createViewDropdown(),i=e.getBoundingClientRect();o.style.top=`${i.bottom+4}px`,o.style.left=`${i.left}px`,document.body.appendChild(o),e.classList.add("dropdown-active"),this.handleDocumentClick=r=>{!e.contains(r.target)&&!o.contains(r.target)&&(o.remove(),e.classList.remove("dropdown-active"),document.removeEventListener("click",this.handleDocumentClick))},setTimeout(()=>{document.addEventListener("click",this.handleDocumentClick)},0)}createViewDropdown(){let e=document.createElement("div");e.className="overtype-dropdown-menu";let t=this.editor.container.classList.contains("plain-mode"),i=this.editor.container.classList.contains("preview-mode")?"preview":t?"plain":"normal";return[{id:"normal",label:"Normal Edit",icon:"\u2713"},{id:"plain",label:"Plain Textarea",icon:"\u2713"},{id:"preview",label:"Preview Mode",icon:"\u2713"}].forEach(s=>{let l=document.createElement("button");l.className="overtype-dropdown-item",l.type="button";let a=document.createElement("span");a.className="overtype-dropdown-check",a.textContent=i===s.id?s.icon:"";let d=document.createElement("span");d.textContent=s.label,l.appendChild(a),l.appendChild(d),i===s.id&&l.classList.add("active"),l.addEventListener("click",p=>{p.stopPropagation(),this.setViewMode(s.id),e.remove(),this.viewModeButton.classList.remove("dropdown-active"),document.removeEventListener("click",this.handleDocumentClick)}),e.appendChild(l)}),e}setViewMode(e){switch(this.editor.container.classList.remove("plain-mode","preview-mode"),e){case"plain":this.editor.showPlainTextarea(!0);break;case"preview":this.editor.showPreviewMode(!0);break;case"normal":default:this.editor.showPlainTextarea(!1),typeof this.editor.showPreviewMode=="function"&&this.editor.showPreviewMode(!1);break}}destroy(){this.container&&(this.handleDocumentClick&&document.removeEventListener("click",this.handleDocumentClick),this.container.remove(),this.container=null,this.buttons={})}};var Z=class{constructor(e){this.editor=e,this.tooltip=null,this.currentLink=null,this.hideTimeout=null,this.init()}init(){CSS.supports("position-anchor: --x")&&CSS.supports("position-area: center")&&(this.createTooltip(),this.editor.textarea.addEventListener("selectionchange",()=>this.checkCursorPosition()),this.editor.textarea.addEventListener("keyup",t=>{(t.key.includes("Arrow")||t.key==="Home"||t.key==="End")&&this.checkCursorPosition()}),this.editor.textarea.addEventListener("input",()=>this.hide()),this.editor.textarea.addEventListener("scroll",()=>this.hide()),this.tooltip.addEventListener("mouseenter",()=>this.cancelHide()),this.tooltip.addEventListener("mouseleave",()=>this.scheduleHide()))}createTooltip(){this.tooltip=document.createElement("div"),this.tooltip.className="overtype-link-tooltip";let e=document.createElement("style");e.textContent=`
|
|
851
857
|
@supports (position-anchor: --x) and (position-area: center) {
|
|
852
858
|
.overtype-link-tooltip {
|
|
853
859
|
position: absolute;
|
|
@@ -886,20 +892,20 @@ ${s}`:r;if(d){let x=n.value[n.selectionStart-1];n.selectionStart!==0&&x!=null&&!
|
|
|
886
892
|
</svg>
|
|
887
893
|
<span class="overtype-link-tooltip-url"></span>
|
|
888
894
|
</span>
|
|
889
|
-
`,this.tooltip.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.currentLink&&(window.open(this.currentLink.url,"_blank"),this.hide())}),this.editor.container.appendChild(this.tooltip)}checkCursorPosition(){let e=this.editor.textarea.selectionStart,t=this.editor.textarea.value,o=this.findLinkAtPosition(t,e);o?(!this.currentLink||this.currentLink.url!==o.url||this.currentLink.index!==o.index)&&this.show(o):this.scheduleHide()}findLinkAtPosition(e,t){let o=/\[([^\]]+)\]\(([^)]+)\)/g,i,r=0;for(;(i=o.exec(e))!==null;){let
|
|
890
|
-
`).length-1}handleInput(e){this.updatePreview()}handleKeydown(e){if(e.key==="Tab"){e.preventDefault();let o=this.textarea.selectionStart,i=this.textarea.selectionEnd,r=this.textarea.value;if(o!==i&&e.shiftKey){let
|
|
895
|
+
`,this.tooltip.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.currentLink&&(window.open(this.currentLink.url,"_blank"),this.hide())}),this.editor.container.appendChild(this.tooltip)}checkCursorPosition(){let e=this.editor.textarea.selectionStart,t=this.editor.textarea.value,o=this.findLinkAtPosition(t,e);o?(!this.currentLink||this.currentLink.url!==o.url||this.currentLink.index!==o.index)&&this.show(o):this.scheduleHide()}findLinkAtPosition(e,t){let o=/\[([^\]]+)\]\(([^)]+)\)/g,i,r=0;for(;(i=o.exec(e))!==null;){let s=i.index,l=i.index+i[0].length;if(t>=s&&t<=l)return{text:i[1],url:i[2],index:r,start:s,end:l};r++}return null}show(e){this.currentLink=e,this.cancelHide();let t=this.tooltip.querySelector(".overtype-link-tooltip-url");t.textContent=e.url,this.tooltip.style.setProperty("--target-anchor",`--link-${e.index}`),this.tooltip.classList.add("visible")}hide(){this.tooltip.classList.remove("visible"),this.currentLink=null}scheduleHide(){this.cancelHide(),this.hideTimeout=setTimeout(()=>this.hide(),300)}cancelHide(){this.hideTimeout&&(clearTimeout(this.hideTimeout),this.hideTimeout=null)}destroy(){this.cancelHide(),this.tooltip&&this.tooltip.parentNode&&this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null,this.currentLink=null}};var b=class b{constructor(e,t={}){let o;if(typeof e=="string"){if(o=document.querySelectorAll(e),o.length===0)throw new Error(`No elements found for selector: ${e}`);o=Array.from(o)}else if(e instanceof Element)o=[e];else if(e instanceof NodeList)o=Array.from(e);else if(Array.isArray(e))o=e;else throw new Error("Invalid target: must be selector string, Element, NodeList, or Array");return o.map(r=>{if(r.overTypeInstance)return r.overTypeInstance.reinit(t),r.overTypeInstance;let s=Object.create(b.prototype);return s._init(r,t),r.overTypeInstance=s,b.instances.set(r,s),s})}_init(e,t={}){this.element=e,this.instanceTheme=t.theme||null,this.options=this._mergeOptions(t),this.instanceId=++b.instanceCount,this.initialized=!1,b.injectStyles(),b.initGlobalListeners();let o=e.querySelector(".overtype-container"),i=e.querySelector(".overtype-wrapper");o||i?this._recoverFromDOM(o,i):this._buildFromScratch(),this.shortcuts=new O(this),this.linkTooltip=new Z(this),this.options.toolbar&&(this.toolbar=new K(this),this.toolbar.create(),this.textarea.addEventListener("selectionchange",()=>{this.toolbar.updateButtonStates()}),this.textarea.addEventListener("input",()=>{this.toolbar.updateButtonStates()})),this.initialized=!0,this.options.onChange&&this.options.onChange(this.getValue(),this)}_mergeOptions(e){let t={fontSize:"14px",lineHeight:1.6,fontFamily:'"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:"16px",mobile:{fontSize:"16px",padding:"12px",lineHeight:1.5},textareaProps:{},autofocus:!1,autoResize:!1,minHeight:"100px",maxHeight:null,placeholder:"Start typing...",value:"",onChange:null,onKeydown:null,showActiveLineRaw:!1,showStats:!1,toolbar:!1,statsFormatter:null},{theme:o,colors:i,...r}=e;return{...t,...r}}_recoverFromDOM(e,t){if(e&&e.classList.contains("overtype-container"))this.container=e,this.wrapper=e.querySelector(".overtype-wrapper");else if(t){this.wrapper=t,this.container=document.createElement("div"),this.container.className="overtype-container";let o=this.instanceTheme||b.currentTheme||$,i=typeof o=="string"?o:o.name;if(i&&this.container.setAttribute("data-theme",i),this.instanceTheme){let r=typeof this.instanceTheme=="string"?I(this.instanceTheme):this.instanceTheme;if(r&&r.colors){let s=z(r.colors);this.container.style.cssText+=s}}t.parentNode.insertBefore(this.container,t),this.container.appendChild(t)}if(!this.wrapper){e&&e.remove(),t&&t.remove(),this._buildFromScratch();return}if(this.textarea=this.wrapper.querySelector(".overtype-input"),this.preview=this.wrapper.querySelector(".overtype-preview"),!this.textarea||!this.preview){this.container.remove(),this._buildFromScratch();return}this.wrapper._instance=this,this.options.fontSize&&this.wrapper.style.setProperty("--instance-font-size",this.options.fontSize),this.options.lineHeight&&this.wrapper.style.setProperty("--instance-line-height",String(this.options.lineHeight)),this.options.padding&&this.wrapper.style.setProperty("--instance-padding",this.options.padding),this._configureTextarea(),this._applyOptions()}_buildFromScratch(){let e=this._extractContent();this.element.innerHTML="",this._createDOM(),(e||this.options.value)&&this.setValue(e||this.options.value),this._applyOptions()}_extractContent(){let e=this.element.querySelector(".overtype-input");return e?e.value:this.element.textContent||""}_createDOM(){this.container=document.createElement("div"),this.container.className="overtype-container";let e=this.instanceTheme||b.currentTheme||$,t=typeof e=="string"?e:e.name;if(t&&this.container.setAttribute("data-theme",t),this.instanceTheme){let o=typeof this.instanceTheme=="string"?I(this.instanceTheme):this.instanceTheme;if(o&&o.colors){let i=z(o.colors);this.container.style.cssText+=i}}this.wrapper=document.createElement("div"),this.wrapper.className="overtype-wrapper",this.options.fontSize&&this.wrapper.style.setProperty("--instance-font-size",this.options.fontSize),this.options.lineHeight&&this.wrapper.style.setProperty("--instance-line-height",String(this.options.lineHeight)),this.options.padding&&this.wrapper.style.setProperty("--instance-padding",this.options.padding),this.wrapper._instance=this,this.textarea=document.createElement("textarea"),this.textarea.className="overtype-input",this.textarea.placeholder=this.options.placeholder,this._configureTextarea(),this.options.textareaProps&&Object.entries(this.options.textareaProps).forEach(([o,i])=>{o==="className"||o==="class"?this.textarea.className+=" "+i:o==="style"&&typeof i=="object"?Object.assign(this.textarea.style,i):this.textarea.setAttribute(o,i)}),this.preview=document.createElement("div"),this.preview.className="overtype-preview",this.preview.setAttribute("aria-hidden","true"),this.wrapper.appendChild(this.textarea),this.wrapper.appendChild(this.preview),this.container.appendChild(this.wrapper),this.options.showStats&&(this.statsBar=document.createElement("div"),this.statsBar.className="overtype-stats",this.container.appendChild(this.statsBar),this._updateStats()),this.element.appendChild(this.container),window.location.pathname.includes("demo.html")&&console.log("_createDOM completed:",{elementId:this.element.id,autoResize:this.options.autoResize,containerClasses:this.container.className,hasStats:!!this.statsBar,hasToolbar:this.options.toolbar}),this.options.autoResize?this._setupAutoResize():(this.container.classList.remove("overtype-auto-resize"),window.location.pathname.includes("demo.html")&&console.log("Removed auto-resize class from:",this.element.id))}_configureTextarea(){this.textarea.setAttribute("autocomplete","off"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.setAttribute("data-gramm","false"),this.textarea.setAttribute("data-gramm_editor","false"),this.textarea.setAttribute("data-enable-grammarly","false")}_applyOptions(){this.options.autofocus&&this.textarea.focus(),this.options.autoResize?this.container.classList.contains("overtype-auto-resize")||this._setupAutoResize():this.container.classList.remove("overtype-auto-resize"),this.updatePreview()}updatePreview(){let e=this.textarea.value,t=this.textarea.selectionStart,o=this._getCurrentLine(e,t),i=H.parse(e,o,this.options.showActiveLineRaw);this.preview.innerHTML=i||'<span style="color: #808080;">Start typing...</span>',this._applyCodeBlockBackgrounds(),this.options.showStats&&this.statsBar&&this._updateStats(),this.options.onChange&&this.initialized&&this.options.onChange(e,this)}_applyCodeBlockBackgrounds(){let e=this.preview.querySelectorAll(".code-fence");for(let t=0;t<e.length-1;t+=2){let o=e[t],i=e[t+1],r=o.parentElement,s=i.parentElement;!r||!s||(o.style.display="block",i.style.display="block",r.classList.add("code-block-line"),s.classList.add("code-block-line"))}}_getCurrentLine(e,t){return e.substring(0,t).split(`
|
|
896
|
+
`).length-1}handleInput(e){this.updatePreview()}handleKeydown(e){if(e.key==="Tab"){e.preventDefault();let o=this.textarea.selectionStart,i=this.textarea.selectionEnd,r=this.textarea.value;if(o!==i&&e.shiftKey){let s=r.substring(0,o),l=r.substring(o,i),a=r.substring(i),p=l.split(`
|
|
891
897
|
`).map(c=>c.replace(/^ /,"")).join(`
|
|
892
|
-
`);this.textarea.value=
|
|
898
|
+
`);document.execCommand?(this.textarea.setSelectionRange(o,i),document.execCommand("insertText",!1,p)):(this.textarea.value=s+p+a,this.textarea.selectionStart=o,this.textarea.selectionEnd=o+p.length)}else if(o!==i){let s=r.substring(0,o),l=r.substring(o,i),a=r.substring(i),p=l.split(`
|
|
893
899
|
`).map(c=>" "+c).join(`
|
|
894
|
-
`);this.textarea.value=
|
|
895
|
-
`),o=e.length,i=e.split(/\s+/).filter(p=>p.length>0).length,r=this.textarea.selectionStart,
|
|
896
|
-
`),l
|
|
900
|
+
`);document.execCommand?(this.textarea.setSelectionRange(o,i),document.execCommand("insertText",!1,p)):(this.textarea.value=s+p+a,this.textarea.selectionStart=o,this.textarea.selectionEnd=o+p.length)}else document.execCommand?document.execCommand("insertText",!1," "):(this.textarea.value=r.substring(0,o)+" "+r.substring(i),this.textarea.selectionStart=this.textarea.selectionEnd=o+2);this.textarea.dispatchEvent(new Event("input",{bubbles:!0}));return}!this.shortcuts.handleKeydown(e)&&this.options.onKeydown&&this.options.onKeydown(e,this)}handleScroll(e){this.preview.scrollTop=this.textarea.scrollTop,this.preview.scrollLeft=this.textarea.scrollLeft}getValue(){return this.textarea.value}setValue(e){this.textarea.value=e,this.updatePreview(),this.options.autoResize&&this._updateAutoHeight()}getRenderedHTML(e=!1){let t=this.getValue(),o=H.parse(t);return e&&(o=H.postProcessHTML(o)),o}getPreviewHTML(){return this.preview.innerHTML}focus(){this.textarea.focus()}blur(){this.textarea.blur()}isInitialized(){return this.initialized}reinit(e={}){this.options=this._mergeOptions({...this.options,...e}),this._applyOptions(),this.updatePreview()}_updateStats(){if(!this.statsBar)return;let e=this.textarea.value,t=e.split(`
|
|
901
|
+
`),o=e.length,i=e.split(/\s+/).filter(p=>p.length>0).length,r=this.textarea.selectionStart,l=e.substring(0,r).split(`
|
|
902
|
+
`),a=l.length,d=l[l.length-1].length+1;this.options.statsFormatter?this.statsBar.innerHTML=this.options.statsFormatter({chars:o,words:i,lines:t.length,line:a,column:d}):this.statsBar.innerHTML=`
|
|
897
903
|
<div class="overtype-stat">
|
|
898
904
|
<span class="live-dot"></span>
|
|
899
905
|
<span>${o} chars, ${i} words, ${t.length} lines</span>
|
|
900
906
|
</div>
|
|
901
|
-
<div class="overtype-stat">Line ${
|
|
902
|
-
`}_setupAutoResize(){this.container.classList.add("overtype-auto-resize"),this.previousHeight=null,this._updateAutoHeight(),this.textarea.addEventListener("input",()=>this._updateAutoHeight()),window.addEventListener("resize",()=>this._updateAutoHeight())}_updateAutoHeight(){if(!this.options.autoResize)return;let e=this.textarea,t=this.preview,o=this.wrapper,i=window.getComputedStyle(e),r=parseFloat(i.paddingTop),
|
|
907
|
+
<div class="overtype-stat">Line ${a}, Col ${d}</div>
|
|
908
|
+
`}_setupAutoResize(){this.container.classList.add("overtype-auto-resize"),this.previousHeight=null,this._updateAutoHeight(),this.textarea.addEventListener("input",()=>this._updateAutoHeight()),window.addEventListener("resize",()=>this._updateAutoHeight())}_updateAutoHeight(){if(!this.options.autoResize)return;let e=this.textarea,t=this.preview,o=this.wrapper,i=window.getComputedStyle(e),r=parseFloat(i.paddingTop),s=parseFloat(i.paddingBottom),l=e.scrollTop;e.style.setProperty("height","auto","important");let a=e.scrollHeight;if(this.options.minHeight){let c=parseInt(this.options.minHeight);a=Math.max(a,c)}let d="hidden";if(this.options.maxHeight){let c=parseInt(this.options.maxHeight);a>c&&(a=c,d="auto")}let p=a+"px";e.style.setProperty("height",p,"important"),e.style.setProperty("overflow-y",d,"important"),t.style.setProperty("height",p,"important"),t.style.setProperty("overflow-y",d,"important"),o.style.setProperty("height",p,"important"),e.scrollTop=l,t.scrollTop=l,this.previousHeight!==a&&(this.previousHeight=a)}showStats(e){this.options.showStats=e,e&&!this.statsBar?(this.statsBar=document.createElement("div"),this.statsBar.className="overtype-stats",this.container.appendChild(this.statsBar),this._updateStats()):!e&&this.statsBar&&(this.statsBar.remove(),this.statsBar=null)}showPlainTextarea(e){if(e?this.container.classList.add("plain-mode"):this.container.classList.remove("plain-mode"),this.toolbar){let t=this.container.querySelector('[data-action="toggle-plain"]');t&&(t.classList.toggle("active",!e),t.title=e?"Show markdown preview":"Show plain textarea")}return e}showPreviewMode(e){return e?this.container.classList.add("preview-mode"):this.container.classList.remove("preview-mode"),e}destroy(){if(this.element.overTypeInstance=null,b.instances.delete(this.element),this.shortcuts&&this.shortcuts.destroy(),this.wrapper){let e=this.getValue();this.wrapper.remove(),this.element.textContent=e}this.initialized=!1}static init(e,t={}){return new b(e,t)}static getInstance(e){return e.overTypeInstance||b.instances.get(e)||null}static destroyAll(){document.querySelectorAll("[data-overtype-instance]").forEach(t=>{let o=b.getInstance(t);o&&o.destroy()})}static injectStyles(e=!1){if(b.stylesInjected&&!e)return;let t=document.querySelector("style.overtype-styles");t&&t.remove();let o=b.currentTheme||$,i=be({theme:o}),r=document.createElement("style");r.className="overtype-styles",r.textContent=i,document.head.appendChild(r),b.stylesInjected=!0}static setTheme(e,t=null){let o=typeof e=="string"?I(e):e;t&&(o=we(o,t)),b.currentTheme=o,b.injectStyles(!0),document.querySelectorAll(".overtype-container").forEach(i=>{let r=typeof o=="string"?o:o.name;r&&i.setAttribute("data-theme",r)}),document.querySelectorAll(".overtype-wrapper").forEach(i=>{if(!i.closest(".overtype-container")){let s=typeof o=="string"?o:o.name;s&&i.setAttribute("data-theme",s)}let r=i._instance;r&&r.updatePreview()})}static initGlobalListeners(){b.globalListenersInitialized||(document.addEventListener("input",e=>{if(e.target&&e.target.classList&&e.target.classList.contains("overtype-input")){let t=e.target.closest(".overtype-wrapper"),o=t==null?void 0:t._instance;o&&o.handleInput(e)}}),document.addEventListener("keydown",e=>{if(e.target&&e.target.classList&&e.target.classList.contains("overtype-input")){let t=e.target.closest(".overtype-wrapper"),o=t==null?void 0:t._instance;o&&o.handleKeydown(e)}}),document.addEventListener("scroll",e=>{if(e.target&&e.target.classList&&e.target.classList.contains("overtype-input")){let t=e.target.closest(".overtype-wrapper"),o=t==null?void 0:t._instance;o&&o.handleScroll(e)}},!0),document.addEventListener("selectionchange",e=>{let t=document.activeElement;if(t&&t.classList.contains("overtype-input")){let o=t.closest(".overtype-wrapper"),i=o==null?void 0:o._instance;i&&(i.options.showStats&&i.statsBar&&i._updateStats(),clearTimeout(i._selectionTimeout),i._selectionTimeout=setTimeout(()=>{i.updatePreview()},50))}}),b.globalListenersInitialized=!0)}};B(b,"instances",new WeakMap),B(b,"stylesInjected",!1),B(b,"globalListenersInitialized",!1),B(b,"instanceCount",0);var S=b;S.MarkdownParser=H;S.ShortcutsManager=O;S.themes={solar:$,cave:I("cave")};S.getTheme=I;S.currentTheme=$;typeof window<"u"&&typeof window.document<"u"&&(window.OverType=S);var Xe=S;return Fe(Ye);})();
|
|
903
909
|
/**
|
|
904
910
|
* OverType - A lightweight markdown editor library with perfect WYSIWYG alignment
|
|
905
911
|
* @version 1.0.0
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "overtype",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"description": "A lightweight markdown editor library with perfect WYSIWYG alignment using an invisible textarea overlay",
|
|
5
5
|
"main": "dist/overtype.cjs",
|
|
6
6
|
"module": "dist/overtype.esm.js",
|
|
@@ -17,13 +17,16 @@
|
|
|
17
17
|
"type": "module",
|
|
18
18
|
"scripts": {
|
|
19
19
|
"build": "node build.js",
|
|
20
|
+
"build:prod": "npm test && npm run build",
|
|
20
21
|
"dev": "http-server -p 8080 -c-1",
|
|
21
22
|
"watch": "node build.js --watch",
|
|
22
|
-
"test": "node test/overtype.test.js && node test/preview-mode.test.js && node test/links.test.js && node test/api-methods.test.js",
|
|
23
|
+
"test": "node test/overtype.test.js && node test/preview-mode.test.js && node test/links.test.js && node test/api-methods.test.js && node test/comprehensive-alignment.test.js",
|
|
23
24
|
"test:main": "node test/overtype.test.js",
|
|
24
25
|
"test:preview": "node test/preview-mode.test.js",
|
|
25
26
|
"test:links": "node test/links.test.js",
|
|
26
27
|
"test:api": "node test/api-methods.test.js",
|
|
28
|
+
"test:alignment": "node test/comprehensive-alignment.test.js",
|
|
29
|
+
"preversion": "npm test",
|
|
27
30
|
"size": "gzip-size dist/overtype.min.js",
|
|
28
31
|
"serve": "http-server -p 8080 -c-1"
|
|
29
32
|
},
|
package/src/overtype.js
CHANGED
|
@@ -489,25 +489,9 @@ class OverType {
|
|
|
489
489
|
openParent.classList.add('code-block-line');
|
|
490
490
|
closeParent.classList.add('code-block-line');
|
|
491
491
|
|
|
492
|
-
//
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
// Apply class to divs between the fences
|
|
496
|
-
if (currentDiv.tagName === 'DIV') {
|
|
497
|
-
currentDiv.classList.add('code-block-line');
|
|
498
|
-
|
|
499
|
-
// Strip all formatting by replacing with plain text
|
|
500
|
-
// This prevents markdown formatting inside code blocks
|
|
501
|
-
const plainText = currentDiv.textContent;
|
|
502
|
-
currentDiv.textContent = plainText;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
// Move to next sibling
|
|
506
|
-
currentDiv = currentDiv.nextElementSibling;
|
|
507
|
-
|
|
508
|
-
// Safety check to prevent infinite loop
|
|
509
|
-
if (!currentDiv) break;
|
|
510
|
-
}
|
|
492
|
+
// With the new structure, there's a <pre> block between fences, not DIVs
|
|
493
|
+
// We don't need to process anything between the fences anymore
|
|
494
|
+
// The <pre><code> structure already handles the content correctly
|
|
511
495
|
}
|
|
512
496
|
}
|
|
513
497
|
|
|
@@ -537,7 +521,6 @@ class OverType {
|
|
|
537
521
|
if (event.key === 'Tab') {
|
|
538
522
|
event.preventDefault();
|
|
539
523
|
|
|
540
|
-
// Insert 2 spaces at cursor position
|
|
541
524
|
const start = this.textarea.selectionStart;
|
|
542
525
|
const end = this.textarea.selectionEnd;
|
|
543
526
|
const value = this.textarea.value;
|
|
@@ -552,9 +535,17 @@ class OverType {
|
|
|
552
535
|
const lines = selection.split('\n');
|
|
553
536
|
const outdented = lines.map(line => line.replace(/^ /, '')).join('\n');
|
|
554
537
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
538
|
+
// Try to use execCommand first to preserve undo history
|
|
539
|
+
if (document.execCommand) {
|
|
540
|
+
// Select the text that needs to be replaced
|
|
541
|
+
this.textarea.setSelectionRange(start, end);
|
|
542
|
+
document.execCommand('insertText', false, outdented);
|
|
543
|
+
} else {
|
|
544
|
+
// Fallback to direct manipulation
|
|
545
|
+
this.textarea.value = before + outdented + after;
|
|
546
|
+
this.textarea.selectionStart = start;
|
|
547
|
+
this.textarea.selectionEnd = start + outdented.length;
|
|
548
|
+
}
|
|
558
549
|
} else if (start !== end) {
|
|
559
550
|
// Indent: add 2 spaces to start of each selected line
|
|
560
551
|
const before = value.substring(0, start);
|
|
@@ -564,13 +555,27 @@ class OverType {
|
|
|
564
555
|
const lines = selection.split('\n');
|
|
565
556
|
const indented = lines.map(line => ' ' + line).join('\n');
|
|
566
557
|
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
558
|
+
// Try to use execCommand first to preserve undo history
|
|
559
|
+
if (document.execCommand) {
|
|
560
|
+
// Select the text that needs to be replaced
|
|
561
|
+
this.textarea.setSelectionRange(start, end);
|
|
562
|
+
document.execCommand('insertText', false, indented);
|
|
563
|
+
} else {
|
|
564
|
+
// Fallback to direct manipulation
|
|
565
|
+
this.textarea.value = before + indented + after;
|
|
566
|
+
this.textarea.selectionStart = start;
|
|
567
|
+
this.textarea.selectionEnd = start + indented.length;
|
|
568
|
+
}
|
|
570
569
|
} else {
|
|
571
570
|
// No selection: just insert 2 spaces
|
|
572
|
-
|
|
573
|
-
|
|
571
|
+
// Use execCommand to preserve undo history
|
|
572
|
+
if (document.execCommand) {
|
|
573
|
+
document.execCommand('insertText', false, ' ');
|
|
574
|
+
} else {
|
|
575
|
+
// Fallback to direct manipulation
|
|
576
|
+
this.textarea.value = value.substring(0, start) + ' ' + value.substring(end);
|
|
577
|
+
this.textarea.selectionStart = this.textarea.selectionEnd = start + 2;
|
|
578
|
+
}
|
|
574
579
|
}
|
|
575
580
|
|
|
576
581
|
// Trigger input event to update preview
|