"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Modal = void 0;
const react_1 = require("@floating-ui/react");
const react_2 = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const Date_Input_1 = require("../date/Date.Input");
const Provider_1 = require("../provider/Provider");
const typography_1 = require("../typography");
const utils_external_1 = require("../utils-external");
const helpers_1 = require("../utils/helpers");
const hooks_1 = require("../utils/hooks");
const Modal_context_1 = require("./Modal.context");
const ModalBody_1 = __importDefault(require("./ModalBody"));
const ModalFooter_1 = __importDefault(require("./ModalFooter"));
const ModalHeader_1 = __importDefault(require("./ModalHeader"));
const ModalUtils_1 = require("./ModalUtils");
const dialog_polyfill_1 = __importStar(require("./dialog-polyfill"));
const polyfillClassName = "aksel-modal--polyfilled";
/**
 * A component that displays a modal dialog.
 *
 * @see [📝 Documentation](https://aksel.nav.no/komponenter/core/modal)
 * @see 🏷️ {@link ModalProps}
 *
 * @example
 * State change with `useRef`
 * ```jsx
 * const ref = useRef<HTMLDialogElement>(null);
 * <Button onClick={() => ref.current?.showModal()}>Open modal</Button>
 * <Modal
 *   ref={ref}
 *   header={{
 *     label: "Optional label",
 *     icon: <FileIcon aria-hidden />,
 *     heading: "My heading",
 *   }}
 * >
 *   <Modal.Body>
 *     <BodyLong>Hello world</BodyLong>
 *   </Modal.Body>
 *   <Modal.Footer>
 *     <Button>Save</Button>
 *     <Button type="button" variant="tertiary" onClick={() => ref.current?.close()}>Close</Button>
 *   </Modal.Footer>
 * </Modal>
 * ```
 * @example
 * State change with `useState`
 * ```jsx
 * const [open, setOpen] = useState(false);
 * <Modal
 *   open={open}
 *   onClose={() => setOpen(false)}
 *   aria-labelledby="modal-heading"
 * >
 *   <Modal.Header>
 *     <Heading level="1" size="large" id="modal-heading">My heading</Heading>
 *   </Modal.Header>
 *   <Modal.Body>
 *     <BodyLong>Hello world</BodyLong>
 *   </Modal.Body>
 * </Modal>
 * ```
 */
exports.Modal = (0, react_2.forwardRef)((_a, ref) => {
    var _b, _c;
    var { header, children, open, onBeforeClose, onCancel, closeOnBackdropClick, width, placement, portal, className, "aria-labelledby": ariaLabelledby, style, onClick, onMouseDown, size = "medium" } = _a, rest = __rest(_a, ["header", "children", "open", "onBeforeClose", "onCancel", "closeOnBackdropClick", "width", "placement", "portal", "className", "aria-labelledby", "style", "onClick", "onMouseDown", "size"]);
    const modalRef = (0, react_2.useRef)(null);
    const mergedRef = (0, hooks_1.useMergeRefs)(modalRef, ref);
    const ariaLabelId = (0, utils_external_1.useId)();
    const rootElement = (_b = (0, Provider_1.useProvider)()) === null || _b === void 0 ? void 0 : _b.rootElement;
    const portalNode = (0, react_1.useFloatingPortalNode)({ root: rootElement });
    const dateContext = (0, Date_Input_1.useDateInputContext)(false);
    const isNested = (0, Modal_context_1.useModalContext)(false) !== undefined;
    const isModalOpen = (0, ModalUtils_1.useIsModalOpen)(modalRef.current);
    if (isNested && !dateContext) {
        console.error("Modals should not be nested");
    }
    (0, react_2.useEffect)(() => {
        // If using portal, modalRef.current will not be set before portalNode is set.
        // If not using portal, modalRef.current is available first.
        // We check both to avoid activating polyfill twice when not using portal.
        if (dialog_polyfill_1.needPolyfill && modalRef.current && portalNode) {
            dialog_polyfill_1.default.registerDialog(modalRef.current);
            // Force-add the "polyfilled" class in case of SSR (needPolyfill will always be false on the server)
            modalRef.current.classList.add(polyfillClassName);
        }
        // We set autofocus on the dialog element to prevent the default behavior where first focusable element gets focus when modal is opened.
        // This is mainly to fix an edge case where having a Tooltip as the first focusable element would make it activate when you open the modal.
        // We have to use JS because it doesn't work to set it with a prop (React bug?)
        // Currently doesn't seem to work in Chrome. See also Tooltip.tsx
        if (modalRef.current && portalNode)
            modalRef.current.autofocus = true;
    }, [portalNode]);
    (0, react_2.useEffect)(() => {
        // We need to have this in a useEffect so that the content renders before the modal is displayed,
        // and in case `open` is true initially.
        // We need to check both modalRef.current and portalNode to make sure the polyfill has been activated.
        if (modalRef.current && portalNode && open !== undefined) {
            if (open && !modalRef.current.open) {
                modalRef.current.showModal();
            }
            else if (!open && modalRef.current.open) {
                modalRef.current.close();
            }
        }
    }, [portalNode, open]);
    (0, hooks_1.useScrollLock)({
        enabled: isModalOpen,
        mounted: isModalOpen,
        open: isModalOpen,
        referenceElement: modalRef.current,
    });
    const isWidthPreset = typeof width === "string" && ["small", "medium"].includes(width);
    const mergedClassName = (0, helpers_1.cl)("aksel-modal", className, `aksel-modal--${size}`, {
        [polyfillClassName]: dialog_polyfill_1.needPolyfill,
        "aksel-modal--autowidth": !width,
        [`aksel-modal--width-${width}`]: isWidthPreset,
        "aksel-modal--top": placement === "top" && !dialog_polyfill_1.needPolyfill,
    });
    const mergedStyle = Object.assign(Object.assign({}, style), (!isWidthPreset ? { width } : {}));
    const mouseClickStart = (0, react_2.useRef)({
        clientX: 0,
        clientY: 0,
    });
    const handleModalMouseDown = (event) => {
        mouseClickStart.current = event;
    };
    const shouldHandleModalClick = closeOnBackdropClick && !dialog_polyfill_1.needPolyfill;
    /**
     * `closeOnBackdropClick` has issues on polyfill when nesting modals (DatePicker)
     */
    const handleModalClick = (endEvent) => {
        if (endEvent.target !== modalRef.current) {
            return;
        }
        const modalRect = modalRef.current.getBoundingClientRect();
        if ((0, ModalUtils_1.coordsAreInside)(mouseClickStart.current, modalRect) ||
            (0, ModalUtils_1.coordsAreInside)(endEvent, modalRect)) {
            return;
        }
        if (onBeforeClose !== undefined && onBeforeClose() === false) {
            return;
        }
        modalRef.current.close();
    };
    /**
     * onCancel fires when you press `Esc`
     */
    const handleModalCancel = (event) => {
        onBeforeClose && onBeforeClose() === false && event.preventDefault();
    };
    const mergedAriaLabelledBy = !ariaLabelledby && !rest["aria-label"] && header
        ? ariaLabelId
        : ariaLabelledby;
    const component = (react_2.default.createElement("dialog", Object.assign({}, rest, { ref: mergedRef, className: mergedClassName, style: mergedStyle, onCancel: (0, helpers_1.composeEventHandlers)(onCancel, handleModalCancel), onClick: shouldHandleModalClick
            ? (0, helpers_1.composeEventHandlers)(onClick, handleModalClick)
            : onClick, onMouseDown: shouldHandleModalClick
            ? (0, helpers_1.composeEventHandlers)(onMouseDown, handleModalMouseDown)
            : onMouseDown, "aria-labelledby": mergedAriaLabelledBy, onKeyDown: (e) => {
            /**
             * Stops propagation of Escape key to prevent closing parent modals/dialogs
             */
            if (e.key === "Escape") {
                e.stopPropagation();
            }
        } }),
        react_2.default.createElement(Modal_context_1.ModalContextProvider, { closeHandler: (0, ModalUtils_1.getCloseHandler)(modalRef, header, onBeforeClose), modalRef: modalRef },
            header && (react_2.default.createElement(ModalHeader_1.default, null,
                header.label && (react_2.default.createElement(typography_1.Detail, { className: "aksel-modal__label" }, header.label)),
                react_2.default.createElement(typography_1.Heading, { size: (_c = header.size) !== null && _c !== void 0 ? _c : "medium", level: "1", id: ariaLabelId },
                    header.icon && (react_2.default.createElement("span", { className: "aksel-modal__header-icon" }, header.icon)),
                    header.heading))),
            children)));
    if (portal) {
        if (portalNode)
            return (0, react_dom_1.createPortal)(component, portalNode);
        return null;
    }
    return component;
});
exports.Modal.Header = ModalHeader_1.default;
exports.Modal.Body = ModalBody_1.default;
exports.Modal.Footer = ModalFooter_1.default;
exports.default = exports.Modal;
//# sourceMappingURL=Modal.js.map