You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Lidarr/src/UI/Mixins/AsSortedCollection.js

131 lines
3.3 KiB

9 years ago
var _ = require('underscore');
var Config = require('../Config');
module.exports = function() {
9 years ago
var originalSetSorting = this.prototype.setSorting;
this.prototype.setSorting = function(sortKey, order, options) {
9 years ago
var sortMapping = this._getSortMapping(sortKey);
options = _.defaults({ sortValue : sortMapping.sortValue }, options || {});
9 years ago
return originalSetSorting.call(this, sortMapping.sortKey, order, options);
};
this.prototype._getSortMappings = function() {
9 years ago
var result = {};
if (this.sortMappings) {
_.each(this.sortMappings, function(values, key) {
9 years ago
var item = {
name : key,
sortKey : values.sortKey || key,
sortValue : values.sortValue
};
result[key] = item;
result[item.sortKey] = item;
});
}
9 years ago
return result;
};
this.prototype._getSortMapping = function(key) {
9 years ago
var sortMappings = this._getSortMappings();
9 years ago
return sortMappings[key] || {
name : key,
sortKey : key
};
9 years ago
};
this.prototype._getSecondarySorting = function() {
9 years ago
var sortKey = this.state.secondarySortKey;
var sortOrder = this.state.secondarySortOrder || -1;
if (!sortKey || sortKey === this.state.sortKey) {
9 years ago
return null;
}
9 years ago
var sortMapping = this._getSortMapping(sortKey);
if (!sortMapping.sortValue) {
sortMapping.sortValue = function(model, attr) {
9 years ago
return model.get(attr);
};
9 years ago
}
9 years ago
return {
key : sortKey,
order : sortOrder,
sortValue : sortMapping.sortValue
};
};
this.prototype._makeComparator = function(sortKey, order, sortValue) {
9 years ago
var state = this.state;
var secondarySorting = this._getSecondarySorting();
9 years ago
sortKey = sortKey || state.sortKey;
order = order || state.order;
if (!sortKey || !order) {
9 years ago
return;
}
if (!sortValue) {
sortValue = function(model, attr) {
9 years ago
return model.get(attr);
};
9 years ago
}
return function(left, right) {
9 years ago
var l = sortValue(left, sortKey, order);
var r = sortValue(right, sortKey, order);
var t;
if (order === 1) {
9 years ago
t = l;
l = r;
r = t;
}
if (l === r) {
if (secondarySorting) {
9 years ago
var ls = secondarySorting.sortValue(left, secondarySorting.key, order);
var rs = secondarySorting.sortValue(right, secondarySorting.key, order);
var ts;
if (secondarySorting.order === 1) {
9 years ago
ts = ls;
ls = rs;
rs = ts;
}
if (ls === rs) {
return 0;
}
if (ls < rs) {
return -1;
}
return 1;
9 years ago
}
9 years ago
return 0;
}
else if (l < r) {
9 years ago
return -1;
}
9 years ago
return 1;
};
9 years ago
};
9 years ago
return this;
};