0fda8087489555f24bbbca165d66298944f3e31a
[yaffs-website] / web / core / modules / views_ui / js / views-admin.js
1 /**
2  * @file
3  * Some basic behaviors and utility functions for Views UI.
4  */
5
6 (function ($, Drupal, drupalSettings) {
7
8   'use strict';
9
10   /**
11    * @namespace
12    */
13   Drupal.viewsUi = {};
14
15   /**
16    * Improve the user experience of the views edit interface.
17    *
18    * @type {Drupal~behavior}
19    *
20    * @prop {Drupal~behaviorAttach} attach
21    *   Attaches toggling of SQL rewrite warning on the corresponding checkbox.
22    */
23   Drupal.behaviors.viewsUiEditView = {
24     attach: function () {
25       // Only show the SQL rewrite warning when the user has chosen the
26       // corresponding checkbox.
27       $('[data-drupal-selector="edit-query-options-disable-sql-rewrite"]').on('click', function () {
28         $('.sql-rewrite-warning').toggleClass('js-hide');
29       });
30     }
31   };
32
33   /**
34    * In the add view wizard, use the view name to prepopulate form fields such
35    * as page title and menu link.
36    *
37    * @type {Drupal~behavior}
38    *
39    * @prop {Drupal~behaviorAttach} attach
40    *   Attaches behavior for prepopulating page title and menu links, based on
41    *   view name.
42    */
43   Drupal.behaviors.viewsUiAddView = {
44     attach: function (context) {
45       var $context = $(context);
46       // Set up regular expressions to allow only numbers, letters, and dashes.
47       var exclude = new RegExp('[^a-z0-9\\-]+', 'g');
48       var replace = '-';
49       var suffix;
50
51       // The page title, block title, and menu link fields can all be
52       // prepopulated with the view name - no regular expression needed.
53       var $fields = $context.find('[id^="edit-page-title"], [id^="edit-block-title"], [id^="edit-page-link-properties-title"]');
54       if ($fields.length) {
55         if (!this.fieldsFiller) {
56           this.fieldsFiller = new Drupal.viewsUi.FormFieldFiller($fields);
57         }
58         else {
59           // After an AJAX response, this.fieldsFiller will still have event
60           // handlers bound to the old version of the form fields (which don't
61           // exist anymore). The event handlers need to be unbound and then
62           // rebound to the new markup. Note that jQuery.live is difficult to
63           // make work in this case because the IDs of the form fields change
64           // on every AJAX response.
65           this.fieldsFiller.rebind($fields);
66         }
67       }
68
69       // Prepopulate the path field with a URLified version of the view name.
70       var $pathField = $context.find('[id^="edit-page-path"]');
71       if ($pathField.length) {
72         if (!this.pathFiller) {
73           this.pathFiller = new Drupal.viewsUi.FormFieldFiller($pathField, exclude, replace);
74         }
75         else {
76           this.pathFiller.rebind($pathField);
77         }
78       }
79
80       // Populate the RSS feed field with a URLified version of the view name,
81       // and an .xml suffix (to make it unique).
82       var $feedField = $context.find('[id^="edit-page-feed-properties-path"]');
83       if ($feedField.length) {
84         if (!this.feedFiller) {
85           suffix = '.xml';
86           this.feedFiller = new Drupal.viewsUi.FormFieldFiller($feedField, exclude, replace, suffix);
87         }
88         else {
89           this.feedFiller.rebind($feedField);
90         }
91       }
92     }
93   };
94
95   /**
96    * Constructor for the {@link Drupal.viewsUi.FormFieldFiller} object.
97    *
98    * Prepopulates a form field based on the view name.
99    *
100    * @constructor
101    *
102    * @param {jQuery} $target
103    *   A jQuery object representing the form field or fields to prepopulate.
104    * @param {bool} [exclude=false]
105    *   A regular expression representing characters to exclude from
106    *   the target field.
107    * @param {string} [replace='']
108    *   A string to use as the replacement value for disallowed characters.
109    * @param {string} [suffix='']
110    *   A suffix to append at the end of the target field content.
111    */
112   Drupal.viewsUi.FormFieldFiller = function ($target, exclude, replace, suffix) {
113
114     /**
115      *
116      * @type {jQuery}
117      */
118     this.source = $('#edit-label');
119
120     /**
121      *
122      * @type {jQuery}
123      */
124     this.target = $target;
125
126     /**
127      *
128      * @type {bool}
129      */
130     this.exclude = exclude || false;
131
132     /**
133      *
134      * @type {string}
135      */
136     this.replace = replace || '';
137
138     /**
139      *
140      * @type {string}
141      */
142     this.suffix = suffix || '';
143
144     // Create bound versions of this instance's object methods to use as event
145     // handlers. This will let us easily unbind those specific handlers later
146     // on. NOTE: jQuery.proxy will not work for this because it assumes we want
147     // only one bound version of an object method, whereas we need one version
148     // per object instance.
149     var self = this;
150
151     /**
152      * Populate the target form field with the altered source field value.
153      *
154      * @return {*}
155      *   The result of the _populate call, which should be undefined.
156      */
157     this.populate = function () { return self._populate.call(self); };
158
159     /**
160      * Stop prepopulating the form fields.
161      *
162      * @return {*}
163      *   The result of the _unbind call, which should be undefined.
164      */
165     this.unbind = function () { return self._unbind.call(self); };
166
167     this.bind();
168     // Object constructor; no return value.
169   };
170
171   $.extend(Drupal.viewsUi.FormFieldFiller.prototype, /** @lends Drupal.viewsUi.FormFieldFiller# */{
172
173     /**
174      * Bind the form-filling behavior.
175      */
176     bind: function () {
177       this.unbind();
178       // Populate the form field when the source changes.
179       this.source.on('keyup.viewsUi change.viewsUi', this.populate);
180       // Quit populating the field as soon as it gets focus.
181       this.target.on('focus.viewsUi', this.unbind);
182     },
183
184     /**
185      * Get the source form field value as altered by the passed-in parameters.
186      *
187      * @return {string}
188      *   The source form field value.
189      */
190     getTransliterated: function () {
191       var from = this.source.val();
192       if (this.exclude) {
193         from = from.toLowerCase().replace(this.exclude, this.replace);
194       }
195       return from;
196     },
197
198     /**
199      * Populate the target form field with the altered source field value.
200      */
201     _populate: function () {
202       var transliterated = this.getTransliterated();
203       var suffix = this.suffix;
204       this.target.each(function (i) {
205         // Ensure that the maxlength is not exceeded by prepopulating the field.
206         var maxlength = $(this).attr('maxlength') - suffix.length;
207         $(this).val(transliterated.substr(0, maxlength) + suffix);
208       });
209     },
210
211     /**
212      * Stop prepopulating the form fields.
213      */
214     _unbind: function () {
215       this.source.off('keyup.viewsUi change.viewsUi', this.populate);
216       this.target.off('focus.viewsUi', this.unbind);
217     },
218
219     /**
220      * Bind event handlers to new form fields, after they're replaced via Ajax.
221      *
222      * @param {jQuery} $fields
223      *   Fields to rebind functionality to.
224      */
225     rebind: function ($fields) {
226       this.target = $fields;
227       this.bind();
228     }
229   });
230
231   /**
232    * Adds functionality for the add item form.
233    *
234    * @type {Drupal~behavior}
235    *
236    * @prop {Drupal~behaviorAttach} attach
237    *   Attaches the functionality in {@link Drupal.viewsUi.AddItemForm} to the
238    *   forms in question.
239    */
240   Drupal.behaviors.addItemForm = {
241     attach: function (context) {
242       var $context = $(context);
243       var $form = $context;
244       // The add handler form may have an id of views-ui-add-handler-form--n.
245       if (!$context.is('form[id^="views-ui-add-handler-form"]')) {
246         $form = $context.find('form[id^="views-ui-add-handler-form"]');
247       }
248       if ($form.once('views-ui-add-handler-form').length) {
249         // If we we have an unprocessed views-ui-add-handler-form, let's
250         // instantiate.
251         new Drupal.viewsUi.AddItemForm($form);
252       }
253     }
254   };
255
256   /**
257    * Constructs a new AddItemForm.
258    *
259    * @constructor
260    *
261    * @param {jQuery} $form
262    *   The form element used.
263    */
264   Drupal.viewsUi.AddItemForm = function ($form) {
265
266     /**
267      *
268      * @type {jQuery}
269      */
270     this.$form = $form;
271     this.$form.find('.views-filterable-options :checkbox').on('click', $.proxy(this.handleCheck, this));
272
273     /**
274      * Find the wrapper of the displayed text.
275      */
276     this.$selected_div = this.$form.find('.views-selected-options').parent();
277     this.$selected_div.hide();
278
279     /**
280      *
281      * @type {Array}
282      */
283     this.checkedItems = [];
284   };
285
286   /**
287    * Handles a checkbox check.
288    *
289    * @param {jQuery.Event} event
290    *   The event triggered.
291    */
292   Drupal.viewsUi.AddItemForm.prototype.handleCheck = function (event) {
293     var $target = $(event.target);
294     var label = $.trim($target.closest('td').next().html());
295     // Add/remove the checked item to the list.
296     if ($target.is(':checked')) {
297       this.$selected_div.show().css('display', 'block');
298       this.checkedItems.push(label);
299     }
300     else {
301       var position = $.inArray(label, this.checkedItems);
302       // Delete the item from the list and make sure that the list doesn't have
303       // undefined items left.
304       for (var i = 0; i < this.checkedItems.length; i++) {
305         if (i === position) {
306           this.checkedItems.splice(i, 1);
307           i--;
308           break;
309         }
310       }
311       // Hide it again if none item is selected.
312       if (this.checkedItems.length === 0) {
313         this.$selected_div.hide();
314       }
315     }
316     this.refreshCheckedItems();
317   };
318
319   /**
320    * Refresh the display of the checked items.
321    */
322   Drupal.viewsUi.AddItemForm.prototype.refreshCheckedItems = function () {
323     // Perhaps we should precache the text div, too.
324     this.$selected_div.find('.views-selected-options')
325       .html(this.checkedItems.join(', '))
326       .trigger('dialogContentResize');
327   };
328
329   /**
330    * The input field items that add displays must be rendered as `<input>`
331    * elements. The following behavior detaches the `<input>` elements from the
332    * DOM, wraps them in an unordered list, then appends them to the list of
333    * tabs.
334    *
335    * @type {Drupal~behavior}
336    *
337    * @prop {Drupal~behaviorAttach} attach
338    *   Fixes the input elements needed.
339    */
340   Drupal.behaviors.viewsUiRenderAddViewButton = {
341     attach: function (context) {
342       // Build the add display menu and pull the display input buttons into it.
343       var $menu = $(context).find('#views-display-menu-tabs').once('views-ui-render-add-view-button');
344       if (!$menu.length) {
345         return;
346       }
347
348       var $addDisplayDropdown = $('<li class="add"><a href="#"><span class="icon add"></span>' + Drupal.t('Add') + '</a><ul class="action-list" style="display:none;"></ul></li>');
349       var $displayButtons = $menu.nextAll('input.add-display').detach();
350       $displayButtons.appendTo($addDisplayDropdown.find('.action-list')).wrap('<li>')
351         .parent().eq(0).addClass('first').end().eq(-1).addClass('last');
352       // Remove the 'Add ' prefix from the button labels since they're being
353       // placed in an 'Add' dropdown. @todo This assumes English, but so does
354       // $addDisplayDropdown above. Add support for translation.
355       $displayButtons.each(function () {
356         var label = $(this).val();
357         if (label.substr(0, 4) === 'Add ') {
358           $(this).val(label.substr(4));
359         }
360       });
361       $addDisplayDropdown.appendTo($menu);
362
363       // Add the click handler for the add display button.
364       $menu.find('li.add > a').on('click', function (event) {
365         event.preventDefault();
366         var $trigger = $(this);
367         Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
368       });
369       // Add a mouseleave handler to close the dropdown when the user mouses
370       // away from the item. We use mouseleave instead of mouseout because
371       // the user is going to trigger mouseout when she moves from the trigger
372       // link to the sub menu items.
373       // We use the live binder because the open class on this item will be
374       // toggled on and off and we want the handler to take effect in the cases
375       // that the class is present, but not when it isn't.
376       $('li.add', $menu).on('mouseleave', function (event) {
377         var $this = $(this);
378         var $trigger = $this.children('a[href="#"]');
379         if ($this.children('.action-list').is(':visible')) {
380           Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
381         }
382       });
383     }
384   };
385
386   /**
387    * Toggle menu visibility.
388    *
389    * @param {jQuery} $trigger
390    *   The element where the toggle was triggered.
391    *
392    *
393    * @note [@jessebeach] I feel like the following should be a more generic
394    *   function and not written specifically for this UI, but I'm not sure
395    *   where to put it.
396    */
397   Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu = function ($trigger) {
398     $trigger.parent().toggleClass('open');
399     $trigger.next().slideToggle('fast');
400   };
401
402   /**
403    * Add search options to the views ui.
404    *
405    * @type {Drupal~behavior}
406    *
407    * @prop {Drupal~behaviorAttach} attach
408    *   Attaches {@link Drupal.viewsUi.OptionsSearch} to the views ui filter
409    *   options.
410    */
411   Drupal.behaviors.viewsUiSearchOptions = {
412     attach: function (context) {
413       var $context = $(context);
414       var $form = $context;
415       // The add handler form may have an id of views-ui-add-handler-form--n.
416       if (!$context.is('form[id^="views-ui-add-handler-form"]')) {
417         $form = $context.find('form[id^="views-ui-add-handler-form"]');
418       }
419       // Make sure we don't add more than one event handler to the same form.
420       if ($form.once('views-ui-filter-options').length) {
421         new Drupal.viewsUi.OptionsSearch($form);
422       }
423     }
424   };
425
426   /**
427    * Constructor for the viewsUi.OptionsSearch object.
428    *
429    * The OptionsSearch object filters the available options on a form according
430    * to the user's search term. Typing in "taxonomy" will show only those
431    * options containing "taxonomy" in their label.
432    *
433    * @constructor
434    *
435    * @param {jQuery} $form
436    *   The form element.
437    */
438   Drupal.viewsUi.OptionsSearch = function ($form) {
439
440     /**
441      *
442      * @type {jQuery}
443      */
444     this.$form = $form;
445
446     // Click on the title checks the box.
447     this.$form.on('click', 'td.title', function (event) {
448       var $target = $(event.currentTarget);
449       $target.closest('tr').find('input').trigger('click');
450     });
451
452     var searchBoxSelector = '[data-drupal-selector="edit-override-controls-options-search"]';
453     var controlGroupSelector = '[data-drupal-selector="edit-override-controls-group"]';
454     this.$form.on('formUpdated', searchBoxSelector + ',' + controlGroupSelector, $.proxy(this.handleFilter, this));
455
456     this.$searchBox = this.$form.find(searchBoxSelector);
457     this.$controlGroup = this.$form.find(controlGroupSelector);
458
459     /**
460      * Get a list of option labels and their corresponding divs and maintain it
461      * in memory, so we have as little overhead as possible at keyup time.
462      */
463     this.options = this.getOptions(this.$form.find('.filterable-option'));
464
465     // Trap the ENTER key in the search box so that it doesn't submit the form.
466     this.$searchBox.on('keypress', function (event) {
467       if (event.which === 13) {
468         event.preventDefault();
469       }
470     });
471   };
472
473   $.extend(Drupal.viewsUi.OptionsSearch.prototype, /** @lends Drupal.viewsUi.OptionsSearch# */{
474
475     /**
476      * Assemble a list of all the filterable options on the form.
477      *
478      * @param {jQuery} $allOptions
479      *   A jQuery object representing the rows of filterable options to be
480      *   shown and hidden depending on the user's search terms.
481      *
482      * @return {Array}
483      *   An array of all the filterable options.
484      */
485     getOptions: function ($allOptions) {
486       var $title;
487       var $description;
488       var $option;
489       var options = [];
490       var length = $allOptions.length;
491       for (var i = 0; i < length; i++) {
492         $option = $($allOptions[i]);
493         $title = $option.find('.title');
494         $description = $option.find('.description');
495         options[i] = {
496           // Search on the lowercase version of the title text + description.
497           searchText: $title.text().toLowerCase() + ' ' + $description.text().toLowerCase(),
498           // Maintain a reference to the jQuery object for each row, so we don't
499           // have to create a new object inside the performance-sensitive keyup
500           // handler.
501           $div: $option
502         };
503       }
504       return options;
505     },
506
507     /**
508      * Filter handler for the search box and type select that hides or shows the relevant
509      * options.
510      *
511      * @param {jQuery.Event} event
512      *   The formUpdated event.
513      */
514     handleFilter: function (event) {
515       // Determine the user's search query. The search text has been converted
516       // to lowercase.
517       var search = this.$searchBox.val().toLowerCase();
518       var words = search.split(' ');
519       // Get selected Group
520       var group = this.$controlGroup.val();
521
522       // Search through the search texts in the form for matching text.
523       this.options.forEach(function (option) {
524         function hasWord(word) {
525           return option.searchText.indexOf(word) !== -1;
526         }
527
528         var found = true;
529         // Each word in the search string has to match the item in order for the
530         // item to be shown.
531         if (search) {
532           found = words.every(hasWord);
533         }
534         if (found && group !== 'all') {
535           found = option.$div.hasClass(group);
536         }
537
538         option.$div.toggle(found);
539       });
540
541       // Adapt dialog to content size.
542       $(event.target).trigger('dialogContentResize');
543     }
544   });
545
546   /**
547    * Preview functionality in the views edit form.
548    *
549    * @type {Drupal~behavior}
550    *
551    * @prop {Drupal~behaviorAttach} attach
552    *   Attaches the preview functionality to the view edit form.
553    */
554   Drupal.behaviors.viewsUiPreview = {
555     attach: function (context) {
556       // Only act on the edit view form.
557       var $contextualFiltersBucket = $(context).find('.views-display-column .views-ui-display-tab-bucket.argument');
558       if ($contextualFiltersBucket.length === 0) {
559         return;
560       }
561
562       // If the display has no contextual filters, hide the form where you
563       // enter the contextual filters for the live preview. If it has contextual
564       // filters, show the form.
565       var $contextualFilters = $contextualFiltersBucket.find('.views-display-setting a');
566       if ($contextualFilters.length) {
567         $('#preview-args').parent().show();
568       }
569       else {
570         $('#preview-args').parent().hide();
571       }
572
573       // Executes an initial preview.
574       if ($('#edit-displays-live-preview').once('edit-displays-live-preview').is(':checked')) {
575         $('#preview-submit').once('edit-displays-live-preview').trigger('click');
576       }
577     }
578   };
579
580   /**
581    * Rearranges the filters.
582    *
583    * @type {Drupal~behavior}
584    *
585    * @prop {Drupal~behaviorAttach} attach
586    *   Attach handlers to make it possible to rearange the filters in the form
587    *   in question.
588    *   @see Drupal.viewsUi.RearrangeFilterHandler
589    */
590   Drupal.behaviors.viewsUiRearrangeFilter = {
591     attach: function (context) {
592       // Only act on the rearrange filter form.
593       if (typeof Drupal.tableDrag === 'undefined' || typeof Drupal.tableDrag['views-rearrange-filters'] === 'undefined') {
594         return;
595       }
596       var $context = $(context);
597       var $table = $context.find('#views-rearrange-filters').once('views-rearrange-filters');
598       var $operator = $context.find('.js-form-item-filter-groups-operator').once('views-rearrange-filters');
599       if ($table.length) {
600         new Drupal.viewsUi.RearrangeFilterHandler($table, $operator);
601       }
602     }
603   };
604
605   /**
606    * Improve the UI of the rearrange filters dialog box.
607    *
608    * @constructor
609    *
610    * @param {jQuery} $table
611    *   The table in the filter form.
612    * @param {jQuery} $operator
613    *   The filter groups operator element.
614    */
615   Drupal.viewsUi.RearrangeFilterHandler = function ($table, $operator) {
616
617     /**
618      * Keep a reference to the `<table>` being altered and to the div containing
619      * the filter groups operator dropdown (if it exists).
620      */
621     this.table = $table;
622
623     /**
624      *
625      * @type {jQuery}
626      */
627     this.operator = $operator;
628
629     /**
630      *
631      * @type {bool}
632      */
633     this.hasGroupOperator = this.operator.length > 0;
634
635     /**
636      * Keep a reference to all draggable rows within the table.
637      *
638      * @type {jQuery}
639      */
640     this.draggableRows = $table.find('.draggable');
641
642     /**
643      * Keep a reference to the buttons for adding and removing filter groups.
644      *
645      * @type {jQuery}
646      */
647     this.addGroupButton = $('input#views-add-group');
648
649     /**
650      * @type {jQuery}
651      */
652     this.removeGroupButtons = $table.find('input.views-remove-group');
653
654     // Add links that duplicate the functionality of the (hidden) add and remove
655     // buttons.
656     this.insertAddRemoveFilterGroupLinks();
657
658     // When there is a filter groups operator dropdown on the page, create
659     // duplicates of the dropdown between each pair of filter groups.
660     if (this.hasGroupOperator) {
661
662       /**
663        * @type {jQuery}
664        */
665       this.dropdowns = this.duplicateGroupsOperator();
666       this.syncGroupsOperators();
667     }
668
669     // Add methods to the tableDrag instance to account for operator cells
670     // (which span multiple rows), the operator labels next to each filter
671     // (e.g., "And" or "Or"), the filter groups, and other special aspects of
672     // this tableDrag instance.
673     this.modifyTableDrag();
674
675     // Initialize the operator labels (e.g., "And" or "Or") that are displayed
676     // next to the filters in each group, and bind a handler so that they change
677     // based on the values of the operator dropdown within that group.
678     this.redrawOperatorLabels();
679     $table.find('.views-group-title select')
680       .once('views-rearrange-filter-handler')
681       .on('change.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
682
683     // Bind handlers so that when a "Remove" link is clicked, we:
684     // - Update the rowspans of cells containing an operator dropdown (since
685     //   they need to change to reflect the number of rows in each group).
686     // - Redraw the operator labels next to the filters in the group (since the
687     //   filter that is currently displayed last in each group is not supposed
688     //   to have a label display next to it).
689     $table.find('a.views-groups-remove-link')
690       .once('views-rearrange-filter-handler')
691       .on('click.views-rearrange-filter-handler', $.proxy(this, 'updateRowspans'))
692       .on('click.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
693   };
694
695   $.extend(Drupal.viewsUi.RearrangeFilterHandler.prototype, /** @lends Drupal.viewsUi.RearrangeFilterHandler# */{
696
697     /**
698      * Insert links that allow filter groups to be added and removed.
699      */
700     insertAddRemoveFilterGroupLinks: function () {
701
702       // Insert a link for adding a new group at the top of the page, and make
703       // it match the action link styling used in a typical page.html.twig.
704       // Since Drupal does not provide a theme function for this markup this is
705       // the best we can do.
706       $('<ul class="action-links"><li><a id="views-add-group-link" href="#">' + this.addGroupButton.val() + '</a></li></ul>')
707         .prependTo(this.table.parent())
708         // When the link is clicked, dynamically click the hidden form button
709         // for adding a new filter group.
710         .once('views-rearrange-filter-handler')
711         .find('#views-add-group-link')
712         .on('click.views-rearrange-filter-handler', $.proxy(this, 'clickAddGroupButton'));
713
714       // Find each (visually hidden) button for removing a filter group and
715       // insert a link next to it.
716       var length = this.removeGroupButtons.length;
717       var i;
718       for (i = 0; i < length; i++) {
719         var $removeGroupButton = $(this.removeGroupButtons[i]);
720         var buttonId = $removeGroupButton.attr('id');
721         $('<a href="#" class="views-remove-group-link">' + Drupal.t('Remove group') + '</a>')
722           .insertBefore($removeGroupButton)
723           // When the link is clicked, dynamically click the corresponding form
724           // button.
725           .once('views-rearrange-filter-handler')
726           .on('click.views-rearrange-filter-handler', {buttonId: buttonId}, $.proxy(this, 'clickRemoveGroupButton'));
727       }
728     },
729
730     /**
731      * Dynamically click the button that adds a new filter group.
732      *
733      * @param {jQuery.Event} event
734      *   The event triggered.
735      */
736     clickAddGroupButton: function (event) {
737       this.addGroupButton.trigger('mousedown');
738       event.preventDefault();
739     },
740
741     /**
742      * Dynamically click a button for removing a filter group.
743      *
744      * @param {jQuery.Event} event
745      *   Event being triggered, with event.data.buttonId set to the ID of the
746      *   form button that should be clicked.
747      */
748     clickRemoveGroupButton: function (event) {
749       this.table.find('#' + event.data.buttonId).trigger('mousedown');
750       event.preventDefault();
751     },
752
753     /**
754      * Move the groups operator so that it's between the first two groups, and
755      * duplicate it between any subsequent groups.
756      *
757      * @return {jQuery}
758      *   An operator element.
759      */
760     duplicateGroupsOperator: function () {
761       var dropdowns;
762       var newRow;
763       var titleRow;
764
765       var titleRows = $('tr.views-group-title').once('duplicateGroupsOperator');
766
767       if (!titleRows.length) {
768         return this.operator;
769       }
770
771       // Get rid of the explanatory text around the operator; its placement is
772       // explanatory enough.
773       this.operator.find('label').add('div.description').addClass('visually-hidden');
774       this.operator.find('select').addClass('form-select');
775
776       // Keep a list of the operator dropdowns, so we can sync their behavior
777       // later.
778       dropdowns = this.operator;
779
780       // Move the operator to a new row just above the second group.
781       titleRow = $('tr#views-group-title-2');
782       newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
783       newRow.find('td').append(this.operator);
784       newRow.insertBefore(titleRow);
785       var length = titleRows.length;
786       // Starting with the third group, copy the operator to a new row above the
787       // group title.
788       for (var i = 2; i < length; i++) {
789         titleRow = $(titleRows[i]);
790         // Make a copy of the operator dropdown and put it in a new table row.
791         var fakeOperator = this.operator.clone();
792         fakeOperator.attr('id', '');
793         newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
794         newRow.find('td').append(fakeOperator);
795         newRow.insertBefore(titleRow);
796         dropdowns.add(fakeOperator);
797       }
798
799       return dropdowns;
800     },
801
802     /**
803      * Make the duplicated groups operators change in sync with each other.
804      */
805     syncGroupsOperators: function () {
806       if (this.dropdowns.length < 2) {
807         // We only have one dropdown (or none at all), so there's nothing to
808         // sync.
809         return;
810       }
811
812       this.dropdowns.on('change', $.proxy(this, 'operatorChangeHandler'));
813     },
814
815     /**
816      * Click handler for the operators that appear between filter groups.
817      *
818      * Forces all operator dropdowns to have the same value.
819      *
820      * @param {jQuery.Event} event
821      *   The event triggered.
822      */
823     operatorChangeHandler: function (event) {
824       var $target = $(event.target);
825       var operators = this.dropdowns.find('select').not($target);
826
827       // Change the other operators to match this new value.
828       operators.val($target.val());
829     },
830
831     /**
832      * @method
833      */
834     modifyTableDrag: function () {
835       var tableDrag = Drupal.tableDrag['views-rearrange-filters'];
836       var filterHandler = this;
837
838       /**
839        * Override the row.onSwap method from tabledrag.js.
840        *
841        * When a row is dragged to another place in the table, several things
842        * need to occur.
843        * - The row needs to be moved so that it's within one of the filter
844        * groups.
845        * - The operator cells that span multiple rows need their rowspan
846        * attributes updated to reflect the number of rows in each group.
847        * - The operator labels that are displayed next to each filter need to
848        * be redrawn, to account for the row's new location.
849        */
850       tableDrag.row.prototype.onSwap = function () {
851         if (filterHandler.hasGroupOperator) {
852           // Make sure the row that just got moved (this.group) is inside one
853           // of the filter groups (i.e. below an empty marker row or a
854           // draggable). If it isn't, move it down one.
855           var thisRow = $(this.group);
856           var previousRow = thisRow.prev('tr');
857           if (previousRow.length && !previousRow.hasClass('group-message') && !previousRow.hasClass('draggable')) {
858             // Move the dragged row down one.
859             var next = thisRow.next();
860             if (next.is('tr')) {
861               this.swap('after', next);
862             }
863           }
864           filterHandler.updateRowspans();
865         }
866         // Redraw the operator labels that are displayed next to each filter, to
867         // account for the row's new location.
868         filterHandler.redrawOperatorLabels();
869       };
870
871       /**
872        * Override the onDrop method from tabledrag.js.
873        */
874       tableDrag.onDrop = function () {
875         // If the tabledrag change marker (i.e., the "*") has been inserted
876         // inside a row after the operator label (i.e., "And" or "Or")
877         // rearrange the items so the operator label continues to appear last.
878         var changeMarker = $(this.oldRowElement).find('.tabledrag-changed');
879         if (changeMarker.length) {
880           // Search for occurrences of the operator label before the change
881           // marker, and reverse them.
882           var operatorLabel = changeMarker.prevAll('.views-operator-label');
883           if (operatorLabel.length) {
884             operatorLabel.insertAfter(changeMarker);
885           }
886         }
887
888         // Make sure the "group" dropdown is properly updated when rows are
889         // dragged into an empty filter group. This is borrowed heavily from
890         // the block.js implementation of tableDrag.onDrop().
891         var groupRow = $(this.rowObject.element).prevAll('tr.group-message').get(0);
892         var groupName = groupRow.className.replace(/([^ ]+[ ]+)*group-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
893         var groupField = $('select.views-group-select', this.rowObject.element);
894         if ($(this.rowObject.element).prev('tr').is('.group-message') && !groupField.is('.views-group-select-' + groupName)) {
895           var oldGroupName = groupField.attr('class').replace(/([^ ]+[ ]+)*views-group-select-([^ ]+)([ ]+[^ ]+)*/, '$2');
896           groupField.removeClass('views-group-select-' + oldGroupName).addClass('views-group-select-' + groupName);
897           groupField.val(groupName);
898         }
899       };
900     },
901
902     /**
903      * Redraw the operator labels that are displayed next to each filter.
904      */
905     redrawOperatorLabels: function () {
906       for (var i = 0; i < this.draggableRows.length; i++) {
907         // Within the row, the operator labels are displayed inside the first
908         // table cell (next to the filter name).
909         var $draggableRow = $(this.draggableRows[i]);
910         var $firstCell = $draggableRow.find('td').eq(0);
911         if ($firstCell.length) {
912           // The value of the operator label ("And" or "Or") is taken from the
913           // first operator dropdown we encounter, going backwards from the
914           // current row. This dropdown is the one associated with the current
915           // row's filter group.
916           var operatorValue = $draggableRow.prevAll('.views-group-title').find('option:selected').html();
917           var operatorLabel = '<span class="views-operator-label">' + operatorValue + '</span>';
918           // If the next visible row after this one is a draggable filter row,
919           // display the operator label next to the current row. (Checking for
920           // visibility is necessary here since the "Remove" links hide the
921           // removed row but don't actually remove it from the document).
922           var $nextRow = $draggableRow.nextAll(':visible').eq(0);
923           var $existingOperatorLabel = $firstCell.find('.views-operator-label');
924           if ($nextRow.hasClass('draggable')) {
925             // If an operator label was already there, replace it with the new
926             // one.
927             if ($existingOperatorLabel.length) {
928               $existingOperatorLabel.replaceWith(operatorLabel);
929             }
930             // Otherwise, append the operator label to the end of the table
931             // cell.
932             else {
933               $firstCell.append(operatorLabel);
934             }
935           }
936           // If the next row doesn't contain a filter, then this is the last row
937           // in the group. We don't want to display the operator there (since
938           // operators should only display between two related filters, e.g.
939           // "filter1 AND filter2 AND filter3"). So we remove any existing label
940           // that this row has.
941           else {
942             $existingOperatorLabel.remove();
943           }
944         }
945       }
946     },
947
948     /**
949      * Update the rowspan attribute of each cell containing an operator
950      * dropdown.
951      */
952     updateRowspans: function () {
953       var $row;
954       var $currentEmptyRow;
955       var draggableCount;
956       var $operatorCell;
957       var rows = $(this.table).find('tr');
958       var length = rows.length;
959       for (var i = 0; i < length; i++) {
960         $row = $(rows[i]);
961         if ($row.hasClass('views-group-title')) {
962           // This row is a title row.
963           // Keep a reference to the cell containing the dropdown operator.
964           $operatorCell = $row.find('td.group-operator');
965           // Assume this filter group is empty, until we find otherwise.
966           draggableCount = 0;
967           $currentEmptyRow = $row.next('tr');
968           $currentEmptyRow.removeClass('group-populated').addClass('group-empty');
969           // The cell with the dropdown operator should span the title row and
970           // the "this group is empty" row.
971           $operatorCell.attr('rowspan', 2);
972         }
973         else if ($row.hasClass('draggable') && $row.is(':visible')) {
974           // We've found a visible filter row, so we now know the group isn't
975           // empty.
976           draggableCount++;
977           $currentEmptyRow.removeClass('group-empty').addClass('group-populated');
978           // The operator cell should span all draggable rows, plus the title.
979           $operatorCell.attr('rowspan', draggableCount + 1);
980         }
981       }
982     }
983   });
984
985   /**
986    * Add a select all checkbox, which checks each checkbox at once.
987    *
988    * @type {Drupal~behavior}
989    *
990    * @prop {Drupal~behaviorAttach} attach
991    *   Attaches select all functionality to the views filter form.
992    */
993   Drupal.behaviors.viewsFilterConfigSelectAll = {
994     attach: function (context) {
995       var $context = $(context);
996
997       var $selectAll = $context.find('.js-form-item-options-value-all').once('filterConfigSelectAll');
998       var $selectAllCheckbox = $selectAll.find('input[type=checkbox]');
999       var $checkboxes = $selectAll.closest('.form-checkboxes').find('.js-form-type-checkbox:not(.js-form-item-options-value-all) input[type="checkbox"]');
1000
1001       if ($selectAll.length) {
1002          // Show the select all checkbox.
1003         $selectAll.show();
1004         $selectAllCheckbox.on('click', function () {
1005           // Update all checkbox beside the select all checkbox.
1006           $checkboxes.prop('checked', $(this).is(':checked'));
1007         });
1008
1009         // Uncheck the select all checkbox if any of the others are unchecked.
1010         $checkboxes.on('click', function () {
1011           if ($(this).is('checked') === false) {
1012             $selectAllCheckbox.prop('checked', false);
1013           }
1014         });
1015       }
1016     }
1017   };
1018
1019   /**
1020    * Remove icon class from elements that are themed as buttons or dropbuttons.
1021    *
1022    * @type {Drupal~behavior}
1023    *
1024    * @prop {Drupal~behaviorAttach} attach
1025    *   Removes the icon class from certain views elements.
1026    */
1027   Drupal.behaviors.viewsRemoveIconClass = {
1028     attach: function (context) {
1029       $(context).find('.dropbutton').once('dropbutton-icon').find('.icon').removeClass('icon');
1030     }
1031   };
1032
1033   /**
1034    * Change "Expose filter" buttons into checkboxes.
1035    *
1036    * @type {Drupal~behavior}
1037    *
1038    * @prop {Drupal~behaviorAttach} attach
1039    *   Changes buttons into checkboxes via {@link Drupal.viewsUi.Checkboxifier}.
1040    */
1041   Drupal.behaviors.viewsUiCheckboxify = {
1042     attach: function (context, settings) {
1043       var $buttons = $('[data-drupal-selector="edit-options-expose-button-button"], [data-drupal-selector="edit-options-group-button-button"]').once('views-ui-checkboxify');
1044       var length = $buttons.length;
1045       var i;
1046       for (i = 0; i < length; i++) {
1047         new Drupal.viewsUi.Checkboxifier($buttons[i]);
1048       }
1049     }
1050   };
1051
1052   /**
1053    * Change the default widget to select the default group according to the
1054    * selected widget for the exposed group.
1055    *
1056    * @type {Drupal~behavior}
1057    *
1058    * @prop {Drupal~behaviorAttach} attach
1059    *   Changes the default widget based on user input.
1060    */
1061   Drupal.behaviors.viewsUiChangeDefaultWidget = {
1062     attach: function (context) {
1063       var $context = $(context);
1064
1065       function changeDefaultWidget(event) {
1066         if ($(event.target).prop('checked')) {
1067           $context.find('input.default-radios').parent().hide();
1068           $context.find('td.any-default-radios-row').parent().hide();
1069           $context.find('input.default-checkboxes').parent().show();
1070         }
1071         else {
1072           $context.find('input.default-checkboxes').parent().hide();
1073           $context.find('td.any-default-radios-row').parent().show();
1074           $context.find('input.default-radios').parent().show();
1075         }
1076       }
1077
1078       // Update on widget change.
1079       $context.find('input[name="options[group_info][multiple]"]')
1080         .on('change', changeDefaultWidget)
1081         // Update the first time the form is rendered.
1082         .trigger('change');
1083     }
1084   };
1085
1086   /**
1087    * Attaches expose filter button to a checkbox that triggers its click event.
1088    *
1089    * @constructor
1090    *
1091    * @param {HTMLElement} button
1092    *   The DOM object representing the button to be checkboxified.
1093    */
1094   Drupal.viewsUi.Checkboxifier = function (button) {
1095     this.$button = $(button);
1096     this.$parent = this.$button.parent('div.views-expose, div.views-grouped');
1097     this.$input = this.$parent.find('input:checkbox, input:radio');
1098     // Hide the button and its description.
1099     this.$button.hide();
1100     this.$parent.find('.exposed-description, .grouped-description').hide();
1101
1102     this.$input.on('click', $.proxy(this, 'clickHandler'));
1103
1104   };
1105
1106   /**
1107    * When the checkbox is checked or unchecked, simulate a button press.
1108    *
1109    * @param {jQuery.Event} e
1110    *   The event triggered.
1111    */
1112   Drupal.viewsUi.Checkboxifier.prototype.clickHandler = function (e) {
1113     this.$button
1114       .trigger('click')
1115       .trigger('submit');
1116   };
1117
1118   /**
1119    * Change the Apply button text based upon the override select state.
1120    *
1121    * @type {Drupal~behavior}
1122    *
1123    * @prop {Drupal~behaviorAttach} attach
1124    *   Attaches behavior to change the Apply button according to the current
1125    *   state.
1126    */
1127   Drupal.behaviors.viewsUiOverrideSelect = {
1128     attach: function (context) {
1129       $(context).find('[data-drupal-selector="edit-override-dropdown"]').once('views-ui-override-button-text').each(function () {
1130         // Closures! :(
1131         var $context = $(context);
1132         var $submit = $context.find('[id^=edit-submit]');
1133         var old_value = $submit.val();
1134
1135         $submit.once('views-ui-override-button-text')
1136           .on('mouseup', function () {
1137             $(this).val(old_value);
1138             return true;
1139           });
1140
1141         $(this).on('change', function () {
1142           var $this = $(this);
1143           if ($this.val() === 'default') {
1144             $submit.val(Drupal.t('Apply (all displays)'));
1145           }
1146           else if ($this.val() === 'default_revert') {
1147             $submit.val(Drupal.t('Revert to default'));
1148           }
1149           else {
1150             $submit.val(Drupal.t('Apply (this display)'));
1151           }
1152           var $dialog = $context.closest('.ui-dialog-content');
1153           $dialog.trigger('dialogButtonsChange');
1154         })
1155           .trigger('change');
1156       });
1157
1158     }
1159   };
1160
1161   /**
1162    * Functionality for the remove link in the views UI.
1163    *
1164    * @type {Drupal~behavior}
1165    *
1166    * @prop {Drupal~behaviorAttach} attach
1167    *   Attaches behavior for the remove view and remove display links.
1168    */
1169   Drupal.behaviors.viewsUiHandlerRemoveLink = {
1170     attach: function (context) {
1171       var $context = $(context);
1172       // Handle handler deletion by looking for the hidden checkbox and hiding
1173       // the row.
1174       $context.find('a.views-remove-link').once('views').on('click', function (event) {
1175         var id = $(this).attr('id').replace('views-remove-link-', '');
1176         $context.find('#views-row-' + id).hide();
1177         $context.find('#views-removed-' + id).prop('checked', true);
1178         event.preventDefault();
1179       });
1180
1181       // Handle display deletion by looking for the hidden checkbox and hiding
1182       // the row.
1183       $context.find('a.display-remove-link').once('display').on('click', function (event) {
1184         var id = $(this).attr('id').replace('display-remove-link-', '');
1185         $context.find('#display-row-' + id).hide();
1186         $context.find('#display-removed-' + id).prop('checked', true);
1187         event.preventDefault();
1188       });
1189     }
1190   };
1191
1192 })(jQuery, Drupal, drupalSettings);