import { TableCellNode, setScrollableTablesActive, registerTablePlugin, registerTableSelectionObserver, registerTableCellUnmergeTransform, } from "@lexical/table";
import { useLexicalComposerContext } from "./LexicalComposerContext";
import { onCleanup, onMount, mergeProps, createEffect, on, } from "solid-js";
/**
 * A plugin to enable all of the features of Lexical's TableNode.
 *
 * @param mergedProps - See type for documentation
 * @returns An element to render in your LexicalComposer
 */
export function TablePlugin(props) {
    const mergedProps = mergeProps({
        hasCellMerge: true,
        hasCellBackgroundColor: true,
        hasHorizontalScroll: false,
    }, props);
    const [editor] = useLexicalComposerContext();
    createEffect(() => {
        setScrollableTablesActive(editor, mergedProps.hasHorizontalScroll);
    });
    onMount(() => onCleanup(registerTablePlugin(editor)));
    createEffect(() => onCleanup(registerTableSelectionObserver(editor, props.hasTabHandler)));
    // Unmerge cells when the feature isn't enabled
    createEffect(() => {
        if (!mergedProps.hasCellMerge) {
            onCleanup(registerTableCellUnmergeTransform(editor));
        }
    });
    // Remove cell background color when feature is disabled
    createEffect(on(() => [mergedProps.hasCellBackgroundColor, mergedProps.hasCellMerge], () => {
        if (mergedProps.hasCellBackgroundColor) {
            return;
        }
        onCleanup(editor.registerNodeTransform(TableCellNode, (node) => {
            if (node.getBackgroundColor() !== null) {
                node.setBackgroundColor(null);
            }
        }));
    }));
    return null;
}
