UNPKG

chintext-editor

Version:

ChinText Editor - A modern WYSIWYG text editor with image support, tables, and PDF export.

1 lines 1.87 kB
const editor=document.getElementById("editor");function format(e,t=null){document.execCommand(e,!1,t)}function setFontSize(e){document.execCommand("fontSize",!1,e)}function setColor(e){document.execCommand("foreColor",!1,e)}function setBgColor(e){document.execCommand("hiliteColor",!1,e)}function setFont(e){document.execCommand("fontName",!1,e)}function insertImageAtCursor(e){const t=document.createElement("img");t.src=e,t.onload=()=>enableResize(t);const n=window.getSelection();if(!n.rangeCount)return;const o=n.getRangeAt(0);o.deleteContents(),o.insertNode(t),enableResize(t)}function insertTable(){let e='<table border="1">';for(let t=0;t<3;t++){e+="<tr>";for(let t=0;t<3;t++)e+="<td contenteditable='true'>Cell</td>";e+="</tr>"}e+="</table>",document.execCommand("insertHTML",!1,e)}function enableResize(e){const t=document.createElement("div");t.className="resize-handle",editor.appendChild(t),positionHandle(e,t),t.onmousedown=function(n){n.preventDefault(),document.onmousemove=function(n){e.style.width=n.pageX-e.offsetLeft+"px",e.style.height="auto",positionHandle(e,t)},document.onmouseup=function(){document.onmousemove=null,document.onmouseup=null}},e.onclick=()=>positionHandle(e,t)}function positionHandle(e,t){t.style.left=e.offsetLeft+e.width-10+"px",t.style.top=e.offsetTop+e.height-10+"px",t.style.display="block"}editor.addEventListener("paste",(e=>{const t=e.clipboardData.items;for(let e of t)if(-1!==e.type.indexOf("image")){const t=e.getAsFile(),n=new FileReader;n.onload=function(e){insertImageAtCursor(e.target.result)},n.readAsDataURL(t)}})),editor.addEventListener("dragover",(e=>e.preventDefault())),editor.addEventListener("drop",(e=>{e.preventDefault();const t=e.dataTransfer.files;if(t.length>0&&t[0].type.startsWith("image/")){const e=new FileReader;e.onload=function(e){insertImageAtCursor(e.target.result)},e.readAsDataURL(t[0])}}));