MediaLibraryWidget.php 32.1 KB
Newer Older
1
2
3
4
5
6
<?php

namespace Drupal\media_library\Plugin\Field\FieldWidget;

use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\SortArray;
7
use Drupal\Core\Ajax\AjaxResponse;
8
use Drupal\Core\Ajax\InvokeCommand;
9
use Drupal\Core\Ajax\OpenModalDialogCommand;
10
use Drupal\Core\Ajax\ReplaceCommand;
11
use Drupal\Core\Entity\EntityTypeManagerInterface;
12
use Drupal\Core\Extension\ModuleHandlerInterface;
13
14
15
16
17
18
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
19
20
21
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\field_ui\FieldUI;
22
use Drupal\media\Entity\Media;
23
24
use Drupal\media_library\MediaLibraryUiBuilder;
use Drupal\media_library\MediaLibraryState;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;

/**
 * Plugin implementation of the 'media_library_widget' widget.
 *
 * @FieldWidget(
 *   id = "media_library_widget",
 *   label = @Translation("Media library"),
 *   description = @Translation("Allows you to select items from the media library."),
 *   field_types = {
 *     "entity_reference"
 *   },
 *   multiple_values = TRUE,
 * )
 *
 * @internal
42
43
44
 *   Media Library is an experimental module and its internal code may be
 *   subject to change in minor releases. External code should not instantiate
 *   or extend this class.
45
46
47
48
49
50
51
52
53
54
 */
class MediaLibraryWidget extends WidgetBase implements ContainerFactoryPluginInterface {

  /**
   * Entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

55
56
57
58
59
60
61
62
63
64
65
66
67
68
  /**
   * The current active user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

69
70
71
72
73
74
75
  /**
   * The prefix to use with a field ID for media library opener IDs.
   *
   * @var string
   */
  protected static $openerIdPrefix = 'field:';

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  /**
   * Constructs a MediaLibraryWidget widget.
   *
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the widget is associated.
   * @param array $settings
   *   The widget settings.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
91
92
93
94
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   (optional) The current active user.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   (optional) The module handler.
95
   */
96
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user = NULL, ModuleHandlerInterface $module_handler = NULL) {
97
98
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityTypeManager = $entity_type_manager;
99
100
101
102
103
104
105
106
107
108
    if (!$current_user) {
      @trigger_error('The current_user service must be passed to MediaLibraryWidget::__construct(), it is required before Drupal 9.0.0.', E_USER_DEPRECATED);
      $current_user = \Drupal::currentUser();
    }
    $this->currentUser = $current_user;
    if (!$module_handler) {
      @trigger_error('The module_handler service must be passed to MediaLibraryWidget::__construct(), it is required before Drupal 9.0.0.', E_USER_DEPRECATED);
      $module_handler = \Drupal::moduleHandler();
    }
    $this->moduleHandler = $module_handler;
109
110
111
112
113
114
115
116
117
118
119
120
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
121
122
123
      $container->get('entity_type.manager'),
      $container->get('current_user'),
      $container->get('module_handler')
124
125
126
127
128
129
130
131
132
133
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return $field_definition->getSetting('target_type') === 'media';
  }

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'media_types' => [],
    ] + parent::defaultSettings();
  }

  /**
   * Get the enabled media type IDs sorted by weight.
   *
   * @return string[]
   *   The media type IDs sorted by weight.
   */
  protected function getAllowedMediaTypeIdsSorted() {
    // Get the media type IDs sorted by the user in the settings form.
    $sorted_media_type_ids = $this->getSetting('media_types');

    // Get the configured media types from the field storage.
    $handler_settings = $this->getFieldSetting('handler_settings');
155
156
157
158
159
160
    $allowed_media_type_ids = $handler_settings['target_bundles'];

    // When there are no allowed media types, return the empty array.
    if ($allowed_media_type_ids === []) {
      return $allowed_media_type_ids;
    }
161
162

    // When no target bundles are configured for the field, all are allowed.
163
    if ($allowed_media_type_ids === NULL) {
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
      $allowed_media_type_ids = $this->entityTypeManager->getStorage('media_type')->getQuery()->execute();
    }

    // When the user did not sort the media types, return the media type IDs
    // configured for the field.
    if (empty($sorted_media_type_ids)) {
      return $allowed_media_type_ids;
    }

    // Some of the media types may no longer exist, and new media types may have
    // been added that we don't yet know about. We need to make sure new media
    // types are added to the list and remove media types that are no longer
    // configured for the field.
    $new_media_type_ids = array_diff($allowed_media_type_ids, $sorted_media_type_ids);
    // Add new media type IDs to the list.
    $sorted_media_type_ids = array_merge($sorted_media_type_ids, array_values($new_media_type_ids));
    // Remove media types that are no longer available.
    $sorted_media_type_ids = array_intersect($sorted_media_type_ids, $allowed_media_type_ids);

    // Make sure the keys are numeric.
    return array_values($sorted_media_type_ids);
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $media_type_ids = $this->getAllowedMediaTypeIdsSorted();

    if (count($media_type_ids) <= 1) {
      return $form;
    }

    $form['media_types'] = [
      '#type' => 'table',
      '#header' => [
        $this->t('Tab order'),
        $this->t('Weight'),
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'weight',
        ],
      ],
      '#value_callback' => [static::class, 'setMediaTypesValue'],
    ];

    $media_types = $this->entityTypeManager->getStorage('media_type')->loadMultiple($media_type_ids);
    $weight = 0;
    foreach ($media_types as $media_type_id => $media_type) {
      $label = $media_type->label();
      $form['media_types'][$media_type_id] = [
        'label' => ['#markup' => $label],
        'weight' => [
          '#type' => 'weight',
          '#title' => t('Weight for @title', ['@title' => $label]),
          '#title_display' => 'invisible',
          '#default_value' => $weight,
          '#attributes' => ['class' => ['weight']],
        ],
        '#weight' => $weight,
        '#attributes' => ['class' => ['draggable']],
      ];
      $weight++;
    }

    return $form;
  }

  /**
   * Value callback to optimize the way the media type weights are stored.
   *
   * The tabledrag functionality needs a specific weight field, but we don't
   * want to store this extra weight field in our settings.
   *
   * @param array $element
   *   An associative array containing the properties of the element.
   * @param mixed $input
   *   The incoming input to populate the form element. If this is FALSE,
   *   the element's default value should be returned.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return mixed
   *   The value to assign to the element.
   */
  public static function setMediaTypesValue(array &$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {
      return isset($element['#default_value']) ? $element['#default_value'] : [];
    }

    // Sort the media types by weight value and set the value in the form state.
    uasort($input, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
    $sorted_media_type_ids = array_keys($input);
    $form_state->setValue($element['#parents'], $sorted_media_type_ids);

    // We have to unset the child elements containing the weight fields for each
    // media type to stop FormBuilder::doBuildForm() from processing the weight
    // fields as well.
    foreach ($sorted_media_type_ids as $media_type_id) {
      unset($element[$media_type_id]);
    }

    return $sorted_media_type_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $media_type_labels = [];
    $media_types = $this->entityTypeManager->getStorage('media_type')->loadMultiple($this->getAllowedMediaTypeIdsSorted());
    if (count($media_types) !== 1) {
      foreach ($media_types as $media_type) {
        $media_type_labels[] = $media_type->label();
      }
      $summary[] = t('Tab order: @order', ['@order' => implode(', ', $media_type_labels)]);
    }
    return $summary;
  }

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
  /**
   * {@inheritdoc}
   */
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
    // Load the items for form rebuilds from the field state.
    $field_state = static::getWidgetState($form['#parents'], $this->fieldDefinition->getName(), $form_state);
    if (isset($field_state['items'])) {
      usort($field_state['items'], [SortArray::class, 'sortByWeightElement']);
      $items->setValue($field_state['items']);
    }

    return parent::form($items, $form, $form_state, $get_delta);
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items */
    $referenced_entities = $items->referencedEntities();
    $view_builder = $this->entityTypeManager->getViewBuilder('media');
    $field_name = $this->fieldDefinition->getName();
    $parents = $form['#parents'];
311
    $id_suffix = $parents ? '-' . implode('-', $parents) : '';
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    $wrapper_id = $field_name . '-media-library-wrapper' . $id_suffix;
    $limit_validation_errors = [array_merge($parents, [$field_name])];

    $settings = $this->getFieldSetting('handler_settings');
    $element += [
      '#type' => 'fieldset',
      '#cardinality' => $this->fieldDefinition->getFieldStorageDefinition()->getCardinality(),
      '#target_bundles' => isset($settings['target_bundles']) ? $settings['target_bundles'] : FALSE,
      '#attributes' => [
        'id' => $wrapper_id,
        'class' => ['media-library-widget'],
      ],
      '#attached' => [
        'library' => ['media_library/widget'],
      ],
    ];

329
330
331
332
333
334
335
336
337
338
339
340
    // When the list of allowed types in the field configuration is null,
    // ::getAllowedMediaTypeIdsSorted() returns all existing media types. When
    // the list of allowed types is an empty array, we show a message to users
    // and ask them to configure the field if they have access.
    $allowed_media_type_ids = $this->getAllowedMediaTypeIdsSorted();
    if (!$allowed_media_type_ids) {
      $element['no_types_message'] = [
        '#markup' => $this->getNoMediaTypesAvailableMessage(),
      ];
      return $element;
    }

341
342
    if (empty($referenced_entities)) {
      $element['empty_selection'] = [
343
344
345
346
347
348
349
350
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->t('No media items are selected.'),
        '#attributes' => [
          'class' => [
            'media-library-widget-empty-text',
          ],
        ],
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
      ];
    }
    else {
      $element['weight_toggle'] = [
        '#type' => 'html_tag',
        '#tag' => 'button',
        '#value' => $this->t('Show media item weights'),
        '#attributes' => [
          'class' => [
            'link',
            'media-library-widget__toggle-weight',
            'js-media-library-widget-toggle-weight',
          ],
        ],
      ];
    }

368
369
370
371
372
373
374
375
376
377
    $element['selection'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'js-media-library-selection',
          'media-library-selection',
        ],
      ],
    ];

378
379
380
381
382
383
    foreach ($referenced_entities as $delta => $media_item) {
      $element['selection'][$delta] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'media-library-item',
384
            'media-library-item--grid',
385
386
387
388
389
390
391
392
393
394
395
            'js-media-library-item',
          ],
        ],
        'preview' => [
          '#type' => 'container',
          'remove_button' => [
            '#type' => 'submit',
            '#name' => $field_name . '-' . $delta . '-media-library-remove-button' . $id_suffix,
            '#value' => $this->t('Remove'),
            '#attributes' => [
              'class' => ['media-library-item__remove'],
396
              'aria-label' => $this->t('Remove @label', ['@label' => $media_item->label()]),
397
398
399
400
401
402
403
404
405
            ],
            '#ajax' => [
              'callback' => [static::class, 'updateWidget'],
              'wrapper' => $wrapper_id,
            ],
            '#submit' => [[static::class, 'removeItem']],
            // Prevent errors in other widgets from preventing removal.
            '#limit_validation_errors' => $limit_validation_errors,
          ],
406
407
          // @todo Make the view mode configurable in https://www.drupal.org/project/drupal/issues/2971209
          'rendered_entity' => $view_builder->view($media_item, 'media_library'),
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        ],
        'target_id' => [
          '#type' => 'hidden',
          '#value' => $media_item->id(),
        ],
        // This hidden value can be toggled visible for accessibility.
        'weight' => [
          '#type' => 'number',
          '#title' => $this->t('Weight'),
          '#default_value' => $delta,
          '#attributes' => [
            'class' => [
              'js-media-library-item-weight',
              'media-library-item__weight',
            ],
          ],
        ],
      ];
    }

    $cardinality_unlimited = ($element['#cardinality'] === FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $remaining = $element['#cardinality'] - count($referenced_entities);

    // Inform the user of how many items are remaining.
    if (!$cardinality_unlimited) {
      if ($remaining) {
        $cardinality_message = $this->formatPlural($remaining, 'One media item remaining.', '@count media items remaining.');
      }
      else {
        $cardinality_message = $this->t('The maximum number of media items have been selected.');
      }
439
440
441
442
443
444

      // Add a line break between the field message and the cardinality message.
      if (!empty($element['#description'])) {
        $element['#description'] .= '<br />';
      }
      $element['#description'] .= $cardinality_message;
445
446
    }

447
448
449
450
451
452
453
454
    // Create a new media library URL with the correct state parameters.
    $selected_type_id = reset($allowed_media_type_ids);
    $remaining = $cardinality_unlimited ? FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED : $remaining;
    // The opener ID is used by the select form and the upload form to add the
    // selected/uploaded media items to the widget.
    $opener_id = static::$openerIdPrefix . $field_name . $id_suffix;

    $state = MediaLibraryState::create($opener_id, $allowed_media_type_ids, $selected_type_id, $remaining);
455

456
457
    // Add a button that will load the Media library in a modal using AJAX.
    $element['media_library_open_button'] = [
458
459
      '#type' => 'submit',
      '#value' => $this->t('Add media'),
460
461
      '#name' => $field_name . '-media-library-open-button' . $id_suffix,
      '#attributes' => [
462
463
464
465
466
467
468
        'class' => [
          'media-library-open-button',
          'js-media-library-open-button',
        ],
        // The jQuery UI dialog automatically moves focus to the first :tabbable
        // element of the modal, so we need to disable refocus on the button.
        'data-disable-refocus' => 'true',
469
      ],
470
471
472
473
474
475
476
477
478
479
480
      '#media_library_state' => $state,
      '#ajax' => [
        'callback' => [static::class, 'openMediaLibrary'],
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Opening media library.'),
        ],
      ],
      '#submit' => [],
      // Allow the media library to be opened even if there are form errors.
      '#limit_validation_errors' => [],
481
482
    ];

483
484
485
486
487
488
489
490
491
492
493
    // When the user returns from the modal to the widget, we want to shift the
    // focus back to the open button. If the user is not allowed to add more
    // items, the button needs to be disabled. Since we can't shift the focus to
    // disabled elements, the focus is set back to the open button via
    // JavaScript by adding the 'data-disabled-focus' attribute.
    // @see Drupal.behaviors.MediaLibraryWidgetDisableButton
    if (!$cardinality_unlimited && $remaining === 0) {
      $element['media_library_open_button']['#attributes']['data-disabled-focus'] = 'true';
      $element['media_library_open_button']['#attributes']['class'][] = 'visually-hidden';
    }

494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    // This hidden field and button are used to add new items to the widget.
    $element['media_library_selection'] = [
      '#type' => 'hidden',
      '#attributes' => [
        // This is used to pass the selection from the modal to the widget.
        'data-media-library-widget-value' => $field_name . $id_suffix,
      ],
    ];

    // When a selection is made this hidden button is pressed to add new media
    // items based on the "media_library_selection" value.
    $element['media_library_update_widget'] = [
      '#type' => 'submit',
      '#value' => $this->t('Update widget'),
      '#name' => $field_name . '-media-library-update' . $id_suffix,
      '#ajax' => [
        'callback' => [static::class, 'updateWidget'],
        'wrapper' => $wrapper_id,
      ],
      '#attributes' => [
        'data-media-library-widget-update' => $field_name . $id_suffix,
        'class' => ['js-hide'],
      ],
      '#validate' => [[static::class, 'validateItems']],
      '#submit' => [[static::class, 'updateItems']],
      // Prevent errors in other widgets from preventing updates.
      '#limit_validation_errors' => $limit_validation_errors,
    ];

    return $element;
  }

526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
  /**
   * Gets the message to display when there are no allowed media types.
   *
   * @return \Drupal\Component\Render\MarkupInterface
   *   The message to display when there are no allowed media types.
   */
  protected function getNoMediaTypesAvailableMessage() {
    $entity_type_id = $this->fieldDefinition->getTargetEntityTypeId();

    $default_message = $this->t('There are no allowed media types configured for this field. Please contact the site administrator.');

    // Show the default message if the user does not have the permissions to
    // configure the fields for the entity type.
    if (!$this->currentUser->hasPermission("administer $entity_type_id fields")) {
      return $default_message;
    }

    // Show a message for privileged users to configure the field if the Field
    // UI module is not enabled.
    if (!$this->moduleHandler->moduleExists('field_ui')) {
      return $this->t('There are no allowed media types configured for this field. Edit the field settings to select the allowed media types.');
    }

    // Add a link to the message to configure the field if the Field UI module
    // is enabled.
    $route_parameters = FieldUI::getRouteBundleParameter($this->entityTypeManager->getDefinition($entity_type_id), $this->fieldDefinition->getTargetBundle());
    $route_parameters['field_config'] = $this->fieldDefinition->id();
    $url = Url::fromRoute('entity.field_config.' . $entity_type_id . '_field_edit_form', $route_parameters);
    if ($url->access($this->currentUser)) {
      return $this->t('There are no allowed media types configured for this field. <a href=":url">Edit the field settings</a> to select the allowed media types.', [
        ':url' => $url->toString(),
      ]);
    }

    // If the user for some reason doesn't have access to the Field UI, fall
    // back to the default message.
    return $default_message;
  }

565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
  /**
   * {@inheritdoc}
   */
  public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {
    return isset($element['target_id']) ? $element['target_id'] : FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    if (isset($values['selection'])) {
      usort($values['selection'], [SortArray::class, 'sortByWeightElement']);
      return $values['selection'];
    }
    return [];
  }

  /**
   * AJAX callback to update the widget when the selection changes.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
591
592
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An AJAX response to update the selection.
593
594
595
   */
  public static function updateWidget(array $form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
596
597
    $wrapper_id = $triggering_element['#ajax']['wrapper'];

598
599
    // This callback is either invoked from the remove button or the update
    // button, which have different nesting levels.
600
601
    $remove_button = end($triggering_element['#parents']) === 'remove_button';
    $length = $remove_button ? -4 : -1;
602
603
604
605
606
607
608
    if (count($triggering_element['#array_parents']) < abs($length)) {
      throw new \LogicException('The element that triggered the widget update was at an unexpected depth. Triggering element parents were: ' . implode(',', $triggering_element['#array_parents']));
    }
    $parents = array_slice($triggering_element['#array_parents'], 0, $length);
    $element = NestedArray::getValue($form, $parents);
    // Always clear the textfield selection to prevent duplicate additions.
    $element['media_library_selection']['#value'] = '';
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632

    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand("#$wrapper_id", $element));

    $field_state = static::getFieldState($element, $form_state);

    // When the remove button is clicked, the focus will be kept in the
    // selection area by default. When the last item is deleted, we no longer
    // have a selection and shift the focus to the open button.
    $removed_last = $remove_button && !count($field_state['items']);

    // Shift focus to the open button if the user did not click the remove
    // button. When the user is not allowed to add more items, the button needs
    // to be disabled. Since we can't shift the focus to disabled elements, the
    // focus is set via JavaScript by adding the 'data-disabled-focus' attribute
    // and we also don't want to set the focus here.
    // @see Drupal.behaviors.MediaLibraryWidgetDisableButton
    $select_more = !$remove_button && !isset($element['media_library_open_button']['#attributes']['data-disabled-focus']);

    if ($removed_last || $select_more) {
      $response->addCommand(new InvokeCommand("#$wrapper_id .js-media-library-open-button", 'focus'));
    }

    return $response;
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
  }

  /**
   * Submit callback for remove buttons.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function removeItem(array $form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();

    // Get the parents required to find the top-level widget element.
    if (count($triggering_element['#array_parents']) < 4) {
      throw new \LogicException('Expected the remove button to be more than four levels deep in the form. Triggering element parents were: ' . implode(',', $triggering_element['#array_parents']));
    }
    $parents = array_slice($triggering_element['#array_parents'], 0, -4);
    // Get the delta of the item being removed.
    $delta = array_slice($triggering_element['#array_parents'], -3, 1)[0];
    $element = NestedArray::getValue($form, $parents);

    // Get the field state.
    $path = $element['#parents'];
    $values = NestedArray::getValue($form_state->getValues(), $path);
    $field_state = static::getFieldState($element, $form_state);

    // Remove the item from the field state and update it.
    if (isset($values['selection'][$delta])) {
      array_splice($values['selection'], $delta, 1);
      $field_state['items'] = $values['selection'];
      static::setFieldState($element, $form_state, $field_state);
    }

    $form_state->setRebuild();
  }

670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
  /**
   * AJAX callback to open the library modal.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An AJAX response to open the media library.
   */
  public static function openMediaLibrary(array $form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    $library_ui = \Drupal::service('media_library.ui_builder')->buildUi($triggering_element['#media_library_state']);
    $dialog_options = MediaLibraryUiBuilder::dialogOptions();
    return (new AjaxResponse())
      ->addCommand(new OpenModalDialogCommand($dialog_options['title'], $library_ui, $dialog_options));
  }

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
  /**
   * Validates that newly selected items can be added to the widget.
   *
   * Making an invalid selection from the view should not be possible, but we
   * still validate in case other selection methods (ex: upload) are valid.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function validateItems(array $form, FormStateInterface $form_state) {
    $button = $form_state->getTriggeringElement();
    $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));

    $field_state = static::getFieldState($element, $form_state);
    $media = static::getNewMediaItems($element, $form_state);
    if (empty($media)) {
      return;
    }

    // Check if more items were selected than we allow.
    $cardinality_unlimited = ($element['#cardinality'] === FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $selection = count($field_state['items']) + count($media);
    if (!$cardinality_unlimited && ($selection > $element['#cardinality'])) {
      $form_state->setError($element, \Drupal::translation()->formatPlural($element['#cardinality'], 'Only one item can be selected.', 'Only @count items can be selected.'));
    }

    // Validate that each selected media is of an allowed bundle.
    $all_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');
    $bundle_labels = array_map(function ($bundle) use ($all_bundles) {
      return $all_bundles[$bundle]['label'];
    }, $element['#target_bundles']);
    foreach ($media as $media_item) {
      if ($element['#target_bundles'] && !in_array($media_item->bundle(), $element['#target_bundles'], TRUE)) {
        $form_state->setError($element, t('The media item "@label" is not of an accepted type. Allowed types: @types', [
          '@label' => $media_item->label(),
          '@types' => implode(', ', $bundle_labels),
        ]));
      }
    }
  }

  /**
   * Updates the field state and flags the form for rebuild.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function updateItems(array $form, FormStateInterface $form_state) {
    $button = $form_state->getTriggeringElement();
    $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));

    $field_state = static::getFieldState($element, $form_state);

    $media = static::getNewMediaItems($element, $form_state);
    if (!empty($media)) {
748
749
750
      // Get the weight of the last items and count from there.
      $last_element = end($field_state['items']);
      $weight = $last_element ? $last_element['weight'] : 0;
751
752
753
754
755
      foreach ($media as $media_item) {
        // Any ID can be passed to the widget, so we have to check access.
        if ($media_item->access('view')) {
          $field_state['items'][] = [
            'target_id' => $media_item->id(),
756
            'weight' => ++$weight,
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
          ];
        }
      }
      static::setFieldState($element, $form_state, $field_state);
    }

    $form_state->setRebuild();
  }

  /**
   * Gets newly selected media items.
   *
   * @param array $element
   *   The wrapping element for this widget.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\media\MediaInterface[]
   *   An array of selected media items.
   */
  protected static function getNewMediaItems(array $element, FormStateInterface $form_state) {
    // Get the new media IDs passed to our hidden button.
    $values = $form_state->getValues();
    $path = $element['#parents'];
    $value = NestedArray::getValue($values, $path);

    if (!empty($value['media_library_selection'])) {
      $ids = explode(',', $value['media_library_selection']);
      $ids = array_filter($ids, 'is_numeric');
      if (!empty($ids)) {
        /** @var \Drupal\media\MediaInterface[] $media */
        return Media::loadMultiple($ids);
      }
    }
    return [];
  }

  /**
   * Gets the field state for the widget.
   *
   * @param array $element
   *   The wrapping element for this widget.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array[]
   *   An array of arrays with the following key/value pairs:
   *   - items: (array) An array of selections.
   *     - target_id: (int) A media entity ID.
   *     - weight: (int) A weight for the selection.
   */
  protected static function getFieldState(array $element, FormStateInterface $form_state) {
809
810
811
812
813
    // Default to using the current selection if the form is new.
    $path = $element['#parents'];
    $values = NestedArray::getValue($form_state->getValues(), $path);
    $selection = isset($values['selection']) ? $values['selection'] : [];

814
    $widget_state = static::getWidgetState($element['#field_parents'], $element['#field_name'], $form_state);
815
    $widget_state['items'] = isset($widget_state['items']) ? $widget_state['items'] : $selection;
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
    return $widget_state;
  }

  /**
   * Sets the field state for the widget.
   *
   * @param array $element
   *   The wrapping element for this widget.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array[] $field_state
   *   An array of arrays with the following key/value pairs:
   *   - items: (array) An array of selections.
   *     - target_id: (int) A media entity ID.
   *     - weight: (int) A weight for the selection.
   */
  protected static function setFieldState(array $element, FormStateInterface $form_state, array $field_state) {
    static::setWidgetState($element['#field_parents'], $element['#field_name'], $form_state, $field_state);
  }

836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
  /**
   * Get the field ID of the widget from an opener ID.
   *
   * @param string $opener_id
   *   The opener ID of the media library.
   *
   * @return string|null
   *   The field ID or NULL if the opener ID is not valid for the widget.
   *
   * @see \Drupal\media_library\MediaLibraryState
   */
  public static function getOpenerFieldId($opener_id) {
    // Media library widget opener IDs are always prefixed with 'field:' in .
    if (preg_match('/^' . static::$openerIdPrefix . '([a-z0-9_-]+)$/', $opener_id, $matches)) {
      return $matches[1];
    }
    return NULL;
  }

855
}