Subversion-Projekte lars-tiefland.ci

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
776 lars 1
/*!
2
 * Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/
3
 * Dual-licensed under the BSD or MIT licenses
4
 */
5
;(function($, window, document, undefined)
6
{
7
    var hasTouch = 'ontouchstart' in window;
8
 
9
    if (navigator.appVersion.indexOf("Win")!=-1){
10
        var hasTouch = false;
11
    } else {
12
        var hasTouch = 'ontouchstart' in window;
13
    }
14
 
15
    /**
16
     * Detect CSS pointer-events property
17
     * events are normally disabled on the dragging element to avoid conflicts
18
     * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js
19
     */
20
    var hasPointerEvents = (function()
21
    {
22
        var el    = document.createElement('div'),
23
            docEl = document.documentElement;
24
        if (!('pointerEvents' in el.style)) {
25
            return false;
26
        }
27
        el.style.pointerEvents = 'auto';
28
        el.style.pointerEvents = 'x';
29
        docEl.appendChild(el);
30
        var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto';
31
        docEl.removeChild(el);
32
        return !!supports;
33
    })();
34
 
35
    var eStart  = hasTouch ? 'touchstart'  : 'mousedown',
36
        eMove   = hasTouch ? 'touchmove'   : 'mousemove',
37
        eEnd    = hasTouch ? 'touchend'    : 'mouseup';
38
        eCancel = hasTouch ? 'touchcancel' : 'mouseup';
39
 
40
    var defaults = {
41
            listNodeName    : 'ol',
42
            itemNodeName    : 'li',
43
            rootClass       : 'dd',
44
            listClass       : 'dd-list',
45
            itemClass       : 'dd-item',
46
            dragClass       : 'dd-dragel',
47
            handleClass     : 'dd-handle',
48
            collapsedClass  : 'dd-collapsed',
49
            placeClass      : 'dd-placeholder',
50
            noDragClass     : 'dd-nodrag',
51
            emptyClass      : 'dd-empty',
52
            expandBtnHTML   : '<button data-action="expand" type="button">Expand</button>',
53
            collapseBtnHTML : '<button data-action="collapse" type="button">Collapse</button>',
54
            group           : 0,
55
            maxDepth        : 5,
56
            threshold       : 20,
57
 
58
            //method for call when an item has been successfully dropped
59
            //method has 1 argument in which sends an object containing all
60
            //necessary details
61
            dropCallback    : null
62
        };
63
 
64
    function Plugin(element, options)
65
    {
66
        this.w  = $(window);
67
        this.el = $(element);
68
        this.options = $.extend({}, defaults, options);
69
        this.init();
70
    }
71
 
72
    Plugin.prototype = {
73
 
74
        init: function()
75
        {
76
            var list = this;
77
 
78
            list.reset();
79
 
80
            list.el.data('nestable-group', this.options.group);
81
 
82
            list.placeEl = $('<div class="' + list.options.placeClass + '"/>');
83
 
84
            $.each(this.el.find(list.options.itemNodeName), function(k, el) {
85
                list.setParent($(el));
86
            });
87
 
88
            list.el.on('click', 'button', function(e) {
89
                if (list.dragEl || (!hasTouch && e.button !== 0)) {
90
                    return;
91
                }
92
                var target = $(e.currentTarget),
93
                    action = target.data('action'),
94
                    item   = target.parent(list.options.itemNodeName);
95
                if (action === 'collapse') {
96
                    list.collapseItem(item);
97
                }
98
                if (action === 'expand') {
99
                    list.expandItem(item);
100
                }
101
            });
102
 
103
            var onStartEvent = function(e)
104
            {
105
                var handle = $(e.target);
106
                if (!handle.hasClass(list.options.handleClass)) {
107
                    if (handle.closest('.' + list.options.noDragClass).length) {
108
                        return;
109
                    }
110
                    handle = handle.closest('.' + list.options.handleClass);
111
                }
112
                if (!handle.length || list.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) {
113
                    return;
114
                }
115
                e.preventDefault();
116
                list.dragStart(hasTouch ? e.touches[0] : e);
117
            };
118
 
119
            var onMoveEvent = function(e)
120
            {
121
                if (list.dragEl) {
122
                    e.preventDefault();
123
                    list.dragMove(hasTouch ? e.touches[0] : e);
124
                }
125
            };
126
 
127
            var onEndEvent = function(e)
128
            {
129
                if (list.dragEl) {
130
                    e.preventDefault();
131
                    list.dragStop(hasTouch ? e.touches[0] : e);
132
                }
133
            };
134
 
135
            if (hasTouch) {
136
                list.el[0].addEventListener(eStart, onStartEvent, false);
137
                window.addEventListener(eMove, onMoveEvent, false);
138
                window.addEventListener(eEnd, onEndEvent, false);
139
                window.addEventListener(eCancel, onEndEvent, false);
140
            } else {
141
                list.el.on(eStart, onStartEvent);
142
                list.w.on(eMove, onMoveEvent);
143
                list.w.on(eEnd, onEndEvent);
144
            }
145
 
146
        },
147
 
148
        serialize: function()
149
        {
150
            var data,
151
                depth = 0,
152
                list  = this;
153
                step  = function(level, depth)
154
                {
155
                    var array = [ ],
156
                        items = level.children(list.options.itemNodeName);
157
                    items.each(function()
158
                    {
159
                        var li   = $(this),
160
                            item = $.extend({}, li.data()),
161
                            sub  = li.children(list.options.listNodeName);
162
                        if (sub.length) {
163
                            item.children = step(sub, depth + 1);
164
                        }
165
                        array.push(item);
166
                    });
167
                    return array;
168
                };
169
            data = step(list.el.find(list.options.listNodeName).first(), depth);
170
            return data;
171
        },
172
 
173
        serialise: function()
174
        {
175
            return this.serialize();
176
        },
177
 
178
        reset: function()
179
        {
180
            this.mouse = {
181
                offsetX   : 0,
182
                offsetY   : 0,
183
                startX    : 0,
184
                startY    : 0,
185
                lastX     : 0,
186
                lastY     : 0,
187
                nowX      : 0,
188
                nowY      : 0,
189
                distX     : 0,
190
                distY     : 0,
191
                dirAx     : 0,
192
                dirX      : 0,
193
                dirY      : 0,
194
                lastDirX  : 0,
195
                lastDirY  : 0,
196
                distAxX   : 0,
197
                distAxY   : 0
198
            };
199
            this.moving     = false;
200
            this.dragEl     = null;
201
            this.dragRootEl = null;
202
            this.dragDepth  = 0;
203
            this.hasNewRoot = false;
204
            this.pointEl    = null;
205
            this.sourceRoot = null;
206
        },
207
 
208
        expandItem: function(li)
209
        {
210
            li.removeClass(this.options.collapsedClass);
211
            li.children('[data-action="expand"]').hide();
212
            li.children('[data-action="collapse"]').show();
213
            li.children(this.options.listNodeName).show();
214
        },
215
 
216
        collapseItem: function(li)
217
        {
218
            var lists = li.children(this.options.listNodeName);
219
            if (lists.length) {
220
                li.addClass(this.options.collapsedClass);
221
                li.children('[data-action="collapse"]').hide();
222
                li.children('[data-action="expand"]').show();
223
                li.children(this.options.listNodeName).hide();
224
            }
225
        },
226
 
227
        expandAll: function()
228
        {
229
            var list = this;
230
            list.el.find(list.options.itemNodeName).each(function() {
231
                list.expandItem($(this));
232
            });
233
        },
234
 
235
        collapseAll: function()
236
        {
237
            var list = this;
238
            list.el.find(list.options.itemNodeName).each(function() {
239
                list.collapseItem($(this));
240
            });
241
        },
242
 
243
        setParent: function(li)
244
        {
245
            if (li.children(this.options.listNodeName).length) {
246
                li.prepend($(this.options.expandBtnHTML));
247
                li.prepend($(this.options.collapseBtnHTML));
248
            }
249
            li.children('[data-action="expand"]').hide();
250
        },
251
 
252
        unsetParent: function(li)
253
        {
254
            li.removeClass(this.options.collapsedClass);
255
            li.children('[data-action]').remove();
256
            li.children(this.options.listNodeName).remove();
257
        },
258
 
259
        dragStart: function(e)
260
        {
261
            var mouse    = this.mouse,
262
                target   = $(e.target),
263
                dragItem = target.closest(this.options.itemNodeName);
264
 
265
            this.sourceRoot = target.closest('.' + this.options.rootClass);
266
            this.placeEl.css('height', dragItem.height());
267
 
268
            mouse.offsetX = e.offsetX !== undefined ? e.offsetX : e.pageX - target.offset().left;
269
            mouse.offsetY = e.offsetY !== undefined ? e.offsetY : e.pageY - target.offset().top;
270
            mouse.startX = mouse.lastX = e.pageX;
271
            mouse.startY = mouse.lastY = e.pageY;
272
 
273
            this.dragRootEl = this.el;
274
 
275
            this.dragEl = $(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass);
276
            this.dragEl.css('width', dragItem.width());
277
 
278
            // fix for zepto.js
279
            //dragItem.after(this.placeEl).detach().appendTo(this.dragEl);
280
            dragItem.after(this.placeEl);
281
            dragItem[0].parentNode.removeChild(dragItem[0]);
282
            dragItem.appendTo(this.dragEl);
283
 
284
            $(document.body).append(this.dragEl);
285
            this.dragEl.css({
286
                'left' : e.pageX - mouse.offsetX,
287
                'top'  : e.pageY - mouse.offsetY
288
            });
289
            // total depth of dragging item
290
            var i, depth,
291
                items = this.dragEl.find(this.options.itemNodeName);
292
            for (i = 0; i < items.length; i++) {
293
                depth = $(items[i]).parents(this.options.listNodeName).length;
294
                if (depth > this.dragDepth) {
295
                    this.dragDepth = depth;
296
                }
297
            }
298
        },
299
 
300
        dragStop: function(e)
301
        {
302
            // fix for zepto.js
303
            //this.placeEl.replaceWith(this.dragEl.children(this.options.itemNodeName + ':first').detach());
304
            var el = this.dragEl.children(this.options.itemNodeName).first();
305
            el[0].parentNode.removeChild(el[0]);
306
            this.placeEl.replaceWith(el);
307
 
308
            this.dragEl.remove();
309
            this.el.trigger('change');
310
 
311
            //Let's find out new parent id
312
            var parentItem = el.parent().parent();
313
            var parentId = null;
314
            if(parentItem !== null && !parentItem.is('.' + this.options.rootClass))
315
                parentId = parentItem.data('id');
316
 
317
            if($.isFunction(this.options.dropCallback)) {
318
              var details = {
319
                sourceId   : el.data('id'),
320
                destId     : parentId,
321
                sourceEl   : el,
322
                destParent : parentItem,
323
                destRoot   : el.closest('.' + this.options.rootClass),
324
                sourceRoot : this.sourceRoot
325
              };
326
              this.options.dropCallback.call(this, details);
327
            }
328
 
329
            if (this.hasNewRoot) {
330
                this.dragRootEl.trigger('change');
331
            }
332
            this.reset();
333
        },
334
 
335
        dragMove: function(e)
336
        {
337
            var list, parent, prev, next, depth,
338
                opt   = this.options,
339
                mouse = this.mouse;
340
 
341
            this.dragEl.css({
342
                'left' : e.pageX - mouse.offsetX,
343
                'top'  : e.pageY - mouse.offsetY
344
            });
345
 
346
            // mouse position last events
347
            mouse.lastX = mouse.nowX;
348
            mouse.lastY = mouse.nowY;
349
            // mouse position this events
350
            mouse.nowX  = e.pageX;
351
            mouse.nowY  = e.pageY;
352
            // distance mouse moved between events
353
            mouse.distX = mouse.nowX - mouse.lastX;
354
            mouse.distY = mouse.nowY - mouse.lastY;
355
            // direction mouse was moving
356
            mouse.lastDirX = mouse.dirX;
357
            mouse.lastDirY = mouse.dirY;
358
            // direction mouse is now moving (on both axis)
359
            mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1;
360
            mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1;
361
            // axis mouse is now moving on
362
            var newAx   = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0;
363
 
364
            // do nothing on first move
365
            if (!mouse.moving) {
366
                mouse.dirAx  = newAx;
367
                mouse.moving = true;
368
                return;
369
            }
370
 
371
            // calc distance moved on this axis (and direction)
372
            if (mouse.dirAx !== newAx) {
373
                mouse.distAxX = 0;
374
                mouse.distAxY = 0;
375
            } else {
376
                mouse.distAxX += Math.abs(mouse.distX);
377
                if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) {
378
                    mouse.distAxX = 0;
379
                }
380
                mouse.distAxY += Math.abs(mouse.distY);
381
                if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) {
382
                    mouse.distAxY = 0;
383
                }
384
            }
385
            mouse.dirAx = newAx;
386
 
387
            /**
388
             * move horizontal
389
             */
390
            if (mouse.dirAx && mouse.distAxX >= opt.threshold) {
391
                // reset move distance on x-axis for new phase
392
                mouse.distAxX = 0;
393
                prev = this.placeEl.prev(opt.itemNodeName);
394
                // increase horizontal level if previous sibling exists and is not collapsed
395
                if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass)) {
396
                    // cannot increase level when item above is collapsed
397
                    list = prev.find(opt.listNodeName).last();
398
                    // check if depth limit has reached
399
                    depth = this.placeEl.parents(opt.listNodeName).length;
400
                    if (depth + this.dragDepth <= opt.maxDepth) {
401
                        // create new sub-level if one doesn't exist
402
                        if (!list.length) {
403
                            list = $('<' + opt.listNodeName + '/>').addClass(opt.listClass);
404
                            list.append(this.placeEl);
405
                            prev.append(list);
406
                            this.setParent(prev);
407
                        } else {
408
                            // else append to next level up
409
                            list = prev.children(opt.listNodeName).last();
410
                            list.append(this.placeEl);
411
                        }
412
                    }
413
                }
414
                // decrease horizontal level
415
                if (mouse.distX < 0) {
416
                    // we can't decrease a level if an item preceeds the current one
417
                    next = this.placeEl.next(opt.itemNodeName);
418
                    if (!next.length) {
419
                        parent = this.placeEl.parent();
420
                        this.placeEl.closest(opt.itemNodeName).after(this.placeEl);
421
                        if (!parent.children().length) {
422
                            this.unsetParent(parent.parent());
423
                        }
424
                    }
425
                }
426
            }
427
 
428
            var isEmpty = false;
429
 
430
            // find list item under cursor
431
            if (!hasPointerEvents) {
432
                this.dragEl[0].style.visibility = 'hidden';
433
            }
434
            this.pointEl = $(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop)));
435
            if (!hasPointerEvents) {
436
                this.dragEl[0].style.visibility = 'visible';
437
            }
438
            if (this.pointEl.hasClass(opt.handleClass)) {
439
                this.pointEl = this.pointEl.parent(opt.itemNodeName);
440
            }
441
            if (this.pointEl.hasClass(opt.emptyClass)) {
442
                isEmpty = true;
443
            }
444
            else if (!this.pointEl.length || !this.pointEl.hasClass(opt.itemClass)) {
445
                return;
446
            }
447
 
448
            // find parent list of item under cursor
449
            var pointElRoot = this.pointEl.closest('.' + opt.rootClass),
450
                isNewRoot   = this.dragRootEl.data('nestable-id') !== pointElRoot.data('nestable-id');
451
 
452
            /**
453
             * move vertical
454
             */
455
            if (!mouse.dirAx || isNewRoot || isEmpty) {
456
                // check if groups match if dragging over new root
457
                if (isNewRoot && opt.group !== pointElRoot.data('nestable-group')) {
458
                    return;
459
                }
460
                // check depth limit
461
                depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length;
462
                if (depth > opt.maxDepth) {
463
                    return;
464
                }
465
                var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2);
466
                    parent = this.placeEl.parent();
467
                // if empty create new list to replace empty placeholder
468
                if (isEmpty) {
469
                    list = $(document.createElement(opt.listNodeName)).addClass(opt.listClass);
470
                    list.append(this.placeEl);
471
                    this.pointEl.replaceWith(list);
472
                }
473
                else if (before) {
474
                    this.pointEl.before(this.placeEl);
475
                }
476
                else {
477
                    this.pointEl.after(this.placeEl);
478
                }
479
                if (!parent.children().length) {
480
                    this.unsetParent(parent.parent());
481
                }
482
                if (!this.dragRootEl.find(opt.itemNodeName).length) {
483
                    this.dragRootEl.append('<div class="' + opt.emptyClass + '"/>');
484
                }
485
                // parent root list has changed
486
                if (isNewRoot) {
487
                    this.dragRootEl = pointElRoot;
488
                    this.hasNewRoot = this.el[0] !== this.dragRootEl[0];
489
                }
490
            }
491
        }
492
 
493
    };
494
 
495
    $.fn.nestable = function(params)
496
    {
497
        var lists  = this,
498
            retval = this;
499
 
500
        lists.each(function()
501
        {
502
            var plugin = $(this).data("nestable");
503
 
504
            if (!plugin) {
505
                $(this).data("nestable", new Plugin(this, params));
506
                $(this).data("nestable-id", new Date().getTime());
507
            } else {
508
                if (typeof params === 'string' && typeof plugin[params] === 'function') {
509
                    retval = plugin[params]();
510
                }
511
            }
512
        });
513
 
514
        return retval || lists;
515
    };
516
 
517
})(window.jQuery || window.Zepto, window, document);