-
Notifications
You must be signed in to change notification settings - Fork 128
/
knockout-sortable.js
326 lines (279 loc) · 14.3 KB
/
knockout-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
;(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD anonymous module
define(["knockout", "jquery", "jquery.ui.sortable"], factory);
} else {
// No module loader (plain <script> tag) - put directly in global namespace
factory(window.ko, jQuery);
}
})(function(ko, $) {
var ITEMKEY = "ko_sortItem",
INDEXKEY = "ko_sourceIndex",
LISTKEY = "ko_sortList",
PARENTKEY = "ko_parentList",
DRAGKEY = "ko_dragItem",
unwrap = ko.utils.unwrapObservable,
dataGet = ko.utils.domData.get,
dataSet = ko.utils.domData.set;
//internal afterRender that adds meta-data to children
var addMetaDataAfterRender = function(elements, data) {
ko.utils.arrayForEach(elements, function(element) {
if (element.nodeType === 1) {
dataSet(element, ITEMKEY, data);
dataSet(element, PARENTKEY, dataGet(element.parentNode, LISTKEY));
}
});
};
//prepare the proper options for the template binding
var prepareTemplateOptions = function(valueAccessor, dataName) {
var result = {},
options = unwrap(valueAccessor()),
actualAfterRender;
//build our options to pass to the template engine
if (options.data) {
result[dataName] = options.data;
result.name = options.template;
} else {
result[dataName] = valueAccessor();
}
ko.utils.arrayForEach(["afterAdd", "afterRender", "as", "beforeRemove", "includeDestroyed", "templateEngine", "templateOptions"], function (option) {
result[option] = options[option] || ko.bindingHandlers.sortable[option];
});
//use an afterRender function to add meta-data
if (dataName === "foreach") {
if (result.afterRender) {
//wrap the existing function, if it was passed
actualAfterRender = result.afterRender;
result.afterRender = function(element, data) {
addMetaDataAfterRender.call(data, element, data);
actualAfterRender.call(data, element, data);
};
} else {
result.afterRender = addMetaDataAfterRender;
}
}
//return options to pass to the template binding
return result;
};
var updateIndexFromDestroyedItems = function(index, items) {
var unwrapped = unwrap(items);
if (unwrapped) {
for (var i = 0; i < index; i++) {
//add one for every destroyed item we find before the targetIndex in the target array
if (unwrapped[i] && unwrap(unwrapped[i]._destroy)) {
index++;
}
}
}
return index;
};
//connect items with observableArrays
ko.bindingHandlers.sortable = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
var $element = $(element),
value = unwrap(valueAccessor()) || {},
templateOptions = prepareTemplateOptions(valueAccessor, "foreach"),
sortable = {},
startActual, updateActual;
//remove leading/trailing non-elements from anonymous templates
ko.utils.arrayForEach(element.childNodes, function(node) {
if (node && node.nodeType !== 1) {
node.parentNode.removeChild(node);
}
});
//build a new object that has the global options with overrides from the binding
$.extend(true, sortable, ko.bindingHandlers.sortable);
if (value.options && sortable.options) {
ko.utils.extend(sortable.options, value.options);
delete value.options;
}
ko.utils.extend(sortable, value);
//if allowDrop is an observable or a function, then execute it in a computed observable
if (sortable.connectClass && (ko.isObservable(sortable.allowDrop) || typeof sortable.allowDrop == "function")) {
ko.computed({
read: function() {
var value = unwrap(sortable.allowDrop),
shouldAdd = typeof value == "function" ? value.call(this, templateOptions.foreach) : value;
ko.utils.toggleDomNodeCssClass(element, sortable.connectClass, shouldAdd);
},
disposeWhenNodeIsRemoved: element
}, this);
} else {
ko.utils.toggleDomNodeCssClass(element, sortable.connectClass, sortable.allowDrop);
}
//wrap the template binding
ko.bindingHandlers.template.init(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
//keep a reference to start/update functions that might have been passed in
startActual = sortable.options.start;
updateActual = sortable.options.update;
//initialize sortable binding after template binding has rendered in update function
var createTimeout = setTimeout(function() {
var dragItem;
$element.sortable(ko.utils.extend(sortable.options, {
start: function(event, ui) {
//track original index
var el = ui.item[0];
dataSet(el, INDEXKEY, ko.utils.arrayIndexOf(ui.item.parent().children(), el));
//make sure that fields have a chance to update model
ui.item.find("input:focus").change();
if (startActual) {
startActual.apply(this, arguments);
}
},
receive: function(event, ui) {
dragItem = dataGet(ui.item[0], DRAGKEY);
if (dragItem) {
//copy the model item, if a clone option is provided
if (dragItem.clone) {
dragItem = dragItem.clone();
}
//configure a handler to potentially manipulate item before drop
if (sortable.dragged) {
dragItem = sortable.dragged.call(this, dragItem, event, ui) || dragItem;
}
}
},
update: function(event, ui) {
var sourceParent, targetParent, sourceIndex, targetIndex, arg,
el = ui.item[0],
parentEl = ui.item.parent()[0],
item = dataGet(el, ITEMKEY) || dragItem;
dragItem = null;
//make sure that moves only run once, as update fires on multiple containers
if (item && (this === parentEl || $.contains(this, parentEl))) {
//identify parents
sourceParent = dataGet(el, PARENTKEY);
sourceIndex = dataGet(el, INDEXKEY);
targetParent = dataGet(el.parentNode, LISTKEY);
targetIndex = ko.utils.arrayIndexOf(ui.item.parent().children(), el);
//take destroyed items into consideration
if (!templateOptions.includeDestroyed) {
sourceIndex = updateIndexFromDestroyedItems(sourceIndex, sourceParent);
targetIndex = updateIndexFromDestroyedItems(targetIndex, targetParent);
}
if (sortable.beforeMove || sortable.afterMove) {
arg = {
item: item,
sourceParent: sourceParent,
sourceParentNode: sourceParent && ui.sender || el.parentNode,
sourceIndex: sourceIndex,
targetParent: targetParent,
targetIndex: targetIndex,
cancelDrop: false
};
}
if (sortable.beforeMove) {
sortable.beforeMove.call(this, arg, event, ui);
if (arg.cancelDrop) {
//call cancel on the correct list
if (arg.sourceParent) {
$(arg.sourceParent === arg.targetParent ? this : ui.sender).sortable('cancel');
}
//for a draggable item just remove the element
else {
$(el).remove();
}
return;
}
}
if (targetIndex >= 0) {
if (sourceParent) {
sourceParent.splice(sourceIndex, 1);
//if using deferred updates plugin, force updates
if (ko.processAllDeferredBindingUpdates) {
ko.processAllDeferredBindingUpdates();
}
}
targetParent.splice(targetIndex, 0, item);
}
//rendering is handled by manipulating the observableArray; ignore dropped element
dataSet(el, ITEMKEY, null);
ui.item.remove();
//if using deferred updates plugin, force updates
if (ko.processAllDeferredBindingUpdates) {
ko.processAllDeferredBindingUpdates();
}
//allow binding to accept a function to execute after moving the item
if (sortable.afterMove) {
sortable.afterMove.call(this, arg, event, ui);
}
}
if (updateActual) {
updateActual.apply(this, arguments);
}
},
connectWith: sortable.connectClass ? "." + sortable.connectClass : false
}));
//handle enabling/disabling sorting
if (sortable.isEnabled !== undefined) {
ko.computed({
read: function() {
$element.sortable(unwrap(sortable.isEnabled) ? "enable" : "disable");
},
disposeWhenNodeIsRemoved: element
});
}
}, 0);
//handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
//only call destroy if sortable has been created
if ($element.data("sortable")) {
$element.sortable("destroy");
}
//do not create the sortable if the element has been removed from DOM
clearTimeout(createTimeout);
});
return { 'controlsDescendantBindings': true };
},
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
var templateOptions = prepareTemplateOptions(valueAccessor, "foreach");
//attach meta-data
dataSet(element, LISTKEY, templateOptions.foreach);
//call template binding's update with correct options
ko.bindingHandlers.template.update(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
},
connectClass: 'ko_container',
allowDrop: true,
afterMove: null,
beforeMove: null,
options: {}
};
//create a draggable that is appropriate for dropping into a sortable
ko.bindingHandlers.draggable = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
var value = unwrap(valueAccessor()) || {},
options = value.options || {},
draggableOptions = ko.utils.extend({}, ko.bindingHandlers.draggable.options),
templateOptions = prepareTemplateOptions(valueAccessor, "data"),
connectClass = value.connectClass || ko.bindingHandlers.draggable.connectClass,
isEnabled = value.isEnabled !== undefined ? value.isEnabled : ko.bindingHandlers.draggable.isEnabled;
value = value.data || value;
//set meta-data
dataSet(element, DRAGKEY, value);
//override global options with override options passed in
ko.utils.extend(draggableOptions, options);
//setup connection to a sortable
draggableOptions.connectToSortable = connectClass ? "." + connectClass : false;
//initialize draggable
$(element).draggable(draggableOptions);
//handle enabling/disabling sorting
if (isEnabled !== undefined) {
ko.computed({
read: function() {
$(element).draggable(unwrap(isEnabled) ? "enable" : "disable");
},
disposeWhenNodeIsRemoved: element
});
}
return ko.bindingHandlers.template.init(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
},
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
var templateOptions = prepareTemplateOptions(valueAccessor, "data");
return ko.bindingHandlers.template.update(element, function() { return templateOptions; }, allBindingsAccessor, data, context);
},
connectClass: ko.bindingHandlers.sortable.connectClass,
options: {
helper: "clone"
}
};
});