"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(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /*
                                                                                                                                                                                                                                                                                                                     * 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", "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", "chatLeft", "chatRight", "check", "checkInCircleEmpty", "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", "crossInCircleEmpty", "crossInCircleFilled", "currency", "cut", "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", "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", "integrationGeneral", "integrationObservability", "integrationSearch", "integrationSecurity", "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", "power", "push", "questionInCircle", "quote", "radius", "recentlyViewedApp", "redeploy", "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", "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"]).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 */