function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
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); }
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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
/*
 * 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.
 */

import React, { createContext, useState, useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { keys, useEuiMemoizedStyles } from '../../../../services';
import { EuiWrappingPopover } from '../../../popover';
import { euiDataGridCellPopoverStyles } from './data_grid_cell_popover.styles';
export var DataGridCellPopoverContext = /*#__PURE__*/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() {}
});
export var useCellPopover = function useCellPopover() {
  // Current open state & cell location are handled here
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    popoverIsOpen = _useState2[0],
    setPopoverIsOpen = _useState2[1];
  var _useState3 = useState({
      rowIndex: 0,
      colIndex: 0
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    cellLocation = _useState4[0],
    setCellLocation = _useState4[1];
  // Popover anchor & content are passed by individual `EuiDataGridCell`s
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    popoverAnchor = _useState6[0],
    setPopoverAnchor = _useState6[1];
  var _useState7 = useState('downLeft'),
    _useState8 = _slicedToArray(_useState7, 2),
    popoverAnchorPosition = _useState8[0],
    setPopoverAnchorPosition = _useState8[1];
  var _useState9 = useState(),
    _useState10 = _slicedToArray(_useState9, 2),
    popoverContent = _useState10[0],
    setPopoverContent = _useState10[1];
  // Allow customization of most (not all) popover props by consumers
  var _useState11 = useState({}),
    _useState12 = _slicedToArray(_useState11, 2),
    cellPopoverProps = _useState12[0],
    setCellPopoverProps = _useState12[1];
  var closeCellPopover = useCallback(function () {
    return setPopoverIsOpen(false);
  }, []);
  var openCellPopover = 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 = 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 = useCallback(function (event) {
    if (event.key === keys.F2 || event.key === 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 = 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 = useEuiMemoizedStyles(euiDataGridCellPopoverStyles);
  var cellPopover = 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 ___EmotionJSX(EuiWrappingPopover, _extends({
      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: classNames('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 useMemo(function () {
    return {
      cellPopoverContext: cellPopoverContext,
      cellPopover: cellPopover
    };
  }, [cellPopoverContext, cellPopover]);
};

/**
 * Popover content renderers
 */
import { EuiText } from '../../../text';
import { EuiCodeBlock } from '../../../code';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var DefaultCellPopover = function DefaultCellPopover(_ref2) {
  var schema = _ref2.schema,
    cellActions = _ref2.cellActions,
    children = _ref2.children,
    cellContentsElement = _ref2.cellContentsElement;
  switch (schema) {
    case 'json':
      return ___EmotionJSX(React.Fragment, null, ___EmotionJSX(JsonPopoverContent, {
        cellText: cellContentsElement.innerText
      }), cellActions);
    default:
      return ___EmotionJSX(React.Fragment, null, ___EmotionJSX(EuiText, null, children), cellActions);
  }
};
export var JsonPopoverContent = function JsonPopoverContent(_ref3) {
  var cellText = _ref3.cellText;
  var formattedText = cellText;
  try {
    formattedText = JSON.stringify(JSON.parse(formattedText), null, 2);
  } catch (e) {}
  return ___EmotionJSX(EuiCodeBlock, {
    isCopyable: true,
    transparentBackground: true,
    paddingSize: "none",
    language: "json"
  }, formattedText);
};