forked from angular-ui/ui-sortable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsortable.js
475 lines (411 loc) · 18.2 KB
/
sortable.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{
// the default for jquery-ui sortable is "> *", we need to restrict this to
// ng-repeat items
// if the user uses
items: '> [ng-repeat],> [data-ng-repeat],> [x-ng-repeat]'
})
.directive('uiSortable', [
'uiSortableConfig', '$timeout', '$log',
function(uiSortableConfig, $timeout, $log) {
return {
require: '?ngModel',
scope: {
ngModel: '=',
uiSortable: '='
},
link: function(scope, element, attrs, ngModel) {
var savedNodes;
function combineCallbacks(first, second){
var firstIsFunc = first && (typeof first === 'function');
var secondIsFunc = second && (typeof second === 'function');
if(firstIsFunc && secondIsFunc) {
return function() {
first.apply(this, arguments);
second.apply(this, arguments);
};
} else if (secondIsFunc) {
return second;
}
return first;
}
function getSortableWidgetInstance(element) {
// this is a fix to support jquery-ui prior to v1.11.x
// otherwise we should be using `element.sortable('instance')`
var data = element.data('ui-sortable');
if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') {
return data;
}
return null;
}
function patchSortableOption(key, value) {
if (callbacks[key]) {
if( key === 'stop' ){
// call apply after stop
value = combineCallbacks(
value, function() { scope.$apply(); });
value = combineCallbacks(value, afterStop);
}
// wrap the callback
value = combineCallbacks(callbacks[key], value);
} else if (wrappers[key]) {
value = wrappers[key](value);
}
if (key === 'items' && !value) {
value = uiSortableConfig.items;
}
return value;
}
function patchUISortableOptions(newVal, oldVal, sortableWidgetInstance) {
function addDummyOptionKey(value, key) {
if (!(key in opts)) {
// add the key in the opts object so that
// the patch function detects and handles it
opts[key] = null;
}
}
// for this directive to work we have to attach some callbacks
angular.forEach(callbacks, addDummyOptionKey);
// only initialize it in case we have to
// update some options of the sortable
var optsDiff = null;
if (oldVal) {
// reset deleted options to default
var defaultOptions;
angular.forEach(oldVal, function(oldValue, key) {
if (!newVal || !(key in newVal)) {
if (key in directiveOpts) {
opts[key] = 'auto';
return;
}
if (!defaultOptions) {
defaultOptions = angular.element.ui.sortable().options;
}
var defaultValue = defaultOptions[key];
defaultValue = patchSortableOption(key, defaultValue);
if (!optsDiff) {
optsDiff = {};
}
optsDiff[key] = defaultValue;
opts[key] = defaultValue;
}
});
}
// update changed options
angular.forEach(newVal, function(value, key) {
// if it's a custom option of the directive,
// handle it approprietly
if (key in directiveOpts) {
if (key === 'ui-floating' && (value === false || value === true) && sortableWidgetInstance) {
sortableWidgetInstance.floating = value;
}
opts[key] = value;
return;
}
value = patchSortableOption(key, value);
if (!optsDiff) {
optsDiff = {};
}
optsDiff[key] = value;
opts[key] = value;
});
return optsDiff;
}
function getPlaceholderElement (element) {
var placeholder = element.sortable('option','placeholder');
// placeholder.element will be a function if the placeholder, has
// been created (placeholder will be an object). If it hasn't
// been created, either placeholder will be false if no
// placeholder class was given or placeholder.element will be
// undefined if a class was given (placeholder will be a string)
if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
var result = placeholder.element();
// workaround for jquery ui 1.9.x,
// not returning jquery collection
result = angular.element(result);
return result;
}
return null;
}
function getPlaceholderExcludesludes (element, placeholder) {
// exact match with the placeholder's class attribute to handle
// the case that multiple connected sortables exist and
// the placehoilder option equals the class of sortable items
var excludes = element.find('[class="' + placeholder.attr('class') + '"]:not([ng-repeat], [data-ng-repeat])');
return excludes;
}
function hasSortingHelper (element, ui) {
var helperOption = element.sortable('option','helper');
return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed());
}
function getSortingHelper (element, ui, savedNodes) {
var result = null;
if (hasSortingHelper(element, ui) &&
element.sortable( 'option', 'appendTo' ) === 'parent') {
// The .ui-sortable-helper element (that's the default class name)
// is placed last.
result = savedNodes.last();
}
return result;
}
// thanks jquery-ui
function isFloating (item) {
return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display'));
}
function getElementScope(elementScopes, element) {
var result = null;
for (var i = 0; i < elementScopes.length; i++) {
var x = elementScopes[i];
if (x.element[0] === element[0]) {
result = x.scope;
break;
}
}
return result;
}
function afterStop(e, ui) {
ui.item.sortable._destroy();
}
// return the index of ui.item among the items
// we can't just do ui.item.index() because there it might have siblings
// which are not items
function getItemIndex(ui) {
return ui.item.parent().find(uiSortableConfig.items)
.index(ui.item);
}
var opts = {};
// directive specific options
var directiveOpts = {
'ui-floating': undefined
};
var callbacks = {
receive: null,
remove:null,
start:null,
stop:null,
update:null
};
var wrappers = {
helper: null
};
angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable);
if (!angular.element.fn || !angular.element.fn.jquery) {
$log.error('ui.sortable: jQuery should be included before AngularJS!');
return;
}
if (ngModel) {
// When we add or remove elements, we need the sortable to 'refresh'
// so it can find the new/removed elements.
scope.$watchCollection('ngModel', function() {
// Timeout to let ng-repeat modify the DOM
$timeout(function() {
// ensure that the jquery-ui-sortable widget instance
// is still bound to the directive's element
if (!!getSortableWidgetInstance(element)) {
element.sortable('refresh');
}
}, 0, false);
});
callbacks.start = function(e, ui) {
if (opts['ui-floating'] === 'auto') {
// since the drag has started, the element will be
// absolutely positioned, so we check its siblings
var siblings = ui.item.siblings();
var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target));
sortableWidgetInstance.floating = isFloating(siblings);
}
// Save the starting position of dragged item
var index = getItemIndex(ui);
ui.item.sortable = {
model: ngModel.$modelValue[index],
index: index,
source: ui.item.parent(),
sourceModel: ngModel.$modelValue,
cancel: function () {
ui.item.sortable._isCanceled = true;
},
isCanceled: function () {
return ui.item.sortable._isCanceled;
},
isCustomHelperUsed: function () {
return !!ui.item.sortable._isCustomHelperUsed;
},
_isCanceled: false,
_isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed,
_destroy: function () {
angular.forEach(ui.item.sortable, function(value, key) {
ui.item.sortable[key] = undefined;
});
}
};
};
callbacks.activate = function(e, ui) {
// We need to make a copy of the current element's contents so
// we can restore it after sortable has messed it up.
// This is inside activate (instead of start) in order to save
// both lists when dragging between connected lists.
savedNodes = element.contents();
// If this list has a placeholder (the connected lists won't),
// don't inlcude it in saved nodes.
var placeholder = getPlaceholderElement(element);
if (placeholder && placeholder.length) {
var excludes = getPlaceholderExcludesludes(element, placeholder);
savedNodes = savedNodes.not(excludes);
}
// save the directive's scope so that it is accessible from ui.item.sortable
var connectedSortables = ui.item.sortable._connectedSortables || [];
connectedSortables.push({
element: element,
scope: scope
});
ui.item.sortable._connectedSortables = connectedSortables;
};
callbacks.update = function(e, ui) {
// Save current drop position but only if this is not a second
// update that happens when moving between lists because then
// the value will be overwritten with the old value
if(!ui.item.sortable.received) {
ui.item.sortable.dropindex = getItemIndex(ui);
var droptarget = ui.item.parent();
ui.item.sortable.droptarget = droptarget;
var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget);
ui.item.sortable.droptargetModel = droptargetScope.ngModel;
// Cancel the sort (let ng-repeat do the sort for us)
// Don't cancel if this is the received list because it has
// already been canceled in the other list, and trying to cancel
// here will mess up the DOM.
element.sortable('cancel');
}
// Put the nodes back exactly the way they started (this is very
// important because ng-repeat uses comment elements to delineate
// the start and stop of repeat sections and sortable doesn't
// respect their order (even if we cancel, the order of the
// comments are still messed up).
var sortingHelper = !ui.item.sortable.received && getSortingHelper(element, ui, savedNodes);
if (sortingHelper && sortingHelper.length) {
// Restore all the savedNodes except from the sorting helper element.
// That way it will be garbage collected.
savedNodes = savedNodes.not(sortingHelper);
}
savedNodes.appendTo(element);
// If this is the target connected list then
// it's safe to clear the restored nodes since:
// update is currently running and
// stop is not called for the target list.
if(ui.item.sortable.received) {
savedNodes = null;
}
// If received is true (an item was dropped in from another list)
// then we add the new item to this list otherwise wait until the
// stop event where we will know if it was a sort or item was
// moved here from another list
if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
ui.item.sortable.moved);
});
}
};
callbacks.stop = function(e, ui) {
// If the received flag hasn't be set on the item, this is a
// normal sort, if dropindex is set, the item was moved, so move
// the items in the list.
if(!ui.item.sortable.received &&
('dropindex' in ui.item.sortable) &&
!ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ngModel.$modelValue.splice(
ui.item.sortable.dropindex, 0,
ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
});
} else {
// if the item was not moved, then restore the elements
// so that the ngRepeat's comment are correct.
if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) &&
!angular.equals(element.contents(), savedNodes)) {
var sortingHelper = getSortingHelper(element, ui, savedNodes);
if (sortingHelper && sortingHelper.length) {
// Restore all the savedNodes except from the sorting helper element.
// That way it will be garbage collected.
savedNodes = savedNodes.not(sortingHelper);
}
savedNodes.appendTo(element);
savedNodes.appendTo(element);
}
}
// It's now safe to clear the savedNodes
// since stop is the last callback.
savedNodes = null;
};
callbacks.receive = function(e, ui) {
// An item was dropped here from another list, set a flag on the
// item.
ui.item.sortable.received = true;
};
callbacks.remove = function(e, ui) {
// Workaround for a problem observed in nested connected lists.
// There should be an 'update' event before 'remove' when moving
// elements. If the event did not fire, cancel sorting.
if (!('dropindex' in ui.item.sortable)) {
element.sortable('cancel');
ui.item.sortable.cancel();
}
// Remove the item from this list's model and copy data into item,
// so the next list can retrive it
if (!ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ui.item.sortable.moved = ngModel.$modelValue.splice(
ui.item.sortable.index, 1)[0];
});
}
};
wrappers.helper = function (inner) {
if (inner && typeof inner === 'function') {
return function (e, item) {
var innerResult = inner.apply(this, arguments);
item.sortable._isCustomHelperUsed = item !== innerResult;
return innerResult;
};
}
return inner;
};
scope.$watchCollection('uiSortable', function(newVal, oldVal) {
// ensure that the jquery-ui-sortable widget instance
// is still bound to the directive's element
var sortableWidgetInstance = getSortableWidgetInstance(element);
if (!!sortableWidgetInstance) {
var optsDiff = patchUISortableOptions(newVal, oldVal, sortableWidgetInstance);
if (optsDiff) {
element.sortable('option', optsDiff);
}
}
}, true);
patchUISortableOptions(opts);
} else {
$log.info('ui.sortable: ngModel not provided!', element);
}
var stopDisabledWatcher = angular.noop;
var startIfEnabled = function()
{
if(!scope.uiSortable.disabled)
{
// Create sortable
element.sortable(opts);
// Stop Watcher
stopDisabledWatcher();
return true;
}
return false;
};
if(!startIfEnabled())
{
stopDisabledWatcher = scope.$watch('uiSortable.disabled', startIfEnabled);
}
}
};
}
]);