"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = PHXTextEditorV2;
const tslib_1 = require("tslib");
const html_1 = require("@lexical/html");
const LexicalComposer_1 = require("@lexical/react/LexicalComposer");
const lexical_1 = require("lexical");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const SharedAutocompleteContext_1 = require("./context/SharedAutocompleteContext");
const SharedHistoryContext_1 = require("./context/SharedHistoryContext");
const ExtendedTextNode_1 = require("./nodes/ExtendedTextNode");
const PlaygroundNodes_1 = tslib_1.__importDefault(require("./nodes/PlaygroundNodes"));
const TablePlugin_1 = require("./plugins/TablePlugin");
const canUseDOM_1 = require("./shared/canUseDOM");
const PlaygroundEditorTheme_1 = tslib_1.__importDefault(require("./themes/PlaygroundEditorTheme"));
const LexicalCheckListPlugin_1 = require("@lexical/react/LexicalCheckListPlugin");
const LexicalClearEditorPlugin_1 = require("@lexical/react/LexicalClearEditorPlugin");
const LexicalHistoryPlugin_1 = require("@lexical/react/LexicalHistoryPlugin");
const LexicalListPlugin_1 = require("@lexical/react/LexicalListPlugin");
const LexicalOnChangePlugin_1 = require("@lexical/react/LexicalOnChangePlugin");
const LexicalRichTextPlugin_1 = require("@lexical/react/LexicalRichTextPlugin");
const LexicalTabIndentationPlugin_1 = require("@lexical/react/LexicalTabIndentationPlugin");
const ImagesPlugin_1 = tslib_1.__importDefault(require("./plugins/ImagesPlugin"));
const InlineImagePlugin_1 = tslib_1.__importDefault(require("./plugins/InlineImagePlugin"));
const ListMaxIndentLevelPlugin_1 = tslib_1.__importDefault(require("./plugins/ListMaxIndentLevelPlugin"));
const MaxLengthPlugin_1 = require("./plugins/MaxLengthPlugin");
const SanitizePastePlugin_1 = tslib_1.__importDefault(require("./plugins/SanitizePastePlugin"));
const PreserveFontSizeOnEnterPlugin_1 = tslib_1.__importDefault(require("./plugins/PreserveFontSizeOnEnterPlugin"));
const ResetEmptyListItemFormatPlugin_1 = tslib_1.__importDefault(require("./plugins/ResetEmptyListItemFormatPlugin"));
const ContentEditable_1 = tslib_1.__importDefault(require("./ui/ContentEditable"));
const ToolbarPlugin_1 = tslib_1.__importDefault(require("./plugins/ToolbarPlugin"));
const SettingsContext_1 = require("./context/SettingsContext");
const constants_1 = require("./constants");
const style_1 = tslib_1.__importDefault(require("./style"));
const LexicalClickableLinkPlugin_1 = require("@lexical/react/LexicalClickableLinkPlugin");
const LexicalLinkPlugin_1 = require("@lexical/react/LexicalLinkPlugin");
const LexicalErrorBoundary_1 = require("./shared/LexicalErrorBoundary");
function PHXTextEditorV2({ defaultValue, label, onChange, placeholder, apiCdnUpload, disabled = false, }) {
    const [isSmallWidthViewport, setIsSmallWidthViewport] = (0, react_1.useState)(false);
    const { historyState } = (0, SharedHistoryContext_1.useSharedHistoryContext)();
    const { settings: { isMaxLength }, } = (0, SettingsContext_1.useSettings)();
    const editorConfig = {
        theme: PlaygroundEditorTheme_1.default,
        editorState: prepopulatedRichText,
        onError(error) {
            throw error;
        },
        nodes: [
            ...PlaygroundNodes_1.default,
            ExtendedTextNode_1.ExtendedTextNode,
            {
                replace: lexical_1.TextNode,
                with: (node) => new ExtendedTextNode_1.ExtendedTextNode(node.__text),
                withKlass: ExtendedTextNode_1.ExtendedTextNode,
            },
        ],
    };
    function prepopulatedRichText() {
        const root = (0, lexical_1.$getRoot)();
        try {
            if (defaultValue) {
                const editor = (0, lexical_1.createEditor)();
                const parser = new DOMParser();
                const dom = parser.parseFromString(defaultValue, 'text/html');
                const nodes = (0, html_1.$generateNodesFromDOM)(editor, dom);
                if (root.getFirstChild() === null) {
                    root.append(...nodes);
                }
            }
        }
        catch (e) {
            root.clear();
        }
    }
    function ensureStyleTag(html, css) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const hasStyle = doc.querySelector('style');
        if (hasStyle) {
            hasStyle.innerHTML = css;
        }
        else {
            const styleTag = doc.createElement('style');
            styleTag.innerHTML = css;
            doc.head.appendChild(styleTag);
        }
        return doc.documentElement.outerHTML;
    }
    const handleChange = (editorState, editor) => {
        editorState.read(() => {
            const data = JSON.stringify(editorState);
            return data;
        });
        editor.update(() => {
            const rawHTML = (0, html_1.$generateHtmlFromNodes)(editor, null);
            const htmlWithStyle = ensureStyleTag(rawHTML, constants_1.styleTag);
            onChange === null || onChange === void 0 ? void 0 : onChange(htmlWithStyle);
        });
    };
    (0, react_1.useEffect)(() => {
        const updateViewPortWidth = () => {
            const isNextSmallWidthViewport = canUseDOM_1.CAN_USE_DOM && window.matchMedia('(max-width: 1025px)').matches;
            if (isNextSmallWidthViewport !== isSmallWidthViewport) {
                setIsSmallWidthViewport(isNextSmallWidthViewport);
            }
        };
        updateViewPortWidth();
        window.addEventListener('resize', updateViewPortWidth);
        return () => {
            window.removeEventListener('resize', updateViewPortWidth);
        };
    }, [isSmallWidthViewport]);
    return (React.createElement("div", null,
        React.createElement(style_1.default, null),
        label && React.createElement("label", { className: 'block mb-1 text-xs font-normal text-gray-700' }, label),
        React.createElement(LexicalComposer_1.LexicalComposer, { initialConfig: editorConfig },
            React.createElement(SharedHistoryContext_1.SharedHistoryContext, null,
                React.createElement(TablePlugin_1.TableContext, null,
                    React.createElement(SharedAutocompleteContext_1.SharedAutocompleteContext, null,
                        React.createElement("div", { className: 'rounded-md border border-gray-300 shadow-sm overflow-hidden' },
                            React.createElement(ToolbarPlugin_1.default, { disabled: disabled, apiCdnUpload: apiCdnUpload }),
                            React.createElement("div", { className: 'relative' },
                                isMaxLength && React.createElement(MaxLengthPlugin_1.MaxLengthPlugin, { maxLength: 30 }),
                                React.createElement(LexicalClearEditorPlugin_1.ClearEditorPlugin, null),
                                React.createElement(LexicalOnChangePlugin_1.OnChangePlugin, { onChange: handleChange }),
                                React.createElement(LexicalHistoryPlugin_1.HistoryPlugin, { externalHistoryState: historyState }),
                                React.createElement(SanitizePastePlugin_1.default, null),
                                React.createElement(PreserveFontSizeOnEnterPlugin_1.default, null),
                                React.createElement(ResetEmptyListItemFormatPlugin_1.default, null),
                                React.createElement(LexicalRichTextPlugin_1.RichTextPlugin, { contentEditable: React.createElement(ContentEditable_1.default, { className: 'PHXTextEditorV2__contentEditable px-2 py-1.5 h-[20rem] overflow-y-auto outline-none' }), ErrorBoundary: LexicalErrorBoundary_1.LexicalErrorBoundary, placeholder: React.createElement("p", { className: 'absolute top-1.5 left-2 text-xs text-[#999] z-10 overflow-hidden text-ellipsis inline-block select-none pointer-events-none' }, placeholder) }),
                                React.createElement(LexicalListPlugin_1.ListPlugin, null),
                                React.createElement(LexicalCheckListPlugin_1.CheckListPlugin, null),
                                React.createElement(ListMaxIndentLevelPlugin_1.default, { maxDepth: 7 }),
                                React.createElement(ImagesPlugin_1.default, null),
                                React.createElement(InlineImagePlugin_1.default, null),
                                React.createElement(LexicalLinkPlugin_1.LinkPlugin, null),
                                React.createElement(LexicalClickableLinkPlugin_1.ClickableLinkPlugin, { newTab: true }),
                                React.createElement(LexicalTabIndentationPlugin_1.TabIndentationPlugin, null)))))))));
}
//# sourceMappingURL=editor.js.map