import { createMemo, createSignal, onMount, createComponent, Suspense, onCleanup, } from "solid-js";
import { Dynamic, Portal } from "solid-js/web";
export function useDecorators(editor, ErrorBoundary) {
    const [decorators, setDecorators] = createSignal(editor.getDecorators());
    // Subscribe to changes
    onCleanup(editor.registerDecoratorListener((nextDecorators) => {
        setDecorators(nextDecorators);
    }));
    onMount(() => {
        // 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());
    });
    // Return decorators defined as React Portals
    return createMemo(() => {
        const decoratedPortals = [];
        const decoratorKeys = Object.keys(decorators());
        for (let i = 0; i < decoratorKeys.length; i++) {
            const nodeKey = decoratorKeys[i];
            const decorator = (<ErrorBoundary onError={(error, reset) => editor._onError(error)}>
          <Suspense fallback={null}>
            <Dynamic component={decorators()[nodeKey]}/>
          </Suspense>
        </ErrorBoundary>);
            const element = editor.getElementByKey(nodeKey);
            if (element !== null) {
                decoratedPortals.push(createComponent(Portal, { mount: element, children: decorator }));
            }
        }
        return decoratedPortals;
    });
}
