lilium-text
Advanced tools
Comparing version 1.0.6 to 1.0.7
@@ -1,1 +0,1 @@ | ||
"use strict";var _slicedToArray=function(){function a(a,b){var c=[],d=!0,e=!1,f=void 0;try{for(var g,h=a[Symbol.iterator]();!(d=(g=h.next()).done)&&(c.push(g.value),!(b&&c.length===b));d=!0);}catch(a){e=!0,f=a}finally{try{!d&&h["return"]&&h["return"]()}finally{if(e)throw f}}return c}return function(b,c){if(Array.isArray(b))return b;if(Symbol.iterator in Object(b))return a(b,c);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_createClass=function(){function a(a,b){for(var c,d=0;d<b.length;d++)c=b[d],c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(a,c.key,c)}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}();function _toConsumableArray(a){if(Array.isArray(a)){for(var b=0,c=Array(a.length);b<a.length;b++)c[b]=a[b];return c}return Array.from(a)}function _possibleConstructorReturn(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return b&&("object"==typeof b||"function"==typeof b)?b:a}function _inherits(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}var LiliumTextCommand=function(){function a(){_classCallCheck(this,a)}return _createClass(a,[{key:"execute",value:function execute(){throw new Error("execute() method was not overridden in child class.")}},{key:"make",value:function make(a){var b=this;this.editor=a;var c=document.createElement("i");if(c.className="liliumtext-topbar-command liliumtext-topbar-command-"+this.webName+" "+(this.cssClass||"liliumtext-topbar-noicon"),c.dataset.command=this.webName,this.text){var d=document.createElement("span");d.className="liliumtext-command-text",d.textContent=this.text,c.classList.add("liliumtext-command-withtext"),c.appendChild(d)}return c.addEventListener("click",function(c){a.log("Executed command "+b.webName+(b.param?" with parameter '"+b.param+"'":"")),a.fire("command",b.webName),b.execute(c,b,a)}),c}}]),a}(),LiliumTextWebCommand=function(a){function b(a,c,d,e,f){_classCallCheck(this,b);var g=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this));return g.webName=a,g.param=c,g.cssClass=d,g.imageURL=e,g.text=f,g}return _inherits(b,a),_createClass(b,[{key:"executeText",value:function executeText(){var a=this,b=this.editor.restoreSelection(),c=this.param;if("Caret"==b.type){var n=this.editor.createSelectionContext(b.focusNode),o=n.find(function(a){return a.type==c});if(o){this.editor.log("Unwrapping element of node type "+c);var p=o.element;this.editor.unwrap(p)}}else if("Range"==b.type){var d=b.anchorNode.compareDocumentPosition(b.focusNode)&Node.DOCUMENT_POSITION_FOLLOWING?[b.anchorNode,b.focusNode]:[b.focusNode,b.anchorNode],e=_slicedToArray(d,2),f=e[0],g=e[1],h=[this.editor.createSelectionContext(f),this.editor.createSelectionContext(g)],i=h[0],j=h[1],k=[i.find(function(a){return a.type==c}),j.find(function(a){return a.type==c})],l=k[0],m=k[1];this.editor.log("Long logic with range using node type "+c);var q=b.getRangeAt(0),r=q.extractContents();if("#text"!=r.childNodes[0].nodeName||r.childNodes[0].data.trim()||(this.editor.log("Removed extra empty text node from fragment"),q.insertNode(r.childNodes[0])),f.parentElement===g.parentElement&&!l){this.editor.log("Quick range wrap with element of node type "+c);var s=document.createElement(c);s.appendChild(r),b.getRangeAt(0).insertNode(s)}else if(!l!=!m){this.editor.log("XOR range wrapper extension of node type "+c);var t=document.createElement(c);t.appendChild(r),b.getRangeAt(0).insertNode(t);Array.prototype.forEach.call((l||m).element.querySelectorAll(c),function(b){a.editor.unwrap(b)})}else if(l&&m&&l.element===m.element){this.editor.log("Placeholder unwrap from two sources with node types : "+c);var u=document.createElement("liliumtext-placeholder");b.getRangeAt(0).insertNode(u);var v=l.element,w=v.cloneNode();for(v.parentElement.insertBefore(w,v);v.firstChild!=u;)w.appendChild(v.firstChild);v.parentElement.insertBefore(r,v),u.remove(),this.editor.log("Removing empty trailing <"+c+"> element"),w.textContent.trim()||w.remove(),v.textContent.trim()||v.remove()}else if(l&&m){this.editor.log("Merge wrap from two sources with node types : "+c);for(var x=r.firstChild,y=r.lastChild;x.nextSibling!=y;)x.appendChild(x.nextSibling);for(;rightFrag.firstChild;)leftFrag.appendChild(rightFrag.firstChild);rightFrag.remove(),b.getRangeAt(0).insertNode(r)}else if(1==r.childNodes.length){this.editor.log("Single unwrap of node type : "+c);for(var z=r.childNodes[0];z.lastChild;)b.getRangeAt(0).insertNode(z.lastChild)}else{this.editor.log("Fragment wrap with node type : "+c);var A=document.createElement(c);A.appendChild(r),b.getRangeAt(0).insertNode(A)}}}},{key:"executeExec",value:function executeExec(){this.editor.restoreSelection(),document.execCommand(this.param)}},{key:"executeBlock",value:function executeBlock(){var a=this.editor.restoreSelection(),b=a.getRangeAt(0),c=this.param,d=this.editor.createSelectionContext(a.focusNode),e=this.editor.settings.blockelements,f=d[d.length-1].element;if(f.nodeName!=c){var g=document.createElement(c);if(f.parentElement.insertBefore(g,f),f.data)g.appendChild(f);else{for(;f.firstChild;)g.appendChild(f.firstChild);f.remove()}b.setStart(g,1),b.collapse(!0),a.removeAllRanges(),a.addRange(b)}}},{key:"executeRemove",value:function executeRemove(){var a=this;if(this.param){var b=this.editor.restoreSelection().focusNode.parentElement,c=this.editor.createSelectionContext(b),d=c.find(function(b){return b.type==a.param});d&&(this.editor.log("Unwrapping node "+this.param),this.editor.unwrap(d.element))}else this.editor.log("Executing native command removeFormat"),this.editor.restoreSelection(),document.execCommand("removeFormat",!1,"")}},{key:"executeInsert",value:function executeInsert(){var a=this.param,b=document.createElement(a),c=this.editor.restoreSelection().focusNode.parentElement,d=this.editor.createSelectionContext(c),e=d[d.length-1].element;this.editor.contentel.insertBefore(b,e.nextElementSibling);var f=this.editor.restoreSelection().getRangeAt(0);f.setStart(b.nextElementSibling||e.nextElementSibling||b,0),f.collapse(!0),selection.removeAllRanges(),selection.addRange(f)}},{key:"execute",value:function execute(a){switch(this.webName){case"text":this.executeText();break;case"exec":this.executeExec();break;case"block":this.executeBlock();break;case"remove":this.executeRemove();break;case"insert":this.executeInsert();break;default:this.editor.log("Warning : Tried to execute command with unknown webName ["+this.webName+"]");}return this.editor.takeSnapshot(),a.stopPropagation(),a.preventDefault(),!1}}]),b}(LiliumTextCommand),LiliumTextCustomCommand=function(a){function b(a,c,d,e,f){_classCallCheck(this,b);var g=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this));return g.webName=a,g.callback=c,g.cssClass=d,g.imageURL=e,g.text=f,g}return _inherits(b,a),_createClass(b,[{key:"execute",value:function execute(){return this.callback.apply(this,arguments)&&this.editor.takeSnapshot(),!1}}]),b}(LiliumTextCommand),LiliumTextHistoryEntry=function(){function a(b){_classCallCheck(this,a),this.type=b}return _createClass(a,[{key:"undo",value:function undo(){}}],[{key:"makeStaticClassesBecauseJavascriptIsStillWeird",value:function makeStaticClassesBecauseJavascriptIsStillWeird(){a.ChildListHistoryEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"ChildList"));return c.record=a,c.target=a.target,c.previousState=a.oldValue,c}return _inherits(b,a),b}(a),a.TextHistoryEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"Text"));return c.record=a,c}return _inherits(b,a),b}(a),a.AttributesHistoryEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"Attributes"));return c.record=a,c}return _inherits(b,a),b}(a),a.AutomaticSnapshotEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"AutomaticSnapshot"));return c.markup=a,c}return _inherits(b,a),_createClass(b,[{key:"undo",value:function undo(a){if(a.content!=this.markup)return a.content=this.markup,!0}}]),b}(a),a.ManualSnapshotEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"ManualSnapshot"));return c.markup=a,c}return _inherits(b,a),_createClass(b,[{key:"undo",value:function undo(a){if(a.content!=this.markup)return a.content=this.markup,!0}}]),b}(a)}},{key:"fromRecord",value:function fromRecord(b){switch(b.type){case"childList":return new a.ChildListHistoryEntry(b);case"characterData":return new a.TextHistoryEntry(b);case"attributes":return new a.AttributesHistoryEntry(b);}}},{key:"fromSnapshot",value:function fromSnapshot(b,c){return c?new a.ManualSnapshotEntry(b):new a.AutomaticSnapshotEntry(b)}}]),a}();LiliumTextHistoryEntry.makeStaticClassesBecauseJavascriptIsStillWeird();var LiliumTextPlugin=function(){function a(b){_classCallCheck(this,a),this.identifier=b,this.active=!1}return _createClass(a,[{key:"register",value:function register(){}},{key:"unregister",value:function unregister(){}}]),a}(),LiliumText=function(){function a(b){var c=this,d=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,a),this.initat=window.performance.now(),this.initialized=!1,this.destroyed=!1,this.codeview=!1,this.focused=!1,this._historylastState="",this.hooks={},this._plugins=[],this.wrapperel="string"==typeof b?document.querySelector(b)||document.getElementById(b):b,!this.wrapperel)throw new Error("LiliumText - Invalid element, DOM selector, or DOM element ID.");this.id=this.wrapperel.id||"liliumtext-"+btoa(Math.random().toString()).slice(0,-2),a.instances[this.id]=this,this.settings=Object.assign(a.defaultSettings,d),this.commandsets=this.settings.commandsets||a.createDefaultCommands(this),this.log=this.settings.dev?a.makeLogFunction():function(){},this.log("Created LiliumText instance"),this.log("Firing document event"),document.dispatchEvent(new CustomEvent("liliumTextCreated",{detail:this})),this.wrapperel.classList.add("liliumtext"),this.wrapperel.classList.add("theme-"+this.settings.theme),Object.keys(this.settings.hooks).forEach(function(a){c.bind(a,c.settings.hooks[a])}),this._init(),this.settings.initrender&&this.render(),this.log("Ready in "+(window.performance.now()-this.initat)+"ms")}return _createClass(a,null,[{key:"createDefaultCommands",value:function createDefaultCommands(a){return[[new LiliumTextWebCommand("text",a.settings.boldnode||"strong","far fa-bold"),new LiliumTextWebCommand("text",a.settings.italicnode||"em","far fa-italic"),new LiliumTextWebCommand("text",a.settings.underlinenode||"u","far fa-underline"),new LiliumTextWebCommand("text",a.settings.strikenode||"strike","far fa-strikethrough"),new LiliumTextWebCommand("remove",void 0,"far fa-eraser")],[new LiliumTextCustomCommand("undo",a.undo.bind(a),"far fa-undo"),new LiliumTextCustomCommand("redo",a.redo.bind(a),"far fa-redo")],[new LiliumTextWebCommand("block",a.settings.breaktag||"p","far fa-paragraph"),new LiliumTextWebCommand("block","h1","far fa-h1"),new LiliumTextWebCommand("block","h2","far fa-h2"),new LiliumTextWebCommand("block","h3","far fa-h3"),new LiliumTextWebCommand("block","blockquote","far fa-quote-right")],[new LiliumTextWebCommand("insert","hr","far fa-minus")],[new LiliumTextWebCommand("exec","insertOrderedList","far fa-list-ol"),new LiliumTextWebCommand("exec","insertUnorderedList","far fa-list-ul"),new LiliumTextWebCommand("remove","a","far fa-unlink")],[new LiliumTextCustomCommand("code",a.toggleCode.bind(a),"far fa-code")]]}},{key:"makeLogFunction",value:function makeLogFunction(){return function(a){return console.log("[LiliumText] "+a)}}},{key:"defaultSettings",get:function get(){return{initrender:!0,removepastedstyles:!0,dev:!1,hooks:{},plugins:[],theme:"minim",width:"auto",boldnode:"strong",italicnode:"em",historyInterval:5e3,maxHistoryStack:100,underlinenode:"u",strikenode:"strike",height:"420px",breaktag:"p",blockelements:["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ol","ul","article","dd","dl","dt","figure","header","hr","main","section","table","tfoot"],inlineelements:["a","b","big","code","em","i","img","small","span","strong","sub","sup","time","var"],content:"",urldetection:/^((https?):\/)\/?([^:\/\s]+)((\/\w+)*\/?)([\w\-\.])+/i}}}]),_createClass(a,[{key:"destroy",value:function destroy(b){for(this.fire("destroy");this.wrapperel.firstElementChild;)this.wrapperel.firstElementChild.remove();for(var c in b?delete a.instances[this.id]:a.instances[this.id]=void 0,this)this[c]=void 0;this.destroyed=!0,document.dispatchEvent(new CustomEvent("liliumTextDestroyed",{detail:this}))}},{key:"lock",value:function lock(){this.contentel.removeAttribute("contenteditable")}},{key:"unlock",value:function unlock(){this.contentel.contentEditable=!0}},{key:"createSelectionContext",value:function createSelectionContext(a){var b=[];do b.push({type:a.nodeName.toLowerCase().replace("#",""),element:a}),a=a.parentNode;while(a!=this.contentel&&a);return b}},{key:"selectWord",value:function selectWord(a){var b=document.createRange();b.setStart(a.anchorNode,a.anchorOffset),b.setEnd(a.focusNode,a.focusOffset);var c=b.collapsed;b.detach();var d=a.focusNode,e=a.focusOffset;a.collapse(a.anchorNode,a.anchorOffset);var f=c?["backward","forward"]:["forward","backward"];a.modify("move",f[0],"character"),a.modify("move",f[1],"word"),a.extend(d,e),a.modify("extend",f[1],"character"),a.modify("extend",f[0],"word")}},{key:"selectParent",value:function selectParent(a,b){var c=document.createRange();c.selectNode(b||a.focusNode.parentNode),window.getSelection().removeAllRanges(),window.getSelection().addRange(c)}},{key:"unwrap",value:function unwrap(a){for(var b=a.parentElement;a.firstChild;)b.insertBefore(a.firstChild,a);a.remove()}},{key:"_pushToHistory",value:function _pushToHistory(a){this.fire("history",a),this.log("Pushing new entry to history"),this._history.mutations.push(a)>this.settings.maxHistoryStack&&this._history.mutations.shift(),this._history.undoStack=[]}},{key:"_observe",value:function _observe(a){var b=this;a.forEach(function(a){return b._pushToHistory(LiliumTextHistoryEntry.fromRecord(a))})}},{key:"_takeSnapshot",value:function _takeSnapshot(a){this.contentel.innerHTML!=this._historylastState&&(this._historylastState=this.contentel.innerHTML,this._pushToHistory(LiliumTextHistoryEntry.fromSnapshot(this._historylastState,a)))}},{key:"_startHistory",value:function _startHistory(){var a=this;this.snapshotTimerID=setInterval(function(){a._takeSnapshot()},this.settings.historyInterval)}},{key:"resetSnapshot",value:function resetSnapshot(){this.snapshotTimerID&&clearInterval(this.snapshotTimerID),this._startHistory()}},{key:"takeSnapshot",value:function takeSnapshot(){this.resetSnapshot(),this._takeSnapshot(!0)}},{key:"isRangeInEditor",value:function isRangeInEditor(a){return a&&a.startContainer.compareDocumentPosition(this.contentel)&Node.DOCUMENT_POSITION_CONTAINS}},{key:"insert",value:function insert(a){var b=this.restoreSelection(),c=this.getRange();this.isRangeInEditor(c)||(this.contentel.focus(),c=this.storeRange()),c.insertNode(a),c.setStartAfter(a),b.removeAllRanges(),b.addRange(c)}},{key:"_focused",value:function _focused(){var a=this.fire("focus");this.focused=!0,a&&a.includes(!1)||(this._tempSelection=void 0,this._tempRange=void 0,document.execCommand("defaultParagraphSeparator",!1,this.settings.breaktag))}},{key:"_clicked",value:function _clicked(a){var b=window.getSelection(),c=this.createSelectionContext(b.focusNode),d=b.focusNode.parentElement;this.fire("clicked",{context:c,event:a,selection:b,element:d})}},{key:"redo",value:function redo(){if(0!=this._history.undoStack.length){this.log("Restoring from undo stack");var a=this._history.undoStack.pop();this._history.mutations.push(a.mutation),this.content=a.markup,this.resetSnapshot()}return!1}},{key:"undo",value:function undo(){if(0!=this._history.mutations.length){this.log("Going up one state in history");var a=this._history.mutations.pop(),b=this.content;if(a.undo(this))this.log("Pushing to undo stack"),this._history.undoStack.push({markup:b,mutation:a}),this.resetSnapshot(),this.fire("undo");else return this.undo()}else this.log("Restored original content"),this.content=this.settings.content;return!1}},{key:"storeRange",value:function storeRange(){var a=window.getSelection();return a.focusNode&&(this._tempRange=a.getRangeAt(0).cloneRange()),this._tempRange}},{key:"restoreSelection",value:function restoreSelection(){var a=window.getSelection();return this.focused||(a.removeAllRanges(),a.addRange(this.getRange())),a}},{key:"getRange",value:function getRange(){return this._tempRange||this.storeRange()}},{key:"_blurred",value:function _blurred(){this.focused=!1,this.storeRange(),this.fire("blur")}},{key:"_keydown",value:function _keydown(a){if((a.ctrlKey||a.metaKey)&&"z"==String.fromCharCode(a.which).toLowerCase())return a.preventDefault(),this.undo(),!1}},{key:"_pasted",value:function _pasted(a){var b=a.clipboardData||window.clipboardData,c=this.fire("paste",b);if(!(c&&c.includes(!1)))if(b.types.includes("text/html")){a.stopPropagation(),a.preventDefault();var d=b.getData("text/html"),e=document.createElement("div");e.innerHTML=d,this.settings.removepastedstyles&&Array.prototype.forEach.call(e.querySelectorAll("*"),function(a){return a.removeAttribute("style")}),document.execCommand("insertHTML",!1,e.innerHTML)}else{var f=b.getData("text");this.settings.urldetection.exec(f)&&(a.stopPropagation(),a.preventDefault(),document.execCommand("createLink",!1,f))}}},{key:"_registerAllPlugins",value:function _registerAllPlugins(){var a=this;this.settings.plugins&&this.settings.plugins.forEach(function(b){return a.registerPlugin(b)})}},{key:"registerPlugin",value:function registerPlugin(a){var b=new a(this);this.log("Registering plugin with id "+b.identifier),b.register(),this._plugins.push(b)}},{key:"_init",value:function _init(){this.log("Initializing LiliumText instance"),this.toolbarel=document.createElement("div"),this.toolbarel.className="liliumtext-topbar",this.contentel=document.createElement("div"),this.contentel.contentEditable=!0,this.contentel.className="liliumtext-editor",this.codeel=document.createElement("div"),this.codeel.contentEditable=!0,this.codeel.className="liliumtext-code",this.wrapperel.appendChild(this.toolbarel),this.wrapperel.appendChild(this.contentel),this.wrapperel.appendChild(this.codeel),this.settings.content&&this.settings.initrender?this.contentel.innerHTML=this.settings.content:this.contentel.appendChild(document.createElement(this.settings.breaktag)),this.contentel.addEventListener("paste",this.settings.onpaste||this._pasted.bind(this)),this.contentel.addEventListener("focus",this._focused.bind(this)),this.contentel.addEventListener("blur",this._blurred.bind(this)),this.contentel.addEventListener("click",this._clicked.bind(this)),this.contentel.addEventListener("keydown",this._keydown.bind(this)),this._history={mutations:[],undoStack:[]},this._startHistory(),this._registerAllPlugins(),this.fire("init"),this.log("Initialized LiliumText instance"),this.initialized=!0}},{key:"createCommandSet",value:function createCommandSet(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:[],b=arguments[1],c=!(2<arguments.length&&void 0!==arguments[2])||arguments[2];-1===b?this.commandsets=[a].concat(_toConsumableArray(this.commandsets)):b<this.commandsets.length?this.commandsets=[].concat(_toConsumableArray(this.commandsets.slice(0,b)),[a],_toConsumableArray(this.commandsets.slice(b))):this.commandsets.push(a),c&&this.render()}},{key:"addCommand",value:function addCommand(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:this.commandsets.length-1,c=!(2<arguments.length&&void 0!==arguments[2])||arguments[2],d=this.commandsets[b];d?d.push(a):this.commandsets.push([a]),c&&this.render()}},{key:"bind",value:function bind(a,b){this.hooks[a]?this.hooks[a].push(b):this.hooks[a]=[b]}},{key:"fire",value:function fire(a,b){var c=this;return this.hooks[a]&&this.hooks[a].map(function(a){return a(c,b)})}},{key:"toggleCode",value:function toggleCode(){return this.log("Toggled code view"),this.codeview=!this.codeview,this.fire("code",this.codeview),this.codeview?this.codeel.textContent=this.contentel.innerHTML:this.contentel.innerHTML=this.codeel.textContent,this.codeel.classList[this.codeview?"add":"remove"]("visible"),this.contentel.classList[this.codeview?"add":"remove"]("invisible"),!0}},{key:"render",value:function render(){var a=this;this.log("Rendering LiliumText instance"),this.fire("willrender"),this.log("Clearing toolbar"),this.toolbarel.firstElementChild&&this.toolbarel.firstElementChild.remove(),this.log("Rendering toolbar");var b=document.createElement("div");b.className="liliumtext-commands",this.commandsets.forEach(function(c){var d=document.createElement("div");d.className="liliumtext-commandset",b.appendChild(d),c.forEach(function(b){d.appendChild(b.make(a))})}),this.contentel.style.height=this.settings.height,this.codeel.style.height=this.settings.height,this.wrapperel.style.width=this.settings.width,this.toolbarel.appendChild(b),this.fire("render"),this.log("Done rendering")}},{key:"toString",value:function toString(){return this.content}},{key:"describe",value:function describe(){var a=this;return this.settings.dev?"[Development LiliumText Editor instance] Wraps DOM element with ID "+(this.wrapperel.id||"[No ID]")+". This instance currently has "+Object.keys(this.hooks).reduce(function(b,c){return b+a.hooks[c].length},0)+" event hooks.":"[LiliumText Editor]"}},{key:"content",set:function set(a){var b={markup:a};this.fire("set",b),this.contentel.innerHTML=b.markup},get:function get(){var a={markup:this.contentel.innerHTML},b=this.fire("get",a);return a.markup}}]),a}();LiliumText.instances={},"undefined"!=typeof module&&(module.exports={LiliumText:LiliumText,LiliumTextCustomCommand:LiliumTextCustomCommand,LiliumTextWebCommand:LiliumTextWebCommand,LiliumTextCommand:LiliumTextCommand,LiliumTextPlugin:LiliumTextPlugin}); | ||
"use strict";var _slicedToArray=function(){function a(a,b){var c=[],d=!0,e=!1,f=void 0;try{for(var g,h=a[Symbol.iterator]();!(d=(g=h.next()).done)&&(c.push(g.value),!(b&&c.length===b));d=!0);}catch(a){e=!0,f=a}finally{try{!d&&h["return"]&&h["return"]()}finally{if(e)throw f}}return c}return function(b,c){if(Array.isArray(b))return b;if(Symbol.iterator in Object(b))return a(b,c);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_createClass=function(){function a(a,b){for(var c,d=0;d<b.length;d++)c=b[d],c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(a,c.key,c)}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}();function _toConsumableArray(a){if(Array.isArray(a)){for(var b=0,c=Array(a.length);b<a.length;b++)c[b]=a[b];return c}return Array.from(a)}function _possibleConstructorReturn(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return b&&("object"==typeof b||"function"==typeof b)?b:a}function _inherits(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}var LiliumTextCommand=function(){function a(){_classCallCheck(this,a)}return _createClass(a,[{key:"execute",value:function execute(){throw new Error("execute() method was not overridden in child class.")}},{key:"make",value:function make(a){var b=this;this.editor=a;var c=document.createElement("i");if(c.className="liliumtext-topbar-command liliumtext-topbar-command-"+this.webName+" "+(this.cssClass||"liliumtext-topbar-noicon"),c.dataset.command=this.webName,this.text){var d=document.createElement("span");d.className="liliumtext-command-text",d.textContent=this.text,c.classList.add("liliumtext-command-withtext"),c.appendChild(d)}return c.addEventListener("click",function(c){a.log("Executed command "+b.webName+(b.param?" with parameter '"+b.param+"'":"")),a.fire("command",b.webName),b.execute(c,b,a)}),c}}]),a}(),LiliumTextWebCommand=function(a){function b(a,c,d,e,f){_classCallCheck(this,b);var g=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this));return g.webName=a,g.param=c,g.cssClass=d,g.imageURL=e,g.text=f,g}return _inherits(b,a),_createClass(b,[{key:"executeText",value:function executeText(){var a=this,b=this.editor.restoreSelection(),c=this.param;if("Caret"==b.type){var n=this.editor.createSelectionContext(b.focusNode),o=n.find(function(a){return a.type==c});if(o){this.editor.log("Unwrapping element of node type "+c);var p=o.element;this.editor.unwrap(p)}}else if("Range"==b.type){var d=b.anchorNode.compareDocumentPosition(b.focusNode)&Node.DOCUMENT_POSITION_FOLLOWING?[b.anchorNode,b.focusNode]:[b.focusNode,b.anchorNode],e=_slicedToArray(d,2),f=e[0],g=e[1],h=[this.editor.createSelectionContext(f),this.editor.createSelectionContext(g)],i=h[0],j=h[1],k=[i.find(function(a){return a.type==c}),j.find(function(a){return a.type==c})],l=k[0],m=k[1];this.editor.log("Long logic with range using node type "+c);var q=b.getRangeAt(0),r=q.extractContents();if("#text"!=r.childNodes[0].nodeName||r.childNodes[0].data.trim()||(this.editor.log("Removed extra empty text node from fragment"),q.insertNode(r.childNodes[0])),f.parentElement===g.parentElement&&!l){this.editor.log("Quick range wrap with element of node type "+c);var s=document.createElement(c);s.appendChild(r),b.getRangeAt(0).insertNode(s)}else if(!l!=!m){this.editor.log("XOR range wrapper extension of node type "+c);var t=document.createElement(c);t.appendChild(r),b.getRangeAt(0).insertNode(t);Array.prototype.forEach.call((l||m).element.querySelectorAll(c),function(b){a.editor.unwrap(b)})}else if(l&&m&&l.element===m.element){this.editor.log("Placeholder unwrap from two sources with node types : "+c);var u=document.createElement("liliumtext-placeholder");b.getRangeAt(0).insertNode(u);var v=l.element,w=v.cloneNode();for(v.parentElement.insertBefore(w,v);v.firstChild!=u;)w.appendChild(v.firstChild);v.parentElement.insertBefore(r,v),u.remove(),this.editor.log("Removing empty trailing <"+c+"> element"),w.textContent.trim()||w.remove(),v.textContent.trim()||v.remove()}else if(l&&m){this.editor.log("Merge wrap from two sources with node types : "+c);for(var x=r.firstChild,y=r.lastChild;x.nextSibling!=y;)x.appendChild(x.nextSibling);for(;rightFrag.firstChild;)leftFrag.appendChild(rightFrag.firstChild);rightFrag.remove(),b.getRangeAt(0).insertNode(r)}else if(1==r.childNodes.length){this.editor.log("Single unwrap of node type : "+c);for(var z=r.childNodes[0];z.lastChild;)b.getRangeAt(0).insertNode(z.lastChild)}else{this.editor.log("Fragment wrap with node type : "+c);var A=document.createElement(c);A.appendChild(r),b.getRangeAt(0).insertNode(A)}}}},{key:"executeExec",value:function executeExec(){this.editor.restoreSelection(),document.execCommand(this.param)}},{key:"executeBlock",value:function executeBlock(){var a=this.editor.restoreSelection(),b=a.getRangeAt(0),c=this.param,d=this.editor.createSelectionContext(a.focusNode),e=this.editor.settings.blockelements,f=d[d.length-1].element;if(f.nodeName!=c){var g=document.createElement(c);if(f.parentElement.insertBefore(g,f),f.data)g.appendChild(f);else{for(;f.firstChild;)g.appendChild(f.firstChild);f.remove()}b.setStart(g,1),b.collapse(!0),a.removeAllRanges(),a.addRange(b)}}},{key:"executeRemove",value:function executeRemove(){var a=this;if(this.param){var b=this.editor.restoreSelection().focusNode.parentElement,c=this.editor.createSelectionContext(b),d=c.find(function(b){return b.type==a.param});d&&(this.editor.log("Unwrapping node "+this.param),this.editor.unwrap(d.element))}else this.editor.log("Executing native command removeFormat"),this.editor.restoreSelection(),document.execCommand("removeFormat",!1,"")}},{key:"executeInsert",value:function executeInsert(){var a=this.param,b=document.createElement(a),c=this.editor.restoreSelection(),d=c.focusNode.parentElement,e=this.editor.createSelectionContext(d),f=e[e.length-1].element;this.editor.contentel.insertBefore(b,f.nextElementSibling);var g=c.getRangeAt(0);g.setStart(b.nextElementSibling||f.nextElementSibling||b,0),g.collapse(!0),c.removeAllRanges(),c.addRange(g)}},{key:"execute",value:function execute(a){switch(this.webName){case"text":this.executeText();break;case"exec":this.executeExec();break;case"block":this.executeBlock();break;case"remove":this.executeRemove();break;case"insert":this.executeInsert();break;default:this.editor.log("Warning : Tried to execute command with unknown webName ["+this.webName+"]");}return this.editor.takeSnapshot(),a.stopPropagation(),a.preventDefault(),!1}}]),b}(LiliumTextCommand),LiliumTextCustomCommand=function(a){function b(a,c,d,e,f){_classCallCheck(this,b);var g=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this));return g.webName=a,g.callback=c,g.cssClass=d,g.imageURL=e,g.text=f,g}return _inherits(b,a),_createClass(b,[{key:"execute",value:function execute(){return this.callback.apply(this,arguments)&&this.editor.takeSnapshot(),!1}}]),b}(LiliumTextCommand),LiliumTextHistoryEntry=function(){function a(b){_classCallCheck(this,a),this.type=b}return _createClass(a,[{key:"undo",value:function undo(){}}],[{key:"makeStaticClassesBecauseJavascriptIsStillWeird",value:function makeStaticClassesBecauseJavascriptIsStillWeird(){a.ChildListHistoryEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"ChildList"));return c.record=a,c.target=a.target,c.previousState=a.oldValue,c}return _inherits(b,a),b}(a),a.TextHistoryEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"Text"));return c.record=a,c}return _inherits(b,a),b}(a),a.AttributesHistoryEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"Attributes"));return c.record=a,c}return _inherits(b,a),b}(a),a.AutomaticSnapshotEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"AutomaticSnapshot"));return c.markup=a,c}return _inherits(b,a),_createClass(b,[{key:"undo",value:function undo(a){if(a.content!=this.markup)return a.content=this.markup,!0}}]),b}(a),a.ManualSnapshotEntry=function(a){function b(a){_classCallCheck(this,b);var c=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this,"ManualSnapshot"));return c.markup=a,c}return _inherits(b,a),_createClass(b,[{key:"undo",value:function undo(a){if(a.content!=this.markup)return a.content=this.markup,!0}}]),b}(a)}},{key:"fromRecord",value:function fromRecord(b){switch(b.type){case"childList":return new a.ChildListHistoryEntry(b);case"characterData":return new a.TextHistoryEntry(b);case"attributes":return new a.AttributesHistoryEntry(b);}}},{key:"fromSnapshot",value:function fromSnapshot(b,c){return c?new a.ManualSnapshotEntry(b):new a.AutomaticSnapshotEntry(b)}}]),a}();LiliumTextHistoryEntry.makeStaticClassesBecauseJavascriptIsStillWeird();var LiliumTextPlugin=function(){function a(b){_classCallCheck(this,a),this.identifier=b,this.active=!1}return _createClass(a,[{key:"register",value:function register(){}},{key:"unregister",value:function unregister(){}}]),a}(),LiliumText=function(){function a(b){var c=this,d=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,a),this.initat=window.performance.now(),this.initialized=!1,this.destroyed=!1,this.codeview=!1,this.focused=!1,this._historylastState="",this.hooks={},this._plugins=[],this.wrapperel="string"==typeof b?document.querySelector(b)||document.getElementById(b):b,!this.wrapperel)throw new Error("LiliumText - Invalid element, DOM selector, or DOM element ID.");this.id=this.wrapperel.id||"liliumtext-"+btoa(Math.random().toString()).slice(0,-2),a.instances[this.id]=this,this.settings=Object.assign(a.defaultSettings,d),this.commandsets=this.settings.commandsets||a.createDefaultCommands(this),this.log=this.settings.dev?a.makeLogFunction():function(){},this.log("Created LiliumText instance"),this.log("Firing document event"),document.dispatchEvent(new CustomEvent("liliumTextCreated",{detail:this})),this.wrapperel.classList.add("liliumtext"),this.wrapperel.classList.add("theme-"+this.settings.theme),Object.keys(this.settings.hooks).forEach(function(a){c.bind(a,c.settings.hooks[a])}),this._init(),this.settings.initrender&&this.render(),this.log("Ready in "+(window.performance.now()-this.initat)+"ms")}return _createClass(a,null,[{key:"createDefaultCommands",value:function createDefaultCommands(a){return[[new LiliumTextWebCommand("text",a.settings.boldnode||"strong","far fa-bold"),new LiliumTextWebCommand("text",a.settings.italicnode||"em","far fa-italic"),new LiliumTextWebCommand("text",a.settings.underlinenode||"u","far fa-underline"),new LiliumTextWebCommand("text",a.settings.strikenode||"strike","far fa-strikethrough"),new LiliumTextWebCommand("remove",void 0,"far fa-eraser")],[new LiliumTextCustomCommand("undo",a.undo.bind(a),"far fa-undo"),new LiliumTextCustomCommand("redo",a.redo.bind(a),"far fa-redo")],[new LiliumTextWebCommand("block",a.settings.breaktag||"p","far fa-paragraph"),new LiliumTextWebCommand("block","h1","far fa-h1"),new LiliumTextWebCommand("block","h2","far fa-h2"),new LiliumTextWebCommand("block","h3","far fa-h3"),new LiliumTextWebCommand("block","blockquote","far fa-quote-right")],[new LiliumTextWebCommand("insert","hr","far fa-minus")],[new LiliumTextWebCommand("exec","insertOrderedList","far fa-list-ol"),new LiliumTextWebCommand("exec","insertUnorderedList","far fa-list-ul"),new LiliumTextWebCommand("remove","a","far fa-unlink")],[new LiliumTextCustomCommand("code",a.toggleCode.bind(a),"far fa-code")]]}},{key:"makeLogFunction",value:function makeLogFunction(){return function(a){return console.log("[LiliumText] "+a)}}},{key:"defaultSettings",get:function get(){return{initrender:!0,removepastedstyles:!0,dev:!1,hooks:{},plugins:[],theme:"minim",width:"auto",boldnode:"strong",italicnode:"em",historyInterval:5e3,maxHistoryStack:100,underlinenode:"u",strikenode:"strike",height:"420px",breaktag:"p",blockelements:["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ol","ul","article","dd","dl","dt","figure","header","hr","main","section","table","tfoot"],inlineelements:["a","b","big","code","em","i","img","small","span","strong","sub","sup","time","var"],content:"",urldetection:/^((https?):\/)\/?([^:\/\s]+)((\/\w+)*\/?)([\w\-\.])+/i}}}]),_createClass(a,[{key:"destroy",value:function destroy(b){for(this.fire("destroy");this.wrapperel.firstElementChild;)this.wrapperel.firstElementChild.remove();for(var c in b?delete a.instances[this.id]:a.instances[this.id]=void 0,this)this[c]=void 0;this.destroyed=!0,document.dispatchEvent(new CustomEvent("liliumTextDestroyed",{detail:this}))}},{key:"lock",value:function lock(){this.contentel.removeAttribute("contenteditable")}},{key:"unlock",value:function unlock(){this.contentel.contentEditable=!0}},{key:"createSelectionContext",value:function createSelectionContext(a){var b=[];do b.push({type:a.nodeName.toLowerCase().replace("#",""),element:a}),a=a.parentNode;while(a!=this.contentel&&a);return b}},{key:"selectWord",value:function selectWord(a){var b=document.createRange();b.setStart(a.anchorNode,a.anchorOffset),b.setEnd(a.focusNode,a.focusOffset);var c=b.collapsed;b.detach();var d=a.focusNode,e=a.focusOffset;a.collapse(a.anchorNode,a.anchorOffset);var f=c?["backward","forward"]:["forward","backward"];a.modify("move",f[0],"character"),a.modify("move",f[1],"word"),a.extend(d,e),a.modify("extend",f[1],"character"),a.modify("extend",f[0],"word")}},{key:"selectParent",value:function selectParent(a,b){var c=document.createRange();c.selectNode(b||a.focusNode.parentNode),window.getSelection().removeAllRanges(),window.getSelection().addRange(c)}},{key:"unwrap",value:function unwrap(a){for(var b=a.parentElement;a.firstChild;)b.insertBefore(a.firstChild,a);a.remove()}},{key:"_pushToHistory",value:function _pushToHistory(a){this.fire("history",a),this.log("Pushing new entry to history"),this._history.mutations.push(a)>this.settings.maxHistoryStack&&this._history.mutations.shift(),this._history.undoStack=[]}},{key:"_observe",value:function _observe(a){var b=this;a.forEach(function(a){return b._pushToHistory(LiliumTextHistoryEntry.fromRecord(a))})}},{key:"_takeSnapshot",value:function _takeSnapshot(a){this.contentel.innerHTML!=this._historylastState&&(this._historylastState=this.contentel.innerHTML,this._pushToHistory(LiliumTextHistoryEntry.fromSnapshot(this._historylastState,a)))}},{key:"_startHistory",value:function _startHistory(){var a=this;this.snapshotTimerID=setInterval(function(){a._takeSnapshot()},this.settings.historyInterval)}},{key:"resetSnapshot",value:function resetSnapshot(){this.snapshotTimerID&&clearInterval(this.snapshotTimerID),this._startHistory()}},{key:"takeSnapshot",value:function takeSnapshot(){this.resetSnapshot(),this._takeSnapshot(!0)}},{key:"isRangeInEditor",value:function isRangeInEditor(a){return a&&a.startContainer.compareDocumentPosition(this.contentel)&Node.DOCUMENT_POSITION_CONTAINS}},{key:"insert",value:function insert(a){var b=this.restoreSelection(),c=this.getRange();this.isRangeInEditor(c)||(this.contentel.focus(),c=this.storeRange()),c.insertNode(a),c.setStartAfter(a),b.removeAllRanges(),b.addRange(c)}},{key:"_focused",value:function _focused(){var a=this.fire("focus");this.focused=!0,a&&a.includes(!1)||(this._tempSelection=void 0,this._tempRange=void 0,document.execCommand("defaultParagraphSeparator",!1,this.settings.breaktag))}},{key:"_clicked",value:function _clicked(a){var b=window.getSelection(),c=this.createSelectionContext(b.focusNode),d=b.focusNode.parentElement;this.fire("clicked",{context:c,event:a,selection:b,element:d})}},{key:"redo",value:function redo(){if(0!=this._history.undoStack.length){this.log("Restoring from undo stack");var a=this._history.undoStack.pop();this._history.mutations.push(a.mutation),this.content=a.markup,this.resetSnapshot(),this.fire("redo")}return!1}},{key:"undo",value:function undo(){if(0!=this._history.mutations.length){this.log("Going up one state in history");var a=this._history.mutations.pop(),b=this.content;if(a.undo(this))this.log("Pushing to undo stack"),this._history.undoStack.push({markup:b,mutation:a}),this.resetSnapshot(),this.fire("undo");else return this.undo()}else this.log("Restored original content"),this.content=this.settings.content;return!1}},{key:"storeRange",value:function storeRange(){var a=window.getSelection();return a.focusNode&&(this._tempRange=a.getRangeAt(0).cloneRange()),this._tempRange}},{key:"restoreSelection",value:function restoreSelection(){var a=window.getSelection();return this.focused||(a.removeAllRanges(),a.addRange(this.getRange())),a}},{key:"getRange",value:function getRange(){return this._tempRange||this.storeRange()}},{key:"_blurred",value:function _blurred(){this.focused=!1,this.storeRange(),this.fire("blur")}},{key:"_keydown",value:function _keydown(a){if((a.ctrlKey||a.metaKey)&&"z"==String.fromCharCode(a.which).toLowerCase())return a.preventDefault(),this.undo(),!1}},{key:"_pasted",value:function _pasted(a){var b=a.clipboardData||window.clipboardData,c=this.fire("paste",b);if(!(c&&c.includes(!1)))if(b.types.includes("text/html")){a.stopPropagation(),a.preventDefault();var d=b.getData("text/html"),e=document.createElement("div");e.innerHTML=d,this.settings.removepastedstyles&&Array.prototype.forEach.call(e.querySelectorAll("*"),function(a){return a.removeAttribute("style")}),document.execCommand("insertHTML",!1,e.innerHTML)}else{var f=b.getData("text");this.settings.urldetection.exec(f)&&(a.stopPropagation(),a.preventDefault(),document.execCommand("createLink",!1,f))}}},{key:"_registerAllPlugins",value:function _registerAllPlugins(){var a=this;this.settings.plugins&&this.settings.plugins.forEach(function(b){return a.registerPlugin(b)})}},{key:"registerPlugin",value:function registerPlugin(a){var b=new a(this);this.log("Registering plugin with id "+b.identifier),b.register(),this._plugins.push(b)}},{key:"unregisterPlugin",value:function unregisterPlugin(a){var b=-1,c=this._plugins.find(function(c,d){if(c.identifier==a)return b=d,c});c&&(c&&c.unregister(),this._plugins.splice(b,1))}},{key:"_init",value:function _init(){this.log("Initializing LiliumText instance"),this.toolbarel=document.createElement("div"),this.toolbarel.className="liliumtext-topbar",this.contentel=document.createElement("div"),this.contentel.contentEditable=!0,this.contentel.className="liliumtext-editor",this.codeel=document.createElement("pre"),this.codeel.contentEditable=!0,this.codeel.className="liliumtext-code",this.wrapperel.appendChild(this.toolbarel),this.wrapperel.appendChild(this.contentel),this.wrapperel.appendChild(this.codeel),this.settings.content&&this.settings.initrender?this.contentel.innerHTML=this.settings.content:this.contentel.appendChild(document.createElement(this.settings.breaktag)),this.contentel.addEventListener("paste",this.settings.onpaste||this._pasted.bind(this)),this.contentel.addEventListener("focus",this._focused.bind(this)),this.contentel.addEventListener("blur",this._blurred.bind(this)),this.contentel.addEventListener("click",this._clicked.bind(this)),this.contentel.addEventListener("keydown",this._keydown.bind(this)),this._history={mutations:[],undoStack:[]},this._startHistory(),this._registerAllPlugins(),this.fire("init"),this.log("Initialized LiliumText instance"),this.initialized=!0}},{key:"createCommandSet",value:function createCommandSet(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:[],b=arguments[1],c=!(2<arguments.length&&void 0!==arguments[2])||arguments[2];-1===b?this.commandsets=[a].concat(_toConsumableArray(this.commandsets)):b<this.commandsets.length?this.commandsets=[].concat(_toConsumableArray(this.commandsets.slice(0,b)),[a],_toConsumableArray(this.commandsets.slice(b))):this.commandsets.push(a),c&&this.render()}},{key:"addCommand",value:function addCommand(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:this.commandsets.length-1,c=!(2<arguments.length&&void 0!==arguments[2])||arguments[2],d=this.commandsets[b];d?d.push(a):this.commandsets.push([a]),c&&this.render()}},{key:"bind",value:function bind(a,b){this.hooks[a]?this.hooks[a].push(b):this.hooks[a]=[b]}},{key:"fire",value:function fire(a,b){var c=this;return this.hooks[a]&&this.hooks[a].map(function(a){return a(c,b)})}},{key:"toggleCode",value:function toggleCode(){return this.log("Toggled code view"),this.codeview=!this.codeview,this.codeview?this.codeel.textContent=this.contentel.innerHTML:this.contentel.innerHTML=this.codeel.textContent,this.codeel.classList[this.codeview?"add":"remove"]("visible"),this.contentel.classList[this.codeview?"add":"remove"]("invisible"),this.fire("code",this.codeview),!0}},{key:"render",value:function render(){var a=this;this.log("Rendering LiliumText instance"),this.fire("willrender"),this.log("Clearing toolbar"),this.toolbarel.firstElementChild&&this.toolbarel.firstElementChild.remove(),this.log("Rendering toolbar");var b=document.createElement("div");b.className="liliumtext-commands",this.commandsets.forEach(function(c){var d=document.createElement("div");d.className="liliumtext-commandset",b.appendChild(d),c.forEach(function(b){d.appendChild(b.make(a))})}),this.contentel.style.height=this.settings.height,this.codeel.style.height=this.settings.height,this.wrapperel.style.width=this.settings.width,this.toolbarel.appendChild(b),this.fire("render"),this.log("Done rendering")}},{key:"toString",value:function toString(){return this.content}},{key:"describe",value:function describe(){var a=this;return this.settings.dev?"[Development LiliumText Editor instance] Wraps DOM element with ID "+(this.wrapperel.id||"[No ID]")+". This instance currently has "+Object.keys(this.hooks).reduce(function(b,c){return b+a.hooks[c].length},0)+" event hooks.":"[LiliumText Editor]"}},{key:"content",set:function set(a){var b={markup:a};this.fire("set",b),this.contentel.innerHTML=b.markup},get:function get(){var a={markup:this.contentel.innerHTML},b=this.fire("get",a);return a.markup}}]),a}();LiliumText.instances={},"undefined"!=typeof module&&(module.exports={LiliumText:LiliumText,LiliumTextCustomCommand:LiliumTextCustomCommand,LiliumTextWebCommand:LiliumTextWebCommand,LiliumTextCommand:LiliumTextCommand,LiliumTextPlugin:LiliumTextPlugin}); |
@@ -197,3 +197,4 @@ class LiliumTextCommand { | ||
const el = this.editor.restoreSelection().focusNode.parentElement; | ||
const selection = this.editor.restoreSelection(); | ||
const el = selection.focusNode.parentElement; | ||
const context = this.editor.createSelectionContext(el); | ||
@@ -204,3 +205,3 @@ const topLevelEl = context[context.length - 1].element; | ||
const range = this.editor.restoreSelection().getRangeAt(0); | ||
const range = selection.getRangeAt(0); | ||
range.setStart(newNode.nextElementSibling || topLevelEl.nextElementSibling || newNode, 0); | ||
@@ -592,2 +593,4 @@ range.collapse(true); | ||
this.resetSnapshot(); | ||
this.fire('redo'); | ||
} | ||
@@ -700,2 +703,17 @@ | ||
unregisterPlugin(id) { | ||
let index = -1; | ||
const pluginInstance = this._plugins.find((x, i) => { | ||
if (x.identifier == id) { | ||
index = i; | ||
return x; | ||
} | ||
}); | ||
if (pluginInstance) { | ||
pluginInstance && pluginInstance.unregister(); | ||
this._plugins.splice(index, 1); | ||
} | ||
} | ||
_init() { | ||
@@ -710,3 +728,3 @@ this.log('Initializing LiliumText instance'); | ||
this.codeel = document.createElement('div'); | ||
this.codeel = document.createElement('pre'); | ||
this.codeel.contentEditable = true; | ||
@@ -781,3 +799,2 @@ this.codeel.className = "liliumtext-code"; | ||
this.fire('code', this.codeview); | ||
if (this.codeview) { | ||
@@ -792,2 +809,3 @@ this.codeel.textContent = this.contentel.innerHTML; | ||
this.fire('code', this.codeview); | ||
return true; | ||
@@ -794,0 +812,0 @@ } |
{ | ||
"name": "lilium-text", | ||
"version": "1.0.6", | ||
"version": "1.0.7", | ||
"description": "Web rich text editor. Not ready to be used at all.", | ||
@@ -5,0 +5,0 @@ "main": "build/liliumtext.js", |
@@ -34,5 +34,11 @@ # Lilium Text | ||
| dev | Development flag. If true, will output in console. | false | | ||
| plugins | An array of LiliumTextPlugin extended classes | [] | | ||
| theme | Theme identifier | "minim" | | ||
| hooks | Objects containing hooks and callbacks. | {} | | ||
| width | CSS width of the entire text Lilium Text | "auto" | | ||
| height | CSS height of the **editor** text box | "420px" | | ||
| boldnode | Element used to wrap bold text | "strong" | | ||
| italicnode | Element used to wrap italic text | "italic" | | ||
| underlinenode | Element used to wrap underlined text | "u" | | ||
| strikenode | Element used to wrap strikedthrough text | "strike" | | ||
| breaktag | Defined the HTML tag used to wrap new lines | "p" | | ||
@@ -62,14 +68,18 @@ | content | Initial content | "" | | ||
| Event Name | Occasion | Args | | ||
| ---------- | -------------------------------------------- | ----------------------------- | | ||
| init | The editor is finished initializing | | | ||
| command | A command is going to be executed | String `commandName` | | ||
| destroy | The editor object was released | | | ||
| focus | The text portion of the editor was focused | | | ||
| paste | The user pasted content into the editor | Object `DataTransfer` | | ||
| code | Toggle between text view and html view | Boolean, true if code view | | ||
| willrender | Editor is about to render | | | ||
| render | Editor rendered | | | ||
| set | The content setter was called | Object `{ markup }` | | ||
| get | The content getter was called | Object `{ markup }` | | ||
| Event Name | Occasion | Args | | ||
| ---------- | -------------------------------------------- | ------------------------------------- | | ||
| init | The editor is finished initializing | | | ||
| command | A command is going to be executed | String `commandName` | | ||
| destroy | The editor object was released | | | ||
| history | A state was pushed to history stack | Entry `LiliumTextHistoryEntry` | | ||
| focus | The text portion of the editor was focused | | | ||
| paste | The user pasted content into the editor | Object `DataTransfer` | | ||
| code | Toggle between text view and html view | Boolean, true if code view | | ||
| willrender | Editor is about to render | | | ||
| render | Editor rendered | | | ||
| set | The content setter was called | Object `{ markup }` | | ||
| get | The content getter was called | Object `{ markup }` | | ||
| clicked | A click inside the content editor | Context, Event, Selection, Element | | ||
| undo | Went back one step in history stack | | | ||
| redo | Went forward one step in history stack | | | ||
@@ -165,2 +175,56 @@ Some events will carry arguments as detailed in the "Args" column. When defining a callback, it is important to remember that the first argument is **always** the editor firing the event. If event arguments exist, they will appear as the second argument of the callback. | ||
## Plugins | ||
For reusable logic, it is possible to extend the LiliumTextPlugin virtual class and create a plugin to avoid duplicate code. The plugin must override the two virtual methods `register`, `unregister` as well as the constructor. | ||
For example. | ||
```javascript | ||
class myPlugin extends LiliumTextPlugin { | ||
static get uniqueIdentifier() { | ||
return "myPlugin"; | ||
} | ||
// The constructor receives a single argument : and instance of LiliumText | ||
constructor(editor) { | ||
// The super constructor must be called. The only argument is a unique ID typically the class name as a string. | ||
// This string will be used to unregister the plugin later. For clarity, let's use a static get. | ||
super(myPlugin.uniqueIdentifier) | ||
// I recommend storing a reference to the editor instance like so | ||
this.editor = editor; | ||
} | ||
register() { | ||
this.boundInsertImage = this.insertImage.bind(this); | ||
const insertImageCommand = new LiliumTextCustomCommand("myPluginInsertImage", this.boundInsertImage, "far fa-image"); | ||
// Add image insertion command in fourth group (index 3) | ||
this.instance.addCommand(insertImageCommand, 3); | ||
this.instance.bind('some-event', this.someOutcome); | ||
} | ||
unregister() { | ||
// Remove command, remove bindings, etc | ||
} | ||
insertImage() { | ||
// Insert new image into content using this.editor reference | ||
} | ||
} | ||
``` | ||
Once the class is ready to be tested, **the class itself** must be passed as an argument to the `registerPlugin` method of a LiliumText instance. It is also possible to pass an array of plugins to register during initialization using the `plugins` options. | ||
```javascript | ||
const myEditor = new LiliumText('myEditor', { plugins : [myPlugin] }); | ||
// OR | ||
const myEdutir = new LiliumText('myEditor', {}); | ||
myEditor.registerPlugin(myPlugin); | ||
``` | ||
The `register` method overridden by the `myPlugin` class will be called during the initialization if provided as an option of the LiliumText constructor, or when the `registerPlugin` method is called. | ||
To unregister a plugin, simply call `editorInstance.unregisterPlugin(pluginID)`. In the previous example, we would do the following. | ||
```javascript | ||
editor.unregisterPlugin(myPlugin.uniqueIdentifier); | ||
``` |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1184031
19
958
228