const _excluded = ["handleId"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState, useRef, useId, forwardRef, useMemo } from "react";
import PropTypes from "prop-types";
import { useSelector, useDispatch } from "react-redux";
import { makeStyles } from "@mui/styles";
import { Dialog as MuiDialog, DialogTitle, Paper } from "@mui/material";
import Draggable from "react-draggable";
import useTranslation from "../../utils/useTranslation";
import useHasScreenSize from "../../utils/useHasScreenSize";
import { setDialogVisible, setDialogPosition } from "../../model/app/actions";
import CloseButton from "../CloseButton";
const useStyles = makeStyles(theme => ({
  rootDesktop: {
    zIndex: "100!important",
    pointerEvents: "none"
  },
  paper: {
    minWidth: 320,
    zIndex: 0
  },
  paperModal: {
    width: "90%",
    maxHeight: "calc(100% - 125px)"
  },
  paperMobile: {
    position: "absolute",
    bottom: 10,
    left: 10,
    right: 10,
    width: "auto",
    zIndex: 1300
  },
  scrollPaper: {
    display: "block" // Prevent Dialog from growing in all directions
  },
  scrollPaperModal: {
    display: "flex" // Prevent Dialog from growing in all directions
  },
  dialogBody: {
    fontFamily: theme.typography.fontFamily,
    fontSize: theme.typography.htmlFontSize,
    "& a": {
      color: theme.palette.primary.main
    },
    "& a:hover": {
      color: theme.palette.secondary.main
    },
    "&>div:first-child": {
      padding: 20,
      "& > *:first-child": {
        marginTop: 0
      },
      "& > *:last-child": {
        marginBottom: 0
      }
    },
    overflowY: "auto"
  },
  dialogBodyDesktop: {
    maxHeight: props => props.isModal ? 620 : 360
  },
  dialogBodyMobile: {
    maxHeight: props => props.isModal ? 360 : 280
  },
  closeBtn: {
    position: "absolute",
    right: 0,
    top: 0,
    width: 50,
    height: 50
  }
}));
const PaperComponent = /*#__PURE__*/forwardRef((props, ref) => {
  return /*#__PURE__*/React.createElement(Paper, _extends({
    square: true,
    ref: ref
  }, props, {
    elevation: 4
  }));
});

// eslint-disable-next-line react/prop-types
function DraggablePaperComponent(_ref) {
  let {
      handleId
    } = _ref,
    props = _objectWithoutProperties(_ref, _excluded);
  const dispatch = useDispatch();
  const dialogPosition = useSelector(state => state.app.dialogPosition);
  const nodeRef = useRef(null);
  return /*#__PURE__*/React.createElement(Draggable, {
    nodeRef: nodeRef
    // eslint-disable-next-line react/destructuring-assignment, react/prop-types
    ,
    handle: "#".concat(handleId),
    cancel: '[class*="MuiDialogContent-root"]',
    defaultPosition: dialogPosition,
    position: dialogPosition,
    bounds: "parent",
    onStop: (evt, pos) => {
      dispatch(setDialogPosition({
        x: pos.lastX,
        y: pos.lastY
      }));
    }
  }, /*#__PURE__*/React.createElement(PaperComponent, _extends({}, props, {
    ref: nodeRef
  })));
}
const propTypes = {
  name: PropTypes.string.isRequired,
  title: PropTypes.node,
  body: PropTypes.element,
  // footer: PropTypes.element,
  isModal: PropTypes.bool,
  className: PropTypes.string,
  onClose: PropTypes.func,
  classes: PropTypes.objectOf(PropTypes.string)
};
function Dialog(_ref2) {
  let {
    body,
    title,
    name,
    isModal = false,
    className = "",
    onClose,
    classes
  } = _ref2;
  const {
    t
  } = useTranslation();
  const dispatch = useDispatch();
  const idd = useId();
  // The id creates useID is not a valid selector so we make it
  // valid by replacing colons with underscores
  const id = useMemo(() => idd.replace(/:/g, "_"), [idd]);
  const classesProp = classes || {};
  const [dialogNode, setDialogNode] = useState(null);
  const classesDialog = useStyles({
    isModal
  });
  const closeDialog = onClose || (() => {
    dispatch(setDialogVisible());
  });
  const escFunction = e => e.which === 27 && (onClose || (() => dispatch(setDialogVisible())));
  const isSmallScreen = useHasScreenSize(["xs", "s"]);
  useEffect(() => {
    // ComponentDidMount
    document.addEventListener("keydown", escFunction, false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const {
      activeElement
    } = document;
    if (dialogNode) {
      const dialogFocusables = dialogNode ? dialogNode.querySelectorAll('[tabindex="0"]') : [];
      if (dialogFocusables.length) {
        // Transform NodeList to array
        const visibleElt = [...dialogFocusables].find(elt => elt.className);
        // Focus the first focusable element in the popup.
        visibleElt.focus();
      }
    }
    // ComponentWillUnmount
    return () => {
      document.removeEventListener("keydown", escFunction, false);
      // Re focus the element that opened the dialog.
      activeElement.focus();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dialogNode]);

  // Props for non modal dialog
  let dialogProps = {
    disableEnforceFocus: true,
    hideBackdrop: true,
    maxWidth: false,
    PaperComponent: isSmallScreen ? PaperComponent : /*#__PURE__*/React.memo(DraggablePaperComponent),
    PaperProps: !isSmallScreen // only for DraggeblePaper
    ? {
      handleId: id
    } : undefined,
    classes: _objectSpread(_objectSpread({}, classesProp), {}, {
      root: "".concat(!isSmallScreen ? classesDialog.rootDesktop : "").concat(classesProp.root ? " ".concat(classesProp.root) : ""),
      scrollPaper: "".concat(classesDialog.scrollPaper).concat(classesProp.scrollPaper ? " ".concat(classesProp.scrollPaper) : ""),
      paper: "".concat(classesDialog.paper, " ").concat(className, " ").concat(isSmallScreen ? classesDialog.paperMobile : "").concat(classesProp.paper ? " ".concat(classesProp.paper) : "")
    })
  };

  // Props for modal dialog
  if (isModal) {
    dialogProps = {
      hideBackdrop: false,
      maxWidth: "md",
      PaperComponent,
      classes: _objectSpread(_objectSpread({}, classesProp), {}, {
        scrollPaper: "".concat(classesDialog.scrollPaperModal).concat(classesProp.scrollPaper ? " ".concat(classesProp.scrollPaper) : ""),
        paper: "".concat(classesDialog.paperModal, " ").concat(className).concat(classesProp.paper ? " ".concat(classesProp.paper) : "")
      })
    };
  }
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(MuiDialog, _extends({
    ref: elt => setDialogNode(elt),
    onClose: closeDialog,
    disablePortal: true,
    open: true,
    name: name,
    "aria-labelledby": id
  }, dialogProps), /*#__PURE__*/React.createElement(DialogTitle, {
    id: id,
    variant: "h4",
    style: {
      cursor: isModal ? "auto" : "move"
    }
  }, title), /*#__PURE__*/React.createElement(CloseButton, {
    size: "small",
    title: t("Dialog schließen"),
    onClick: closeDialog,
    className: classesDialog.closeBtn
  }), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classesDialog.dialogBody, " ").concat(isSmallScreen ? classesDialog.dialogBodyMobile : classesDialog.dialogBodyDesktop)
  }, body)));
}
Dialog.propTypes = propTypes;
export default Dialog;
//# sourceMappingURL=Dialog.js.map