item-selection
Version:
Manage item multi-selections.
132 lines (102 loc) • 2.82 kB
JavaScript
function range(start, end) {
if (start > end) {
var _ref = [end, start];
start = _ref[0];
end = _ref[1];
}
var list = [];
for (var i = start; i <= end; i++) {
list.push(i);
}
return list;
}
var includes = function includes(arr, item) {
return arr.indexOf(item) !== -1;
};
var cmp = function cmp(a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
};
var ItemSelection =
/*#__PURE__*/
function () {
function ItemSelection(items, selection, lastIndex) {
if (selection === void 0) {
selection = [];
}
if (lastIndex === void 0) {
lastIndex = null;
}
if (!Array.isArray(items)) {
throw new TypeError('Expected an array');
}
this.items = items;
this.selection = selection;
this.lastIndex = lastIndex;
}
var _proto = ItemSelection.prototype;
_proto.getIndices = function getIndices() {
return this.selection.slice().sort(cmp);
};
_proto.get = function get() {
var _this = this;
return this.getIndices().map(function (index) {
return _this.items[index];
});
};
_proto.set = function set(selection, lastIndex) {
return new ItemSelection(this.items, selection, lastIndex);
};
_proto.isSelectedIndex = function isSelectedIndex(index) {
return includes(this.selection, index);
};
_proto.isSelected = function isSelected(item) {
return includes(this.get(), item);
};
_proto.clear = function clear() {
return this.set([], null);
};
_proto.add = function add(index) {
return this.set([].concat(this.selection, [index]), this.lastIndex);
};
_proto.remove = function remove(index) {
return this.set(this.selection.filter(function (idx) {
return idx !== index;
}), null);
};
_proto.select = function select(index) {
return this.set([index], index);
};
_proto.deselect = function deselect(index) {
return this.remove(index);
};
_proto.selectRange = function selectRange(index, end) {
if (end === void 0) {
end = null;
}
if (end !== null) {
return this.set(range(index, end), null);
}
if (typeof this.lastIndex !== 'number') {
return this.select(index);
}
return this.set(range(this.lastIndex, index), this.lastIndex);
};
_proto.selectToggle = function selectToggle(index) {
if (this.isSelectedIndex(index)) {
return this.remove(index);
}
return this.set([].concat(this.selection, [index]), index);
};
_proto.selectAll = function selectAll() {
return this.set(this.items.map(function (item, index) {
return index;
}), null);
};
return ItemSelection;
}();
export default function itemSelection(items, selection, lastIndex) {
return new ItemSelection(items, selection, lastIndex);
}
export { ItemSelection };