MediaLibraryTest.php 73.9 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Tests\media_library\FunctionalJavascript;

5 6
use Drupal\Core\Url;
use Drupal\field_ui\FieldUI;
7
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
8
use Drupal\media\Entity\Media;
9
use Drupal\media_library\MediaLibraryState;
10 11
use Drupal\media_test_oembed\Controller\ResourceController;
use Drupal\Tests\media\Traits\OEmbedTestTrait;
12
use Drupal\Tests\TestFileCreationTrait;
13 14
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
15 16

/**
17
 * Contains Media Library integration tests.
18 19 20
 *
 * @group media_library
 */
21
class MediaLibraryTest extends WebDriverTestBase {
22

23
  use TestFileCreationTrait;
24
  use OEmbedTestTrait;
25

26 27 28
  /**
   * {@inheritdoc}
   */
29
  protected static $modules = ['block', 'media_library_test', 'field_ui'];
30 31 32 33 34 35

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
36
    $this->lockHttpClientToFixtures();
37 38 39 40

    // Create a few example media items for use in selection.
    $media = [
      'type_one' => [
41 42 43 44
        'Horse',
        'Bear',
        'Cat',
        'Dog',
45 46
      ],
      'type_two' => [
47 48 49 50
        'Crocodile',
        'Lizard',
        'Snake',
        'Turtle',
51 52 53
      ],
    ];

54
    $time = time();
55 56 57 58
    foreach ($media as $type => $names) {
      foreach ($names as $name) {
        $entity = Media::create(['name' => $name, 'bundle' => $type]);
        $source_field = $type === 'type_one' ? 'field_media_test' : 'field_media_test_1';
59 60
        $entity->setCreatedTime(++$time);
        $entity->set($source_field, $name);
61 62 63 64 65 66 67
        $entity->save();
      }
    }

    // Create a user who can use the Media library.
    $user = $this->drupalCreateUser([
      'access administration pages',
68
      'access content',
69
      'access media overview',
70 71
      'edit own basic_page content',
      'create basic_page content',
72 73 74
      'create media',
      'delete any media',
      'view media',
75
      'administer node form display',
76 77 78 79 80 81 82
    ]);
    $this->drupalLogin($user);
    $this->drupalPlaceBlock('local_tasks_block');
    $this->drupalPlaceBlock('local_actions_block');
  }

  /**
83
   * Tests that the Media Library's administration page works as expected.
84 85
   */
  public function testAdministrationPage() {
86 87
    $session = $this->getSession();
    $page = $session->getPage();
88 89 90 91 92 93 94 95 96
    $assert_session = $this->assertSession();

    // Visit the administration page.
    $this->drupalGet('admin/content/media');

    // Verify that the "Add media" link is present.
    $assert_session->linkExists('Add media');

    // Verify that media from two separate types is present.
97 98
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextContains('Turtle');
99 100

    // Test that users can filter by type.
101
    $page->selectFieldOption('Media type', 'Type One');
102
    $page->pressButton('Apply filters');
103
    $assert_session->assertWaitOnAjaxRequest();
104 105
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Turtle');
106
    $page->selectFieldOption('Media type', 'Type Two');
107
    $page->pressButton('Apply filters');
108
    $assert_session->assertWaitOnAjaxRequest();
109 110
    $assert_session->pageTextNotContains('Dog');
    $assert_session->pageTextContains('Turtle');
111 112

    // Test that selecting elements as a part of bulk operations works.
113
    $page->selectFieldOption('Media type', '- Any -');
114
    $page->pressButton('Apply filters');
115 116
    $assert_session->assertWaitOnAjaxRequest();
    // This tests that anchor tags clicked inside the preview are suppressed.
117
    $this->getSession()->executeScript('jQuery(".js-click-to-select-trigger a")[4].click()');
118
    $this->submitForm([], 'Apply to selected items');
119 120
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Cat');
121
    $this->submitForm([], 'Delete');
122 123
    $assert_session->pageTextNotContains('Dog');
    $assert_session->pageTextContains('Cat');
124 125 126 127 128 129 130

    // Test 'Select all media'.
    $this->getSession()->getPage()->checkField('Select all media');
    $this->getSession()->getPage()->selectFieldOption('Action', 'media_delete_action');
    $this->submitForm([], 'Apply to selected items');
    $this->getSession()->getPage()->pressButton('Delete');

131 132 133
    $assert_session->pageTextNotContains('Cat');
    $assert_session->pageTextNotContains('Turtle');
    $assert_session->pageTextNotContains('Snake');
134 135 136

    // Test empty text.
    $assert_session->pageTextContains('No media available.');
137 138 139 140 141 142 143

    // Verify that the "Table" link is present, click it and check address.
    $assert_session->linkExists('Table');
    $page->clickLink('Table');
    $assert_session->addressEquals('admin/content/media-table');
    // Verify that the "Add media" link is present.
    $assert_session->linkExists('Add media');
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
  /**
   * Tests that the widget works as expected when media types are deleted.
   */
  public function testWidgetWithoutMediaTypes() {
    $assert_session = $this->assertSession();

    $user = $this->drupalCreateUser([
      'access administration pages',
      'access content',
      'create basic_page content',
      'create media',
      'view media',
    ]);
    $this->drupalLogin($user);

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

    $this->drupalGet('node/add/basic_page');

    // Assert a properly configured field does not show a message.
    $assert_session->elementTextNotContains('css', '.field--name-field-twin-media', 'There are no allowed media types configured for this field.');
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]');
    // Assert that the message is shown when the target_bundles setting for the
    // entity reference field is an empty array. No types are allowed in this
    // case.
    $assert_session->elementTextContains('css', '.field--name-field-empty-types-media', $default_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_empty_types_media"]');
    // Assert that the message is not shown when the target_bundles setting for
    // the entity reference field is null. All types are allowed in this case.
    $assert_session->elementTextNotContains('css', '.field--name-field-null-types-media', 'There are no allowed media types configured for this field.');
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_null_types_media"]');

    // Delete all media and media types.
    $entity_type_manager = \Drupal::entityTypeManager();
    $media_storage = $entity_type_manager->getStorage('media');
    $media_type_storage = $entity_type_manager->getStorage('media_type');
    $media_storage->delete($media_storage->loadMultiple());
    $media_type_storage->delete($media_type_storage->loadMultiple());

    // Visit a node create page.
    $this->drupalGet('node/add/basic_page');

    // Assert a properly configured field now shows a message.
    $assert_session->elementTextContains('css', '.field--name-field-twin-media', $default_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_twin_media"]');
    // Assert that the message is shown when the target_bundles setting for the
    // entity reference field is an empty array.
    $assert_session->elementTextContains('css', '.field--name-field-empty-types-media', $default_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_empty_types_media"]');
    // Assert that the message is shown when the target_bundles setting for
    // the entity reference field is null.
    $assert_session->elementTextContains('css', '.field--name-field-null-types-media', $default_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_null_types_media"]');

    // Assert a different message is shown when the user is allowed to
    // administer the fields.
    $user = $this->drupalCreateUser([
      'access administration pages',
      'access content',
      'create basic_page content',
      'view media',
      'administer node fields',
    ]);
    $this->drupalLogin($user);

    $route_bundle_params = FieldUI::getRouteBundleParameter(\Drupal::entityTypeManager()->getDefinition('node'), 'basic_page');

    $field_twin_url = new Url('entity.field_config.node_field_edit_form', [
      'field_config' => 'node.basic_page.field_twin_media',
    ] + $route_bundle_params);
    $field_twin_message = 'There are no allowed media types configured for this field. <a href="' . $field_twin_url->toString() . '">Edit the field settings</a> to select the allowed media types.';

    $field_empty_types_url = new Url('entity.field_config.node_field_edit_form', [
      'field_config' => 'node.basic_page.field_empty_types_media',
    ] + $route_bundle_params);
    $field_empty_types_message = 'There are no allowed media types configured for this field. <a href="' . $field_empty_types_url->toString() . '">Edit the field settings</a> to select the allowed media types.';

    $field_null_types_url = new Url('entity.field_config.node_field_edit_form', [
        'field_config' => 'node.basic_page.field_null_types_media',
      ] + $route_bundle_params);
    $field_null_types_message = 'There are no allowed media types configured for this field. <a href="' . $field_null_types_url->toString() . '">Edit the field settings</a> to select the allowed media types.';

    // Visit a node create page.
    $this->drupalGet('node/add/basic_page');

    // Assert a properly configured field still shows a message.
    $assert_session->elementContains('css', '.field--name-field-twin-media', $field_twin_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_twin_media"]');
    // Assert that the message is shown when the target_bundles setting for the
    // entity reference field is an empty array.
    $assert_session->elementContains('css', '.field--name-field-empty-types-media', $field_empty_types_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_empty_types_media"]');
    // Assert that the message is shown when the target_bundles setting for the
    // entity reference field is null.
    $assert_session->elementContains('css', '.field--name-field-null-types-media', $field_null_types_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_null_types_media"]');

    // Assert the messages are also shown in the default value section of the
    // field edit form.
    $this->drupalGet($field_empty_types_url);
    $assert_session->elementContains('css', '.field--name-field-empty-types-media', $field_empty_types_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_empty_types_media"]');
    $this->drupalGet($field_null_types_url);
    $assert_session->elementContains('css', '.field--name-field-null-types-media', $field_null_types_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_null_types_media"]');

    // Uninstall the Field UI and check if the link is removed from the message.
    \Drupal::service('module_installer')->uninstall(['field_ui']);

    // Visit a node create page.
    $this->drupalGet('node/add/basic_page');

    $field_ui_uninstalled_message = 'There are no allowed media types configured for this field. Edit the field settings to select the allowed media types.';

    // Assert the link is now longer part of the message.
    $assert_session->elementNotExists('named', ['link', 'Edit the field settings']);
    // Assert a properly configured field still shows a message.
    $assert_session->elementContains('css', '.field--name-field-twin-media', $field_ui_uninstalled_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_twin_media"]');
    // Assert that the message is shown when the target_bundles setting for the
    // entity reference field is an empty array.
    $assert_session->elementContains('css', '.field--name-field-empty-types-media', $field_ui_uninstalled_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_empty_types_media"]');
    // Assert that the message is shown when the target_bundles setting for the
    // entity reference field is null.
    $assert_session->elementContains('css', '.field--name-field-null-types-media', $field_ui_uninstalled_message);
    $assert_session->elementNotExists('css', '.media-library-open-button[name^="field_null_types_media"]');
  }

275 276 277 278 279 280 281 282 283 284 285 286 287
  /**
   * Tests that the widget access works as expected.
   */
  public function testWidgetAccess() {
    $assert_session = $this->assertSession();

    $this->drupalLogout();

    $role = Role::load(RoleInterface::ANONYMOUS_ID);
    $role->revokePermission('view media');
    $role->save();

    // Create a working state.
288 289
    $allowed_types = ['type_one', 'type_two', 'type_three', 'type_four'];
    $state = MediaLibraryState::create('test', $allowed_types, 'type_three', 2);
290 291 292 293 294
    $url_options = ['query' => $state->all()];

    // Verify that unprivileged users can't access the widget view.
    $this->drupalGet('admin/content/media-widget', $url_options);
    $assert_session->responseContains('Access denied');
295 296
    $this->drupalGet('admin/content/media-widget-table', $url_options);
    $assert_session->responseContains('Access denied');
297 298 299 300 301 302 303 304 305 306
    $this->drupalGet('media-library', $url_options);
    $assert_session->responseContains('Access denied');

    // Allow users with 'view media' permission to access the media library view
    // and controller.
    $this->grantPermissions($role, [
      'view media',
    ]);
    $this->drupalGet('admin/content/media-widget', $url_options);
    $assert_session->elementExists('css', '.view-media-library');
307 308
    $this->drupalGet('admin/content/media-widget-table', $url_options);
    $assert_session->elementExists('css', '.view-media-library');
309 310
    $this->drupalGet('media-library', $url_options);
    $assert_session->elementExists('css', '.view-media-library');
311 312 313 314
    // Assert the user does not have access to the media add form if the user
    // does not have the 'create media' permission.
    $assert_session->fieldNotExists('files[upload][]');

315 316 317 318 319 320 321 322 323
    // Assert users can not access the widget displays of the media library view
    // without a valid media library state.
    $this->drupalGet('admin/content/media-widget');
    $assert_session->responseContains('Access denied');
    $this->drupalGet('admin/content/media-widget-table');
    $assert_session->responseContains('Access denied');
    $this->drupalGet('media-library');
    $assert_session->responseContains('Access denied');

324 325 326 327 328 329 330 331
    // Assert users with the 'create media' permission can access the media add
    // form.
    $this->grantPermissions($role, [
      'create media',
    ]);
    $this->drupalGet('media-library', $url_options);
    $assert_session->elementExists('css', '.view-media-library');
    $assert_session->fieldExists('Add files');
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

    // Assert the media library can not be accessed if the required state
    // parameters are changed without changing the hash.
    $this->drupalGet('media-library', [
      'query' => array_merge($url_options['query'], ['media_library_opener_id' => 'fail']),
    ]);
    $assert_session->responseContains('Access denied');
    $this->drupalGet('media-library', [
      'query' => array_merge($url_options['query'], ['media_library_allowed_types' => ['type_one', 'type_two']]),
    ]);
    $assert_session->responseContains('Access denied');
    $this->drupalGet('media-library', [
      'query' => array_merge($url_options['query'], ['media_library_selected_type' => 'type_one']),
    ]);
    $assert_session->responseContains('Access denied');
    $this->drupalGet('media-library', [
      'query' => array_merge($url_options['query'], ['media_library_remaining' => 3]),
    ]);
    $assert_session->responseContains('Access denied');
    $this->drupalGet('media-library', [
      'query' => array_merge($url_options['query'], ['hash' => 'fail']),
    ]);
    $assert_session->responseContains('Access denied');
355 356
  }

357 358 359 360 361 362 363 364 365 366
  /**
   * Tests that the Media library's widget works as expected.
   */
  public function testWidget() {
    $assert_session = $this->assertSession();
    $page = $this->getSession()->getPage();

    // Visit a node create page.
    $this->drupalGet('node/add/basic_page');

367
    // Assert that media widget instances are present.
368 369
    $assert_session->pageTextContains('Unlimited media');
    $assert_session->pageTextContains('Twin media');
370
    $assert_session->pageTextContains('Single media type');
371
    $assert_session->pageTextContains('Empty types media');
372

373
    // Assert generic media library elements.
374
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
375
    $assert_session->assertWaitOnAjaxRequest();
376
    $assert_session->pageTextContains('Add or select media');
377 378 379 380 381
    $this->assertFalse($assert_session->elementExists('css', '.media-library-select-all')->isVisible());
    $page->find('css', '.ui-dialog-titlebar-close')->click();

    // Assert that the media type menu is available when more than 1 type is
    // configured for the field.
382
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
383 384
    $assert_session->assertWaitOnAjaxRequest();
    $menu = $assert_session->elementExists('css', '.media-library-menu');
385 386 387 388 389 390 391
    $this->assertTrue($menu->hasLink('Type One'));
    $this->assertFalse($menu->hasLink('Type Two'));
    $this->assertTrue($menu->hasLink('Type Three'));
    $this->assertFalse($menu->hasLink('Type Four'));
    $page->find('css', '.ui-dialog-titlebar-close')->click();
    $assert_session->assertWaitOnAjaxRequest();

392 393 394 395
    // Assert that the media type menu is available when the target_bundles
    // setting for the entity reference field is null. All types should be
    // allowed in this case.
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_null_types_media"]')->click();
396 397 398 399 400 401 402
    $assert_session->assertWaitOnAjaxRequest();
    $menu = $assert_session->elementExists('css', '.media-library-menu');
    $this->assertTrue($menu->hasLink('Type One'));
    $this->assertTrue($menu->hasLink('Type Two'));
    $this->assertTrue($menu->hasLink('Type Three'));
    $this->assertTrue($menu->hasLink('Type Four'));
    $this->assertTrue($menu->hasLink('Type Five'));
403 404 405 406
    $page->find('css', '.ui-dialog-titlebar-close')->click();

    // Assert that the media type menu is not available when only 1 type is
    // configured for the field.
407
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_single_media_type"]')->click();
408 409 410 411 412
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->elementTextContains('css', '.media-library-selected-count', '0 of 1 item selected');
    // Select a media item, assert the hidden selection field contains the ID of
    // the selected item.
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
413
    $this->assertGreaterThanOrEqual(1, count($checkboxes));
414 415 416 417 418 419 420
    $checkboxes[0]->click();
    $assert_session->hiddenFieldValueEquals('media-library-modal-selection', '4');
    $assert_session->elementTextContains('css', '.media-library-selected-count', '1 of 1 item selected');
    $assert_session->elementNotExists('css', '.media-library-menu');
    $page->find('css', '.ui-dialog-titlebar-close')->click();

    // Assert the menu links can be sorted through the widget configuration.
421
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
422 423 424 425 426 427
    $assert_session->assertWaitOnAjaxRequest();
    $links = $page->findAll('css', '.media-library-menu a');
    $link_titles = [];
    foreach ($links as $link) {
      $link_titles[] = $link->getText();
    }
428
    $expected_link_titles = ['Type Three (active tab)', 'Type One', 'Type Two', 'Type Four'];
429 430 431 432 433 434 435 436 437 438 439 440 441
    $this->assertSame($link_titles, $expected_link_titles);
    $this->drupalGet('admin/structure/types/manage/basic_page/form-display');
    $assert_session->buttonExists('field_twin_media_settings_edit')->press();
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->buttonExists('Show row weights')->press();
    $assert_session->fieldExists('fields[field_twin_media][settings_edit_form][settings][media_types][type_one][weight]')->selectOption(0);
    $assert_session->fieldExists('fields[field_twin_media][settings_edit_form][settings][media_types][type_three][weight]')->selectOption(1);
    $assert_session->fieldExists('fields[field_twin_media][settings_edit_form][settings][media_types][type_four][weight]')->selectOption(2);
    $assert_session->fieldExists('fields[field_twin_media][settings_edit_form][settings][media_types][type_two][weight]')->selectOption(3);
    $assert_session->buttonExists('Save')->press();
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->buttonExists('Hide row weights')->press();
    $this->drupalGet('node/add/basic_page');
442
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
443 444 445 446 447 448 449 450
    $assert_session->assertWaitOnAjaxRequest();
    $link_titles = array_map(function ($link) {
      return $link->getText();
    }, $page->findAll('css', '.media-library-menu a'));
    $this->assertSame($link_titles, ['Type One (active tab)', 'Type Three', 'Type Four', 'Type Two']);
    $page->find('css', '.ui-dialog-titlebar-close')->click();

    // Assert media is only visible on the tab for the related media type.
451
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
452
    $assert_session->assertWaitOnAjaxRequest();
453 454 455
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextContains('Bear');
    $assert_session->pageTextNotContains('Turtle');
456
    $page->clickLink('Type Three');
457 458 459 460 461 462 463 464
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->elementExists('named', ['link', 'Type Three (active tab)']);
    $assert_session->pageTextNotContains('Dog');
    $assert_session->pageTextNotContains('Bear');
    $assert_session->pageTextNotContains('Turtle');
    $page->find('css', '.ui-dialog-titlebar-close')->click();

    // Assert the exposed name filter of the view.
465
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
466
    $assert_session->assertWaitOnAjaxRequest();
467 468
    $session = $this->getSession();
    $session->getPage()->fillField('Name', 'Dog');
469
    $session->getPage()->pressButton('Apply filters');
470 471 472 473
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Bear');
    $session->getPage()->fillField('Name', '');
474
    $session->getPage()->pressButton('Apply filters');
475
    $assert_session->assertWaitOnAjaxRequest();
476 477 478
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextContains('Bear');
    $page->find('css', '.ui-dialog-titlebar-close')->click();
479 480 481

    // Assert the media library contains header links to switch between the grid
    // and table display.
482
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
483 484 485 486 487
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->elementExists('css', '.media-library-view .media-library-item--grid');
    $assert_session->elementNotExists('css', '.media-library-view .media-library-item--table');
    // Assert the 'Apply filter' button is not moved to the button pane.
    $button_pane = $assert_session->elementExists('css', '.ui-dialog-buttonpane');
488
    $assert_session->buttonExists('Insert selected', $button_pane);
489 490 491 492 493 494 495 496 497
    $assert_session->buttonNotExists('Apply filters', $button_pane);
    $assert_session->linkExists('Grid');
    $page->clickLink('Table');
    // Assert the display change is correctly announced for screen readers.
    $this->assertNotEmpty($assert_session->waitForText('Loading table view.'));
    $this->assertNotEmpty($assert_session->waitForText('Changed to table view.'));
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.media-library-view .media-library-item--table'));
    $assert_session->elementNotExists('css', '.media-library-view .media-library-item--grid');
    // Assert the 'Apply filter' button is not moved to the button pane.
498
    $assert_session->buttonExists('Insert selected', $button_pane);
499 500 501 502 503 504
    $assert_session->buttonNotExists('Apply filters', $button_pane);
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextContains('Bear');
    $assert_session->pageTextNotContains('Turtle');
    // Assert the exposed filters can be applied.
    $page->fillField('Name', 'Dog');
505
    $page->pressButton('Apply filters');
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Bear');
    $assert_session->pageTextNotContains('Turtle');
    $page->checkField('Select Dog');
    $assert_session->linkExists('Table');
    $page->clickLink('Grid');
    // Assert the display change is correctly announced for screen readers.
    $this->assertNotEmpty($assert_session->waitForText('Loading grid view.'));
    $this->assertNotEmpty($assert_session->waitForText('Changed to grid view.'));
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.media-library-view .media-library-item--grid'));
    $assert_session->elementNotExists('css', '.media-library-view .media-library-item--table');
    // Assert the exposed filters are persisted when changing display.
    $this->assertSame('Dog', $page->findField('Name')->getValue());
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Bear');
    $assert_session->pageTextNotContains('Turtle');
    $assert_session->linkExists('Grid');
    $assert_session->linkExists('Table');
    // Select the item.
526
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
527 528 529 530 531 532 533 534 535
    $assert_session->assertWaitOnAjaxRequest();
    // Ensure that the selection completed successfully.
    $assert_session->pageTextNotContains('Add or select media');
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Bear');
    $assert_session->pageTextNotContains('Turtle');
    // Clear the selection.
    $assert_session->elementAttributeContains('css', '.media-library-item__remove', 'aria-label', 'Remove Dog');
    $assert_session->elementExists('css', '.media-library-item__remove')->click();
536 537
    $assert_session->assertWaitOnAjaxRequest();

538 539 540 541 542 543
    // Assert adding a single media item and removing it.
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
    $assert_session->assertWaitOnAjaxRequest();
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
    $this->assertGreaterThanOrEqual(1, count($checkboxes));
    $checkboxes[0]->click();
544
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
545 546 547 548 549 550 551 552 553
    $assert_session->assertWaitOnAjaxRequest();
    // Assert the focus is set back on the open button of the media field.
    $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .js-media-library-open-button").is(":focus")');
    $assert_session->elementAttributeContains('css', '.media-library-item__remove', 'aria-label', 'Remove Dog');
    $assert_session->elementExists('css', '.media-library-item__remove')->click();
    $assert_session->assertWaitOnAjaxRequest();
    // Assert the focus is set back on the open button of the media field.
    $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .js-media-library-open-button").is(":focus")');

554 555
    // Assert the selection is persistent in the media library modal, and
    // the number of selected items is displayed correctly.
556
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
557 558 559 560
    $assert_session->assertWaitOnAjaxRequest();
    // Assert the number of selected items is displayed correctly.
    $assert_session->elementExists('css', '.media-library-selected-count');
    $assert_session->elementTextContains('css', '.media-library-selected-count', '0 of 2 items selected');
561
    $assert_session->elementAttributeContains('css', '.media-library-selected-count', 'role', 'status');
562
    $assert_session->elementAttributeContains('css', '.media-library-selected-count', 'aria-live', 'polite');
563
    $assert_session->elementAttributeContains('css', '.media-library-selected-count', 'aria-atomic', 'true');
564 565 566
    // Select a media item, assert the hidden selection field contains the ID of
    // the selected item.
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
567
    $this->assertCount(4, $checkboxes);
568
    $checkboxes[0]->click();
569 570 571 572
    $assert_session->hiddenFieldValueEquals('media-library-modal-selection', '4');
    // Assert the number of selected items is displayed correctly.
    $assert_session->elementTextContains('css', '.media-library-selected-count', '1 of 2 items selected');
    // Select another item and assert the number of selected items is updated.
573
    $checkboxes[1]->click();
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    $assert_session->elementTextContains('css', '.media-library-selected-count', '2 of 2 items selected');
    $assert_session->hiddenFieldValueEquals('media-library-modal-selection', '4,3');
    // Assert unselected items are disabled when the maximum allowed items are
    // selected (cardinality for this field is 2).
    $this->assertTrue($checkboxes[2]->hasAttribute('disabled'));
    $this->assertTrue($checkboxes[3]->hasAttribute('disabled'));
    // Assert the selected items are updated when deselecting an item.
    $checkboxes[0]->click();
    $assert_session->elementTextContains('css', '.media-library-selected-count', '1 of 2 items selected');
    $assert_session->hiddenFieldValueEquals('media-library-modal-selection', '3');
    // Assert deselected items are available again.
    $this->assertFalse($checkboxes[2]->hasAttribute('disabled'));
    $this->assertFalse($checkboxes[3]->hasAttribute('disabled'));
    // The selection should be persisted when navigating to other media types in
    // the modal.
589
    $page->clickLink('Type Three');
590
    $assert_session->assertWaitOnAjaxRequest();
591
    $page->clickLink('Type One');
592 593 594 595 596 597 598 599 600 601 602 603
    $assert_session->assertWaitOnAjaxRequest();
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
    $selected_checkboxes = [];
    foreach ($checkboxes as $checkbox) {
      if ($checkbox->isChecked()) {
        $selected_checkboxes[] = $checkbox->getValue();
      }
    }
    $this->assertCount(1, $selected_checkboxes);
    $assert_session->hiddenFieldValueEquals('media-library-modal-selection', implode(',', $selected_checkboxes));
    $assert_session->elementTextContains('css', '.media-library-selected-count', '1 of 2 items selected');
    // Add to selection from another type.
604
    $page->clickLink('Type Two');
605 606
    $assert_session->assertWaitOnAjaxRequest();
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
607
    $this->assertCount(4, $checkboxes);
608 609 610 611 612 613 614 615 616 617 618
    $checkboxes[0]->click();
    // Assert the selection is updated correctly.
    $assert_session->elementTextContains('css', '.media-library-selected-count', '2 of 2 items selected');
    $assert_session->hiddenFieldValueEquals('media-library-modal-selection', '3,8');
    // Assert unselected items are disabled when the maximum allowed items are
    // selected (cardinality for this field is 2).
    $this->assertFalse($checkboxes[0]->hasAttribute('disabled'));
    $this->assertTrue($checkboxes[1]->hasAttribute('disabled'));
    $this->assertTrue($checkboxes[2]->hasAttribute('disabled'));
    $this->assertTrue($checkboxes[3]->hasAttribute('disabled'));
    // Assert the checkboxes are also disabled on other pages.
619
    $page->clickLink('Type One');
620 621 622 623 624 625
    $assert_session->assertWaitOnAjaxRequest();
    $this->assertTrue($checkboxes[0]->hasAttribute('disabled'));
    $this->assertFalse($checkboxes[1]->hasAttribute('disabled'));
    $this->assertTrue($checkboxes[2]->hasAttribute('disabled'));
    $this->assertTrue($checkboxes[3]->hasAttribute('disabled'));
    // Select the items.
626
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
627
    $assert_session->assertWaitOnAjaxRequest();
628 629 630 631 632
    // Assert the open button is disabled.
    $open_button = $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]');
    $this->assertTrue($open_button->hasAttribute('data-disabled-focus'));
    $this->assertTrue($open_button->hasAttribute('disabled'));
    $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .media-library-open-button").is(":disabled")');
633

634
    // Ensure that the selection completed successfully.
635
    $assert_session->pageTextNotContains('Add or select media');
636 637
    $assert_session->pageTextNotContains('Dog');
    $assert_session->pageTextContains('Cat');
638 639
    $assert_session->pageTextContains('Turtle');
    $assert_session->pageTextNotContains('Snake');
640

641 642 643
    // Remove "Cat" (happens to be the first remove button on the page).
    $assert_session->elementAttributeContains('css', '.media-library-item__remove', 'aria-label', 'Remove Cat');
    $assert_session->elementExists('css', '.media-library-item__remove')->click();
644
    $assert_session->assertWaitOnAjaxRequest();
645 646
    // Assert the focus is set to the remove button of the other selected item.
    $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .media-library-item__remove").is(":focus")');
647
    $assert_session->pageTextNotContains('Cat');
648
    $assert_session->pageTextContains('Turtle');
649 650 651 652 653
    // Assert the open button is no longer disabled.
    $open_button = $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]');
    $this->assertFalse($open_button->hasAttribute('data-disabled-focus'));
    $this->assertFalse($open_button->hasAttribute('disabled'));
    $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .media-library-open-button").is(":not(:disabled)")');
654 655

    // Open the media library again and select another item.
656
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
657 658
    $assert_session->assertWaitOnAjaxRequest();
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
659
    $this->assertGreaterThanOrEqual(1, count($checkboxes));
660
    $checkboxes[0]->click();
661
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
662
    $assert_session->assertWaitOnAjaxRequest();
663 664
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Cat');
665 666
    $assert_session->pageTextContains('Turtle');
    $assert_session->pageTextNotContains('Snake');
667 668 669 670
    // Assert the open button is disabled.
    $this->assertTrue($assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->hasAttribute('data-disabled-focus'));
    $this->assertTrue($assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->hasAttribute('disabled'));
    $this->assertJsCondition('jQuery("#field_twin_media-media-library-wrapper .media-library-open-button").is(":disabled")');
671 672

    // Assert the selection is cleared when the modal is closed.
673
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
674
    $assert_session->assertWaitOnAjaxRequest();
675 676
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
    $this->assertGreaterThanOrEqual(4, count($checkboxes));
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    // Nothing is selected yet.
    $this->assertFalse($checkboxes[0]->isChecked());
    $this->assertFalse($checkboxes[1]->isChecked());
    $this->assertFalse($checkboxes[2]->isChecked());
    $this->assertFalse($checkboxes[3]->isChecked());
    $assert_session->elementTextContains('css', '.media-library-selected-count', '0 items selected');
    // Select the first 2 items.
    $checkboxes[0]->click();
    $assert_session->elementTextContains('css', '.media-library-selected-count', '1 item selected');
    $checkboxes[1]->click();
    $assert_session->elementTextContains('css', '.media-library-selected-count', '2 items selected');
    $this->assertTrue($checkboxes[0]->isChecked());
    $this->assertTrue($checkboxes[1]->isChecked());
    $this->assertFalse($checkboxes[2]->isChecked());
    $this->assertFalse($checkboxes[3]->isChecked());
    // Close the dialog, reopen it and assert not is selected again.
    $page->find('css', '.ui-dialog-titlebar-close')->click();
694
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
695 696 697 698 699 700 701 702
    $assert_session->assertWaitOnAjaxRequest();
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
    $this->assertFalse($checkboxes[0]->isChecked());
    $this->assertFalse($checkboxes[1]->isChecked());
    $this->assertFalse($checkboxes[2]->isChecked());
    $this->assertFalse($checkboxes[3]->isChecked());
    $page->find('css', '.ui-dialog-titlebar-close')->click();

703 704 705 706
    // Finally, save the form.
    $assert_session->elementExists('css', '.js-media-library-widget-toggle-weight')->click();
    $this->submitForm([
      'title[0][value]' => 'My page',
707
      'field_twin_media[selection][0][weight]' => '2',
708 709 710
    ], 'Save');
    $assert_session->pageTextContains('Basic Page My page has been created');
    // We removed this item earlier.
711 712
    $assert_session->pageTextNotContains('Cat');
    // This item was never selected.
713
    $assert_session->pageTextNotContains('Snake');
714 715
    // "Dog" should come after "Turtle", since we changed the weight.
    $assert_session->elementExists('css', '.field--name-field-twin-media > .field__items > .field__item:last-child:contains("Turtle")');
716
    // Make sure everything that was selected shows up.
717
    $assert_session->pageTextContains('Dog');
718
    $assert_session->pageTextContains('Turtle');
719 720 721

    // Re-edit the content and make a new selection.
    $this->drupalGet('node/1/edit');
722 723 724 725
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextNotContains('Cat');
    $assert_session->pageTextNotContains('Bear');
    $assert_session->pageTextNotContains('Horse');
726
    $assert_session->pageTextContains('Turtle');
727
    $assert_session->pageTextNotContains('Snake');
728
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
729
    $assert_session->assertWaitOnAjaxRequest();
730
    $assert_session->pageTextContains('Add or select media');
731
    // Select all media items of type one (should also contain Dog, again).
732 733
    $checkbox_selector = '.media-library-view .js-click-to-select-checkbox input';
    $checkboxes = $page->findAll('css', $checkbox_selector);
734
    $this->assertGreaterThanOrEqual(4, count($checkboxes));
735
    $checkboxes[0]->click();
736 737 738
    $checkboxes[1]->click();
    $checkboxes[2]->click();
    $checkboxes[3]->click();
739
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
740 741 742 743 744 745
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextContains('Cat');
    $assert_session->pageTextContains('Bear');
    $assert_session->pageTextContains('Horse');
    $assert_session->pageTextContains('Turtle');
746 747 748 749 750 751 752 753
    $assert_session->pageTextNotContains('Snake');
    $this->submitForm([], 'Save');
    $assert_session->pageTextContains('Dog');
    $assert_session->pageTextContains('Cat');
    $assert_session->pageTextContains('Bear');
    $assert_session->pageTextContains('Horse');
    $assert_session->pageTextContains('Turtle');
    $assert_session->pageTextNotContains('Snake');
754 755 756 757 758 759 760
  }

  /**
   * Tests that the widget works as expected for anonymous users.
   */
  public function testWidgetAnonymous() {
    $assert_session = $this->assertSession();
761
    $page = $this->getSession()->getPage();
762 763 764 765

    $this->drupalLogout();

    // Allow the anonymous user to create pages and view media.
766
    $role = Role::load(RoleInterface::ANONYMOUS_ID);
767 768 769 770 771 772 773 774 775 776
    $this->grantPermissions($role, [
      'access content',
      'create basic_page content',
      'view media',
    ]);

    // Ensure the widget works as an anonymous user.
    $this->drupalGet('node/add/basic_page');

    // Add to the unlimited cardinality field.
777
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
778 779 780
    $assert_session->assertWaitOnAjaxRequest();

    // Select the first media item (should be Dog).
781
    $page->find('css', '.media-library-view .js-click-to-select-checkbox input')->click();
782
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
783 784 785
    $assert_session->assertWaitOnAjaxRequest();

    // Ensure that the selection completed successfully.
786
    $assert_session->pageTextNotContains('Add or select media');
787 788 789 790 791 792 793 794 795 796 797 798
    $assert_session->pageTextContains('Dog');

    // Save the form.
    $assert_session->elementExists('css', '.js-media-library-widget-toggle-weight')->click();
    $this->submitForm([
      'title[0][value]' => 'My page',
      'field_unlimited_media[selection][0][weight]' => '0',
    ], 'Save');
    $assert_session->pageTextContains('Basic Page My page has been created');
    $assert_session->pageTextContains('Dog');
  }

799 800 801 802 803 804
  /**
   * Tests that uploads in the Media library's widget works as expected.
   */
  public function testWidgetUpload() {
    $assert_session = $this->assertSession();
    $page = $this->getSession()->getPage();
805
    $driver = $this->getSession()->getDriver();
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820

    foreach ($this->getTestFiles('image') as $image) {
      $extension = pathinfo($image->filename, PATHINFO_EXTENSION);
      if ($extension === 'png') {
        $png_image = $image;
      }
      elseif ($extension === 'jpg') {
        $jpg_image = $image;
      }
    }

    if (!isset($png_image) || !isset($jpg_image)) {
      $this->fail('Expected test files not present.');
    }

821 822 823 824 825
    // Create a user that can only add media of type four.
    $user = $this->drupalCreateUser([
      'access administration pages',
      'access content',
      'create basic_page content',
826
      'create type_one media',
827 828 829 830 831 832 833
      'create type_four media',
      'view media',
    ]);
    $this->drupalLogin($user);

    // Visit a node create page and open the media library.
    $this->drupalGet('node/add/basic_page');
834
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
835
    $assert_session->assertWaitOnAjaxRequest();
836
    $assert_session->pageTextContains('Add or select media');
837

838 839 840 841 842 843 844 845 846 847
    // Assert the upload form is not visible for default tab type_three without
    // the proper permissions.
    $assert_session->elementNotExists('css', '.media-library-add-form');

    // Assert the upload form is not visible for the non-file based media type
    // type_one.
    $page->clickLink('Type One');
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->elementNotExists('css', '.media-library-add-form');

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    // Assert the upload form is visible for type_four.
    $page->clickLink('Type Four');
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->fieldExists('Add files');
    $assert_session->pageTextContains('Maximum 2 files.');

    // Create a user that can create media for all media types.
    $user = $this->drupalCreateUser([
      'access administration pages',
      'access content',
      'create basic_page content',
      'create media',
      'view media',
    ]);
    $this->drupalLogin($user);

864 865 866 867 868 869 870
    // Visit a node create page.
    $this->drupalGet('node/add/basic_page');

    $file_storage = $this->container->get('entity_type.manager')->getStorage('file');
    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = $this->container->get('file_system');

871
    // Add to the twin media field.
872
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
873
    $assert_session->assertWaitOnAjaxRequest();
874
    $assert_session->pageTextContains('Add or select media');
875

876 877 878
    // Assert the upload form is now visible for default tab type_three.
    $assert_session->elementExists('css', '.media-library-add-form');
    $assert_session->fieldExists('Add files');
879

880
    // Assert we can upload a file to the default tab type_three.
881 882 883 884
    $assert_session->elementExists('css', '.media-library-add-form--without-input');
    $assert_session->elementNotExists('css', '.media-library-add-form--with-input');
    $page->attachFileToField('Add files', $this->container->get('file_system')->realpath($png_image->uri));
    $assert_session->assertWaitOnAjaxRequest();
885 886 887
    $this->assertJsCondition('jQuery(".media-library-add-form__added-media").is(":focus")');
    $assert_session->pageTextContains('The media item has been created but has not yet been saved. Fill in any required fields and save to add it to the media library.');
    $assert_session->elementAttributeContains('css', '.media-library-add-form__added-media', 'aria-label', 'Added media items');
888 889
    $assert_session->elementExists('css', '.media-library-add-form--with-input');
    $assert_session->elementNotExists('css', '.media-library-add-form--without-input');
890 891 892
    // We do not have a pre-selected items, so the container should not be added
    // to the form.
    $assert_session->elementNotExists('css', '.media-library-add-form__selected-media');
893 894 895 896 897
    // Files are temporary until the form is saved.
    $files = $file_storage->loadMultiple();
    $file = array_pop($files);
    $this->assertSame('public://type-three-dir', $file_system->dirname($file->getFileUri()));
    $this->assertTrue($file->isTemporary());
898 899 900 901
    // Assert the revision_log_message field is not shown.
    $upload_form = $assert_session->elementExists('css', '.media-library-add-form');
    $assert_session->fieldNotExists('Revision log message', $upload_form);
    // Assert the name field contains the filename and the alt text is required.
902
    $assert_session->fieldValueEquals('Name', $png_image->filename);
903
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Save and select');
904 905 906
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextContains('Alternative text field is required');
    $page->fillField('Alternative text', $this->randomString());
907
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Save and select');
908 909 910 911 912
    $assert_session->assertWaitOnAjaxRequest();
    // The file should be permanent now.
    $files = $file_storage->loadMultiple();
    $file = array_pop($files);
    $this->assertFalse($file->isTemporary());
913
    // Load the created media item.
914
    $media_items = Media::loadMultiple();
915 916 917 918
    $added_media = array_pop($media_items);
    // Ensure the media item was saved to the library and automatically
    // selected. The added media items should be in the first position of the
    // add form.
919
    $assert_session->pageTextContains('Add or select media');
920 921 922 923
    $assert_session->pageTextContains($png_image->filename);
    $assert_session->fieldValueEquals('media_library_select_form[0]', $added_media->id());
    $assert_session->checkboxChecked('media_library_select_form[0]');
    $assert_session->pageTextContains('1 of 2 items selected');
924
    $assert_session->hiddenFieldValueEquals('current_selection', $added_media->id());
925
    // Ensure the created item is added in the widget.
926
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');
927
    $assert_session->assertWaitOnAjaxRequest();
928
    $assert_session->pageTextNotContains('Add or select media');
929 930
    $assert_session->pageTextContains($png_image->filename);

931 932 933 934 935 936 937 938 939 940 941
    // Remove the item.
    $assert_session->elementExists('css', '.media-library-item__remove')->click();
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextNotContains($png_image->filename);

    // Assert we can also directly insert uploaded files in the widget.
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_twin_media"]')->click();
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextContains('Add or select media');
    $page->clickLink('Type Three');
    $assert_session->assertWaitOnAjaxRequest();
942
    $png_uri_2 = $file_system->copy($png_image->uri, 'public://');
943 944 945 946 947 948 949 950
    $page->attachFileToField('Add files', $this->container->get('file_system')->realpath($png_uri_2));
    $assert_session->assertWaitOnAjaxRequest();
    $page->fillField('Alternative text', $this->randomString());
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Save and insert');
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->pageTextNotContains('Add or select media');
    $assert_session->pageTextContains($file_system->basename($png_uri_2));

951
    // Also make sure that we can upload to the unlimited cardinality field.
952
    $assert_session->elementExists('css', '.media-library-open-button[name^="field_unlimited_media"]')->click();
953
    $assert_session->assertWaitOnAjaxRequest();
954
    $assert_session->pageTextContains('Add or select media');
955
    $page->clickLink('Type Three');
956
    $assert_session->assertWaitOnAjaxRequest();
957

958 959 960 961 962 963
    // Select a media item to check if the selection is persisted when adding
    // new items.
    $existing_media_name = $file_system->basename($png_uri_2);
    $checkbox = $page->findField("Select $existing_media_name");
    $selected_item_id = $checkbox->getAttribute('value');
    $checkbox->click();
964
    $assert_session->pageTextContains('1 item selected');
965
    $assert_session->hiddenFieldValueEquals('current_selection', $selected_item_id);
966
    $png_uri_3 = $file_system->copy($png_image->uri, 'public://');
967
    $page->attachFileToField('Add files', $this->container->get('file_system')->realpath($png_uri_3));
968
    $assert_session->assertWaitOnAjaxRequest();
969
    $assert_session->checkboxChecked("Select $existing_media_name");
970 971
    $page->fillField('Name', 'Unlimited Cardinality Image');
    $page->fillField('Alternative text', $this->randomString());
972
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Save and select');
973
    $assert_session->assertWaitOnAjaxRequest();
974
    // Load the created media item.
975
    $media_items = Media::loadMultiple();
976
    $added_media = array_pop($media_items);
977
    $added_media_name = $added_media->label();
978 979 980
    // Ensure the media item was saved to the library and automatically
    // selected. The added media items should be in the first position of the
    // add form.
981
    $assert_session->pageTextContains('Add or select media');
982 983 984 985 986 987
    $assert_session->pageTextContains('Unlimited Cardinality Image');
    $assert_session->fieldValueEquals('media_library_select_form[0]', $added_media->id());
    $assert_session->checkboxChecked('media_library_select_form[0]');
    // Assert the item that was selected before uploading the file is still
    // selected.
    $assert_session->pageTextContains('2 items selected');
988 989 990
    $assert_session->checkboxChecked("Select $added_media_name");
    $assert_session->checkboxChecked("Select $existing_media_name");
    $assert_session->hiddenFieldValueEquals('current_selection', implode(',', [$selected_item_id, $added_media->id()]));
991 992 993 994
    $checkboxes = $page->findAll('css', '.media-library-view .js-click-to-select-checkbox input');
    $selected_checkboxes = [];
    foreach ($checkboxes as $checkbox) {
      if ($checkbox->isChecked()) {
995
        $selected_checkboxes[] = $checkbox->getAttribute('value');
996 997 998 999
      }
    }
    $this->assertCount(2, $selected_checkboxes);
    // Ensure the created item is added in the widget.
1000
    $assert_session->elementExists('css', '.ui-dialog-buttonpane')->pressButton('Insert selected');