"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useActionState = useActionState;
exports.useActionsState = useActionsState;
const react_1 = require("react");
const react_use_1 = require("react-use");
const lodash_1 = require("../lodash.js");
const context_1 = require("./context.js");
function useActionState(editor, { isActive, isEnable }) {
    const context = (0, context_1.useToolbarContext)();
    const eventBus = context?.eventBus;
    const [state, setState] = (0, react_1.useState)({
        active: false,
        enabled: true,
    });
    const stateRef = (0, react_use_1.useLatest)(state);
    (0, react_1.useEffect)(() => {
        const onUpdate = () => {
            const newActive = isActive(editor);
            const newEnabled = isEnable(editor);
            const { active, enabled } = stateRef.current;
            if (active !== newActive || enabled !== newEnabled) {
                setState({
                    active: newActive,
                    enabled: newEnabled,
                });
            }
        };
        onUpdate();
        if (eventBus) {
            eventBus.on('update', onUpdate);
            return () => eventBus.off('update', onUpdate);
        }
        return undefined;
    }, [editor, isActive, isEnable, eventBus, stateRef]);
    return state;
}
function useActionsState(editor, actions) {
    const context = (0, context_1.useToolbarContext)();
    const eventBus = context?.eventBus;
    const [state, setState] = (0, react_1.useState)(() => actions.map(() => ({
        active: false,
        enabled: true,
    })));
    const stateRef = (0, react_use_1.useLatest)(state);
    (0, react_1.useEffect)(() => {
        const onUpdate = () => {
            const currentState = stateRef.current;
            const newState = actions.map(({ isActive, isEnable }) => ({
                active: isActive(editor),
                enabled: isEnable(editor),
            }));
            if (!(0, lodash_1.isEqual)(currentState, newState)) {
                setState(newState);
            }
        };
        onUpdate();
        if (eventBus) {
            eventBus.on('update', onUpdate);
            return () => eventBus.off('update', onUpdate);
        }
        return undefined;
    }, [actions, editor, eventBus, stateRef]);
    return state.length === actions.length
        ? state
        : actions.map(() => ({ active: false, enabled: true }));
}
//# sourceMappingURL=hooks.js.map
