"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
});
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(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; }

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", "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", "check", "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", "currency", "cut", "dashboardApp", "database", "dataVisualizer", "devToolsApp", "discoverApp", "document", "documentation", "documentEdit", "documents", "dot", "download", "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", "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", "push", "questionInCircle", "quote", "radius", "recentlyViewedApp", "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", "timeline", "timelionApp", "timeslider", "training", "trash", "upgradeAssistantApp", "uptimeApp", "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
};
OuiMarkdownEditorFooter.displayName = 'OuiMarkdownEditorFooter';
/* OUI -> EUI Aliases: Build-Time */