 .../QuickEditIntegrationTest.php                   | 321 +++++++++++++++++++++
 1 file changed, 321 insertions(+)

diff --git a/core/modules/quickedit/tests/src/FunctionalJavaScript/QuickEditIntegrationTest.php b/core/modules/quickedit/tests/src/FunctionalJavaScript/QuickEditIntegrationTest.php
new file mode 100644
index 0000000..1ba5cf0
--- /dev/null
+++ b/core/modules/quickedit/tests/src/FunctionalJavaScript/QuickEditIntegrationTest.php
@@ -0,0 +1,321 @@
+<?php
+
+namespace Drupal\Tests\quickedit\FunctionalJavascript;
+
+use Drupal\editor\Entity\Editor;
+use Drupal\filter\Entity\FilterFormat;
+use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
+
+/**
+ * @group quickedit
+ */
+class QuickEditIntegrationTest extends JavascriptTestBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public static $modules = ['node', 'editor', 'ckeditor', 'contextual', 'quickedit', 'toolbar'];
+
+  /**
+   * A user with permissions to edit Articles and use Quick Edit.
+   *
+   * @var \Drupal\user\UserInterface
+   */
+  protected $contentAuthorUser;
+
+  protected static $expectedFieldStateAttributes = [
+    'candidate' => '.quickedit-field.quickedit-editable.quickedit-candidate:not(.quickedit-highlighted):not(.quickedit-editing):not(.quickedit-changed)',
+    'active'    => '.quickedit-field.quickedit-editable.quickedit-candidate.quickedit-highlighted.quickedit-editing:not(.quickedit-changed)',
+    'changed'   => '.quickedit-field.quickedit-editable.quickedit-candidate.quickedit-highlighted.quickedit-editing.quickedit-changed',
+    'saving'    => '.quickedit-field.quickedit-editable.quickedit-candidate.quickedit-highlighted.quickedit-editing.quickedit-changed',
+  ];
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    // Create text format, associate CKEditor.
+    FilterFormat::create([
+      'format' => 'some_format',
+      'name' => 'Some format',
+      'weight' => 0,
+      'filters' => [
+        'filter_html' => [
+          'status' => 1,
+          'settings' => [
+            'allowed_html' => '<h2 id> <h3> <h4> <h5> <h6> <p> <br> <strong> <a href hreflang>',
+          ],
+        ],
+      ],
+    ])->save();
+    Editor::create([
+      'format' => 'some_format',
+      'editor' => 'ckeditor',
+    ])->save();
+
+    // Create the Article node type.
+    $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
+
+    // Log in as a content author who can use Quick Edit and edit Articles.
+    $this->contentAuthorUser = $this->drupalCreateUser([
+      'access contextual links',
+      'access toolbar',
+      'access in-place editing',
+      'access content',
+      'create article content',
+      'edit any article content',
+      'use text format some_format',
+    ]);
+    $this->drupalLogin($this->contentAuthorUser);
+  }
+
+  protected function startQuickEditViaToolbar($entity_type_id, $entity_id) {
+    $page = $this->getSession()->getPage();
+
+    $toolbar_edit_button_selector = '#toolbar-bar .contextual-toolbar-tab button';
+    $entity_selector = '[data-quickedit-entity-id="' . $entity_type_id . '/' . $entity_id . '"]';
+    $contextual_links_trigger_selector = '[data-contextual-id] > .trigger';
+
+    // Assert the original page state does not have the toolbar's "Edit" button
+    // pressed/activated, and hence none of the contextual link triggers should
+    // be visible.
+    $toolbar_edit_button = $page->find('css', $toolbar_edit_button_selector);
+    $this->assertSame('false', $toolbar_edit_button->getAttribute('aria-pressed'), 'The "Edit" button in the toolbar is not yet pressed.');
+    $this->assertFalse($toolbar_edit_button->hasClass('is-active'), 'The "Edit" button in the toolbar is not yet marked as active.');
+    foreach ($page->findAll('css', $contextual_links_trigger_selector) as $dom_node) {
+      /** @var \Behat\Mink\Element\NodeElement $dom_node */
+      $this->assertTrue($dom_node->hasClass('visually-hidden'), 'The contextual links trigger "' . $dom_node->getParent()->getAttribute('data-contextual-id') .'" is hidden.');
+    }
+    $this->assertTrue(TRUE, 'All contextual links triggers are hidden.');
+
+    // Click the "Edit" button in the toolbar.
+    $this->click($toolbar_edit_button_selector);
+
+    // Assert the toolbar's "Edit" button is now pressed/activated, and hence
+    // allof the contextual link triggers should be visible.
+    $this->assertSame('true', $toolbar_edit_button->getAttribute('aria-pressed'), 'The "Edit" button in the toolbar is pressed.');
+    $this->assertTrue($toolbar_edit_button->hasClass('is-active'), 'The "Edit" button in the toolbar is marked as active.');
+    foreach ($page->findAll('css', $contextual_links_trigger_selector) as $dom_node) {
+      /** @var \Behat\Mink\Element\NodeElement $dom_node */
+      $this->assertFalse($dom_node->hasClass('visually-hidden'), 'The contextual links trigger "' . $dom_node->getParent()->getAttribute('data-contextual-id') .'" is visible.');
+    }
+    $this->assertTrue(TRUE, 'All contextual links triggers are visible.');
+
+    // @todo Press tab key to verify that tabbing is now contrained to only
+    // contextual links triggers.
+
+    // Assert that the contextual links associated with the entity's contextual
+    // links trigger are not visible.
+    /** @var \Behat\Mink\Element\NodeElement $entity_contextual_links_container */
+    $entity_contextual_links_container = $page->find('css', $entity_selector)
+      ->find('css', $contextual_links_trigger_selector)
+      ->getParent();
+    $this->assertFalse($entity_contextual_links_container->hasClass('open'));
+    $this->assertTrue($entity_contextual_links_container->find('css', 'ul.contextual-links')->hasAttribute('hidden'));
+
+    // Click the contextual link trigger for the entity we want to Quick Edit.
+    $this->click($entity_selector . ' ' . $contextual_links_trigger_selector);
+
+    $this->assertTrue($entity_contextual_links_container->hasClass('open'));
+    $this->assertFalse($entity_contextual_links_container->find('css', 'ul.contextual-links')->hasAttribute('hidden'));
+
+    // Click the "Quick edit" contextual link.
+    $this->click($entity_selector . ' [data-contextual-id] ul.contextual-links li.quickedit a');
+
+    // Assert the Quick Edit internal state is correct.
+    $js_condition = <<<JS
+Drupal.quickedit.collections.entities.where({isActive: true}).length === 1 && Drupal.quickedit.collections.entities.where({isActive: true})[0].get('entityID') === '$entity_type_id/$entity_id';
+JS;
+    $this->assertJsCondition($js_condition);
+  }
+
+  // @todo startViaMouseOver
+
+  protected function awaitQuickEditForEntity($entity_type_id, $entity_id) {
+    $entity_selector = '[data-quickedit-entity-id="' . $entity_type_id . '/' . $entity_id . '"]';
+    $condition = "document.querySelectorAll('" . $entity_selector . " .quickedit').length > 0";
+    $this->assertJsCondition($condition, 10000);
+  }
+
+  /**
+   * @param string $expected_entity_label
+   *   The expected label in the Quick Edit Entity Toolbar.
+   */
+  protected function assertQuickEditEntityToolbar($expected_entity_label, $expected_field_label) {
+    $quickedit_entity_toolbar = $this->getSession()->getPage()->findById('quickedit-entity-toolbar');
+    // We cannot use ->getText() because it also returns the text of all child
+    // nodes. So we use XPath to select only the text node.
+    $this->assertSame($expected_entity_label, $quickedit_entity_toolbar->find('css', '.quickedit-toolbar-label')->find('xpath', 'text()')->getText());
+    if ($expected_field_label !== NULL) {
+      $this->assertSame($expected_field_label, $quickedit_entity_toolbar->find('css', '.quickedit-toolbar-label > .field')->getText());
+    }
+    else {
+      $this->assertFalse($quickedit_entity_toolbar->find('css', '.quickedit-toolbar-label > .field'));
+    }
+  }
+
+  /**
+   * Asserts all EntityModels for the page.
+   *
+   * @see Drupal.quickedit.EntityModel
+   *
+   * @param array $expected_entity_states
+   *   Must describe the expected state of all in-place editable entities on the
+   *   page.
+   */
+  protected function assertEntityStates(array $expected_entity_states) {
+    $js_get_all_field_states_for_entity = <<<JS
+function () {
+    Drupal.quickedit.collections.entities.reduce(function (result, fieldModel) { result[fieldModel.get('id')] = fieldModel.get('state'); return result; }, {})
+  var entityCollection = Drupal.quickedit.collections.entities;
+  return entityCollection.reduce(function (result, entityModel) {
+    result[entityModel.id] = entityModel.get('state');
+    return result;
+  }, {});
+}()
+JS;
+    $this->assertSame($expected_entity_states, $this->getSession()->evaluateScript($js_get_all_field_states_for_entity));
+  }
+
+  protected function assertEntityFieldStates($entity_type_id, $entity_id, $entity_instance_id, array $expected_field_states) {
+    // Get all FieldModel states for the entity instance being asserted. This
+    // ensures that $expected_field_states must describe the state of all fields
+    // of the entity instance.
+    $entity_page_id = $entity_type_id . '/' . $entity_id . '[' . $entity_instance_id . ']';
+    $js_get_all_field_states_for_entity = <<<JS
+function () {
+  var entityCollection = Drupal.quickedit.collections.entities;
+  var entityModel = entityCollection.get('$entity_page_id');
+  return entityModel.get('fields').reduce(function (result, fieldModel) {
+    result[fieldModel.get('fieldID')] = fieldModel.get('state');
+    return result;
+  }, {});
+}()
+JS;
+    $this->assertSame($expected_field_states, $this->getSession()->evaluateScript($js_get_all_field_states_for_entity));
+
+    // Assert that those fields also have the appropriate DOM decorations.
+    $expected_field_attributes = [];
+    foreach ($expected_field_states as $quickedit_field_id => $expected_field_state) {
+      $expected_field_attributes[$quickedit_field_id] = static::$expectedFieldStateAttributes[$expected_field_state];
+    }
+    $this->assertEntityFieldMarkup($entity_type_id, $entity_id, $entity_instance_id, $expected_field_attributes);
+  }
+
+  protected function assertEntityFieldMarkup($entity_type_id, $entity_id, $entity_instance_id, array $expected_field_attributes) {
+    $entity_page_id = $entity_type_id . '/' . $entity_id . '[' . $entity_instance_id . ']';
+    $expected_field_attributes_json = json_encode($expected_field_attributes);
+    $js_match_field_element_attributes = <<<JS
+function () {
+  var expectations = $expected_field_attributes_json;
+  var entityCollection = Drupal.quickedit.collections.entities;
+  var entityModel = entityCollection.get('$entity_page_id');
+  return entityModel.get('fields').reduce(function (result, fieldModel) {
+    var fieldID = fieldModel.get('fieldID');
+    var element = fieldModel.get('el');
+    var matches = element.webkitMatchesSelector(expectations[fieldID]);
+    result[fieldID] = matches ? matches : element.outerHTML;
+    return result;
+  }, {});
+}()
+JS;
+//    var_dump($js_match_field_element_attributes);
+    $result = $this->getSession()->evaluateScript($js_match_field_element_attributes);
+    foreach ($expected_field_attributes as $quickedit_field_id => $expectation) {
+      $this->assertSame(TRUE, $result[$quickedit_field_id], 'Field ' . $quickedit_field_id . ' did not match its expectation selector (' . $expectation . '), actual HTML: ' . $result[$quickedit_field_id]);
+    }
+  }
+
+  /**
+   * Tests if an article node can be in-place edited with Quick Edit.
+   */
+  public function testArticleNode() {
+    $node = $this->drupalCreateNode([
+      'type' => 'article',
+      'title' => t('My Test Node'),
+      'body' => [
+        'value' => 'Hello world!',
+        'format' => 'some_format',
+      ],
+    ]);
+
+    $this->drupalGet('node/' . $node->id());
+
+    // Initial state.
+    $this->awaitQuickEditForEntity('node', 1);
+    $this->assertEntityStates([
+      'node/1[0]' => 'closed',
+    ]);
+
+    // Start in-place editing of the article node.
+    $this->startQuickEditViaToolbar('node', 1);
+    $this->assertEntityStates([
+      'node/1[0]' => 'opened',
+    ]);
+    $this->assertQuickEditEntityToolbar((string) $node->label(), NULL);
+    $this->assertEntityFieldStates('node', 1, 0, [
+      'node/1/title/en/full'   => 'candidate',
+      'node/1/uid/en/full'     => 'candidate',
+      'node/1/created/en/full' => 'candidate',
+      'node/1/body/en/full'    => 'candidate',
+    ]);
+
+    // Click the title field.
+    $this->click('h1.js-quickedit-page-title > span');
+    $this->assertQuickEditEntityToolbar((string) $node->label(), 'Title');
+    $this->assertEntityFieldStates('node', 1, 0, [
+      'node/1/title/en/full'   => 'active',
+      'node/1/uid/en/full'     => 'candidate',
+      'node/1/created/en/full' => 'candidate',
+      'node/1/body/en/full'    => 'candidate',
+    ]);
+
+    // Type in the title field.
+    // @todo Clean this up once PhantomJS is fixed, see http://sticksnglue.com/wordpress/phantomjs-1-9-and-keyboardevent/.
+    $text_to_type = $node->get('body')->value . ' Llamas are awesome!';
+    $js_simulate_user_typing = <<<JS
+function () {
+  window.KeyboardEvent = function(eventString) {
+    var keyboardEvent = document.createEvent('KeyboardEvent');
+    keyboardEvent.initKeyboardEvent(eventString, true, true, window, 1, 0, 0);
+    return keyboardEvent;
+  };
+  var el = document.querySelector('h1.js-quickedit-page-title > span');
+  el.textContent = '$text_to_type';
+  el.dispatchEvent(window.KeyboardEvent('keyup'));
+}()
+JS;
+    $this->getSession()->evaluateScript($js_simulate_user_typing);
+    $this->assertEntityFieldStates('node', 1, 0, [
+      'node/1/title/en/full'   => 'changed',
+      'node/1/uid/en/full'     => 'candidate',
+      'node/1/created/en/full' => 'candidate',
+      'node/1/body/en/full'    => 'candidate',
+    ]);
+
+    // Click the body field.
+    $this->click('[data-quickedit-entity-id="node/1"] .field--name-body');
+    $this->assertQuickEditEntityToolbar((string) $node->label(), 'Body');
+    $this->assertEntityFieldStates('node', 1, 0, [
+      'node/1/title/en/full'   => 'saving',
+      'node/1/uid/en/full'     => 'candidate',
+      'node/1/created/en/full' => 'candidate',
+      'node/1/body/en/full'    => 'active',
+    ]);
+
+    $this->createScreenshot('/tmp/screenshot.png');
+
+    // @todo wait for CKEditor instance to load
+
+    // @todo type something
+
+    // @todo change another field
+
+    // @todo save
+  }
+
+  // @todo test custom block
+
+}
