date.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* eslint-disable import/prefer-default-export */
  2. import moment from 'moment';
  3. import { isEmpty } from '../../../helpers/mixed';
  4. import { DO_NOT_SWAP, FIRST_BEFORE_SECOND, FIRST_AFTER_SECOND } from '../sortService';
  5. /**
  6. * Date sorting compare function factory. Method get as parameters `sortOrder` and `columnMeta` and return compare function.
  7. *
  8. * @param {String} sortOrder Sort order (`asc` for ascending, `desc` for descending).
  9. * @param {Object} columnMeta Column meta object.
  10. * @param {Object} columnPluginSettings Plugin settings for the column.
  11. * @returns {Function} The compare function.
  12. */
  13. export function compareFunctionFactory(sortOrder, columnMeta, columnPluginSettings) {
  14. return function(value, nextValue) {
  15. const { sortEmptyCells } = columnPluginSettings;
  16. if (value === nextValue) {
  17. return DO_NOT_SWAP;
  18. }
  19. if (isEmpty(value)) {
  20. if (isEmpty(nextValue)) {
  21. return DO_NOT_SWAP;
  22. }
  23. // Just fist value is empty and `sortEmptyCells` option was set
  24. if (sortEmptyCells) {
  25. return sortOrder === 'asc' ? FIRST_BEFORE_SECOND : FIRST_AFTER_SECOND;
  26. }
  27. return FIRST_AFTER_SECOND;
  28. }
  29. if (isEmpty(nextValue)) {
  30. // Just second value is empty and `sortEmptyCells` option was set
  31. if (sortEmptyCells) {
  32. return sortOrder === 'asc' ? FIRST_AFTER_SECOND : FIRST_BEFORE_SECOND;
  33. }
  34. return FIRST_BEFORE_SECOND;
  35. }
  36. const dateFormat = columnMeta.dateFormat;
  37. const firstDate = moment(value, dateFormat);
  38. const nextDate = moment(nextValue, dateFormat);
  39. if (!firstDate.isValid()) {
  40. return FIRST_AFTER_SECOND;
  41. }
  42. if (!nextDate.isValid()) {
  43. return FIRST_BEFORE_SECOND;
  44. }
  45. if (nextDate.isAfter(firstDate)) {
  46. return sortOrder === 'asc' ? FIRST_BEFORE_SECOND : FIRST_AFTER_SECOND;
  47. }
  48. if (nextDate.isBefore(firstDate)) {
  49. return sortOrder === 'asc' ? FIRST_AFTER_SECOND : FIRST_BEFORE_SECOND;
  50. }
  51. return DO_NOT_SWAP;
  52. };
  53. }
  54. export const COLUMN_DATA_TYPE = 'date';