"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.DialogPopupInternal = void 0;
const react_1 = __importStar(require("react"));
const box_1 = require("../../primitives/box");
const DismissableLayer_1 = require("../../utils/components/dismissablelayer/DismissableLayer");
const FocusBoundary_1 = require("../../utils/components/focus-boundary/FocusBoundary");
const FocusGuards_1 = require("../../utils/components/focus-guards/FocusGuards");
const helpers_1 = require("../../utils/helpers");
const hooks_1 = require("../../utils/hooks");
const DialogRoot_context_1 = require("../root/DialogRoot.context");
const DialogPopupInternal = (0, react_1.forwardRef)((_a, forwardedRef) => {
    var { className, modal, closeOnOutsideClick = true, initialFocusTo, returnFocusTo, position = "center", width = "medium", height, id, style, "aria-labelledby": ariaLabelledbyProp, withBackdrop, role = "dialog" } = _a, restProps = __rest(_a, ["className", "modal", "closeOnOutsideClick", "initialFocusTo", "returnFocusTo", "position", "width", "height", "id", "style", "aria-labelledby", "withBackdrop", "role"]);
    const { mounted, popupRef, setPopupElement, triggerElement, setOpen, open, transitionStatus, popupElement, nestedOpenDialogCount: nestedOpenDialogCountProp, nested, size, titleId, popupId, onOpenChangeComplete, setMounted, } = (0, DialogRoot_context_1.useDialogContext)();
    const mergedRefs = (0, hooks_1.useMergeRefs)(forwardedRef, popupRef, setPopupElement);
    (0, hooks_1.useScrollLock)({
        enabled: open && modal === true,
        mounted,
        open,
        referenceElement: popupElement,
    });
    (0, hooks_1.useOpenChangeAnimationComplete)({
        open,
        ref: popupRef,
        onComplete() {
            if (open) {
                onOpenChangeComplete === null || onOpenChangeComplete === void 0 ? void 0 : onOpenChangeComplete(true);
            }
            else {
                setMounted(false);
                onOpenChangeComplete === null || onOpenChangeComplete === void 0 ? void 0 : onOpenChangeComplete(false);
            }
        },
    });
    const resolvedInitialFocus = initialFocusTo !== null && initialFocusTo !== void 0 ? initialFocusTo : popupRef;
    const resolvedReturnFocus = () => {
        if (returnFocusTo) {
            return typeof returnFocusTo === "function"
                ? returnFocusTo()
                : returnFocusTo.current;
        }
        if (isFocusable(triggerElement)) {
            return triggerElement;
        }
        return true;
    };
    return (react_1.default.createElement(FocusGuards_1.FocusGuards, null,
        react_1.default.createElement(FocusBoundary_1.FocusBoundary, { loop: true, trapped: open, initialFocus: resolvedInitialFocus, returnFocus: resolvedReturnFocus, modal: true },
            react_1.default.createElement(DismissableLayer_1.DismissableLayer, { asChild: true, safeZone: {
                    anchor: triggerElement,
                }, onDismiss: (event) => {
                    open && setOpen(false, event);
                }, disableOutsidePointerEvents: modal === true || withBackdrop, onInteractOutside: (event) => {
                    /**
                     * Since trigger might be set up to close the dialog on click,
                     * we need to prevent dismissing when clicking the trigger to avoid double close events (potentially re-triggering open)
                     */
                    const target = event.target;
                    const targetIsTrigger = triggerElement === null || triggerElement === void 0 ? void 0 : triggerElement.contains(target);
                    if (targetIsTrigger) {
                        event.preventDefault();
                    }
                }, 
                /**
                 * Only close dialog on pointerUp pointerEvents
                 */
                onPointerDownOutside: (event) => {
                    event.preventDefault();
                }, onFocusOutside: (event) => {
                    /**
                     * Focus-events are tricky when dealing with portals and nested dialogs.
                     * If multiple dialogs are open, initial auto-focus might cause
                     * onFocusOutside to trigger on the parent dialog when focusing the child dialog.
                     */
                    event.preventDefault();
                }, enablePointerUpOutside: true, onPointerUpOutside: (event) => {
                    !closeOnOutsideClick && event.preventDefault();
                } },
                react_1.default.createElement(box_1.BoxNew, Object.assign({ "aria-labelledby": ariaLabelledbyProp !== null && ariaLabelledbyProp !== void 0 ? ariaLabelledbyProp : titleId, id: id !== null && id !== void 0 ? id : popupId }, restProps, { ref: mergedRefs, className: (0, helpers_1.cl)("aksel-dialog__popup", className), role: role, "aria-modal": "true" }, (0, hooks_1.createTransitionStatusAttribute)(transitionStatus), { "data-position": position, "data-size": size, width: translateWidth(width, position), height: translateHeight(height, position), style: Object.assign(Object.assign({}, style), { "--__axc-nested-level": nestedOpenDialogCountProp }), "data-nested-dialog-open": !!nestedOpenDialogCountProp, "data-nested": !!nested }))))));
});
exports.DialogPopupInternal = DialogPopupInternal;
function translateWidth(width, position) {
    if (position === "fullscreen") {
        return undefined;
    }
    switch (width) {
        case "small":
            return "480px";
        case "medium":
            return "640px";
        case "large":
            return "800px";
        default:
            return width;
    }
}
function translateHeight(height, position) {
    if (position === "fullscreen" ||
        position === "left" ||
        position === "right") {
        return undefined;
    }
    return height;
}
function isFocusable(element) {
    if (!(element === null || element === void 0 ? void 0 : element.isConnected)) {
        return false;
    }
    /**
     * Baselined in 2024
     * @see https://caniuse.com/?search=checkvisibility
     */
    if (typeof element.checkVisibility === "function") {
        return element.checkVisibility();
    }
    return getComputedStyle(element).display !== "none";
}
//# sourceMappingURL=DialogPopupInternal.js.map