facebookarchive / draft-js

A React framework for building text editors.

Home Page:https://draftjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to integrate the 'color' example into the 'rich' example

yi-jy opened this issue · comments

commented

I ran the color example and the rich example provided by the official website, The 'color' example code
indicates that only one color can be selected simultaneously. And The 'rich' example INLINE_STYLES part can multiple choices at the same time.

I tried to integrate the 'color' example into the 'rich' example, But found that you can only single select(apply color code) or only choose more(apply 'rich' code). I expect to The 'rich' example INLINE_STYLES
keep multiple select, and keep 'color' part keep single-select. But I failed after many attempts. I really want to know how can I integrate them? Does anyone know the solution, or related ideas?

commented

The problem has been solved.

Hi @joy-yi0905, thanks for your interest in Draft.js!

Do you mind sharing your solution so others can refer to this issue in case they're stuck?

Thanks!

commented

@claudiopro Certainly! In fact, as long as the content of the click is judged when clicked, if the clicked content can only be single-selected, the other styles in the group are removed.

const COLORS = [
  {label: 'Red', style: 'COLOR_RED'},
  {label: 'Orange', style: 'COLOR_ORANGE'},
  {label: 'Yellow', style: 'COLOR_YELLOW'},
];

...

// Unset style override for current color.
if (selection.isCollapsed()) {
  nextEditorState = currentStyle.reduce((state, color) => {

    // If the current selection is clicked on color
    // And when the current style contains color, just remove other colors
    if (toggledColor.includes('COLOR') && color && color.includes('COLOR')) {
      return RichUtils.toggleInlineStyle(state, color);
    } else {
      return RichUtils.toggleInlineStyle(state);
    }
  }, nextEditorState);
}

// If the color is being toggled on, apply it.
nextEditorState = RichUtils.toggleInlineStyle(
  !currentStyle.has(toggledColor) ? nextEditorState : this.state.editorState,
  toggledColor
)

I wrote a lightweight project, and it contains a related demo.