var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { autoUpdate, arrow as flArrow, flip, offset, safePolygon, shift, useDismiss, useFloating, useFocus, useHover, useInteractions, } from "@floating-ui/react";
import React, { Fragment, forwardRef, useRef, } from "react";
import { useModalContext } from "../modal/Modal.context.js";
import { Portal } from "../portal/index.js";
import { HStack } from "../primitives/stack/index.js";
import { Detail } from "../typography/index.js";
import { useId } from "../utils-external/index.js";
import { Slot } from "../utils/components/slot/Slot.js";
import { cl } from "../utils/helpers/index.js";
import { consoleWarning } from "../utils/helpers/consoleWarning.js";
import { useControllableState, useMergeRefs } from "../utils/hooks/index.js";
import { useI18n } from "../utils/i18n/i18n.hooks.js";
/**
 * A component that displays a tooltip when the user hovers over its child element.
 *
 * @see [📝 Documentation](https://aksel.nav.no/komponenter/core/tooltip)
 * @see 🏷️ {@link TooltipProps}
 *
 * @example
 * ```jsx Tooltip as only form of labeling
 * <Tooltip content="Skriv ut dokument">
 *   <Button icon={<PrinterLargeIcon aria-hidden />} />
 * </Tooltip>
 * ```
 */
export const Tooltip = forwardRef((_a, ref) => {
    var { children, className, arrow: _arrow = true, placement: _placement = "top", open, defaultOpen = false, onOpenChange, offset: _offset, content, delay = 150, id, keys, maxChar = 80, describesChild = false } = _a, rest = __rest(_a, ["children", "className", "arrow", "placement", "open", "defaultOpen", "onOpenChange", "offset", "content", "delay", "id", "keys", "maxChar", "describesChild"]);
    const [_open, _setOpen] = useControllableState({
        defaultValue: defaultOpen,
        value: open,
        onChange: onOpenChange,
    });
    const arrowRef = useRef(null);
    const modalContext = useModalContext(false);
    const rootElement = modalContext
        ? modalContext.modalRef.current
        : undefined;
    const { x, y, strategy, context, placement, middlewareData: { arrow: { x: arrowX, y: arrowY } = {}, hide: { referenceHidden } = {}, }, refs, } = useFloating({
        placement: _placement,
        open: _open,
        onOpenChange: (newState) => _setOpen(newState),
        middleware: [
            offset(_offset !== null && _offset !== void 0 ? _offset : (_arrow ? 8 : 4)),
            shift(),
            flip({ padding: 5, fallbackPlacements: ["bottom", "top"] }),
            flArrow({ element: arrowRef, padding: 5 }),
        ],
        whileElementsMounted: modalContext
            ? (reference, floating, update) => 
            // Reduces jumping in Chrome when used in a Modal and it's the first focusable element.
            // Can be removed when autofocus starts working on <dialog> in Chrome. See also Modal.tsx
            autoUpdate(reference, floating, update, { animationFrame: true })
            : autoUpdate,
        strategy: modalContext ? "fixed" : undefined,
    });
    const { getReferenceProps, getFloatingProps } = useInteractions([
        useHover(context, { handleClose: safePolygon(), restMs: delay }),
        useFocus(context),
        useDismiss(context),
    ]);
    const ariaId = useId(id);
    const mergedRef = useMergeRefs(ref, refs.setFloating);
    if (!children ||
        (children === null || children === void 0 ? void 0 : children.type) === React.Fragment ||
        children === React.Fragment) {
        console.error("<Tooltip> children needs to be a single ReactElement and not: <React.Fragment/> | <></>");
        return null;
    }
    if ((content === null || content === void 0 ? void 0 : content.length) > maxChar) {
        consoleWarning(`<Tooltip />: Because of strict a11y concerns we encourage all tooltips to have less than 80 characters. Can be overridden with the maxChar prop\n\nLength:${content.length}\nTooltip content: ${content}`);
    }
    const labelProps = describesChild
        ? _open
            ? { "aria-describedby": ariaId }
            : { title: content }
        : { "aria-label": content };
    return (React.createElement(React.Fragment, null,
        React.createElement(Slot, Object.assign({ ref: refs.setReference }, getReferenceProps(), labelProps, { "aria-keyshortcuts": ariaShortcuts(keys) }), children),
        _open && (React.createElement(Portal, { rootElement: rootElement },
            React.createElement("div", Object.assign({}, getFloatingProps(Object.assign(Object.assign({}, rest), { ref: mergedRef, style: {
                    position: strategy,
                    top: y !== null && y !== void 0 ? y : 0,
                    left: x !== null && x !== void 0 ? x : 0,
                    visibility: referenceHidden ? "hidden" : "visible",
                }, role: "tooltip", id: ariaId, className: cl("aksel-tooltip", "aksel-detail aksel-detail--small", className) })), { "data-side": placement, "data-state": "open" }),
                content,
                React.createElement(TooltipShortcuts, { shortcuts: keys }),
                _arrow && (React.createElement("div", { ref: arrowRef, className: "aksel-tooltip__arrow", style: {
                        left: arrowX != null ? `${arrowX}px` : "",
                        top: arrowY != null ? `${arrowY}px` : "",
                        right: "",
                        bottom: "",
                        [{
                            top: "bottom",
                            right: "left",
                            bottom: "top",
                            left: "right",
                        }[placement]]: "-3.5px",
                    } })))))));
});
function isKeyShortcutNested(shortcuts) {
    return Array.isArray(shortcuts === null || shortcuts === void 0 ? void 0 : shortcuts[0]);
}
/**
 * https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-keyshortcuts
 * Space-separated shortcuts is valid syntax
 */
function ariaShortcuts(shortcuts) {
    if (!shortcuts) {
        return undefined;
    }
    if (isKeyShortcutNested(shortcuts)) {
        return shortcuts.map((key) => key.join("+")).join(" ");
    }
    return shortcuts.join("+");
}
function TooltipShortcuts({ shortcuts }) {
    const translate = useI18n("Tooltip");
    if (!shortcuts) {
        return null;
    }
    if (isKeyShortcutNested(shortcuts)) {
        return (React.createElement("span", { className: "aksel-tooltip__keys", "aria-hidden": true }, shortcuts.map((key, index) => (React.createElement(Fragment, { key: key.join("+") },
            React.createElement(HStack, { gap: "space-4" }, key.map((k, i) => (React.createElement(Detail, { as: "kbd", key: i, className: "aksel-tooltip__key" }, k)))),
            index < shortcuts.length - 1 && (React.createElement("span", null,
                " ",
                translate("shortcutSeparator"),
                " ")))))));
    }
    return (React.createElement("span", { className: "aksel-tooltip__keys", "aria-hidden": true }, shortcuts.map((k, i) => (React.createElement(Detail, { as: "kbd", key: i, className: "aksel-tooltip__key" }, k)))));
}
export default Tooltip;
//# sourceMappingURL=Tooltip.js.map