"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiMarkdownEditorToolbar = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../services");
var _button = require("../button");
var _i18n = require("../i18n");
var _tool_tip = require("../tool_tip");
var _markdown_modes = require("./markdown_modes");
var _markdown_context = require("./markdown_context");
var _markdown_editor_toolbar = require("./markdown_editor_toolbar.styles");
var _react2 = require("@emotion/react");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/*
 * 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.
 */

/**
 * A helper type to ensure the `button` property is defined
 * on an ` EuiMarkdownEditorUiPlugin ` object.
 */

var boldItalicButtons = [{
  id: 'mdBold',
  label: 'Bold',
  name: 'strong',
  iconType: 'textBold'
}, {
  id: 'mdItalic',
  label: 'Italic',
  name: 'emphasis',
  iconType: 'textItalic'
}];
var listButtons = [{
  id: 'mdUl',
  label: 'Unordered list',
  name: 'ul',
  iconType: 'listBullet'
}, {
  id: 'mdOl',
  label: 'Ordered list',
  name: 'ol',
  iconType: 'listNumber'
}, {
  id: 'mdTl',
  label: 'Task list',
  name: 'tl',
  iconType: 'listCheck'
}];
var quoteCodeLinkButtons = [{
  id: 'mdQuote',
  label: 'Quote',
  name: 'quote',
  iconType: 'quote'
}, {
  id: 'mdCode',
  label: 'Code',
  name: 'inlineCode',
  iconType: 'code'
}, {
  id: 'mdLink',
  label: 'Link',
  name: 'link',
  iconType: 'link'
}];
var EuiMarkdownEditorToolbarButton = function EuiMarkdownEditorToolbarButton(_ref) {
  var selectedNode = _ref.selectedNode,
    handleMdButtonClick = _ref.handleMdButtonClick,
    isEditable = _ref.isEditable,
    isDisabled = _ref.isDisabled,
    id = _ref.id,
    nodeId = _ref.nodeId,
    label = _ref.label,
    icon = _ref.icon;
  var isSelected = selectedNode && selectedNode.type === nodeId;
  return (0, _react2.jsx)(_button.EuiButtonIcon, (0, _extends2.default)({
    color: "text"
  }, isSelected ? {
    style: {
      background: 'rgba(0, 0, 0, 0.15)'
    }
  } : null, {
    "data-test-subj": "euiMarkdownEditorToolbarButton".concat(isSelected ? ' pressed' : ''),
    onClick: function onClick() {
      return handleMdButtonClick(id);
    },
    iconType: icon,
    "aria-label": label,
    isDisabled: !isEditable || isDisabled
  }));
};
var EuiMarkdownEditorToolbar = exports.EuiMarkdownEditorToolbar = /*#__PURE__*/(0, _react.forwardRef)(function (_ref2, ref) {
  var className = _ref2.className,
    markdownActions = _ref2.markdownActions,
    viewMode = _ref2.viewMode,
    onClickPreview = _ref2.onClickPreview,
    _uiPlugins = _ref2.uiPlugins,
    selectedNode = _ref2.selectedNode,
    right = _ref2.right;
  var _useContext = (0, _react.useContext)(_markdown_context.EuiMarkdownContext),
    openPluginEditor = _useContext.openPluginEditor,
    readOnly = _useContext.readOnly;
  var classes = (0, _classnames.default)('euiMarkdownEditorToolbar', className);
  var handleMdButtonClick = function handleMdButtonClick(mdButtonId) {
    var actionResult = markdownActions.do(mdButtonId);
    if (actionResult !== true) openPluginEditor(actionResult);
  };
  var isPreviewing = viewMode === _markdown_modes.MODE_VIEWING;
  var isEditable = !isPreviewing && !readOnly;
  var styles = (0, _services.useEuiMemoizedStyles)(_markdown_editor_toolbar.euiMarkdownEditorToolbarStyles);
  var uiPlugins = _uiPlugins.filter(function (uiPlugin) {
    return !!uiPlugin.button;
  });
  return (0, _react2.jsx)("div", {
    ref: ref,
    css: styles.euiMarkdownEditorToolbar,
    className: classes,
    "data-test-subj": "euiMarkdownEditorToolbar"
  }, (0, _react2.jsx)("div", {
    css: styles.euiMarkdownEditorToolbar__buttons,
    className: "euiMarkdownEditorToolbar__buttons"
  }, boldItalicButtons.map(function (item) {
    return (0, _react2.jsx)(_tool_tip.EuiToolTip, {
      key: item.id,
      content: item.label
    }, (0, _react2.jsx)(EuiMarkdownEditorToolbarButton, {
      selectedNode: selectedNode,
      handleMdButtonClick: handleMdButtonClick,
      isEditable: isEditable,
      id: item.id,
      nodeId: item.name,
      label: item.label,
      icon: item.iconType
    }));
  }), (0, _react2.jsx)("span", {
    css: styles.euiMarkdownEditorToolbar__divider,
    className: "euiMarkdownEditorToolbar__divider"
  }), listButtons.map(function (item) {
    return (0, _react2.jsx)(_tool_tip.EuiToolTip, {
      key: item.id,
      content: item.label
    }, (0, _react2.jsx)(EuiMarkdownEditorToolbarButton, {
      selectedNode: selectedNode,
      handleMdButtonClick: handleMdButtonClick,
      isEditable: isEditable,
      id: item.id,
      nodeId: item.name,
      label: item.label,
      icon: item.iconType
    }));
  }), (0, _react2.jsx)("span", {
    css: styles.euiMarkdownEditorToolbar__divider,
    className: "euiMarkdownEditorToolbar__divider"
  }), quoteCodeLinkButtons.map(function (item) {
    return (0, _react2.jsx)(_tool_tip.EuiToolTip, {
      key: item.id,
      content: item.label
    }, (0, _react2.jsx)(EuiMarkdownEditorToolbarButton, {
      selectedNode: selectedNode,
      handleMdButtonClick: handleMdButtonClick,
      isEditable: isEditable,
      id: item.id,
      nodeId: item.name,
      label: item.label,
      icon: item.iconType
    }));
  }), uiPlugins.length > 0 ? (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)("span", {
    css: styles.euiMarkdownEditorToolbar__divider,
    className: "euiMarkdownEditorToolbar__divider"
  }), uiPlugins.map(function (_ref3) {
    var name = _ref3.name,
      button = _ref3.button;
    return (0, _react2.jsx)(_tool_tip.EuiToolTip, {
      key: name,
      content: button.label
    }, (0, _react2.jsx)(EuiMarkdownEditorToolbarButton, {
      selectedNode: selectedNode,
      handleMdButtonClick: handleMdButtonClick,
      isEditable: isEditable,
      isDisabled: button.isDisabled,
      id: name,
      nodeId: name,
      label: button.label,
      icon: button.iconType
    }));
  })) : null), right !== null && right !== void 0 ? right : (0, _react2.jsx)(PreviewEditorSwitch, {
    isPreviewing: isPreviewing,
    onClickPreview: onClickPreview,
    readOnly: readOnly
  }));
});
EuiMarkdownEditorToolbar.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  css: _propTypes.default.any,
  selectedNode: _propTypes.default.oneOfType([_propTypes.default.oneOf([null]), _propTypes.default.any.isRequired]),
  markdownActions: _propTypes.default.any.isRequired,
  viewMode: _propTypes.default.oneOfType([_propTypes.default.any.isRequired, _propTypes.default.any.isRequired]).isRequired,
  onClickPreview: _propTypes.default.func.isRequired,
  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", "addToDashboard", "advancedSettingsApp", "agentApp", "aggregate", "alignBottom", "alignBottomLeft", "alignBottomRight", "alignCenterHorizontal", "alignCenterVertical", "alignLeft", "alignRight", "alignTop", "alignTopLeft", "alignTopRight", "alert", "analyzeEvent", "annotation", "anomalyChart", "chartAnomaly", "anomalySwimLane", "apmApp", "apmTrace", "chartWaterfall", "appSearchApp", "apps", "arrowDown", "chevronSingleDown", "arrowLeft", "chevronSingleLeft", "arrowRight", "chevronSingleRight", "arrowUp", "chevronSingleUp", "arrowStart", "chevronLimitLeft", "arrowEnd", "chevronLimitRight", "article", "asterisk", "at", "archive", "axisX", "axisYLeft", "axisYRight", "auditbeatApp", "backgroundTask", "beaker", "bell", "bellSlash", "beta", "bolt", "boxesHorizontal", "boxesVertical", "branch", "briefcase", "branchUser", "broom", "brush", "bug", "bulb", "bullseye", "calendar", "canvasApp", "casesApp", "changePointDetection", "chartChangePoint", "chartArea", "chartAreaStack", "chartBarHorizontal", "chartBarHorizontalStack", "chartBarVertical", "chartBarVerticalStack", "chartGauge", "chartHeatmap", "chartLine", "chartPie", "chartTagCloud", "chartThreshold", "check", "checkCircle", "checkInCircleFilled", "checkCircleFill", "cheer", "popper", "classificationJob", "clickLeft", "clickRight", "clock", "clockCounter", "clockControl", "cloud", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "code", "codeApp", "color", "paintBucket", "commandLine", "comment", "compare", "compute", "processor", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "contrast", "contrastHigh", "contrastFill", "controls", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "crossProjectSearch", "createAdvancedJob", "createGenericJob", "createGeoJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crossInCircle", "crossCircle", "crosshair", "crosshairs", "currency", "money", "cut", "scissors", "dashboardApp", "dashedCircle", "dataVisualizer", "database", "desktop", "display", "devToolsApp", "diff", "discoverApp", "distributeHorizontal", "distributeVertical", "download", "drag", "dragHorizontal", "dragVertical", "discuss", "document", "documentEdit", "documentation", "documents", "dot", "dotInCircle", "doubleArrowLeft", "chevronDoubleLeft", "doubleArrowRight", "chevronDoubleRight", "ellipsis", "editorAlignCenter", "textAlignCenter", "editorAlignLeft", "textAlignLeft", "editorAlignRight", "textAlignRight", "editorBold", "textBold", "editorChecklist", "listCheck", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "textHeading", "editorItalic", "textItalic", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignLeft", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "listNumber", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "redo", "editorStrike", "textStrike", "editorTable", "table", "editorUnderline", "textUnderline", "editorUndo", "undo", "editorUnorderedList", "listBullet", "email", "mail", "empty", "emsApp", "endpoint", "eql", "query", "eraser", "error", "errorFilled", "errorFill", "esqlVis", "exit", "logOut", "expand", "maximize", "expandMini", "export", "exportAction", "upload", "external", "eye", "eyeClosed", "eyeSlash", "faceHappy", "faceNeutral", "faceSad", "fieldStatistics", "tableInfo", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flask", "flag", "fleetApp", "fold", "folder", "folderClosed", "folderClose", "folderCheck", "folderExclamation", "folderOpen", "folderOpened", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "grabOmnidirectional", "gradient", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "hourglass", "if", "info", "image", "importAction", "index", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "mapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "indexTemporary", "tableTime", "infinity", "inputOutput", "inspect", "invert", "ip", "key", "keyboard", "kqlField", "queryField", "kqlFunction", "kqlOperand", "queryOperand", "kqlSelector", "querySelector", "kqlValue", "queryValue", "kubernetesNode", "kubernetesPod", "launch", "rocket", "layers", "lensApp", "lettering", "text", "lineBreak", "lineBreakSlash", "lineDash", "lineDashed", "lineDot", "lineDotted", "lineSolid", "link", "linkSlash", "list", "listAdd", "lock", "lockOpen", "logPatternAnalysis", "pattern", "logRateAnalysis", "logoAWS", "logoAWSMono", "logoAerospike", "logoApache", "logoAppSearch", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticStack", "logoElasticsearch", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoVulnerabilityManagement", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logsApp", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "queue", "machineLearningApp", "magnet", "magnify", "magnifyExclamation", "magnifyMinus", "magnifyPlus", "magnifyWithExclamation", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "map", "mapMarker", "waypoint", "megaphone", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusCircle", "minusInCircle", "minusInCircleFilled", "minusInSquare", "minusSquare", "mobile", "monitoringApp", "moon", "move", "namespace", "nested", "newChat", "node", "vectorTriangle", "notebookApp", "number", "offline", "wifiSlash", "online", "wifi", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "palette", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFill", "pinFilled", "pipeBreaks", "pipelineApp", "pipeNoBreaks", "pivot", "play", "playFilled", "plugs", "plus", "plusCircle", "plusInCircle", "plusInCircleFilled", "plusInSquare", "plusSquare", "popout", "presentation", "productRobot", "productAgent", "productCloudInfra", "productDashboard", "productDiscover", "productML", "productStreamsClassic", "productStreamsWired", "push", "send", "question", "quote", "radar", "readOnly", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "return", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "section", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "server", "sessionViewer", "shard", "share", "singleMetricViewer", "snowflake", "sortAscending", "sortDescending", "sortDown", "sortLeft", "sortRight", "sortUp", "sortable", "spaces", "spacesApp", "sparkles", "sqlApp", "star", "starEmpty", "starEmptySpace", "starFill", "starFilled", "starFillSpace", "starFilledSpace", "starMinusEmpty", "starMinusFill", "starMinusFilled", "starPlusEmpty", "starPlusFill", "starPlusFilled", "stats", "stop", "stopFill", "stopFilled", "stopSlash", "storage", "streamsClassic", "streamsWired", "string", "submodule", "sun", "swatchInput", "symlink", "tableDensityCompact", "tableDensityHigh", "tableDensityExpanded", "tableDensityLow", "tableDensityNormal", "tableOfContents", "tag", "tear", "temperature", "thermometer", "thumbDown", "thumbUp", "timeline", "timelineWithArrow", "timelionApp", "timeRefresh", "refreshTime", "timeslider", "training", "transitionBottomIn", "transitionBottomOut", "transitionLeftIn", "transitionLeftOut", "transitionTopIn", "transitionTopOut", "trash", "unfold", "unlink", "upgradeAssistantApp", "uptimeApp", "user", "userAvatar", "users", "usersRolesApp", "unarchive", "vector", "vectorSquare", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "chartMetric", "visPie", "visTable", "visTagCloud", "visText", "visTimelion", "visVega", "visVisualBuilder", "visualizeApp", "vulnerabilityManagementApp", "warning", "warningFilled", "warningFill", "watchesApp", "web", "wordWrap", "wordWrapDisabled", "workflowsApp", "workflow", "workplaceSearchApp", "wrench", "tokenAlias", "tokenAnnotation", "tokenArray", "tokenBinary", "tokenBoolean", "tokenClass", "tokenCompletionSuggester", "tokenConstant", "tokenDate", "tokenDimension", "tokenElement", "tokenEnum", "tokenEnumMember", "tokenEvent", "tokenException", "tokenField", "tokenFile", "tokenFlattened", "tokenFunction", "tokenGeo", "tokenHistogram", "tokenInterface", "tokenIP", "tokenJoin", "tokenKey", "tokenKeyword", "tokenMethod", "tokenMetricCounter", "tokenMetricGauge", "tokenModule", "tokenNamespace", "tokenNested", "tokenNull", "tokenNumber", "tokenObject", "tokenOperator", "tokenPackage", "tokenParameter", "tokenPercolator", "tokenProperty", "tokenRange", "tokenRankFeature", "tokenRankFeatures", "tokenRepo", "tokenSearchType", "tokenSemanticText", "tokenShape", "tokenString", "tokenStruct", "tokenSymbol", "tokenTag", "tokenText", "tokenTokenCount", "tokenVariable", "tokenVectorDense", "tokenDenseVector", "tokenVectorSparse"]).isRequired, _propTypes.default.string.isRequired, _propTypes.default.elementType.isRequired]).isRequired,
      isDisabled: _propTypes.default.bool
    }),
    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,
  right: _propTypes.default.node
};
var PreviewEditorSwitch = function PreviewEditorSwitch(_ref4) {
  var isPreviewing = _ref4.isPreviewing,
    onClickPreview = _ref4.onClickPreview,
    readOnly = _ref4.readOnly;
  return (0, _react2.jsx)(_button.EuiButtonEmpty, {
    iconType: isPreviewing ? 'code' : 'eye',
    color: "text",
    size: "s",
    onClick: onClickPreview,
    isDisabled: readOnly,
    "data-test-subj": isPreviewing ? 'markdown_editor_preview_button' : 'markdown_editor_edit_button'
  }, isPreviewing ? (0, _react2.jsx)(_i18n.EuiI18n, {
    token: "euiMarkdownEditorToolbar.editor",
    default: "Editor"
  }) : (0, _react2.jsx)(_i18n.EuiI18n, {
    token: "euiMarkdownEditorToolbar.previewMarkdown",
    default: "Preview"
  }));
};
EuiMarkdownEditorToolbar.displayName = 'EuiMarkdownEditorToolbar';