Franz
Franz

Reputation: 675

How to remove old tinymce style_format classes when changing / updating format

I have created some custom style formats, that add a class to a block level element. The problem is that when I apply one style it keeps the old class and adds the new class.

How do I remove the old class when switching to another format?

mce_options_article = {
        // ...
        formats: {
          p_grey: { selector: 'p', classes: 'grey' },
          p_red: { selector: 'p', classes: 'red' } 
        },
        style_formats: [
          {title: 'Paragraph Color', items: [
            {title: 'Grey ', format:'p_grey'},
            {title: 'Red ', format:'p_red'},
           ]},
        ]
        // ...
    }

Upvotes: 2

Views: 2029

Answers (3)

ZalemCitizen
ZalemCitizen

Reputation: 534

When you build complex custom style_formats menu with nested submenus, it may be useful to get rid of the previous classes inside a submenu (= group inside style_formats) but not of others. So the solution with attributes/class from @Franz is good but too brutal :)

Example :

style_formats
- font sizes
-- size 1 applies 'fs-1' class
-- size 2 applies 'fs-2' class
- text colors
-- color 1 applies 'text-color1' class
-- color 2 applies 'text-color2' class

When applying color 2, you want to get rid of color 1 but NOT of size-1 or size-2.

This was tested on TinyMCE 4 (in a Wordpress context). Vanilla JS.

  1. Add an exclusive: true property in your style_formats for groups needing this behaviour :
  [{
    "title":"Color",
    "exclusive":true,
    "items":[{"title":"color 1","classes":"text-color1","inline":"span"}],
  },...]
  1. Use an event listener on BeforeExecCommand to get rid of classes of style formats items in same group.
tinymce.on( 'AddEditor', function( e ) {

    /**
     * Recurse among style_formats setting to find siblings of an item name
     * @returns array of items of same group if group is exclusive, else empty array
     */
    const searchGroupItems = ( itemName, items, isParentExclusive ) => {
      for( const item of items ) {
        if( item.items ) {
          return searchGroupItems( itemName, item.items, item.exclusive )
        }
        else if( item.name && item.name == itemName ) {
          if( isParentExclusive ) {
            return items
          }
          else {
            return []
          }
        }
      }

      return []
    }

    e.editor
    .on( 'BeforeExecCommand', function( ev ) {
      // Filter on format selector action only
      if( ev.command == 'mceToggleFormat' ) {
        /**
         * Unselect other items of same group if group is exclusive
         */
        const itemName = ev.value
        let groupItems = []

        // Search siblings items in style_formats
        for( const group of e.editor.settings.style_formats ) {
          if( ! group.items ) {
            continue
          }
          
          if( groupItems = searchGroupItems( itemName, group.items ) ) {
            break
          }
        }
        
        // clicked style_format is among an exclusive list
        if( groupItems.length ) {
          const styleFormat   = groupItems.filter( it => it.name == itemName ).find( () => true ) // get first element of array
          const otherFormats  = groupItems.filter( it => it.name != itemName )
          const domSelection  = ev.target.selection
          
          // style_format is applying classes
          if( styleFormat && styleFormat.classes ) {
            const parentSelector = styleFormat.inline ? styleFormat.inline : ( styleFormat.selector ? styleFormat.selector : null )
            // style_format applies to inline tag
            if( parentSelector ) {
              const parent = domSelection.getNode().closest( parentSelector )

              // Selection (or caret) is inside a matching parent
              if( parent ) {
                // Remove classes brought by any other styles in same group
                for( const sF of otherFormats ) {
                  if( sF.classes && Array.isArray( sF.classes ) ) {
                    parent.classList.remove( ...sF.classes )
                  }
                }
              }
              // else, the selection may be wrapped in a new parent, no class to remove
            }
          }
        }
      }
    } )

  } )

Besides, due to TinyMCE native beahviour, the style_formats are automatically unselected (since you got rid of classes they bring)

Upvotes: 0

Jon Knight
Jon Knight

Reputation: 317

The solution of using formats and then referencing them in style_formats didn't work for me (using TinyMCE v4.x), I think because I was trying to define 2 sets of styles for H tags - one with a class and one without. It resulted in all of the styles being disabled (I'm not entirely sure why).

I ended up adding an event handler for ExecCommand in the setup:

    setup: function (editor) {
        editor.on('ExecCommand', function (e) {

            if (e.command === 'mceToggleFormat' && e.value.startsWith('custom')) {
                var format = e.target.settings.style_formats.filter(obj => { return obj.name === e.value; })[0];
                e.target.selection.getSelectedBlocks()[0].className = format.classes ? format.classes.join(' ') : '';
            }
        });
    }

This seems to work ok, but doesn't always seem to highlight the current format when the 'Format' dropdown is shown, although I think that this is due to the style formats I have defined, rather than the above code.

I hope this helps someone out with the same issue that I had, but obviously test it thoroughly with your code before using it.

Upvotes: 2

Franz
Franz

Reputation: 675

Use attributes instead of classes.

This is what I did:

mce_options_article = {
    // ...
    formats: {
      p_grey: { selector: 'p', attributes: {'class':'grey'} }, // use attributes
      p_red: { selector: 'p', attributes: {'class':'red'} } // use attributes
    },
    style_formats: [
      {title: 'Paragraph Color', items: [
        {title: 'Grey ', format:'p_grey'},
        {title: 'Red ', format:'p_red'},
       ]},
    ]
    // ...
}

Upvotes: 10

Related Questions