/* !
 * (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
 */
import * as React from "react";
import { mergeRefs, Utils } from "../common";
var DEFAULT_OPTIONS = { defaultTabIndex: undefined, disabledTabIndex: -1 };
export function useInteractiveAttributes(interactive, props, ref, options) {
    if (options === void 0) { options = DEFAULT_OPTIONS; }
    var defaultTabIndex = options.defaultTabIndex, disabledTabIndex = options.disabledTabIndex;
    var active = props.active, onClick = props.onClick, onFocus = props.onFocus, onKeyDown = props.onKeyDown, onKeyUp = props.onKeyUp, onBlur = props.onBlur, _a = props.tabIndex, tabIndex = _a === void 0 ? defaultTabIndex : _a;
    // the current key being pressed
    var _b = React.useState(), currentKeyPressed = _b[0], setCurrentKeyPressed = _b[1];
    // whether the button is in "active" state
    var _c = React.useState(false), isActive = _c[0], setIsActive = _c[1];
    // our local ref for the interactive element, merged with the consumer's own ref in this hook's return value
    var elementRef = React.useRef(null);
    var handleBlur = React.useCallback(function (e) {
        if (isActive) {
            setIsActive(false);
        }
        onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
    }, [isActive, onBlur]);
    var handleKeyDown = React.useCallback(function (e) {
        if (Utils.isKeyboardClick(e)) {
            e.preventDefault();
            if (e.key !== currentKeyPressed) {
                setIsActive(true);
            }
        }
        setCurrentKeyPressed(e.key);
        onKeyDown === null || onKeyDown === void 0 ? void 0 : onKeyDown(e);
    }, [currentKeyPressed, onKeyDown]);
    var handleKeyUp = React.useCallback(function (e) {
        var _a;
        if (Utils.isKeyboardClick(e)) {
            setIsActive(false);
            (_a = elementRef.current) === null || _a === void 0 ? void 0 : _a.click();
        }
        setCurrentKeyPressed(undefined);
        onKeyUp === null || onKeyUp === void 0 ? void 0 : onKeyUp(e);
    }, [onKeyUp, elementRef]);
    var resolvedActive = interactive && (active || isActive);
    return [
        resolvedActive,
        {
            onBlur: handleBlur,
            onClick: interactive ? onClick : undefined,
            onFocus: interactive ? onFocus : undefined,
            onKeyDown: handleKeyDown,
            onKeyUp: handleKeyUp,
            ref: mergeRefs(elementRef, ref),
            tabIndex: interactive ? tabIndex : disabledTabIndex,
        },
    ];
}
//# sourceMappingURL=useInteractiveAttributes.js.map