New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

lilium-text

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lilium-text - npm Package Compare versions

Comparing version 1.0.4 to 1.0.5

2

build/liliumtext.js

@@ -1,1 +0,1 @@

"use strict";var _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,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("mousedown",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:"execute",value:function execute(a){return document.execCommand(this.webName,!1,this.param),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),!1}}]),b}(LiliumTextCommand),LiliumText=function(){function a(b){var c=this,d=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,a),this.initialized=!1,this.destroyed=!1,this.codeview=!1,this.hooks={},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()),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 object"),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()}return _createClass(a,null,[{key:"createDefaultCommands",value:function createDefaultCommands(a){return[[new LiliumTextWebCommand("bold",void 0,"far fa-bold"),new LiliumTextWebCommand("italic",void 0,"far fa-italic"),new LiliumTextWebCommand("underline",void 0,"far fa-underline"),new LiliumTextWebCommand("strikethrough",void 0,"far fa-strikethrough"),new LiliumTextWebCommand("removeFormat",void 0,"far fa-eraser")],[new LiliumTextWebCommand("undo",void 0,"far fa-undo"),new LiliumTextWebCommand("redo",void 0,"far fa-redo")],[new LiliumTextWebCommand("formatBlock","p","far fa-paragraph"),new LiliumTextWebCommand("formatBlock","h1","far fa-h1"),new LiliumTextWebCommand("formatBlock","h2","far fa-h2"),new LiliumTextWebCommand("formatBlock","h3","far fa-h3"),new LiliumTextWebCommand("formatBlock","blockquote","far fa-quote-right")],[new LiliumTextWebCommand("insertOrderedList",void 0,"far fa-list-ol"),new LiliumTextWebCommand("insertUnorderedList",void 0,"far fa-list-ul"),new LiliumTextWebCommand("unlink",!1,"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:{},theme:"minim",width:"auto",height:"420px",breaktag:"p",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:"isRangeInEditor",value:function isRangeInEditor(a){if(a)for(var b=a.endContainer;b.parentElement;){if(b==this.contentel)return!0;b=b.parentElement}return!1}},{key:"insert",value:function insert(a){var b=this._tempRange||this._makeRange();this.isRangeInEditor(b)||(this.contentel.focus(),b=this._makeRange()),b.insertNode(a),b.setStartAfter(a),this._tempSelection.removeAllRanges(),this._tempSelection.addRange(b),this._tempRange=b}},{key:"_focused",value:function _focused(){var a=this.fire("focus");a&&a.includes(!1)||document.execCommand("defaultParagraphSeparator",!1,this.settings.breaktag)}},{key:"_makeRange",value:function _makeRange(){return this._tempSelection=window.getSelection(),this._tempSelection.focusNode&&(this._tempRange=this._tempSelection.getRangeAt(0).cloneRange()),this._tempRange}},{key:"_blurred",value:function _blurred(){this._makeRange()}},{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:"_init",value:function _init(){var a=this;this.log("Initializing object"),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("textarea"),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?setTimeout(function(){a.contentel.innerHTML=a.settings.content},10):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.fire("init"),this.log("Initialized object"),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.log("Firing event : "+a),this.hooks[a]&&this.hooks[a].map(function(a){return a(c,b)})}},{key:"toggleCode",value:function toggleCode(){this.log("Toggled code view"),this.codeview=!this.codeview,this.fire("code",this.codeview),this.codeview?this.codeel.value=this.contentel.innerHTML:this.contentel.innerHTML=this.codeel.value,this.codeel.classList[this.codeview?"add":"remove"]("visible"),this.contentel.classList[this.codeview?"add":"remove"]("invisible")}},{key:"render",value:function render(){var a=this;this.log("Rendering object"),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});
"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)}},{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 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.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 object"),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:{},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:"_init",value:function _init(){this.log("Initializing object"),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.fire("init"),this.log("Initialized object"),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 object"),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});
class LiliumTextCommand {
execute() { throw new Error("execute() method was not overridden in child class.") }
make(editor) {
this.editor = editor;
const el = document.createElement("i");

@@ -17,3 +18,3 @@ el.className = "liliumtext-topbar-command liliumtext-topbar-command-" + this.webName + " " + (this.cssClass || "liliumtext-topbar-noicon");

el.addEventListener('mousedown', (ev) => {
el.addEventListener('click', (ev) => {
editor.log('Executed command ' + this.webName + (this.param ? (" with parameter '" + this.param + "'") : ''));

@@ -39,4 +40,181 @@ editor.fire('command', this.webName);

executeText() {
const selection = this.editor.restoreSelection();
const nodetype = this.param;
if (selection.type == "Caret") {
const context = this.editor.createSelectionContext(selection.focusNode);
let maybeCtxElem = context.find(x => x.type == nodetype);
if (maybeCtxElem) {
this.editor.log('Unwrapping element of node type ' + nodetype);
const el = maybeCtxElem.element;
this.editor.unwrap(el);
}
} else if (selection.type == "Range") {
const [left, right] = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING ?
[selection.anchorNode, selection.focusNode] : [selection.focusNode, selection.anchorNode];
const [leftCtx, rightCtx] = [this.editor.createSelectionContext(left), this.editor.createSelectionContext(right)];
const [leftExistWrap, rightExistWrap] = [leftCtx.find(x => x.type == nodetype), rightCtx.find(x => x.type == nodetype)];
// Fun! :D
this.editor.log("Long logic with range using node type " + nodetype);
const range = selection.getRangeAt(0);
const frag = range.extractContents();
if (frag.childNodes[0].nodeName == "#text" && !frag.childNodes[0].data.trim()) {
this.editor.log("Removed extra empty text node from fragment");
range.insertNode(frag.childNodes[0]);
}
if (left.parentElement === right.parentElement && !leftExistWrap) {
this.editor.log("Quick range wrap with element of node type " + nodetype);
const newElem = document.createElement(nodetype);
newElem.appendChild(frag);
selection.getRangeAt(0).insertNode(newElem);
} else if (!leftExistWrap != !rightExistWrap) {
// Apparently there is no XOR in Javascript, so here's a syntax monstrosity
// This will not execute the block unless one is truthy and one is falsey
this.editor.log('XOR range wrapper extension of node type ' + nodetype);
const newElem = document.createElement(nodetype);
newElem.appendChild(frag);
selection.getRangeAt(0).insertNode(newElem);
// Extend existing wrapper
const wrapper = leftExistWrap || rightExistWrap;
Array.prototype.forEach.call(wrapper.element.querySelectorAll(nodetype), node => {
this.editor.unwrap(node);
});
} else if (leftExistWrap && rightExistWrap && leftExistWrap.element === rightExistWrap.element) {
// Unwrap both ends, possible solution : while (textnode has next sibling) { insert sibling after wrapper node }
this.editor.log("Placeholder unwrap from two sources with node types : " + nodetype);
const placeholder = document.createElement('liliumtext-placeholder');
selection.getRangeAt(0).insertNode(placeholder);
const leftEl = leftExistWrap.element;
const clone = leftEl.cloneNode();
leftEl.parentElement.insertBefore(clone, leftEl);
while (leftEl.firstChild != placeholder) {
clone.appendChild(leftEl.firstChild);
}
leftEl.parentElement.insertBefore(frag, leftEl);
placeholder.remove();
this.editor.log('Removing empty trailing <' + nodetype + '> element');
!clone.textContent.trim() && clone.remove();
!leftEl.textContent.trim() && leftEl.remove();
} else if (leftExistWrap && rightExistWrap) {
this.editor.log("Merge wrap from two sources with node types : " + nodetype);
// Merge wrap
const leftFrag = frag.firstChild;
const rightFrag = frag.lastChild;
while (leftFrag.nextSibling != rightFrag) {
leftFrag.appendChild(leftFrag.nextSibling);
}
while(rightFrag.firstChild) {
leftFrag.appendChild(rightFrag.firstChild);
}
rightFrag.remove();
selection.getRangeAt(0).insertNode(frag);
} else if (frag.childNodes.length == 1) {
// Entire element is selected, Unwrap entire element
this.editor.log("Single unwrap of node type : " + nodetype);
const wrap = frag.childNodes[0];
while (wrap.lastChild) {
selection.getRangeAt(0).insertNode(wrap.lastChild);
}
} else {
// Create new element, insert before selection
this.editor.log("Fragment wrap with node type : " + nodetype);
const newElem = document.createElement(nodetype);
newElem.appendChild(frag);
selection.getRangeAt(0).insertNode(newElem);
}
}
}
executeExec() {
this.editor.restoreSelection();
document.execCommand(this.param);
}
executeBlock() {
const selection = this.editor.restoreSelection();
const range = selection.getRangeAt(0);
const nodetype = this.param;
const context = this.editor.createSelectionContext(selection.focusNode);
const blocktags = this.editor.settings.blockelements;
const topLevelTag = context[context.length - 1].element;
if (topLevelTag.nodeName != nodetype) {
const newNode = document.createElement(nodetype);
topLevelTag.parentElement.insertBefore(newNode, topLevelTag);
if (topLevelTag.data) {
newNode.appendChild(topLevelTag);
} else {
while (topLevelTag.firstChild) {
newNode.appendChild(topLevelTag.firstChild);
}
topLevelTag.remove();
}
range.setStart(newNode, 1);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
}
executeRemove() {
if (this.param) {
const el = this.editor.restoreSelection().focusNode.parentElement;
const context = this.editor.createSelectionContext(el);
const wrapperCtx = context.find(x => x.type == this.param);
if (wrapperCtx) {
this.editor.log('Unwrapping node ' + this.param);
this.editor.unwrap(wrapperCtx.element);
}
} else {
this.editor.log('Executing native command removeFormat');
this.editor.restoreSelection();
document.execCommand('removeFormat', false, "");
}
}
executeInsert() {
const nodetype = this.param;
const newNode = document.createElement(nodetype);
const el = this.editor.restoreSelection().focusNode.parentElement;
const context = this.editor.createSelectionContext(el);
const topLevelEl = context[context.length - 1].element;
this.editor.contentel.insertBefore(newNode, topLevelEl.nextElementSibling);
}
execute(ev) {
document.execCommand(this.webName, false, this.param);
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 is noOp, but display warning for easier debugging
default: this.editor.log(`Warning : Tried to execute command with unknown webName [${this.webName}]`);
}
this.editor.takeSnapshot();
ev.stopPropagation();

@@ -60,3 +238,3 @@ ev.preventDefault();

execute() {
this.callback(...arguments);
this.callback(...arguments) && this.editor.takeSnapshot();
return false;

@@ -66,2 +244,79 @@ }

class LiliumTextHistoryEntry {
constructor(type) {
this.type = type;
}
undo() { }
static makeStaticClassesBecauseJavascriptIsStillWeird() {
// Create nested static classes
LiliumTextHistoryEntry.ChildListHistoryEntry = class ChildListHistoryEntry extends LiliumTextHistoryEntry {
constructor(record) {
super("ChildList");
this.record = record;
this.target = record.target;
this.previousState = record.oldValue;
}
}
LiliumTextHistoryEntry.TextHistoryEntry = class TextHistoryEntry extends LiliumTextHistoryEntry {
constructor(record) {
super("Text");
this.record = record;
}
}
LiliumTextHistoryEntry.AttributesHistoryEntry = class AttributesHistoryEntry extends LiliumTextHistoryEntry {
constructor(record) {
super("Attributes");
this.record = record;
}
}
LiliumTextHistoryEntry.AutomaticSnapshotEntry = class AutomaticSnapshotEntry extends LiliumTextHistoryEntry {
constructor(state) {
super("AutomaticSnapshot");
this.markup = state;
}
undo(editor) {
if (editor.content != this.markup) {
editor.content = this.markup;
return true;
}
}
}
LiliumTextHistoryEntry.ManualSnapshotEntry = class ManualSnapshotEntry extends LiliumTextHistoryEntry {
constructor(state) {
super("ManualSnapshot");
this.markup = state;
}
undo(editor) {
if (editor.content != this.markup) {
editor.content = this.markup;
return true;
}
}
}
}
static fromRecord(record) {
switch (record.type) {
case "childList" : return new LiliumTextHistoryEntry.ChildListHistoryEntry(record);
case "characterData" : return new LiliumTextHistoryEntry.TextHistoryEntry(record);
case "attributes" : return new LiliumTextHistoryEntry.AttributesHistoryEntry(record);
}
}
static fromSnapshot(markup, manual) {
return manual ?
new LiliumTextHistoryEntry.ManualSnapshotEntry(markup) :
new LiliumTextHistoryEntry.AutomaticSnapshotEntry(markup);
}
}
LiliumTextHistoryEntry.makeStaticClassesBecauseJavascriptIsStillWeird();
class LiliumText {

@@ -76,4 +331,12 @@ static get defaultSettings() {

width : "auto",
boldnode : "strong",
italicnode : "em",
historyInterval : 5000,
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 : "",

@@ -87,21 +350,23 @@ urldetection : /^((https?):\/)\/?([^:\/\s]+)((\/\w+)*\/?)([\w\-\.])+/i

[
new LiliumTextWebCommand("bold", undefined, "far fa-bold"),
new LiliumTextWebCommand("italic", undefined, "far fa-italic"),
new LiliumTextWebCommand("underline", undefined, "far fa-underline"),
new LiliumTextWebCommand("strikethrough", undefined, "far fa-strikethrough"),
new LiliumTextWebCommand('removeFormat', undefined, "far fa-eraser")
new LiliumTextWebCommand('text', editor.settings.boldnode || "strong", "far fa-bold"),
new LiliumTextWebCommand('text', editor.settings.italicnode || "em", "far fa-italic"),
new LiliumTextWebCommand('text', editor.settings.underlinenode || "u", "far fa-underline"),
new LiliumTextWebCommand('text', editor.settings.strikenode || "strike", "far fa-strikethrough"),
new LiliumTextWebCommand('remove', undefined, "far fa-eraser")
], [
new LiliumTextWebCommand("undo", undefined, "far fa-undo"),
new LiliumTextWebCommand("redo", undefined, "far fa-redo")
new LiliumTextCustomCommand('undo', editor.undo.bind(editor), 'far fa-undo'),
new LiliumTextCustomCommand('redo', editor.redo.bind(editor), 'far fa-redo')
], [
new LiliumTextWebCommand('formatBlock', 'p', 'far fa-paragraph'),
new LiliumTextWebCommand("formatBlock", "h1", "far fa-h1"),
new LiliumTextWebCommand("formatBlock", "h2", "far fa-h2"),
new LiliumTextWebCommand("formatBlock", "h3", "far fa-h3"),
new LiliumTextWebCommand("formatBlock", "blockquote", "far fa-quote-right"),
new LiliumTextWebCommand('block', editor.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("insertOrderedList", undefined, "far fa-list-ol"),
new LiliumTextWebCommand("insertUnorderedList", undefined, "far fa-list-ul"),
new LiliumTextWebCommand('unlink', false, 'far fa-unlink')
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", editor.toggleCode.bind(editor), "far fa-code")

@@ -117,5 +382,8 @@ ]

constructor(nameOrElem, settings = {}) {
this.initat = window.performance.now();
this.initialized = false;
this.destroyed = false;
this.codeview = false;
this.focused = false;
this._historylastState = "";
this.hooks = {};

@@ -128,3 +396,3 @@

this.id = this.wrapperel.id || ("liliumtext-" + btoa(Math.random().toString()));
this.id = this.wrapperel.id || ("liliumtext-" + btoa(Math.random().toString()).slice(0, -2));
LiliumText.instances[this.id] = this;

@@ -148,2 +416,4 @@

this.settings.initrender && this.render();
this.log('Ready in ' + (window.performance.now() - this.initat) + 'ms');
}

@@ -179,22 +449,100 @@

isRangeInEditor(range) {
if (range) {
let par = range.endContainer;
while (par.parentElement) {
if (par == this.contentel) {
return true;
}
createSelectionContext(elem) {
const context = [];
par = par.parentElement;
}
do {
context.push({ type : elem.nodeName.toLowerCase().replace('#', ''), element : elem });
elem = elem.parentNode;
} while (elem != this.contentel && elem);
return context;
}
selectWord(sel) {
const range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
const backwards = range.collapsed;
range.detach();
const endNode = sel.focusNode
const endOffset = sel.focusOffset;
sel.collapse(sel.anchorNode, sel.anchorOffset);
const direction = backwards ? ['backward', 'forward'] : ['forward', 'backward'];
sel.modify("move", direction[0], "character");
sel.modify("move", direction[1], "word");
sel.extend(endNode, endOffset);
sel.modify("extend", direction[1], "character");
sel.modify("extend", direction[0], "word");
}
selectParent(sel, par) {
const range = document.createRange();
range.selectNode(par || sel.focusNode.parentNode);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
unwrap(el) {
const par = el.parentElement;
while(el.firstChild) {
par.insertBefore(el.firstChild, el);
}
el.remove();
}
return false;
_pushToHistory(entry) {
this.fire('history', entry);
this.log("Pushing new entry to history");
// Push to history, and remove first element if array is too big
this._history.mutations.push(entry) > this.settings.maxHistoryStack && this._history.mutations.shift();
this._history.undoStack = [];
}
_observe(record) {
record.forEach(x => this._pushToHistory(LiliumTextHistoryEntry.fromRecord(x)));
}
_takeSnapshot(manual) {
if (this.contentel.innerHTML != this._historylastState) {
this._historylastState = this.contentel.innerHTML;
this._pushToHistory(LiliumTextHistoryEntry.fromSnapshot(this._historylastState, manual));
}
}
_startHistory() {
if (false && window.MutationObserver) {
this.observer = new MutationObserver(this._observe.bind(this));
this.observer.observe(this.contentel, { childList: true, subtree : true });
} else {
this.snapshotTimerID = setInterval(() => {
this._takeSnapshot();
}, this.settings.historyInterval);
}
}
resetSnapshot() {
this.snapshotTimerID && clearInterval(this.snapshotTimerID);
this._startHistory();
}
takeSnapshot() {
this.resetSnapshot();
this._takeSnapshot(true);
}
isRangeInEditor(range) {
return range && range.startContainer.compareDocumentPosition(this.contentel) & Node.DOCUMENT_POSITION_CONTAINS;
}
insert(element) {
let range = this._tempRange || this._makeRange();
const selection = this.restoreSelection();
let range = this.getRange();
if (!this.isRangeInEditor(range)) {
this.contentel.focus();
range = this._makeRange();
range = this.storeRange();
}

@@ -205,5 +553,4 @@

this._tempSelection.removeAllRanges();
this._tempSelection.addRange(range);
this._tempRange = range;
selection.removeAllRanges();
selection.addRange(range);
}

@@ -213,3 +560,6 @@

const eventresult = this.fire('focus');
this.focused = true;
if (!eventresult || !eventresult.includes(false)) {
this._tempSelection = undefined;
this._tempRange = undefined;
document.execCommand("defaultParagraphSeparator", false, this.settings.breaktag);

@@ -219,16 +569,82 @@ }

_makeRange() {
this._tempSelection = window.getSelection();
_clicked(event) {
const selection = window.getSelection();
const context = this.createSelectionContext(selection.focusNode);
const element = selection.focusNode.parentElement;
this.fire('clicked', { context, event, selection, element });
}
if (this._tempSelection.focusNode) {
this._tempRange = this._tempSelection.getRangeAt(0).cloneRange();
redo() {
if (this._history.undoStack.length != 0) {
this.log('Restoring from undo stack');
const undoItem = this._history.undoStack.pop();
this._history.mutations.push(undoItem.mutation);
this.content = undoItem.markup;
this.resetSnapshot();
}
return false;
}
undo() {
if (this._history.mutations.length != 0) {
this.log('Going up one state in history');
let mutation = this._history.mutations.pop();
const oldMarkup = this.content;
if (mutation.undo(this)) {
this.log('Pushing to undo stack');
this._history.undoStack.push({ markup : oldMarkup, mutation });
this.resetSnapshot();
this.fire('undo');
} else {
return this.undo();
}
} else {
this.log('Restored original content');
this.content = this.settings.content;
}
return false;
}
storeRange() {
const tempSelection = window.getSelection();
if (tempSelection.focusNode) {
this._tempRange = tempSelection.getRangeAt(0).cloneRange();
}
return this._tempRange;
}
restoreSelection() {
const sel = window.getSelection();
if (!this.focused) {
sel.removeAllRanges();
sel.addRange(this.getRange());
}
return sel;
}
getRange() {
return this._tempRange || this.storeRange();
}
_blurred() {
this._makeRange();
this.focused = false;
this.storeRange();
this.fire('blur');
}
_keydown(e) {
if ((e.ctrlKey || e.metaKey) && String.fromCharCode(e.which).toLowerCase() == 'z') {
e.preventDefault();
this.undo();
return false;
}
}
_pasted(e) {

@@ -272,3 +688,4 @@ const data = e.clipboardData || window.clipboardData;

this.codeel = document.createElement('textarea');
this.codeel = document.createElement('div');
this.codeel.contentEditable = true;
this.codeel.className = "liliumtext-code";

@@ -281,5 +698,5 @@

if (this.settings.content && this.settings.initrender) {
setTimeout(() => {
//setTimeout(() => {
this.contentel.innerHTML = this.settings.content;
}, 10);
//}, 10);
} else {

@@ -289,5 +706,13 @@ 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('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();

@@ -327,3 +752,3 @@ this.fire('init');

fire(eventname, args) {
this.log('Firing event : ' + eventname);
// this.log('Firing event : ' + eventname);
return this.hooks[eventname] && this.hooks[eventname].map(callback => callback(this, args));

@@ -338,5 +763,5 @@ }

if (this.codeview) {
this.codeel.value = this.contentel.innerHTML;
this.codeel.textContent = this.contentel.innerHTML;
} else {
this.contentel.innerHTML = this.codeel.value;
this.contentel.innerHTML = this.codeel.textContent;
}

@@ -346,2 +771,4 @@

this.contentel.classList[this.codeview ? "add" : "remove"]("invisible");
return true;
}

@@ -348,0 +775,0 @@

{
"name": "lilium-text",
"version": "1.0.4",
"version": "1.0.5",
"description": "Web rich text editor. Not ready to be used at all.",
"main": "testserver.js",
"main": "build/liliumtext.js",
"scripts": {

@@ -7,0 +7,0 @@ "build": "lessc dev/minim.less build/minim.css && uglifycss build/minim.css > build/minim.min.css && babel dev/liliumtext.js -o build/liliumtext.js",

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc