import { $isListItemNode } from '@lexical/list';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $findMatchingParent } from '@lexical/utils';
import { $getSelection, $isElementNode, $isRangeSelection, $isTextNode, COMMAND_PRIORITY_CRITICAL, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, } from 'lexical';
import { useEffect } from 'react';
function isInsideListItem(node) {
    return $isListItemNode(node) || $findMatchingParent(node, (parent) => $isListItemNode(parent)) !== null;
}
function isSelectionInsideListItem() {
    const selection = $getSelection();
    if (!$isRangeSelection(selection)) {
        return false;
    }
    const nodes = selection.getNodes();
    return (nodes.some((node) => isInsideListItem(node)) ||
        isInsideListItem(selection.anchor.getNode()) ||
        isInsideListItem(selection.focus.getNode()));
}
function resetEmptyBlockFormat() {
    const selection = $getSelection();
    if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
        return;
    }
    const anchorNode = selection.anchor.getNode();
    const listItemNode = $isListItemNode(anchorNode)
        ? anchorNode
        : $findMatchingParent(anchorNode, (node) => $isListItemNode(node));
    if (listItemNode !== null) {
        return;
    }
    const targetNode = $isElementNode(anchorNode)
        ? anchorNode
        : $isTextNode(anchorNode)
            ? anchorNode.getTopLevelElement()
            : null;
    if (!$isElementNode(targetNode) || targetNode.getTextContent().trim() !== '') {
        return;
    }
    selection.setFormat(0);
    selection.setStyle('');
    targetNode.setTextFormat(0);
    targetNode.setTextStyle('');
}
export default function ResetEmptyListItemFormatPlugin() {
    const [editor] = useLexicalComposerContext();
    useEffect(() => {
        const handleDelete = () => {
            const shouldResetFormat = isSelectionInsideListItem();
            if (!shouldResetFormat) {
                return false;
            }
            queueMicrotask(() => {
                editor.update(resetEmptyBlockFormat);
            });
            return false;
        };
        const unregisterBackspace = editor.registerCommand(KEY_BACKSPACE_COMMAND, handleDelete, COMMAND_PRIORITY_CRITICAL);
        const unregisterDelete = editor.registerCommand(KEY_DELETE_COMMAND, handleDelete, COMMAND_PRIORITY_CRITICAL);
        return () => {
            unregisterBackspace();
            unregisterDelete();
        };
    }, [editor]);
    return null;
}
//# sourceMappingURL=index.js.map