New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TinyMceArea as htmlArea replacement #9344

Open
stahl-riesa opened this Issue May 24, 2017 · 3 comments

Comments

Projects
None yet
4 participants
@stahl-riesa
Contributor

stahl-riesa commented May 24, 2017

Just a suggestion for wrapping / using better developed editors in an qooxdoo enviroment

/*
have to be included:
/tinymcearea/tinymce/tinymce.min.js
/tinymcearea/tinymce/themes/modern/theme.min.js
*/

qx.Class.define("qx.ui.form.TinyMceArea",
{
  extend : qx.ui.core.Widget,

  implement : qx.ui.form.IStringForm,

  construct : function(value)
  {
    this.base(arguments);

    if (value != null) {
      this.setValue(value);
    }

    this.getContentElement().addListenerOnce("appear", function() {
      tinymce.baseURL = '../tinymcearea/tinymce';
      tinymce.suffix  = '.min';

      tinymce.PluginManager.add('autoheight', function(editor) {
        var editor_container;
        var bars_height = 0;

        function resizeEditor(e) {
          if (typeof(editor_container) === 'undefined') return;

          try {
            var element_height = parseInt(window.getComputedStyle(editor_container).height);
            /*calculate bar height only once*/
            if (bars_height === 0) {
              var toolbars = editor_container.querySelectorAll('.mce-toolbar, .mce-statusbar, .mce-menubar');
              /*IE11 FIX*/
              var toolbarsLength = toolbars.length;
              for (var i = 0; i < toolbarsLength; i++) {
                var toolbar = toolbars[i];
                /*skip sidebar*/
                if (!toolbar.classList.contains('mce-sidebar-toolbar')) {
                  var bar_height = parseInt(window.getComputedStyle(toolbar).height);
                  bars_height += bar_height;
                }
              }
            }
            /*the extra 8 is for margin added between the toolbars*/
            new_height = element_height - bars_height - 8;
            editor.theme.resizeTo('100%', new_height);
          } catch (err) {
            console.log(err);
          }
        }

        editor.on('ResizeWindow', resizeEditor);
        editor.on("Init", function() {
          try {
            editor_container = editor.getContainer().parentNode;
          } catch (e) {}
          setTimeout(function() {
            resizeEditor();
          }, 10);
        });
      });

      tinymce.init({
        selector: "#" + this._getTextareaId(),
        menubar: false,
        branding: false,
        resize: false,
        plugins: 'autoheight lists link anchor searchreplace visualblocks code',
        code_dialog_width: 700,
        toolbar: 'undo redo | bold italic | bullist numlist | link | code',
        init_instance_callback: function (editor) {
          editor.on('KeyUp', function () {
            this.__fireChangeValueEvent();
          }.bind(this));
          editor.on('Change', function () {
            this.__fireChangeValueEvent();
          }.bind(this));
          editor.on('Focus', function () {
            this.fireNonBubblingEvent("focusin", qx.event.type.Focus);
          }.bind(this));
          editor.on('Blur', function () {
            this.fireNonBubblingEvent("focusout", qx.event.type.Focus);
          }.bind(this));
        }.bind(this),
        setup: function (editor) {
          editor.on('Init', function () {
            this.__initDone = true;
            this.setValue(this.__oldValue);
          }.bind(this));
        }.bind(this),
      });
    }, this);
  },

  events :
  {
    "changeValue" : "qx.event.type.Data"
  },

  members :
  {
    __initDone : false,
    __oldValue : "",

    _getTextareaId : function()
    {
      return "taid-" + this.toHashCode();
    },

    // overridden
    _createContentElement : function()
    {
      return new qx.html.Input("textarea", {
        overflowX: "auto",
        overflowY: "auto"
      }, {
        id: this._getTextareaId()
      });
    },

    getValue : function()
    {
      return this.__initDone ? tinymce.get(this._getTextareaId()).getContent() : this.__oldValue;
    },

    setValue : function(value)
    {
      if( this.__initDone )
      {
        var editor = tinymce.get(this._getTextareaId());
        editor.setContent(value);
        editor.undoManager.clear();
      } else {
        this.__oldValue = value;
      }
    },

    __fireChangeValueEvent : function()
    {
      var value = this.getValue();
      var old = this.__oldValue;

      if( value != this.__oldValue )
      {
        this.__oldValue = value;

        this.fireNonBubblingEvent("changeValue", qx.event.type.Data, [value, old]);
      }
    }
  }
});
@oetiker

This comment has been minimized.

Show comment
Hide comment
@oetiker

oetiker May 24, 2017

Member

how about making this a contrib? we also have dynamic loader support in core now, so you can tell qx to load the external js libraries and once they are loaded start using them ...

Member

oetiker commented May 24, 2017

how about making this a contrib? we also have dynamic loader support in core now, so you can tell qx to load the external js libraries and once they are loaded start using them ...

@stahl-riesa

This comment has been minimized.

Show comment
Hide comment
@stahl-riesa

stahl-riesa May 29, 2017

Contributor

First of all this should be a suggestion you all qooxdoo user, which are looking for a htmlarea replacement. If this implementation works und I have got some free time for developing stuff, I could make a contrib.

Contributor

stahl-riesa commented May 29, 2017

First of all this should be a suggestion you all qooxdoo user, which are looking for a htmlarea replacement. If this implementation works und I have got some free time for developing stuff, I could make a contrib.

@johnspackman

This comment has been minimized.

Show comment
Hide comment
@johnspackman

johnspackman May 30, 2017

Member

I switched from TinyMCE to MediumEditor - it is lighter and has less quirks than TinyMCE, and when presenting a rich text editor to users it's simplicity gives a much better user experience. This should also be a contrib, but FWIW this is my code:

/**
 * @asset(grasshopper/medium-editor/*)
 * @ignore(MediumEditor)
 */
qx.Class.define("grasshopper.af.ui.editor.Medium", {
  extend: qx.ui.core.Widget,
  implement: [ qx.ui.form.IStringForm, qx.ui.form.IForm ],
  include: [ qx.ui.form.MForm ],
  
  construct: function(initFn) {
    this.base(arguments);
    this.__initFn = initFn;
    grasshopper.af.ScriptLoader
      .loadScript([ "grasshopper/medium-editor/js/medium-editor.js" ], this.__onScriptLoaded, this)
      .loadStylesheet([ "grasshopper/medium-editor/css/medium-editor.css",
                        "grasshopper/medium-editor/css/themes/mani.css",
                        "grasshopper/medium-editor/css/themes/grasshopper.css" ]);
    
    this.__changeValueTimeout = new grasshopper.utils.Timeout(500, function() {
      if (this.hasListener("changeValue"))
        this.fireDataEvent("changeValue", this.getValue());
    }, this);
    
    this.addListenerOnce("appear", function() {
      this.__initEditor();
    }, this);
    
    this.addListener("disappear", function(evt) {
      if (this.__editor) {
        this.__editor.getExtensionByName('toolbar').hideToolbar();
        var t = this;
        setTimeout(function() {
          t.__editor.getExtensionByName('toolbar').hideToolbar();
        }, 100)
      }
    }, this);
  },
  
  events: {
    "change": "qx.event.type.Event",
    "changeValue": "qx.event.type.Data"
  },

  properties: {
    readOnly: {
      init: false,
      check: "Boolean",
      apply: "_applyReadOnly"
    },
    
    appearance: {
      init: "textarea",
      refine: true
    },
    
    // overridden
    selectable: {
      refine: true,
      init: true
    },

    // overridden
    focusable: {
      refine: true,
      init: true
    },

    /**
     * Whether the {@link #changeValue} event should be fired on every
     * key input. If set to true, the changeValue event is equal to the
     * {@link #input} event.
     */
    liveUpdate: {
      check: "Boolean",
      init: false
    }

  },


  members: {
    __pendingValue: null,
    __changeValueTimeout: false,
    __initialised: false,
    __inChangeEvent: false,
    
    __onScriptLoaded: function(originalUrl, url) {
      this.__scriptsLoaded = true;
      if (this.isDisposed())
        return;
      this.__initEditor();
    },
    
    __initEditor: function() {
      var el = this.getContentElement().getDomElement();
      if (this.__editor || !this.__scriptsLoaded || !el)
        return;
      
      el.innerHTML = this.__pendingValue||"<p></p>";
      var opts = {
          toolbar: {
            buttons: 
              [
                "bold", "italic", "underline", "anchor", "header1", "header2",
                "unorderedlist", "orderedlist", "justifyLeft", "justifyCenter", "justifyFull", "justifyRight",
                "indent", "outdent",
                "quote"
              ]
          },
          cleanPastedHTML: true,
          forcePlainText: false
        };
      if (this.__initFn)
        opts = this.__initFn(opts);
      var ed = this.__editor = new MediumEditor(el, opts);
      ed.subscribe("editableInput", this._onNativeInput.bind(this));
      this.__initialised = true;
      if (this.isReadOnly()) {
        el.setAttribute("readOnly", true);
        el.setAttribute("contenteditable", "false");
      }
    },
    
    _onNativeInput: function(evt) {
      if (this.isReadOnly()) {
        if (typeof evt.preventDefault == "function")
          evt.preventDefault();
        else if (typeof evt.stopPropagation == "function")
          evt.stopPropagation();
        return;
      }
      this.fireEvent("change");
      this.__changeValueTimeout.resetTimer();
    },
    
    /*
     * @Override
     */
    _createContentElement: function() {
      var elOuter = new qx.html.Element("div");
      elOuter.setStyles({
        "overflow": "scroll"
      });
      return elOuter;
    },

    /*
     * @Override
     */
    /*
    _getContentHint: function() {
      var hint = this.base(arguments);

      // two lines of text by default
      hint.height = hint.height * 2;

      // 10 character wide
      hint.width = 16 * 10;

      return hint;
    },
    */

    /*
     * @Override
     */
    /*
    renderLayout: function(left, top, width, height) {
      var result = this.base(arguments, left, top, width, height - 7);
      this._width = width;
      this._height = height;
      this._resizeEditor();
      return result;
    },
    */

    /**
     * Resizes MCE to match the widget
     */
    _resizeEditor: function() {
      /*
      if (this.__editor)
        this.__editor.theme.resizeTo(this._width - 2, this._height - 2);
        */
    },

    /*
     * @Override
     */
    getFocusElement : function() {
      var el = this.getContentElement();
      if (el) {
        return el;
      }
    },

    /*
     * @Override
     */
    _applyEnabled: function(value, oldValue) {
      this.base(arguments, value, oldValue);
    },

    _applyReadOnly: function(value, oldValue) {
      var element = this.getContentElement();

      element.setAttribute("readOnly", value);
      element.setAttribute("contenteditable", value ? "false" : "true");

      if (value) {
        this.addState("readonly");
        this.setFocusable(false);
      } else {
        this.removeState("readonly");
        this.setFocusable(true);
      }
    },
    
    /**
     * Sets the value of the textfield to the given value.
     * 
     * @param value
     *          {String} The new value
     */
    setValue: function(value) {
      if (this.__inChangeEvent)
        return;
      if (this.__initialised) {
        value = value || "";
        var el = this.getContentElement().getDomElement();
        var current = el.innerHTML;
        if (current != value)
          el.innerHTML = value;
      } else
        this.__pendingValue = value;
    },

    /**
     * Returns the current value of the textfield
     * 
     * @return {String|null} The current value
     */
    getValue: function() {
      if (!this.__initialised)
        return this.__pendingValue;
      var el = this.getContentElement().getDomElement();
      var current = el.innerHTML;
      return current;
    },

    /**
     * Resets the value to the default
     */
    resetValue: function() {
      this.setValue(null);
    }    
  }
});

I think this will work just fine, except that you'll have to replace calls to grasshopper.af.ScriptLoader with the standard qx.util.ScriptLoader

Member

johnspackman commented May 30, 2017

I switched from TinyMCE to MediumEditor - it is lighter and has less quirks than TinyMCE, and when presenting a rich text editor to users it's simplicity gives a much better user experience. This should also be a contrib, but FWIW this is my code:

/**
 * @asset(grasshopper/medium-editor/*)
 * @ignore(MediumEditor)
 */
qx.Class.define("grasshopper.af.ui.editor.Medium", {
  extend: qx.ui.core.Widget,
  implement: [ qx.ui.form.IStringForm, qx.ui.form.IForm ],
  include: [ qx.ui.form.MForm ],
  
  construct: function(initFn) {
    this.base(arguments);
    this.__initFn = initFn;
    grasshopper.af.ScriptLoader
      .loadScript([ "grasshopper/medium-editor/js/medium-editor.js" ], this.__onScriptLoaded, this)
      .loadStylesheet([ "grasshopper/medium-editor/css/medium-editor.css",
                        "grasshopper/medium-editor/css/themes/mani.css",
                        "grasshopper/medium-editor/css/themes/grasshopper.css" ]);
    
    this.__changeValueTimeout = new grasshopper.utils.Timeout(500, function() {
      if (this.hasListener("changeValue"))
        this.fireDataEvent("changeValue", this.getValue());
    }, this);
    
    this.addListenerOnce("appear", function() {
      this.__initEditor();
    }, this);
    
    this.addListener("disappear", function(evt) {
      if (this.__editor) {
        this.__editor.getExtensionByName('toolbar').hideToolbar();
        var t = this;
        setTimeout(function() {
          t.__editor.getExtensionByName('toolbar').hideToolbar();
        }, 100)
      }
    }, this);
  },
  
  events: {
    "change": "qx.event.type.Event",
    "changeValue": "qx.event.type.Data"
  },

  properties: {
    readOnly: {
      init: false,
      check: "Boolean",
      apply: "_applyReadOnly"
    },
    
    appearance: {
      init: "textarea",
      refine: true
    },
    
    // overridden
    selectable: {
      refine: true,
      init: true
    },

    // overridden
    focusable: {
      refine: true,
      init: true
    },

    /**
     * Whether the {@link #changeValue} event should be fired on every
     * key input. If set to true, the changeValue event is equal to the
     * {@link #input} event.
     */
    liveUpdate: {
      check: "Boolean",
      init: false
    }

  },


  members: {
    __pendingValue: null,
    __changeValueTimeout: false,
    __initialised: false,
    __inChangeEvent: false,
    
    __onScriptLoaded: function(originalUrl, url) {
      this.__scriptsLoaded = true;
      if (this.isDisposed())
        return;
      this.__initEditor();
    },
    
    __initEditor: function() {
      var el = this.getContentElement().getDomElement();
      if (this.__editor || !this.__scriptsLoaded || !el)
        return;
      
      el.innerHTML = this.__pendingValue||"<p></p>";
      var opts = {
          toolbar: {
            buttons: 
              [
                "bold", "italic", "underline", "anchor", "header1", "header2",
                "unorderedlist", "orderedlist", "justifyLeft", "justifyCenter", "justifyFull", "justifyRight",
                "indent", "outdent",
                "quote"
              ]
          },
          cleanPastedHTML: true,
          forcePlainText: false
        };
      if (this.__initFn)
        opts = this.__initFn(opts);
      var ed = this.__editor = new MediumEditor(el, opts);
      ed.subscribe("editableInput", this._onNativeInput.bind(this));
      this.__initialised = true;
      if (this.isReadOnly()) {
        el.setAttribute("readOnly", true);
        el.setAttribute("contenteditable", "false");
      }
    },
    
    _onNativeInput: function(evt) {
      if (this.isReadOnly()) {
        if (typeof evt.preventDefault == "function")
          evt.preventDefault();
        else if (typeof evt.stopPropagation == "function")
          evt.stopPropagation();
        return;
      }
      this.fireEvent("change");
      this.__changeValueTimeout.resetTimer();
    },
    
    /*
     * @Override
     */
    _createContentElement: function() {
      var elOuter = new qx.html.Element("div");
      elOuter.setStyles({
        "overflow": "scroll"
      });
      return elOuter;
    },

    /*
     * @Override
     */
    /*
    _getContentHint: function() {
      var hint = this.base(arguments);

      // two lines of text by default
      hint.height = hint.height * 2;

      // 10 character wide
      hint.width = 16 * 10;

      return hint;
    },
    */

    /*
     * @Override
     */
    /*
    renderLayout: function(left, top, width, height) {
      var result = this.base(arguments, left, top, width, height - 7);
      this._width = width;
      this._height = height;
      this._resizeEditor();
      return result;
    },
    */

    /**
     * Resizes MCE to match the widget
     */
    _resizeEditor: function() {
      /*
      if (this.__editor)
        this.__editor.theme.resizeTo(this._width - 2, this._height - 2);
        */
    },

    /*
     * @Override
     */
    getFocusElement : function() {
      var el = this.getContentElement();
      if (el) {
        return el;
      }
    },

    /*
     * @Override
     */
    _applyEnabled: function(value, oldValue) {
      this.base(arguments, value, oldValue);
    },

    _applyReadOnly: function(value, oldValue) {
      var element = this.getContentElement();

      element.setAttribute("readOnly", value);
      element.setAttribute("contenteditable", value ? "false" : "true");

      if (value) {
        this.addState("readonly");
        this.setFocusable(false);
      } else {
        this.removeState("readonly");
        this.setFocusable(true);
      }
    },
    
    /**
     * Sets the value of the textfield to the given value.
     * 
     * @param value
     *          {String} The new value
     */
    setValue: function(value) {
      if (this.__inChangeEvent)
        return;
      if (this.__initialised) {
        value = value || "";
        var el = this.getContentElement().getDomElement();
        var current = el.innerHTML;
        if (current != value)
          el.innerHTML = value;
      } else
        this.__pendingValue = value;
    },

    /**
     * Returns the current value of the textfield
     * 
     * @return {String|null} The current value
     */
    getValue: function() {
      if (!this.__initialised)
        return this.__pendingValue;
      var el = this.getContentElement().getDomElement();
      var current = el.innerHTML;
      return current;
    },

    /**
     * Resets the value to the default
     */
    resetValue: function() {
      this.setValue(null);
    }    
  }
});

I think this will work just fine, except that you'll have to replace calls to grasshopper.af.ScriptLoader with the standard qx.util.ScriptLoader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment