# all files / keystone/lib/schemaPlugins/ sortable.js

3.45% Statements 1/29
0% Branches 0/18
0% Functions 0/7
3.45% Lines 1/29

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    651×

     module.exports = function sortable () {

    	var list = this;

    	this.add({
    		sortOrder: { type: Number, index: true, hidden: true },
    	});

    	this.schema.pre('save', function (next) {

    		if (typeof this.sortOrder === 'number') {
    			return next();
    		}

    		var item = this;

    		var addLast = function (done) {
    			list.model.findOne().sort('-sortOrder').exec(function (err, max) { // eslint-disable-line no-unused-vars, handle-callback-err
    				item.sortOrder = (max && max.sortOrder) ? max.sortOrder + 1 : 1;
    				done();
    			});
    		};

    		if (list.get('sortable') === 'unshift') {
    			list.model.where('sortOrder')
    				.setOptions({ multi: true })
    				.update(
    					{ $inc: { sortOrder: 1 } },
    					function (err) {
    						if (err) {
    							console.log('err', err);
    							return addLast(next);
    						}
    						item.sortOrder = 1;
    						next();
    					}
    				);
    		} else {
    			addLast(next);
    		}
    	});

    	this.schema.statics.reorderItems = function reorderItems (id, prevOrder, newOrder, cb) {

    		prevOrder = parseFloat(prevOrder);
    		newOrder = parseFloat(newOrder);

    		var whichWay = (newOrder > prevOrder) ? -1 : 1;
    		var gte = (newOrder > prevOrder) ? prevOrder + 1 : newOrder;
    		var lte = (newOrder > prevOrder) ? newOrder : prevOrder - 1;
    		return list.model
    			.where('sortOrder')
    			.gte(gte)
    			.lte(lte)
    			.setOptions({ multi: true })
    			.update({ $inc: { sortOrder: whichWay } }, function (err) {
    				if (err) {
    					console.log('err', err);
    				}
    				list.model.findOneAndUpdate({ _id: id }, { sortOrder: newOrder }).exec(cb);
    			});
    	};

    };