"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiDataGridColumnSortingDraggable", {
  enumerable: true,
  get: function get() {
    return _column_sorting_draggable.EuiDataGridColumnSortingDraggable;
  }
});
exports.OuiDataGridColumnSortingDraggable = exports.defaultSortDescLabel = exports.defaultSortAscLabel = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _i18n = require("../i18n");
var _drag_and_drop = require("../drag_and_drop");
var _accessibility = require("../accessibility");
var _flex = require("../flex");
var _button = require("../button");
var _icon = require("../icon");
var _text = require("../text");
var _data_grid_schema = require("./data_grid_schema");
var _token = require("../token");
var _column_sorting_draggable = require("../../eui_components/datagrid/column_sorting_draggable");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
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 _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) { o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) { if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; } /*
 * 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.
 */
var defaultSortAscLabel = /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
  token: "ouiColumnSortingDraggable.defaultSortAsc",
  default: "A-Z"
});
exports.defaultSortAscLabel = defaultSortAscLabel;
var defaultSortDescLabel = /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
  token: "ouiColumnSortingDraggable.defaultSortDesc",
  default: "Z-A"
});
exports.defaultSortDescLabel = defaultSortDescLabel;
var OuiDataGridColumnSortingDraggable = function OuiDataGridColumnSortingDraggable(_ref) {
  var id = _ref.id,
    display = _ref.display,
    direction = _ref.direction,
    index = _ref.index,
    sorting = _ref.sorting,
    schema = _ref.schema,
    schemaDetectors = _ref.schemaDetectors,
    rest = _objectWithoutProperties(_ref, ["id", "display", "direction", "index", "sorting", "schema", "schemaDetectors"]);
  var schemaDetails = schema.hasOwnProperty(id) && schema[id].columnType != null ? (0, _data_grid_schema.getDetailsForSchema)(schemaDetectors, schema[id].columnType) : null;
  var textSortAsc = schemaDetails != null ? schemaDetails.sortTextAsc : defaultSortAscLabel;
  var textSortDesc = schemaDetails != null ? schemaDetails.sortTextDesc : defaultSortDescLabel;
  var toggleOptions = [{
    id: "".concat(id, "Asc"),
    value: 'asc',
    label: textSortAsc,
    'data-test-subj': "ouiDataGridColumnSorting-sortColumn-".concat(id, "-asc")
  }, {
    id: "".concat(id, "Desc"),
    value: 'desc',
    label: textSortDesc,
    'data-test-subj': "ouiDataGridColumnSorting-sortColumn-".concat(id, "-desc")
  }];
  return /*#__PURE__*/_react.default.createElement(_drag_and_drop.OuiDraggable, _extends({
    draggableId: id,
    index: index
  }, rest), function (provided, state) {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: "ouiDataGridColumnSorting__item ".concat(state.isDragging && 'ouiDataGridColumnSorting__item-isDragging')
    }, /*#__PURE__*/_react.default.createElement(_accessibility.OuiScreenReaderOnly, null, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiColumnSortingDraggable.activeSortLabel",
      default: "is sorting this data grid"
    }, function (activeSortLabel) {
      return /*#__PURE__*/_react.default.createElement("span", null, display, " ", activeSortLabel);
    }))), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexGroup, {
      gutterSize: "xs",
      alignItems: "center",
      responsive: false,
      "data-test-subj": "ouiDataGridColumnSorting-sortColumn-".concat(id)
    }, /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiColumnSortingDraggable.removeSortLabel",
      default: "Remove from data grid sort:"
    }, function (removeSortLabel) {
      return /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, {
        color: "text",
        className: "ouiDataGridColumnSorting__button",
        "aria-label": "".concat(removeSortLabel, " ").concat(id),
        iconType: "cross",
        onClick: function onClick() {
          var nextColumns = _toConsumableArray(sorting.columns);
          var columnIndex = nextColumns.map(function (_ref2) {
            var id = _ref2.id;
            return id;
          }).indexOf(id);
          nextColumns.splice(columnIndex, 1);
          sorting.onSort(nextColumns);
        }
      });
    })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_token.OuiToken, {
      color: schemaDetails != null ? schemaDetails.color : undefined,
      iconType: schemaDetails != null ? schemaDetails.icon : 'tokenString'
    })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
      "aria-hidden": true
    }, /*#__PURE__*/_react.default.createElement(_text.OuiText, {
      size: "xs"
    }, /*#__PURE__*/_react.default.createElement("p", null, display))), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, {
      className: "ouiDataGridColumnSorting__orderButtons"
    }, /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiColumnSortingDraggable.toggleLegend",
      default: "Select sorting method for field: "
    }, function (toggleLegend) {
      return /*#__PURE__*/_react.default.createElement(_button.OuiButtonGroup, {
        legend: "".concat(toggleLegend, " ").concat(id),
        name: id,
        isFullWidth: true,
        options: toggleOptions,
        "data-test-subj": "-".concat(direction),
        buttonSize: "compressed",
        className: "ouiDataGridColumnSorting__order",
        idSelected: direction === 'asc' ? "".concat(id, "Asc") : "".concat(id, "Desc"),
        onChange: function onChange(_, direction) {
          var nextColumns = _toConsumableArray(sorting.columns);
          var columnIndex = nextColumns.map(function (_ref3) {
            var id = _ref3.id;
            return id;
          }).indexOf(id);
          nextColumns.splice(columnIndex, 1, {
            id: id,
            direction: direction
          });
          sorting.onSort(nextColumns);
        }
      });
    })), /*#__PURE__*/_react.default.createElement(_flex.OuiFlexItem, _extends({
      grow: false
    }, provided.dragHandleProps), /*#__PURE__*/_react.default.createElement("div", provided.dragHandleProps, /*#__PURE__*/_react.default.createElement(_icon.OuiIcon, {
      type: "grab",
      color: "subdued"
    })))));
  });
};

/* OUI -> EUI Aliases: Build-Time */
exports.OuiDataGridColumnSortingDraggable = OuiDataGridColumnSortingDraggable;
OuiDataGridColumnSortingDraggable.propTypes = {
  id: _propTypes.default.string.isRequired,
  direction: _propTypes.default.string.isRequired,
  index: _propTypes.default.number.isRequired,
  sorting: _propTypes.default.shape({
    /**
       * A function that receives updated column sort details in response to user interactions in the toolbar controls
       */
    onSort: _propTypes.default.func.isRequired,
    /**
       * An array of the column ids currently being sorted and their sort direction. The array order determines the sort order. `{ id: 'A'; direction: 'asc' }`
       */
    columns: _propTypes.default.arrayOf(_propTypes.default.shape({
      id: _propTypes.default.string.isRequired,
      direction: _propTypes.default.oneOf(["asc", "desc"]).isRequired
    }).isRequired).isRequired
  }).isRequired,
  schema: _propTypes.default.shape({}).isRequired,
  schemaDetectors: _propTypes.default.arrayOf(_propTypes.default.shape({
    /**
       * The name of this data type, matches #OuiDataGridColumn / schema `schema`
       */
    type: _propTypes.default.string.isRequired,
    /**
       * The function given the text value of a cell and returns a score of [0...1] of how well the value matches this data type
       */
    detector: _propTypes.default.func.isRequired,
    /**
       * A custom comparator function when performing in-memory sorting on this data type, takes `(a: string, b: string, direction: 'asc' | 'desc) => -1 | 0 | 1`
       */
    comparator: _propTypes.default.func,
    /**
       * The icon used to visually represent this data type. Accepts any `OuiIcon IconType`.
       */
    icon: _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,
    /**
       * The color associated with this data type; it's used to color the icon token
       */
    color: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.oneOf(["ouiColorVis0", "ouiColorVis1", "ouiColorVis2", "ouiColorVis3", "ouiColorVis4", "ouiColorVis5", "ouiColorVis6", "ouiColorVis7", "ouiColorVis8", "ouiColorVis9", "gray"]).isRequired, _propTypes.default.string.isRequired]).isRequired, _propTypes.default.string.isRequired]),
    /**
       * Text for how to represent an ascending sort of this data type, e.g. 'A -> Z'
       */
    sortTextAsc: _propTypes.default.node.isRequired,
    /**
       * Text for how to represent a descending sort of this data type, e.g. 'Z -> A'
       */
    sortTextDesc: _propTypes.default.node.isRequired,
    /**
       * Whether this column is sortable (defaults to true)
       */
    isSortable: _propTypes.default.bool,
    /**
       *  This property controls the capitalization of text
       */
    textTransform: _propTypes.default.oneOf(["uppercase", "lowercase", "capitalize"]),
    /**
       * Default sort direction of the column
       */
    defaultSortDirection: _propTypes.default.oneOf(["asc", "desc"])
  }).isRequired).isRequired,
  /**
     * Value to be shown in column sorting popover.
     */
  display: _propTypes.default.string.isRequired
};
/* OUI -> EUI Aliases: Build-Time */