"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ResetEmptyListItemFormatPlugin;
const list_1 = require("@lexical/list");
const LexicalComposerContext_1 = require("@lexical/react/LexicalComposerContext");
const utils_1 = require("@lexical/utils");
const lexical_1 = require("lexical");
const react_1 = require("react");
function isInsideListItem(node) {
    return (0, list_1.$isListItemNode)(node) || (0, utils_1.$findMatchingParent)(node, (parent) => (0, list_1.$isListItemNode)(parent)) !== null;
}
function isSelectionInsideListItem() {
    const selection = (0, lexical_1.$getSelection)();
    if (!(0, lexical_1.$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 = (0, lexical_1.$getSelection)();
    if (!(0, lexical_1.$isRangeSelection)(selection) || !selection.isCollapsed()) {
        return;
    }
    const anchorNode = selection.anchor.getNode();
    const listItemNode = (0, list_1.$isListItemNode)(anchorNode)
        ? anchorNode
        : (0, utils_1.$findMatchingParent)(anchorNode, (node) => (0, list_1.$isListItemNode)(node));
    if (listItemNode !== null) {
        return;
    }
    const targetNode = (0, lexical_1.$isElementNode)(anchorNode)
        ? anchorNode
        : (0, lexical_1.$isTextNode)(anchorNode)
            ? anchorNode.getTopLevelElement()
            : null;
    if (!(0, lexical_1.$isElementNode)(targetNode) || targetNode.getTextContent().trim() !== '') {
        return;
    }
    selection.setFormat(0);
    selection.setStyle('');
    targetNode.setTextFormat(0);
    targetNode.setTextStyle('');
}
function ResetEmptyListItemFormatPlugin() {
    const [editor] = (0, LexicalComposerContext_1.useLexicalComposerContext)();
    (0, react_1.useEffect)(() => {
        const handleDelete = () => {
            const shouldResetFormat = isSelectionInsideListItem();
            if (!shouldResetFormat) {
                return false;
            }
            queueMicrotask(() => {
                editor.update(resetEmptyBlockFormat);
            });
            return false;
        };
        const unregisterBackspace = editor.registerCommand(lexical_1.KEY_BACKSPACE_COMMAND, handleDelete, lexical_1.COMMAND_PRIORITY_CRITICAL);
        const unregisterDelete = editor.registerCommand(lexical_1.KEY_DELETE_COMMAND, handleDelete, lexical_1.COMMAND_PRIORITY_CRITICAL);
        return () => {
            unregisterBackspace();
            unregisterDelete();
        };
    }, [editor]);
    return null;
}
//# sourceMappingURL=index.js.map