import { createLexicalComposerContext, LexicalComposerContext, } from "./LexicalComposerContext";
import { $createParagraphNode, $getRoot, $getSelection, createEditor, } from "lexical";
import { onMount } from "solid-js";
const HISTORY_MERGE_OPTIONS = { tag: "history-merge" };
export function LexicalComposer(props) {
    const { editable, theme, namespace, nodes, onError, editorState: initialEditorState, html, } = props.initialConfig;
    const context = createLexicalComposerContext(null, theme);
    const editor = createEditor({
        editable,
        html,
        namespace,
        nodes,
        onError: (error) => onError(error, editor),
        theme,
    });
    initializeEditor(editor, initialEditorState);
    onMount(() => {
        const isEditable = props.initialConfig.editable;
        editor.setEditable(isEditable !== undefined ? isEditable : true);
    });
    return (<LexicalComposerContext.Provider value={[editor, context]}>
      {props.children}
    </LexicalComposerContext.Provider>);
}
function initializeEditor(editor, initialEditorState) {
    if (initialEditorState === null) {
        return;
    }
    else if (initialEditorState === undefined) {
        editor.update(() => {
            const root = $getRoot();
            if (root.isEmpty()) {
                const paragraph = $createParagraphNode();
                root.append(paragraph);
                const activeElement = typeof window !== "undefined" ? document.activeElement : null;
                if ($getSelection() !== null ||
                    (activeElement !== null && activeElement === editor.getRootElement())) {
                    paragraph.select();
                }
            }
        }, HISTORY_MERGE_OPTIONS);
    }
    else if (initialEditorState !== null) {
        switch (typeof initialEditorState) {
            case "string": {
                const parsedEditorState = editor.parseEditorState(initialEditorState);
                editor.setEditorState(parsedEditorState, HISTORY_MERGE_OPTIONS);
                break;
            }
            case "object": {
                editor.setEditorState(initialEditorState, HISTORY_MERGE_OPTIONS);
                break;
            }
            case "function": {
                editor.update(() => {
                    const root = $getRoot();
                    if (root.isEmpty()) {
                        initialEditorState(editor);
                    }
                }, HISTORY_MERGE_OPTIONS);
                break;
            }
        }
    }
}
