lexical icon indicating copy to clipboard operation
lexical copied to clipboard

Feature: Support __style for ListItemNode

Open maliuta-oleksandr opened this issue 3 years ago • 9 comments

I'm experience an issue when I style text inside Lists - pseudo selectors remain with default color, font size... And I can't style parent list item with node transform, because it doesn't support __style as TextNode. Then I have to override the node like this, but it's looks crazy ) And would be awesome to export all functions from @lexical/list to reuse it. I can create PR

import type { NodeKey, EditorConfig, EditorThemeClasses } from 'lexical';
import { ListItemNode, ListNode, $isListNode } from '@lexical/list';
import {
    addClassNamesToElement,
    removeClassNamesFromElement,
} from '@lexical/utils';

function $setListItemThemeClassNames(
    dom: HTMLElement,
    editorThemeClasses: EditorThemeClasses,
    node: ListItemNode,
): void {
    const classesToAdd = [];
    const classesToRemove = [];
    const listTheme = editorThemeClasses.list;
    const listItemClassName = listTheme ? listTheme.listitem : undefined;
    let nestedListItemClassName;

    if (listTheme && listTheme.nested) {
        nestedListItemClassName = listTheme.nested.listitem;
    }

    if (listItemClassName !== undefined) {
        const listItemClasses = listItemClassName.split(' ');
        classesToAdd.push(...listItemClasses);
    }

    if (listTheme) {
        const parentNode = node.getParent();
        const isCheckList =
            $isListNode(parentNode) && parentNode.getListType() === 'check';
        const checked = node.getChecked();

        if (!isCheckList || checked) {
            classesToRemove.push(listTheme.listitemUnchecked);
        }

        if (!isCheckList || !checked) {
            classesToRemove.push(listTheme.listitemChecked);
        }

        if (isCheckList) {
            classesToAdd.push(
                checked ? listTheme.listitemChecked : listTheme.listitemUnchecked,
            );
        }
    }

    if (nestedListItemClassName !== undefined) {
        const nestedListItemClasses = nestedListItemClassName.split(' ');

        if (node.getChildren().some((child) => $isListNode(child))) {
            classesToAdd.push(...nestedListItemClasses);
        } else {
            classesToRemove.push(...nestedListItemClasses);
        }
    }

    if (classesToRemove.length > 0) {
        removeClassNamesFromElement(dom, ...classesToRemove);
    }

    if (classesToAdd.length > 0) {
        addClassNamesToElement(dom, ...classesToAdd);
    }
}

function updateListItemChecked(
    dom: HTMLElement,
    listItemNode: ListItemNode,
    prevListItemNode: ListItemNode | null,
    listNode: ListNode,
): void {
    // Only add attributes for leaf list items
    if ($isListNode(listItemNode.getFirstChild())) {
        dom.removeAttribute('role');
        dom.removeAttribute('tabIndex');
        dom.removeAttribute('aria-checked');
    } else {
        dom.setAttribute('role', 'checkbox');
        dom.setAttribute('tabIndex', '-1');

        if (
            !prevListItemNode ||
            listItemNode.__checked !== prevListItemNode.__checked
        ) {
            dom.setAttribute(
                'aria-checked',
                listItemNode.getChecked() ? 'true' : 'false',
            );
        }
    }
}


export class ExtendedListItemNode extends ListItemNode {
    /** @internal */
    __style: string;

    static getType(): string {
        return 'extended-list-item';
    }

    constructor(value?: number, checked?: boolean, key?: NodeKey) {
        super(key);
        this.__style = '';
        this.__value = value === undefined ? 1 : value;
        this.__checked = checked;
    }

    createDOM(config: EditorConfig): HTMLElement {
        const element = document.createElement('li');
        const parent = this.getParent();
        if ($isListNode(parent) && parent.getListType() === 'check') {
            updateListItemChecked(element, this, null, parent);
        }
        element.value = this.__value;
        $setListItemThemeClassNames(element, config.theme, this);
        const style = this.__style;
        if (style !== '') {
            element.style.cssText = style;
        }
        return element;
    }

    setStyle(style: string): this {
        const self = this.getWritable();
        self.__style = style;
        return self;
    }

    /**
     * Returns the styles currently applied to the node. This is analogous to CSSText in the DOM.
     *
     * @returns CSSText-like string of styles applied to the underlying DOM node.
     */
    getStyle(): string {
        const self = this.getLatest();
        return self.__style;
    }

    static clone(node: ExtendedListItemNode): ExtendedListItemNode {
        return new ExtendedListItemNode(node.__value, node.__checked, node.__key);
    }
}

maliuta-oleksandr avatar Aug 01 '23 07:08 maliuta-oleksandr

And what I'm doing currently, maybe will help someone

editor.registerNodeTransform(TextNode, textNode => {
            const $parent = textNode.getParent();
            if ($parent && $isListItemNode($parent)) {
                const children = $parent.getChildren();
                if (children.length === 1) {
                    $parent.setStyle(textNode.__style); // Fix Pseudo selectors styles for Lists
                }
            }
        })

maliuta-oleksandr avatar Aug 01 '23 07:08 maliuta-oleksandr

Can you provide a little more detail here about what specifically you are trying to do that can't be done with the existing theme classes? How are you trying to use pseudo-selectors?

acywatson avatar Aug 01 '23 16:08 acywatson

For example I select the list item(s) and apply a color or maybe font-size. but the numbers remain with parent styles and it looks ugly. Theme classes - for different case $patchStyleText(selection,{ 'color': 'red' });

image

image

maliuta-oleksandr avatar Aug 01 '23 16:08 maliuta-oleksandr

oooh, you want the number to change to match the style of the child text content. got it.

acywatson avatar Aug 01 '23 16:08 acywatson

And what I'm doing currently, maybe will help someone

editor.registerNodeTransform(TextNode, textNode => {
            const $parent = textNode.getParent();
            if ($parent && $isListItemNode($parent)) {
                const children = $parent.getChildren();
                if (children.length === 1) {
                    $parent.setStyle(textNode.__style); // Fix Pseudo selectors styles for Lists
                }
            }
        })

@maliuta-oleksandr this seems exactly the kind of work-around I was looking for the past few days. Are you re-implementing the insertList function for that? How else could you make lexical create ExtendedListItemNode nodes instead of ListItemNode when a new node is created?

arielyz avatar Oct 01 '23 12:10 arielyz

And what I'm doing currently, maybe will help someone

editor.registerNodeTransform(TextNode, textNode => {
            const $parent = textNode.getParent();
            if ($parent && $isListItemNode($parent)) {
                const children = $parent.getChildren();
                if (children.length === 1) {
                    $parent.setStyle(textNode.__style); // Fix Pseudo selectors styles for Lists
                }
            }
        })

@maliuta-oleksandr I think this only works when a new list is created. When you change the style of a TextNode, the parent's style is indeed changed, but changes are not reflected in the editor (you also need to implement the updateDOM method).

arielyz avatar Oct 01 '23 14:10 arielyz

@arielyz Yeah, noticed that issue later, haven't chance to work on it. Try to registerNodeTransform(ExtendedListItemNode and update these conditions to the current node, not parent, probably that's issue

maliuta-oleksandr avatar Oct 02 '23 07:10 maliuta-oleksandr

@arielyz seems weird, but works) Don't forget to call listeners to unusbcribe(cleanup)

    editor.registerNodeTransform(ExtendedListItemNode, listItemNode => {
            const children = listItemNode.getChildren();
            if (children.length === 1 && listItemNode.__style !== children[0].__style) {
                listItemNode.setStyle(children[0].__style); // Fix Pseudo selectors styles for Lists
            }
        });
        editor.registerNodeTransform(TextNode, textNode => {
            const $parent = textNode.getParent();
            if ($parent && $isListItemNode($parent)) {
                const children = $parent.getChildren();
                if (children.length === 1 && $parent.__style !== textNode.__style) {
                    $parent.setStyle(textNode.__style); // Fix Pseudo selectors styles for Lists
                }
            }

maliuta-oleksandr avatar Oct 03 '23 08:10 maliuta-oleksandr

This was implemented in several stages:

  • PR #6970 added __textStyle / __textFormat to ElementNode (so ListItemNode inherits them)
  • The registerList plugin syncs the first child TextNode's style to its parent ListItemNode via node transforms
  • PR #7325 moved marker styling to CSS custom properties (--listitem-marker-color, --listitem-marker-font-size, etc.) to avoid style cascade to children

To use it, add CSS for the ::marker pseudo-element:

.YourTheme__listItem::marker {
  color: var(--listitem-marker-color);
  font-size: var(--listitem-marker-font-size);
  font-family: var(--listitem-marker-font-family);
}

The playground theme has a working example. I think this can be closed.

mayrang avatar Jul 22 '26 09:07 mayrang