"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tooltip = void 0;
const react_1 = require("@floating-ui/react");
const react_2 = __importStar(require("react"));
const Modal_context_1 = require("../modal/Modal.context");
const portal_1 = require("../portal");
const stack_1 = require("../primitives/stack");
const typography_1 = require("../typography");
const utils_external_1 = require("../utils-external");
const Slot_1 = require("../utils/components/slot/Slot");
const helpers_1 = require("../utils/helpers");
const consoleWarning_1 = require("../utils/helpers/consoleWarning");
const hooks_1 = require("../utils/hooks");
const i18n_hooks_1 = require("../utils/i18n/i18n.hooks");
/**
 * 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>
 * ```
 */
exports.Tooltip = (0, react_2.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] = (0, hooks_1.useControllableState)({
        defaultValue: defaultOpen,
        value: open,
        onChange: onOpenChange,
    });
    const arrowRef = (0, react_2.useRef)(null);
    const modalContext = (0, Modal_context_1.useModalContext)(false);
    const rootElement = modalContext
        ? modalContext.modalRef.current
        : undefined;
    const { x, y, strategy, context, placement, middlewareData: { arrow: { x: arrowX, y: arrowY } = {}, hide: { referenceHidden } = {}, }, refs, } = (0, react_1.useFloating)({
        placement: _placement,
        open: _open,
        onOpenChange: (newState) => _setOpen(newState),
        middleware: [
            (0, react_1.offset)(_offset !== null && _offset !== void 0 ? _offset : (_arrow ? 8 : 4)),
            (0, react_1.shift)(),
            (0, react_1.flip)({ padding: 5, fallbackPlacements: ["bottom", "top"] }),
            (0, react_1.arrow)({ 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
            (0, react_1.autoUpdate)(reference, floating, update, { animationFrame: true })
            : react_1.autoUpdate,
        strategy: modalContext ? "fixed" : undefined,
    });
    const { getReferenceProps, getFloatingProps } = (0, react_1.useInteractions)([
        (0, react_1.useHover)(context, { handleClose: (0, react_1.safePolygon)(), restMs: delay }),
        (0, react_1.useFocus)(context),
        (0, react_1.useDismiss)(context),
    ]);
    const ariaId = (0, utils_external_1.useId)(id);
    const mergedRef = (0, hooks_1.useMergeRefs)(ref, refs.setFloating);
    if (!children ||
        (children === null || children === void 0 ? void 0 : children.type) === react_2.default.Fragment ||
        children === react_2.default.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) {
        (0, consoleWarning_1.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_2.default.createElement(react_2.default.Fragment, null,
        react_2.default.createElement(Slot_1.Slot, Object.assign({ ref: refs.setReference }, getReferenceProps(), labelProps, { "aria-keyshortcuts": ariaShortcuts(keys) }), children),
        _open && (react_2.default.createElement(portal_1.Portal, { rootElement: rootElement },
            react_2.default.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: (0, helpers_1.cl)("aksel-tooltip", "aksel-detail aksel-detail--small", className) })), { "data-side": placement, "data-state": "open" }),
                content,
                react_2.default.createElement(TooltipShortcuts, { shortcuts: keys }),
                _arrow && (react_2.default.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 = (0, i18n_hooks_1.useI18n)("Tooltip");
    if (!shortcuts) {
        return null;
    }
    if (isKeyShortcutNested(shortcuts)) {
        return (react_2.default.createElement("span", { className: "aksel-tooltip__keys", "aria-hidden": true }, shortcuts.map((key, index) => (react_2.default.createElement(react_2.Fragment, { key: key.join("+") },
            react_2.default.createElement(stack_1.HStack, { gap: "space-4" }, key.map((k, i) => (react_2.default.createElement(typography_1.Detail, { as: "kbd", key: i, className: "aksel-tooltip__key" }, k)))),
            index < shortcuts.length - 1 && (react_2.default.createElement("span", null,
                " ",
                translate("shortcutSeparator"),
                " ")))))));
    }
    return (react_2.default.createElement("span", { className: "aksel-tooltip__keys", "aria-hidden": true }, shortcuts.map((k, i) => (react_2.default.createElement(typography_1.Detail, { as: "kbd", key: i, className: "aksel-tooltip__key" }, k)))));
}
exports.default = exports.Tooltip;
//# sourceMappingURL=Tooltip.js.map