striven-editor

Maintained and contributed to an open source WYSIWYG editor as an internship project that made it to production and was adopted by the company I was working at.
git clone https://unitehenry.com/git/striven-editor.git
Log | Files | Refs | README | LICENSE

striveneditor.js (140383B)


      1 import './striveneditor.css';
      2 import {
      3     EXTENSIONS,
      4     FONTPACK,
      5     OPTIONGROUPS,
      6     DEFAULTOPTIONS,
      7     ACTIVEOPTIONCOLOR,
      8     FORECOLORICON,
      9     HILITECOLORICON,
     10     FONTNAMES,
     11     FONTSIZES,
     12     COLLAPSEICON,
     13     EXPANDICON,
     14     DESIGNICON,
     15     UPLOADICON
     16 } from './defaults.js';
     17 
     18 // Helpers
     19 import { createSVG, denormalizeCamel, blowUpElement, getImageDimensions, getImageDataURL, computeImageDimensions, createImageElement } from './utils';
     20 
     21 // Polyfills
     22 import ResizeObserver from 'resize-observer-polyfill';
     23 
     24 // Plugins
     25 import linkify from 'linkifyjs/element';
     26 
     27 // Pickr
     28 //import './classic.min.css';
     29 //import Pickr from './pickr.min.js';
     30 import '@simonwep/pickr/dist/themes/classic.min.css'; // 'classic' theme
     31 import Pickr from '@simonwep/pickr/dist/pickr.es5.min';
     32 
     33 // Formatting
     34 import js_beautify from 'js-beautify';
     35 
     36 // Consts
     37 const MAX_FILES_UPLOAD = 25;
     38 
     39 /* Represents an instance of the Striven Editor */
     40 export default class StrivenEditor {
     41     /**
     42      * Bind onchange handler to contenteditable element
     43      * @param {HTMLElement} element to bind onchange to
     44      */
     45     _bindContenteditableOnChange(el) {
     46         const se = this;
     47 
     48         el.addEventListener('focus', function () {
     49             if (el.data_orig === undefined) {
     50                 el.data_orig = el.innerHTML;
     51             }
     52             //reset toolbarclick
     53             se.toolbarClick = false;
     54         });
     55 
     56         el.addEventListener('blur', function () {
     57             const menus = se.editor.getElementsByClassName('se-popup-open:not(.se-toolbar-group)');
     58             const inputs = se.editor.getElementsByTagName('input');
     59             const colorPicker = se.editor.querySelectorAll('.pcr-app.visible');
     60             const actives = [...menus, ...colorPicker, ...inputs, se.body, se.toolbar, se.editor];
     61             if (
     62                 el.innerHTML != el.data_orig &&
     63                 !se.toolbarClick &&
     64                 !actives.includes(document.activeElement) &&
     65                 !menus.length &&
     66                 !colorPicker.length
     67             ) {
     68                 se.createLinks();
     69                 if (se.options.change) {
     70                     se.options.change(se.getContent());
     71                 }
     72                 delete el.data_orig;
     73             }
     74         });
     75     }
     76 
     77     /**
     78      * Instantiate the StrivenEditor
     79      * @param {HTMLElement} el The element to initialize StrivenEditor on
     80      * @param {Object} options StrivenEditor options to initialize the editor with
     81      */
     82     constructor(el, options) {
     83         const se = this;
     84 
     85         // Webpack inserts the package.json version
     86         se['_version'] = __VERSION__;
     87 
     88         // Establish the browser context
     89         se.establishBrowser();
     90 
     91         // Initialize a range instance for the editor
     92         se.range = new Range();
     93 
     94         // Initialize a file array for file upload
     95         se.files = [];
     96 
     97         // Default Option Groups with SVG Data
     98         se.optionGroups = OPTIONGROUPS;
     99 
    100         // Gets whether an image is being uploaded when pasting or inserting an image
    101         se._isImageUploading = false;
    102 
    103         // Initialize Options
    104         if (options) {
    105             // Set options property
    106             se.options = options;
    107 
    108             // Font Pack for font-awesome (not being used)
    109             options.fontPack || (se.options.fontPack = FONTPACK);
    110 
    111             // Allowed File Extensions
    112             options.extensions || (se.options.extensions = EXTENSIONS);
    113 
    114             // Enabled Toolbar options
    115             options.toolbarOptions || (se.options.toolbarOptions = DEFAULTOPTIONS);
    116 
    117             // Fill color for active options
    118             options.activeOptionColor || (se.options.activeOptionColor = ACTIVEOPTIONCOLOR);
    119 
    120             // Default fonts names
    121             options.fontNames || (se.options.fontNames = FONTNAMES);
    122 
    123             // Allow File Upload
    124             options.fileUpload !== false && (se.options.fileUpload = true);
    125 
    126             options.maxFiles = options.maxFiles || MAX_FILES_UPLOAD;
    127 
    128             // Configure Options with Minimal Enabled
    129             if (options.toolbarOptions && options.minimal) {
    130                 // Get custom options from toolbarOptions
    131                 const customs = options.toolbarOptions.filter((opt) => typeof opt === 'object');
    132 
    133                 // Set toolbar options for minimal configuration
    134                 se.options.toolbarOptions = ['bold', 'italic', 'underline', 'insertUnorderedList', 'attachment', 'link', 'image', ...customs];
    135 
    136                 //disallow tabbing
    137                 se.options.canTab = false;
    138             }
    139         } else {
    140             // Set default options
    141             se.options = {
    142                 fontPack: FONTPACK,
    143                 extensions: EXTENSIONS,
    144                 toolbarOptions: DEFAULTOPTIONS,
    145                 activeOptionColor: ACTIVEOPTIONCOLOR,
    146                 fontNames: FONTNAMES,
    147                 maxFiles: MAX_FILES_UPLOAD,
    148                 fileUpload: true,
    149                 canTab: false
    150             };
    151         }
    152 
    153         // Initialize the editor
    154         se.initEditor(el); // Core Editor Initialization
    155         se.initResponsive(); // Editor Reponsive Logic
    156         se.initOverflow(); // Overflow Content Logic
    157         se.overflow(); // Trigger overflow login on init
    158         se.getIsImageUploading = () => se._isImageUploading;
    159 
    160         // DOM Access to the Editor Instance
    161         el.StrivenEditor = () => se;
    162 
    163         // Bind handler functions to scope
    164         se.bound_popupEscapeHandler = se.popupEscapeHandler.bind(se);
    165     }
    166 
    167     /**
    168      * Initiliaze the StrivenEditor on the passed element.
    169      * @param {HTMLElement} el
    170      */
    171     initEditor(el) {
    172         const se = this;
    173 
    174         se.editor = el;
    175         se.toolbar = se.initToolbar();
    176         se.body = se.initBody();
    177         se.linkMenu = se.initLinkMenu();
    178         se.imageMenu = se.initImageMenu();
    179         se.tableMenu = se.initTableMenu();
    180         se.metaDataSection = se.options.metaUrl ? se.initMetaDataSection() : null;
    181         se.filesSection = se.options.fileUpload ? se.initFilesSection() : null;
    182 
    183         // Add Striven Editor Class
    184         se.editor.classList.add('striven-editor');
    185 
    186         // Stop events from bubbling up the DOM
    187         se.editor.onkeypress = (e) => e.stopPropagation();
    188 
    189         // Initialze with the value property in the options
    190         se.setContent(se.options.value || '');
    191 
    192         window.addEventListener('click', () => {
    193             if (!se.editor.contains(document.activeElement)) {
    194                 se.closeAllMenus();
    195             }
    196         });
    197 
    198         // Remove all link option popups on escape
    199         window.addEventListener('keydown', (e) => {
    200             if (e.key === 'Escape') {
    201                 [...se.body.querySelectorAll('.se-link-options')].forEach((o) => o.remove());
    202 
    203                 [...se.body.querySelectorAll('.se-image-options')].forEach((o) => o.remove());
    204             }
    205         });
    206 
    207         // Toolbar Hide
    208         if (se.options.toolbarHide) {
    209             // Hide the toolbar template if there is one
    210             se.toolbarTemplate && (se.toolbarTemplate.style.display = 'none');
    211 
    212             // Hide the toolbar options
    213             se.toolbarOptionsGroup.style.display = 'none';
    214 
    215             // Add the close class
    216             se.toolbar.classList.add('se-toolbar-close');
    217 
    218             // Bind the focus event to reopen the toolbar
    219             const bodyFocus = se.body.onfocus;
    220             se.body.onfocus = () => {
    221                 se.overflow();
    222                 se.openToolbar();
    223 
    224                 bodyFocus && bodyFocus();
    225             };
    226 
    227             // Bind the blur event close the toolbar
    228             const bodyBlur = se.body.onblur;
    229             se.body.onblur = () => {
    230                 bodyBlur && bodyBlur();
    231                 se.overflow();
    232 
    233                 // Do not close the toolbar is editor is active
    234                 setTimeout(() => {
    235                     if (
    236                         se.linkMenu.dataset.active !== 'true' &&
    237                         se.imageMenu.dataset.active !== 'true' &&
    238                         se.tableMenu.dataset.active !== 'true' &&
    239                         !se.isEditorInFocus()
    240                     ) {
    241                         se.closeToolbar();
    242                     }
    243                 }, 200);
    244             };
    245         } else {
    246             se.toolbar.style.boxShadow = '#ddd -1px 2px 3px 0px';
    247             se.toolbar.style.height = 'fit-content';
    248         }
    249 
    250         // Toolbar Options
    251         se.toolbarOptions.forEach((optionEl) => {
    252             // Execute Toolbar Commands
    253             const optionElClick = optionEl.onclick;
    254 
    255             // Bind the toolbar commands click hander
    256             optionEl.onclick = (e) => {
    257                 if (!se.browser.isSafari()) {
    258                     se.range = se.getRange();
    259                 }
    260 
    261                 // Get the document execute command
    262                 const command = optionEl.id.split('-').pop();
    263 
    264                 // Command Logic
    265                 switch (command) {
    266                     case 'bold':
    267                     case 'underline':
    268                     case 'italic':
    269                     case 'strikethrough':
    270                         // If active, deactive the command
    271                         if (optionEl.classList.contains('se-toolbar-option-active')) {
    272                             optionEl.classList.remove('se-toolbar-option-active');
    273 
    274                             // Save the range
    275                             se.setRange();
    276 
    277                             // Focus back into the body
    278                             se.body.focus();
    279 
    280                             // If the command is active, deactivate the command
    281                             document.queryCommandState(command) && se.executeCommand(command);
    282                         } else {
    283                             // Set the command active (body on focus will execute the command)
    284                             optionEl.classList.add('se-toolbar-option-active');
    285 
    286                             // Save the range
    287                             se.setRange();
    288 
    289                             // Focus back into the body
    290                             se.body.focus();
    291                         }
    292                         break;
    293                     case 'removeFormat':
    294                         se.executeCommand(command);
    295 
    296                         // Deactivate all toolbar options
    297                         se.toolbarOptions.forEach((o) => o.classList.remove('se-toolbar-option-active'));
    298 
    299                         break;
    300                     case 'indent':
    301                         setTimeout(() => se.setRange(se.range), 0);
    302                     default:
    303                         se.body.focus();
    304                         se.executeCommand(command);
    305                         break;
    306                 }
    307 
    308                 optionElClick && optionElClick();
    309             };
    310         });
    311 
    312         // Add dividers
    313         function constructDivider() {
    314             const divider = document.createElement('div');
    315             divider.classList.add('se-divider-section');
    316 
    317             const bar = document.createElement('div');
    318             bar.classList.add('se-divider-bar');
    319 
    320             divider.append(bar);
    321             return divider;
    322         }
    323 
    324         const areas = [...se.toolbarGroups, ...se.toolbar.querySelectorAll('.se-toolbar-selection')];
    325         areas.forEach((a) => {
    326             if (a.querySelector('.se-toolbar-option')) {
    327                 a.after(constructDivider());
    328             }
    329         });
    330 
    331         // Construct editor elements
    332         se.toolbar && se.editor.appendChild(se.toolbar);
    333         se.body && se.editor.appendChild(se.body);
    334         se.linkMenu && se.editor.appendChild(se.linkMenu);
    335         se.imageMenu && se.editor.appendChild(se.imageMenu);
    336         se.tableMenu && se.editor.appendChild(se.tableMenu);
    337         se.metaDataSection && se.editor.appendChild(se.metaDataSection);
    338         se.filesSection && se.editor.appendChild(se.filesSection);
    339 
    340         // Reposition Toolbar
    341         if (se.options.toolbarBottom) {
    342             se.toolbar.classList.add('se-toolbar-bottom');
    343             se.toolbar.classList.add('se-toolbar-top');
    344 
    345             se.linkMenu.classList.remove('se-popup-top');
    346             se.linkMenu.classList.add('se-popup-bottom');
    347 
    348             se.imageMenu.classList.remove('se-popup-top');
    349             se.imageMenu.classList.add('se-popup-bottom');
    350 
    351             se.tableMenu.classList.remove('se-popup-top');
    352             se.tableMenu.classList.add('se-popup-bottom');
    353 
    354             se.editor.removeChild(se.toolbar);
    355             se.editor.append(se.toolbar);
    356         }
    357 
    358         se.options.init && se.options.init(se);
    359     }
    360 
    361     /**
    362      * Open the toolbar for when the toolbarHide option is set to true
    363      */
    364     openToolbar() {
    365         const se = this;
    366 
    367         se.toolbar.classList.remove('se-toolbar-close');
    368         setTimeout(() => {
    369             se.toolbarOptionsGroup.style.display = 'flex';
    370             se.toolbarTemplate && (se.toolbarTemplate.style.display = 'flex');
    371         }, 200);
    372     }
    373     /**
    374      * Close the toolbar for when the toolbarHide option is set to true
    375      */
    376     closeToolbar() {
    377         const se = this;
    378 
    379         se.closeAllMenus();
    380         se.toolbarOptionsGroup.style.display = 'none';
    381         se.toolbarTemplate && (se.toolbarTemplate.style.display = 'none');
    382         se.toolbar.classList.add('se-toolbar-close');
    383     }
    384 
    385     /**
    386      * Initialized the toolbar for StrivenEditor
    387      * @returns {HTMLElement} The StrivenEditor toolbar
    388      */
    389     initToolbar() {
    390         const se = this;
    391 
    392         const toolbar = document.createElement('div');
    393         se.toolbarOptionsGroup = document.createElement('div');
    394         const groups = Object.keys(se.optionGroups);
    395 
    396         toolbar.classList.add('se-toolbar');
    397         toolbar.classList.add('toolbar-top');
    398 
    399         se.toolbarOptionsGroup.classList.add('se-toolbar-options');
    400 
    401         toolbar.onclick = (ev) => {
    402             se.body.focus();
    403         };
    404 
    405         // Append Font Options
    406         !se.options.minimal && se.initToolbarFontOptions();
    407 
    408         //iterate groups
    409         groups.forEach((group) => {
    410             // add menu to toolbarOptions
    411             const toolbarMenu = document.createElement('div');
    412             // const toolbarMenuIcon = document.createElement("i");
    413 
    414             toolbarMenu.classList.add('se-toolbar-menu');
    415             toolbarMenu.id = `menu-${group}`;
    416             toolbarMenu.setAttribute('data-name', group);
    417 
    418             // toolbarMenuIcon.classList.add(se.options.fontPack);
    419             // toolbarMenuIcon.classList.add(se.optionGroups[group].menu);
    420 
    421             const arrow = {
    422                 viewBox: '0 0 1792 1792',
    423                 d: 'M1395 736q0 13-10 23l-466 466q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l50-50q10-10 23-10t23 10l393 393 393-393q10-10 23-10t23 10l50 50q10 10 10 23z'
    424             };
    425 
    426             const svgSpan = se.constructSVG(se.optionGroups[group].menu);
    427             toolbarMenu.appendChild(svgSpan.getElementsByTagName('svg')[0]);
    428 
    429             if (group !== 'options') {
    430                 const arrowSpan = se.constructSVG(arrow);
    431                 arrowSpan.classList.add('se-arrow-span');
    432                 toolbarMenu.appendChild(arrowSpan);
    433             }
    434 
    435             se.toolbarOptionsGroup.appendChild(toolbarMenu);
    436 
    437             // add group to toolbarOptions
    438             const toolbarGroup = document.createElement('div');
    439 
    440             toolbarGroup.classList.add('se-toolbar-group');
    441             toolbarGroup.id = `group-${group}`;
    442 
    443             // iterate options within group
    444             se.options.toolbarOptions.forEach((option) => {
    445                 const toolbarOption = se.optionGroups[group].group.filter((group) => group[option])[0];
    446                 if (toolbarOption) {
    447                     const svgData = toolbarOption[option];
    448                     const optionSpan = se.constructSVG(svgData);
    449 
    450                     optionSpan.classList.add('se-toolbar-option');
    451                     optionSpan.id = `toolbar-${option}`;
    452                     optionSpan.title = denormalizeCamel(option);
    453                     optionSpan.setAttribute('data-group-name', group);
    454 
    455                     switch (option) {
    456                         case 'removeFormat':
    457                             optionSpan.setAttribute('title', 'Clear Format');
    458                             break;
    459                         case 'hiliteColor':
    460                             optionSpan.setAttribute('title', 'Background Color');
    461                             break;
    462                         default:
    463                             optionSpan.setAttribute('title', denormalizeCamel(option));
    464                             break;
    465                     }
    466                     toolbarGroup.appendChild(optionSpan);
    467                 }
    468             });
    469 
    470             se.toolbarOptionsGroup.appendChild(toolbarGroup);
    471         });
    472 
    473         toolbar.appendChild(se.toolbarOptionsGroup);
    474 
    475         // Custom toolbar template
    476         if (se.options.toolbarTemplate) {
    477             const toolbarTemplate = document.createElement('div');
    478             toolbarTemplate.id = 'toolbar-template';
    479             toolbarTemplate.setAttribute('style', 'display: flex');
    480             toolbarTemplate.appendChild(se.options.toolbarTemplate);
    481             toolbar.appendChild(toolbarTemplate);
    482 
    483             se.toolbarTemplate = toolbarTemplate;
    484         }
    485 
    486         se.toolbarOptions = toolbar.querySelectorAll('span');
    487         se.toolbarGroups = [...toolbar.getElementsByClassName('se-toolbar-group')];
    488         se.toolbarMenus = [...toolbar.getElementsByClassName('se-toolbar-menu')];
    489 
    490         // Remove menu that has no options enabled
    491         se.toolbarGroups.forEach((group) => {
    492             if (group && group.children.length < 1) {
    493                 const groupName = group.id.split('-')[1];
    494                 const menu = se.toolbarMenus.filter((menu) => menu && menu.id.split('-')[1] === groupName)[0];
    495                 menu.remove();
    496             }
    497         });
    498 
    499         const miscOptions = toolbar.querySelector('#group-options');
    500         // toolbar group for custom options
    501         const customOptions = se.options.toolbarOptions.filter((option) => typeof option === 'object');
    502         if (customOptions.length > 0) {
    503             customOptions.forEach((opt) => {
    504                 const { icon, handler, title } = opt;
    505 
    506                 if (typeof icon === 'object') {
    507                     const option = se.constructSVG({ viewBox: icon.viewBox, d: icon.d });
    508                     option.classList.add('se-toolbar-option');
    509 
    510                     option.onclick = () => handler(option);
    511                     option.setAttribute('id', `toolbar-${title}`);
    512                     option.setAttribute('title', denormalizeCamel(title));
    513 
    514                     miscOptions.appendChild(option);
    515                 } else {
    516                     const option = document.createElement('span');
    517                     const image = document.createElement('img');
    518                     image.setAttribute('src', opt.icon);
    519                     image.setAttribute('alt', 'custom option');
    520 
    521                     option.style.paddingTop = '6px';
    522                     option.style.paddingBottom = '8px';
    523                     option.classList.add('se-toolbar-option');
    524 
    525                     option.onclick = () => handler();
    526 
    527                     option.append(image);
    528                     miscOptions.appendChild(option);
    529                 }
    530             });
    531         }
    532 
    533         const removeFormatOption = toolbar.querySelector('#toolbar-removeFormat');
    534 
    535         if (removeFormatOption) {
    536             removeFormatOption.remove();
    537             miscOptions.append(removeFormatOption);
    538         }
    539 
    540         se.toolbarClick = false;
    541         toolbar.addEventListener('mousedown', () => {
    542             se.toolbarClick = true;
    543         });
    544 
    545         toolbar.addEventListener('mouseup', () => {
    546             se.toolbarClick = false;
    547         });
    548         return toolbar;
    549     }
    550 
    551     /*
    552      * Initializes the toolbars font options
    553      */
    554     initToolbarFontOptions() {
    555         const se = this;
    556 
    557         function initMenu(name, onOpen) {
    558             const menu = document.createElement('div');
    559             menu.setAttribute('id', `${name}-menu`);
    560             menu.classList.add('se-popup', se.options.toolbarBottom ? 'se-popup-bottom' : 'se-popup-top');
    561             menu.dataset.active = 'false';
    562 
    563             menu.open = () => {
    564                 se.closeAllMenus();
    565 
    566                 se.setMenuOffset(se.toolbar.querySelector(`#toolbar-${name}`), menu);
    567 
    568                 menu.classList.add('se-popup-open');
    569 
    570                 menu.dataset.active = 'true';
    571                 se.addPopupEscapeHandler();
    572 
    573                 onOpen && onOpen(menu);
    574             };
    575 
    576             menu.close = () => {
    577                 menu.classList.remove('se-popup-open');
    578                 menu.dataset.active = 'false';
    579                 se.removePopupEscapeHandler();
    580             };
    581 
    582             se.editor.append(menu);
    583             return menu;
    584         }
    585 
    586         function initFontNameMenu(select) {
    587             const menu = initMenu('fontName');
    588 
    589             menu.dataset.init = 'true';
    590             ['(inherited font)', ...se.options.fontNames].forEach((f) => {
    591                 const fontOption = document.createElement('div');
    592 
    593                 fontOption.classList.add('se-toolbar-popup-option');
    594                 fontOption.textContent = f;
    595                 fontOption.style.fontFamily = f;
    596 
    597                 const trigger = (e) => {
    598                     let fontselect = e.target.textContent;
    599                     select.textContent = fontselect;
    600                     menu.close();
    601 
    602                     function execute() {
    603                         if (fontselect === '(inherited font)') {
    604                             fontselect = getComputedStyle(se.body).fontFamily;
    605                         }
    606 
    607                         if (se.browser.isEdge() || se.browser.isFirefox()) {
    608                             document.execCommand('fontName', false, fontselect);
    609                         } else {
    610                             document.execCommand('fontName', true, fontselect);
    611                         }
    612                     }
    613 
    614                     execute();
    615 
    616                     const refocus = se.body.onfocus;
    617                     se.body.onfocus = () => {
    618                         se.setRange(se.range);
    619 
    620                         if (!se.getContent()) {
    621                             const enabler = () => {
    622                                 setTimeout(() => {
    623                                     execute();
    624                                     se.body.removeEventListener('keydown', enabler);
    625                                 });
    626                             };
    627 
    628                             se.body.addEventListener('keydown', enabler);
    629                         }
    630 
    631                         setTimeout(() => execute(), 0);
    632 
    633                         if (se.scrollPosition && !se.browser.isEdge()) {
    634                             se.body.scrollTo(se.scrollPosition.x, se.scrollPosition.y);
    635                         }
    636                         se.body.onfocus = refocus;
    637                     };
    638 
    639                     se.body.focus();
    640                 };
    641 
    642                 fontOption.onmousedown = trigger;
    643 
    644                 menu.append(fontOption);
    645             });
    646 
    647             return menu;
    648         }
    649 
    650         function initFontSizeMenu(select) {
    651             const menu = initMenu('fontSize');
    652 
    653             const sizes = FONTSIZES;
    654 
    655             ['(inherited size)', ...Object.keys(sizes)].forEach((size) => {
    656                 let s = sizes[size] || '(inherited size)';
    657 
    658                 const fontOption = document.createElement('div');
    659 
    660                 fontOption.classList.add('se-toolbar-popup-option');
    661                 fontOption.textContent = s;
    662 
    663                 function execute() {
    664                     let execSize = size;
    665 
    666                     if (size === '(inherited size)') {
    667                         execSize = 3;
    668                     }
    669 
    670                     if (se.browser.isEdge() || se.browser.isFirefox()) {
    671                         document.execCommand('fontSize', false, execSize);
    672                     } else {
    673                         document.execCommand('fontSize', true, execSize);
    674                     }
    675                 }
    676 
    677                 const trigger = (e) => {
    678                     const fontsize = e.target.textContent;
    679 
    680                     select.textContent = fontsize;
    681                     select.dataset.command = size;
    682 
    683                     menu.close();
    684 
    685                     execute();
    686 
    687                     const refocus = se.body.focus;
    688                     se.body.onfocus = () => {
    689                         se.setRange(se.range);
    690 
    691                         if (!se.getContent()) {
    692                             const enabler = () => {
    693                                 setTimeout(() => {
    694                                     execute();
    695                                     se.body.removeEventListener('keydown', enabler);
    696                                 }, 0);
    697                             };
    698 
    699                             se.body.addEventListener('keydown', enabler);
    700                         }
    701 
    702                         setTimeout(() => execute(), 0);
    703 
    704                         if (se.scrollPosition && !se.browser.isEdge()) {
    705                             se.body.scrollTo(se.scrollPosition.x, se.scrollPosition.y);
    706                         }
    707                         se.body.onfocus = refocus;
    708                     };
    709 
    710                     se.body.focus();
    711                 };
    712 
    713                 fontOption.onmousedown = trigger;
    714 
    715                 menu.append(fontOption);
    716             });
    717 
    718             return menu;
    719         }
    720 
    721         function initFontFormatMenu() {
    722             const menu = initMenu('fontFormat');
    723 
    724             const formats = [
    725                 {
    726                     command: 'H1',
    727                     option: '<h1 style="margin: 0; color: #000;">Heading 1</h1>'
    728                 },
    729                 {
    730                     command: 'H2',
    731                     option: '<h2 style="margin: 0; color: #000;">Heading 2</h2>'
    732                 },
    733                 {
    734                     command: 'H3',
    735                     option: '<h3 style="margin: 0; color: #000;">Heading 3</h4>'
    736                 },
    737                 {
    738                     command: 'H4',
    739                     option: '<h4 style="margin: 0; color: #000;">Heading 4</h4>'
    740                 },
    741                 {
    742                     command: 'H5',
    743                     option: '<h5 style="margin: 0; color: #000;">Heading 5</h5>'
    744                 },
    745                 {
    746                     command: 'H6',
    747                     option: '<h6 style="margin: 0; color: #000;">Heading 6</h6>'
    748                 },
    749                 {
    750                     command: 'P',
    751                     option: '<p style="margin: 0; color: #000;">Paragraph</p>'
    752                 }
    753             ];
    754 
    755             formats.forEach((s) => {
    756                 const fontOption = document.createElement('div');
    757 
    758                 fontOption.classList.add('se-toolbar-popup-option');
    759                 fontOption.innerHTML = s.option;
    760 
    761                 fontOption.onclick = (e) => {
    762                     menu.close();
    763                     se.body.focus();
    764                     se.setRange();
    765 
    766                     if (se.browser.isFirefox() || se.browser.isEdge()) {
    767                         document.execCommand('removeFormat', false);
    768                     } else {
    769                         document.execCommand('removeFormat', true);
    770                     }
    771 
    772                     se.executeCommand('formatBlock', s.command);
    773                 };
    774 
    775                 menu.append(fontOption);
    776             });
    777 
    778             return menu;
    779         }
    780 
    781         // Get enabled toolbar options
    782         const enabledOptions = se.options.toolbarOptions;
    783 
    784         // Enable font name option
    785         if (enabledOptions.includes('fontName')) {
    786             // Initialize and append toolbar option
    787             const fontSelect = document.createElement('div');
    788             const selectedFont = document.createElement('p');
    789 
    790             // Initialize the popup menu to be length of longest name
    791             const menu = initFontNameMenu(selectedFont);
    792 
    793             // Toggle the fontselect popup on the select click
    794             fontSelect.onclick = () => {
    795                 if (!se.browser.isSafari()) {
    796                     se.range = se.getRange();
    797                 }
    798 
    799                 if (menu.dataset.active === 'true') {
    800                     menu.close();
    801                 } else {
    802                     menu.open();
    803                 }
    804             };
    805 
    806             // Set the select to initialize on the first font name
    807             selectedFont.textContent = '(inherited font)';
    808 
    809             fontSelect.setAttribute('id', 'toolbar-fontName');
    810 
    811             fontSelect.classList.add('se-toolbar-selection');
    812             selectedFont.classList.add('se-toolbar-option');
    813 
    814             fontSelect.append(selectedFont);
    815             se.toolbarOptionsGroup.append(fontSelect);
    816             se.fontName = selectedFont;
    817         }
    818 
    819         // Enable font size option
    820         if (enabledOptions.includes('fontSize')) {
    821             const fontSizeSelect = document.createElement('div');
    822             const selectedFontSize = document.createElement('p');
    823             const menu = initFontSizeMenu(selectedFontSize);
    824 
    825             fontSizeSelect.onclick = () => {
    826                 if (!se.browser.isSafari()) {
    827                     se.range = se.getRange();
    828                 }
    829 
    830                 if (menu.dataset.active === 'true') {
    831                     menu.close();
    832                 } else {
    833                     menu.open();
    834                 }
    835             };
    836 
    837             fontSizeSelect.setAttribute('id', 'toolbar-fontSize');
    838             selectedFontSize.textContent = '(inherited size)';
    839 
    840             fontSizeSelect.classList.add('se-toolbar-selection');
    841             selectedFontSize.classList.add('se-toolbar-option');
    842 
    843             fontSizeSelect.append(selectedFontSize);
    844             se.toolbarOptionsGroup.append(fontSizeSelect);
    845             se.fontSize = selectedFontSize;
    846         }
    847 
    848         if (enabledOptions.includes('fontFormat')) {
    849             const fontFormatSelect = document.createElement('div');
    850             const selectedFontFormat = document.createElement('p');
    851             const menu = initFontFormatMenu();
    852 
    853             fontFormatSelect.onclick = () => {
    854                 if (!se.browser.isSafari()) {
    855                     se.range = se.getRange();
    856                 }
    857 
    858                 if (menu.dataset.active === 'true') {
    859                     menu.close();
    860                 } else {
    861                     menu.open();
    862                 }
    863             };
    864 
    865             fontFormatSelect.setAttribute('id', 'toolbar-fontFormat');
    866             selectedFontFormat.textContent = 'Format';
    867 
    868             fontFormatSelect.classList.add('se-toolbar-selection');
    869             selectedFontFormat.classList.add('se-toolbar-option');
    870 
    871             fontFormatSelect.append(selectedFontFormat);
    872             se.toolbarOptionsGroup.append(fontFormatSelect);
    873         }
    874     }
    875 
    876     /**
    877      * Initialized the StrivenEditor body
    878      * @returns {HTMLElement} The StrivenEditor body
    879      */
    880     initBody() {
    881         const se = this;
    882         const body = document.createElement('div');
    883 
    884         body.classList.add('se-body');
    885         body.contentEditable = 'true';
    886         body.style.height = se.editor.style.height;
    887         body.style.minHeight = se.editor.style.minHeight;
    888         body.style.maxHeight = se.editor.style.maxHeight;
    889 
    890         se.editor.setAttribute('height', se.editor.style.height);
    891         se.editor.setAttribute('min-height', se.editor.style.minHeight);
    892         se.editor.setAttribute('max-height', se.editor.style.maxHeight);
    893 
    894         se.editor.style.height = 'auto';
    895         se.editor.style.minHeight = 'auto';
    896         se.editor.style.maxHeight = 'auto';
    897 
    898         se.options.placeholder && (body.dataset.placeholder = se.options.placeholder);
    899 
    900         se._bindContenteditableOnChange(body);
    901 
    902         // Execute this function on mouseup and keyup
    903         const execRange = () => {
    904             const current = se.getRange();
    905             if (current) {
    906                 se.range = current;
    907             }
    908         };
    909 
    910         // Paste Handler
    911         body.onpaste = (e) => {
    912             // Editor Paste Handler
    913             if (se.options.onPaste) {
    914                 const content = se.options.onPaste(e);
    915                 if (content) {
    916                     e.preventDefault();
    917                     se.executeCommand('insertHTML', content);
    918                     return true;
    919                 }
    920             }
    921 
    922             const afterPaste = () => {
    923                 // After the paste
    924                 setTimeout(() => {
    925                     // Editor After Paste Handler
    926                     se.options.afterPaste && se.options.afterPaste(e);
    927                 }, 10);
    928 
    929                 se.overflow();
    930             };
    931 
    932             // Paste image logic
    933             if (e.clipboardData.files && e.clipboardData.files.length > 0 ) {
    934                 e.preventDefault();
    935                 
    936                 se.insertImages(e.clipboardData.files)
    937                 .catch((ex) => {
    938                     console.error(ex);
    939                 })
    940                 .finally(() => {
    941                     afterPaste();
    942                 });
    943 
    944                 return true;
    945             }
    946 
    947             // pasting text content
    948             if (e.clipboardData.items && e.clipboardData.items.length > 0 && e.clipboardData.items[0].type === 'text/plain') {
    949                 let plainText = e.clipboardData.getData('text/plain');
    950 
    951                 if (se.validURL(plainText.trim())) {
    952                     // get meta data
    953                     if (se.options.metaUrl) {
    954                         se.getMeta(plainText).then((res) => {
    955                             const { url, title, image, description } = res;
    956                             url && title && image && se.createMetaDataElement(url, image, title, description);
    957                         });
    958                     }
    959                 }
    960             }
    961 
    962             let pastedHTML = false;
    963             if (e.clipboardData.types.includes('text/html')) {
    964                 //get the html
    965                 pastedHTML = e.clipboardData.getData('text/html');
    966             }
    967 
    968             // Wrap pasted link content for resetting the range
    969             if (pastedHTML) {
    970                 e.preventDefault();
    971 
    972                 let pasteNode = document.createElement('span');
    973                 pasteNode.innerHTML = pastedHTML;
    974 
    975                 //cleanup styles
    976                 this.pruneInlineStyles(pasteNode);
    977 
    978                 //cleanup css classes
    979                 this.cleanCss(pasteNode);
    980 
    981                 //sanitize
    982                 if (se.options.sanitizePaste) {
    983                     pasteNode = this.scrubHTML(pasteNode);
    984                 }
    985 
    986                 pasteNode.setAttribute('class', 'se-pasted-content');
    987                 se.executeCommand('insertHTML', pasteNode.innerHTML);
    988             }
    989 
    990             afterPaste();
    991         };
    992 
    993         body.onkeydown = (e) => {
    994             switch (e.key) {
    995                 case 'Tab':
    996                     if (se.options.canTab) {
    997                         e.shiftKey ? se.executeCommand('outdent') : se.executeCommand('indent');
    998                         e.preventDefault();
    999                     }
   1000                     break;
   1001                 case 'Shift':
   1002                     break;
   1003                 case 'Backspace':
   1004                     se.textBuffer && (se.textBuffer = se.textBuffer.substring(0, se.textBuffer.length - 1));
   1005                     break;
   1006                 case 'Control':
   1007                     break;
   1008 
   1009                 case 'Semicolon':
   1010                     if (e.shiftKey) {
   1011                         se.textBuffer ? (se.textBuffer += ':') : (se.textBuffer = ':');
   1012                     }
   1013                     break;
   1014                 default:
   1015                     se.textBuffer ? (se.textBuffer += e.key) : (se.textBuffer = e.key);
   1016                     break;
   1017             }
   1018         };
   1019 
   1020         // State of the editor
   1021         const bodyKeyup = body.onkeyup;
   1022         body.onkeyup = (e) => {
   1023             bodyKeyup && bodyKeyup();
   1024             execRange();
   1025 
   1026             if (e.key) {
   1027                 switch (e.key) {
   1028                     case 'Enter':
   1029                         se.options.onEnter && se.options.onEnter(e);
   1030                         break;
   1031                     default:
   1032                         break;
   1033                 }
   1034             }
   1035 
   1036             se.setFontStates();
   1037             se.toolbarState();
   1038         };
   1039 
   1040         // addEventListener('keyup', (e) => {
   1041         //   const tab = (e.key === 'Tab' || e.keyCode === 9);
   1042         //   if (tab && document.activeElement === se.body) {
   1043         //     if (se.body.textContent.trim() === '') {
   1044         //       const r = se.getRange();
   1045 
   1046         //       if (r) {
   1047         //         const selNode = document.createElement('span');
   1048         //         selNode.innerHTML = '&nbsp;';
   1049         //         se.body.append(selNode);
   1050 
   1051         //         r.selectNode(selNode);
   1052         //         r.collapse();
   1053         //       }
   1054 
   1055         //     } else {
   1056         //       const r = se.getRange();
   1057 
   1058         //       if (r) {
   1059         //         r.selectNodeContents(se.body);
   1060         //         r.collapse();
   1061         //       }
   1062         //     }
   1063         //   }
   1064 
   1065         //   if (tab && document.activeElement !== se.body && se.body.textContent.trim() === '') {
   1066         //     se.clearContent();
   1067         //   }
   1068         // });
   1069 
   1070         const bodyFocus = body.onfocus;
   1071         body.onfocus = (e) => {
   1072             !se.browser.isEdge() && se.setRange();
   1073 
   1074             window.addEventListener('mouseup', execRange);
   1075 
   1076             se.editor.classList.add('se-focus');
   1077 
   1078             if (se.body.textContent.trim() === '') {
   1079                 const selNode = document.createTextNode('');
   1080                 se.body.append(selNode);
   1081 
   1082                 setTimeout(() => {
   1083                     se.placeCaretAtEnd(se.body);
   1084                     selNode.remove();    
   1085                 }, 0);
   1086                                 
   1087             }
   1088 
   1089             if (se.scrollPosition && !se.browser.isEdge()) {
   1090                 body.scrollTo(se.scrollPosition);
   1091             }
   1092 
   1093             bodyFocus && bodyFocus();
   1094         };
   1095 
   1096         // Bind state management event
   1097         body.addEventListener('focus', () => {
   1098             // disables all states
   1099             se.options.toolbarOptions.forEach((opt) => {
   1100                 if (typeof opt === 'string') {
   1101                     if (document.queryCommandState('insertUnorderedList') && opt === 'insertUnorderedList') {
   1102                         return false;
   1103                     }
   1104                     if (document.queryCommandState('insertOrderedList') && opt === 'insertOrderedList') {
   1105                         return false;
   1106                     }
   1107 
   1108                     document.queryCommandState(opt) && se.executeCommand(opt);
   1109                 }
   1110             });
   1111 
   1112             // enable only active states
   1113             se.getActiveOptions().forEach((opt) => {
   1114                 !document.queryCommandState(opt) && se.executeCommand(opt);
   1115             });
   1116         });
   1117 
   1118         const bodyBlur = body.onblur;
   1119         body.onblur = (e) => {
   1120             se.editor.classList.remove('se-focus');
   1121 
   1122             window.removeEventListener('mouseup', execRange);
   1123 
   1124             se.scrollPosition = {
   1125                 y: body.scrollTop,
   1126                 x: body.scrollWidth
   1127             };
   1128 
   1129             se.textBuffer = null;
   1130 
   1131             se.clearLinksToEdit();
   1132             se.clearImagesToEdit();
   1133 
   1134             bodyBlur && bodyBlur();
   1135         };
   1136 
   1137         const bodyClick = body.onclick;
   1138         body.onclick = (event) => {
   1139             se.closeAllMenus();
   1140             se.setFontStates();
   1141             body.textContent && se.toolbarState();
   1142 
   1143             se.handleImageClick(event.target);
   1144 
   1145             bodyClick && bodyClick();
   1146         };
   1147 
   1148         return body;
   1149     }
   1150 
   1151     /**
   1152      * Intializes the StrivenEditor link menu popup
   1153      * @returns {HTMLElement} The StrivenEditor link menu
   1154      */
   1155     initLinkMenu() {
   1156         const se = this;
   1157 
   1158         const linkMenu = document.createElement('div');
   1159         const linkMenuHeader = document.createElement('p');
   1160         const linkMenuForm = document.createElement('div');
   1161         const linkMenuButtons = document.createElement('div');
   1162         const linkMenuButton = document.createElement('button');
   1163         const linkMenuCloseButton = document.createElement('button');
   1164         const linkMenuFormLabel = document.createElement('p');
   1165         const linkMenuFormInput = document.createElement('input');
   1166         const linkMenuCheck = document.createElement('input');
   1167 
   1168         function resetInput() {
   1169             linkMenuFormInput.value = 'http://';
   1170         }
   1171 
   1172         linkMenu.id = 'link-menu';
   1173         linkMenu.classList.add('se-popup', 'se-popup-top');
   1174         linkMenu.dataset.active = 'false';
   1175 
   1176         linkMenuForm.classList.add('se-popup-form');
   1177 
   1178         linkMenuFormLabel.classList.add('se-form-label');
   1179         linkMenuFormLabel.textContent = 'URL';
   1180 
   1181         linkMenuFormInput.classList.add('se-form-input');
   1182         se.options.useBootstrap && linkMenuFormInput.classList.add('form-control');
   1183         linkMenuFormInput.type = 'text';
   1184         linkMenuFormInput.placeholder = 'Insert a Link';
   1185 
   1186         resetInput();
   1187 
   1188         linkMenuButton.type = 'button';
   1189         linkMenuCloseButton.type = 'button';
   1190 
   1191         linkMenuButtons.classList.add('se-popup-button-container');
   1192 
   1193         linkMenuButton.classList.add('se-popup-button', 'se-button-primary');
   1194         linkMenuButton.textContent = 'Insert';
   1195 
   1196         linkMenuCloseButton.classList.add('se-popup-button', 'se-button-secondary');
   1197         linkMenuCloseButton.textContent = 'Close';
   1198 
   1199         linkMenuButton.onclick = (e) => {
   1200             const linkValue = linkMenuFormInput.value;
   1201             se.body.focus();
   1202             se.setRange();
   1203             if (linkValue) {
   1204                 const linkToEdit = se.body.querySelector('.se-link-to-edit');
   1205 
   1206                 if (linkToEdit) {
   1207                     linkToEdit.setAttribute('href', linkValue);
   1208                     linkToEdit.innerText = textRowInput.value || linkValue;
   1209                     linkToEdit.classList.remove('se-link-to-edit');
   1210                     linkToEdit.setAttribute('target', windowRowInput.checked ? '_blank' : '');
   1211                     linkToEdit.setAttribute('contenteditable', true);
   1212                     se.makeLinksClickable([linkToEdit]);
   1213                 } else if (!se.body.textContent.trim()) {
   1214                     const linkToCreate = document.createElement('a');
   1215                     linkToCreate.setAttribute('href', linkValue);
   1216                     linkToCreate.innerText = textRowInput.value || linkValue;
   1217                     linkToCreate.setAttribute('contenteditable', true);
   1218                     linkToCreate.setAttribute('target', windowRowInput.checked ? '_blank' : '');
   1219                     se.body.append(linkToCreate);
   1220                     se.makeLinksClickable([linkToCreate]);
   1221                 }
   1222 
   1223                 if (se.options.metaUrl && se.validURL(linkValue)) {
   1224                     se.getMeta(linkValue).then((res) => {
   1225                         const { url, image, title, description } = res;
   1226                         url && image && title && se.createMetaDataElement(url, image, title, description);
   1227                     });
   1228                 }
   1229 
   1230                 // trigger input event
   1231                 let inpEvent = new Event('input', { cancelable: true, bubbles: true });
   1232                 se.body.dispatchEvent(inpEvent);
   1233 
   1234                 se.closeLinkMenu();
   1235             } else {
   1236                 se.body.focus();
   1237                 se.closeLinkMenu();
   1238             }
   1239 
   1240             resetInput();
   1241         };
   1242 
   1243         linkMenuCloseButton.onclick = (e) => {
   1244             se.body.focus();
   1245             se.closeLinkMenu();
   1246             resetInput();
   1247         };
   1248 
   1249         linkMenuHeader.classList.add('se-popup-header');
   1250         linkMenuHeader.innerText = 'Insert Link';
   1251 
   1252         linkMenu.appendChild(linkMenuHeader);
   1253 
   1254         linkMenuForm.appendChild(linkMenuFormLabel);
   1255         linkMenuForm.appendChild(linkMenuFormInput);
   1256 
   1257         const textRow = linkMenuForm.cloneNode(true);
   1258         const textRowLabel = textRow.querySelector('.se-form-label');
   1259         const textRowInput = textRow.querySelector('.se-form-input');
   1260 
   1261         if (textRowLabel) {
   1262             textRowLabel.innerText = 'Text';
   1263         }
   1264 
   1265         if (textRowInput) {
   1266             textRowInput.value = '';
   1267             textRowInput.placeholder = 'Text content';
   1268         }
   1269 
   1270         const windowRow = linkMenuForm.cloneNode(true);
   1271         const windowRowLabel = windowRow.querySelector('.se-form-label');
   1272         const windowRowInput = windowRow.querySelector('.se-form-input');
   1273 
   1274         if (windowRow) {
   1275             windowRow.setAttribute('style', 'justify-content: flex-end; align-items: center; flex-direction: row-reverse');
   1276         }
   1277 
   1278         if (windowRowLabel) {
   1279             windowRowLabel.innerText = 'Open in new window';
   1280             windowRowLabel.style.marginLeft = '5px';
   1281         }
   1282 
   1283         if (windowRowInput) {
   1284             windowRowInput.checked = true;
   1285             windowRowInput.setAttribute('type', 'checkbox');
   1286             windowRowInput.setAttribute('style', 'width: auto');
   1287         }
   1288 
   1289         linkMenu.appendChild(linkMenuForm);
   1290         linkMenu.appendChild(textRow);
   1291         linkMenu.appendChild(windowRow);
   1292 
   1293         linkMenuButtons.appendChild(linkMenuButton);
   1294         linkMenuButtons.appendChild(linkMenuCloseButton);
   1295 
   1296         linkMenu.appendChild(linkMenuButtons);
   1297 
   1298         [...linkMenu.getElementsByTagName('input')].forEach((inp) => {
   1299             inp.onkeydown = (e) => {
   1300                 if (e.key === 'Enter') {
   1301                     e.preventDefault();
   1302                 }
   1303             };
   1304 
   1305             inp.onblur = () => {
   1306                 setTimeout(() => se.clearLinksToEdit(), 200);
   1307             };
   1308         });
   1309 
   1310         return linkMenu;
   1311     }
   1312 
   1313     /**
   1314      * Initializes the StrivenEditor image menu popup
   1315      * @returns {HTMLElement} The StrivenEditor image menu
   1316      */
   1317     initImageMenu() {
   1318         const se = this;
   1319 
   1320         const imageMenu = document.createElement('div');
   1321         const imageMenuHeader = document.createElement('div');
   1322         // Upload tab button
   1323         const imageMenuUploadTabButton = document.createElement('button');
   1324         imageMenuUploadTabButton.classList.add('se-tab-button', 'se-tab-button-upload', 'tab-button-active');
   1325         imageMenuUploadTabButton.type = 'button';
   1326         imageMenuUploadTabButton.tabIndex = 1;
   1327         // Link tab button
   1328         const imageMenuLinkTabButton = document.createElement('button');
   1329         imageMenuLinkTabButton.classList.add('se-tab-button', 'se-tab-button-link');
   1330         imageMenuLinkTabButton.type = 'button';
   1331         imageMenuUploadTabButton.tabIndex = 2;
   1332 
   1333         // Image Menu Tabs
   1334         const imageMenuUploadTab = document.createElement('div');
   1335         imageMenuUploadTab.classList.add('se-image-menu-tab', 'se-image-menu-upload-tab');
   1336 
   1337         const imageMenuLinkTab = document.createElement('div');
   1338         imageMenuLinkTab.classList.add('se-image-menu-tab', 'se-image-menu-link-tab');
   1339         imageMenuLinkTab.style.display = 'none';
   1340 
   1341         // Upload form inputs
   1342         const imageMenuUploadInput = document.createElement('input');
   1343         imageMenuUploadInput.type = 'file';
   1344         imageMenuUploadInput.accept = 'image/jpeg,image/webp,image/gif,image/png,image/svg+xml,image/bmp,image/x-icon';
   1345         imageMenuUploadInput.multiple = true;
   1346         imageMenuUploadInput.style.display = 'none';
   1347 
   1348         // Drop zone
   1349         const imageMenuUploadDropZone = document.createElement('div');
   1350         imageMenuUploadDropZone.classList.add('se-file-drop-dropzone');
   1351 
   1352         const imageMenuUploadDropZoneText = document.createElement('p');
   1353         imageMenuUploadDropZoneText.textContent = 'Click to upload OR drag and drop images here';
   1354         imageMenuUploadDropZone.appendChild(createSVG(UPLOADICON, undefined, '48px', '48px'));
   1355         imageMenuUploadDropZone.appendChild(imageMenuUploadDropZoneText);
   1356 
   1357         // Link form inputs
   1358         const imageMenuForm = document.createElement('div');
   1359         const imageMenuButtons = document.createElement('div');
   1360         const imageInsertButton = document.createElement('button');
   1361         const imageMenuCloseButton = document.createElement('button');
   1362         const imageMenuFormLabel = document.createElement('p');
   1363         const imageMenuFormSourceInput = document.createElement('input');
   1364 
   1365         imageMenu.id = 'image-menu';
   1366         imageMenu.classList.add('se-popup', 'se-popup-top');
   1367         imageMenu.dataset.active = 'false';
   1368 
   1369         imageMenuForm.classList.add('se-popup-form');
   1370 
   1371         imageMenuFormLabel.classList.add('se-form-label');
   1372         imageMenuFormLabel.textContent = 'Image URL';
   1373 
   1374         // Set up image URL input field
   1375         imageMenuFormSourceInput.classList.add('se-form-input');
   1376         se.options.useBootstrap && imageMenuFormSourceInput.classList.add('form-control');
   1377 
   1378         imageMenuFormSourceInput.type = 'text';
   1379         imageMenuFormSourceInput.placeholder = 'Insert a Link';
   1380 
   1381         // Set up the buttons for the image form
   1382         imageMenuButtons.classList.add('se-popup-button-container');
   1383         // Set types
   1384         imageInsertButton.type = 'button';
   1385         imageMenuCloseButton.type = 'button';
   1386 
   1387         // Insert button
   1388         imageInsertButton.classList.add('se-popup-button', 'se-button-primary', 'se-image-insert-button');
   1389         imageInsertButton.tabIndex = 0;
   1390         imageInsertButton.textContent = 'Insert Image';
   1391 
   1392         // Close Button
   1393         imageMenuCloseButton.classList.add('se-popup-button', 'se-button-secondary');
   1394         imageMenuCloseButton.textContent = 'Close';
   1395 
   1396         // Add the label and input fields to a div. This will get cloned for the input fields
   1397         // like width and height.
   1398         imageMenuForm.appendChild(imageMenuFormLabel);
   1399         imageMenuForm.appendChild(imageMenuFormSourceInput);
   1400 
   1401         // Height Input Form
   1402         const imageMenuHeightForm = imageMenuForm.cloneNode(true);
   1403         const imageMenuHeightFormInput = imageMenuHeightForm.querySelector('input');
   1404         const imageMenuHeightFormLabel = imageMenuHeightForm.querySelector('p');
   1405 
   1406         imageMenuHeightFormInput.placeholder = 'Image Height';
   1407         imageMenuHeightFormLabel.textContent = 'Height (px)';
   1408 
   1409         // Width Input Form
   1410         const imageMenuWidthForm = imageMenuForm.cloneNode(true);
   1411         const imageMenuWidthFormInput = imageMenuWidthForm.querySelector('input');
   1412         const imageMenuWidthFormLabel = imageMenuWidthForm.querySelector('p');
   1413 
   1414         imageMenuWidthFormInput.placeholder = 'Image Width';
   1415         imageMenuWidthFormLabel.textContent = 'Width (px)';
   1416 
   1417         // Set up alternate text input
   1418         const imageMenuAltTextForm = imageMenuForm.cloneNode(true);
   1419         const imageMenuAltTextInput = imageMenuAltTextForm.querySelector('input');
   1420         const imageMenuAltTextLabel = imageMenuAltTextForm.querySelector('p');
   1421 
   1422         imageMenuAltTextInput.placeholder = 'Image Description';
   1423         imageMenuAltTextLabel.textContent = 'Alternate Text';
   1424 
   1425         // Set up title text input
   1426         const imageMenuTitleForm = imageMenuForm.cloneNode(true);
   1427         const imageMenuTitleInput = imageMenuTitleForm.querySelector('input');
   1428         const imageMenuTitleLabel = imageMenuTitleForm.querySelector('p');
   1429 
   1430         imageMenuTitleInput.placeholder = 'Tooltip Text';
   1431         imageMenuTitleLabel.textContent = 'Title';
   1432 
   1433         const clearImageMenuInputs = function () {
   1434             // Clear the inputs
   1435             imageMenuFormSourceInput.value = '';
   1436             imageMenuAltTextInput.value = '';
   1437             imageMenuTitleInput.value = '';
   1438             imageMenuHeightFormInput.value = '';
   1439             imageMenuWidthFormInput.value = '';
   1440 
   1441             // Clear the files from the file input
   1442             imageMenuUploadInput.value = '';
   1443         };
   1444 
   1445         // Register click handlers
   1446 
   1447         // Create an event handler for upload tab click that will show the upload tab
   1448         imageMenuUploadTabButton.onclick = (e) => {
   1449             // Hide the link tab
   1450             imageMenuLinkTab.style.display = 'none';
   1451             // Show the upload tab
   1452             imageMenuUploadTab.style.display = 'block';
   1453             // Make this tab active
   1454             imageMenuUploadTabButton.classList.add('tab-button-active');
   1455             // Remove the active class from the link tab
   1456             imageMenuLinkTabButton.classList.remove('tab-button-active');
   1457             // Prevent event from bubbling up
   1458             e.stopPropagation();
   1459         };
   1460 
   1461         // Create an event handler for the link tab click that will show the link tab
   1462         imageMenuLinkTabButton.onclick = (e) => {
   1463             // Hide the upload tab
   1464             imageMenuUploadTab.style.display = 'none';
   1465             // Show the link tab
   1466             imageMenuLinkTab.style.display = 'block';
   1467             // Make this tab active
   1468             imageMenuLinkTabButton.classList.add('tab-button-active');
   1469             // Remove the active class from the upload tab
   1470             imageMenuUploadTabButton.classList.remove('tab-button-active');
   1471             // Prevent event from bubbling up
   1472             e.stopPropagation();
   1473         };
   1474 
   1475         // Create an event handler for when the images are selected
   1476         imageMenuUploadInput.onchange = (e) => {
   1477             // Clean up
   1478             se.closeImageMenu();
   1479 
   1480             // Get the files that were selected
   1481             const files = e.target.files;
   1482 
   1483             // For each file, get the data url and insert the image
   1484             se.insertImages(files)
   1485             .then(() => {
   1486                 // Clear the inputs
   1487                 clearImageMenuInputs();
   1488             })
   1489             .catch((ex) => {
   1490                 console.error(ex);
   1491             });
   1492         };
   1493 
   1494         // When clicking on the dropzone, trigger the file input
   1495         imageMenuUploadDropZone.onclick = (e) => {
   1496             se.body.focus();
   1497             // Trigger the file input
   1498             imageMenuUploadInput.click();
   1499         };
   1500 
   1501         // Hook up dropzone events
   1502         imageMenuUploadDropZone.ondragover = (e) => {
   1503             e.preventDefault();
   1504 
   1505             imageMenuUploadDropZone.classList.add('dropzone-hot');
   1506         };
   1507 
   1508         imageMenuUploadDropZone.ondragleave = (e) => {
   1509             e.preventDefault();
   1510 
   1511             imageMenuUploadDropZone.classList.remove('dropzone-hot');
   1512         };
   1513 
   1514         imageMenuUploadDropZone.ondrop = (e) => {
   1515             e.preventDefault();
   1516 
   1517             imageMenuUploadDropZone.classList.remove('dropzone-hot');
   1518 
   1519             // Clean up
   1520             se.closeImageMenu();
   1521 
   1522             const files = e.dataTransfer.files;
   1523             // For each file, get the data url and insert the image
   1524             se.insertImages(files)
   1525             .then(() => {
   1526                 // Clear the inputs
   1527                 clearImageMenuInputs();
   1528             })
   1529             .catch((ex) => {
   1530                 console.error(ex);
   1531             });
   1532         };
   1533 
   1534         // Insert image button click event
   1535         imageInsertButton.onclick = (e) => {
   1536             se.body.focus();
   1537             se.setRange();
   1538 
   1539             // Get the values of the input fields
   1540             const linkValue = imageMenuFormSourceInput.value;
   1541             const altTextValue = imageMenuAltTextInput.value;
   1542             const titleValue = imageMenuTitleInput.value;
   1543             const heightValue = imageMenuHeightFormInput.value;
   1544             const widthValue = imageMenuWidthFormInput.value;
   1545 
   1546             // Check if we are inserting a new image or editing an existing one
   1547             let imageToEdit = se.body.querySelector('.se-image-to-edit');
   1548 
   1549             // Link value may be left blank or isn't set because it is a data url image
   1550             if (linkValue) {
   1551                 if (!imageToEdit) {
   1552                     // No editing image found, so this is an insert. Insert the image.
   1553                     if (se.browser.isFirefox() || se.browser.isEdge()) {
   1554                         document.execCommand('insertImage', false, linkValue);
   1555                     } else {
   1556                         document.execCommand('insertImage', true, linkValue);
   1557                     }
   1558 
   1559                     // Get the image we just inserted by querying the img tags and looking for the one
   1560                     // that matches the image url.
   1561                     let insertedImages = [...se.body.querySelectorAll(`img`)].filter((img) => img.src === linkValue);
   1562                     // Get the last one that was added
   1563                     imageToEdit = insertedImages[insertedImages.length - 1];
   1564                 } else {
   1565                     // This is an image that we are editing, update the src attribute
   1566                     imageToEdit.classList.remove('se-image-to-edit');
   1567                     imageToEdit.setAttribute('src', `${linkValue}`);
   1568                 }
   1569             }
   1570 
   1571             // Add / update the attributes for the image
   1572             if (imageToEdit && (linkValue || imageToEdit.dataset.dataUrl)) {
   1573                 // Add the attributes for the image
   1574                 imageToEdit.setAttribute('height', `${heightValue}px`);
   1575                 imageToEdit.setAttribute('width', `${widthValue}px`);
   1576                 imageToEdit.setAttribute('alt', `${altTextValue}`);
   1577                 imageToEdit.setAttribute('title', `${titleValue}`);
   1578             }
   1579 
   1580             // Call se.overflow in set timeout
   1581             setTimeout(() => {
   1582                 se.overflow();
   1583             }, 100);
   1584             // Clear the inputs
   1585             clearImageMenuInputs();
   1586             // Focus the body
   1587             se.body.focus();
   1588             // Clean up
   1589             se.closeImageMenu();
   1590         };
   1591 
   1592         imageMenuCloseButton.onclick = (e) => {
   1593             se.body.focus();
   1594             se.closeImageMenu();
   1595             clearImageMenuInputs();
   1596         };
   1597 
   1598         // Set the tab text
   1599         imageMenuUploadTabButton.textContent = 'Upload';
   1600         imageMenuLinkTabButton.textContent = 'Image URL';
   1601 
   1602         // Add the tabs for the image menu
   1603         imageMenuHeader.appendChild(imageMenuUploadTabButton);
   1604         imageMenuHeader.appendChild(imageMenuLinkTabButton);
   1605 
   1606         imageMenu.appendChild(imageMenuHeader);
   1607 
   1608         // Add the fields to the image form
   1609         imageMenuLinkTab.appendChild(imageMenuForm);
   1610         imageMenuLinkTab.appendChild(imageMenuAltTextForm);
   1611         imageMenuLinkTab.appendChild(imageMenuTitleForm);
   1612         imageMenuLinkTab.appendChild(imageMenuWidthForm);
   1613         imageMenuLinkTab.appendChild(imageMenuHeightForm);
   1614 
   1615         // Add the buttons
   1616         imageMenuButtons.appendChild(imageInsertButton);
   1617         imageMenuButtons.appendChild(imageMenuCloseButton);
   1618 
   1619         imageMenuLinkTab.appendChild(imageMenuButtons);
   1620 
   1621         imageMenu.appendChild(imageMenuLinkTab);
   1622 
   1623         // Build the upload form
   1624         imageMenuUploadTab.appendChild(imageMenuUploadInput);
   1625         imageMenuUploadTab.appendChild(imageMenuUploadDropZone);
   1626         imageMenu.appendChild(imageMenuUploadTab);
   1627 
   1628         [...imageMenu.getElementsByTagName('input')].forEach((inp) => {
   1629             inp.onkeydown = (e) => {
   1630                 if (e.key === 'Enter') {
   1631                     e.preventDefault();
   1632                     imageInsertButton.click();
   1633                 }
   1634             };
   1635         });
   1636         return imageMenu;
   1637     }
   1638 
   1639     initTableMenu() {
   1640         const se = this;
   1641 
   1642         const tableMenu = document.createElement('div');
   1643         const tableMenuHeader = document.createElement('p');
   1644         const tableMenuForm = document.createElement('div');
   1645         const tableMenuButtons = document.createElement('div');
   1646         const tableMenuButton = document.createElement('button');
   1647         const tableMenuCloseButton = document.createElement('button');
   1648         const tableMenuFormLabel = document.createElement('p');
   1649         const tableMenuFormColsInput = document.createElement('input');
   1650 
   1651         tableMenu.id = 'table-menu';
   1652         tableMenu.classList.add('se-popup', 'se-popup-top');
   1653         tableMenu.dataset.active = 'false';
   1654 
   1655         tableMenuForm.classList.add('se-popup-form');
   1656 
   1657         tableMenuFormLabel.classList.add('se-form-label');
   1658         tableMenuFormLabel.textContent = 'Columns';
   1659 
   1660         tableMenuFormColsInput.classList.add('se-form-input');
   1661         se.options.useBootstrap && tableMenuFormColsInput.classList.add('form-control');
   1662 
   1663         tableMenuFormColsInput.type = 'text';
   1664         tableMenuFormColsInput.placeholder = 'Table Columns';
   1665 
   1666         tableMenuButtons.classList.add('se-popup-button-container');
   1667 
   1668         tableMenuButton.type = 'button';
   1669         tableMenuCloseButton.type = 'button';
   1670 
   1671         tableMenuButton.classList.add('se-popup-button', 'se-button-primary');
   1672         tableMenuCloseButton.classList.add('se-popup-button', 'se-button-secondary');
   1673 
   1674         tableMenuButton.textContent = 'Create Table';
   1675         tableMenuCloseButton.textContent = 'Close';
   1676 
   1677         tableMenuForm.appendChild(tableMenuFormLabel);
   1678         tableMenuForm.appendChild(tableMenuFormColsInput);
   1679 
   1680         // Rows Input
   1681         const tableMenuRowsForm = tableMenuForm.cloneNode(true);
   1682         const tableMenuRowsInput = tableMenuRowsForm.querySelector('input');
   1683         const tableMenuRowsLabel = tableMenuRowsForm.querySelector('p');
   1684 
   1685         tableMenuRowsInput.placeholder = 'Table Rows';
   1686         tableMenuRowsLabel.textContent = 'Rows';
   1687 
   1688         tableMenuRowsInput.value = '3';
   1689         tableMenuFormColsInput.value = '3';
   1690 
   1691         function clearValues() {
   1692             tableMenuFormColsInput.value = '3';
   1693             tableMenuRowsInput.value = '3';
   1694         }
   1695 
   1696         tableMenuButton.onclick = () => {
   1697             se.body.focus();
   1698             se.setRange();
   1699 
   1700             if (tableMenuFormColsInput.value && tableMenuRowsInput.value) {
   1701                 se.generateTable(parseInt(tableMenuFormColsInput.value), parseInt(tableMenuRowsInput.value));
   1702             }
   1703 
   1704             clearValues();
   1705             se.closeAllMenus();
   1706             se.body.focus();
   1707         };
   1708 
   1709         tableMenuCloseButton.onclick = () => {
   1710             clearValues();
   1711             se.closeAllMenus();
   1712         };
   1713 
   1714         tableMenuHeader.classList.add('se-popup-header');
   1715         tableMenuHeader.innerText = 'Insert Table';
   1716 
   1717         tableMenu.appendChild(tableMenuHeader);
   1718 
   1719         tableMenuButtons.appendChild(tableMenuButton);
   1720         tableMenuButtons.appendChild(tableMenuCloseButton);
   1721         tableMenu.appendChild(tableMenuRowsForm);
   1722         tableMenu.appendChild(tableMenuForm);
   1723         tableMenu.appendChild(tableMenuButtons);
   1724 
   1725         [...tableMenu.getElementsByTagName('input')].forEach((inp) => {
   1726             inp.onkeydown = (e) => {
   1727                 if (e.key === 'Enter') {
   1728                     e.preventDefault();
   1729                 }
   1730             };
   1731         });
   1732         return tableMenu;
   1733     }
   1734 
   1735     /**
   1736      * Initializes the StrivenEditor meta data section for inserted links into the editor
   1737      * @returns {HTMLElement} The StrivenEditor meta data section
   1738      */
   1739     initMetaDataSection() {
   1740         const metaDataSection = document.createElement('div');
   1741         metaDataSection.classList.add('se-metadata-section');
   1742 
   1743         return metaDataSection;
   1744     }
   1745 
   1746     /**
   1747      * Initializes the StrivenEditor meta data section for attached files
   1748      * @returns {HTMLElement} The StrivenEditor attached file section
   1749      */
   1750     initFilesSection() {
   1751         const se = this;
   1752 
   1753         const filesSection = document.createElement('div');
   1754         filesSection.classList.add('se-files-section');
   1755 
   1756         window.addEventListener(
   1757             'dragover',
   1758             function (e) {
   1759                 e = e || event;
   1760                 e.preventDefault();
   1761             },
   1762             false
   1763         );
   1764 
   1765         window.addEventListener(
   1766             'drop',
   1767             function (e) {
   1768                 e = e || event;
   1769                 e.preventDefault();
   1770             },
   1771             false
   1772         );
   1773 
   1774         se.body.ondragenter = (e) => {
   1775             if (!se.body.querySelector('.se-file-drop-dropzone') && e.dataTransfer.types.includes('Files')) {
   1776                 const dropzone = document.createElement('div');
   1777                 const dropzoneTextEl = document.createElement('p');
   1778 
   1779                 dropzone.classList.add('se-file-drop-dropzone', 'dropzone-overlay');
   1780                 dropzone.contentEditable = 'false';
   1781                 dropzoneTextEl.textContent = 'Drop files to upload';
   1782 
   1783                 dropzone.ondrop = (e) => e.target.remove();
   1784                 dropzone.ondragover = (e) => (dropzone.dataset.enabled = 'true');
   1785 
   1786                 dropzone.append(dropzoneTextEl);
   1787                 se.body.append(dropzone);
   1788             }
   1789         };
   1790 
   1791         se.body.ondragleave = (e) => {
   1792             const dropzone = se.body.querySelector('.se-file-drop-dropzone');
   1793             dropzone && dropzone.dataset.enabled === 'true' && dropzone.remove();
   1794         };
   1795 
   1796         se.body.ondrop = (e) => {
   1797             const dropzone = se.body.querySelector('.se-file-drop-dropzone');
   1798             dropzone && dropzone.remove();
   1799 
   1800             e.preventDefault();
   1801 
   1802             if (e.dataTransfer.types.includes('Files')) {
   1803                 if (e.dataTransfer.files.length) {
   1804                     const files =[...e.dataTransfer.files];
   1805                     
   1806                     // Ensure there are no more than the max files allowed
   1807                     if (files.length + se.files.length > se.options.maxFiles) {
   1808                         alert(`Only ${se.options.maxFiles} files are allowed to upload in one batch.`);
   1809                         return;
   1810                     }
   1811 
   1812                     files.forEach((file) => se.attachFile(file));
   1813                 }
   1814             }
   1815         };
   1816 
   1817         se.isEdge && (se.body.ondragover = (e) => e.preventDefault());
   1818 
   1819         return filesSection;
   1820     }
   1821 
   1822     /**
   1823      * Creates a file element and appends it to the attached files seciton of the editor
   1824      * @param {String} name Name of the file
   1825      * @param {Number} size Size of the file in bytes
   1826      */
   1827     createFileElement(name, size) {
   1828         const se = this;
   1829 
   1830         const fileEl = document.createElement('div');
   1831         const fileNameEl = document.createElement('p');
   1832         const fileSizeEl = document.createElement('p');
   1833         const removeFileEl = document.createElement('p');
   1834 
   1835         fileNameEl.textContent = name;
   1836         fileSizeEl.textContent = size;
   1837         removeFileEl.textContent = 'X';
   1838 
   1839         fileEl.classList.add('se-file');
   1840         fileEl.dataset.fileindex = se.files.length - 1;
   1841 
   1842         fileNameEl.classList.add('se-file-name');
   1843 
   1844         fileSizeEl.classList.add('se-file-size');
   1845 
   1846         removeFileEl.classList.add('se-remove-link');
   1847 
   1848         removeFileEl.onclick = (e) => {
   1849             se.files.splice(e.target.parentElement.dataset.fileindex, 1);
   1850             e.target.parentElement.remove();
   1851         };
   1852 
   1853         fileEl.appendChild(fileNameEl);
   1854         fileEl.appendChild(fileSizeEl);
   1855         fileEl.appendChild(removeFileEl);
   1856 
   1857         se.filesSection.appendChild(fileEl);
   1858     }
   1859 
   1860     /**
   1861      * Creates a meta data element and appends it to the meta data section of the editor
   1862      * @param {String} url Url of the inserted link
   1863      * @param {String} img Image to use for the meta data item
   1864      * @param {String} title Title of the meta data item
   1865      * @param {String} description Description of the meta data item
   1866      */
   1867     createMetaDataElement(url, img, title, description) {
   1868         const metaItemEl = document.createElement('div');
   1869         const metaLinkEl = document.createElement('a');
   1870         const metaImageEl = document.createElement('img');
   1871         const metaDataEl = document.createElement('div');
   1872         const metaDataTitleEl = document.createElement('h4');
   1873         const metaDataDescriptionEl = document.createElement('p');
   1874         const removeMetaDataEl = document.createElement('span');
   1875 
   1876         metaLinkEl.href = url;
   1877         metaImageEl.src = img;
   1878         metaDataTitleEl.textContent = title;
   1879         metaDataDescriptionEl.textContent = description;
   1880         removeMetaDataEl.textContent = 'X';
   1881 
   1882         metaLinkEl.target = 'blank';
   1883 
   1884         metaItemEl.classList.add('se-meta-item');
   1885 
   1886         metaImageEl.classList.add('se-meta-image');
   1887 
   1888         metaDataTitleEl.classList.add('se-meta-data-title');
   1889 
   1890         metaDataDescriptionEl.style.margin = '0';
   1891 
   1892         removeMetaDataEl.classList.add('se-remove-link');
   1893 
   1894         removeMetaDataEl.onclick = (e) => e.target.parentElement.remove();
   1895 
   1896         metaLinkEl.appendChild(metaImageEl);
   1897 
   1898         metaDataEl.appendChild(metaDataTitleEl);
   1899         metaDataEl.appendChild(metaDataDescriptionEl);
   1900 
   1901         metaItemEl.appendChild(metaLinkEl);
   1902         metaItemEl.appendChild(metaDataEl);
   1903         metaItemEl.appendChild(removeMetaDataEl);
   1904 
   1905         se.metaDataSection.appendChild(metaItemEl);
   1906     }
   1907 
   1908     /**
   1909      * Constructs an svg given an object with the viewBox and d property
   1910      * @param {Object} svgData ViewBox and D attributes to use for the <svg>
   1911      * @returns {HTMLElement} Returns the constructed svg
   1912      */
   1913     constructSVG(svgData) {
   1914         const se = this;
   1915 
   1916         const { viewBox, d } = svgData;
   1917         const fillColor = se.options.toolbarOptionFillColor ? se.options.toolbarOptionFillColor : '#333';
   1918         const xmlns = 'http://www.w3.org/2000/svg';
   1919         const height = '14';
   1920         const width = '16';
   1921 
   1922         const icon = document.createElement('span');
   1923         const svg = `<svg width="${width}" height="${height}" viewBox="${viewBox}" xmlns="${xmlns}">`;
   1924         const path = `<path fill="${fillColor}" d="${d}"/>`;
   1925 
   1926         icon.innerHTML = `${svg}${path}</svg>`;
   1927 
   1928         return icon;
   1929     }
   1930 
   1931     /**
   1932      * Initialize the responsive properties of the editor
   1933      */
   1934     initResponsive() {
   1935         const se = this;
   1936 
   1937         if (!se.options.minimal) {
   1938             function responsiveGroups(isResponsive) {
   1939                 se.toolbarGroups.forEach((group) => {
   1940                     if (group) {
   1941                         group.dataset.open = 'false';
   1942 
   1943                         group.style.display = isResponsive ? 'none' : 'block';
   1944                         group.style.position = isResponsive ? 'absolute' : 'relative';
   1945 
   1946                         if (!isResponsive) {
   1947                             group.setAttribute('style', null);
   1948                             group.classList.remove('se-popup');
   1949                             group.classList.remove(se.options.toolbarBottom ? 'se-popup-bottom' : 'se-popup-top');
   1950                         }
   1951                     }
   1952                 });
   1953 
   1954                 se.toolbarMenus.forEach((menu) => {
   1955                     function toggleMenu() {
   1956                         const selectedGroup = se.toolbar.querySelector(`#group-${menu.id.split('-')[1]}`);
   1957 
   1958                         selectedGroup.classList.add('se-popup');
   1959                         selectedGroup.classList.add(se.options.toolbarBottom ? 'se-popup-bottom' : 'se-popup-top');
   1960 
   1961                         se.setMenuOffset(menu, selectedGroup);
   1962 
   1963                         if (selectedGroup.dataset.open === 'false') {
   1964                             // close opened groups
   1965                             se.toolbarGroups.forEach((group) => {
   1966                                 if (group && group.dataset.open === 'true') {
   1967                                     group.classList.remove('se-popup-open');
   1968                                     group.style.display = 'none';
   1969                                     group.dataset.open = 'false';
   1970                                 }
   1971                             });
   1972 
   1973                             // open group
   1974                             selectedGroup.classList.add('se-popup-open');
   1975                             se.addPopupEscapeHandler();
   1976                             selectedGroup.style.display = 'block';
   1977                             selectedGroup.dataset.open = 'true';
   1978                         } else {
   1979                             selectedGroup.classList.remove('se-popup-open');
   1980                             se.removePopupEscapeHandler();
   1981                             selectedGroup.style.display = 'none';
   1982                             selectedGroup.dataset.open = 'false';
   1983                         }
   1984                     }
   1985 
   1986                     if (menu) {
   1987                         menu.style.display = isResponsive ? 'flex' : 'none';
   1988                         menu.onclick = (e) => {
   1989                             se.closeAllMenus();
   1990                             toggleMenu();
   1991                             se.body.focus();
   1992                         };
   1993                     }
   1994                 });
   1995 
   1996                 [...se.toolbar.getElementsByClassName('se-toolbar-selection')].forEach((sl) => {
   1997                     const respond = se.editor.offsetWidth < 500;
   1998                     sl.style.display = respond ? 'none' : null;
   1999                     const { nextElementSibling } = sl;
   2000                     if (nextElementSibling.classList.contains('se-divider-section')) {
   2001                         nextElementSibling.style.display = respond ? 'none' : null;
   2002                     }
   2003                 });
   2004             }
   2005 
   2006             function setResponsive() {
   2007                 let responsive = window.matchMedia('(max-width: 700px)').matches;
   2008 
   2009                 responsiveGroups(responsive || se.editor.offsetWidth < 1100);
   2010             }
   2011 
   2012             setResponsive();
   2013 
   2014             const ro = new ResizeObserver((e) => {
   2015                 se.closeAllMenus();
   2016                 setResponsive();
   2017             });
   2018 
   2019             ro.observe(se.editor);
   2020         } else {
   2021             function responsiveMinimal(responsive) {
   2022                 const textDecorationMenu = se.toolbar.querySelector('#menu-textDecoration');
   2023                 const textDecorationGroup = se.toolbar.querySelector('#group-textDecoration');
   2024 
   2025                 textDecorationMenu.onclick = () => {
   2026                     setTimeout(() => {
   2027                         const textdecorationPopup = se.toolbar.querySelector('#group-textDecoration');
   2028                         let isOpen = textdecorationPopup.classList.contains('se-popup-open');
   2029 
   2030                         if (responsive) {
   2031                             if (isOpen) {
   2032                                 textDecorationGroup.classList.remove('se-popup-open');
   2033                             } else {
   2034                                 textDecorationGroup.classList.add('se-popup-open');
   2035                             }
   2036                         }
   2037                     }, 10);
   2038                 };
   2039 
   2040                 if (responsive) {
   2041                     textDecorationMenu.style.display = 'inline-block';
   2042                     textDecorationGroup.classList.add('se-popup');
   2043                     textDecorationGroup.classList.add(se.options.toolbarBottom ? 'se-popup-bottom' : 'se-popup-top');
   2044                 } else {
   2045                     textDecorationMenu.style.display = 'none';
   2046                     textDecorationGroup.classList.remove('se-popup');
   2047                 }
   2048             }
   2049 
   2050             function hideOption(option) {
   2051                 const optionEl = se.toolbar.querySelector(`#toolbar-${option}`);
   2052                 optionEl && (optionEl.style.display = 'none');
   2053             }
   2054 
   2055             se.toolbarMenus.forEach((menu) => menu && (menu.style.display = 'none'));
   2056 
   2057             hideOption('strikethrough');
   2058             hideOption('insertOrderedList');
   2059             hideOption('textAlign');
   2060             hideOption('removeFormat');
   2061 
   2062             if (
   2063                 se.toolbarTemplate
   2064                     ? se.toolbarTemplate.offsetWidth + se.toolbarOptionsGroup.offsetWidth > se.editor.offsetWidth
   2065                     : se.toolbarOptionsGroup.offsetWidth > se.editor.offsetWidth
   2066             ) {
   2067                 responsiveMinimal(true);
   2068             } else {
   2069                 responsiveMinimal(false);
   2070             }
   2071 
   2072             const ro = new ResizeObserver((e) => {
   2073                 se.closeAllMenus();
   2074 
   2075                 if (se.editor.offsetWidth < 300) {
   2076                     responsiveMinimal(true);
   2077                 } else {
   2078                     responsiveMinimal(false);
   2079                 }
   2080             });
   2081 
   2082             ro.observe(se.editor);
   2083         }
   2084     }
   2085 
   2086     /**
   2087      * Initilizes the overflow properties of the editor
   2088      */
   2089     initOverflow() {
   2090         const se = this;
   2091 
   2092         const onFocus = se.body.onfocus;
   2093         se.body.onfocus = () => {
   2094             onFocus && onFocus();
   2095             se.overflow();
   2096         };
   2097 
   2098         const onBlur = se.body.onblur;
   2099         se.body.onblur = () => {
   2100             onBlur && onBlur();
   2101             se.overflow();
   2102         };
   2103 
   2104         const bodyKeypress = se.body.onkeypress;
   2105         se.body.onkeypress = () => {
   2106             bodyKeypress && bodyKeypress();
   2107             se.overflow();
   2108         };
   2109     }
   2110 
   2111     /**
   2112      * Gets the attached files of the editor
   2113      * @returns {Array} Returns an array of attached files to the editor
   2114      */
   2115     getFiles() {
   2116         const se = this;
   2117         return se.files;
   2118     }
   2119 
   2120     /**
   2121      * Gets the content of the editor if there are attached files or provided content
   2122      * @returns {String} Returns the HTML String of the editor's content
   2123      */
   2124     getContent() {
   2125         const se = this;
   2126         let html = se.body;
   2127         const htmlView = !!se.editor.querySelector('.se-html');
   2128         if (htmlView) {
   2129             let dv = document.createElement('div');
   2130             dv.innerHTML = se.body.textContent;
   2131 
   2132             html = dv;
   2133         }
   2134         const body = se.pruneScripts(html);
   2135 
   2136         // Remove contenteditable tags for body
   2137         [...body.querySelectorAll('[contenteditable="true"]')].forEach((ce) => ce.removeAttribute('contenteditable'));
   2138 
   2139         //remove any link and image options
   2140         [...body.querySelectorAll('.se-link-options')].forEach((lOpt) => lOpt.remove());
   2141         [...body.querySelectorAll('.se-image-wrapper')].forEach((iwrap) => {
   2142             //find image inside the wrapper and replace the wrapper with image
   2143             const img = iwrap.querySelector('img');
   2144             iwrap.parentNode.replaceChild(img, iwrap);
   2145         });
   2146 
   2147         if (body.textContent || se.body.getElementsByTagName('img').length || se.body.getElementsByTagName('iframe').length) {
   2148             return body.innerHTML;
   2149         } else {
   2150             return null;
   2151         }
   2152     }
   2153 
   2154     /**
   2155      * Places the caret at the end of the specified element. See https://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser
   2156      * @param {HTMLElement} el Element to place the caret at the end of
   2157      */
   2158      placeCaretAtEnd(el) {
   2159         if (typeof window.getSelection != "undefined"
   2160                 && typeof document.createRange != "undefined") {
   2161             var range = document.createRange();
   2162             range.selectNodeContents(el);
   2163             range.collapse(false);
   2164             var sel = window.getSelection();
   2165             sel.removeAllRanges();
   2166             sel.addRange(range);
   2167         } else if (typeof document.body.createTextRange != "undefined") {
   2168             var textRange = document.body.createTextRange();
   2169             textRange.moveToElementText(el);
   2170             textRange.collapse(false);
   2171             textRange.select();
   2172         }
   2173     }
   2174 
   2175     /**
   2176      * Get the range of the window
   2177      * @returns {Range} Range of the window
   2178      */
   2179     getRange() {
   2180         try {
   2181             const selection = window.getSelection();
   2182             if (selection) {
   2183                 return selection.getRangeAt(0);
   2184             }
   2185         } catch (e) {}
   2186     }
   2187     
   2188     /**
   2189      * Gets the meta data from the metaUrl option
   2190      * @param {String} url Url to fetch meta data from
   2191      * @returns {Promise} Returns a promise that has the resolves with the meta data object
   2192      */
   2193     getMeta(url) {
   2194         const se = this;
   2195         return fetch(se.options.metaUrl, {
   2196             method: 'POST',
   2197             headers: { 'Content-Type': 'application/json' },
   2198             body: JSON.stringify({ targetUrl: url })
   2199         }).then((res) => res.json());
   2200     }
   2201 
   2202     /**
   2203      * Gets the image path from the imageUrl option
   2204      * @param {String} imageEncoding Encoded image string
   2205      * @returns {Promise} Returns a promise that resolves with the image path
   2206      */
   2207     getImage(imageEncoding) {
   2208         const se = this;
   2209         return new Promise((resolve, reject) => {
   2210             fetch(se.options.imageUrl, {
   2211                 method: 'POST',
   2212                 headers: { 'Content-Type': 'application/json' },
   2213                 body: JSON.stringify({ imageEncoding })
   2214             })
   2215                 .then((response) => {
   2216                     response
   2217                         .json()
   2218                         .then((data) => {
   2219                             resolve(data);
   2220                         })
   2221                         .catch((err) => {
   2222                             reject(err);
   2223                         });
   2224                 })
   2225                 .catch((err) => {
   2226                     reject(err);
   2227                 });
   2228         });
   2229     }
   2230 
   2231     /**
   2232      * Gets the editors active options based on UI
   2233      * @returns {Array} Returns an array with the toolbar commands currently active
   2234      */
   2235     getActiveOptions() {
   2236         const se = this;
   2237         return [...se.toolbarOptions].filter((opt) => opt.classList.contains('se-toolbar-option-active')).map((opt) => opt.id.split('-').pop());
   2238     }
   2239 
   2240     /**
   2241      * String to validate url pattern
   2242      * @param {String} str
   2243      * @returns {Boolean} Returns true if url is valid
   2244      */
   2245     validURL(str) {
   2246         const pattern = /^(?:http(s)?:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;
   2247         return pattern.test(str);
   2248     }
   2249 
   2250     /**
   2251      * Checks if the content overflows and removes or provides scrollbar
   2252      */
   2253     overflow() {
   2254         const se = this;
   2255 
   2256         const body = se.body;
   2257         body.scrollHeight > body.clientHeight ? (body.style.overflowY = 'scroll') : (body.style.overflowY = 'hidden');
   2258         body.scrollWidth > body.clientWidth ? (body.style.overflowX = 'scroll') : (body.style.overflowX = 'hidden');
   2259     }
   2260 
   2261     /**
   2262      * Prunes scripts from an elemenet
   2263      * @param {HTMLElement} el Element to prune scripts from
   2264      * @returns {HTMLElement} Returns the sanitized element
   2265      */
   2266     pruneScripts(el) {
   2267         const scripts = [...el.querySelectorAll('script')];
   2268         scripts.forEach((script) => script.remove());
   2269 
   2270         return el;
   2271     }
   2272 
   2273     /**
   2274      * Prunes styles from an element
   2275      * @param {HTMLElement} el Element to prune styles from
   2276      * @returns {HTMLElemenet} Returns the sanitized element
   2277      */
   2278     pruneStyles(el) {
   2279         const styles = [...el.querySelectorAll('style')];
   2280         styles.forEach((style) => style.remove());
   2281 
   2282         return el;
   2283     }
   2284 
   2285     /**
   2286      * Prunes inline position styles from elements
   2287      * @param {HTMLElement} el Element to prune inline styles from
   2288      * @returns {HTMLElement} Returns the sanitized element
   2289      */
   2290     pruneInlineStyles(el) {
   2291         let inlineStyleNodes = [...el.querySelectorAll('[style]')];
   2292         inlineStyleNodes = inlineStyleNodes.filter((node) => node.style.position);
   2293         inlineStyleNodes.forEach((node) => (node.style.position = 'static'));
   2294         return el;
   2295     }
   2296 
   2297     /* Cleans css  */
   2298     cleanCss(node) {
   2299         if (node.childNodes && node.childNodes.length) {
   2300             node.childNodes.forEach((cn) => {
   2301                 if (cn.nodeType == 1) {
   2302                     if (cn.className !== 'se-pasted-content') {
   2303                         cn.className = '';
   2304                     }
   2305                     this.cleanCss(cn);
   2306                 }
   2307             });
   2308         }
   2309     }
   2310 
   2311     /**
   2312      * Denormalizes provided bytes into human readable string
   2313      * @param {Number} bytes
   2314      * @param {Number} decimals
   2315      * @returns {String} Human readable file size string
   2316      */
   2317     formatBytes(bytes, decimals = 2) {
   2318         if (bytes === 0) return '0 Bytes';
   2319 
   2320         const k = 1024;
   2321         const dm = decimals < 0 ? 0 : decimals;
   2322         const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   2323 
   2324         const i = Math.floor(Math.log(bytes) / Math.log(k));
   2325 
   2326         return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
   2327     }
   2328 
   2329     /**
   2330      * Validates file based on provided extensions. If no extensions are provided, defaults
   2331      * to a predefined array.
   2332      * @param {File} file File to validate
   2333      * @returns {Boolean} Returns true if file is valid
   2334      */
   2335     validateFile(file) {
   2336         const se = this;
   2337 
   2338         const extension = file && file.name.split('.').pop().toLowerCase();
   2339         if (extension) {
   2340             return se.options.extensions.includes(`.${extension}`);
   2341         } else {
   2342             return false;
   2343         }
   2344     }
   2345 
   2346     /**
   2347      * Attaches file to the editor
   2348      * @param {File} file File to attach to editor
   2349      */
   2350     attachFile(file) {
   2351         const se = this;
   2352 
   2353         if (se.validateFile(file)) {
   2354             se.files.push(file);
   2355             se.createFileElement(file.name, se.formatBytes(file.size));
   2356             se.options.onValidFile && se.option.onValidFile();
   2357         } else {
   2358             se.fileInvalid();
   2359         }
   2360     }
   2361 
   2362     /**
   2363      * Fires the file invalid animation on the editor
   2364      */
   2365     fileInvalid() {
   2366         const se = this;
   2367 
   2368         se.options.onInvalidFile && se.options.onInvalidFile();
   2369         se.body.style.transition = 'background-color .5s';
   2370         se.body.style.backgroundColor = '#e3bdbd';
   2371         setTimeout(() => {
   2372             se.body.style.backgroundColor = 'inherit';
   2373             setTimeout(() => (se.body.style.transition = 'none'), 500);
   2374         }, 500);
   2375     }
   2376 
   2377     /**
   2378      * Sets the offset of the popup menu based on the button
   2379      * @param {HTMLElement} button Button to set offset for
   2380      * @param {HTMLElement} menu Popup menu to set offset on
   2381      */
   2382     setMenuOffset(button, menu) {
   2383         const se = this;
   2384         // Get the rect of the button to position the pop up. Sometimes, this may not be available
   2385         // yet, so we will need to open the menu to let the browser calculate bounds.
   2386         let buttonRect = button.getClientRects()[0];
   2387 
   2388         // Find the group that has the same group name as the button
   2389         if (!buttonRect) {
   2390             const toolbarMenu = se.toolbarMenus?.find((menu) => menu.getAttribute('data-name') === button.getAttribute('data-group-name'));
   2391             if (toolbarMenu) {
   2392                 // Trigger the toolbar menu because if we don't, and the mode is responsive, then the button is technically not there
   2393                 // yet and the below code will fail because the button dimensions can't be retrieved.
   2394                 toolbarMenu.onclick();
   2395                 // Close the menu immediately so it isn't visible. This should be enough for the browser
   2396                 // to calculate the rects
   2397                 se.closeAllMenus();
   2398             }
   2399         }
   2400 
   2401         const editorRect = se.editor.getClientRects()[0];
   2402         // Get the rect of the button. Hopefully, the browser has already calculated this when we forced the menu open.
   2403         buttonRect = button.getClientRects()[0];
   2404         const buttonOffset = buttonRect.left - editorRect.left;
   2405         const menuRight = buttonOffset + menu.clientWidth;
   2406 
   2407         let offset;
   2408         if (menuRight > se.editor.clientWidth) {
   2409             offset = buttonOffset + (se.editor.clientWidth - menuRight);
   2410         } else {
   2411             offset = buttonOffset;
   2412         }
   2413 
   2414         menu.style.left = `${offset}px`;
   2415     }
   2416 
   2417     /**
   2418      * Opens the editor's link menu popup
   2419      */
   2420     openLinkMenu() {
   2421         const se = this;
   2422 
   2423         se.closeAllMenus();
   2424 
   2425         se.setMenuOffset(se.toolbar.querySelector('.se-toolbar-option#toolbar-link'), se.linkMenu);
   2426         se.linkMenu.classList.add('se-popup-open');
   2427 
   2428         se.linkMenu.dataset.active = 'true';
   2429         se.addPopupEscapeHandler();
   2430 
   2431         se.linkMenu.scrollIntoView({ block: 'nearest', inline: 'nearest' });
   2432 
   2433         const submitEvt = (e) => {
   2434             if (e.key === 'Enter') {
   2435                 const submitEl = se.linkMenu.querySelector('button');
   2436                 submitEl.click();
   2437                 e.preventDefault();
   2438                 window.removeEventListener('keyup', se.linkMenu.submitEvt);
   2439             }
   2440         };
   2441 
   2442         se.linkMenu.submitEvt = submitEvt;
   2443         window.addEventListener('keyup', se.linkMenu.submitEvt);
   2444     }
   2445 
   2446     /**
   2447      * Opens the editor's image menu popup
   2448      */
   2449     openImageMenu(isEdit) {
   2450         const se = this;
   2451 
   2452         se.closeAllMenus();
   2453 
   2454         se.setMenuOffset(se.toolbar.querySelector('#toolbar-image'), se.imageMenu);
   2455 
   2456         // Select the tab buttons
   2457         const imageMenuUploadTabButton = se.imageMenu.querySelector('.se-tab-button-upload');
   2458         const imageMenuLinkTabButton = se.imageMenu.querySelector('.se-tab-button-link');
   2459         const imageInsertButton = se.imageMenu.querySelector('.se-image-insert-button');
   2460 
   2461         if (isEdit) {
   2462             imageMenuLinkTabButton.click();
   2463             imageMenuUploadTabButton.setAttribute('disabled', 'disabled');
   2464             imageMenuUploadTabButton.style.cursor = 'not-allowed';
   2465             // Change the text of the insert image button to Update Image
   2466             imageInsertButton.textContent = 'Update Image';
   2467             // Set cursor to indicate disabled
   2468         } else {
   2469             imageMenuUploadTabButton.click();
   2470             imageMenuUploadTabButton.removeAttribute('disabled');
   2471             imageMenuUploadTabButton.style.cursor = 'pointer';
   2472             // Rename insert image button
   2473             imageInsertButton.textContent = 'Insert Image';
   2474         }
   2475 
   2476         // Clear the input fields
   2477         const imageInputs = se.imageMenu.querySelectorAll('input');
   2478         for (const imageInput of imageInputs) {
   2479             imageInput.value = '';
   2480             // Enable the input
   2481             imageInput.removeAttribute('disabled');
   2482         }
   2483 
   2484         se.imageMenu.classList.add('se-popup-open');
   2485 
   2486         se.imageMenu.dataset.active = 'true';
   2487         se.addPopupEscapeHandler();
   2488         se.imageMenu.scrollIntoView({ block: 'nearest', inline: 'nearest' });
   2489 
   2490         const submitEvt = (e) => {
   2491             if (e.key === 'Enter') {
   2492                 const submitEl = se.imageMenu.querySelector('button');
   2493                 submitEl.click();
   2494                 e.preventDefault();
   2495                 window.removeEventListener('keyup', se.imageMenu.submitEvt);
   2496             }
   2497         };
   2498 
   2499         se.imageMenu.submitEvt = submitEvt;
   2500         window.addEventListener('keyup', se.imageMenu.submitEvt);
   2501     }
   2502 
   2503     openTableMenu() {
   2504         const se = this;
   2505 
   2506         se.closeAllMenus();
   2507 
   2508         se.setMenuOffset(se.toolbar.querySelector('#toolbar-table'), se.tableMenu);
   2509         se.tableMenu.classList.add('se-popup-open');
   2510 
   2511         se.tableMenu.dataset.active = 'true';
   2512         se.addPopupEscapeHandler();
   2513 
   2514         const submitEvt = (e) => {
   2515             if (e.key === 'Enter') {
   2516                 const submitEl = se.tableMenu.querySelector('button');
   2517                 submitEl.click();
   2518                 e.preventDefault();
   2519                 window.removeEventListener('keyup', se.tableMenu.submitEvt);
   2520             }
   2521         };
   2522 
   2523         se.tableMenu.submitEvt = submitEvt;
   2524         window.addEventListener('keyup', se.tableMenu.submitEvt);
   2525     }
   2526 
   2527     clearLinksToEdit(force) {
   2528         const se = this;
   2529 
   2530         if (force || (se.linkMenu && !se.linkMenu.classList.contains('se-popup-open'))) {
   2531             [...se.body.querySelectorAll('.se-link-options')].forEach((opt) => opt.remove());
   2532 
   2533             for (const lnk of se.body.querySelectorAll('a.se-link-to-edit[href="#"]')) {
   2534                 lnk.outerHTML = lnk.textContent;
   2535             }
   2536 
   2537             for (const lnk of se.body.querySelectorAll('.se-link-to-edit')) {
   2538                 lnk.classList.remove('se-link-to-edit');
   2539             }
   2540         }
   2541     }
   2542 
   2543     clearImagesToEdit(force) {
   2544         const se = this;
   2545 
   2546         if (force || (se.imageMenu && !se.imageMenu.classList.contains('se-popup-open'))) {
   2547             // Find any lingering edit menus
   2548             const imageEditMenus = se.body.querySelectorAll('.se-image-options');
   2549             for (const menu of imageEditMenus) {
   2550                 menu.remove();
   2551             }
   2552 
   2553             // Clear the edit class from the images
   2554             const imagesToEdit = se.body.querySelectorAll('.se-image-to-edit');
   2555             for (const img of imagesToEdit) {
   2556                 img.classList.remove('se-image-to-edit');
   2557                 let wrapper = img.parentElement;
   2558                 if (wrapper.classList.contains('se-image-wrapper')) {
   2559                     wrapper.parentElement.insertBefore(img, wrapper);
   2560                     wrapper.remove();
   2561                 }
   2562             }
   2563         }
   2564     }
   2565 
   2566     /**
   2567      * Closes the editor's link menu popup
   2568      */
   2569     closeLinkMenu() {
   2570         const se = this;
   2571 
   2572         se.closeAllMenus();
   2573         se.linkMenu.classList.remove('se-popup-open');
   2574         se.linkMenu.dataset.active = 'false';
   2575         se.removePopupEscapeHandler();
   2576         se.clearLinksToEdit();
   2577     }
   2578 
   2579     /**
   2580      * Closes the editor's image menu popup
   2581      */
   2582     closeImageMenu() {
   2583         const se = this;
   2584 
   2585         se.closeAllMenus();
   2586         se.imageMenu.classList.remove('se-popup-open');
   2587         se.imageMenu.dataset.active = 'false';
   2588         se.removePopupEscapeHandler();
   2589         se.clearImagesToEdit();
   2590     }
   2591 
   2592     closeTableMenu() {
   2593         const se = this;
   2594 
   2595         se.closeAllMenus();
   2596         se.tableMenu.classList.remove('se-popup-open');
   2597         se.tableMenu.dataset.active = 'false';
   2598         se.removePopupEscapeHandler();
   2599     }
   2600 
   2601     /**
   2602      * Closes all menus opended on the editor instance
   2603      */
   2604     closeAllMenus() {
   2605         const se = this;
   2606 
   2607         const popups = se.editor.getElementsByClassName('se-popup');
   2608         [...popups].forEach((popup) => {
   2609             popup.classList.remove('se-popup-open');
   2610             popup.dataset.active = 'false';
   2611 
   2612             if (popup.submitEvt) {
   2613                 window.removeEventListener('keyup', popup.submitEvt);
   2614             }
   2615         });
   2616     }
   2617 
   2618     /**
   2619      * Binds the escape handler event
   2620      * @param {Event} evt Event to bind to
   2621      */
   2622     popupEscapeHandler(evt) {
   2623         const se = this;
   2624 
   2625         if (evt.which === 27) {
   2626             //clear unused links
   2627             se.clearLinksToEdit(true);
   2628             se.clearImagesToEdit(true);
   2629 
   2630             //close all open popups
   2631             se.closeAllMenus();
   2632         }
   2633     }
   2634 
   2635     /**
   2636      * Binds the escape handler to the editor for popup menus
   2637      */
   2638     addPopupEscapeHandler() {
   2639         const se = this;
   2640 
   2641         se.removePopupEscapeHandler();
   2642         se.editor.addEventListener('keyup', se.bound_popupEscapeHandler);
   2643     }
   2644 
   2645     /**
   2646      * Removes the escape handler on the editor for popup menus
   2647      */
   2648     removePopupEscapeHandler() {
   2649         const se = this;
   2650         se.editor.removeEventListener('keyup', se.bound_popupEscapeHandler);
   2651     }
   2652 
   2653     /**
   2654      * Clears the editor and sets the its content with html string
   2655      * @param {String} html Html string to set the content with
   2656      */
   2657     setContent(html) {
   2658         const se = this;
   2659 
   2660         se.clearContent();
   2661         if (html) {
   2662             se.body.innerHTML = html;
   2663             se.makeLinksClickable();
   2664         }
   2665     }
   2666 
   2667     /**
   2668      * Removes ranges on the window and sets it to the provided range
   2669      * @param {Range} range Range to set the window with
   2670      */
   2671     setRange(range) {
   2672         const se = this;
   2673 
   2674         try {
   2675             if (range) {
   2676                 window.getSelection().removeAllRanges();
   2677                 window.getSelection().addRange(range);
   2678             } else {
   2679                 window.getSelection().removeAllRanges();
   2680                 window.getSelection().addRange(se.range);
   2681             }
   2682         } catch (e) {}
   2683     }
   2684 
   2685     /**
   2686      * Clears the editors content
   2687      */
   2688     clearContent() {
   2689         const se = this;
   2690         se.body.innerHTML = '';
   2691     }
   2692 
   2693     /**
   2694      * Clears all attached files to the editor
   2695      */
   2696     clearFiles() {
   2697         const se = this;
   2698         se.files = [];
   2699         se.filesSection.innerHTML = '';
   2700     }
   2701 
   2702     /**
   2703      * Gets the text content of the editor
   2704      * @returns {String} Returns text content of the editor
   2705      */
   2706     getTextContent() {
   2707         const se = this;
   2708         return se.body.textContent;
   2709     }
   2710 
   2711     /**
   2712      * Sanitizes the provided element
   2713      * @param {HTMLElement} dirtyNode HTML Node to sanitize
   2714      * @returns {HTMLElement} Cleaned HTML node
   2715      */
   2716     scrubHTML(dirtyNode) {
   2717         const cleanNode = document.createElement('div');
   2718 
   2719         cleanNode.append(document.createTextNode(dirtyNode.textContent));
   2720 
   2721         return cleanNode;
   2722     }
   2723 
   2724     /**
   2725      * Sets the toolbars stated based on which options are enabled on the document
   2726      */
   2727     toolbarState() {
   2728         const se = this;
   2729         se.options.toolbarOptions.forEach((option) => {
   2730             if (typeof option === 'string') {
   2731                 const toolbarOption = se.toolbar.querySelector(`#toolbar-${option}`);
   2732                 if (!option.toLowerCase().includes('justify') && !option.toLowerCase().includes('list')) {
   2733                     if (document.queryCommandState(option)) {
   2734                         toolbarOption && toolbarOption.classList.add('se-toolbar-option-active');
   2735                         // toolbarOption.querySelector('path').setAttribute('fill', se.options.activeOptionColor);
   2736                     } else {
   2737                         toolbarOption && toolbarOption.classList.remove('se-toolbar-option-active');
   2738                         // toolbarOption.querySelector('path').setAttribute('fill', '#333');
   2739                     }
   2740                 }
   2741             }
   2742         });
   2743     }
   2744 
   2745     /*
   2746      * Update the font states on the toolbar
   2747      */
   2748     setFontStates() {
   2749         const se = this;
   2750         if (se.fontSize && !se.browser.isFirefox()) {
   2751             se.fontSize.textContent = FONTSIZES[document.queryCommandValue('fontSize')] || '(inherited size)';
   2752         }
   2753 
   2754         if (se.fontName) {
   2755             const currentfont = document.queryCommandValue('fontName').split(',')[0].replace(/\"/g, '');
   2756 
   2757             se.fontName.textContent = currentfont || '(inherited font)';
   2758         }
   2759 
   2760         se.foreColor && se.foreColor.setAttribute('fill', document.queryCommandValue('foreColor'));
   2761         se.hiliteColor && !se.browser.isFirefox() && se.hiliteColor.setAttribute('fill', document.queryCommandValue('hiliteColor'));
   2762     }
   2763 
   2764     /*
   2765      * Execute current state of the fonts as displayed in the toolbar
   2766      */
   2767     execFontStates() {
   2768         const se = this;
   2769 
   2770         if (se.browser.isFirefox() || se.browser.isEdge()) {
   2771             se.foreColor && document.execCommand('foreColor', false, se.foreColor.getAttribute('fill'));
   2772             se.hiliteColor && document.execCommand('hiliteColor', false, se.hiliteColor.getAttribute('fill'));
   2773             se.fontName && document.execCommand('fontName', false, se.fontName.textContent);
   2774             se.fontSize && document.execCommand('fontSize', false, se.fontSize.textContent.split(' ')[0]);
   2775         } else {
   2776             se.foreColor && document.execCommand('foreColor', true, se.foreColor.getAttribute('fill'));
   2777             se.hiliteColor && document.execCommand('hiliteColor', true, se.hiliteColor.getAttribute('fill'));
   2778 
   2779             se.fontName && document.execCommand('fontName', true, se.fontName.textContent);
   2780             se.fontSize && document.execCommand('fontSize', true, parseInt(se.fontSize.dataset.command));
   2781         }
   2782     }
   2783 
   2784     generateTable(cols = 3, rows = 3) {
   2785         const se = this;
   2786 
   2787         let table = document.createElement('table');
   2788 
   2789         for (let i = 0; i < rows; i++) {
   2790             table.insertRow();
   2791         }
   2792 
   2793         [...table.rows].forEach((r) => {
   2794             for (let i = 0; i < cols; i++) {
   2795                 r.insertCell();
   2796             }
   2797         });
   2798 
   2799         table.setAttribute('data-init', true);
   2800         se.executeCommand('insertHTML', table.outerHTML);
   2801 
   2802         table = se.body.querySelector('table[data-init="true"]');
   2803         if (table) {
   2804             table.removeAttribute('data-init');
   2805             table.setAttribute('cellspacing', '0');
   2806             table.setAttribute('style', 'width: 100%');
   2807 
   2808             const tdCollection = [...table.getElementsByTagName('td')];
   2809             tdCollection.forEach((td) => {
   2810                 td.setAttribute('style', 'border: 1px solid #ddd');
   2811 
   2812                 td.onfocus = () => {
   2813                     se.toolbarState();
   2814                 };
   2815 
   2816                 td.onclick = () => {
   2817                     const range = se.getRange();
   2818                     td.textContent && range.selectNode(td);
   2819                     se.toolbarState();
   2820                 };
   2821             });
   2822         }
   2823 
   2824         return table;
   2825     }
   2826 
   2827     /**
   2828      * This method is used to detect the user browser and environment
   2829      */
   2830     establishBrowser() {
   2831         const se = this;
   2832 
   2833         const userAgent = ((navigator && navigator.userAgent) || '').toLowerCase();
   2834         const vendor = ((navigator && navigator.vendor) || '').toLowerCase();
   2835 
   2836         const comparator = {
   2837             '<': function (a, b) {
   2838                 return a < b;
   2839             },
   2840             '<=': function (a, b) {
   2841                 return a <= b;
   2842             },
   2843             '>': function (a, b) {
   2844                 return a > b;
   2845             },
   2846             '>=': function (a, b) {
   2847                 return a >= b;
   2848             }
   2849         };
   2850 
   2851         const compareVersion = (version, range) => {
   2852             const str = range + '';
   2853             const n = +(str.match(/\d+/) || NaN);
   2854             const op = str.match(/^[<>]=?|/)[0];
   2855             return comparator[op] ? comparator[op](version, n) : version == n || n !== n;
   2856         };
   2857 
   2858         se.browser = {
   2859             userAgent,
   2860             vendor
   2861         };
   2862 
   2863         // detect opera
   2864         se.browser.isOpera = function isOpera(range) {
   2865             const match = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
   2866             return match !== null && compareVersion(match[1], range);
   2867         };
   2868 
   2869         // detect chrome
   2870         se.browser.isChrome = function isChrome(range) {
   2871             const match = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
   2872             return match !== null && !se.isOpera() && compareVersion(match[1], range);
   2873         };
   2874 
   2875         // detect firefox
   2876         se.browser.isFirefox = function isFirefox(range) {
   2877             const match = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
   2878             return match !== null && compareVersion(match[1], range);
   2879         };
   2880 
   2881         // detect safari
   2882         se.browser.isSafari = function isSafari(range) {
   2883             const match = userAgent.match(/version\/(\d+).+?safari/);
   2884             return match !== null && compareVersion(match[1], range);
   2885         };
   2886 
   2887         // detect internet explorer
   2888         se.browser.isIE = function isIE(range) {
   2889             const match = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
   2890             return match !== null && compareVersion(match[1], range);
   2891         };
   2892 
   2893         // detect edge
   2894         se.browser.isEdge = function isEdge(range) {
   2895             const match = userAgent.match(/edge\/(\d+)/);
   2896             return match !== null && compareVersion(match[1], range);
   2897         };
   2898 
   2899         // detect blink engine
   2900         se.browser.isBlink = function isBlink() {
   2901             return (se.isChrome() || se.isOpera()) && !!window.CSS;
   2902         };
   2903     }
   2904 
   2905     /**
   2906      * Checks if editor is being focused on (inclusive to children and relative elements)
   2907      * @returns {Boolean} Returns true if editor is being focused
   2908      */
   2909     isEditorInFocus() {
   2910         const se = this;
   2911 
   2912         let activeEl = document.activeElement;
   2913         var isEditor = (el) => {
   2914             if (el === se.editor) {
   2915                 return true;
   2916             } else if (el === document.body) {
   2917                 return false;
   2918             }
   2919             return el.parentNode && isEditor(el.parentNode);
   2920         };
   2921         return isEditor(activeEl);
   2922     }
   2923 
   2924     /*
   2925   parses all links on the editor or links passed and makes them clickable and adds option to change/remove the link
   2926   */
   2927     makeLinksClickable(links = []) {
   2928         const se = this;
   2929         if (!links.length) {
   2930             const linkElements = se.body.getElementsByTagName('a');
   2931             if (linkElements.length > 0) {
   2932                 links = [...linkElements];
   2933             }
   2934         }
   2935 
   2936         links.forEach((link) => {
   2937             link.onmousemove = (e) => {
   2938                 e.ctrlKey && (link.style.cursor = 'pointer');
   2939             };
   2940 
   2941             link.onclick = (e) => {
   2942                 if (e.ctrlKey || e.metaKey) {
   2943                     const anchor = document.createElement('a');
   2944                     anchor.setAttribute('href', link.getAttribute('href'));
   2945                     anchor.setAttribute('target', '_blank');
   2946                     document.body.append(anchor);
   2947                     anchor.click();
   2948                     anchor.remove();
   2949                 } else if (!link.querySelector('.se-link-options')) {
   2950                     const linkOptions = document.createElement('span');
   2951                     linkOptions.setAttribute('class', 'se-link-options');
   2952                     linkOptions.setAttribute('contenteditable', false);
   2953                     linkOptions.onclick = (e) => e.stopPropagation();
   2954                     link.append(linkOptions);
   2955 
   2956                     const removeOption = document.createElement('span');
   2957                     removeOption.textContent = 'Remove';
   2958                     removeOption.onclick = (e) => {
   2959                         e.preventDefault();
   2960                         e.stopPropagation();
   2961                         linkOptions.remove();
   2962 
   2963                         const replNode = document.createElement('span');
   2964                         replNode.textContent = link.textContent;
   2965                         link.replaceWith(replNode);
   2966                     };
   2967 
   2968                     const changeOption = document.createElement('span');
   2969                     changeOption.textContent = 'Change';
   2970                     changeOption.onclick = (e) => {
   2971                         e.preventDefault();
   2972                         e.stopPropagation();
   2973                         linkOptions.remove();
   2974 
   2975                         link.classList.add('se-link-to-edit');
   2976                         se.openLinkMenu();
   2977 
   2978                         const linkInputs = se.linkMenu.querySelectorAll('input');
   2979                         linkInputs[0]['value'] = link.getAttribute('href');
   2980                         linkInputs[1]['value'] = link.textContent;
   2981                         linkInputs[2]['checked'] = link.getAttribute('target') === '_blank';
   2982 
   2983                         setTimeout(() => linkInputs[0].select(), 100);
   2984                     };
   2985 
   2986                     linkOptions.append(changeOption);
   2987                     linkOptions.append(removeOption);
   2988 
   2989                     const optionHandler = () => {
   2990                         try {
   2991                             const r = se.getRange();
   2992                             const rNode = r['commonAncestorContainer']['parentElement'];
   2993                             if (rNode !== link) {
   2994                                 linkOptions.remove();
   2995                                 se.body.removeEventListener('click', optionHandler);
   2996                             }
   2997                         } catch (e) {
   2998                             linkOptions.remove();
   2999                             window.removeEventListener('click', optionHandler);
   3000                         }
   3001                     };
   3002 
   3003                     window.addEventListener('click', optionHandler);
   3004                 }
   3005             };
   3006 
   3007             link.onmouseleave = () => (link.style.cursor = null);
   3008 
   3009             link.setAttribute('contenteditable', true);
   3010         });
   3011     }
   3012 
   3013     /**
   3014      * Creates links
   3015      * @parma {HTMLElement} Element to convert links in
   3016      */
   3017     createLinks(el) {
   3018         const se = this;
   3019         const htmlView = !!se.editor.querySelector('.se-html');
   3020         if (!htmlView) {
   3021             linkify(
   3022                 el || se.body,
   3023                 {
   3024                     target: {
   3025                         url: '_blank'
   3026                     },
   3027                     className: 'linkified',
   3028                     validate: {
   3029                         email: function (value) {
   3030                             return false;
   3031                         }
   3032                     }
   3033                 },
   3034                 document
   3035             );
   3036         }
   3037         var links = [];
   3038         if (el) {
   3039             const linkElements = el.getElementsByTagName('a');
   3040             if (linkElements.length > 0) {
   3041                 links = [...linkElements];
   3042             }
   3043         }
   3044         this.makeLinksClickable(links);
   3045 
   3046         // Trigger input event
   3047         let inpEvent = new Event('input', { cancelable: true, bubbles: true });
   3048         se.body.dispatchEvent(inpEvent);
   3049     }
   3050 
   3051     /*
   3052      * Init Pickr Plugin menu for font colors
   3053      * @param {Object} Pickr instance
   3054      * @param {Function} Handler even for the select button
   3055      */
   3056     initPickrMenu(pickr, onclick) {
   3057         const pickrMenu = pickr['_root']['app'];
   3058 
   3059         const pickrMenuActions = document.createElement('div');
   3060         const pickrMenuButton = document.createElement('button');
   3061         const pickrMenuClose = document.createElement('button');
   3062 
   3063         pickrMenuButton.setAttribute('type', 'button');
   3064         pickrMenuClose.setAttribute('type', 'button');
   3065 
   3066         pickrMenuActions.setAttribute('style', 'display: flex; justify-content: flex-end; margin-top: 10px;');
   3067 
   3068         pickrMenuButton.textContent = 'Select';
   3069         pickrMenuClose.textContent = 'Close';
   3070 
   3071         pickrMenuButton.classList.add('se-popup-button');
   3072         pickrMenuButton.classList.add('se-button-primary');
   3073         pickrMenuClose.classList.add('se-popup-button');
   3074         pickrMenuClose.classList.add('se-button-secondary');
   3075 
   3076         pickrMenuClose.onclick = () => pickr.hide();
   3077 
   3078         pickrMenuButton.onclick = onclick;
   3079 
   3080         pickrMenuActions.append(pickrMenuButton);
   3081         pickrMenuActions.append(pickrMenuClose);
   3082         pickrMenu.append(pickrMenuActions);
   3083     }
   3084 
   3085     /**
   3086      * Executes a command on the document with respect to browser
   3087      * @param {String} command Command to execute on the document
   3088      */
   3089     executeCommand(command, input) {
   3090         const se = this;
   3091 
   3092         function textDecorationInsert(el) {
   3093             const r = se.range || new Range();
   3094             se.setRange(r);
   3095 
   3096             const b = document.createElement(el);
   3097             const selNode = se.body.querySelector('.se-init-sel') || document.createElement('span');
   3098             selNode.setAttribute('class', 'se-init-sel');
   3099             selNode.innerHTML = '&nbsp;';
   3100 
   3101             b.append(selNode);
   3102 
   3103             const fc = se.body.firstChild;
   3104             fc && fc.append ? fc.append(b) : se.body.append(b);
   3105 
   3106             r.selectNode(selNode);
   3107             r.collapse();
   3108         }
   3109 
   3110         switch (command) {
   3111             case 'html':
   3112                 const saveoption = document.createElement('div');
   3113                 saveoption.classList.add('se-toolbar-option');
   3114                 saveoption.setAttribute('title', 'Design');
   3115                 saveoption.append(createSVG(DESIGNICON));
   3116 
   3117                 se.toolbar.classList.add('se-html');
   3118 
   3119                 saveoption.onclick = () => {
   3120                     saveoption.remove();
   3121                     se.body.style.fontFamily = null;
   3122                     // Remove white-space: pre to prevent text wrapping weirdly
   3123                     se.body.style.whiteSpace = null;
   3124 
   3125                     se.toolbar.classList.remove('se-html');
   3126                     se.setContent(se.body.textContent);
   3127                 };
   3128 
   3129                 se.toolbar.prepend(saveoption);
   3130 
   3131                 se.body.style.fontFamily = 'Courier';
   3132 
   3133                 // Add this so that the textContent will wrap at line breaks (not br tags)
   3134                 se.body.style.whiteSpace = 'pre';
   3135 
   3136                 // Format the HTML so that it looks somewhat pretty
   3137                 var options = {
   3138                     indent_size: 4,
   3139                     unformatted: []
   3140                 };
   3141 
   3142                 let formatedHtml = js_beautify.html(se.body.innerHTML, options);
   3143 
   3144                 // Set the content of the editor to the formatted html
   3145                 se.body.textContent = formatedHtml;
   3146                 se.overflow();
   3147 
   3148                 break;
   3149             case 'fullscreen':
   3150                 const opt = se.toolbar.querySelector('#toolbar-fullscreen');
   3151 
   3152                 if (!se.editor.oncollapse) {
   3153                     se.editor.oncollapse = () => {
   3154                         if (opt.original !== se.body.innerHTML && se.options.change) {
   3155                             se.createLinks();
   3156                             se.options.change(se.getContent());
   3157                         }
   3158 
   3159                         opt.innerHTML = '';
   3160                         opt.append(createSVG(EXPANDICON));
   3161 
   3162                         se.editor.style.maxHeight = null;
   3163                         document.body.style.overflow = null;
   3164 
   3165                         se.body.style.height = se.editor.getAttribute('height');
   3166                         se.body.style.minHeight = se.editor.getAttribute('min-height');
   3167                         se.body.style.maxHeight = se.editor.getAttribute('max-height');
   3168 
   3169                         se.overflow();
   3170 
   3171                         opt.removeAttribute('data-fullscreen');
   3172                     };
   3173                 }
   3174 
   3175                 if (opt.getAttribute('data-fullscreen')) {
   3176                     se.editor.collapse && se.editor.collapse();
   3177                     se.options.onFullscreenCollapse && se.options.onFullscreenCollapse();
   3178                 } else {
   3179                     blowUpElement(se.editor, '#fff', (e) => {
   3180                         opt.original = se.body.innerHTML;
   3181                         opt.innerHTML = '';
   3182                         opt.append(createSVG(COLLAPSEICON));
   3183 
   3184                         document.body.style.overflow = 'hidden';
   3185 
   3186                         se.body.style.height = '100%';
   3187                         se.body.style.minHeight = null;
   3188                         se.body.style.maxHeight = null;
   3189 
   3190                         se.editor.style.maxHeight = 'inherit';
   3191                         opt.setAttribute('data-fullscreen', 'active');
   3192                     });
   3193                 }
   3194                 break;
   3195             case 'foreColor':
   3196             case 'hiliteColor':
   3197                 const colorOption = se.toolbar.querySelector(`#toolbar-${command}`);
   3198                 const colorIcon = colorOption.getElementsByTagName('path')[0];
   3199                 se[command] = colorIcon;
   3200 
   3201                 const defaultColor = () => {
   3202                     if (command === 'foreColor') {
   3203                         return '#000';
   3204                     }
   3205 
   3206                     if (command === 'hiliteColor') {
   3207                         return '#fff';
   3208                     }
   3209 
   3210                     return '#000';
   3211                 };
   3212 
   3213                 if (colorOption.dataset.init !== 'true') {
   3214                     const pickr = Pickr.create({
   3215                         el: colorOption,
   3216                         theme: 'classic',
   3217                         container: se.editor,
   3218                         useAsButton: true,
   3219                         default: defaultColor(),
   3220                         components: {
   3221                             preview: true,
   3222                             palette: true,
   3223                             hue: true,
   3224                             interaction: { hex: true, input: true }
   3225                         }
   3226                     });
   3227 
   3228                     se.initPickrMenu(pickr, () => {
   3229                         const color = pickr.getColor().toHEXA().toString();
   3230 
   3231                         function execute() {
   3232                             if (se.browser.isEdge() || se.browser.isFirefox()) {
   3233                                 document.execCommand(command, false, color);
   3234                             } else {
   3235                                 document.execCommand(command, true, color);
   3236                             }
   3237                         }
   3238 
   3239                         colorIcon.setAttribute('fill', color);
   3240 
   3241                         const enabler = () => {
   3242                             execute();
   3243                             se.body.removeEventListener('keydown', enabler);
   3244                         };
   3245 
   3246                         if (se.range) {
   3247                             if (se.range.collapsed) {
   3248                                 se.body.addEventListener('keydown', enabler);
   3249                             } else {
   3250                                 execute();
   3251                             }
   3252                         } else {
   3253                             se.body.addEventListener('keydown', enabler);
   3254                         }
   3255 
   3256                         pickr.hide();
   3257                     });
   3258 
   3259                     pickr.on('init', (p) => {
   3260                         colorOption.dataset.init = 'true';
   3261                         pickr.show();
   3262                     });
   3263 
   3264                     pickr.on('change', (h, p) => {
   3265                         const color = h.toHEXA().toString();
   3266                         colorIcon.setAttribute('fill', color);
   3267                     });
   3268 
   3269                     pickr.on('hide', (p) => {
   3270                         const color = p.getColor().toHEXA().toString();
   3271 
   3272                         se.body.focus();
   3273                     });
   3274                 }
   3275                 break;
   3276             case 'insertOrderedList':
   3277                 if (!se.body.textContent) {
   3278                     const list = document.createElement('ol');
   3279                     const item = document.createElement('li');
   3280                     list.append(item);
   3281 
   3282                     se.body.append(list);
   3283 
   3284                     const r = se.range || new Range();
   3285                     window.getSelection().removeAllRanges();
   3286                     window.getSelection().addRange(r);
   3287                     r.selectNode(item);
   3288 
   3289                     return false;
   3290                 }
   3291 
   3292                 if (se.browser.isFirefox() || se.browser.isEdge()) {
   3293                     document.execCommand(command, false);
   3294                 } else {
   3295                     document.execCommand(command);
   3296                 }
   3297                 break;
   3298             case 'insertUnorderedList':
   3299                 if (!se.body.textContent) {
   3300                     const list = document.createElement('ul');
   3301                     const item = document.createElement('li');
   3302                     list.append(item);
   3303 
   3304                     se.body.append(list);
   3305 
   3306                     const r = se.range || new Range();
   3307                     window.getSelection().removeAllRanges();
   3308                     window.getSelection().addRange(r);
   3309                     r.selectNode(list);
   3310 
   3311                     return false;
   3312                 }
   3313 
   3314                 if (se.browser.isFirefox() || se.browser.isEdge()) {
   3315                     document.execCommand(command, false);
   3316                 } else {
   3317                     document.execCommand(command);
   3318                 }
   3319                 break;
   3320             case 'attachment':
   3321                 const attachmentInput = document.createElement('input');
   3322                 attachmentInput.style.display = 'none';
   3323                 attachmentInput.type = 'file';
   3324                 attachmentInput.multiple = true;
   3325                 attachmentInput.style.visibility = 'hidden';
   3326                 attachmentInput.style.display = 'none';
   3327                 document.body.append(attachmentInput);
   3328                 attachmentInput.onchange = (e) => {
   3329                     const files = [...attachmentInput.files]
   3330                     
   3331                     // Ensure there are no more than the max files allowed
   3332                     if (files.length + se.files.length > se.options.maxFiles) {
   3333                         alert(`Only ${se.options.maxFiles} files are allowed to upload in one batch.`);
   3334                         return;
   3335                     }
   3336 
   3337                     files.forEach((file) => se.attachFile(file));
   3338                     attachmentInput.remove();
   3339                 };
   3340                 attachmentInput.click();
   3341                 break;
   3342             case 'link':
   3343                 if (se.linkMenu.dataset.active === 'true') {
   3344                     se.closeLinkMenu();
   3345                 } else {
   3346                     if (window.getSelection().toString().split('\n').length > 1) {
   3347                         return;
   3348                     }
   3349 
   3350                     function traverseLink(trav, val) {
   3351                         if (trav && trav !== se.body) {
   3352                             if (trav.querySelector) {
   3353                                 const travQuery = trav.querySelector(`a[href="${val}"]`);
   3354                                 if (travQuery) {
   3355                                     return travQuery;
   3356                                 }
   3357                             }
   3358 
   3359                             if (trav.tagName === 'A' && trav.getAttribute('href') === val) {
   3360                                 return trav;
   3361                             } else {
   3362                                 return traverseLink(trav.parentElement, val);
   3363                             }
   3364                         } else {
   3365                             return se.body.querySelector(`a[href="${val}"]`);
   3366                         }
   3367                     }
   3368                     const r = se.getRange();
   3369 
   3370                     if (r) {
   3371                         if (r.collapsed) {
   3372                             const linkToEdit = document.createElement('a');
   3373                             linkToEdit.setAttribute('class', 'se-link-to-edit');
   3374 
   3375                             r.insertNode(linkToEdit);
   3376                         } else {
   3377                             if (se.browser.isFirefox() || se.browser.isEdge()) {
   3378                                 document.execCommand('createLink', false, '#');
   3379                             } else {
   3380                                 document.execCommand('createLink', true, '#');
   3381                             }
   3382 
   3383                             const travLink = traverseLink(r['startContainer'], '#');
   3384                             travLink && travLink.classList.add('se-link-to-edit');
   3385                         }
   3386 
   3387                         se.openLinkMenu();
   3388                     }
   3389 
   3390                     setTimeout(() => {
   3391                         const selection = se.linkMenu.querySelector('input[placeholder="Text content"]');
   3392 
   3393                         selection && (selection.value = document.getSelection().toString());
   3394                         se.linkMenu.querySelector('input').select();
   3395                     }, 100);
   3396                 }
   3397                 break;
   3398             case 'image':
   3399                 if (se.imageMenu.dataset.active === 'true') {
   3400                     se.closeImageMenu();
   3401                 } else {
   3402                     se.openImageMenu();
   3403 
   3404                     se.range = se.getRange();
   3405                     setTimeout(() => se.imageMenu.querySelector('input').focus(), 100);
   3406                 }
   3407                 break;
   3408             case 'table':
   3409                 if (se.tableMenu.dataset.active === 'true') {
   3410                     se.closeTableMenu();
   3411                 } else {
   3412                     se.openTableMenu();
   3413 
   3414                     se.range = se.getRange();
   3415                     setTimeout(() => se.tableMenu.querySelector('input').focus(), 100);
   3416                 }
   3417                 break;
   3418             case 'bold':
   3419                 if (se.body.textContent.trim() === '') {
   3420                     textDecorationInsert('b');
   3421                     break;
   3422                 }
   3423             case 'italic':
   3424                 if (se.body.textContent.trim() === '') {
   3425                     textDecorationInsert('i');
   3426                     break;
   3427                 }
   3428             case 'underline':
   3429                 if (se.body.textContent.trim() === '') {
   3430                     textDecorationInsert('u');
   3431                     break;
   3432                 }
   3433             case 'strikethrough':
   3434                 if (se.body.textContent.trim() === '') {
   3435                     textDecorationInsert('strike');
   3436                     break;
   3437                 }
   3438             default:
   3439                 if (se.browser.isFirefox() || se.browser.isEdge()) {
   3440                     input ? document.execCommand(command, false, input) : document.execCommand(command);
   3441                 } else {
   3442                     input ? document.execCommand(command, true, input) : document.execCommand(command, true);
   3443                 }
   3444                 break;
   3445         }
   3446 
   3447         if (command === 'indent') {
   3448             [...se.body.getElementsByTagName('blockquote')].forEach((bq) => {
   3449                 const wrapper = document.createElement('div');
   3450                 wrapper.innerHTML = bq.outerHTML;
   3451                 bq.replaceWith(wrapper);
   3452             });
   3453         }
   3454     }
   3455 
   3456     /**
   3457      * Ensures that the selection is within the body of the editor
   3458      * @param {*} contentEditableElement 
   3459      */
   3460     ensureSelectionInBody(contentEditableElement) {
   3461         if (contentEditableElement) {
   3462           const selection = window.getSelection();
   3463       
   3464           // Check if the contentEditableElement has focus and the selection is within it
   3465           if (document.activeElement !== contentEditableElement || !contentEditableElement.contains(selection.anchorNode)) {
   3466             contentEditableElement.focus(); // Ensure the element has focus
   3467       
   3468             const range = document.createRange();
   3469       
   3470             if (contentEditableElement.childNodes.length > 0) {
   3471               const lastChild = contentEditableElement.childNodes[contentEditableElement.childNodes.length - 1];
   3472       
   3473               if (lastChild.nodeType === Node.TEXT_NODE) {
   3474                 range.setStart(lastChild, lastChild.length);
   3475                 range.collapse(true);
   3476                 selection.removeAllRanges();
   3477                 selection.addRange(range);
   3478               } else {
   3479                 // If the last child is an element node, set the cursor after it.
   3480                 range.selectNodeContents(contentEditableElement);
   3481                 range.collapse(false); // Collapse to the end
   3482                 selection.removeAllRanges();
   3483                 selection.addRange(range);
   3484               }
   3485       
   3486             } else {
   3487               // If contenteditable is empty.
   3488               range.selectNodeContents(contentEditableElement);
   3489               range.collapse(false);
   3490               selection.removeAllRanges();
   3491               selection.addRange(range);
   3492             }
   3493           }
   3494         }
   3495       }
   3496   
   3497     /**
   3498      * Inserts a node into the editor
   3499      * @param {*} node
   3500      * @param {*} range
   3501      */
   3502     insertNode(node, range) {
   3503         const se = this;
   3504         // Ensre that any selected contents is deleted before inserting
   3505         range.deleteContents();
   3506         range.insertNode(node);
   3507         range.setStartAfter(node);
   3508 
   3509         se.setRange(range);
   3510     }
   3511 
   3512     /**
   3513      * Inserts images into the editor
   3514      * @param {*} files
   3515      * @returns
   3516      */
   3517     insertImages(files) {
   3518 
   3519         const se = this;
   3520         se.ensureSelectionInBody(se.body);
   3521         const currentRange = se.getRange();
   3522 
   3523         return new Promise((resolve, reject) => {
   3524             // Check if files has more than 25 files
   3525             if (files.length > se.options.maxFiles) {
   3526                 const errorMessage = `Only ${se.options.maxFiles} files are allowed to upload in one batch.`;
   3527                 alert(errorMessage);
   3528                 reject(errorMessage);
   3529                 return;
   3530             }
   3531 
   3532             // Add busy class to striven editor
   3533             se.editor.classList.add('se-image-uploading');
   3534             se._isImageUploading = true;
   3535 
   3536             // Create a promise chain to insert each image in the files array only after the previous one is completed.
   3537             // p = Promise.resolve() is used to start the chain with a resolved promise.
   3538             let p = Promise.resolve();
   3539             for (const file of files) {
   3540                 // Check if the file is an image
   3541                 if (!file.type.includes('image')) {
   3542                     continue;
   3543                 }
   3544                 p = p.finally(() => se.insertImage(file, currentRange));
   3545             }
   3546 
   3547             // Add the resolve to the end of the promise chain
   3548             p.finally(() => {
   3549                 // Remove busy class
   3550                 se.editor.classList.remove('se-image-uploading');
   3551                 se._isImageUploading = false;
   3552 
   3553                 // Check image overflow
   3554                 setTimeout(() => se.overflow(), 500);
   3555 
   3556                 resolve();
   3557             });
   3558         });
   3559     }
   3560 
   3561     /**
   3562      * Inserts image into the editor, uploads to the server if imageUrl is provided otherwise uses data:image url
   3563      * @param {*} file
   3564      * @returns
   3565      */
   3566     insertImage(file, range) {
   3567         const se = this;
   3568 
   3569         return new Promise((resolveImageInsert) => {
   3570             const bodyWidth = se.body.offsetWidth;
   3571 
   3572             getImageDataURL(file)
   3573                 .then((imgDataUrl) => {
   3574                     getImageDimensions(imgDataUrl)
   3575                         .then(({ width, height }) => {
   3576                             const { width: newWidth } = computeImageDimensions(width, height, bodyWidth);
   3577 
   3578                             if (se.options.imageUrl) {
   3579                                 //upload image if imageUrl is provided
   3580                                 se.getImage(imgDataUrl)
   3581                                     .then((imageUrl) => {
   3582                                         const img = createImageElement(imageUrl, newWidth);
   3583 
   3584                                         // Ensre that any selected contents is deleted before inserting
   3585                                         se.insertNode(img, range);
   3586 
   3587                                         resolveImageInsert();
   3588                                     })
   3589                                     .catch(() => {
   3590                                         // Create the image tag to insert
   3591                                         const img = createImageElement(imgDataUrl, newWidth);
   3592                                         img.setAttribute('data-data-url', 'true');
   3593 
   3594                                         // Ensre that any selected contents is deleted before inserting
   3595                                         se.insertNode(img, range);
   3596 
   3597                                         resolveImageInsert();
   3598                                     });
   3599                             } else {
   3600                                 // Create the image tag to insert
   3601                                 // Create the image tag to insert
   3602                                 const img = createImageElement(imgDataUrl, newWidth);
   3603                                 img.setAttribute('data-data-url', 'true');
   3604 
   3605                                 // Ensre that any selected contents is deleted before inserting
   3606                                 se.insertNode(img, range);
   3607 
   3608                                 resolveImageInsert();
   3609                             }
   3610                         })
   3611                         .catch((err) => {
   3612                             console.error(err);
   3613                             resolveImageInsert();
   3614                         });
   3615                 })
   3616                 .catch((err) => {
   3617                     console.error(err);
   3618                     resolveImageInsert();
   3619                 });
   3620         }).catch((err) => {
   3621             console.error(err);
   3622             resolveImageInsert();
   3623         });
   3624     }
   3625 
   3626     /**
   3627      * handles click event to show image editing option and resize markers on an image placed in editor body
   3628      * @param {*} e
   3629      */
   3630     handleImageClick(target) {
   3631         const se = this;
   3632         if (target.tagName === 'IMG') {
   3633             const image = target;
   3634 
   3635             if (!image.nextElementSibling || image.nextElementSibling.className !== 'se-image-options') {
   3636                 let resizeHandles = [];
   3637                 let imageWrapper = image.parentElement;
   3638                 let imageRect = image.getBoundingClientRect();
   3639 
   3640                 if (!imageWrapper.classList.contains('se-image-wrapper')) {
   3641                     //wrapper not present, create one
   3642                     imageWrapper = document.createElement('div');
   3643                     imageWrapper.classList.add('se-image-wrapper');
   3644                     imageWrapper.setAttribute('contenteditable', false);
   3645                     imageWrapper.style.width = `${imageRect.width}px`;
   3646                     imageWrapper.style.height = `${imageRect.height}px`;
   3647 
   3648                     image.parentElement.insertBefore(imageWrapper, image);
   3649                     imageWrapper.appendChild(image);
   3650 
   3651                     //Add a div that shows resize marker
   3652                     const resizeMarker = document.createElement('div');
   3653                     resizeMarker.classList.add('resize-marker');
   3654                     imageWrapper.appendChild(resizeMarker);
   3655 
   3656                     // Add resize handles (8 in total)
   3657                     const positions = [
   3658                         'top-left',
   3659                         'top-middle',
   3660                         'top-right',
   3661                         'left-middle',
   3662                         'right-middle',
   3663                         'bottom-left',
   3664                         'bottom-middle',
   3665                         'bottom-right'
   3666                     ];
   3667                     positions.forEach((pos) => {
   3668                         let handle = document.createElement('div');
   3669                         resizeHandles.push(handle);
   3670                         handle.classList.add('resize-handle', pos);
   3671                         imageWrapper.appendChild(handle);
   3672 
   3673                         handle.addEventListener('mousedown', function (e) {
   3674                             e.preventDefault();
   3675                             se.startImageResize(e, resizeMarker, pos, image);
   3676                         });
   3677 
   3678                         handle.addEventListener('touchstart', function (e) {
   3679                             e.preventDefault();
   3680                             se.startImageResize(e.touches[0], resizeMarker, pos, image);
   3681                         });
   3682                     });
   3683                 }
   3684 
   3685                 const editImageMenu = document.createElement('span');
   3686                 editImageMenu.setAttribute('class', 'se-image-options');
   3687                 editImageMenu.setAttribute('contenteditable', false);
   3688                 editImageMenu.onclick = (e) => e.stopPropagation();
   3689                 image.after(editImageMenu);
   3690 
   3691                 const changeOption = document.createElement('span');
   3692                 changeOption.textContent = 'Edit Image';
   3693                 changeOption.onclick = (e) => {
   3694                     e.preventDefault();
   3695                     e.stopPropagation();
   3696                     editImageMenu.remove();
   3697 
   3698                     image.classList.add('se-image-to-edit');
   3699                     se.openImageMenu(true);
   3700 
   3701                     // Get from the data-data-url attribute whether this link is a data url. The data attribute will be true if it is
   3702                     const isDataUrl = image.dataset.dataUrl;
   3703 
   3704                     const linkInputs = se.imageMenu.querySelectorAll('input');
   3705                     // If the image is a data url, we need to disable the source input and not set the value
   3706                     if (isDataUrl) {
   3707                         // Disable the input
   3708                         linkInputs[0].setAttribute('disabled', 'disabled');
   3709                     } else {
   3710                         // Enable the input
   3711                         linkInputs[0].removeAttribute('disabled');
   3712                         // Set the url of the image in the input
   3713                         linkInputs[0].value = image.getAttribute('src');
   3714                     }
   3715 
   3716                     linkInputs[1].value = image.getAttribute('alt');
   3717                     linkInputs[2].value = image.getAttribute('title');
   3718                     let imageWidth = parseFloat(image.getAttribute('width'));
   3719                     if (isNaN(imageWidth)) {
   3720                         // Get width from image element
   3721                         imageWidth = image.clientWidth;
   3722                     }
   3723 
   3724                     let imageHeight = parseFloat(image.getAttribute('height'));
   3725                     if (isNaN(imageHeight)) {
   3726                         // Get width from image element
   3727                         imageHeight = image.clientHeight;
   3728                     }
   3729 
   3730                     linkInputs[3].value = imageWidth;
   3731                     linkInputs[4].value = imageHeight;
   3732 
   3733                     setTimeout(() => linkInputs[0].select(), 100);
   3734                 };
   3735 
   3736                 editImageMenu.append(changeOption);
   3737 
   3738                 // When user clicks anywhere but the image, remove the menu
   3739                 const optionHandler = (ev) => {
   3740                     if (imageWrapper?.parentNode && ev.target !== image && ev.target !== imageWrapper && !resizeHandles.includes(ev.target)) {
   3741                         imageWrapper.parentNode.replaceChild(image, imageWrapper);
   3742                         window.removeEventListener('click', optionHandler);
   3743                     }
   3744                 };
   3745 
   3746                 window.addEventListener('click', optionHandler);
   3747 
   3748                 // When user presses a key, remove the menu
   3749                 const keyPressHandler = () => {
   3750                     if (imageWrapper?.parentNode) {
   3751                         imageWrapper.parentNode.replaceChild(image, imageWrapper);
   3752                     }
   3753                     se.body.removeEventListener('keypress', keyPressHandler);
   3754                 };
   3755                 se.body.addEventListener('keypress', keyPressHandler);
   3756             }
   3757         }
   3758     }
   3759 
   3760     startImageResize(e, resizeMarker, handlePosition, img) {
   3761         const se = this;
   3762         e.preventDefault && e.preventDefault();
   3763 
   3764         let startX = e.clientX;
   3765         let startY = e.clientY;
   3766         let startWidth = img.offsetWidth;
   3767         let startHeight = img.offsetHeight;
   3768         let startLeft = img.offsetLeft;
   3769         let startTop = img.offsetTop;
   3770         let aspectRatio = startWidth / startHeight; // Maintain original aspect ratio
   3771 
   3772         function mouseMoveHandler(e) {
   3773             if (e.touches) e = e.touches[0];
   3774 
   3775             let deltaX = e.clientX - startX;
   3776             let deltaY = e.clientY - startY;
   3777             let newWidth, newHeight;
   3778 
   3779             //update position and dimension of resize marker to show the resize effect
   3780             switch (handlePosition) {
   3781                 case 'top-left':
   3782                 case 'top-right':
   3783                 case 'bottom-left':
   3784                 case 'bottom-right':
   3785                     if (Math.abs(deltaX) > Math.abs(deltaY)) {
   3786                         newWidth = startWidth + (handlePosition.includes('left') ? -deltaX : deltaX);
   3787                         newHeight = newWidth / aspectRatio;
   3788                     } else {
   3789                         newHeight = startHeight + (handlePosition.includes('top') ? -deltaY : deltaY);
   3790                         newWidth = newHeight * aspectRatio;
   3791                     }
   3792                     break;
   3793                 case 'top-middle':
   3794                     newHeight = startHeight - deltaY;
   3795                     break;
   3796                 case 'bottom-middle':
   3797                     newHeight = startHeight + deltaY;
   3798                     break;
   3799                 case 'left-middle':
   3800                     newWidth = startWidth - deltaX;
   3801                     break;
   3802                 case 'right-middle':
   3803                     newWidth = startWidth + deltaX;
   3804                     break;
   3805                 default:
   3806                     newWidth = startWidth;
   3807                     newHeight = startHeight;
   3808             }
   3809 
   3810             if (handlePosition.includes('top')) {
   3811                 resizeMarker.style.top = startTop + deltaY + 'px';
   3812             }
   3813             if (handlePosition.includes('left')) {
   3814                 resizeMarker.style.left = startLeft + deltaX + 'px';
   3815             }
   3816             resizeMarker.style.width = newWidth + 'px';
   3817             resizeMarker.style.height = newHeight + 'px';
   3818         }
   3819 
   3820         function mouseUpHandler() {
   3821             //set properties of the image to the resized marker
   3822             let resizedRect = resizeMarker.getBoundingClientRect();
   3823 
   3824             img.width = resizedRect.width;
   3825             img.height = resizedRect.height;
   3826             //reset the wrapper dimension if it's present
   3827             let imageWrapper = img.parentElement;
   3828             if (imageWrapper.classList.contains('se-image-wrapper')) {
   3829                 imageWrapper.style.width = `${img.width}px`;
   3830                 imageWrapper.style.height = `${img.height}px`;
   3831             }
   3832 
   3833             //restore the marker back to the original position
   3834             resizeMarker.style.left = 0;
   3835             resizeMarker.style.top = 0;
   3836 
   3837             //recompute overflow style
   3838             setTimeout(function () {
   3839                 se.overflow();
   3840             }, 0);
   3841 
   3842             document.removeEventListener('mousemove', mouseMoveHandler);
   3843             document.removeEventListener('mouseup', mouseUpHandler);
   3844         }
   3845 
   3846         document.addEventListener('mousemove', mouseMoveHandler);
   3847         document.addEventListener('mouseup', mouseUpHandler);
   3848 
   3849         document.addEventListener('touchmove', mouseMoveHandler);
   3850         document.addEventListener('mouseend', mouseUpHandler);
   3851     }
   3852 }