"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDecorators = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_dom_1 = require("react-dom");
const react_core_1 = require("@selfcommunity/react-core");
function useDecorators(editor, ErrorBoundary) {
    const [decorators, setDecorators] = (0, react_1.useState)(() => editor.getDecorators());
    // Subscribe to changes
    (0, react_core_1.useIsomorphicLayoutEffect)(() => {
        return editor.registerDecoratorListener((nextDecorators) => {
            (0, react_dom_1.flushSync)(() => {
                setDecorators(nextDecorators);
            });
        });
    }, [editor]);
    (0, react_1.useEffect)(() => {
        // If the content editable mounts before the subscription is added, then
        // nothing will be rendered on initial pass. We can get around that by
        // ensuring that we set the value.
        setDecorators(editor.getDecorators());
    }, [editor]);
    // Return decorators defined as React Portals
    return (0, react_1.useMemo)(() => {
        const decoratedPortals = [];
        const decoratorKeys = Object.keys(decorators);
        for (let i = 0; i < decoratorKeys.length; i++) {
            const nodeKey = decoratorKeys[i];
            const reactDecorator = ((0, jsx_runtime_1.jsx)(ErrorBoundary, Object.assign({ onError: (e) => editor._onError(e) }, { children: (0, jsx_runtime_1.jsx)(react_1.Suspense, Object.assign({ fallback: null }, { children: decorators[nodeKey] })) })));
            const element = editor.getElementByKey(nodeKey);
            if (element !== null) {
                decoratedPortals.push((0, react_dom_1.createPortal)(reactDecorator, element, nodeKey));
            }
        }
        return decoratedPortals;
    }, [ErrorBoundary, decorators, editor]);
}
exports.useDecorators = useDecorators;
