Draft JS unordered list bullet colour
Asked Answered
M

3

6

I've implemented Draft JS on a project as a simple editor but I'm having trouble styling unordered lists, specifically changing the colour of the bullets to match the text colour.

There doesn't seem to be information in the docs on how to apply styles to the li that wraps unordered-list-item items. I can select text and apply colours however this produces editor state like the following:

{
  "entityMap": {},
  "blocks": [
    {
      "key": "bcci",
      "text": "Heading",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [
        {
          "offset": 0,
          "length": 7,
          "style": "red"
        }
      ],
      "entityRanges": []
    },
    {
      "key": "28tv7",
      "text": "One",
      "type": "unordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [
        {
          "offset": 0,
          "length": 3,
          "style": "yellow"
        }
      ],
      "entityRanges": []
    },
    {
      "key": "85hig",
      "text": "Two",
      "type": "unordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [
        {
          "offset": 0,
          "length": 3,
          "style": "red"
        }
      ],
      "entityRanges": []
    },
    {
      "key": "6fkt5",
      "text": "Three",
      "type": "unordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [
        {
          "offset": 0,
          "length": 5,
          "style": "red"
        }
      ],
      "entityRanges": []
    },
    {
      "key": "ah3co",
      "text": "End",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [
        {
          "offset": 0,
          "length": 3,
          "style": "red"
        }
      ],
      "entityRanges": []
    }
  ]
}

enter image description here

Does anyone have experience / can point me in the direction of how to add colour to the bullets?

Update

After some investigation and reading the docs over and over, I was able to achieve the desired result by adding a custom blockStyleFn and adding custom classes to the li block:

_getBlockStyle (block) {
    const blockStyles = [];
    const styleMap = Object.keys(colorStyleMap);

    switch (block.getType()) {
      case 'unordered-list-item':
        // With draft JS we cannot output different styles for the same block type.
        // We can however customise the css classes:
        block.findStyleRanges((item) => {
          const itemStyles = item.getStyle();
          return _.some(styleMap, (styleKey) => itemStyles.includes(styleKey));
        }, (startCharacter) => {
          if (startCharacter === 0) {
            // Apply the same styling to the block as the first character
            _.each(block.getInlineStyleAt(startCharacter).toArray(), (styleKey) => {
              blockStyles.push(`block-style-${styleKey}`);
            });
          }
        });

        return blockStyles.join(' ');
      default:
        return null;
    }
  }

This also requires writing extra css classes for the block to match the styling of the colour blocks (e.g. .block-style-yellow { color: rgb(180, 180, 0, 1.0) } ).

An example of this working is available in this fiddle

enter image description here

Metonym answered 25/8, 2016 at 11:8 Comment(0)
G
1

Did you take a look at this block styling? https://facebook.github.io/draft-js/docs/advanced-topics-block-styling.html#content

I have not seen your entire code but what you are attempting is to give inline style may be that is the reason you see the text in desired color but not the bullet. Instead try changing the style for 'unordered-list-item' type at the time of rendering.

Gettysburg answered 25/8, 2016 at 22:20 Comment(1)
Thanks for the suggestion, got me on the right track! I've updated the question with a solution that works, but seems like a hacky way to have to add block styles. As long as it works right!Frap
F
1

Drfat-js can not apply different block styles to same block type. so you can:

  • inject different styles to html, use different block type for bullet colors and map the types to styles in blockStyleFn prop.

or

  • change the draft source like this, which you can set block style in block meta data.
Federico answered 26/8, 2016 at 6:13 Comment(0)
G
1

For those who want to have different bullet colors, here is how I did it.

  1. Use blockStyleFn prop to pass a getBlockStyle function.

    <Editor 
        blockStyleFn={this.getBlockStyle}
        decorators={customDecorators}>
    
    
  2. In this function, define a dynamic css class name for ordered or unordered list item. Use the block key to set a dynamic class name.

    getBlockStyle(block) { 
    if (block.getType() === "ordered-list-item" || block.getType() === "unordered-list-item") {
            return `color-for-${block.getKey()}`
          }
        }
    
    
  3. Use the draftJS decorators feature. Define a strategy. The customDecorators array is passed to the Editor decorators prop.

    const customDecorators = [{
        strategy: listStrategy,
        component: BulletListBlock }];
    
    
  4. Create a decorator component that dynamically set a css class in the head with the name you defined in step 2.

    import React from "react";
    interface Props {
        children: JSX.Element;
        contentState: any;
        blockKey: string;
    }
    
    const BulletListBlock: React.FC<Props> = (props) => {
        const contentBlock = props.contentState.getBlockForKey(props.blockKey);
    
        const colorValue = //use some logic here to retrieve color from contentBlock;
    
        var css = `.color-for-${props.blockKey} { color: ${colorValue}; }`;
        var head = document.head || document.getElementsByTagName('head')[0];
        var style = document.createElement('style');
    
        head.appendChild(style);
        style.appendChild(document.createTextNode(css));
    
        return <>
            { props.children }
        </>;
    };
    
    export default BulletListBlock;
    
Greysun answered 3/4, 2023 at 8:51 Comment(3)
The question seemed to refer to bullet color rather than bullet size.Coagulant
My bad, thanks for letting me know. I edited my answer after tried it for it fit with the question. This works the same for color or size.Greysun
I've recode this, and actually you do not need part 3 and 4. You just need to add a function in the part 2 before the return. this.appendCssClassToDomHead(block); this function will do the logic that was in part 3 and 4Greysun

© 2022 - 2024 — McMap. All rights reserved.