import { $getNodeByKey, $getSelection, $isNodeSelection, $isRangeSelection, CLICK_COMMAND, COMMAND_PRIORITY_LOW, FORMAT_ELEMENT_COMMAND, } from "lexical";
import { useLexicalComposerContext } from "./LexicalComposerContext";
import { $isDecoratorBlockNode } from "./LexicalDecoratorBlockNode";
import { useLexicalNodeSelection } from "./useLexicalNodeSelection";
import { $getNearestBlockElementAncestorOrThrow, mergeRegister, } from "@lexical/utils";
import { createEffect, onCleanup } from "solid-js";
export function BlockWithAlignableContents(props) {
    const [editor] = useLexicalComposerContext();
    const [isSelected, setSelected, clearSelection] = useLexicalNodeSelection(props.nodeKey);
    let ref;
    createEffect(() => {
        onCleanup(mergeRegister(editor.registerCommand(FORMAT_ELEMENT_COMMAND, (formatType) => {
            if (isSelected()) {
                const selection = $getSelection();
                if ($isNodeSelection(selection)) {
                    const node = $getNodeByKey(props.nodeKey);
                    if ($isDecoratorBlockNode(node)) {
                        node.setFormat(formatType);
                    }
                }
                else if ($isRangeSelection(selection)) {
                    const nodes = selection.getNodes();
                    for (const node of nodes) {
                        if ($isDecoratorBlockNode(node)) {
                            node.setFormat(formatType);
                        }
                        else {
                            const element = $getNearestBlockElementAncestorOrThrow(node);
                            element.setFormat(formatType);
                        }
                    }
                }
                return true;
            }
            return false;
        }, COMMAND_PRIORITY_LOW), editor.registerCommand(CLICK_COMMAND, (event) => {
            if (event.target === ref) {
                event.preventDefault();
                if (!event.shiftKey) {
                    clearSelection();
                }
                setSelected(!isSelected);
                return true;
            }
            return false;
        }, COMMAND_PRIORITY_LOW)));
    });
    return (<div classList={{
            [props.classes.base]: true,
            [props.classes.focus]: isSelected(),
        }} ref={ref} style={{
            "text-align": props.format ? props.format : undefined,
        }}>
      {props.children}
    </div>);
}
