PageSourceSearch

https://gardenclub.org/modules/contrib/better_exposed_filters/js/auto_submit.js?tlq6l1

js gardenclub.org collected 2026-10-01 10:37:35 UTC 7,822 bytes, 201 lines download raw bytes

1/**
2 * @file
3 * auto_submit.js
4 *
5 * Provides a "form auto-submit" feature for the Better Exposed Filters module.
6 */
7
8(function ($, Drupal, once) {
9
10  /**
11   * To make a form auto submit, all you have to do is 3 things:.
12   *
13   * Use the "better_exposed_filters/auto_submit" js library.
14   *
15   * On gadgets, you want to auto-submit when changed, add the
16   * data-bef-auto-submit attribute. With FAPI, add:
17   * @code
18   *  '#attributes' => array('data-bef-auto-submit' => ''),
19   * @endcode
20   *
21   * If you want to have auto-submit for every form element, add the
22   * data-bef-auto-submit-full-form to the form. With FAPI, add:
23   * @code
24   *   '#attributes' => array('data-bef-auto-submit-full-form' => ''),
25   * @endcode
26   *
27   * If you want to exclude a field from the bef-auto-submit-full-form auto
28   * submission, add an attribute of data-bef-auto-submit-exclude to the form
29   * element. With FAPI, add:
30   * @code
31   *   '#attributes' => array('data-bef-auto-submit-exclude' => ''),
32   * @endcode
33   *
34   * Finally, you have to identify which button you want clicked for autosubmit.
35   * The behavior of this button will be honored if it's ajax or not:
36   * @code
37   *  '#attributes' => array('data-bef-auto-submit-click' => ''),
38   * @endcode
39   *
40   * Currently only 'select', 'radio', 'checkbox' and 'textfield' types are
41   * supported. We probably could use additional support for HTML5 input types.
42   */
43  Drupal.behaviors.betterExposedFiltersAutoSubmit = {
44    attach: function (context, settings) {
45
46      let selectors = '';
47      if (drupalSettings.better_exposed_filters.auto_submit_sort_only
47) {
48        selectors = 'form[data-bef-auto-submit-sort-only] .form-item-sort-order';
49      }
50      else {
51        // When exposed as a block, the form #attributes are moved from the form
52        // to the block element, thus the second selector.
53        // @see \Drupal\block\BlockViewBuilder::preRender
54        selectors = 'form[data-bef-auto-submit-full-form], [data-bef-auto-submit-full-form] form, [data-bef-auto-submit]';
55      }
56
57      $(selectors, context).addBack(selectors).find('input:text:not(.hasDatepicker), textarea').each(function () {
58        const $el = $(this);
59        const $valueLength = $el.val().length * 2;
60
61        $el[0].setSelectionRange($valueLength, $valueLength);
62        setFocus($el, $valueLength);
63      });
64
65      function setFocus($el) {
66        const observer = new IntersectionObserver((entries) => {
67
68          entries.forEach(entry => {
69            if (entry.isIntersecting) {
70              const $lastTriggeredSelector = $(settings.bef_autosubmit_target).attr('data-drupal-selector');
71              if ($el.attr('data-drupal-selector') && $el.attr('data-drupal-selector') === $lastTriggeredSelector) {
72                $el.focus();
73              }
74            }
75          });
76        });
77
78        observer.observe($el.get(0));
79      }
80
81      // The change event bubbles, so we only need to bind it to the outer form
82      // in case of a full form, or a single element when specified explicitly.
83      $(selectors, context).addBack(selectors).each(function (i, e) {
84        const $e = $(e);
85        // Store the current form.
86        let $needsAutoSubmit = $e;
87
88        // Retrieve the autosubmit delay for this particular form.
89        let autoSubmitDelay = 500;
90        if (e.hasAttribute('data-bef-auto-submit-delay')) {
91          autoSubmitDelay = $e.data('bef-auto-submit-delay');
92        }
93        else if (!e.hasAttribute('data-bef-auto-submit-full-form')) {
94          // Find the container but skip checking if this element already is
95          // 'form[data-bef-auto-submit-full-form]'.
96          const $container = $e.closest('[data-bef-auto-submit-full-form]');
97          if ($container.length && $container.get(0).hasAttribute('data-bef-auto-submit-delay')) {
98            $needsAutoSubmit = $container;
99            autoSubmitDelay = $container.data('bef-auto-submit-delay');
100          }
101        }
102
103        // Ensure that have a delay.
104        autoSubmitDelay = autoSubmitDelay || 500;
105        // Separate debounce instance for date inputs change event.
106        let dateInputChangeDebounce = Drupal.debounce(triggerSubmit, autoSubmitDelay, false);
107
108        // Attach event listeners.
109        $(once('bef-auto-submit', $needsAutoSubmit))
110          // On change, trigger the submit immediately unless it's a date
111          // input which emits change event as soon as the date value is
112          // valid, even if user is still typing.
113          .on('change', function (e) {
114            return e.target.type === 'date'
115              ? dateInputChangeDebounce(e)
116              : triggerSubmit(e);
117          })
118          // On keyup, wait for a specified number of milliseconds before
119          // triggering autosubmit. Each new keyup event resets the timer.
120          .on('keyup', Drupal.debounce(triggerSubmit, autoSubmitDelay, false));
121      });
122
123      /**
124       * Triggers form autosubmit when conditions are right.
125       *
126       * - Checks first that the element that was the target of the triggering
127       *   event is `:text` or `textarea`, but is not `.hasDatePicker`.
128       * - Checks that the keycode of the keyup was not in the list of ignored
129       *   keys (navigation keys etc.).
130       *
131       * @param {object} e - The triggering event.
132       */
133      function triggerSubmit(e) {
134        // e.keyCode: key.
135        const ignoredKeyCodes = [
136          16, // Shift.
137          17, // Ctrl.
138          18, // Alt.
139          20, // Caps lock.
140          33, // Page up.
141          34, // Page down.
142          35, // End.
143          36, // Home.
144          37, // Left arrow.
145          38, // Up arrow.
146          39, // Right arrow.
147          40, // Down arrow.
148          9, // Tab.
149          13, // Enter.
150          27,  // Esc.
151          32, // Space.
152        ];
153
154        // Triggering element.
155        const $target = $(e.target);
156        const $form = e.target.form ? $(e.target.form) : $target.closest('form');
157        const $submit = $form.find('[data-bef-auto-submit-click]');
158        const mediaQuery = $target.closest('form').data('bef-auto-submit-media-query');
159
160        // Don't submit when the document doesn't match the media query string.
161        if (mediaQuery && !matchMedia(mediaQuery).matches) {
162          return true;
163        }
164
165        // Don't submit on changes to excluded elements,submit elements, or select2 autocomplete.
166        if ($target.is('[data-bef-auto-submit-exclude], :submit, .select2-search__field, .chosen-search-input')) {
167          return true;
168        }
169
170        // Submit only if this is a non-datepicker textfield and if the
171        // incoming keycode is not one of the excluded values, and it has a
172        // minimum character length.
173        let textfieldMinimumLength = $target.closest('form').data('bef-auto-submit-minimum-length') || 1;
174        let inputTextLength = $target.val().length;
175        let textfieldHasMinimumLength = ($target.is(':text:not(.hasDatepicker), textarea') && inputTextLength >= textfieldMinimumLength) || $target.is('[type="checkbox"], [type="radio"]');
176        if (
177          (textfieldHasMinimumLength || inputTextLength === 0)
178          && $.inArray(e.keyCode, ignoredKeyCodes) === -1
179          && !e.altKey
180          && !e.ctrlKey
181          && !e.shiftKey
182        ) {
183          $submit.click();
184        }
185        // Only trigger submit if a change was the trigger (no keyup).
186        else if (e.type === 'change') {
187          let target = $target.is(':text:not(.hasDatepicker), textarea');
188          if (target && textfieldHasMinimumLength) {
189            $submit.click();
190          }
191          else if (!target) {
192            $submit.click();
193          }
194        }
195
196        settings.bef_autosubmit_target = $target;
197      }
198    },
199  };
200
201}(jQuery, Drupal, once));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.