summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/user/js/user.permissions.js
blob: e8a84607c592c6824710e2d475115cc552bc2d47 (plain) (blame)
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
/**
 * @file
 * User permission page behaviors.
 */

(function ($, Drupal, debounce) {
  /**
   * Shows checked and disabled checkboxes for inherited permissions.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches functionality to the permissions table.
   */
  Drupal.behaviors.permissions = {
    attach() {
      const [table] = once('permissions', 'table#permissions');
      if (!table) {
        return;
      }

      // Create fake checkboxes. We use fake checkboxes instead of reusing
      // the existing checkboxes here because new checkboxes don't alter the
      // submitted form. If we'd automatically check existing checkboxes, the
      // permission table would be polluted with redundant entries. This is
      // deliberate, but desirable when we automatically check them.
      const $fakeCheckbox = $(Drupal.theme('checkbox'))
        .removeClass('form-checkbox')
        .addClass('fake-checkbox js-fake-checkbox')
        .attr({
          disabled: 'disabled',
          checked: 'checked',
          title: Drupal.t(
            'This permission is inherited from the authenticated user role.',
          ),
        });
      const $wrapper = $('<div></div>').append($fakeCheckbox);
      const fakeCheckboxHtml = $wrapper.html();

      /**
       * Process each table row to create fake checkboxes.
       *
       * @param {object} object
       * @param {HTMLElement} object.target
       */
      function tableRowProcessing({ target }) {
        once('permission-checkbox', target).forEach((checkbox) => {
          checkbox
            .closest('tr')
            .querySelectorAll(
              'input[type="checkbox"]:not(.js-rid-anonymous, .js-rid-authenticated)',
            )
            .forEach((check) => {
              check.classList.add('real-checkbox', 'js-real-checkbox');
              check.insertAdjacentHTML('beforebegin', fakeCheckboxHtml);
            });
        });
      }

      // An IntersectionObserver object is associated with each of the table
      // rows to activate checkboxes interactively as users scroll the page
      // up or down. This prevents processing all checkboxes on page load.
      const checkedCheckboxObserver = new IntersectionObserver(
        (entries, thisObserver) => {
          entries
            .filter((entry) => entry.isIntersecting)
            .forEach((entry) => {
              tableRowProcessing(entry);
              thisObserver.unobserve(entry.target);
            });
        },
        {
          rootMargin: '50%',
        },
      );

      // Select rows with checked authenticated role and attach an observer
      // to each.
      table
        .querySelectorAll(
          'tbody tr input[type="checkbox"].js-rid-authenticated:checked',
        )
        .forEach((checkbox) => checkedCheckboxObserver.observe(checkbox));

      // Create checkboxes only when necessary on click.
      $(table).on(
        'click.permissions',
        'input[type="checkbox"].js-rid-authenticated',
        tableRowProcessing,
      );
    },
  };

  /**
   * Filters the permission list table by a text input search string.
   *
   * Text search input: input.table-filter-text
   * Target table:      input.table-filter-text[data-table]
   * Source text:       .table-filter-text-source
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.tableFilterByText = {
    attach(context, settings) {
      const [input] = once('table-filter-text', 'input.table-filter-text');
      if (!input) {
        return;
      }
      const tableSelector = input.getAttribute('data-table');
      const $table = $(tableSelector);
      const $rows = $table.find('tbody tr');

      function hideEmptyPermissionHeader(index, row) {
        const tdsWithModuleClass = row.querySelectorAll('td.module');
        // Function to check if an element is visible (`display: block`).
        function isVisible(element) {
          return getComputedStyle(element).display !== 'none';
        }
        if (tdsWithModuleClass.length > 0) {
          // Find the next visible sibling `<tr>`.
          let nextVisibleSibling = row.nextElementSibling;
          while (nextVisibleSibling && !isVisible(nextVisibleSibling)) {
            nextVisibleSibling = nextVisibleSibling.nextElementSibling;
          }

          // Check if the next visible sibling has the "module" class in any of
          // its `<td>` elements.
          let nextVisibleSiblingHasModuleClass = false;
          if (nextVisibleSibling) {
            const nextSiblingTdsWithModuleClass =
              nextVisibleSibling.querySelectorAll('td.module');
            nextVisibleSiblingHasModuleClass =
              nextSiblingTdsWithModuleClass.length > 0;
          }

          // Check if this is the last visible row with class "module".
          const isLastVisibleModuleRow =
            !nextVisibleSibling || !isVisible(nextVisibleSibling);

          // Hide the current row with class "module" if it meets the
          // conditions.
          $(row).toggle(
            !nextVisibleSiblingHasModuleClass && !isLastVisibleModuleRow,
          );
        }
      }

      function filterPermissionList(e) {
        const query = e.target.value;
        if (query.length === 0) {
          // Reset table when the textbox is cleared.
          $rows.show();
        }
        // Case insensitive expression to find query at the beginning of a word.
        const re = new RegExp(`\\b${query}`, 'i');

        function showPermissionRow(index, row) {
          const sources = row.querySelectorAll('.table-filter-text-source');
          if (sources.length > 0) {
            const textMatch = sources[0].textContent.search(re) !== -1;
            $(row).closest('tr').toggle(textMatch);
          }
        }
        // Search over all rows.
        $rows.show();

        // Filter if the length of the query is at least 2 characters.
        if (query.length >= 2) {
          $rows.each(showPermissionRow);

          // Hide the empty header if they don't have any visible rows.
          const visibleRows = $table.find('tbody tr:visible');
          visibleRows.each(hideEmptyPermissionHeader);
          const rowsWithoutEmptyModuleName = $table.find('tbody tr:visible');
          // Find elements with class "permission" within visible rows.
          const tdsWithModuleOrPermissionClass =
            rowsWithoutEmptyModuleName.find('.permission');

          Drupal.announce(
            Drupal.formatPlural(
              tdsWithModuleOrPermissionClass.length,
              '1 permission is available in the modified list.',
              '@count permissions are available in the modified list.',
            ),
          );
        }
      }

      function preventEnterKey(event) {
        if (event.which === 13) {
          event.preventDefault();
          event.stopPropagation();
        }
      }

      if ($table.length) {
        $(input).on({
          keyup: debounce(filterPermissionList, 200),
          click: debounce(filterPermissionList, 200),
          keydown: preventEnterKey,
        });
      }
    },
  };
})(jQuery, Drupal, Drupal.debounce);