"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useCellPopover = exports.JsonPopoverContent = exports.DefaultCellPopover = exports.DataGridCellPopoverContext = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../../../services");
var _popover = require("../../../popover");
var _data_grid_cell_popover = require("./data_grid_cell_popover.styles");
var _text = require("../../../text");
var _code = require("../../../code");
var _react2 = require("@emotion/react");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
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) { (0, _defineProperty2.default)(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; } /*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */
var DataGridCellPopoverContext = exports.DataGridCellPopoverContext = /*#__PURE__*/(0, _react.createContext)({
  popoverIsOpen: false,
  cellLocation: {
    rowIndex: 0,
    colIndex: 0
  },
  openCellPopover: function openCellPopover() {},
  closeCellPopover: function closeCellPopover() {},
  setPopoverAnchor: function setPopoverAnchor() {},
  setPopoverAnchorPosition: function setPopoverAnchorPosition() {},
  setPopoverContent: function setPopoverContent() {},
  setCellPopoverProps: function setCellPopoverProps() {}
});
var useCellPopover = exports.useCellPopover = function useCellPopover() {
  // Current open state & cell location are handled here
  var _useState = (0, _react.useState)(false),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    popoverIsOpen = _useState2[0],
    setPopoverIsOpen = _useState2[1];
  var _useState3 = (0, _react.useState)({
      rowIndex: 0,
      colIndex: 0
    }),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    cellLocation = _useState4[0],
    setCellLocation = _useState4[1];
  // Popover anchor & content are passed by individual `EuiDataGridCell`s
  var _useState5 = (0, _react.useState)(null),
    _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
    popoverAnchor = _useState6[0],
    setPopoverAnchor = _useState6[1];
  var _useState7 = (0, _react.useState)('downLeft'),
    _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
    popoverAnchorPosition = _useState8[0],
    setPopoverAnchorPosition = _useState8[1];
  var _useState9 = (0, _react.useState)(),
    _useState10 = (0, _slicedToArray2.default)(_useState9, 2),
    popoverContent = _useState10[0],
    setPopoverContent = _useState10[1];
  // Allow customization of most (not all) popover props by consumers
  var _useState11 = (0, _react.useState)({}),
    _useState12 = (0, _slicedToArray2.default)(_useState11, 2),
    cellPopoverProps = _useState12[0],
    setCellPopoverProps = _useState12[1];
  var closeCellPopover = (0, _react.useCallback)(function () {
    return setPopoverIsOpen(false);
  }, []);
  var openCellPopover = (0, _react.useCallback)(function (_ref) {
    var rowIndex = _ref.rowIndex,
      colIndex = _ref.colIndex;
    // Prevent popover DOM issues when re-opening the same popover
    if (popoverIsOpen && rowIndex === cellLocation.rowIndex && colIndex === cellLocation.colIndex) {
      return;
    }

    // Toggle our open cell state, which causes EuiDataGridCells to react/check
    // if they should be the open popover and send their anchor+content if so
    setPopoverAnchor(null); // Resetting the anchor node is required for rerendering to work correctly
    setCellLocation({
      rowIndex: rowIndex,
      colIndex: colIndex
    });
    setPopoverIsOpen(true);
  }, [popoverIsOpen, cellLocation]);

  // Override the default EuiPopover `onClickOutside` behavior, since the toggling
  // popover button isn't actually the DOM node we pass to `button`. Otherwise,
  // clicking the expansion cell action triggers an outside click
  var onClickOutside = (0, _react.useCallback)(function (event) {
    var cellActions = popoverAnchor === null || popoverAnchor === void 0 ? void 0 : popoverAnchor.closest('.euiDataGridRowCell__actionsWrapper');
    if (!(cellActions !== null && cellActions !== void 0 && cellActions.contains(event.target))) {
      closeCellPopover();
    }
  }, [popoverAnchor, closeCellPopover]);
  var onKeyDown = (0, _react.useCallback)(function (event) {
    if (event.key === _services.keys.F2 || event.key === _services.keys.ESCAPE) {
      event.preventDefault();
      event.stopPropagation();
      closeCellPopover();
      var cell = popoverAnchor === null || popoverAnchor === void 0 ? void 0 : popoverAnchor.closest('.euiDataGridRowCell');

      // Prevent cell animation flash while focus is being shifted between popover and cell
      cell === null || cell === void 0 || cell.setAttribute('data-keyboard-closing', 'true');
      // Ensure focus is returned to the parent cell, and remove animation stopgap
      requestAnimationFrame(function () {
        cell === null || cell === void 0 || cell.focus();
        cell === null || cell === void 0 || cell.removeAttribute('data-keyboard-closing');
      });
    }
  }, [popoverAnchor, closeCellPopover]);
  var cellPopoverContext = (0, _react.useMemo)(function () {
    return {
      popoverIsOpen: popoverIsOpen,
      closeCellPopover: closeCellPopover,
      openCellPopover: openCellPopover,
      cellLocation: cellLocation,
      setPopoverAnchorPosition: setPopoverAnchorPosition,
      setPopoverAnchor: setPopoverAnchor,
      setPopoverContent: setPopoverContent,
      setCellPopoverProps: setCellPopoverProps
    };
  }, [popoverIsOpen, closeCellPopover, openCellPopover, cellLocation]);
  var styles = (0, _services.useEuiMemoizedStyles)(_data_grid_cell_popover.euiDataGridCellPopoverStyles);
  var cellPopover = (0, _react.useMemo)(function () {
    var _cellPopoverProps$pan, _cell$offsetWidth;
    if (!popoverIsOpen || !popoverAnchor) return null;
    var cell = popoverAnchor.closest('.euiDataGridRowCell');

    // Note that this popover is rendered once at the top grid level, rather than one popover per cell.
    //
    // We intentionally do NOT pass `zIndex` here. Letting `EuiPopover` derive the
    // panel's z-index from the anchor's stacking context (`getElementZIndex(button) + 2000`)
    // keeps cell popovers above their host flyout — including when sibling/nested
    // flyouts push the host's z-index above `levels.header`. See
    // https://github.com/elastic/eui/issues/8801. Consumers that need a fixed
    // value can still override via `setCellPopoverProps({ zIndex })`.
    return (0, _react2.jsx)(_popover.EuiWrappingPopover, (0, _extends2.default)({
      isOpen: popoverIsOpen,
      display: "block",
      hasArrow: false,
      attachToAnchor: true // required for https://github.com/elastic/eui/issues/6151
      ,
      panelPaddingSize: "s",
      anchorPosition: popoverAnchorPosition,
      repositionToCrossAxis: false
    }, cellPopoverProps, {
      focusTrapProps: {
        onClickOutside: onClickOutside,
        clickOutsideDisables: false
      },
      panelProps: _objectSpread(_objectSpread({
        'data-test-subj': 'euiDataGridExpansionPopover'
      }, cellPopoverProps.panelProps || {}), {}, {
        css: [styles.euiDataGridRowCell__popover, cellPopoverProps.css]
      }),
      panelClassName: (0, _classnames.default)('euiDataGridRowCell__popover', cellPopoverProps.panelClassName, (_cellPopoverProps$pan = cellPopoverProps.panelProps) === null || _cellPopoverProps$pan === void 0 ? void 0 : _cellPopoverProps$pan.className),
      panelStyle: {
        maxInlineSize: "min(75vw, max(".concat((_cell$offsetWidth = cell === null || cell === void 0 ? void 0 : cell.offsetWidth) !== null && _cell$offsetWidth !== void 0 ? _cell$offsetWidth : 0, "px, 400px))"),
        maxBlockSize: '50vh'
      },
      onKeyDown: onKeyDown,
      button: popoverAnchor,
      closePopover: closeCellPopover
    }), popoverContent);
  }, [styles, popoverIsOpen, popoverAnchor, popoverContent, cellPopoverProps, closeCellPopover, onClickOutside, onKeyDown, popoverAnchorPosition]);
  return (0, _react.useMemo)(function () {
    return {
      cellPopoverContext: cellPopoverContext,
      cellPopover: cellPopover
    };
  }, [cellPopoverContext, cellPopover]);
};

/**
 * Popover content renderers
 */

var DefaultCellPopover = exports.DefaultCellPopover = function DefaultCellPopover(_ref2) {
  var schema = _ref2.schema,
    cellActions = _ref2.cellActions,
    children = _ref2.children,
    cellContentsElement = _ref2.cellContentsElement;
  switch (schema) {
    case 'json':
      return (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)(JsonPopoverContent, {
        cellText: cellContentsElement.innerText
      }), cellActions);
    default:
      return (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)(_text.EuiText, null, children), cellActions);
  }
};
var JsonPopoverContent = exports.JsonPopoverContent = function JsonPopoverContent(_ref3) {
  var cellText = _ref3.cellText;
  var formattedText = cellText;
  try {
    formattedText = JSON.stringify(JSON.parse(formattedText), null, 2);
  } catch (e) {}
  return (0, _react2.jsx)(_code.EuiCodeBlock, {
    isCopyable: true,
    transparentBackground: true,
    paddingSize: "none",
    language: "json"
  }, formattedText);
};