"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiMarkdownEditorFooter", {
  enumerable: true,
  get: function get() {
    return _markdown_editor_footer.EuiMarkdownEditorFooter;
  }
});
exports.OuiMarkdownEditorFooter = 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");
var _markdown_editor_footer = require("../../eui_components/markdown_editor/markdown_editor_footer");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, 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; } /*
 * 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 OuiMarkdownEditorFooter = /*#__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.useOuiI18n)('ouiMarkdownEditorFooter.uploadingFiles', 'Click to upload files'),
    openUploadModal: (0, _i18n.useOuiI18n)('ouiMarkdownEditorFooter.openUploadModal', 'Open upload files modal'),
    unsupportedFileType: (0, _i18n.useOuiI18n)('ouiMarkdownEditorFooter.unsupportedFileType', 'File type not supported'),
    supportedFileTypes: (0, _i18n.useOuiI18n)('ouiMarkdownEditorFooter.supportedFileTypes', 'Supported files: {supportedFileTypes}', {
      supportedFileTypes: supportedFileTypes
    }),
    showSyntaxErrors: (0, _i18n.useOuiI18n)('ouiMarkdownEditorFooter.showSyntaxErrors', 'Show errors'),
    showMarkdownHelp: (0, _i18n.useOuiI18n)('ouiMarkdownEditorFooter.showMarkdownHelp', 'Show markdown help')
  };
  if (isUploadingFiles) {
    uploadButton = /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, {
      iconType: _loading.OuiLoadingSpinner,
      "aria-label": ariaLabels.uploadingFiles
    });
  } else if (dropHandlers.length > 0 && hasUnacceptedItems) {
    uploadButton = /*#__PURE__*/_react.default.createElement(_tool_tip.OuiToolTip, {
      content: ariaLabels.supportedFileTypes
    }, /*#__PURE__*/_react.default.createElement(_button.OuiButtonEmpty, {
      className: "ouiMarkdownEditorFooter__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.OuiButtonIcon, {
      iconType: "paperClip",
      color: "text",
      "aria-label": ariaLabels.openUploadModal,
      onClick: openFiles
    });
  }
  var errorsButton;
  if (errors && errors.length) {
    errorsButton = /*#__PURE__*/_react.default.createElement(_popover.OuiPopover, {
      button: /*#__PURE__*/_react.default.createElement(_button.OuiButtonEmpty, {
        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: "ouiMarkdownEditorFooter__popover"
    }, /*#__PURE__*/_react.default.createElement(_popover.OuiPopoverTitle, null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiMarkdownEditorFooter.errorsTitle",
      default: "Errors"
    })), errors.map(function (message, idx) {
      return /*#__PURE__*/_react.default.createElement(_text.OuiText, {
        size: "s",
        key: idx
      }, message.toString());
    })));
  }
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: ref,
    className: "ouiMarkdownEditorFooter"
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "ouiMarkdownEditorFooter__actions"
  }, uploadButton, errorsButton), /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, {
    className: "ouiMarkdownEditorFooter__help",
    iconType: _markdown_logo.default,
    color: "text",
    "aria-label": ariaLabels.showMarkdownHelp,
    onClick: function onClick() {
      return setIsShowingHelp(!isShowingHelp);
    }
  }), isShowingHelp && /*#__PURE__*/_react.default.createElement(_modal.OuiModal, {
    onClose: function onClose() {
      return setIsShowingHelp(false);
    }
  }, /*#__PURE__*/_react.default.createElement(_modal.OuiModalHeader, null, /*#__PURE__*/_react.default.createElement(_title.OuiTitle, null, /*#__PURE__*/_react.default.createElement("h3", null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
    token: "ouiMarkdownEditorFooter.syntaxTitle",
    default: "Syntax help"
  })))), /*#__PURE__*/_react.default.createElement(_modal.OuiModalBody, null, /*#__PURE__*/_react.default.createElement(_text.OuiText, null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
    tokens: ['ouiMarkdownEditorFooter.descriptionPrefix', 'ouiMarkdownEditorFooter.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.OuiHorizontalRule, 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.OuiTitle, {
      size: "xxs"
    }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement("strong", null, name))), /*#__PURE__*/_react.default.createElement(_spacer.OuiSpacer, {
      size: "s"
    }), helpText, /*#__PURE__*/_react.default.createElement(_spacer.OuiSpacer, {
      size: "l"
    }));
  }), /*#__PURE__*/_react.default.createElement(_horizontal_rule.OuiHorizontalRule, null)), /*#__PURE__*/_react.default.createElement(_modal.OuiModalFooter, null, /*#__PURE__*/_react.default.createElement(_button.OuiButton, {
    onClick: function onClick() {
      return setIsShowingHelp(false);
    },
    fill: true
  }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
    token: "ouiMarkdownEditorFooter.closeButton",
    default: "Close"
  })))));
});
exports.OuiMarkdownEditorFooter = OuiMarkdownEditorFooter;
OuiMarkdownEditorFooter.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", "addBookmark", "addDataApp", "advancedSettingsApp", "aggregate", "alert", "analyzeEvent", "annotation", "anomalyDetection", "apmApp", "apmTrace", "apps", "appSearchApp", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "asterisk", "auditbeatApp", "beaker", "bell", "bellSlash", "bolt", "bookOpen", "boxesHorizontal", "boxesVertical", "branch", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "codeApp", "chatLeft", "chatRight", "check", "checkInCircleEmpty", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "color", "compass", "compute", "console", "consoleApp", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "crossInACircleFilled", "crossInCircleEmpty", "crossInCircleFilled", "currency", "cut", "dashboard", "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", "functionAdd", "gear", "generate", "generateContent", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "history", "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", "lineChart", "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", "pulse", "push", "questionInCircle", "quote", "radar", "radius", "recent", "recentlyViewedApp", "redeploy", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "rocket", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "shard", "share", "snowflake", "sortable", "sortDown", "sortLeft", "sortRight", "sortUp", "spacesApp", "sparkleFilled", "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", "wsAnalytics", "wsEssentials", "wsObservability", "wsSearch", "wsSecurityAnalytics", "wsSelector", "navAdministration", "navAiFlow", "navAlerting", "navAnomalyDetection", "navDashboards", "navData", "navDetectionRules", "navDevtools", "navDiscover", "navExperiments", "navGetStarted", "navInfo", "navInfra", "navIntegrations", "navJudgements", "navManage", "navMaps", "navModels", "navNotebooks", "navNotifications", "navOverview", "navQuerySets", "navReports", "navSecurityCases", "navSecurityFindings", "navServiceMap", "navServices", "navSlos", "navThreatIntel", "navTicketing", "navUi", "navSearchConfigurationsln"]).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
};
OuiMarkdownEditorFooter.displayName = 'OuiMarkdownEditorFooter';

/* OUI -> EUI Aliases: Build-Time */