Wagtail: Extending the Draftail Editor Part 4 - Custom Lists

Introduction

I started this as an afterthought for the second part on block styles and realised it required some lengthy explanation.

It's next to impossible to find information on creating your own lists in Draftail, and what I have found has been through accident, code trawling and experimentation.

The discussion below is based purely on that, so if you do find a supported way to customise lists without creating a brand new entity, I would love to hear about it.

Registering a Custom List Style

Using the List Handlers

Much like the BlockElementHandler and InlineStyleElementHandler methods, there are two for registering lists:

from wagtail.admin.rich_text.converters.html_to_contentstate import ListElementHandler, ListItemElementHandler

You use ListElementHandler to register your <ul> or <ol> styled element. <dl> is not supported. To call it and have a supported list created in the editor, it must be called with either ListElementHandler("unordered-list-item") or ListElementHandler("ordered-list-item").

Use ListItemElementHandler for your styled <li> elements. This is called without any parameters.

So a db_conversion definition might look like the following:

db_conversion = {
    "from_database_format":  {
        "ul[class='custom-list-wrapper']": ListElementHandler("unordered-list-item"),
        "li[class='custom-list']": ListItemElementHandler(),
    },
    "to_database_format": {
        "block_map": {
            type_: {
                "element": "li",
                "wrapper": "ul class='custom-list-wrapper'",
                "props": {
                    "class": "custom-list"
                }
            }
        },
    }
}

The Problem

This will render fine on the front-end with

<ul class="custom-list-wrapper">
    <div class="custom-list" data-block-key="...">Item #1</div>
    <div class="custom-list" data-block-key="...">Item #2</div>
    <div class="custom-list" data-block-key="...">Item #3</div>
</ul>

However, in the editor, no custom style is applied, the custom list looks like any other unordered list with the same bullet style as normal.

This is because, in the editor, the <ul> is formatted with public-DraftStyleDefault-ul and the <li> with Draftail-block--unordered-list-item public-DraftStyleDefault-unorderedListItem public-DraftStyleDefault-reset public-DraftStyleDefault-depth0 public-DraftStyleDefault-listLTR (!!). The custom classes we registered with don't make it into the editor.

A Workaround (with limitations)

What if you call you call ListElementHandler with your own string?

You won't throw an error, but what will happen is that, in the editor, your <ul>/<ol> will be missing completely while the <li> elements will be rendered as <div> elements instead.

Your front-end will still be rendered correctly, but in the editor, you've lost your list styling (you can't apply the ::marker pseudo element to a <div> element), and also list behaviour: you can't nest list items, and each element must have the style applied to it (you can't continue the list by simply pressing enter).

This is the same behaviour that happens if you just call BlockElementHandler for your <li> element and register your <ul> as a wrapper.

For example:

db_conversion = {
    "from_database_format":  {
        "li[class='custom-list']": BlockElementHandler (_type),
    },
    "to_database_format": {
        "block_map": {
            type_: {
                "element": "li",
                "wrapper": "ul class='custom-list-wrapper'",
                "props": {
                    "class": "custom-list"
                }
            }
        },
    }
}

Rendering the Custom List in the Editor

Looking at the rendered code, each list item element is an <li> element with css class Draftail-block--type as for a normal block. Nested in that is another <div> element with css class public-DraftStyleDefault-block. There's no <ul> element wrapping the list items in the editor however.

<li class="Draftail-block--custom-list  public-DraftStyleDefault-reset public-DraftStyleDefault-depth0 public-DraftStyleDefault-listLTR"
    data-block="true" data-editor="5vqca" data-offset-key="bctdk-0-0">
    <div data-offset-key="bctdk-0-0" class="public-DraftStyleDefault-block public-DraftStyleDefault-ltr">
        <span data-offset-key="bctdk-0-0">
            <span data-text="true">Lorem ipsum dolor sit amet....</span>
        </span>
    </div>
</li>

We can set a ::before pseudo class to our custom type to display our styled bullet, but this will place it on its own line. To fix that, we target the inner <div> to set the before and add some css to mimic the indented paragraph.

I'll set out how to do this in the example below.

Example: Custom List Style with Check Mark Bullets

Before I continue, in case you skipped the sections before, there are a couple of limitations with this:

  1. This will only let you create a single level list, no nested/multi-tiered lists are possible with this method.
  2. The list style must be applied to each element, it won't continue the list when pressing enter. The easiest usage is to enter all the list items in the editor then apply the list with all items selected.
fa-solid fa-triangle-exclamation fa-lg Important!
Your editor features must include 'ol' or 'ul' (depending on which you use) as well as the custom list to render correctly in the editor. Without this, the editor will insert a blank line above the list when it next reloads after saving the page. The examples below both make use of 'ul' only.

Add the front end styling

I'll need two css classes here, one for <li> (check-list) and one for the <ul> (check-list-wrapper). Additionally, I'll create a ::marker pseudo class to add the bullet icon. I'm using the unicode character \1F5F9 which renders šŸ—¹:

.check-list {
  margin-bottom: 0.1em;
}
.check-list::marker {
  content: 'šŸ—¹';
  letter-spacing: 0.5em;
}
.check-list-wrapper {
  list-style: none;
}

If you wanted to apply a style to the list as a whole (such as padding, background colour etc.), then the wrapper class is a good place for this. I'll be doing this in the next example.

Register the custom list as a feature

I'll use the register_block_feature method I defined in Part 2 of this series to register the custom list:

@hooks.register('register_rich_text_features')
def register_checklist_feature(features):
    register_block_feature(
        features=features,
        feature_name='checklist',
        type_='checklist',
        description='Check List',
        css_class='check-list',
        element='li',
        wrapper="ul class='check-list-wrapper' role='list'",
        icon="tasks"
    )

If you just want to use the standard code from the Wagtail docs, your db_conversion dictionary should look like the following:

def register_checklist_feature(features):
    ....
    db_conversion = {
        "from_database_format":  {
            "li[class='check-list']": BlockElementHandler(type_),
        },
        "to_database_format": {
            "block_map": {
                type_: {
                    "element": "li",
                    "wrapper": "ul class='check-list-wrapper' role='list'",
                    "props": {
                        "class": "check-list"
                    }
                }
            },
        }
    }

fa-regular fa-pen-to-square fa-lg A note on role="list"

From the MDN web docs

Safari will not recognize an ordered or unordered list as a list in the accessibility tree if it has a list-style value of none. This behaviour is intentional and not considered a bug.

Since we're setting our <ul> style to none to override the bullet style, I'm adding role="list" to the wrapper definition to restore the list semantics.

Make sure you've added 'checklist' to your editor's features list and, once you've restarted, you'll see the check mark list icon on the toolbar.

Define the Draftail editor styling

If you style any lines at this point, you won't see any styling happening in the editor. In your editor or admin css, we need to add the following classes:

li.Draftail-block--checklist {
    margin-left: 0 !important;
}
li.Draftail-block--checklist > div.public-DraftStyleDefault-block {
    padding-left: 2em;
}
li.Draftail-block--checklist > div.public-DraftStyleDefault-block::before {
    content: 'šŸ—¹';
    padding-right: 1em;
    margin-left: -2em;
}
  1. The first removes the default left margin for list item elements, just my preference.
  2. Next, we add a left padding to the nested <div> to nudge the text to the right.
  3. Lastly, the ::before pseudo element adds the check mark bullet point. There's a negative margin to complement the padding in the parent element we just added, plus some padding for spacing.

Now in the editor, with a list of a couple of items, it looks like the following:

custom list styles in wagtail draftail

The custom list renders on the front end as:

  • Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec lacus ante. Quisque venenatis egestas mi, vel sollicitudin urna elementum at. Maecenas sed purus sed diam interdum congue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque accumsan enim ut massa auctor dictum.
  • Maecenas sit amet arcu eget erat auctor tempus. Suspendisse pretium eleifend ante, et venenatis quam consectetur non. Aliquam iaculis purus nec dolor mattis sollicitudin.

If you inspect the list, you'll see it's been rendered with:

<ul class="check-list-wrapper" role="list">
    <li class="check-list" data-block-key="...">....</li>
    <li class="check-list" data-block-key="...">....</li>
</ul>

Example: Using a Wrapper to Group Consecutive Blocks of the Same Type

In the final example I'll show how to make use of the wrapper attribute to group consecutive blocks of a type together and apply some styling to the group as a whole.

This needn't apply only to list items. My use case for the example is to create a code block where the lines of code are tight together, but an overall padding and margin is added around the group of blocks.

To do this, I add a <ul> wrapper to the block_map with the necessary CSS styling.

fa-regular fa-pen-to-square fa-lg Why use the <ul> and <li> elements for non-list items?

I would have used a <div> tag for this purpose, since we're not creating an unordered list. When I used that, it would render fine, however each save of the page would inject a nested <div> containing a line break <br> tag above each group of code blocks.

From this, I can only guess that only certain tags are accepted as wrappers and <div> is not amongst them. <ul> and <ol> both work fine, even if it's not being used for its intended purpose.

<dl> would be an appropriate element to use, but it's not supported as a wrapper element and has the same problem as using <div>, so this is an imperfect solution.

There is practically no documentation in Draftail regarding using the wrapper. If you know of a better solution, I'd be happy to hear from you!

Add the front end list item styling

To begin with, I'll define the css for each code block without the wrapped padding:

.code-block {
  font-size: var(--font-size-6);
  font-family: var(--font-family-monospace);
  text-align: left !important;
  color: floralwhite;
  background-color: #272822;
  padding: 0;
  line-height: 1.6;
}

This gives us text formatted as:

Code line #1
Code line #2
Code line #3

Padding between the lines is twice the beginning and end since both top and bottom spacing are applied for contiguous lines.

Define the wrapper style

We can add a wrapper class to apply to the enclosing <ul> tag:

.code-block-wrapper {
  background-color: #272822;
  padding: 0.8em 1.2em;
  margin-bottom: 0.8em;
  border-radius: 0.4em;
}

Here we have some padding to add the coloured background around the blocks of code, a bottom margin to apply spacing before the following element, and a little border radius to soften the corners.

Define the editor block style

That's the front-end styling done, but we need to add a style to the editor css to tell Draftail how to render this in the editor. Unfortunately, the wrapper doesn't get a class in the editor, the best we can do is format the code-blocks with some padding to emulate the final format:

.Draftail-block--CODE-BLOCK {
    font-family: var(--font-family-monospace);
    font-size: var(--font-size-6) !important;
    text-align: left !important;
    color: #f8f8f2;
    background-color: #272822;
    padding: 0.5em;
    line-height: 1.2;
}

Register the feature

With that in place, all that's left is to register the block type using the register_block_feature function defined in Part 2.

I'll add an SVG path to my custom DRAFTAIL_ICONS class as before to use the icon fa-regular fa-file-code:

class DRAFTAIL_ICONS:
    ....
    code_block = [
        "m 449.2,515.6 c -15.624,-15.624 -40.94,-15.624 -56.56,0 l -96,96 c -15.624,15.624 -15.624,41 0,56.62 l 96,96 C 400.6,772.2 410.8,776 421,776 c 10.2,0 20.46,-3.876 28.28,-11.688 15.624,-15.624 15.624,-41 0,-56.62 L 381.6,640 449.32,572.32 C 463.2,556.6 463.2,531.4 449.2,515.6 Z M 855.6,186.76 706.34,37.48 C 682.2,13.484 649.6,0 615.8,0 H 253 C 182.3,0 125,57.3 125,128 l 0.013,768 c 0,70.68 57.3,128 128,128 H 765 c 70.4,0 128,-57.6 128,-128 V 277.2 c 0,-33.8 -13.4,-66.4 -37.4,-90.44 z M 797,896 c 0,17.672 -14.328,32 -32,32 H 253.04 c -17.676,0 -32,-14.328 -32,-32 L 221,128.26 c 0,-17.672 14.328,-32 32,-32 H 573 V 256 c 0,35.34 28.66,64 64,64 H 795.2 V 896 Z M 568.8,515.6 c -15.624,15.624 -15.624,41 0,56.62 l 67.6,67.78 -67.72,67.68 c -15.624,15.624 -15.624,41 0,56.62 7.92,7.9 18.12,11.7 28.32,11.7 10.2,0 20.46,-3.876 28.28,-11.688 l 96,-96 c 15.624,-15.624 15.624,-41 0,-56.62 l -96,-96 C 609.6,500 584.4,500 568.8,515.6 Z"
    ]

And in my wagtail_hooks.py, register with:

@hooks.register('register_rich_text_features')
def register_code_block_feature(features):
    register_block_feature(
        features=features,
        feature_name='code-block',
        type_='CODE-BLOCK',
        description='Code Block',
        css_class='code-block',
        wrapper='ul class="code-block-wrapper"',
        icon=DRAFTAIL_ICONS.code_block
    )
fa-regular fa-pen-to-square fa-lg Note
I leave off role="list" from the <ul> wrapper definition in this case as I'm not defining a working list. You could use role="presentation" to explicitly tell assistive readers that the list is not to be considered a list.

In the front end, this renders our 3 lines of code with:

  • Code line 1
  • Code line 2
  • Code line 3

And html:

<ul class="code-block-wrapper">
    <li class="code-block" data-block-key="....">Code line 1</li>
    <li class="code-block" data-block-key="....">Code line 2</li>
    <li class="code-block" data-block-key="....">Code line 3</li>
</ul>

As before, don't forget to add 'code-block' to the features list for your editor to use this in your rich text blocks.

For the most part, I use a dedicated code block with syntax highlighting powered by prism, but there are occasions that I want to include a block of code directly in a text block.

This example serves as a good proof of concept for other grouped block styles you might want to add.

 

Conclusion

In this article, I showed the limitations around creating custom list styles in Draftail, and how you can achieve a workaround that will create a single tier list.

I also showed how you can use the wrapper to apply styling around a group of consecutive elements of the same style, even if they are not necessarily list items.


  Please feel free to leave any questions or comments below, or send me a message here