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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
|
/**
* @file
* Some basic behaviors and utility functions for Views UI.
*/
(function ($, Drupal, drupalSettings) {
/**
* @namespace
*/
Drupal.viewsUi = {};
/**
* Improve the user experience of the views edit interface.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches toggling of SQL rewrite warning on the corresponding checkbox.
*/
Drupal.behaviors.viewsUiEditView = {
attach() {
// Only show the SQL rewrite warning when the user has chosen the
// corresponding checkbox.
$('[data-drupal-selector="edit-query-options-disable-sql-rewrite"]').on(
'click',
() => {
$('.sql-rewrite-warning').toggleClass('js-hide');
},
);
},
};
/**
* In the add view wizard, use the view name to prepopulate form fields such
* as page title and menu link.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches behavior for prepopulating page title and menu links, based on
* view name.
*/
Drupal.behaviors.viewsUiAddView = {
attach(context) {
const $context = $(context);
// Set up regular expressions to allow only numbers, letters, and dashes.
const exclude = new RegExp('[^a-z0-9\\-]+', 'g');
const replace = '-';
let suffix;
// The page title, block title, and menu link fields can all be
// prepopulated with the view name - no regular expression needed.
const $fields = $context.find(
'[id^="edit-page-title"], [id^="edit-block-title"], [id^="edit-page-link-properties-title"]',
);
if ($fields.length) {
if (!this.fieldsFiller) {
this.fieldsFiller = new Drupal.viewsUi.FormFieldFiller($fields);
} else {
// After an AJAX response, this.fieldsFiller will still have event
// handlers bound to the old version of the form fields (which don't
// exist anymore). The event handlers need to be unbound and then
// rebound to the new markup. Note that jQuery.live is difficult to
// make work in this case because the IDs of the form fields change
// on every AJAX response.
this.fieldsFiller.rebind($fields);
}
}
// Prepopulate the path field with a URLified version of the view name.
const $pathField = $context.find('[id^="edit-page-path"]');
if ($pathField.length) {
if (!this.pathFiller) {
this.pathFiller = new Drupal.viewsUi.FormFieldFiller(
$pathField,
exclude,
replace,
);
} else {
this.pathFiller.rebind($pathField);
}
}
// Populate the RSS feed field with a URLified version of the view name,
// and an .xml suffix (to make it unique).
const $feedField = $context.find(
'[id^="edit-page-feed-properties-path"]',
);
if ($feedField.length) {
if (!this.feedFiller) {
suffix = '.xml';
this.feedFiller = new Drupal.viewsUi.FormFieldFiller(
$feedField,
exclude,
replace,
suffix,
);
} else {
this.feedFiller.rebind($feedField);
}
}
},
};
/**
* Constructor for the {@link Drupal.viewsUi.FormFieldFiller} object.
*
* Prepopulates a form field based on the view name.
*
* @constructor
*
* @param {jQuery} $target
* A jQuery object representing the form field or fields to prepopulate.
* @param {boolean} [exclude=false]
* A regular expression representing characters to exclude from
* the target field.
* @param {string} [replace='']
* A string to use as the replacement value for disallowed characters.
* @param {string} [suffix='']
* A suffix to append at the end of the target field content.
*/
Drupal.viewsUi.FormFieldFiller = function (
$target,
exclude,
replace,
suffix,
) {
/**
*
* @type {jQuery}
*/
this.source = $('#edit-label');
/**
*
* @type {jQuery}
*/
this.target = $target;
/**
*
* @type {boolean}
*/
this.exclude = exclude || false;
/**
*
* @type {string}
*/
this.replace = replace || '';
/**
*
* @type {string}
*/
this.suffix = suffix || '';
// Create bound versions of this instance's object methods to use as event
// handlers. This will let us easily unbind those specific handlers later
// on.
const self = this;
/**
* Populate the target form field with the altered source field value.
*
* @return {*}
* The result of the _populate call, which should be undefined.
*/
this.populate = function () {
return self._populate.call(self);
};
/**
* Stop prepopulating the form fields.
*
* @return {*}
* The result of the _unbind call, which should be undefined.
*/
this.unbind = function () {
return self._unbind.call(self);
};
this.bind();
// Object constructor; no return value.
};
$.extend(
Drupal.viewsUi.FormFieldFiller.prototype,
/** @lends Drupal.viewsUi.FormFieldFiller# */ {
/**
* Bind the form-filling behavior.
*/
bind() {
this.unbind();
// Populate the form field when the source changes.
this.source.on('keyup.viewsUi change.viewsUi', this.populate);
// Quit populating the field as soon as it gets focus.
this.target.on('focus.viewsUi', this.unbind);
},
/**
* Get the source form field value as altered by the passed-in parameters.
*
* @return {string}
* The source form field value.
*/
getTransliterated() {
let from = this.source.length ? this.source[0].value : '';
if (this.exclude) {
from = from.toLowerCase().replace(this.exclude, this.replace);
}
return from;
},
/**
* Populate the target form field with the altered source field value.
*/
_populate() {
const transliterated = this.getTransliterated();
const suffix = this.suffix;
this.target.each(function (i) {
// Ensure that the maxlength is not exceeded by prepopulating the field.
const maxlength = $(this).attr('maxlength') - suffix.length;
this.value = transliterated.substring(0, maxlength) + suffix;
});
},
/**
* Stop prepopulating the form fields.
*/
_unbind() {
this.source.off('keyup.viewsUi change.viewsUi', this.populate);
this.target.off('focus.viewsUi', this.unbind);
},
/**
* Bind event handlers to new form fields, after they're replaced via Ajax.
*
* @param {jQuery} $fields
* Fields to rebind functionality to.
*/
rebind($fields) {
this.target = $fields;
this.bind();
},
},
);
/**
* Adds functionality for the add item form.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the functionality in {@link Drupal.viewsUi.AddItemForm} to the
* forms in question.
*/
Drupal.behaviors.addItemForm = {
attach(context) {
const $context = $(context);
let $form = $context;
// The add handler form may have an id of views-ui-add-handler-form--n.
if (
!(
context instanceof HTMLElement &&
context.matches('form[id^="views-ui-add-handler-form"]')
)
) {
$form = $context.find('form[id^="views-ui-add-handler-form"]');
}
if (once('views-ui-add-handler-form', $form).length) {
// If we have an unprocessed views-ui-add-handler-form, let's
// instantiate.
new Drupal.viewsUi.AddItemForm($form);
}
},
};
/**
* Constructs a new AddItemForm.
*
* @constructor
*
* @param {jQuery} $form
* The form element used.
*/
Drupal.viewsUi.AddItemForm = function ($form) {
/**
*
* @type {jQuery}
*/
this.$form = $form;
this.$form
.find('.views-filterable-options :checkbox')
.on('click', this.handleCheck.bind(this));
/**
* Find the wrapper of the displayed text.
*/
this.$selected_div = this.$form.find('.views-selected-options').parent();
this.$selected_div.hide();
/**
*
* @type {Array}
*/
this.checkedItems = [];
};
/**
* Handles a checkbox check.
*
* @param {jQuery.Event} event
* The event triggered.
*/
Drupal.viewsUi.AddItemForm.prototype.handleCheck = function (event) {
const $target = $(event.target);
const label = $target.closest('td').next().html().trim();
// Add/remove the checked item to the list.
if (event.target.checked) {
this.$selected_div.show();
this.$selected_div[0].style.display = 'block';
this.checkedItems.push(label);
} else {
const position = $.inArray(label, this.checkedItems);
// Delete the item from the list and make sure that the list doesn't have
// undefined items left.
for (let i = 0; i < this.checkedItems.length; i++) {
if (i === position) {
this.checkedItems.splice(i, 1);
i--;
break;
}
}
// Hide it again if none item is selected.
if (this.checkedItems.length === 0) {
this.$selected_div.hide();
}
}
this.refreshCheckedItems();
};
/**
* Refresh the display of the checked items.
*/
Drupal.viewsUi.AddItemForm.prototype.refreshCheckedItems = function () {
// Perhaps we should precache the text div, too.
this.$selected_div
.find('.views-selected-options')
.html(this.checkedItems.join(', '));
this.$selected_div
?.get(0)
?.dispatchEvent(
new CustomEvent('dialogContentResize', { bubbles: true }),
);
};
/**
* The input field items that add displays must be rendered as `<input>`
* elements. The following behavior detaches the `<input>` elements from the
* DOM, wraps them in an unordered list, then appends them to the list of
* tabs.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Fixes the input elements needed.
*/
Drupal.behaviors.viewsUiRenderAddViewButton = {
attach(context) {
// Build the add display menu and pull the display input buttons into it.
const menu = once(
'views-ui-render-add-view-button',
'#views-display-menu-tabs',
context,
);
if (!menu.length) {
return;
}
const $menu = $(menu);
const $addDisplayDropdown = $(
`<li class="add"><a href="#"><span class="icon add"></span>${Drupal.t(
'Add',
)}</a><ul class="action-list" style="display:none;"></ul></li>`,
);
const $displayButtons = $menu.nextAll('input.add-display').detach();
$displayButtons
.appendTo($addDisplayDropdown.find('.action-list'))
.wrap('<li>')
.parent()
.eq(0)
.addClass('first')
.end()
.eq(-1)
.addClass('last');
$displayButtons.each(function () {
const $this = $(this);
this.value = $this.attr('data-drupal-dropdown-label');
});
$addDisplayDropdown.appendTo($menu);
// Add the click handler for the add display button.
$menu.find('li.add > a').on('click', function (event) {
event.preventDefault();
const $trigger = $(this);
Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
});
// Add a mouseleave handler to close the dropdown when the user mouses
// away from the item. We use mouseleave instead of mouseout because
// the user is going to trigger mouseout when moving away from the trigger
// link to the sub menu items.
// We use the live binder because the open class on this item will be
// toggled on and off and we want the handler to take effect in the cases
// that the class is present, but not when it isn't.
$('li.add', $menu).on('mouseleave', function (event) {
const $this = $(this);
const $trigger = $this.children('a[href="#"]');
if (Drupal.elementIsVisible($this.children('.action-list')[0])) {
Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
}
});
},
};
/**
* Toggle menu visibility.
*
* @param {jQuery} $trigger
* The element where the toggle was triggered.
*
*
* @note [@jessebeach] I feel like the following should be a more generic
* function and not written specifically for this UI, but I'm not sure
* where to put it.
*/
Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu = function ($trigger) {
$trigger.parent().toggleClass('open');
$trigger.next().slideToggle('fast');
};
/**
* Add search options to the views ui.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches {@link Drupal.viewsUi.OptionsSearch} to the views ui filter
* options.
*/
Drupal.behaviors.viewsUiSearchOptions = {
attach(context) {
const $context = $(context);
let $form = $context;
// The add handler form may have an id of views-ui-add-handler-form--n.
if (
!(
context instanceof HTMLElement &&
context.matches('form[id^="views-ui-add-handler-form"]')
)
) {
$form = $context.find('form[id^="views-ui-add-handler-form"]');
}
// Make sure we don't add more than one event handler to the same form.
if (once('views-ui-filter-options', $form).length) {
new Drupal.viewsUi.OptionsSearch($form);
}
},
};
/**
* Constructor for the viewsUi.OptionsSearch object.
*
* The OptionsSearch object filters the available options on a form according
* to the user's search term. Typing in "taxonomy" will show only those
* options containing "taxonomy" in their label.
*
* @constructor
*
* @param {jQuery} $form
* The form element.
*/
Drupal.viewsUi.OptionsSearch = function ($form) {
/**
*
* @type {jQuery}
*/
this.$form = $form;
// Click on the title checks the box.
this.$form.on('click', 'td.title', (event) => {
const $target = $(event.currentTarget);
$target.closest('tr').find('input').trigger('click');
});
const searchBoxSelector =
'[data-drupal-selector="edit-override-controls-options-search"]';
const controlGroupSelector =
'[data-drupal-selector="edit-override-controls-group"]';
this.$form.on(
'formUpdated',
`${searchBoxSelector},${controlGroupSelector}`,
this.handleFilter.bind(this),
);
this.$searchBox = this.$form.find(searchBoxSelector);
this.$controlGroup = this.$form.find(controlGroupSelector);
/**
* Get a list of option labels and their corresponding divs and maintain it
* in memory, so we have as little overhead as possible at keyup time.
*/
this.options = this.getOptions(this.$form.find('.filterable-option'));
// Trap the ENTER key in the search box so that it doesn't submit the form.
this.$searchBox.on('keypress', (event) => {
if (event.which === 13) {
event.preventDefault();
}
});
};
$.extend(
Drupal.viewsUi.OptionsSearch.prototype,
/** @lends Drupal.viewsUi.OptionsSearch# */ {
/**
* Assemble a list of all the filterable options on the form.
*
* @param {jQuery} $allOptions
* A jQuery object representing the rows of filterable options to be
* shown and hidden depending on the user's search terms.
*
* @return {Array}
* An array of all the filterable options.
*/
getOptions($allOptions) {
let $title;
let $description;
let $option;
const options = [];
const length = $allOptions.length;
for (let i = 0; i < length; i++) {
$option = $($allOptions[i]);
$title = $option.find('.title');
$description = $option.find('.description');
options[i] = {
// Search on the lowercase version of the title text + description.
searchText: `${$title[0].textContent.toLowerCase()} ${$description[0].textContent.toLowerCase()}
.toLowerCase()}`,
// Maintain a reference to the jQuery object for each row, so we don't
// have to create a new object inside the performance-sensitive keyup
// handler.
$div: $option,
};
}
return options;
},
/**
* Filter handler for the search box and type select that hides or shows the relevant
* options.
*
* @param {jQuery.Event} event
* The formUpdated event.
*/
handleFilter(event) {
// Determine the user's search query. The search text has been converted
// to lowercase.
const search = this.$searchBox[0].value.toLowerCase();
const words = search.split(' ');
// Get selected Group
const group = this.$controlGroup[0].value;
// Search through the search texts in the form for matching text.
this.options.forEach((option) => {
function hasWord(word) {
return option.searchText.includes(word);
}
let found = true;
// Each word in the search string has to match the item in order for the
// item to be shown.
if (search) {
found = words.every(hasWord);
}
if (found && group !== 'all') {
found = option.$div.hasClass(group);
}
option.$div.toggle(found);
});
// Adapt dialog to content size.
event.target?.dispatchEvent(
new CustomEvent('dialogContentResize', { bubbles: true }),
);
},
},
);
/**
* Preview functionality in the views edit form.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the preview functionality to the view edit form.
*/
Drupal.behaviors.viewsUiPreview = {
attach(context) {
// Only act on the edit view form.
const $contextualFiltersBucket = $(context).find(
'.views-display-column .views-ui-display-tab-bucket.argument',
);
if ($contextualFiltersBucket.length === 0) {
return;
}
// If the display has no contextual filters, hide the form where you
// enter the contextual filters for the live preview. If it has contextual
// filters, show the form.
const $contextualFilters = $contextualFiltersBucket.find(
'.views-display-setting a',
);
if ($contextualFilters.length) {
$('#preview-args').parent().show();
} else {
$('#preview-args').parent().hide();
}
// Executes an initial preview.
const $livePreview = $(
once('edit-displays-live-preview', '#edit-displays-live-preview'),
);
if ($livePreview.length && $livePreview[0].checked) {
$(once('edit-displays-live-preview', '#preview-submit')).trigger(
'click',
);
}
},
};
/**
* Improve the UI of the rearrange filters dialog box.
*
* @constructor
*
* @param {jQuery} $table
* The table in the filter form.
* @param {jQuery} $operator
* The filter groups operator element.
*/
Drupal.viewsUi.RearrangeFilterHandler = function ($table, $operator) {
/**
* Keep a reference to the `<table>` being altered and to the div containing
* the filter groups operator dropdown (if it exists).
*/
this.table = $table;
/**
*
* @type {jQuery}
*/
this.operator = $operator;
/**
*
* @type {boolean}
*/
this.hasGroupOperator = this.operator.length > 0;
/**
* Keep a reference to all draggable rows within the table.
*
* @type {jQuery}
*/
this.draggableRows = $table.find('.draggable');
/**
* Keep a reference to the buttons for adding and removing filter groups.
*
* @type {jQuery}
*/
this.addGroupButton = $('#views-add-group');
/**
* @type {jQuery}
*/
this.removeGroupButtons = $table.find('.views-remove-group');
// Add links that duplicate the functionality of the (hidden) add and remove
// buttons.
this.insertAddRemoveFilterGroupLinks();
// When there is a filter groups operator dropdown on the page, create
// duplicates of the dropdown between each pair of filter groups.
if (this.hasGroupOperator) {
/**
* @type {jQuery}
*/
this.dropdowns = this.duplicateGroupsOperator();
this.syncGroupsOperators();
}
// Add methods to the tableDrag instance to account for operator cells
// (which span multiple rows), the operator labels next to each filter
// (e.g., "And" or "Or"), the filter groups, and other special aspects of
// this tableDrag instance.
this.modifyTableDrag();
// Initialize the operator labels (e.g., "And" or "Or") that are displayed
// next to the filters in each group, and bind a handler so that they change
// based on the values of the operator dropdown within that group.
this.redrawOperatorLabels();
$(
once(
'views-rearrange-filter-handler',
$table.find('.views-group-title select'),
),
).on(
'change.views-rearrange-filter-handler',
this.redrawOperatorLabels.bind(this),
);
// Bind handlers so that when a "Remove" link is clicked, we:
// - Update the rowspans of cells containing an operator dropdown (since
// they need to change to reflect the number of rows in each group).
// - Redraw the operator labels next to the filters in the group (since the
// filter that is currently displayed last in each group is not supposed
// to have a label display next to it).
$(
once(
'views-rearrange-filter-handler',
$table.find('a.views-groups-remove-link'),
),
)
.on(
'click.views-rearrange-filter-handler',
this.updateRowspans.bind(this),
)
.on(
'click.views-rearrange-filter-handler',
this.redrawOperatorLabels.bind(this),
);
};
$.extend(
Drupal.viewsUi.RearrangeFilterHandler.prototype,
/** @lends Drupal.viewsUi.RearrangeFilterHandler# */ {
/**
* Insert links that allow filter groups to be added and removed.
*/
insertAddRemoveFilterGroupLinks() {
// Insert a link for adding a new group at the top of the page, and make
// it match the action link styling used in a typical page.html.twig.
// Since Drupal does not provide a theme function for this markup this is
// the best we can do.
$(
once(
'views-rearrange-filter-handler',
// When the link is clicked, dynamically click the hidden form
// button for adding a new filter group.
$(
`<ul class="action-links"><li><a id="views-add-group-link" href="#">${this.addGroupButton[0].value}</a></li></ul>`,
).prependTo(this.table.parent()),
),
)
.find('#views-add-group-link')
.on(
'click.views-rearrange-filter-handler',
this.clickAddGroupButton.bind(this),
);
// Find each (visually hidden) button for removing a filter group and
// insert a link next to it.
const length = this.removeGroupButtons.length;
let i;
for (i = 0; i < length; i++) {
const $removeGroupButton = $(this.removeGroupButtons[i]);
const buttonId = $removeGroupButton.attr('id');
$(
once(
'views-rearrange-filter-handler',
// When the link is clicked, dynamically click the corresponding form
// button.
$(
`<a href="#" class="views-remove-group-link">${Drupal.t(
'Remove group',
)}</a>`,
).insertBefore($removeGroupButton),
),
).on(
'click.views-rearrange-filter-handler',
{ buttonId },
this.clickRemoveGroupButton.bind(this),
);
}
},
/**
* Dynamically click the button that adds a new filter group.
*
* @param {jQuery.Event} event
* The event triggered.
*/
clickAddGroupButton(event) {
this.addGroupButton.trigger('mousedown');
event.preventDefault();
},
/**
* Dynamically click a button for removing a filter group.
*
* @param {jQuery.Event} event
* Event being triggered, with event.data.buttonId set to the ID of the
* form button that should be clicked.
*/
clickRemoveGroupButton(event) {
this.table.find(`#${event.data.buttonId}`).trigger('mousedown');
event.preventDefault();
},
/**
* Move the groups operator so that it's between the first two groups, and
* duplicate it between any subsequent groups.
*
* @return {jQuery}
* An operator element.
*/
duplicateGroupsOperator() {
let newRow;
let titleRow;
const titleRows = once(
'duplicateGroupsOperator',
'tr.views-group-title',
);
if (!titleRows.length) {
return this.operator;
}
// Get rid of the explanatory text around the operator; its placement is
// explanatory enough.
this.operator
.find('label')
.add('div.description')
.addClass('visually-hidden');
this.operator.find('select').addClass('form-select');
// Keep a list of the operator dropdowns, so we can sync their behavior
// later.
const dropdowns = this.operator;
// Move the operator to a new row just above the second group.
titleRow = $('tr#views-group-title-2');
newRow = $(
'<tr class="filter-group-operator-row"><td colspan="5"></td></tr>',
);
newRow.find('td').append(this.operator);
newRow.insertBefore(titleRow);
const length = titleRows.length;
// Starting with the third group, copy the operator to a new row above the
// group title.
for (let i = 2; i < length; i++) {
titleRow = $(titleRows[i]);
// Make a copy of the operator dropdown and put it in a new table row.
const fakeOperator = this.operator.clone();
fakeOperator.attr('id', '');
newRow = $(
'<tr class="filter-group-operator-row"><td colspan="5"></td></tr>',
);
newRow.find('td').append(fakeOperator);
newRow.insertBefore(titleRow);
dropdowns.add(fakeOperator);
}
return dropdowns;
},
/**
* Make the duplicated groups operators change in sync with each other.
*/
syncGroupsOperators() {
if (this.dropdowns.length < 2) {
// We only have one dropdown (or none at all), so there's nothing to
// sync.
return;
}
this.dropdowns.on('change', this.operatorChangeHandler.bind(this));
},
/**
* Click handler for the operators that appear between filter groups.
*
* Forces all operator dropdowns to have the same value.
*
* @param {jQuery.Event} event
* The event triggered.
*/
operatorChangeHandler(event) {
const $target = $(event.target);
const operators = this.dropdowns.find('select').not($target);
// Change the other operators to match this new value.
operators.each(function (index, item) {
item.value = $target[0].value;
});
},
/**
* @method
*/
modifyTableDrag() {
const tableDrag = Drupal.tableDrag['views-rearrange-filters'];
const filterHandler = this;
/**
* Override the row.onSwap method from tabledrag.js.
*
* When a row is dragged to another place in the table, several things
* need to occur.
* - The row needs to be moved so that it's within one of the filter
* groups.
* - The operator cells that span multiple rows need their rowspan
* attributes updated to reflect the number of rows in each group.
* - The operator labels that are displayed next to each filter need to
* be redrawn, to account for the row's new location.
*/
tableDrag.row.prototype.onSwap = function () {
if (filterHandler.hasGroupOperator) {
// Make sure the row that just got moved (this.group) is inside one
// of the filter groups (i.e. below an empty marker row or a
// draggable). If it isn't, move it down one.
const thisRow = $(this.group);
const previousRow = thisRow.prev('tr');
if (
previousRow.length &&
!previousRow.hasClass('group-message') &&
!previousRow.hasClass('draggable')
) {
// Move the dragged row down one.
const next = thisRow.next();
if (next[0].tagName === 'TR') {
this.swap('after', next);
}
}
filterHandler.updateRowspans();
}
// Redraw the operator labels that are displayed next to each filter, to
// account for the row's new location.
filterHandler.redrawOperatorLabels();
};
/**
* Override the onDrop method from tabledrag.js.
*/
tableDrag.onDrop = function () {
// If the tabledrag change marker (i.e., the "*") has been inserted
// inside a row after the operator label (i.e., "And" or "Or")
// rearrange the items so the operator label continues to appear last.
const changeMarker = $(this.oldRowElement).find('.tabledrag-changed');
if (changeMarker.length) {
// Search for occurrences of the operator label before the change
// marker, and reverse them.
const operatorLabel = changeMarker.prevAll('.views-operator-label');
if (operatorLabel.length) {
operatorLabel.insertAfter(changeMarker);
}
}
// Make sure the "group" dropdown is properly updated when rows are
// dragged into an empty filter group. This is borrowed heavily from
// the block.js implementation of tableDrag.onDrop().
const groupRow = $(this.rowObject.element)
.prevAll('tr.group-message')
.get(0);
const groupName = groupRow.className.replace(
/([^ ]+[ ]+)*group-([^ ]+)-message([ ]+[^ ]+)*/,
'$2',
);
const groupField = $(
'select.views-group-select',
this.rowObject.element,
);
if (!groupField[0].matches(`.views-group-select-${groupName}`)) {
const oldGroupName = groupField
.attr('class')
.replace(
/([^ ]+[ ]+)*views-group-select-([^ ]+)([ ]+[^ ]+)*/,
'$2',
);
groupField
.removeClass(`views-group-select-${oldGroupName}`)
.addClass(`views-group-select-${groupName}`);
groupField[0].value = groupName;
}
};
},
/**
* Redraw the operator labels that are displayed next to each filter.
*/
redrawOperatorLabels() {
for (let i = 0; i < this.draggableRows.length; i++) {
// Within the row, the operator labels are displayed inside the first
// table cell (next to the filter name).
const $draggableRow = $(this.draggableRows[i]);
const $firstCell = $draggableRow.find('td').eq(0);
if ($firstCell.length) {
// The value of the operator label ("And" or "Or") is taken from the
// first operator dropdown we encounter, going backwards from the
// current row. This dropdown is the one associated with the current
// row's filter group.
const operatorValue = $draggableRow
.prevAll('.views-group-title')
.find('option:selected')
.html();
const operatorLabel = `<span class="views-operator-label">${operatorValue}</span>`;
// If the next visible row after this one is a draggable filter row,
// display the operator label next to the current row. (Checking for
// visibility is necessary here since the "Remove" links hide the
// removed row but don't actually remove it from the document).
const $nextRow = $draggableRow.nextAll(':visible').eq(0);
const $existingOperatorLabel = $firstCell.find(
'.views-operator-label',
);
if ($nextRow.hasClass('draggable')) {
// If an operator label was already there, replace it with the new
// one.
if ($existingOperatorLabel.length) {
$existingOperatorLabel.replaceWith(operatorLabel);
}
// Otherwise, append the operator label to the end of the table
// cell.
else {
$firstCell.append(operatorLabel);
}
}
// If the next row doesn't contain a filter, then this is the last row
// in the group. We don't want to display the operator there (since
// operators should only display between two related filters, e.g.
// "filter1 AND filter2 AND filter3"). So we remove any existing label
// that this row has.
else {
$existingOperatorLabel.remove();
}
}
}
},
/**
* Update the rowspan attribute of each cell containing an operator
* dropdown.
*/
updateRowspans() {
let $row;
let $currentEmptyRow;
let draggableCount;
let $operatorCell;
const rows = $(this.table).find('tr');
const length = rows.length;
for (let i = 0; i < length; i++) {
$row = $(rows[i]);
if ($row.hasClass('views-group-title')) {
// This row is a title row.
// Keep a reference to the cell containing the dropdown operator.
$operatorCell = $row.find('td.group-operator');
// Assume this filter group is empty, until we find otherwise.
draggableCount = 0;
$currentEmptyRow = $row.next('tr');
$currentEmptyRow
.removeClass('group-populated')
.addClass('group-empty');
// The cell with the dropdown operator should span the title row and
// the "this group is empty" row.
$operatorCell.attr('rowspan', 2);
} else if (
$row.hasClass('draggable') &&
Drupal.elementIsVisible(rows[i])
) {
// We've found a visible filter row, so we now know the group isn't
// empty.
draggableCount++;
$currentEmptyRow
.removeClass('group-empty')
.addClass('group-populated');
// The operator cell should span all draggable rows, plus the title.
$operatorCell.attr('rowspan', draggableCount + 1);
}
}
},
},
);
/**
* Add a select all checkbox, which checks each checkbox at once.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches select all functionality to the views filter form.
*/
Drupal.behaviors.viewsFilterConfigSelectAll = {
attach(context) {
const selectAll = once(
'filterConfigSelectAll',
'.js-form-item-options-value-all',
context,
);
if (selectAll.length) {
const $selectAll = $(selectAll);
const $selectAllCheckbox = $selectAll.find('input[type=checkbox]');
const $checkboxes = $selectAll
.closest('.form-checkboxes')
.find(
'.js-form-type-checkbox:not(.js-form-item-options-value-all) input[type="checkbox"]',
);
// Show the select all checkbox.
$selectAll.show();
$selectAllCheckbox.on('click', function () {
// Update all checkbox beside the select all checkbox.
$checkboxes.prop('checked', this.checked);
});
// Uncheck the select all checkbox if any of the others are unchecked.
$checkboxes.on('click', function () {
if (this.checked === false) {
$selectAllCheckbox.prop('checked', false);
}
});
}
},
};
/**
* Remove icon class from elements that are themed as buttons or dropbuttons.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Removes the icon class from certain views elements.
*/
Drupal.behaviors.viewsRemoveIconClass = {
attach(context) {
$(once('dropbutton-icon', '.dropbutton', context))
.find('.icon')
.removeClass('icon');
},
};
/**
* Change "Expose filter" buttons into checkboxes.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Changes buttons into checkboxes via {@link Drupal.viewsUi.Checkboxifier}.
*/
Drupal.behaviors.viewsUiCheckboxify = {
attach(context, settings) {
const buttons = once(
'views-ui-checkboxify',
'[data-drupal-selector="edit-options-expose-button-button"], [data-drupal-selector="edit-options-group-button-button"]',
).forEach((button) => new Drupal.viewsUi.Checkboxifier(button));
},
};
/**
* Change the default widget to select the default group according to the
* selected widget for the exposed group.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Changes the default widget based on user input.
*/
Drupal.behaviors.viewsUiChangeDefaultWidget = {
attach(context) {
const $context = $(context);
function changeDefaultWidget(event) {
if ($(event.target).prop('checked')) {
$context.find('input.default-radios').parent().hide();
$context.find('td.any-default-radios-row').parent().hide();
$context.find('input.default-checkboxes').parent().show();
} else {
$context.find('input.default-checkboxes').parent().hide();
$context.find('td.any-default-radios-row').parent().show();
$context.find('input.default-radios').parent().show();
}
}
// Update on widget change.
$context
.find('input[name="options[group_info][multiple]"]')
.on('change', changeDefaultWidget)
// Update the first time the form is rendered.
.trigger('change');
},
};
/**
* Attaches expose filter button to a checkbox that triggers its click event.
*
* @constructor
*
* @param {Element} button
* The DOM object representing the button to be checkboxified.
*/
Drupal.viewsUi.Checkboxifier = function (button) {
this.$button = $(button);
this.$parent = this.$button.parent('div.views-expose, div.views-grouped');
this.$input = this.$parent.find('input:checkbox, input:radio');
// Hide the button and its description.
this.$button.hide();
this.$parent.find('.exposed-description, .grouped-description').hide();
this.$input.on('click', this.clickHandler.bind(this));
};
/**
* When the checkbox is checked or unchecked, simulate a button press.
*
* @param {jQuery.Event} e
* The event triggered.
*/
Drupal.viewsUi.Checkboxifier.prototype.clickHandler = function (e) {
this.$button.trigger('click').trigger('submit');
};
/**
* Change the Apply button text based upon the override select state.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches behavior to change the Apply button according to the current
* state.
*/
Drupal.behaviors.viewsUiOverrideSelect = {
attach(context) {
once(
'views-ui-override-button-text',
'[data-drupal-selector="edit-override-dropdown"]',
context,
).forEach((dropdown) => {
// Closures! :(
const submit = context.querySelector('[id^=edit-submit]');
const oldValue = submit ? submit.value : '';
$(once('views-ui-override-button-text', submit)).on(
'mouseup',
function () {
this.value = oldValue;
return true;
},
);
$(dropdown)
.on('change', function () {
if (!submit) {
return;
}
if (this.value === 'default') {
submit.value = Drupal.t('Apply (all displays)');
} else if (this.value === 'default_revert') {
submit.value = Drupal.t('Revert to default');
} else {
submit.value = Drupal.t('Apply (this display)');
}
if (context !== document) {
const dialog = context.closest('.ui-dialog-content');
dialog?.dispatchEvent(new CustomEvent('dialogButtonsChange'));
}
})
.trigger('change');
});
},
};
/**
* Functionality for the remove link in the views UI.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches behavior for the remove view and remove display links.
*/
Drupal.behaviors.viewsUiHandlerRemoveLink = {
attach(context) {
const $context = $(context);
// Handle handler deletion by looking for the hidden checkbox and hiding
// the row.
$(once('views', 'a.views-remove-link', context)).on(
'click',
function (event) {
const id = $(this).attr('id').replace('views-remove-link-', '');
$context.find(`#views-row-${id}`).hide();
$context.find(`#views-removed-${id}`).prop('checked', true);
event.preventDefault();
},
);
// Handle display deletion by looking for the hidden checkbox and hiding
// the row.
$(once('display', 'a.display-remove-link', context)).on(
'click',
function (event) {
const id = $(this).attr('id').replace('display-remove-link-', '');
$context.find(`#display-row-${id}`).hide();
$context.find(`#display-removed-${id}`).prop('checked', true);
event.preventDefault();
},
);
},
};
/**
* Rearranges the filters.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attach handlers to make it possible to rearrange the filters in the form
* in question.
* @see Drupal.viewsUi.RearrangeFilterHandler
*/
Drupal.behaviors.viewsUiRearrangeFilter = {
attach(context) {
// Only act on the rearrange filter form.
if (
typeof Drupal?.tableDrag?.['views-rearrange-filters'] === 'undefined'
) {
return;
}
const table = once(
'views-rearrange-filters',
'#views-rearrange-filters',
context,
);
const operator = once(
'views-rearrange-filters',
'.js-form-item-filter-groups-operator',
context,
);
if (table.length) {
new Drupal.viewsUi.RearrangeFilterHandler($(table), $(operator));
}
},
};
})(jQuery, Drupal, drupalSettings);
|