0

I'm working on a Google Fonts plugin for WordPress and I try to have the same effect as the core WYSIWYG editor. Basically when you click on element (inside the Editor) with font class I want to get the class and then based on that reload the font family/style listbox in the Toolbar.

(I found couple of hacks here on SO like this one Proper Way Of Modifying Toolbar After Init in TinyMCE but nothing that works like the WP core example)

There is the same functionality when you click on P, H1, H3, H3 ... How they do it? Can you point me at least to the JS file in WordPress distro; I think I can figure it out if see the code.

Here is GIF that demonstrates what I'm talking about. Thanks in advance.

enter image description here

krasenslavov
  • 355
  • 1
  • 4
  • 14

1 Answers1

1

I found the solution and because it's not a hack, like the other ones I found on SO, I will post it in here and hopes it will help anyone else that's trying to do something similar.

First to access the button/listbox need to use onpostrender with a callback function.

editor.addButton( 'developry_google_font_family_button', {
   type  : 'listbox',
   onpostrender : fontFamilyNodeChange,
   value : '',
...

Next the callback function should look something like this:

function fontFamilyNodeChange() {
    var listbox = this;
    editor.on('NodeChange', function( e ) {
        // This next part is specific for my needs but I will post it as an example.
        var selected = [];
        if ( $( e.element ).hasClass( 'mce-ga' ) )  { // this a class I add to all elements that have google fonts format
            // Then I strip the classes from classList that I don't need and add the rest into an array (e.g ['roboto', '100'])
            var gfont_options = $( e.element ).attr('class')
                .replace('mce-ga', '')
                    .replace('mce-family-', '')
                        .replace('mce-weight-', '')
                            .trim()
                                .split(' ');
            selected.push( gfont_options );
            // At end I add the new value to listbox select[0][0] (e.g. 'roboto')
            listbox.value(selected[0][0]);
        }
    });
}

And here is an example:

enter image description here

krasenslavov
  • 355
  • 1
  • 4
  • 14
  • One more thing that I had to figure out if you want to pass an additional args to `fontFamilyNodeChange` the code need to change as follow. `onpostrender : function() { fontFamilyNodeChange( this, 'option' ) }` – krasenslavov Jul 03 '18 at 16:13