3 * Some basic behaviors and utility functions for Views UI.
6 (function ($, Drupal, drupalSettings) {
13 * Improve the user experience of the views edit interface.
15 * @type {Drupal~behavior}
17 * @prop {Drupal~behaviorAttach} attach
18 * Attaches toggling of SQL rewrite warning on the corresponding checkbox.
20 Drupal.behaviors.viewsUiEditView = {
22 // Only show the SQL rewrite warning when the user has chosen the
23 // corresponding checkbox.
24 $('[data-drupal-selector="edit-query-options-disable-sql-rewrite"]').on('click', () => {
25 $('.sql-rewrite-warning').toggleClass('js-hide');
31 * In the add view wizard, use the view name to prepopulate form fields such
32 * as page title and menu link.
34 * @type {Drupal~behavior}
36 * @prop {Drupal~behaviorAttach} attach
37 * Attaches behavior for prepopulating page title and menu links, based on
40 Drupal.behaviors.viewsUiAddView = {
42 const $context = $(context);
43 // Set up regular expressions to allow only numbers, letters, and dashes.
44 const exclude = new RegExp('[^a-z0-9\\-]+', 'g');
48 // The page title, block title, and menu link fields can all be
49 // prepopulated with the view name - no regular expression needed.
50 const $fields = $context.find('[id^="edit-page-title"], [id^="edit-block-title"], [id^="edit-page-link-properties-title"]');
52 if (!this.fieldsFiller) {
53 this.fieldsFiller = new Drupal.viewsUi.FormFieldFiller($fields);
56 // After an AJAX response, this.fieldsFiller will still have event
57 // handlers bound to the old version of the form fields (which don't
58 // exist anymore). The event handlers need to be unbound and then
59 // rebound to the new markup. Note that jQuery.live is difficult to
60 // make work in this case because the IDs of the form fields change
61 // on every AJAX response.
62 this.fieldsFiller.rebind($fields);
66 // Prepopulate the path field with a URLified version of the view name.
67 const $pathField = $context.find('[id^="edit-page-path"]');
68 if ($pathField.length) {
69 if (!this.pathFiller) {
70 this.pathFiller = new Drupal.viewsUi.FormFieldFiller($pathField, exclude, replace);
73 this.pathFiller.rebind($pathField);
77 // Populate the RSS feed field with a URLified version of the view name,
78 // and an .xml suffix (to make it unique).
79 const $feedField = $context.find('[id^="edit-page-feed-properties-path"]');
80 if ($feedField.length) {
81 if (!this.feedFiller) {
83 this.feedFiller = new Drupal.viewsUi.FormFieldFiller($feedField, exclude, replace, suffix);
86 this.feedFiller.rebind($feedField);
93 * Constructor for the {@link Drupal.viewsUi.FormFieldFiller} object.
95 * Prepopulates a form field based on the view name.
99 * @param {jQuery} $target
100 * A jQuery object representing the form field or fields to prepopulate.
101 * @param {bool} [exclude=false]
102 * A regular expression representing characters to exclude from
104 * @param {string} [replace='']
105 * A string to use as the replacement value for disallowed characters.
106 * @param {string} [suffix='']
107 * A suffix to append at the end of the target field content.
109 Drupal.viewsUi.FormFieldFiller = function ($target, exclude, replace, suffix) {
114 this.source = $('#edit-label');
120 this.target = $target;
126 this.exclude = exclude || false;
132 this.replace = replace || '';
138 this.suffix = suffix || '';
140 // Create bound versions of this instance's object methods to use as event
141 // handlers. This will let us easily unbind those specific handlers later
142 // on. NOTE: jQuery.proxy will not work for this because it assumes we want
143 // only one bound version of an object method, whereas we need one version
144 // per object instance.
148 * Populate the target form field with the altered source field value.
151 * The result of the _populate call, which should be undefined.
153 this.populate = function () {
154 return self._populate.call(self);
158 * Stop prepopulating the form fields.
161 * The result of the _unbind call, which should be undefined.
163 this.unbind = function () {
164 return self._unbind.call(self);
168 // Object constructor; no return value.
171 $.extend(Drupal.viewsUi.FormFieldFiller.prototype, /** @lends Drupal.viewsUi.FormFieldFiller# */{
174 * Bind the form-filling behavior.
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);
185 * Get the source form field value as altered by the passed-in parameters.
188 * The source form field value.
190 getTransliterated() {
191 let from = this.source.val();
193 from = from.toLowerCase().replace(this.exclude, this.replace);
199 * Populate the target form field with the altered source field value.
202 const transliterated = this.getTransliterated();
203 const suffix = this.suffix;
204 this.target.each(function (i) {
205 // Ensure that the maxlength is not exceeded by prepopulating the field.
206 const maxlength = $(this).attr('maxlength') - suffix.length;
207 $(this).val(transliterated.substr(0, maxlength) + suffix);
212 * Stop prepopulating the form fields.
215 this.source.off('keyup.viewsUi change.viewsUi', this.populate);
216 this.target.off('focus.viewsUi', this.unbind);
220 * Bind event handlers to new form fields, after they're replaced via Ajax.
222 * @param {jQuery} $fields
223 * Fields to rebind functionality to.
226 this.target = $fields;
232 * Adds functionality for the add item form.
234 * @type {Drupal~behavior}
236 * @prop {Drupal~behaviorAttach} attach
237 * Attaches the functionality in {@link Drupal.viewsUi.AddItemForm} to the
240 Drupal.behaviors.addItemForm = {
242 const $context = $(context);
243 let $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"]');
248 if ($form.once('views-ui-add-handler-form').length) {
249 // If we we have an unprocessed views-ui-add-handler-form, let's
251 new Drupal.viewsUi.AddItemForm($form);
257 * Constructs a new AddItemForm.
261 * @param {jQuery} $form
262 * The form element used.
264 Drupal.viewsUi.AddItemForm = function ($form) {
270 this.$form.find('.views-filterable-options :checkbox').on('click', $.proxy(this.handleCheck, this));
273 * Find the wrapper of the displayed text.
275 this.$selected_div = this.$form.find('.views-selected-options').parent();
276 this.$selected_div.hide();
282 this.checkedItems = [];
286 * Handles a checkbox check.
288 * @param {jQuery.Event} event
289 * The event triggered.
291 Drupal.viewsUi.AddItemForm.prototype.handleCheck = function (event) {
292 const $target = $(event.target);
293 const label = $.trim($target.closest('td').next().html());
294 // Add/remove the checked item to the list.
295 if ($target.is(':checked')) {
296 this.$selected_div.show().css('display', 'block');
297 this.checkedItems.push(label);
300 const position = $.inArray(label, this.checkedItems);
301 // Delete the item from the list and make sure that the list doesn't have
302 // undefined items left.
303 for (let i = 0; i < this.checkedItems.length; i++) {
304 if (i === position) {
305 this.checkedItems.splice(i, 1);
310 // Hide it again if none item is selected.
311 if (this.checkedItems.length === 0) {
312 this.$selected_div.hide();
315 this.refreshCheckedItems();
319 * Refresh the display of the checked items.
321 Drupal.viewsUi.AddItemForm.prototype.refreshCheckedItems = function () {
322 // Perhaps we should precache the text div, too.
323 this.$selected_div.find('.views-selected-options')
324 .html(this.checkedItems.join(', '))
325 .trigger('dialogContentResize');
329 * The input field items that add displays must be rendered as `<input>`
330 * elements. The following behavior detaches the `<input>` elements from the
331 * DOM, wraps them in an unordered list, then appends them to the list of
334 * @type {Drupal~behavior}
336 * @prop {Drupal~behaviorAttach} attach
337 * Fixes the input elements needed.
339 Drupal.behaviors.viewsUiRenderAddViewButton = {
341 // Build the add display menu and pull the display input buttons into it.
342 const $menu = $(context).find('#views-display-menu-tabs').once('views-ui-render-add-view-button');
347 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>`);
348 const $displayButtons = $menu.nextAll('input.add-display').detach();
349 $displayButtons.appendTo($addDisplayDropdown.find('.action-list')).wrap('<li>')
350 .parent().eq(0).addClass('first').end().eq(-1).addClass('last');
351 // Remove the 'Add ' prefix from the button labels since they're being
352 // placed in an 'Add' dropdown. @todo This assumes English, but so does
353 // $addDisplayDropdown above. Add support for translation.
354 $displayButtons.each(function () {
355 const label = $(this).val();
356 if (label.substr(0, 4) === 'Add ') {
357 $(this).val(label.substr(4));
360 $addDisplayDropdown.appendTo($menu);
362 // Add the click handler for the add display button.
363 $menu.find('li.add > a').on('click', function (event) {
364 event.preventDefault();
365 const $trigger = $(this);
366 Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
368 // Add a mouseleave handler to close the dropdown when the user mouses
369 // away from the item. We use mouseleave instead of mouseout because
370 // the user is going to trigger mouseout when she moves from the trigger
371 // link to the sub menu items.
372 // We use the live binder because the open class on this item will be
373 // toggled on and off and we want the handler to take effect in the cases
374 // that the class is present, but not when it isn't.
375 $('li.add', $menu).on('mouseleave', function (event) {
376 const $this = $(this);
377 const $trigger = $this.children('a[href="#"]');
378 if ($this.children('.action-list').is(':visible')) {
379 Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
386 * Toggle menu visibility.
388 * @param {jQuery} $trigger
389 * The element where the toggle was triggered.
392 * @note [@jessebeach] I feel like the following should be a more generic
393 * function and not written specifically for this UI, but I'm not sure
396 Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu = function ($trigger) {
397 $trigger.parent().toggleClass('open');
398 $trigger.next().slideToggle('fast');
402 * Add search options to the views ui.
404 * @type {Drupal~behavior}
406 * @prop {Drupal~behaviorAttach} attach
407 * Attaches {@link Drupal.viewsUi.OptionsSearch} to the views ui filter
410 Drupal.behaviors.viewsUiSearchOptions = {
412 const $context = $(context);
413 let $form = $context;
414 // The add handler form may have an id of views-ui-add-handler-form--n.
415 if (!$context.is('form[id^="views-ui-add-handler-form"]')) {
416 $form = $context.find('form[id^="views-ui-add-handler-form"]');
418 // Make sure we don't add more than one event handler to the same form.
419 if ($form.once('views-ui-filter-options').length) {
420 new Drupal.viewsUi.OptionsSearch($form);
426 * Constructor for the viewsUi.OptionsSearch object.
428 * The OptionsSearch object filters the available options on a form according
429 * to the user's search term. Typing in "taxonomy" will show only those
430 * options containing "taxonomy" in their label.
434 * @param {jQuery} $form
437 Drupal.viewsUi.OptionsSearch = function ($form) {
444 // Click on the title checks the box.
445 this.$form.on('click', 'td.title', (event) => {
446 const $target = $(event.currentTarget);
447 $target.closest('tr').find('input').trigger('click');
450 const searchBoxSelector = '[data-drupal-selector="edit-override-controls-options-search"]';
451 const controlGroupSelector = '[data-drupal-selector="edit-override-controls-group"]';
452 this.$form.on('formUpdated', `${searchBoxSelector},${controlGroupSelector}`, $.proxy(this.handleFilter, this));
454 this.$searchBox = this.$form.find(searchBoxSelector);
455 this.$controlGroup = this.$form.find(controlGroupSelector);
458 * Get a list of option labels and their corresponding divs and maintain it
459 * in memory, so we have as little overhead as possible at keyup time.
461 this.options = this.getOptions(this.$form.find('.filterable-option'));
463 // Trap the ENTER key in the search box so that it doesn't submit the form.
464 this.$searchBox.on('keypress', (event) => {
465 if (event.which === 13) {
466 event.preventDefault();
471 $.extend(Drupal.viewsUi.OptionsSearch.prototype, /** @lends Drupal.viewsUi.OptionsSearch# */{
474 * Assemble a list of all the filterable options on the form.
476 * @param {jQuery} $allOptions
477 * A jQuery object representing the rows of filterable options to be
478 * shown and hidden depending on the user's search terms.
481 * An array of all the filterable options.
483 getOptions($allOptions) {
488 const length = $allOptions.length;
489 for (let i = 0; i < length; i++) {
490 $option = $($allOptions[i]);
491 $title = $option.find('.title');
492 $description = $option.find('.description');
494 // Search on the lowercase version of the title text + description.
495 searchText: `${$title.text().toLowerCase()} ${$description.text().toLowerCase()}`,
496 // Maintain a reference to the jQuery object for each row, so we don't
497 // have to create a new object inside the performance-sensitive keyup
506 * Filter handler for the search box and type select that hides or shows the relevant
509 * @param {jQuery.Event} event
510 * The formUpdated event.
512 handleFilter(event) {
513 // Determine the user's search query. The search text has been converted
515 const search = this.$searchBox.val().toLowerCase();
516 const words = search.split(' ');
517 // Get selected Group
518 const group = this.$controlGroup.val();
520 // Search through the search texts in the form for matching text.
521 this.options.forEach((option) => {
522 function hasWord(word) {
523 return option.searchText.indexOf(word) !== -1;
527 // Each word in the search string has to match the item in order for the
530 found = words.every(hasWord);
532 if (found && group !== 'all') {
533 found = option.$div.hasClass(group);
536 option.$div.toggle(found);
539 // Adapt dialog to content size.
540 $(event.target).trigger('dialogContentResize');
545 * Preview functionality in the views edit form.
547 * @type {Drupal~behavior}
549 * @prop {Drupal~behaviorAttach} attach
550 * Attaches the preview functionality to the view edit form.
552 Drupal.behaviors.viewsUiPreview = {
554 // Only act on the edit view form.
555 const $contextualFiltersBucket = $(context).find('.views-display-column .views-ui-display-tab-bucket.argument');
556 if ($contextualFiltersBucket.length === 0) {
560 // If the display has no contextual filters, hide the form where you
561 // enter the contextual filters for the live preview. If it has contextual
562 // filters, show the form.
563 const $contextualFilters = $contextualFiltersBucket.find('.views-display-setting a');
564 if ($contextualFilters.length) {
565 $('#preview-args').parent().show();
568 $('#preview-args').parent().hide();
571 // Executes an initial preview.
572 if ($('#edit-displays-live-preview').once('edit-displays-live-preview').is(':checked')) {
573 $('#preview-submit').once('edit-displays-live-preview').trigger('click');
579 * Rearranges the filters.
581 * @type {Drupal~behavior}
583 * @prop {Drupal~behaviorAttach} attach
584 * Attach handlers to make it possible to rearange the filters in the form
586 * @see Drupal.viewsUi.RearrangeFilterHandler
588 Drupal.behaviors.viewsUiRearrangeFilter = {
590 // Only act on the rearrange filter form.
591 if (typeof Drupal.tableDrag === 'undefined' || typeof Drupal.tableDrag['views-rearrange-filters'] === 'undefined') {
594 const $context = $(context);
595 const $table = $context.find('#views-rearrange-filters').once('views-rearrange-filters');
596 const $operator = $context.find('.js-form-item-filter-groups-operator').once('views-rearrange-filters');
598 new Drupal.viewsUi.RearrangeFilterHandler($table, $operator);
604 * Improve the UI of the rearrange filters dialog box.
608 * @param {jQuery} $table
609 * The table in the filter form.
610 * @param {jQuery} $operator
611 * The filter groups operator element.
613 Drupal.viewsUi.RearrangeFilterHandler = function ($table, $operator) {
615 * Keep a reference to the `<table>` being altered and to the div containing
616 * the filter groups operator dropdown (if it exists).
624 this.operator = $operator;
630 this.hasGroupOperator = this.operator.length > 0;
633 * Keep a reference to all draggable rows within the table.
637 this.draggableRows = $table.find('.draggable');
640 * Keep a reference to the buttons for adding and removing filter groups.
644 this.addGroupButton = $('input#views-add-group');
649 this.removeGroupButtons = $table.find('input.views-remove-group');
651 // Add links that duplicate the functionality of the (hidden) add and remove
653 this.insertAddRemoveFilterGroupLinks();
655 // When there is a filter groups operator dropdown on the page, create
656 // duplicates of the dropdown between each pair of filter groups.
657 if (this.hasGroupOperator) {
661 this.dropdowns = this.duplicateGroupsOperator();
662 this.syncGroupsOperators();
665 // Add methods to the tableDrag instance to account for operator cells
666 // (which span multiple rows), the operator labels next to each filter
667 // (e.g., "And" or "Or"), the filter groups, and other special aspects of
668 // this tableDrag instance.
669 this.modifyTableDrag();
671 // Initialize the operator labels (e.g., "And" or "Or") that are displayed
672 // next to the filters in each group, and bind a handler so that they change
673 // based on the values of the operator dropdown within that group.
674 this.redrawOperatorLabels();
675 $table.find('.views-group-title select')
676 .once('views-rearrange-filter-handler')
677 .on('change.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
679 // Bind handlers so that when a "Remove" link is clicked, we:
680 // - Update the rowspans of cells containing an operator dropdown (since
681 // they need to change to reflect the number of rows in each group).
682 // - Redraw the operator labels next to the filters in the group (since the
683 // filter that is currently displayed last in each group is not supposed
684 // to have a label display next to it).
685 $table.find('a.views-groups-remove-link')
686 .once('views-rearrange-filter-handler')
687 .on('click.views-rearrange-filter-handler', $.proxy(this, 'updateRowspans'))
688 .on('click.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
691 $.extend(Drupal.viewsUi.RearrangeFilterHandler.prototype, /** @lends Drupal.viewsUi.RearrangeFilterHandler# */{
694 * Insert links that allow filter groups to be added and removed.
696 insertAddRemoveFilterGroupLinks() {
697 // Insert a link for adding a new group at the top of the page, and make
698 // it match the action link styling used in a typical page.html.twig.
699 // Since Drupal does not provide a theme function for this markup this is
700 // the best we can do.
701 $(`<ul class="action-links"><li><a id="views-add-group-link" href="#">${this.addGroupButton.val()}</a></li></ul>`)
702 .prependTo(this.table.parent())
703 // When the link is clicked, dynamically click the hidden form button
704 // for adding a new filter group.
705 .once('views-rearrange-filter-handler')
706 .find('#views-add-group-link')
707 .on('click.views-rearrange-filter-handler', $.proxy(this, 'clickAddGroupButton'));
709 // Find each (visually hidden) button for removing a filter group and
710 // insert a link next to it.
711 const length = this.removeGroupButtons.length;
713 for (i = 0; i < length; i++) {
714 const $removeGroupButton = $(this.removeGroupButtons[i]);
715 const buttonId = $removeGroupButton.attr('id');
716 $(`<a href="#" class="views-remove-group-link">${Drupal.t('Remove group')}</a>`)
717 .insertBefore($removeGroupButton)
718 // When the link is clicked, dynamically click the corresponding form
720 .once('views-rearrange-filter-handler')
721 .on('click.views-rearrange-filter-handler', { buttonId }, $.proxy(this, 'clickRemoveGroupButton'));
726 * Dynamically click the button that adds a new filter group.
728 * @param {jQuery.Event} event
729 * The event triggered.
731 clickAddGroupButton(event) {
732 this.addGroupButton.trigger('mousedown');
733 event.preventDefault();
737 * Dynamically click a button for removing a filter group.
739 * @param {jQuery.Event} event
740 * Event being triggered, with event.data.buttonId set to the ID of the
741 * form button that should be clicked.
743 clickRemoveGroupButton(event) {
744 this.table.find(`#${event.data.buttonId}`).trigger('mousedown');
745 event.preventDefault();
749 * Move the groups operator so that it's between the first two groups, and
750 * duplicate it between any subsequent groups.
753 * An operator element.
755 duplicateGroupsOperator() {
760 const titleRows = $('tr.views-group-title').once('duplicateGroupsOperator');
762 if (!titleRows.length) {
763 return this.operator;
766 // Get rid of the explanatory text around the operator; its placement is
767 // explanatory enough.
768 this.operator.find('label').add('div.description').addClass('visually-hidden');
769 this.operator.find('select').addClass('form-select');
771 // Keep a list of the operator dropdowns, so we can sync their behavior
773 dropdowns = this.operator;
775 // Move the operator to a new row just above the second group.
776 titleRow = $('tr#views-group-title-2');
777 newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
778 newRow.find('td').append(this.operator);
779 newRow.insertBefore(titleRow);
780 const length = titleRows.length;
781 // Starting with the third group, copy the operator to a new row above the
783 for (let i = 2; i < length; i++) {
784 titleRow = $(titleRows[i]);
785 // Make a copy of the operator dropdown and put it in a new table row.
786 const fakeOperator = this.operator.clone();
787 fakeOperator.attr('id', '');
788 newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
789 newRow.find('td').append(fakeOperator);
790 newRow.insertBefore(titleRow);
791 dropdowns.add(fakeOperator);
798 * Make the duplicated groups operators change in sync with each other.
800 syncGroupsOperators() {
801 if (this.dropdowns.length < 2) {
802 // We only have one dropdown (or none at all), so there's nothing to
807 this.dropdowns.on('change', $.proxy(this, 'operatorChangeHandler'));
811 * Click handler for the operators that appear between filter groups.
813 * Forces all operator dropdowns to have the same value.
815 * @param {jQuery.Event} event
816 * The event triggered.
818 operatorChangeHandler(event) {
819 const $target = $(event.target);
820 const operators = this.dropdowns.find('select').not($target);
822 // Change the other operators to match this new value.
823 operators.val($target.val());
830 const tableDrag = Drupal.tableDrag['views-rearrange-filters'];
831 const filterHandler = this;
834 * Override the row.onSwap method from tabledrag.js.
836 * When a row is dragged to another place in the table, several things
838 * - The row needs to be moved so that it's within one of the filter
840 * - The operator cells that span multiple rows need their rowspan
841 * attributes updated to reflect the number of rows in each group.
842 * - The operator labels that are displayed next to each filter need to
843 * be redrawn, to account for the row's new location.
845 tableDrag.row.prototype.onSwap = function () {
846 if (filterHandler.hasGroupOperator) {
847 // Make sure the row that just got moved (this.group) is inside one
848 // of the filter groups (i.e. below an empty marker row or a
849 // draggable). If it isn't, move it down one.
850 const thisRow = $(this.group);
851 const previousRow = thisRow.prev('tr');
852 if (previousRow.length && !previousRow.hasClass('group-message') && !previousRow.hasClass('draggable')) {
853 // Move the dragged row down one.
854 const next = thisRow.next();
856 this.swap('after', next);
859 filterHandler.updateRowspans();
861 // Redraw the operator labels that are displayed next to each filter, to
862 // account for the row's new location.
863 filterHandler.redrawOperatorLabels();
867 * Override the onDrop method from tabledrag.js.
869 tableDrag.onDrop = function () {
870 // If the tabledrag change marker (i.e., the "*") has been inserted
871 // inside a row after the operator label (i.e., "And" or "Or")
872 // rearrange the items so the operator label continues to appear last.
873 const changeMarker = $(this.oldRowElement).find('.tabledrag-changed');
874 if (changeMarker.length) {
875 // Search for occurrences of the operator label before the change
876 // marker, and reverse them.
877 const operatorLabel = changeMarker.prevAll('.views-operator-label');
878 if (operatorLabel.length) {
879 operatorLabel.insertAfter(changeMarker);
883 // Make sure the "group" dropdown is properly updated when rows are
884 // dragged into an empty filter group. This is borrowed heavily from
885 // the block.js implementation of tableDrag.onDrop().
886 const groupRow = $(this.rowObject.element).prevAll('tr.group-message').get(0);
887 const groupName = groupRow.className.replace(/([^ ]+[ ]+)*group-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
888 const groupField = $('select.views-group-select', this.rowObject.element);
889 if ($(this.rowObject.element).prev('tr').is('.group-message') && !groupField.is(`.views-group-select-${groupName}`)) {
890 const oldGroupName = groupField.attr('class').replace(/([^ ]+[ ]+)*views-group-select-([^ ]+)([ ]+[^ ]+)*/, '$2');
891 groupField.removeClass(`views-group-select-${oldGroupName}`).addClass(`views-group-select-${groupName}`);
892 groupField.val(groupName);
898 * Redraw the operator labels that are displayed next to each filter.
900 redrawOperatorLabels() {
901 for (let i = 0; i < this.draggableRows.length; i++) {
902 // Within the row, the operator labels are displayed inside the first
903 // table cell (next to the filter name).
904 const $draggableRow = $(this.draggableRows[i]);
905 const $firstCell = $draggableRow.find('td').eq(0);
906 if ($firstCell.length) {
907 // The value of the operator label ("And" or "Or") is taken from the
908 // first operator dropdown we encounter, going backwards from the
909 // current row. This dropdown is the one associated with the current
910 // row's filter group.
911 const operatorValue = $draggableRow.prevAll('.views-group-title').find('option:selected').html();
912 const operatorLabel = `<span class="views-operator-label">${operatorValue}</span>`;
913 // If the next visible row after this one is a draggable filter row,
914 // display the operator label next to the current row. (Checking for
915 // visibility is necessary here since the "Remove" links hide the
916 // removed row but don't actually remove it from the document).
917 const $nextRow = $draggableRow.nextAll(':visible').eq(0);
918 const $existingOperatorLabel = $firstCell.find('.views-operator-label');
919 if ($nextRow.hasClass('draggable')) {
920 // If an operator label was already there, replace it with the new
922 if ($existingOperatorLabel.length) {
923 $existingOperatorLabel.replaceWith(operatorLabel);
925 // Otherwise, append the operator label to the end of the table
928 $firstCell.append(operatorLabel);
931 // If the next row doesn't contain a filter, then this is the last row
932 // in the group. We don't want to display the operator there (since
933 // operators should only display between two related filters, e.g.
934 // "filter1 AND filter2 AND filter3"). So we remove any existing label
935 // that this row has.
937 $existingOperatorLabel.remove();
944 * Update the rowspan attribute of each cell containing an operator
949 let $currentEmptyRow;
952 const rows = $(this.table).find('tr');
953 const length = rows.length;
954 for (let i = 0; i < length; i++) {
956 if ($row.hasClass('views-group-title')) {
957 // This row is a title row.
958 // Keep a reference to the cell containing the dropdown operator.
959 $operatorCell = $row.find('td.group-operator');
960 // Assume this filter group is empty, until we find otherwise.
962 $currentEmptyRow = $row.next('tr');
963 $currentEmptyRow.removeClass('group-populated').addClass('group-empty');
964 // The cell with the dropdown operator should span the title row and
965 // the "this group is empty" row.
966 $operatorCell.attr('rowspan', 2);
968 else if ($row.hasClass('draggable') && $row.is(':visible')) {
969 // We've found a visible filter row, so we now know the group isn't
972 $currentEmptyRow.removeClass('group-empty').addClass('group-populated');
973 // The operator cell should span all draggable rows, plus the title.
974 $operatorCell.attr('rowspan', draggableCount + 1);
981 * Add a select all checkbox, which checks each checkbox at once.
983 * @type {Drupal~behavior}
985 * @prop {Drupal~behaviorAttach} attach
986 * Attaches select all functionality to the views filter form.
988 Drupal.behaviors.viewsFilterConfigSelectAll = {
990 const $context = $(context);
992 const $selectAll = $context.find('.js-form-item-options-value-all').once('filterConfigSelectAll');
993 const $selectAllCheckbox = $selectAll.find('input[type=checkbox]');
994 const $checkboxes = $selectAll.closest('.form-checkboxes').find('.js-form-type-checkbox:not(.js-form-item-options-value-all) input[type="checkbox"]');
996 if ($selectAll.length) {
997 // Show the select all checkbox.
999 $selectAllCheckbox.on('click', function () {
1000 // Update all checkbox beside the select all checkbox.
1001 $checkboxes.prop('checked', $(this).is(':checked'));
1004 // Uncheck the select all checkbox if any of the others are unchecked.
1005 $checkboxes.on('click', function () {
1006 if ($(this).is('checked') === false) {
1007 $selectAllCheckbox.prop('checked', false);
1015 * Remove icon class from elements that are themed as buttons or dropbuttons.
1017 * @type {Drupal~behavior}
1019 * @prop {Drupal~behaviorAttach} attach
1020 * Removes the icon class from certain views elements.
1022 Drupal.behaviors.viewsRemoveIconClass = {
1024 $(context).find('.dropbutton').once('dropbutton-icon').find('.icon').removeClass('icon');
1029 * Change "Expose filter" buttons into checkboxes.
1031 * @type {Drupal~behavior}
1033 * @prop {Drupal~behaviorAttach} attach
1034 * Changes buttons into checkboxes via {@link Drupal.viewsUi.Checkboxifier}.
1036 Drupal.behaviors.viewsUiCheckboxify = {
1037 attach(context, settings) {
1038 const $buttons = $('[data-drupal-selector="edit-options-expose-button-button"], [data-drupal-selector="edit-options-group-button-button"]').once('views-ui-checkboxify');
1039 const length = $buttons.length;
1041 for (i = 0; i < length; i++) {
1042 new Drupal.viewsUi.Checkboxifier($buttons[i]);
1048 * Change the default widget to select the default group according to the
1049 * selected widget for the exposed group.
1051 * @type {Drupal~behavior}
1053 * @prop {Drupal~behaviorAttach} attach
1054 * Changes the default widget based on user input.
1056 Drupal.behaviors.viewsUiChangeDefaultWidget = {
1058 const $context = $(context);
1060 function changeDefaultWidget(event) {
1061 if ($(event.target).prop('checked')) {
1062 $context.find('input.default-radios').parent().hide();
1063 $context.find('td.any-default-radios-row').parent().hide();
1064 $context.find('input.default-checkboxes').parent().show();
1067 $context.find('input.default-checkboxes').parent().hide();
1068 $context.find('td.any-default-radios-row').parent().show();
1069 $context.find('input.default-radios').parent().show();
1073 // Update on widget change.
1074 $context.find('input[name="options[group_info][multiple]"]')
1075 .on('change', changeDefaultWidget)
1076 // Update the first time the form is rendered.
1082 * Attaches expose filter button to a checkbox that triggers its click event.
1086 * @param {HTMLElement} button
1087 * The DOM object representing the button to be checkboxified.
1089 Drupal.viewsUi.Checkboxifier = function (button) {
1090 this.$button = $(button);
1091 this.$parent = this.$button.parent('div.views-expose, div.views-grouped');
1092 this.$input = this.$parent.find('input:checkbox, input:radio');
1093 // Hide the button and its description.
1094 this.$button.hide();
1095 this.$parent.find('.exposed-description, .grouped-description').hide();
1097 this.$input.on('click', $.proxy(this, 'clickHandler'));
1101 * When the checkbox is checked or unchecked, simulate a button press.
1103 * @param {jQuery.Event} e
1104 * The event triggered.
1106 Drupal.viewsUi.Checkboxifier.prototype.clickHandler = function (e) {
1113 * Change the Apply button text based upon the override select state.
1115 * @type {Drupal~behavior}
1117 * @prop {Drupal~behaviorAttach} attach
1118 * Attaches behavior to change the Apply button according to the current
1121 Drupal.behaviors.viewsUiOverrideSelect = {
1123 $(context).find('[data-drupal-selector="edit-override-dropdown"]').once('views-ui-override-button-text').each(function () {
1125 const $context = $(context);
1126 const $submit = $context.find('[id^=edit-submit]');
1127 const old_value = $submit.val();
1129 $submit.once('views-ui-override-button-text')
1130 .on('mouseup', function () {
1131 $(this).val(old_value);
1135 $(this).on('change', function () {
1136 const $this = $(this);
1137 if ($this.val() === 'default') {
1138 $submit.val(Drupal.t('Apply (all displays)'));
1140 else if ($this.val() === 'default_revert') {
1141 $submit.val(Drupal.t('Revert to default'));
1144 $submit.val(Drupal.t('Apply (this display)'));
1146 const $dialog = $context.closest('.ui-dialog-content');
1147 $dialog.trigger('dialogButtonsChange');
1155 * Functionality for the remove link in the views UI.
1157 * @type {Drupal~behavior}
1159 * @prop {Drupal~behaviorAttach} attach
1160 * Attaches behavior for the remove view and remove display links.
1162 Drupal.behaviors.viewsUiHandlerRemoveLink = {
1164 const $context = $(context);
1165 // Handle handler deletion by looking for the hidden checkbox and hiding
1167 $context.find('a.views-remove-link').once('views').on('click', function (event) {
1168 const id = $(this).attr('id').replace('views-remove-link-', '');
1169 $context.find(`#views-row-${id}`).hide();
1170 $context.find(`#views-removed-${id}`).prop('checked', true);
1171 event.preventDefault();
1174 // Handle display deletion by looking for the hidden checkbox and hiding
1176 $context.find('a.display-remove-link').once('display').on('click', function (event) {
1177 const id = $(this).attr('id').replace('display-remove-link-', '');
1178 $context.find(`#display-row-${id}`).hide();
1179 $context.find(`#display-removed-${id}`).prop('checked', true);
1180 event.preventDefault();
1184 }(jQuery, Drupal, drupalSettings));