7
votes

I'm trying to make a shortcode "plugin" - similar to what Wordpress uses with TinyMce. I'd like user to be able to insert a shortcode (like [gallery id="3"] or [image id="9"]) via a button and then show a placeholder instead of the actual shortcode. I'll put all the code to github once I get it to work.

Current setup

I have a button which inserts html to the editor using insertHtml() like this:

// Custom button code
CKEDITOR.instances['editor_instance_name'].insertHtml '<div class="media-library-gallery">[gallery id=' + gallery_id + ']</div>'

and I've added extraAllowedContent to allow div with the classes I need:

// CKEditor configuration (config.js)
config.extraAllowedContent = 'div(media-library-image,media-library-gallery)';

I managed to replace div.media-library-gallery with an image using the code below:

(function() {
  CKEDITOR.plugins.add('media_gallery', {

    init: function(editor) {
      CKEDITOR.addCss('.media_gallery{background: #f2f8ff url("/assets/gallery.png") no-repeat scroll center center; border: 1px dashed #888; display: block; width:100%; height: 250px;}');
    },

    afterInit: function( editor ) {
      var dataProcessor = editor.dataProcessor;
      var dataFilter = dataProcessor && dataProcessor.dataFilter;

      dataFilter.addRules({
        elements: {
          'div': function(element) {
            if (element.attributes.class == "media-library-gallery") {
              var fakeElement = editor.createFakeParserElement(element, 'media_gallery', 'div', false);
              return fakeElement;
            }
          }
        }
      })

    }

  })
})();

The problem

Currently the replacement nests a div inside the paragraph tag:

<p>
  <div class="media-library-gallery">[gallery id="5"]</div>
</p>

Shortcode replacement bug

I don't want to change the enterMode from the default CKEDITOR.ENTER_P but I want to get rid of the surrounding p. Can I do this using insertHtml or write a rule that would do that for me? Any other suggestions are welcome.

I've been digging around http://docs.ckeditor.com/ for a solution/inspiration but had little luck.

1

1 Answers

0
votes

A bit late, but try to insert your div as an element:

var element = CKEDITOR.dom.element.createFromHtml('<div class="media-library-gallery">[gallery id=' + gallery_id + ']</div>');
CKEDITOR.instances['editor_instance_name'].insertElement(element);