Search code examples
javascriptnode.jsgruntjswysiwygdom-events

Paste html content in Pell Editor and format with Striptags nodejs package


On our project we use pell WYSIWYG text editor, with following code:

import { moduleInit } from 'gs-components/export/js/_utils';
import pell from 'pell';

class Wysiwyg {
  constructor (element) {
    this._element = element;

    this._store = this._element.querySelector('.input__input')
    this._placeholder = this._element.querySelector('.input__label');
    this._element.appendChild(this._placeholder);


    this._editor = pell.init({
      element: this._element.querySelector('.wysiwyg__editor'),
      defaultParagraphSeparator: 'p',
      onChange: html => this._store.value = html,
      actions: [
        {
          name: 'heading2',
          icon: '<b>Überschrift</b>',
          title: 'Überschrift'
        },
        {
          name: 'paragraph',
          icon: 'Text',
          title: 'Text'
        },
        'bold',
        'italic',
        'underline',
        'olist',
        'ulist'
      ],
      classes: {
        button: 'gs-btn gs-btn--xs gs-btn--bordered',
        selected: 'gs-btn--dark'
      }
    });

    this._editor.content.innerHTML = this._store.value;

    const pellContent = this._element.querySelector('.pell-content');
    pellContent.addEventListener('focus', (e) => {
      this._store.dispatchEvent(this._buildEvent('focus'));
    });

    pellContent.addEventListener('blur', (e) => {
      this._store.dispatchEvent(this._buildEvent('blur'));
    });

    this._store.dispatchEvent(this._buildEvent('blur'));
  }

  _buildEvent(type) {
    const event = document.createEvent('HTMLEvents');
    event.initEvent(type, true, true);
    return event;
  }
}

export const init = () => moduleInit('.input--wysiwyg', element => {
  new Wysiwyg(element);
});

and we must implement paste event and striptags function:

Example

var striptags = require('striptags');

var html =
    '<a href="https://example.com">' +
        'lorem ipsum <strong>dolor</strong> <em>sit</em> amet' +
    '</a>';

striptags(html);
striptags(html, '<strong>');
striptags(html, ['a']);
striptags(html, [], '\n');

But, how and where?


Solution

  • Here is answer:

    pellContent.addEventListener('paste', (e) => {
      setTimeout(() => {
        this._editor.content.innerHTML = striptags(this._editor.content.innerHTML, ['h2', 'p', 'br', 'ul', 'ol', 'li']);
        this._store.value = this._editor.content.innerHTML;
      })
    });