@vtex/styleguide
Version:
> VTEX Styleguide React components ([Docs](https://vtex.github.io/styleguide))
109 lines (90 loc) • 2.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SortOrder = undefined;
exports.default = useTableSort;
var _react = require("react");
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); }
var SortOrder = exports.SortOrder = undefined;
(function (SortOrder) {
SortOrder["ASC"] = "ASC";
SortOrder["DSC"] = "DSC";
})(SortOrder || (exports.SortOrder = SortOrder = {}));
var ActionType;
(function (ActionType) {
ActionType["SortASC"] = "SORT_ASC";
ActionType["SortDSC"] = "SORT_DSC";
ActionType["Clear"] = "CLEAR";
})(ActionType || (ActionType = {}));
var clearState = {
by: null,
order: null
};
function useTableSort(initialState) {
var _useReducer = (0, _react.useReducer)(reducer, _extends({}, clearState, {}, initialState)),
sorted = _useReducer[0],
dispatch = _useReducer[1];
var sortASC = function sortASC(id) {
return dispatch({
type: ActionType.SortASC,
payload: {
id: id
}
});
};
var sortDSC = function sortDSC(id) {
return dispatch({
type: ActionType.SortDSC,
payload: {
id: id
}
});
};
var clear = function clear() {
return dispatch({
type: ActionType.Clear
});
};
var sort = function sort(id) {
var by = sorted.by,
order = sorted.order;
if (!by || by !== id) {
sortASC(id);
} else {
var sortFn = order === SortOrder.ASC ? sortDSC : sortASC;
sortFn(id);
}
};
return {
sorted: sorted,
clear: clear,
sort: sort
};
}
function reducer(state, action) {
switch (action.type) {
case ActionType.SortASC:
{
var id = action.payload.id;
return {
by: id,
order: SortOrder.ASC
};
}
case ActionType.SortDSC:
{
var _id = action.payload.id;
return {
by: _id,
order: SortOrder.DSC
};
}
case ActionType.Clear:
{
return clearState;
}
default:
return state;
}
}