UNPKG

editify

Version:

A pure implementation of WYSIWYG HTML editor all we needed

2 lines (1 loc) 2.37 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=!1,t=0,n=function(n){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,n){var r;if((!e.isComposing&&229!==e.keyCode||"Enter"===e.code&&229===e.keyCode)&&n){var i=t,l=o.getCaretPosition(o.editor),d=e.target,u=d.innerHTML,s=null===(r=d.textContent)||void 0===r?void 0:r.substring(i,l);t=l,n(u,s)}},this.onSelectStart=function(){e=!0},this.onMouseUp=function(n,r){t=o.getCaretPosition(o.editor),e&&(r&&r(document.getSelection()),e=!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 r=null==n?void 0:n.createContextualFragment(o.currentState.style.bold?"<b>"+t+"</b>":t),i=null==r?void 0:r.firstChild,l=null==r?void 0:r.lastChild;null==n||n.insertNode(r),null==n||n.setStartBefore(i),null==n||n.setEndAfter(l),null==e||e.removeAllRanges(),null==e||e.addRange(n)};var r=document.getElementById(n);r&&(this.editor=r,this.editor.contentEditable="true",document.addEventListener("pointerup",(function(e){var t=document.getSelection();if(t)for(var n=0;n<t.rangeCount;n++){var r=t.getRangeAt(n).commonAncestorContainer.parentElement;if(r===o.editor);else if(r){o.currentState.element=r;var i=getComputedStyle(r);o.currentState.style.bold=400<~~i.getPropertyValue("font-weight")}}})));var i=document.getElementById("toolbar-bold");i&&(this.toolbarBold=i,this.toolbarBold.addEventListener("click",this.toggleBold))};exports.Editify=n;