summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/media_library/js/media_library.ui.js
blob: 10fe212f4a57af7ed7a51304fc21ee252575ea3b (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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/**
 * @file media_library.ui.js
 */
(($, Drupal, window, { tabbable }) => {
  /**
   * Wrapper object for the current state of the media library.
   */
  Drupal.MediaLibrary = {
    /**
     * When a user interacts with the media library we want the selection to
     * persist as long as the media library modal is opened. We temporarily
     * store the selected items while the user filters the media library view or
     * navigates to different tabs.
     */
    currentSelection: [],
  };

  /**
   * Command to update the current media library selection.
   *
   * @param {Drupal.Ajax} [ajax]
   *   The Drupal Ajax object.
   * @param {object} response
   *   Object holding the server response.
   * @param {number} [status]
   *   The HTTP status code.
   */
  Drupal.AjaxCommands.prototype.updateMediaLibrarySelection = function (
    ajax,
    response,
    status,
  ) {
    Object.values(response.mediaIds).forEach((value) => {
      Drupal.MediaLibrary.currentSelection.push(value);
    });
  };

  /**
   * Load media library content through AJAX.
   *
   * Standard AJAX links (using the 'use-ajax' class) replace the entire library
   * dialog. When navigating to a media type through the vertical tabs, we only
   * want to load the changed library content. This is not only more efficient,
   * but also provides a more accessible user experience for screen readers.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches behavior to vertical tabs in the media library.
   *
   * @todo Remove when the AJAX system adds support for replacing a specific
   *   selector via a link.
   *   https://www.drupal.org/project/drupal/issues/3026636
   */
  Drupal.behaviors.MediaLibraryTabs = {
    attach(context) {
      const $menu = $('.js-media-library-menu');
      $(once('media-library-menu-item', $menu.find('a')))
        .on('keypress', (e) => {
          // The AJAX link has the button role, so we need to make sure the link
          // is also triggered when pressing the space bar.
          if (e.which === 32) {
            e.preventDefault();
            e.stopPropagation();
            $(e.currentTarget).trigger('click');
          }
        })
        .on('click', (e) => {
          e.preventDefault();
          e.stopPropagation();

          // Replace the library content.
          const ajaxObject = Drupal.ajax({
            wrapper: 'media-library-content',
            url: e.currentTarget.href,
            dialogType: 'ajax',
            progress: {
              type: 'fullscreen',
              message: Drupal.t('Processing...'),
            },
          });

          // Override the AJAX success callback to shift focus to the media
          // library content.
          ajaxObject.success = function (response, status) {
            return Promise.resolve(
              Drupal.Ajax.prototype.success.call(ajaxObject, response, status),
            ).then(() => {
              // Set focus to the first tabbable element in the media library
              // content.
              const mediaLibraryContent = document.getElementById(
                'media-library-content',
              );
              if (mediaLibraryContent) {
                const tabbableContent = tabbable(mediaLibraryContent);
                if (tabbableContent.length) {
                  tabbableContent[0].focus();
                }
              }
            });
          };
          ajaxObject.execute();

          // Set the selected tab.
          $menu.find('.active-tab').remove();
          $menu.find('a').removeClass('active');
          $(e.currentTarget)
            .addClass('active')
            .html(
              Drupal.t(
                '<span class="visually-hidden">Show </span>@title<span class="visually-hidden"> media</span><span class="active-tab visually-hidden"> (selected)</span>',
                { '@title': $(e.currentTarget).data('title') },
              ),
            );

          // Announce the updated content.
          Drupal.announce(
            Drupal.t('Showing @title media.', {
              '@title': $(e.currentTarget).data('title'),
            }),
          );
        });
    },
  };

  /**
   * Load media library displays through AJAX.
   *
   * Standard AJAX links (using the 'use-ajax' class) replace the entire library
   * dialog. When navigating to a media library views display, we only want to
   * load the changed views display content. This is not only more efficient,
   * but also provides a more accessible user experience for screen readers.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches behavior to vertical tabs in the media library.
   *
   * @todo Remove when the AJAX system adds support for replacing a specific
   *   selector via a link.
   *   https://www.drupal.org/project/drupal/issues/3026636
   */
  Drupal.behaviors.MediaLibraryViewsDisplay = {
    attach(context) {
      const $view = $(context).hasClass('.js-media-library-view')
        ? $(context)
        : $('.js-media-library-view', context);

      // Add a class to the view to allow it to be replaced via AJAX.
      // @todo Remove the custom ID when the AJAX system allows replacing
      //    elements by selector.
      //    https://www.drupal.org/project/drupal/issues/2821793
      $view
        .closest('.views-element-container')
        .attr('id', 'media-library-view');

      // We would ideally use a generic JavaScript specific class to detect the
      // display links. Since we have no good way of altering display links yet,
      // this is the best we can do for now.
      // @todo Add media library specific classes and data attributes to the
      //    media library display links when we can alter display links.
      //    https://www.drupal.org/project/drupal/issues/3036694
      $(
        once(
          'media-library-views-display-link',
          '.views-display-link-widget, .views-display-link-widget_table',
          context,
        ),
      ).on('click', (e) => {
        e.preventDefault();
        e.stopPropagation();

        const $link = $(e.currentTarget);

        // Add a loading and display announcement for screen reader users.
        let loadingAnnouncement = '';
        let displayAnnouncement = '';
        let focusSelector = '';
        if ($link.hasClass('views-display-link-widget')) {
          loadingAnnouncement = Drupal.t('Loading grid view.');
          displayAnnouncement = Drupal.t('Changed to grid view.');
          focusSelector = '.views-display-link-widget';
        } else if ($link.hasClass('views-display-link-widget_table')) {
          loadingAnnouncement = Drupal.t('Loading table view.');
          displayAnnouncement = Drupal.t('Changed to table view.');
          focusSelector = '.views-display-link-widget_table';
        }

        // Replace the library view.
        const ajaxObject = Drupal.ajax({
          wrapper: 'media-library-view',
          url: e.currentTarget.href,
          dialogType: 'ajax',
          progress: {
            type: 'fullscreen',
            message: loadingAnnouncement || Drupal.t('Processing...'),
          },
        });

        // Override the AJAX success callback to announce the updated content
        // to screen readers.
        if (displayAnnouncement || focusSelector) {
          const success = ajaxObject.success;
          ajaxObject.success = function (response, status) {
            success.bind(this)(response, status);
            // The AJAX link replaces the whole view, including the clicked
            // link. Move the focus back to the clicked link when the view is
            // replaced.
            if (focusSelector) {
              $(focusSelector).focus();
            }
            // Announce the new view is loaded to screen readers.
            if (displayAnnouncement) {
              Drupal.announce(displayAnnouncement);
            }
          };
        }

        ajaxObject.execute();

        // Announce the new view is being loaded to screen readers.
        // @todo Replace custom announcement when
        //   https://www.drupal.org/project/drupal/issues/2973140 is in.
        if (loadingAnnouncement) {
          Drupal.announce(loadingAnnouncement);
        }
      });
    },
  };

  /**
   * Update the media library selection when loaded or media items are selected.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches behavior to select media items.
   */
  Drupal.behaviors.MediaLibraryItemSelection = {
    attach(context, settings) {
      const $form = $(
        '.js-media-library-views-form, .js-media-library-add-form',
        context,
      );
      const currentSelection = Drupal.MediaLibrary.currentSelection;

      if (!$form.length) {
        return;
      }

      const $mediaItems = $(
        '.js-media-library-item input[type="checkbox"]',
        $form,
      );

      /**
       * Disable media items.
       *
       * @param {jQuery} $items
       *   A jQuery object representing the media items that should be disabled.
       */
      function disableItems($items) {
        $items
          .prop('disabled', true)
          .closest('.js-media-library-item')
          .addClass('media-library-item--disabled');
      }

      /**
       * Enable media items.
       *
       * @param {jQuery} $items
       *   A jQuery object representing the media items that should be enabled.
       */
      function enableItems($items) {
        $items
          .prop('disabled', false)
          .closest('.js-media-library-item')
          .removeClass('media-library-item--disabled');
      }

      /**
       * Update the number of selected items in the button pane.
       *
       * @param {number} remaining
       *   The number of remaining slots.
       */
      function updateSelectionCount(remaining) {
        // When the remaining number of items is a negative number, we allow an
        // unlimited number of items. In that case we don't want to show the
        // number of remaining slots.
        const selectItemsText =
          remaining < 0
            ? Drupal.formatPlural(
                currentSelection.length,
                '1 item selected',
                '@count items selected',
              )
            : Drupal.formatPlural(
                remaining,
                '@selected of @count item selected',
                '@selected of @count items selected',
                {
                  '@selected': currentSelection.length,
                },
              );
        // The selected count div could have been created outside of the
        // context, so we unfortunately can't use context here.
        $('.js-media-library-selected-count').html(selectItemsText);
      }

      function checkEnabled() {
        updateSelectionCount(settings.media_library.selection_remaining);
        if (
          currentSelection.length === settings.media_library.selection_remaining
        ) {
          disableItems($mediaItems.not(':checked'));
          enableItems($mediaItems.filter(':checked'));
        } else {
          enableItems($mediaItems);
        }
      }
      // Update the selection array and the hidden form field when a media item
      // is selected.
      $(once('media-item-change', $mediaItems)).on('change', (e) => {
        const id = e.currentTarget.value;

        // Update the selection.
        if (e.currentTarget.checked) {
          // Check if the ID is not already in the selection and add if needed.
          if (!currentSelection.includes(id)) {
            currentSelection.push(id);
          }
        } else if (currentSelection.includes(id)) {
          // Remove the ID when it is in the current selection.
          currentSelection.splice(currentSelection.indexOf(id), 1);
        }

        const mediaLibraryModalSelection = document.querySelector(
          '#media-library-modal-selection',
        );

        if (mediaLibraryModalSelection) {
          // Set the selection in the hidden form element.
          mediaLibraryModalSelection.value = currentSelection.join();
          $(mediaLibraryModalSelection).trigger('change');
        }

        // Set the selection in the media library add form. Since the form is
        // not necessarily loaded within the same context, we can't use the
        // context here.
        document
          .querySelectorAll('.js-media-library-add-form-current-selection')
          .forEach((item) => {
            item.value = currentSelection.join();
          });
      });
      checkEnabled();
      // The hidden selection form field changes when the selection is updated.
      $(
        once(
          'media-library-selection-change',
          $form.find('#media-library-modal-selection'),
        ),
      ).on('change', (e) => {
        checkEnabled();
      });

      // Apply the current selection to the media library view. Changing the
      // checkbox values triggers the change event for the media items. The
      // change event handles updating the hidden selection field for the form.
      currentSelection.forEach((value) => {
        $form
          .find(`input[type="checkbox"][value="${value}"]`)
          .prop('checked', true)
          .trigger('change');
      });

      // Add the selection count to the button pane when a media library dialog
      // is created.
      if (!once('media-library-selection-info', 'html').length) {
        return;
      }
      window.addEventListener('dialog:aftercreate', () => {
        // Since the dialog HTML is not part of the context, we can't use
        // context here.
        const $buttonPane = $(
          '.media-library-widget-modal .ui-dialog-buttonpane',
        );
        if (!$buttonPane.length) {
          return;
        }
        $buttonPane.append(Drupal.theme('mediaLibrarySelectionCount'));
        updateSelectionCount(settings.media_library.selection_remaining);
      });
    },
  };

  /**
   * Clear the current selection.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches behavior to clear the selection when the library modal closes.
   */
  Drupal.behaviors.MediaLibraryModalClearSelection = {
    attach() {
      if (!once('media-library-clear-selection', 'html').length) {
        return;
      }
      window.addEventListener('dialog:afterclose', () => {
        // This empty the array while keeping the existing array reference,
        // to keep event listeners working.
        Drupal.MediaLibrary.currentSelection.length = 0;
      });
    },
  };

  /**
   * Theme function for the selection count.
   *
   * @return {string}
   *   The corresponding HTML.
   */
  Drupal.theme.mediaLibrarySelectionCount = function () {
    return `<div class="media-library-selected-count js-media-library-selected-count" role="status" aria-live="polite" aria-atomic="true"></div>`;
  };
})(jQuery, Drupal, window, window.tabbable);