UNPKG

medium-button

Version:

MediumButton extends Medium Editor with your custom buttons.

6 lines (5 loc) 2.32 kB
/** * MediumButton 1.0 (24.02.2015) * MIT (c) Patrick Stillhart */ "use strict";function MediumButton(a){if(!(void 0!==a.label&&/\S{1}/.test(a.label)&&void 0!==a.start&&/\S{1}/.test(a.start)&&void 0!==a.end&&/\S{1}/.test(a.end)||void 0!==a.label&&/\S{1}/.test(a.label)&&void 0!==a.action&&/\S{1}/.test(a.action)))return void console.error('[Custom-Button] You need to specify "label", "start" and "end" OR "label" and "action"');a.start=void 0===a.start?"":a.start,a.end=void 0===a.end?"":a.end;var b=this;this.options=a,this.button=document.createElement("button"),this.button.className="medium-editor-action",this.button.innerHTML=a.label,this.button.onclick=function(){var c=getCurrentSelection(),d=window.getSelection(),e=d.anchorNode.parentElement;void 0===a.start||c.indexOf(a.start)==-1&&c.indexOf(a.end)==-1?(void 0!=a.action&&(c=a.action(c,!0,e)),c=a.start+c+a.end):(void 0!=a.action&&(c=a.action(c,!1,e)),c=String(c).split(a.start).join(""),c=String(c).split(a.end).join(""));var g,h;if(d.getRangeAt&&d.rangeCount){if(g=window.getSelection().getRangeAt(0),g.deleteContents(),g.createContextualFragment)h=g.createContextualFragment(c);else{var i=document.createElement("div");for(i.innerHTML=c,h=document.createDocumentFragment();child=i.firstChild;)h.appendChild(child)}var j=h.firstChild,k=h.lastChild;g.insertNode(h),j&&(g.setStartBefore(j),g.setEndAfter(k)),d.removeAllRanges(),d.addRange(g)}b.base.checkContentChanged()}}function getCurrentSelection(){var b,a="";if("undefined"!=typeof window.getSelection){if(b=window.getSelection(),b.rangeCount){for(var c=document.createElement("div"),d=0,e=b.rangeCount;d<e;++d)c.appendChild(b.getRangeAt(d).cloneContents());a=c.innerHTML}}else"undefined"!=typeof document.selection&&"Text"==document.selection.type&&(a=document.selection.createRange().htmlText);return a}MediumButton.prototype.getButton=function(){return this.button},MediumButton.prototype.checkState=function(a){var b=getCurrentSelection();""!=this.options.start&&b.indexOf(this.options.start)>-1&&b.indexOf(this.options.end)>-1?this.button.classList.add("medium-editor-button-active"):this.button.classList.remove("medium-editor-button-active")},"undefined"!=typeof exports&&("undefined"!=typeof module&&module.exports&&(exports=module.exports=MediumButton),exports.MediumButton=MediumButton);