forked from mechanicious/domenu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.domenu-0.24.53.js
1371 lines (1229 loc) · 46.7 KB
/
jquery.domenu-0.24.53.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright © 2015 Mateusz Zawartka
* @version 0.24.53
* MIT license
*/
;
(function($, window, document, undefined) {
var hasTouch = 'ontouchstart' in document;
/**
* Add a dot at the beginning of a string
* @returns {string}
*/
String.prototype.dot = function() {
return '.' + this;
};
/**
* For each chunk prepend the current string
* @param chunk
* @param knife
* @param innerGlue
* @param outerGlue
* @returns {string}
*/
String.prototype.eachHas = function(chunk, knife, innerGlue, outerGlue) {
var subject = this,
opt = [],
knife = knife || ', ',
innerGlue = innerGlue || ' ',
outerGlue = outerGlue || knife,
chunks = chunk.split(knife);
chunks.forEach(function(chunk, c) {
opt.push(subject + innerGlue + chunk);
});
return opt.join(outerGlue);
};
/**
* Pad a string with a specified value, till a min length has been reached
* @param val
* @param minLength
* @returns {String}
*/
String.prototype.padLength = function(val, minLength) {
var subject = this;
while(subject.length < minLength) {
subject = val + subject;
}
return subject;
};
/**
* Join a sibling string by a delimiter
* @param sibling
* @param delimiter
* @returns {string}
*/
String.prototype.join = function(sibling, delimiter) {
var delimiter = typeof delimiter === 'string' ? delimiter : " ";
return this + delimiter + sibling;
};
/**
* Detect CSS pointer-events property
* events are normally disabled on the dragging element to avoid conflicts
* https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js
*/
var hasPointerEvents = (function() {
var el = document.createElement('div'),
docEl = document.documentElement;
if(!('pointerEvents' in el.style)) {
return false;
}
el.style.pointerEvents = 'auto';
el.style.pointerEvents = 'x';
docEl.appendChild(el);
var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto';
docEl.removeChild(el);
return !!supports;
})();
/**
* @version-control +0.1.0 slide animation duration option, default is 0
* @version-control +0.0.1 max depth default set to 20
* @dev-since 0.13.29
* @version-control +0.1.0 option endItemEditBtnClass
* @version-control +0.1.0 option itemAddBtnClass
* @version-control +0.1.0 option refuseConfirmDelay (ms), default is 2000ms
* @version-control +0.1.0 option addBtnSelector
* @type {{listNodeName: string, itemNodeName: string, rootClass: string, listClass: string, itemClass: string, dragClass: string, handleClass: string, collapsedClass: string, placeClass: string, noDragClass: string, emptyClass: string, contentClass: string, removeBtnClass: string, editBoxClass: string, expandBtnHTML: string, collapseBtnHTML: string, editBtnHTML: string, data: string, slideAnimationDuration: number, group: number, maxDepth: number, threshold: number}}
*/
var defaults = {
listNodeName: 'ol',
itemNodeName: 'li',
rootClass: 'dd',
listClass: 'dd-list',
itemClass: 'dd-item',
itemBlueprintClass: 'dd-item-blueprint',
dragClass: 'dd-dragel',
handleClass: 'dd-handle',
collapsedClass: 'dd-collapsed',
placeClass: 'dd-placeholder',
noDragClass: 'dd-nodrag',
emptyClass: 'dd-empty',
contentClass: 'dd3-content',
itemAddBtnClass: 'item-add',
removeBtnClass: 'item-remove',
endEditBtnClass: 'end-edit',
addBtnSelector: '',
addBtnClass: 'dd-new-item',
editBoxClass: 'dd-edit-box',
inputSelector: 'input, select, textarea',
expandBtnHTML: '<button data-action="expand" type="button">+</button>',
collapseBtnHTML: '<button data-action="collapse" type="button">-</button>',
editBtnHTML: '<button data-action="edit" type="button">edit</button>',
data: '',
slideAnimationDuration: 0,
group: 0,
maxDepth: 20,
threshold: 20,
refuseConfirmDelay: 2000,
onToJson: [],
onParseJson: [],
onDomenuInitialized: [],
onSaveEditBoxInput: [],
onItemDrag: [],
onItemAddChildItem: [],
onItemDrop: [],
onItemAdded: [],
onItemExpand: [],
onItemCollapse: [],
onItemRemoved: [],
onItemStartEdit: [],
onItemEndEdit: []
};
function Plugin(element, options) {
// After $(...).domenu() is called 1:
this.w = $(document);
this.el = $(element);
this.options = $.extend({}, defaults, options);
// 2:
this.init();
}
Plugin.prototype = {
init: function() {
// Plugin {w: m.fn.init[1], el: m.fn.init[1], options: Object, mouse: Object, isTouch: false…}
var list = this,
opt = this.options;
list.reset();
// el = jQuery object
// assign to el domenu-group the value user supplied as group property
list.el.data('domenu-group', this.options.group);
list.placeEl = $('<div class="' + list.options.placeClass + '"/>');
// forEach itemNodeName=li element
$.each(this.el.find(list.options.itemNodeName), function(k, el) {
// pass the li element
// If an element is a parent then it contains another li elements
// and can be collapsed and expanded
list.setParent($(el));
});
list.el.on('click', 'button', function(e) {
// Don't do anything when dragging
if(list.dragEl) {
return;
}
var target = $(e.currentTarget),
action = target.data('action'),
item = target.parent(list.options.itemNodeName);
// Some internal click handlers communicating through
// jQuery object data
if(action === 'collapse') {
list.collapseItem(item);
}
if(action === 'expand') {
list.expandItem(item);
}
});
// Declaring some custom event handlers
var onStartEvent = function(e) {
var handle = $(e.target);
// Identify if the object is draggable
if(!handle.hasClass(list.options.handleClass)) {
if(handle.closest(list.options.noDragClass.dot()).length) {
return;
}
handle = handle.closest(list.options.handleClass.dot());
}
// If the element is not draggable, or is while dragging
// then don't do anything
if(!handle.length || list.dragEl) return;
// Same here making sure if the object can be draggeds
list.isTouch = /^touch/.test(e.type);
if(list.isTouch && e.touches.length !== 1) {
return;
}
// Don't do whatever browsers do by default
e.preventDefault();
// At this point object is identified as available to drag
// so start dragging
list.dragStart(e.touches ? e.touches[0] : e);
},
onMoveEvent = function(e) {
if(list.dragEl) {
e.preventDefault();
list.dragMove(e.touches ? e.touches[0] : e);
}
},
onEndEvent = function(e) {
if(list.dragEl) {
e.preventDefault();
list.dragStop(e.touches ? e.touches[0] : e);
}
};
// If thouch events are avialable, start listening for those events
if(hasTouch) {
list.el[0].addEventListener('touchstart', onStartEvent, false);
window.addEventListener('touchmove', onMoveEvent, false);
window.addEventListener('touchend', onEndEvent, false);
window.addEventListener('touchcancel', onEndEvent, false);
}
// Start listening for the events below
list.el.on('mousedown', onStartEvent);
// list.w = $(document)
list.w.on('mousemove', onMoveEvent);
list.w.on('mouseup', onEndEvent);
// @dev-since 0.13.29
// @version-control +0.1.0 support global add button selector
if(opt.addBtnSelector) this.addNewListItemListener($(opt.addBtnSelector));
else this.addNewListItemListener(this.el.find(opt.addBtnClass.dot()));
},
/**
* @dev-since 0.13.29
* @version-control +0.1.0 default add button removed
* @param addBtn
* @param parent
*/
addNewListItemListener: function(addBtn, parent) {
var _this = this,
opt = this.options;
addBtn.on('click', function(e) {
var list = $(opt.rootClass.dot()).find(opt.listClass.dot()).first(),
item = _this.createNewListItem().css('display', 'none');
list.prepend(item);
item.fadeIn();
// Call item addition event listeners
opt.onItemAdded.forEach(function(cb, i) {
cb(item, e);
});
});
// Call init event listeners
opt.onDomenuInitialized.forEach(function(cb, i) {
cb();
});
},
/**
* @dev-since 0.13.29
* @version-control +0.0.5 support end edit on click
* @param event
*/
clickEndEditEventHandler: function(item) {
var _this = this,
opt = _this.options,
endEditBtn = item.find(opt.endEditBtnClass.dot()).first();
endEditBtn.on('click', null, {forced: true}, _this.keypressEnterEndEditEventHandler.bind(_this));
},
/**
* @version-control +0.0.1 lazy keypressEnterEndEditEventHandler binding
* @version-control +0.0.1 prevent slide animation bubbling
* @version-control +0.0.2 slide animation duration support
*/
clickStartEditEventHandler: function(event) {
var opt = this.options,
_this = this,
spn = $(event.target),
item = spn.parents(opt.itemClass.dot()).first(),
firstInput = item.find(opt.inputSelector).first(),
rmvBtn = item.find(opt.removeBtnClass.dot()).first(),
addBtn = item.find(opt.itemAddBtnClass.dot()).first(),
edtBox = item.find(opt.editBoxClass.dot()).first();
var igniteKeypressEnterEndEditEventHandler = function(el) {
el.each(function(c, item) {
var item = $(item),
keypressEnterEndEditEventHandler = _this.keypressEnterEndEditEventHandler;
if(item.data('domenu_keypressEnterEndEditEventHandler')) return;
item.data('domenu_keypressEnterEndEditEventHandler', true);
item.on('keypress', keypressEnterEndEditEventHandler.bind(_this));
});
};
// Setup on click endEdit event listener
if(item.data('domenu_clickEndEditEventHandler') !== true)
{
_this.clickEndEditEventHandler(item);
item.data('domenu_clickEndEditEventHandler', true);
}
// Hide the span
spn.stop().slideToggle(opt.slideAnimationDuration, function() {
// Use either the default title or the user specified title as the value for the input
if(firstInput.get(0).nodeName !== 'SELECT')
firstInput.val(spn.text());
else firstInput.val(firstInput.find('option:contains(' + spn.text() + ')').val());
// Hide the remove button
addBtn.slideToggle(opt.slideAnimationDuration);
rmvBtn.slideToggle(opt.slideAnimationDuration, function() {
// Show the edit panel
edtBox.stop().slideToggle(opt.slideAnimationDuration, function() {
edtBox.children().first('input').select().focus();
// Be ready to close the edit mode
igniteKeypressEnterEndEditEventHandler(item);
});
});
});
// Call start edit event listeners
opt.onItemStartEdit.forEach(function(cb, i) {
cb(item, event);
});
},
/**
* @version-control +0.1.0 support default value tokens and placeholder tokens
* @param token
* @param input
* @returns {*}
*/
resolveToken: function(token, input) {
if(typeof token !== "string") return;
var out = token,
tagRegex = /\{\?[a-z\-\.]+\}/ig,
tags = out.match(tagRegex),
tagsCount = tags && tags.length || 0;
// As long as there are tags available
for(var currentTag = 0; currentTag < tagsCount; currentTag++) {
// Process each tag and replace it it in the output string
switch(tags[currentTag]) {
case "{?date.gregorian-slashed-DMY}":
var dateTime = new Date(Date.now()),
date = dateTime.getDay().toString().padLength('0', 2) + '/' +
dateTime.getMonth().toString().padLength('0', 2) + '/' +
dateTime.getFullYear();
out = out.replace(tags[currentTag], date);
break;
case "{?date.mysql-datetime}":
var date = new Date(Date.now());
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
out = out.replace(tags[currentTag], date);
break;
case "{?numeric.increment}":
// We begin with 1 - evaluate to true on check..
this.incrementIncrement = this.incrementIncrement || 1;
out = out.replace(tags[currentTag], this.incrementIncrement);
this.incrementIncrement += 1;
break;
case "{?value}":
out = out.replace(tags[currentTag], input.value);
break;
default:
out = token;
break;
}
}
return out;
},
/**
* @version-control +0.0.1 shared way to save input state
* @version-control +0.0.5 tokens support
* @param inputCollection jQuery Selection
*/
saveEditBoxInput: function(inputCollection) {
var _this = this,
opt = this.options;
// Call on save edit box event listeners
opt.onSaveEditBoxInput.forEach(function(cb, i) {
cb(inputCollection);
});
inputCollection.each(function(c, input) {
var itemDataValue = $(input).parents(opt.itemClass.dot().join(',').join(opt.itemBlueprintClass.dot())).first().data(input.getAttribute('name')),
inputDefaultValue = $(input).data('default-value') || '',
item = $(input).parents(opt.itemClass.dot()).first();
if(!(itemDataValue || input.value)) var tokenizedDefault = _this.resolveToken(inputDefaultValue, $(input));
item.data(input.getAttribute('name'), $(input).val()|| itemDataValue || tokenizedDefault);
});
},
/**
* @version-control +0.1.0 dynamic inputs
* @version-control +0.0.1 prevent slide bubbling
* @version-control +0.0.2 slide animation duration support
* @dev-since 0.13.29
* @version-control +0.0.1 removeBtn first
* @version-control +0.0.2 support add button
* @param event
*/
keypressEnterEndEditEventHandler: function(event) {
var _this = this,
opt = this.options,
item = $(event.target).parents(opt.itemClass.dot()).first(),
edtBox = item.find(opt.editBoxClass.dot()).first(),
inputCollection = item.find(opt.inputSelector),
spn = item.find('span').first(),
removeBtn = item.find(opt.removeBtnClass.dot()).first(),
addBtn = item.find(opt.itemAddBtnClass.dot()).first();
// Listen only to the Enter key, unless you'll forced otherwise
if(event.keyCode !== 13 && !(event.data && event.data.forced && event.data.forced === true)) return;
// Set title
_this.determineAndSetItemTitle(item);
// Don't leave empty strings
if(spn.text() === '') spn.text(_this.determineAndSetItemTitle(item));
// Hide the edit box
edtBox.stop().slideUp(opt.slideAnimationDuration, function() {
// Save inputs
_this.saveEditBoxInput(inputCollection);
// Show the remove button
removeBtn.stop().slideDown(opt.slideAnimationDuration);
// Show the add button
addBtn.stop().slideDown(opt.slideAnimationDuration);
// Call end edit event listeners
opt.onItemEndEdit.forEach(function(cb, i) {
cb(item, event);
});
// Show the span content
spn.stop().slideDown(opt.slideAnimationDuration);
});
},
resolveInputDataEntryByName: function(name) {
var item = this.el
opt = this.options,
item.find(opt.editBoxClass.dot().join(opt.inputSelector)).each(function(i, input) {
if(input.getAttribute('name') === name) return $(input).data('name');
})
},
setItemTitle: function(item, title) {
var _this = this,
opt = this.options;
item.find(opt.contentClass.dot().join('span')).first().text(title);
},
determineAndSetItemTitle: function(item) {
var _this = this,
opt = this.options,
firstInput = item.find(opt.inputSelector).first(),
firstInputText = firstInput.find('option:selected').first().text() || firstInput.text(),
firstInputValue = item.find(opt.editBoxClass.dot().eachHas(opt.inputSelector)).first().val(),
itemDataValue = item.data(item.find(opt.inputSelector).first().attr('name')),
firstEditBoxInputPlaceholderValue = item.find(opt.editBoxClass.dot().eachHas(opt.inputSelector)).first().attr('placeholder'),
firstEditBoxInputDataPlaceholderValue = item.find(opt.editBoxClass.dot().eachHas(opt.inputSelector)).first().data('placeholder'),
choice = firstInputText || firstInputValue || itemDataValue || _this.resolveToken(firstEditBoxInputDataPlaceholderValue) || firstEditBoxInputPlaceholderValue;
item.find(opt.contentClass.dot().join('span')).first().text(choice);
},
/**
* @version-control +0.0.4 fix fill inputs with placeholders #3
* @version-control +0.1.0 fix populate inputs with values whenever possible #5
* @param item
* @param inputCollection
*/
setInputCollectionPlaceholders: function(item, inputCollection) {
var _this = this;
$(inputCollection).each(function(c, input) {
if(input.nodeName === 'SELECT')
{
$(input).find('option[selected="selected"]').removeAttr('selected');
return $(input).find('option[value="' + item.data($(input).attr('name')) + '"]').attr('selected', 'selected');
}
// Set the placeholder value of the input
$(input).attr('placeholder', _this.resolveToken($(input).data('placeholder'), $(input)) || $(input).attr('placeholder'));
// And set the value of the input
$(input).val(item.data($(input).attr('name')));
});
},
/**
* @version-control +0.0.5 support dynamic inputs
* @version-control +0.0.5 support tokenization
* @version-control +0.0.2 support dyanmic titles
* @dev-since 0.13.29
* @version-control +0.1.0 feature confirm item deletion
* @version-control +0.1.0 feature add a child item
* @version-control +0.0.1 support itemAddChildItem onItemAdded events
* @param data
* @returns {*}
*/
createNewListItem: function(data) {
var id = typeof id !== 'undefined' ? id : this.getHighestId() + 1,
_this = this,
el = this.el,
opt = this.options,
blueprint = el.find(opt.itemBlueprintClass.dot()).first().clone(),
inputCollection = blueprint.find(opt.editBoxClass.dot()).find(opt.inputSelector);
/**
* @dev-since 0.13.29
* @version-control +0.1.0 fix ghost parent elements
*/
blueprint.remove = function() {
var parent = blueprint.parents(_this.options.itemClass.dot()).first();
jQuery(this).remove();
_this.unsetEmptyParent(parent);
};
// Use user supplied JSON data to fill the data fields
$.each(data || {}, function(key, value) {
blueprint.data(key, value);
});
// Rename yourself to the default itemClass
blueprint.attr('class', opt.itemClass);
// Set intial input values (needed on deserialization)
this.setInputCollectionPlaceholders(blueprint, inputCollection);
// Save input state
this.saveEditBoxInput(inputCollection);
// Set title
this.determineAndSetItemTitle(blueprint);
// Parse tokens etc..
this.setInputCollectionPlaceholders(inputCollection);
// Set the remove button click event handler
blueprint.find(opt.removeBtnClass.dot()).first().on('click', function(e) {
var rmvBtn = $(this),
confirmClass = rmvBtn.data('confirm-class');
// When there is a confirmation class...
if(confirmClass) {
// And that class has been already applied to the item, then just remove the item
if(rmvBtn.hasClass(confirmClass)) blueprint.remove();
// If the confirmation class hasn't been yet applied to the item, then apply the class...
else {
rmvBtn.addClass(confirmClass);
// but only for a limited amount of time
var revertAddClass = setTimeout(function() {
rmvBtn.removeClass(confirmClass);
}, opt.refuseConfirmDelay);
}
// When there is no confirmation class just remove the item
} else {
blueprint.remove();
// Call item remove event listeners
opt.onItemRemoved.forEach(function(cb, i) {
cb(blueprint, e);
});
}
});
// Set the add button click event handler
blueprint.find(opt.itemAddBtnClass.dot()).first().on('click', function(event) {
_this.itemAddChildItem(blueprint);
// Call item addition event listeners
opt.onItemAdded.forEach(function(cb, i) {
cb(blueprint, event);
});
// Call item add child item event listeners
opt.onItemAddChildItem .forEach(function(cb, i) {
cb(blueprint, event);
});
});
// Setup editing; on every mouse click clickStartEditEventHandler will be called
blueprint.find('span').first().get(0).addEventListener('click', this.clickStartEditEventHandler.bind(this));
// Give back a ready itemClass element
return blueprint;
},
itemAddChildItem: function(parentElement) {
var _this = this,
opt = _this.options,
parentElement = $(parentElement),
listElement = $('<' + opt.listNodeName + '/>').addClass(opt.listClass),
newItem = _this.createNewListItem();
listElement.append(newItem);
parentElement.append(listElement);
_this.setParent(parentElement);
},
getHighestId: function() {
var opt = this.options,
el = this.el,
id = 0;
el.find(opt.itemNodeName).each(function(i, e) {
var eId = $(e).data('id');
if(eId > id) return id = eId;
});
return id;
},
/**
* @version-control +0.0.2 itemClass li prefix support
* @returns {*}
*/
serialize: function() {
// Call toJson event listeners
this.options.onToJson.forEach(function(cb, i) {
cb();
});
var data,
depth = 0,
list = this;
step = function(level, depth) {
var array = [],
items = level.children(list.options.itemNodeName);
items.each(function() {
var li = $(this),
sub = li.children(list.options.listNodeName),
filteredData = {};
// Filter out domenu_ prefixed data values
$.each(li.data(), function(key, i) {
// Skip when the prefix is present
if(key.indexOf('domenu_') === 0) return;
// Include the value if not skipped
filteredData[key] = li.data(key);
});
var item = $.extend({}, filteredData);
if(sub.length) {
item.children = step(sub, depth + 1);
}
array.push(item);
});
return array;
};
data = step(list.el.find(list.options.listNodeName).first(), depth);
return data;
},
deserialize: function(data, override) {
var data = JSON.parse(data) || JSON.parse(this.options.data),
_this = this,
opt = this.options,
list = _this.el.find(opt.listClass.dot()).first();
// Call start edit event listeners
this.options.onParseJson.forEach(function(cb, i) {
cb();
});
if(override) list.children().remove();
var processItem = function(i, pref) {
if(i.children) {
var cref = $('<ol class="' + opt.listClass + '"></ol>'),
item = _this.createNewListItem(i);
pref.append(item);
item.append(cref);
_this.setParent(item, true);
jQuery.each(i.children, function(i, e) {
processItem(e, cref);
})
} else {
var item = _this.createNewListItem(i);
pref.append(item);
}
}
jQuery.each(data, function(i, e) {
processItem(e, list);
})
},
serialise: function() {
return this.serialize();
},
reset: function() {
this.mouse = {
offsetX: 0,
offsetY: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
nowX: 0,
nowY: 0,
distX: 0,
distY: 0,
dirAx: 0,
dirX: 0,
dirY: 0,
lastDirX: 0,
lastDirY: 0,
distAxX: 0,
distAxY: 0
};
this.isTouch = false;
this.moving = false;
this.dragEl = null;
this.dragRootEl = null;
this.dragDepth = 0;
this.hasNewRoot = false;
this.pointEl = null;
},
expandItem: function(li) {
li.removeClass(this.options.collapsedClass);
li.children('[data-action="expand"]').hide();
li.children('[data-action="collapse"]').show();
li.children(this.options.listNodeName).show();
// Call start edit event listeners
this.options.onItemExpand.forEach(function(cb, i) {
cb(li);
});
},
collapseItem: function(li) {
var lists = li.children(this.options.listNodeName);
if(lists.length) {
li.addClass(this.options.collapsedClass);
li.children('[data-action="collapse"]').hide();
li.children('[data-action="expand"]').show();
li.children(this.options.listNodeName).hide();
}
// Call start edit event listeners
this.options.onItemCollapse.forEach(function(cb, i) {
cb(li);
});
},
expandAll: function(cb) {
var list = this;
list.el.find(list.options.itemNodeName).each(function() {
var item = $(this);
if(cb && cb(item)) list.expandItem($(this));
else list.expandItem($(this));
});
},
/**
* @version-control +0.0.1 collapse all fix
* @param cb
*/
collapseAll: function(cb) {
var list = this;
list.el.find(list.options.itemNodeName).each(function() {
var item = $(this);
if(cb && cb(item)) list.collapseItem(item);
else list.collapseItem(item);
});
},
/**
* @dev-since 0.13.29
* @version-control +0.0.5 prevent setting multiple parents on a parent element
* @param li
* @param force
*/
setParent: function(li, force) {
// If the specified selector targets any element
if(li.children(this.options.listNodeName).length && !li.children('[data-action]').length || force) {
// LI STRUCTURE
// <li class="dd-item dd3-item" data-id="15">
// <button data-action="collapse" type="button">Collapse</button>
// <button data-action="expand" type="button" style="display: none;">Expand</button>
// <div class="dd-handle dd3-handle">Drag</div><div class="dd3-content">Item 15</div>
// <ol class="dd-list">
// <li class="dd-item dd3-item" data-id="16">
// <div class="dd-handle dd3-handle">Drag</div><div class="dd3-content">Item 16</div>
// </li>
// <li class="dd-item dd3-item" data-id="17">
// <div class="dd-handle dd3-handle">Drag</div><div class="dd3-content">Item 17</div>
// </li>
// <li class="dd-item dd3-item" data-id="18">
// <div class="dd-handle dd3-handle">Drag</div><div class="dd3-content">Item 18</div>
// </li>
// </ol>
// </li>
li.prepend($(this.options.expandBtnHTML));
li.prepend($(this.options.collapseBtnHTML));
// make sure handle is the first element
var handle = li.find(this.options.handleClass.dot()).first().clone();
li.find(this.options.handleClass.dot()).first().remove();
li.prepend(handle);
}
// If the selector gets targeted within the li element
// hide it
li.children('[data-action="expand"]').hide();
},
/**
* @dev-since 0.13.29
* @version-control +0.1.0 fix clean item data when unsetting a parent #4
* @param parent
*/
unsetParent: function(parent) {
parent.removeClass(this.options.collapsedClass);
// Clear collapse/expand controls from the parent
parent.children('[data-action]').remove();
parent.children(this.options.listNodeName).remove();
parent.removeData('children');
},
/**
* @dev-since 0.13.29
* @version-control +0.0.5 unsetEmptyParent
* @param parent
*/
unsetEmptyParent: function(parent) {
var _this = this;
if (parent.find(this.options.itemClass.dot()).length === 0) _this.unsetParent(parent);
},
dragStart: function(e) {
var mouse = this.mouse,
target = $(e.target),
dragItem = target.closest(this.options.itemNodeName);
this.placeEl.css('height', dragItem.height());
mouse.offsetX = e.offsetX !== undefined ? e.offsetX : e.pageX - target.offset().left;
mouse.offsetY = e.offsetY !== undefined ? e.offsetY : e.pageY - target.offset().top;
mouse.startX = mouse.lastX = e.pageX;
mouse.startY = mouse.lastY = e.pageY;
this.dragRootEl = this.el;
// Define the state as dragging so no other elements get attached due
// to the identification process in init onStartDrag
this.dragEl = $(document.createElement(this.options.listNodeName))
.addClass(this.options.listClass + ' ' + this.options.dragClass);
this.dragEl.css('width', dragItem.width());
// this.placeEl -> $('<div class="' + list.options.placeClass + '"/>');
// Put the targeted element into the dragEl which will work as a kind of a bag
// while dragging
dragItem.after(this.placeEl);
dragItem[0].parentNode.removeChild(dragItem[0]);
dragItem.appendTo(this.dragEl);
$(document.body).append(this.dragEl);
// Adjust the dragging bag (dragEl) initial position within the
// element
this.dragEl.css({
'left': e.pageX - mouse.offsetX,
'top': e.pageY - mouse.offsetY
});
// What is the deepest element within dragEl?
var i, depth,
items = this.dragEl.find(this.options.itemNodeName);
for(i = 0; i < items.length; i++) {
depth = $(items[i]).parents(this.options.listNodeName).length;
if(depth > this.dragDepth) {
this.dragDepth = depth;
}
}
// Call start drag event listeners
this.options.onItemDrag.forEach(function(cb, i) {
cb(dragItem, e);
});
},
dragStop: function(e) {
var el = this.dragEl.children(this.options.itemNodeName).first();
el[0].parentNode.removeChild(el[0]);
this.placeEl.replaceWith(el);
this.dragEl.remove();
this.el.trigger('change');
if(this.hasNewRoot) {
this.dragRootEl.trigger('change');
}
this.reset();
// Call end drag event listeners
this.options.onItemDrop.forEach(function(cb, i) {
cb(el, e);
});
},
dragMove: function(e) {
var list, parent, prev, next, depth,
opt = this.options,
mouse = this.mouse;
// Placeholder will be dragged around, the member list will actually
// hide itself and replace the placeholder on dragStop
this.dragEl.css({
// Place element on the document following the mouse
// position change
//
// e.pageX position of the mouse relative to the whole page
// e.offsetX position of the mouse relative to .dd3-handle
// mouse absolute position - the position offset in the element =
// = begin offset of the element
'left': e.pageX - mouse.offsetX,
'top': e.pageY - mouse.offsetY
});
// mouse position last events
mouse.lastX = mouse.nowX;
mouse.lastY = mouse.nowY;
// mouse position this events
mouse.nowX = e.pageX;
mouse.nowY = e.pageY;
// distance mouse moved between events
mouse.distX = mouse.nowX - mouse.lastX;
mouse.distY = mouse.nowY - mouse.lastY;
// direction mouse was moving
mouse.lastDirX = mouse.dirX;
mouse.lastDirY = mouse.dirY;
// direction mouse is now moving (on both axis)
mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1;
mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1;
// axis mouse is now moving on
var newAx = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0;
// do nothing on first move
if(!mouse.moving) {
mouse.dirAx = newAx;
mouse.moving = true;
return;
}
// calc distance moved on this axis (and direction)
// if the direction has changed
if(mouse.dirAx !== newAx) {
mouse.distAxX = 0;
mouse.distAxY = 0;
} else {
mouse.distAxX += Math.abs(mouse.distX);
if(mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) {
mouse.distAxX = 0;
}
mouse.distAxY += Math.abs(mouse.distY);
if(mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) {