/
ProcessPageList.js
1510 lines (1256 loc) · 48.3 KB
/
ProcessPageList.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
/**
* ProcessWire Page List Process, JQuery Plugin
*
* Provides the Javascript/jQuery implementation of the PageList process when used with the JSON renderer
*
* ProcessWire 3.x (development), Copyright 2016 by Ryan Cramer
* https://processwire.com
*
*/
function ProcessPageListInit() {
if(ProcessWire.config.ProcessPageList) {
$('#' + ProcessWire.config.ProcessPageList.containerID).ProcessPageList(ProcessWire.config.ProcessPageList);
}
}
$(document).ready(function() {
ProcessPageListInit();
});
(function($) {
$.fn.ProcessPageList = function(customOptions) {
/**
* List of options that may be passed to the plugin
*
*/
var options = {
// mode: 'select' or 'actions', currently this is automatically determined based on the element the PageList is attached to
mode: '',
// default number of pages to show before pagination
limit: 35,
// the page ID that starts the list
rootPageID: 0,
// show the page identified by 'rootPageID' ?
showRootPage: true,
// the page ID currently selected
selectedPageID: 0,
// id of the admin page
adminPageID: 2,
// id of the trash page
trashPageID: 7,
// language ID, if applicable
langID: 0,
// in 'select' mode, allow no value to be selected (to abort a selected value)
selectAllowUnselect: false,
// show the 'currently selected' page header? (should be false on multi-selection)
selectShowPageHeader: true,
// show the parent path in the selected page label?
selectShowPath: true,
// use multiple mode enhancements when select mode enabled?
selectMultiple: false,
// the label to click on to change the currently selected page
selectStartLabel: 'Change',
// the label to click on to cancel selecting a page
selectCancelLabel: 'Cancel',
// the label to click on to select a given page
selectSelectLabel: 'Select',
// the label to click on to unselect a selected page
selectUnselectLabel: 'Unselect',
// label used for 'more' in paginated lists
moreLabel: 'More',
// label used for 'trash' button in Move mode
trashLabel: 'Trash',
// label used for the move instruction
moveInstructionLabel: "Click and drag to move",
// href attribute of 'select' link
selectSelectHref: '#',
// href attribute of 'unselect' link
selectUnselectHref: '#',
// URL where page lists are loaded from
ajaxURL: ProcessWire.config.urls.admin + 'page/list/',
// URL where page move's should be posted
ajaxMoveURL: ProcessWire.config.urls.admin + 'page/sort/',
// classes for pagination
paginationClass: 'PageListPagination',
paginationCurrentClass: 'PageListPaginationCurrent',
paginationLinkClass: 'ui-state-default',
paginationLinkCurrentClass: 'ui-state-active',
paginationHoverClass: 'ui-state-hover',
paginationDisabledClass: 'ui-priority-secondary',
// pagination number that you want to open (to correspond with openPageIDs)
openPagination: 0,
// IDs of the pages that we want to automatically open (default none)
openPageIDs: [],
// pre-rendered data corresponding to openPageIDs, indexed by 'id-start', i.e. 123-0
openPageData: {},
// speed at which the slideUp/slideDown run (in ms)
speed: 200,
// whether or not hovering an item reveals its actions
useHoverActions: false,
// milliseconds delay between hovering an item and it revealing actions
hoverActionDelay: 250,
// milliseconds in fade time to reveal or hide hover actions
hoverActionFade: 150,
// show only edit and view actions, and make everything else extra actions
useNarrowActions: $('body').hasClass('pw-narrow-width'),
// markup for the spinner used when ajax calls are made
spinnerMarkup: "<span class='PageListLoading'><i class='ui-priority-secondary fa fa-fw fa-spin fa-spinner'></i></span>",
// session field name that holds page label format, when used
labelName: '',
// what to show in the PageListNumChildren quantity: 'children', 'total', 'children/total', 'total/children', or 'id'
// default is blank, which implies 'children'
qtyType: '',
};
// array of "123.0" (page_id.start) that are currently open (used in non-select mode only)
var currentOpenPageIDs = [];
// true when operations are occurring where we want to ignore clicks
var ignoreClicks = false;
var isModal = $("body").hasClass("modal") || $("body").hasClass("pw-iframe");
if(typeof ProcessWire.config.ProcessPageList != "undefined") {
$.extend(options, ProcessWire.config.ProcessPageList);
}
$.extend(options, customOptions);
return this.each(function(index) {
var $container = $(this);
var $outer;
var $root;
var $loading = $(options.spinnerMarkup);
var firstPagination = 0; // used internally by the getPaginationList() function
var curPagination = 0; // current page number used by getPaginationList() function
/**
* Initialize the Page List
*
*/
function init() {
$root = $("<div class='PageListRoot'></div>");
if($container.is(":input")) {
options.selectedPageID = $container.val();
if(!options.selectedPageID.length) options.selectedPageID = 0;
options.mode = 'select';
$container.before($root);
$outer = $container.closest('.InputfieldContent');
setupSelectMode();
} else {
options.mode = 'actions';
$container.append($root);
$outer = $container;
loadChildren(options.rootPageID > 0 ? options.rootPageID : 1, $root, 0, true);
/*
// longclick to initiate sort, still marinating on whether to support this
$(document).on('longclick', 'a.PageListPage', function() {
$(this).parent().find('.PageListActionMove > a').trigger('click');
});
*/
}
$(document).on('pageListRefresh', function(e, pageID) {
// i.e. $(document).trigger('pageListRefresh', pageID);
refreshList(pageID);
});
if(options.useHoverActions) {
$root.addClass('PageListUseHoverActions');
setupHoverActions();
}
}
/**
* If hover actions enabled, setup events to hide/show hover actions
*
*/
function setupHoverActions() {
var hoverTimeout = null;
var hoverOutTimeout = null;
var $hoveredItem = null;
function showItem($item) {
var $actions = $item.find('.PageListActions');
if(!$actions.is(":visible") || $item.hasClass('PageListItemOpen')) {
// we confirm :visible so that we don't iterfere with admin themes that already
// make the PageList items visible with css hover states
$item.addClass('PageListItemHover');
$actions.css('display', 'inline').css('opacity', 0)
.animate({opacity: 1.0}, options.hoverActionFade);
}
}
function hideItem($item) {
var $actions = $item.find('.PageListActions');
$item.removeClass('PageListItemHover');
if($actions.is(":visible")) { // || $hoveredItem.hasClass('PageListItemOpen')) {
$actions.animate({opacity: 0}, options.hoverActionFade, function () {
$actions.hide();
});
}
}
$outer.on('keydown', '.PageListItem', function(e) {
// PR#1 makes page-list keyboard accessible
e = e || window.event;
if(e.keyCode == 0 || e.keyCode == 32) {
// spacebar
var $actions = $(this).find('.PageListActions');
if($actions.is(":visible")) {
$actions.css('display', 'none');
} else {
$actions.css('display', 'inline-block');
}
return false;
}
});
$outer.on('mouseover', '.PageListItem', function(e) {
if($root.is(".PageListSorting") || $root.is(".PageListSortSaving")) return;
var $a = $(this).children('a').first();
if($a.length && !$a.is(':hover')) return;
$hoveredItem = $(this);
//console.log('pageX=' + e.pageX);
//console.log('offsetX=' + $hoveredItem.offset().left);
//var maxPageX = $(this).children('.PageListNumChildren').offset().left + 100;
//if(e.pageX > maxPageX) return;
if($hoveredItem.hasClass('PageListItemHover')) return;
var $item = $(this);
if(hoverTimeout) clearTimeout(hoverTimeout);
var delay = options.hoverActionDelay;
hoverTimeout = setTimeout(function() {
if($hoveredItem.attr('class') == $item.attr('class')) {
var $a = $hoveredItem.children('a').first();
if($a.length && !$a.is(':hover')) return;
var $hideItems = $outer.find(".PageListItemHover");
showItem($hoveredItem);
$hideItems.each(function() { hideItem($(this)); });
}
}, delay);
}).on('mouseout', '.PageListItem', function(e) {
if($root.is(".PageListSorting") || $root.is(".PageListSortSaving")) return;
var $item = $(this);
if($item.hasClass('PageListItemOpen')) return;
if(!$item.hasClass('PageListItemHover')) return;
var delay = options.hoverActionDelay * 0.7;
hoverOutTimeout = setTimeout(function() {
if($item.is(":hover")) return;
if($item.attr('class') == $hoveredItem.attr('class')) return;
hideItem($item);
}, delay);
});
}
/**
* Sets up a mode where the user is given a "select" link for each page, rather than a list of actions
*
* When they hit "select" the list collapses and the selected page ID is populated into an input
*
*/
function setupSelectMode() {
var $actions = $("<ul></ul>").addClass('PageListActions PageListSelectActions actions');
var $pageLabel = $("<p></p>").addClass("PageListSelectName");
if(options.selectShowPageHeader) $pageLabel.append($loading);
var $action = $("<a></a>")
.addClass("PageListSelectActionToggle")
.addClass("PageListSelectActionToggleStart")
.attr('href', '#')
.text(options.selectStartLabel)
.on('click', function() {
if($(this).text() == options.selectStartLabel) {
loadChildren(options.rootPageID > 0 ? options.rootPageID : 1, $root, 0, true);
$(this).text(options.selectCancelLabel)
.removeClass('PageListSelectActionToggleStart').addClass('PageListSelectActionToggleCancel');
} else {
$(this).addClass('PageListSelectActionToggleStart').removeClass('PageListSelectActionToggleCancel');
$root.children(".PageList").slideUp(options.speed, function() {
$(this).remove();
});
$(this).text(options.selectStartLabel);
}
return false;
});
$actions.append($("<li></li>").append($action));
$root.append($("<div></div>").addClass('PageListSelectHeader').append($pageLabel).append($actions));
if(options.selectShowPageHeader) {
var ajaxURL = options.ajaxURL +
"?id=" + options.selectedPageID +
"&render=JSON&start=0&limit=0&lang=" + options.langID +
"&mode=" + options.mode;
if(options.labelName.length) ajaxURL += '&labelName=' + options.labelName;
$.getJSON(ajaxURL, function(data) {
var parentPath = '';
if(options.selectShowPath) {
parentPath = data.page.path;
if(parentPath.substring(-1) == '/') parentPath = parentPath.substring(0, parentPath.length-1);
parentPath = parentPath.substring(0, parentPath.lastIndexOf('/')+1);
parentPath = '<span class="detail">' + parentPath + '</span> ';
}
var label = options.selectedPageID > 0 ? parentPath + data.page.label : '';
$root.children(".PageListSelectHeader").find(".PageListSelectName").html(label);
});
}
}
/**
* Method that is triggered when the processChildren() method completes
*
*/
function loaded() {
ignoreClicks = false;
}
/**
* Handles pagination of PageList items
*
* @param int id ID of the page having children to show
* @param start Index that we are starting with in the current list
* @param int limit The limit being applied to the list (items per page)
* @param int total The total number of items in the list (excluding any limits)
* @return jQuery $list The pagination list ready for insertion
*
*/
function getPaginationList(id, start, limit, total) {
// console.log('getPaginationList(id=' + id + ', start=' + start + ", limit=" + limit + ", total=" + total + ')');
var maxPaginationLinks = 9;
var numPaginations = Math.ceil(total / limit);
curPagination = start >= limit ? Math.floor(start / limit) : 0;
if(curPagination == 0) {
firstPagination = 0;
} else if((curPagination-maxPaginationLinks+1) > firstPagination) {
firstPagination = curPagination - Math.floor(maxPaginationLinks / 2);
} else if(firstPagination > 0 && curPagination == firstPagination) {
firstPagination = curPagination - Math.ceil(maxPaginationLinks / 2);
}
// if we're on the last page of pagination links, then make the firstPagination static at the end
if(firstPagination > numPaginations - maxPaginationLinks) firstPagination = numPaginations - maxPaginationLinks;
if(firstPagination < 0) firstPagination = 0;
var $list = $("<ul></ul>").addClass(options.paginationClass).data('paginationInfo', {
start: start,
limit: limit,
total: total
});
/**
* paginationClick is the event function called when an item in the pagination nav is clicked
*
* It loads the new pages (via loadChildren) and then replaces the old pageList with the new one
*
*/
var paginationClick = function(e) {
var $curList = $(this).parents("ul." + options.paginationClass);
var info = $curList.data('paginationInfo');
if(!info) return false;
var start = parseInt($(this).attr('href')) * info.limit;
if(start === NaN) start = 0;
var $newList = getPaginationList(id, start, info.limit, info.total);
var $spinner = $(options.spinnerMarkup);
var $loading = $("<li> </li>").addClass(options.paginationDisabledClass).append($spinner.hide());
$curList.siblings(".PageList").remove(); // remove any open lists below current
$curList.replaceWith($newList);
$newList.append($loading);
$spinner.fadeIn('fast');
var $siblings = $newList.siblings().css('opacity', 0.5);
loadChildren(id, $newList.parent(), start, false, false, true, function() {
$spinner.fadeOut('fast', function() {
$loading.remove();
});
$newList.parent('.PageList').prev('.PageListItem').data('start', start);
updateOpenPageIDs();
});
return false;
}
var $separator = null;
var $blankItem = null;
for(var pagination = firstPagination, cnt = 0; pagination < numPaginations; pagination++, cnt++) {
var $a = $("<a></a>").html(pagination+1).attr('href', pagination).addClass(options.paginationLinkClass);
var $item = $("<li></li>").addClass(options.paginationClass + cnt).append($a); // .addClass('ui-state-default');
if(pagination == curPagination) {
//$item.addClass("PageListPaginationCurrent ui-state-focus");
$item.addClass(options.paginationCurrentClass).find("a")
.removeClass(options.paginationLinkClass)
.addClass(options.paginationLinkCurrentClass);
}
$list.append($item);
if(!$blankItem) {
$blankItem = $item.clone().removeClass(options.paginationCurrentClass + ' ' + options.paginationLinkCurrentClass);
$blankItem.find('a').removeClass(options.paginationLinkCurrentClass).addClass(options.paginationLinkClass);
}
// if(!$blankItem) $blankItem = $item.clone().removeClass('PageListPaginationCurrent').find('a').removeClass('ui-state-focus').addClass('ui-state-default');
if(!$separator) $separator = $blankItem.clone().removeClass(options.paginationLinkClass)
.addClass(options.paginationDisabledClass).html("…");
//if(!$separator) $separator = $blankItem.clone().html("…");
if(cnt >= maxPaginationLinks && pagination < numPaginations) {
$lastItem = $blankItem.clone();
$lastItem.find("a").text(numPaginations).attr('href', numPaginations-1);
$list.append($separator.clone()).append($lastItem);
break;
}
}
if(firstPagination > 0) {
$firstItem = $blankItem.clone();
$firstItem.find("a").text("1").attr('href', '0').on('click', paginationClick);
$list.prepend($separator.clone()).prepend($firstItem);
}
//if(curPagination+1 < maxPaginationLinks && curPagination+1 < numPaginations) {
if(curPagination+1 < numPaginations) {
$nextBtn = $blankItem.clone();
$nextBtn.find("a").html("<i class='fa fa-angle-right'></i>").attr('href', curPagination+1);
$list.append($nextBtn);
}
if(curPagination > 0) {
$prevBtn = $blankItem.clone();
$prevBtn.find("a").attr('href', curPagination-1).html("<i class='fa fa-angle-left'></i>");
$list.prepend($prevBtn);
}
$list.find("a").on('click', paginationClick)
.on('mouseenter', function() {
$(this).addClass(options.paginationHoverClass);
}).on('mouseleave', function() {
$(this).removeClass(options.paginationHoverClass);
});
return $list;
}
/**
* Load children via ajax call, attach them to $target and show.
*
* @param int id ID of the page having children to show
* @param jQuery $target Item to attach children to
* @param int start If not starting from first item, num of item to start with
* @param bool beginList Set to true if this is the first call to create the list
* @param bool pagination Set to false if you don't want pagination, otherwise leave it out
* @param bool replace Should any existing list be replaced (true) or appended (false)
*
*/
function loadChildren(id, $target, start, beginList, pagination, replace, callback) {
if(pagination == undefined) pagination = true;
if(replace == undefined) replace = false;
var processChildren = function(data) {
if(data && data.error) {
ProcessWire.alert(data.message);
$loading.hide();
ignoreClicks = false;
return;
}
var $children = listChildren($(data.children));
var nextStart = data.start + data.limit;
//var openPageKey = id + '-' + start;
if($target.hasClass('PageListItem')) {
setNumChildren($target, data.page.numChildren, data.page.numTotal);
}
if(data.page.numChildren > nextStart) {
var $a = $("<a></a>").attr('href', nextStart).data('pageId', id).text(options.moreLabel).on('click', clickMore);
$children.append($("<ul></ul>").addClass('PageListActions actions').append($("<li></li>").addClass('PageListActionMore').append($a)));
}
if(pagination && (data.page.numChildren > nextStart || data.start > 0)) {
$children.prepend(getPaginationList(id, data.start, data.limit, data.page.numChildren));
}
$children.hide();
if(beginList) {
var $listRoot;
$listRoot = listChildren($(data.page));
if(options.showRootPage) $listRoot.children(".PageListItem").addClass("PageListItemOpen");
else $listRoot.children('.PageListItem').hide().parent('.PageList').addClass('PageListRootHidden');
$listRoot.append($children);
$target.append($listRoot);
} else if($target.hasClass('PageList')) {
var $newChildren = $children.children(".PageListItem, .PageListActions");
if(replace) {
// $target.children(".PageListItem, .PageListActions").replaceWith($newChildren); // doesn't work w/jQuery 1.9+
$target.children('.PageListItem, .PageListActions').remove();
}
$target.append($newChildren);
} else {
$target.after($children);
}
if($loading.parent().is('.PageListRoot')) {
$loading.hide();
} else {
$loading.fadeOut('fast');
}
if(replace) {
$children.show();
loaded();
if(callback != undefined) callback();
$container.trigger('pageListChildrenDone', data);
} else {
$children.slideDown(options.speed, function() {
loaded();
if(callback != undefined) callback();
$container.trigger('pageListChildrenDone', data);
});
}
$children.prev('.PageListItem').data('start', data.start);
// if a pagination is requested to be opened, and it exists, then open it
/*
if(options.openPagination > 1) {
//var $a = $(".PageListPagination" + (options.openPagination-1) + ">a");
var $a = $(".PageListPagination a[href=" + (options.openPagination-1) + "]");
if($a.length > 0) {
$a.trigger('click');
options.openPagination = 0;
} else {
// last pagination link
$(".PageListPagination9 a").trigger('click');
}
}
*/
};
if(!replace) $target.append($loading.fadeIn('fast'));
var key = id + '-' + start;
if(typeof options.openPageData[key] != "undefined"
&& !$target.hasClass('PageListID7') // trash
&& !$target.hasClass('PageListForceReload')) {
processChildren(options.openPageData[key]);
return;
}
// @teppokoivula PR #1052
var ajaxURL = options.ajaxURL +
"?id=" + id +
"&render=JSON&start=" + start +
"&lang=" + options.langID +
"&open=" + options.openPageIDs[0] +
"&mode=" + options.mode;
if(options.labelName.length) ajaxURL += '&labelName=' + options.labelName;
$.getJSON(ajaxURL)
.done(function(data, textStatus, jqXHR) {
processChildren(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
processChildren({
error: 1,
message: !jqXHR.status ? options.ajaxNetworkError : options.ajaxUnknownError
});
});
// end #1052
}
/**
* Given a list of pages, generates a list of them
*
* @param jQuery $children
*
*/
function listChildren($children) {
var $list = $("<div></div>").addClass("PageList");
var $ul = $list;
$children.each(function(n, child) {
$ul.append(listChild(child));
});
addClickEvents($ul);
return $list;
}
/**
* Set a parent to reload its children on next access rather than using cached data
*
* @param $pageListItem .PageList or .PageListItem element
* @param reloadNow Reload the list now? (default=false)
*
*/
function setForceReload($pageListItem, reloadNow) {
if($pageListItem.hasClass('PageList')) $pageListItem = $pageListItem.prev('.PageListItem');
$pageListItem.addClass('PageListForceReload');
var id = $pageListItem.data('pageId');
var prefix = id + '-';
if(typeof options.openPageData != "undefined") {
// remove cached items from openPageData
var openPageData = {};
for(var key in options.openPageData) {
if(key.indexOf(prefix) === 0) {
// skip it
} else {
openPageData[key] = options.openPageData[key];
}
}
options.openPageData = openPageData;
}
if(typeof reloadNow != "undefined" && reloadNow) {
var $a = $pageListItem.children('a.PageListPage');
if($pageListItem.hasClass('PageListItemOpen')) {
$a.trigger('click');
setTimeout(function() { $a.trigger('click'); }, 250);
} else {
$a.trigger('click');
}
}
}
/**
*
* @param $ul Any element that contains items needing click events attached
*
*/
function addClickEvents($ul) {
$("a.PageListPage", $ul).on('click', clickChild);
$ul.on('click', '.PageListActionMove a', clickMove);
// $(".PageListActionMove a", $ul).on('click', clickMove);
$(".PageListActionSelect a", $ul).on('click', clickSelect);
$(".PageListTriggerOpen:not(.PageListID1) > a.PageListPage", $ul).trigger('click');
$(".PageListActionExtras > a:not(.clickExtras)", $ul).addClass('clickExtras').on('click', clickExtras);
// if(options.useHoverActions) $(".PageListActionExtras > a", $ul).on('mouseover', clickExtras);
}
/**
* Given a single page, generates the list item for it
*
* @param map child
*
*/
function listChild(child) {
var $li = $("<div></div>").data('pageId', child.id).addClass('PageListItem').addClass('PageListTemplate_' + child.template);
var $a = $("<a></a>")
.attr('href', '#')
.attr('title', child.path)
.html(child.label)
.addClass('PageListPage label');
$li.addClass(child.numChildren > 0 ? 'PageListHasChildren' : 'PageListNoChildren').addClass('PageListID' + child.id);
if(child.status == 0) $li.addClass('PageListStatusOff disabled');
if(child.status & 2048) $li.addClass('PageListStatusUnpublished secondary');
if(child.status & 1024) $li.addClass('PageListStatusHidden secondary');
if(child.status & 512) $li.addClass('PageListStatusTemp secondary'); // typically combined with PageListStatusUnpublished
if(child.status & 16) $li.addClass('PageListStatusSystem');
if(child.status & 8) $li.addClass('PageListStatusSystem');
if(child.status & 4) $li.addClass('PageListStatusLocked');
if(child.addClass && child.addClass.length) $li.addClass(child.addClass);
if(child.type && child.type.length > 0) if(child.type == 'System') $li.addClass('PageListStatusSystem');
$(options.openPageIDs).each(function(n, id) {
id = parseInt(id);
if(child.id == id) $li.addClass('PageListTriggerOpen');
});
$li.append($a);
setNumChildren($li, child.numChildren, child.numTotal, true);
if(child.note && child.note.length) $li.append($("<span>" + child.note + "</span>").addClass('PageListNote detail'));
var $actions = $("<ul></ul>").addClass('PageListActions actions');
var links = options.rootPageID == child.id ? [] : [{ name: options.selectSelectLabel, url: options.selectSelectHref }];
if(options.mode == 'actions') {
links = child.actions;
} else if(options.selectAllowUnselect) {
if(child.id == $container.val()) links = [{ name: options.selectUnselectLabel, url: options.selectUnselectHref }];
}
var $lastAction = null;
var $extrasLink = null; // link that toggles extra actions
var extras = {}; // extra actions
var hasExtrasLink = false; // only referenced if options.useNarrowActions
if(options.useNarrowActions) {
for(var n = 0; n < links.length; n++) {
if(typeof links[n].extras != "undefined") hasExtrasLink = true;
}
}
$(links).each(function(n, action) {
var actionName;
if(action.name == options.selectSelectLabel) {
actionName = 'Select';
} else if(action.name == options.selectUnselectLabel) {
actionName = 'Select';
} else {
actionName = action.cn; // cn = className
if(options.useNarrowActions && hasExtrasLink
&& (actionName != 'Edit' && actionName != 'View' && actionName != 'Extras')) {
// move non-edit/view actions to extras when in narrow mode
extras[actionName] = action;
return;
}
}
var $a = $("<a></a>").html(action.name).attr('href', action.url);
if(!isModal) {
if(action.cn == 'Edit') {
$a.addClass('pw-modal pw-modal-large pw-modal-longclick');
$a.attr('data-buttons', '#ProcessPageEdit > .Inputfields > .InputfieldSubmit .ui-button');
} else if(action.cn == 'View') {
$a.addClass('pw-modal pw-modal-large pw-modal-longclick');
}
}
if(typeof action.extras != "undefined") {
for(var key in action.extras) {
extras[key] = action.extras[key];
}
$extrasLink = $a;
}
var $action = $("<li></li>").addClass('PageListAction' + actionName).append($a);
if(actionName == 'Extras') $lastAction = $action;
else $actions.append($action);
});
if($extrasLink) $extrasLink.data('extras', extras);
if($lastAction) {
$actions.append($lastAction);
$lastAction.addClass('ui-priority-secondary');
}
$li.append($actions);
return $li;
}
/**
* Get number of children for given .PageListItem
*
*/
function getNumChildren($item, getTotal) {
if(typeof getTotal == "undefined") getTotal = false;
var n;
if(getTotal) {
n = $item.attr('data-numTotal');
} else {
n = $item.attr('data-numChild');
}
return n && n.length > 0 ? parseInt(n) : 0;
}
function getNumTotal($item) {
return getNumChildren($item, true);
}
/**
* Set number of children for given PageListItem
*
*/
function setNumChildren($item, numChildren, numTotal, addNew) {
if(typeof numTotal == "undefined") numTotal = numChildren;
if(typeof addNew == "undefined") addNew = false;
var $numChildren = addNew ? '' : $item.children('.PageListNumChildren');
var n = numChildren === false ? numTotal : numChildren;
if(addNew || !$numChildren.length) {
$numChildren = $('<span></span>').addClass('PageListNumChildren detail');
addNew = true;
}
if(n < 1) {
$item.removeClass('PageListHasChildren').addClass('PageListNoChildren');
if(numTotal !== false) numTotal = 0;
} else {
$item.removeClass('PageListNoChildren').addClass('PageListHasChildren');
}
if(numTotal === false) {
numTotal = getNumTotal($item);
} else {
$item.attr('data-numTotal', numTotal);
}
if(numChildren === false) {
numChildren = getNumChildren($item);
} else {
if(numChildren < 0) numChildren = 0;
$item.attr('data-numChild', numChildren);
}
var numLabel = '';
var slash;
switch(options.qtyType) {
case 'total':
numLabel = numTotal;
break;
case 'total/children':
slash = "<span class='ui-priority-secondary'>/</span>";
numLabel = numTotal > 0 && numTotal != numChildren ? numTotal + slash + numChildren : numTotal;
break;
case 'children/total':
slash = "<span class='ui-priority-secondary'>/</span>";
numLabel = numTotal > 0 && numTotal != numChildren ? numChildren + slash + numTotal : numTotal;
break;
case 'id':
numLabel = $item.data('pageId');
break;
default:
numLabel = numChildren;
}
if(!numLabel) numLabel = '';
$numChildren.html(numLabel);
if(addNew) $item.append($numChildren);
}
/**
* Set total/descendants
*
*/
function setNumTotal($item, numTotal) {
setNumChildren($item, false, numTotal);
}
/**
* Recursively adjust total/descendants number up the tree by given amount (n)
*
*/
function adjustNumTotal($item, n) {
var numTotal = getNumTotal($item);
numTotal += n;
if(numTotal < 0) numTotal = 0;
setNumTotal($item, numTotal);
var $parentItem = $item.closest('.PageList').prev('.PageListItem');
if($parentItem.length) adjustNumTotal($parentItem, n);
}
/**
* Extra actions button click handler
*
*/
function clickExtras(e) {
var $a = $(this);
var extras = $a.data('extras');
if(typeof extras == "undefined") return false;
var $li = $a.closest('.PageListItem');
var $actions = $a.closest('.PageListActions');
var $lastItem = null;
var $icon = $a.children('i.fa');
var $extraActions = $actions.find("li.PageListActionExtra");
/*
if($extraActions.length && e.type != 'click') {
// mouseover only opens, but a click is required to close
return;
}
*/
$icon.toggleClass('fa-flip-horizontal');
if($extraActions.length) {
$extraActions.fadeOut(100, function() {
$extraActions.remove();
});
return false;
}
for(var extraKey in extras) {
var extra = extras[extraKey];
var $extraLink = $("<a />")
.addClass('PageListActionExtra PageListAction' + extra.cn)
.attr('href', extra.url)
.html(extra.name);
/*
if(extra.cn == 'Trash') {
// handler for trash action
$extraLink.on('click', function() {
trashPage($li);
return false;
});
} else
*/
if(typeof extra.ajax != "undefined" && extra.ajax == true) {
// ajax action
$extraLink.on('click', function () {
$li.find('.PageListActions').hide();
var $spinner = $(options.spinnerMarkup);
var href = $(this).attr('href');
var actionName = href.match(/[\?&]action=([-_a-zA-Z0-9]+)/)[1];
var pageID = parseInt(href.match(/[\?&]id=([0-9]+)/)[1]);
var tokenName = $("#PageListContainer").attr('data-token-name');
var tokenValue = $("#PageListContainer").attr('data-token-value');
var postData = {
action: actionName,
id: pageID,
};
postData[tokenName] = tokenValue;
$li.append($spinner);
$.post(href + '&render=json', postData, function (data) {
if (data.success) {
$li.fadeOut('fast', function() {
var addNew = false;
var removeItem = data.remove;
var refreshChildren = data.refreshChildren;
var $liNew = false;
if(typeof data.child != "undefined") {
// prepare update existing item
$liNew = listChild(data.child);
} else if(typeof data.newChild != "undefined") {
// prepare append new item
$liNew = listChild(data.newChild);
addNew = true;
}
// display a message for a second to let them know what was done