<!DOCTYPE html>
<link rel=author href="mailto:jarhar@chromium.org">
<link rel=help href="https://github.com/whatwg/html/pull/8199">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>

<dialog autofocus id=autofocusdialog data-description="dialog element with autofocus should get initial focus." class=target>
  <button>focusable button</button>
  <button autofocus>autofocusable button</button>
</dialog>

<dialog id=keyboardfocusdialog data-description="Only keyboard-focusable elements should get dialog initial focus.">
  <button tabindex="-1">mouse focusable button</button>
  <button class=target>keyboard focusable button</button>
</dialog>

<dialog id=autofocuswithoutkeyboarddialog data-description="Autofocus takes precedence over keyboard-focusable requirement.">
  <button>keyboard focusable button</button>
  <button tabindex="-1" autofocus class=target>mouse focusable autofocus button</button>
</dialog>

<dialog id=subtree data-description="Only keyboard-focusable elements should get dialog initial focus including in subtrees.">
  <div>
    <button tabindex="-1">mouse focusable button</button>
    <button class=target>keyboard focusable button</button>
  </div>
</dialog>

<dialog id=nestedbuttons data-description="Only keyboard-focusable elements should get dialog initial focus including in nested buttons.">
  <button tabindex="-1">
    <span>mouse focusable button</span>
    <button tabindex="-1">nested mouse focusable button</button>
  </button>
  <button class=target>keyboard focusable button</button>
</dialog>

<script>
document.querySelectorAll('dialog').forEach(dialog => {
  test(t => {
    let target = dialog.querySelector('.target');
    if (dialog.classList.contains('target')) {
      target = dialog;
    }
    t.add_cleanup(() => {
      if (dialog.open)
        dialog.close();
    });

    dialog.showModal();
    assert_equals(document.activeElement, target,
      'showModal: the target element did not receive initial focus.');
    dialog.close();

    dialog.show();
    assert_equals(document.activeElement, target,
      'show: the target element did not receive initial focus.');
    dialog.close();
  }, dialog.dataset.description);
});
</script>
