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.
 */

import React, { useState, useMemo, Fragment, forwardRef } from 'react';
import PropTypes from "prop-types";
import { OuiLoadingSpinner } from '../loading';
import { OuiButton, OuiButtonEmpty, OuiButtonIcon } from '../button';
import { OuiTitle } from '../title';
import { OuiModal, OuiModalBody, OuiModalFooter, OuiModalHeader } from '../modal';
import { OuiI18n, useOuiI18n } from '../i18n';
import { OuiPopover, OuiPopoverTitle } from '../popover';
import { OuiText } from '../text';
import { OuiSpacer } from '../spacer';
// @ts-ignore a react svg
import MarkdownLogo from './icons/markdown_logo';
import { OuiHorizontalRule } from '../horizontal_rule';
import { OuiToolTip } from '../tool_tip';
export var OuiMarkdownEditorFooter = /*#__PURE__*/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 = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isShowingHelp = _useState2[0],
    setIsShowingHelp = _useState2[1];
  var _useState3 = 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 = useMemo(function () {
    return dropHandlers.map(function (_ref) {
      var supportedFiles = _ref.supportedFiles;
      return supportedFiles.join(', ');
    }).sort().join(', ');
  }, [dropHandlers]);
  var ariaLabels = {
    uploadingFiles: useOuiI18n('ouiMarkdownEditorFooter.uploadingFiles', 'Click to upload files'),
    openUploadModal: useOuiI18n('ouiMarkdownEditorFooter.openUploadModal', 'Open upload files modal'),
    unsupportedFileType: useOuiI18n('ouiMarkdownEditorFooter.unsupportedFileType', 'File type not supported'),
    supportedFileTypes: useOuiI18n('ouiMarkdownEditorFooter.supportedFileTypes', 'Supported files: {supportedFileTypes}', {
      supportedFileTypes: supportedFileTypes
    }),
    showSyntaxErrors: useOuiI18n('ouiMarkdownEditorFooter.showSyntaxErrors', 'Show errors'),
    showMarkdownHelp: useOuiI18n('ouiMarkdownEditorFooter.showMarkdownHelp', 'Show markdown help')
  };
  if (isUploadingFiles) {
    uploadButton = /*#__PURE__*/React.createElement(OuiButtonIcon, {
      iconType: OuiLoadingSpinner,
      "aria-label": ariaLabels.uploadingFiles
    });
  } else if (dropHandlers.length > 0 && hasUnacceptedItems) {
    uploadButton = /*#__PURE__*/React.createElement(OuiToolTip, {
      content: ariaLabels.supportedFileTypes
    }, /*#__PURE__*/React.createElement(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.createElement(OuiButtonIcon, {
      iconType: "paperClip",
      color: "text",
      "aria-label": ariaLabels.openUploadModal,
      onClick: openFiles
    });
  }
  var errorsButton;
  if (errors && errors.length) {
    errorsButton = /*#__PURE__*/React.createElement(OuiPopover, {
      button: /*#__PURE__*/React.createElement(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.createElement("div", {
      className: "ouiMarkdownEditorFooter__popover"
    }, /*#__PURE__*/React.createElement(OuiPopoverTitle, null, /*#__PURE__*/React.createElement(OuiI18n, {
      token: "ouiMarkdownEditorFooter.errorsTitle",
      default: "Errors"
    })), errors.map(function (message, idx) {
      return /*#__PURE__*/React.createElement(OuiText, {
        size: "s",
        key: idx
      }, message.toString());
    })));
  }
  return /*#__PURE__*/React.createElement("div", {
    ref: ref,
    className: "ouiMarkdownEditorFooter"
  }, /*#__PURE__*/React.createElement("div", {
    className: "ouiMarkdownEditorFooter__actions"
  }, uploadButton, errorsButton), /*#__PURE__*/React.createElement(OuiButtonIcon, {
    className: "ouiMarkdownEditorFooter__help",
    iconType: MarkdownLogo,
    color: "text",
    "aria-label": ariaLabels.showMarkdownHelp,
    onClick: function onClick() {
      return setIsShowingHelp(!isShowingHelp);
    }
  }), isShowingHelp && /*#__PURE__*/React.createElement(OuiModal, {
    onClose: function onClose() {
      return setIsShowingHelp(false);
    }
  }, /*#__PURE__*/React.createElement(OuiModalHeader, null, /*#__PURE__*/React.createElement(OuiTitle, null, /*#__PURE__*/React.createElement("h3", null, /*#__PURE__*/React.createElement(OuiI18n, {
    token: "ouiMarkdownEditorFooter.syntaxTitle",
    default: "Syntax help"
  })))), /*#__PURE__*/React.createElement(OuiModalBody, null, /*#__PURE__*/React.createElement(OuiText, null, /*#__PURE__*/React.createElement(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.createElement("p", null, descriptionPrefix, ' ', /*#__PURE__*/React.createElement("a", {
      href: "https://github.github.com/gfm/",
      target: "_blank"
    }, "Github flavored markdown"), ". ", descriptionSuffix);
  })), /*#__PURE__*/React.createElement(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.createElement(Fragment, {
      key: name
    }, /*#__PURE__*/React.createElement(OuiTitle, {
      size: "xxs"
    }, /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement("strong", null, name))), /*#__PURE__*/React.createElement(OuiSpacer, {
      size: "s"
    }), helpText, /*#__PURE__*/React.createElement(OuiSpacer, {
      size: "l"
    }));
  }), /*#__PURE__*/React.createElement(OuiHorizontalRule, null)), /*#__PURE__*/React.createElement(OuiModalFooter, null, /*#__PURE__*/React.createElement(OuiButton, {
    onClick: function onClick() {
      return setIsShowingHelp(false);
    },
    fill: true
  }, /*#__PURE__*/React.createElement(OuiI18n, {
    token: "ouiMarkdownEditorFooter.closeButton",
    default: "Close"
  })))));
});
OuiMarkdownEditorFooter.propTypes = {
  uiPlugins: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.string.isRequired,
    button: PropTypes.shape({
      label: PropTypes.string.isRequired,
      iconType: PropTypes.oneOfType([PropTypes.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.string.isRequired, PropTypes.elementType.isRequired]).isRequired
    }).isRequired,
    helpText: PropTypes.node,
    formatting: PropTypes.shape({
      prefix: PropTypes.string,
      suffix: PropTypes.string,
      blockPrefix: PropTypes.string,
      blockSuffix: PropTypes.string,
      multiline: PropTypes.bool,
      replaceNext: PropTypes.string,
      prefixSpace: PropTypes.bool,
      scanFor: PropTypes.string,
      surroundWithNewlines: PropTypes.bool,
      orderedList: PropTypes.bool,
      trimFirst: PropTypes.bool
    }),
    editor: PropTypes.elementType
  }).isRequired).isRequired,
  isUploadingFiles: PropTypes.bool.isRequired,
  openFiles: PropTypes.func.isRequired,
  errors: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.any.isRequired, PropTypes.any.isRequired]).isRequired).isRequired,
  hasUnacceptedItems: PropTypes.bool.isRequired,
  dropHandlers: PropTypes.arrayOf(PropTypes.shape({
    supportedFiles: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
    accepts: PropTypes.func.isRequired,
    getFormattingForItem: PropTypes.func.isRequired
  }).isRequired).isRequired
};
OuiMarkdownEditorFooter.displayName = 'OuiMarkdownEditorFooter';

/* OUI -> EUI Aliases: Build-Time */
export { EuiMarkdownEditorFooter } from '../../eui_components/markdown_editor/markdown_editor_footer';