"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ConsoleHistory = ConsoleHistory;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _lodash = require("lodash");
var _moment = _interopRequireDefault(require("moment"));
var _eui = require("@elastic/eui");
var _contexts = require("../../contexts");
var _history_viewer = require("./history_viewer");
var _editor_context = require("../../contexts/editor_context");
var _hooks = require("../../hooks");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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.
 */

const CHILD_ELEMENT_PREFIX = 'historyReq';
function ConsoleHistory({
  close
}) {
  const {
    services: {
      history
    }
  } = (0, _contexts.useServicesContext)();
  const {
    settings: readOnlySettings
  } = (0, _editor_context.useEditorReadContext)();
  const [requests, setPastRequests] = (0, _react.useState)(history.getHistory());
  const clearHistory = (0, _react.useCallback)(() => {
    history.clearHistory();
    setPastRequests(history.getHistory());
  }, [history]);
  const listRef = (0, _react.useRef)(null);
  const [viewingReq, setViewingReq] = (0, _react.useState)(null);
  const [selectedIndex, setSelectedIndex] = (0, _react.useState)(0);
  const selectedReq = (0, _react.useRef)(null);
  const describeReq = (0, _react.useMemo)(() => {
    const _describeReq = req => {
      const endpoint = req.endpoint;
      const date = (0, _moment.default)(req.time);
      let formattedDate = date.format('MMM D');
      if (date.diff((0, _moment.default)(), 'days') > -7) {
        formattedDate = date.fromNow();
      }
      return `${endpoint} (${formattedDate})`;
    };
    _describeReq.cache = new WeakMap();
    return (0, _lodash.memoize)(_describeReq);
  }, []);
  const scrollIntoView = (0, _react.useCallback)(idx => {
    const activeDescendant = listRef.current.querySelector(`#${CHILD_ELEMENT_PREFIX}${idx}`);
    if (activeDescendant) {
      activeDescendant.scrollIntoView();
    }
  }, []);
  const initialize = (0, _react.useCallback)(() => {
    const nextSelectedIndex = 0;
    describeReq.cache = new WeakMap();
    setViewingReq(requests[nextSelectedIndex]);
    selectedReq.current = requests[nextSelectedIndex];
    setSelectedIndex(nextSelectedIndex);
    scrollIntoView(nextSelectedIndex);
  }, [describeReq, requests, scrollIntoView]);
  const clear = () => {
    clearHistory();
    initialize();
  };
  const restoreRequestFromHistory = (0, _hooks.useRestoreRequestFromHistory)();
  (0, _react.useEffect)(() => {
    initialize();
  }, [initialize]);
  (0, _react.useEffect)(() => {
    const done = history.change(setPastRequests);
    return () => done();
  }, [history]);

  /* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role,jsx-a11y/click-events-have-key-events */
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
    className: "conHistory"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "s"
  }, /*#__PURE__*/_react.default.createElement("h2", null, _i18n.i18n.translate('console.historyPage.pageTitle', {
    defaultMessage: 'History'
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "conHistory__body"
  }, /*#__PURE__*/_react.default.createElement("ul", {
    ref: listRef,
    onKeyDown: ev => {
      if (ev.key === _eui.keys.ENTER) {
        restoreRequestFromHistory(selectedReq.current);
        return;
      }
      let currentIdx = selectedIndex;
      if (ev.key === _eui.keys.ARROW_UP) {
        ev.preventDefault();
        --currentIdx;
      } else if (ev.key === _eui.keys.ARROW_DOWN) {
        ev.preventDefault();
        ++currentIdx;
      }
      const nextSelectedIndex = Math.min(Math.max(0, currentIdx), requests.length - 1);
      setViewingReq(requests[nextSelectedIndex]);
      selectedReq.current = requests[nextSelectedIndex];
      setSelectedIndex(nextSelectedIndex);
      scrollIntoView(nextSelectedIndex);
    },
    role: "listbox",
    className: "list-group conHistory__reqs",
    tabIndex: 0,
    "aria-activedescendant": `${CHILD_ELEMENT_PREFIX}${selectedIndex}`,
    "aria-label": _i18n.i18n.translate('console.historyPage.requestListAriaLabel', {
      defaultMessage: 'History of sent requests'
    })
  }, requests.map((req, idx) => {
    const reqDescription = describeReq(req);
    const isSelected = viewingReq === req;
    return (
      /*#__PURE__*/
      // Ignore a11y issues on li's
      _react.default.createElement("li", {
        key: idx,
        id: `${CHILD_ELEMENT_PREFIX}${idx}`,
        className: `list-group-item conHistory__req ${isSelected ? 'conHistory__req-selected' : ''}`,
        onClick: () => {
          setViewingReq(req);
          selectedReq.current = req;
          setSelectedIndex(idx);
        },
        role: "option",
        onMouseEnter: () => setViewingReq(req),
        onMouseLeave: () => setViewingReq(selectedReq.current),
        onDoubleClick: () => restoreRequestFromHistory(selectedReq.current),
        "aria-label": _i18n.i18n.translate('console.historyPage.itemOfRequestListAriaLabel', {
          defaultMessage: 'Request: {historyItem}',
          values: {
            historyItem: reqDescription
          }
        }),
        "aria-selected": isSelected
      }, reqDescription, /*#__PURE__*/_react.default.createElement("span", {
        className: "conHistory__reqIcon"
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: "arrowRight"
      })))
    );
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "conHistory__body__spacer"
  }), /*#__PURE__*/_react.default.createElement(_history_viewer.HistoryViewer, {
    settings: readOnlySettings,
    req: viewingReq
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    justifyContent: "spaceBetween",
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    "data-test-subj": "consoleClearHistoryButton",
    color: "danger",
    onClick: () => clear()
  }, _i18n.i18n.translate('console.historyPage.clearHistoryButtonLabel', {
    defaultMessage: 'Clear'
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    justifyContent: "flexEnd",
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    "data-test-subj": "consoleHistoryCloseButton",
    color: "primary",
    onClick: () => close()
  }, _i18n.i18n.translate('console.historyPage.closehistoryButtonLabel', {
    defaultMessage: 'Close'
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "consoleHistoryApplyButton",
    color: "primary",
    disabled: !selectedReq,
    onClick: () => restoreRequestFromHistory(selectedReq.current)
  }, _i18n.i18n.translate('console.historyPage.applyHistoryButtonLabel', {
    defaultMessage: 'Apply'
  }))))))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }));
}