0

Following a guide, I created a lexical toolbar component in React that changes the format of text eg. bold, underline, italic, and list.

Unfortunately, the team im working with wants 100% code coverage so im trying to finish up some tests for this bit of code. This is the main chunk of logic:

const updateToolbar = useCallback(() => {
        const selection = $getSelection();

        if ($isRangeSelection(selection)) {

            const anchorNode = selection.anchor.getNode();
            const element = anchorNode.getKey() === 'root'
                ? anchorNode
                : anchorNode.getTopLevelElementOrThrow();

            const elementKey = element.getKey();
            const elementDOM = editor.getElementByKey(elementKey);

            if (elementDOM !== null) {
                if ($isListNode(element)) {
                    const parentList = $getNearestNodeOfType(anchorNode, ListNode);
                    const type = parentList ? parentList.getTag() : element.getTag();

                    console.log({ parentList, type })

                    setBlockType(type);
                } else {
                    const type = $isHeadingNode(element)
                        ? element.getTag()
                        : element.getType();
                    setBlockType(type);
                }
            }

            setIsBold(selection.hasFormat('bold'))
            setIsItalic(selection.hasFormat('italic'))
            setIsUnderline(selection.hasFormat('underline'))
        }
    }, [editor])

    useEffect(() => {
        return mergeRegister(
            editor.registerUpdateListener(({ editorState }) => {
                editorState.read(() => { updateToolbar() })
            })
        )
    }, [updateToolbar, editor])

    const handleToolbarClick = (type: 'bold' | 'italic' | 'underline' | 'list') => {
        if (type === 'list') {
            // @ts-expect-error
            editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND);
            return;
        }

        editor.dispatchCommand(FORMAT_TEXT_COMMAND, type)
    }

Am I supposed to be checking if the editor dispatched the right commands after clicking on a format option?

Would appreciate some guidance. Thank you.

syn
  • 11
  • 2

0 Answers0