"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiMarkdownEditorFooter = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _loading = require("../loading");

var _button = require("../button");

var _title = require("../title");

var _modal = require("../modal");

var _i18n = require("../i18n");

var _popover = require("../popover");

var _text = require("../text");

var _spacer = require("../spacer");

var _markdown_logo = _interopRequireDefault(require("./icons/markdown_logo"));

var _horizontal_rule = require("../horizontal_rule");

var _tool_tip = require("../tool_tip");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /*
                                                                       * SPDX-License-Identifier: Apache-2.0
                                                                       *
                                                                       * The OpenSearch Contributors require contributions made to
                                                                       * this file be licensed under the Apache-2.0 license or a
                                                                       * compatible open source license.
                                                                       *
                                                                       * Modifications Copyright OpenSearch Contributors. See
                                                                       * GitHub history for details.
                                                                       */ /*
                                                                           * Licensed to Elasticsearch B.V. under one or more contributor
                                                                           * license agreements. See the NOTICE file distributed with
                                                                           * this work for additional information regarding copyright
                                                                           * ownership. Elasticsearch B.V. licenses this file to you under
                                                                           * the Apache License, Version 2.0 (the "License"); you may
                                                                           * not use this file except in compliance with the License.
                                                                           * You may obtain a copy of the License at
                                                                           *
                                                                           *    http://www.apache.org/licenses/LICENSE-2.0
                                                                           *
                                                                           * Unless required by applicable law or agreed to in writing,
                                                                           * software distributed under the License is distributed on an
                                                                           * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
                                                                           * KIND, either express or implied.  See the License for the
                                                                           * specific language governing permissions and limitations
                                                                           * under the License.
                                                                           */ // @ts-ignore a react svg


var EuiMarkdownEditorFooter = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var uiPlugins = props.uiPlugins,
      isUploadingFiles = props.isUploadingFiles,
      openFiles = props.openFiles,
      errors = props.errors,
      hasUnacceptedItems = props.hasUnacceptedItems,
      dropHandlers = props.dropHandlers;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      isShowingHelp = _useState2[0],
      setIsShowingHelp = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isPopoverOpen = _useState4[0],
      setIsPopoverOpen = _useState4[1];

  var onButtonClick = function onButtonClick() {
    return setIsPopoverOpen(function (isPopoverOpen) {
      return !isPopoverOpen;
    });
  };

  var closePopover = function closePopover() {
    return setIsPopoverOpen(false);
  };

  var uploadButton;
  var supportedFileTypes = (0, _react.useMemo)(function () {
    return dropHandlers.map(function (_ref) {
      var supportedFiles = _ref.supportedFiles;
      return supportedFiles.join(', ');
    }).sort().join(', ');
  }, [dropHandlers]);
  var ariaLabels = {
    uploadingFiles: (0, _i18n.useEuiI18n)('euiMarkdownEditorFooter.uploadingFiles', 'Click to upload files'),
    openUploadModal: (0, _i18n.useEuiI18n)('euiMarkdownEditorFooter.openUploadModal', 'Open upload files modal'),
    unsupportedFileType: (0, _i18n.useEuiI18n)('euiMarkdownEditorFooter.unsupportedFileType', 'File type not supported'),
    supportedFileTypes: (0, _i18n.useEuiI18n)('euiMarkdownEditorFooter.supportedFileTypes', 'Supported files: {supportedFileTypes}', {
      supportedFileTypes: supportedFileTypes
    }),
    showSyntaxErrors: (0, _i18n.useEuiI18n)('euiMarkdownEditorFooter.showSyntaxErrors', 'Show errors'),
    showMarkdownHelp: (0, _i18n.useEuiI18n)('euiMarkdownEditorFooter.showMarkdownHelp', 'Show markdown help')
  };

  if (isUploadingFiles) {
    uploadButton = /*#__PURE__*/_react.default.createElement(_button.EuiButtonIcon, {
      iconType: _loading.EuiLoadingSpinner,
      "aria-label": ariaLabels.uploadingFiles
    });
  } else if (dropHandlers.length > 0 && hasUnacceptedItems) {
    uploadButton = /*#__PURE__*/_react.default.createElement(_tool_tip.EuiToolTip, {
      content: ariaLabels.supportedFileTypes
    }, /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
      className: "euiMarkdownEditorFooter__uploadError",
      autoFocus: true,
      size: "xs",
      iconType: "paperClip",
      color: "danger",
      "aria-label": "".concat(ariaLabels.unsupportedFileType, ". ").concat(ariaLabels.supportedFileTypes, ". ").concat(ariaLabels.uploadingFiles),
      onClick: openFiles
    }, ariaLabels.unsupportedFileType));
  } else if (dropHandlers.length > 0) {
    uploadButton = /*#__PURE__*/_react.default.createElement(_button.EuiButtonIcon, {
      iconType: "paperClip",
      color: "text",
      "aria-label": ariaLabels.openUploadModal,
      onClick: openFiles
    });
  }

  var errorsButton;

  if (errors && errors.length) {
    errorsButton = /*#__PURE__*/_react.default.createElement(_popover.EuiPopover, {
      button: /*#__PURE__*/_react.default.createElement(_button.EuiButtonEmpty, {
        iconType: "crossInACircleFilled",
        size: "s",
        color: "danger",
        "aria-label": ariaLabels.showSyntaxErrors,
        onClick: onButtonClick
      }, errors.length),
      isOpen: isPopoverOpen,
      closePopover: closePopover,
      panelPaddingSize: "s",
      anchorPosition: "upCenter"
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: "euiMarkdownEditorFooter__popover"
    }, /*#__PURE__*/_react.default.createElement(_popover.EuiPopoverTitle, null, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
      token: "euiMarkdownEditorFooter.errorsTitle",
      default: "Errors"
    })), errors.map(function (message, idx) {
      return /*#__PURE__*/_react.default.createElement(_text.EuiText, {
        size: "s",
        key: idx
      }, message.toString());
    })));
  }

  return /*#__PURE__*/_react.default.createElement("div", {
    ref: ref,
    className: "euiMarkdownEditorFooter"
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "euiMarkdownEditorFooter__actions"
  }, uploadButton, errorsButton), /*#__PURE__*/_react.default.createElement(_button.EuiButtonIcon, {
    className: "euiMarkdownEditorFooter__help",
    iconType: _markdown_logo.default,
    color: "text",
    "aria-label": ariaLabels.showMarkdownHelp,
    onClick: function onClick() {
      return setIsShowingHelp(!isShowingHelp);
    }
  }), isShowingHelp && /*#__PURE__*/_react.default.createElement(_modal.EuiModal, {
    onClose: function onClose() {
      return setIsShowingHelp(false);
    }
  }, /*#__PURE__*/_react.default.createElement(_modal.EuiModalHeader, null, /*#__PURE__*/_react.default.createElement(_title.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h3", null, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiMarkdownEditorFooter.syntaxTitle",
    default: "Syntax help"
  })))), /*#__PURE__*/_react.default.createElement(_modal.EuiModalBody, null, /*#__PURE__*/_react.default.createElement(_text.EuiText, null, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    tokens: ['euiMarkdownEditorFooter.descriptionPrefix', 'euiMarkdownEditorFooter.descriptionSuffix'],
    defaults: ['This editor uses', 'You can also utilize these additional syntax plugins to add rich content to your text.']
  }, function (_ref2) {
    var _ref3 = _slicedToArray(_ref2, 2),
        descriptionPrefix = _ref3[0],
        descriptionSuffix = _ref3[1];

    return /*#__PURE__*/_react.default.createElement("p", null, descriptionPrefix, ' ', /*#__PURE__*/_react.default.createElement("a", {
      href: "https://github.github.com/gfm/",
      target: "_blank"
    }, "Github flavored markdown"), ". ", descriptionSuffix);
  })), /*#__PURE__*/_react.default.createElement(_horizontal_rule.EuiHorizontalRule, null), uiPlugins.filter(function (_ref4) {
    var helpText = _ref4.helpText;
    return !!helpText;
  }).map(function (_ref5) {
    var name = _ref5.name,
        helpText = _ref5.helpText;
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, {
      key: name
    }, /*#__PURE__*/_react.default.createElement(_title.EuiTitle, {
      size: "xxs"
    }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement("strong", null, name))), /*#__PURE__*/_react.default.createElement(_spacer.EuiSpacer, {
      size: "s"
    }), helpText, /*#__PURE__*/_react.default.createElement(_spacer.EuiSpacer, {
      size: "l"
    }));
  }), /*#__PURE__*/_react.default.createElement(_horizontal_rule.EuiHorizontalRule, null)), /*#__PURE__*/_react.default.createElement(_modal.EuiModalFooter, null, /*#__PURE__*/_react.default.createElement(_button.EuiButton, {
    onClick: function onClick() {
      return setIsShowingHelp(false);
    },
    fill: true
  }, /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
    token: "euiMarkdownEditorFooter.closeButton",
    default: "Close"
  })))));
});
exports.EuiMarkdownEditorFooter = EuiMarkdownEditorFooter;
EuiMarkdownEditorFooter.propTypes = {
  uiPlugins: _propTypes.default.arrayOf(_propTypes.default.shape({
    name: _propTypes.default.string.isRequired,
    button: _propTypes.default.shape({
      label: _propTypes.default.string.isRequired,
      iconType: _propTypes.default.oneOfType([_propTypes.default.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "aggregate", "alert", "analyzeEvent", "annotation", "anomalyDetection", "apmApp", "apmTrace", "apps", "appSearchApp", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "asterisk", "auditbeatApp", "beaker", "bell", "bellSlash", "bolt", "boxesHorizontal", "boxesVertical", "branch", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "codeApp", "chatLeft", "chatRight", "check", "checkInCircleEmpty", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "color", "compute", "console", "consoleApp", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "crossInACircleFilled", "crossInCircleEmpty", "crossInCircleFilled", "currency", "cut", "dashboardApp", "database", "dataVisualizer", "devToolsApp", "discoverApp", "document", "documentation", "documentEdit", "documents", "dot", "download", "dockedBottom", "dockedDetached", "dockedLeft", "dockedRight", "dockedTakeover", "dockedTop", "editorAlignCenter", "editorAlignLeft", "editorAlignRight", "editorBold", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "editorItalic", "editorItemAlignLeft", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "editorStrike", "editorTable", "editorUnderline", "editorUndo", "editorUnorderedList", "email", "empty", "emsApp", "eql", "eraser", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "filebeatApp", "filter", "flag", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "iInCircle", "image", "importAction", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "inputOutput", "inspect", "integrationGeneral", "integrationObservability", "integrationSearch", "integrationSecurity", "invert", "ip", "keyboardShortcut", "kqlField", "kqlFunction", "kqlOperand", "kqlSelector", "kqlValue", "layers", "lensApp", "link", "list", "listAdd", "lock", "lockOpen", "logsApp", "logoAerospike", "logoApache", "logoAppSearch", "logoAWS", "logoAWSMono", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticsearch", "logoElasticStack", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOpenSearch", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "machineLearningApp", "magnet", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "mapMarker", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusInCircle", "minusInCircleFilled", "mobile", "monitoringApp", "moon", "nested", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "partial", "paperClip", "pause", "pencil", "percent", "pin", "pinFilled", "pipelineApp", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "polygon", "popout", "power", "push", "questionInCircle", "quote", "radius", "recentlyViewedApp", "redeploy", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "shard", "share", "snowflake", "sortable", "sortDown", "sortLeft", "sortRight", "sortUp", "spacesApp", "sqlApp", "starEmpty", "starEmptySpace", "starFilled", "starFilledSpace", "starMinusEmpty", "starMinusFilled", "starPlusEmpty", "starPlusFilled", "stats", "stop", "stopFilled", "stopSlash", "storage", "string", "submodule", "swatchInput", "symlink", "tableOfContents", "tableDensityExpanded", "tableDensityCompact", "tableDensityNormal", "tag", "tear", "temperature", "thumbsDown", "thumbsUp", "timeline", "timelionApp", "timeslider", "training", "trash", "upgradeAssistantApp", "uptimeApp", "undeploy", "unfold", "unlink", "user", "users", "usersRolesApp", "vector", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visBuilder", "visBuilderSavedObject", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "visPie", "visQueryDQL", "visQueryPPL", "visQueryPromQL", "visQuerySQL", "visTable", "visTagCloud", "visText", "visTimelion", "visualizeApp", "visVega", "visVisualBuilder", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenClass", "tokenProperty", "tokenEnum", "tokenVariable", "tokenMethod", "tokenAnnotation", "tokenException", "tokenInterface", "tokenParameter", "tokenField", "tokenElement", "tokenFunction", "tokenBoolean", "tokenString", "tokenArray", "tokenNumber", "tokenConstant", "tokenObject", "tokenEvent", "tokenKey", "tokenNull", "tokenStruct", "tokenPackage", "tokenOperator", "tokenEnumMember", "tokenRepo", "tokenSymbol", "tokenFile", "tokenModule", "tokenNamespace", "tokenDate", "tokenIP", "tokenNested", "tokenAlias", "tokenShape", "tokenGeo", "tokenRange", "tokenBinary", "tokenJoin", "tokenPercolator", "tokenFlattened", "tokenRankFeature", "tokenRankFeatures", "tokenKeyword", "tokenCompletionSuggester", "tokenDenseVector", "tokenText", "tokenTokenCount", "tokenSearchType", "tokenHistogram"]).isRequired, _propTypes.default.string.isRequired, _propTypes.default.elementType.isRequired]).isRequired
    }).isRequired,
    helpText: _propTypes.default.node,
    formatting: _propTypes.default.shape({
      prefix: _propTypes.default.string,
      suffix: _propTypes.default.string,
      blockPrefix: _propTypes.default.string,
      blockSuffix: _propTypes.default.string,
      multiline: _propTypes.default.bool,
      replaceNext: _propTypes.default.string,
      prefixSpace: _propTypes.default.bool,
      scanFor: _propTypes.default.string,
      surroundWithNewlines: _propTypes.default.bool,
      orderedList: _propTypes.default.bool,
      trimFirst: _propTypes.default.bool
    }),
    editor: _propTypes.default.elementType
  }).isRequired).isRequired,
  isUploadingFiles: _propTypes.default.bool.isRequired,
  openFiles: _propTypes.default.func.isRequired,
  errors: _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.any.isRequired, _propTypes.default.any.isRequired]).isRequired).isRequired,
  hasUnacceptedItems: _propTypes.default.bool.isRequired,
  dropHandlers: _propTypes.default.arrayOf(_propTypes.default.shape({
    supportedFiles: _propTypes.default.arrayOf(_propTypes.default.string.isRequired).isRequired,
    accepts: _propTypes.default.func.isRequired,
    getFormattingForItem: _propTypes.default.func.isRequired
  }).isRequired).isRequired
};
EuiMarkdownEditorFooter.displayName = 'EuiMarkdownEditorFooter';