editify
Version:
A pure implementation of WYSIWYG HTML editor all we needed
2 lines (1 loc) • 2.59 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Editify={})}(this,(function(e){"use strict";var t=!1,n=0,o=function(e){var o=this;this.currentState={element:null,style:{bold:!1}},this.on=function(e,t){"change"===e&&o.editor.addEventListener("keyup",(function(e){return o.onKeyUp(e,t)})),"selectionchange"===e&&(o.editor.addEventListener("selectstart",o.onSelectStart),o.editor.addEventListener("mouseup",(function(e){return o.onMouseUp(e,t)})))},this.off=function(e,t){"change"===e&&o.editor.removeEventListener("keyup",(function(e){return o.onKeyUp(e,t)})),"selectionchange"===e&&(o.editor.removeEventListener("selectstart",o.onSelectStart),o.editor.removeEventListener("mouseup",(function(e){return o.onMouseUp(e,t)})))},this.onKeyUp=function(e,t){var i;if((!e.isComposing&&229!==e.keyCode||"Enter"===e.code&&229===e.keyCode)&&t){var r=n,l=o.getCaretPosition(o.editor),d=e.target,u=d.innerHTML,s=null===(i=d.textContent)||void 0===i?void 0:i.substring(r,l);n=l,t(u,s)}},this.onSelectStart=function(){t=!0},this.onMouseUp=function(e,i){n=o.getCaretPosition(o.editor),t&&(i&&i(document.getSelection()),t=!1)},this.getCaretPosition=function(e){var t,n=null===(t=document.getSelection())||void 0===t?void 0:t.getRangeAt(0),o=null==n?void 0:n.cloneRange();return o?(o.selectNodeContents(e),o.setEnd(n.endContainer,n.endOffset),o.toString().length):-1},this.toggleBold=function(){o.currentState.style.bold=!o.currentState.style.bold;var e=document.getSelection(),t=null==e?void 0:e.toString(),n=null==e?void 0:e.getRangeAt(0);null==n||n.deleteContents();var i=null==n?void 0:n.createContextualFragment(o.currentState.style.bold?"<b>"+t+"</b>":t),r=null==i?void 0:i.firstChild,l=null==i?void 0:i.lastChild;null==n||n.insertNode(i),null==n||n.setStartBefore(r),null==n||n.setEndAfter(l),null==e||e.removeAllRanges(),null==e||e.addRange(n)};var i=document.getElementById(e);i&&(this.editor=i,this.editor.contentEditable="true",document.addEventListener("pointerup",(function(e){var t=document.getSelection();if(t)for(var n=0;n<t.rangeCount;n++){var i=t.getRangeAt(n).commonAncestorContainer.parentElement;if(i===o.editor);else if(i){o.currentState.element=i;var r=getComputedStyle(i);o.currentState.style.bold=400<~~r.getPropertyValue("font-weight")}}})));var r=document.getElementById("toolbar-bold");r&&(this.toolbarBold=r,this.toolbarBold.addEventListener("click",this.toggleBold))};e.Editify=o,Object.defineProperty(e,"__esModule",{value:!0})}));