<!DOCTYPE html>
<meta name="timeout" content="long">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/open-blank-host.js"></script>
<script>
promise_test(async t => {
  assert_implements("HTMLPortalElement" in self);
  const w = await openBlankPortalHost();
  try {
    const bc = new BroadcastChannel('click-activate');
    const portal = w.document.createElement('portal');
    portal.src = new URL(`resources/portal-activate-broadcastchannel.html?bc=${bc.name}`, location.href);
    w.document.body.appendChild(portal);
    await new Promise(resolve => portal.onload = resolve);
    let activated = new Promise(resolve => bc.onmessage = e => resolve(e.data));
    portal.click();
    let {event, data} = await activated;
    assert_equals(event, 'portalactivate');
    assert_equals(data, undefined);
  } finally {
    w.close();
  }
}, "Clicking should activate with undefined data.");

promise_test(async t => {
  assert_implements("HTMLPortalElement" in self);
  const w = await openBlankPortalHost();
  try {
    const bc = new BroadcastChannel('prevent-no-activate');
    const portal = w.document.createElement('portal');
    portal.src = new URL(`resources/portal-activate-broadcastchannel.html?bc=${bc.name}`, location.href);
    portal.onclick = e => e.preventDefault();
    w.document.body.appendChild(portal);
    await new Promise(resolve => portal.onload = resolve);
    bc.onmessage = t.unreached_func('activation should not occur');
    portal.click();
    await new Promise(resolve => t.step_timeout(resolve, 3000));
  } finally {
    w.close();
  }
}, "Clicking shouldn't activate if prevented.");

// Script didn't create the promise so it shouldn't observe one.
// This forecloses a naive implementation of this behavior that simply calls the WebIDL operation.
promise_test(async t => {
  assert_implements("HTMLPortalElement" in self);
  const w = await openBlankPortalHost();
  try {
    const portal = w.document.createElement('portal');
    w.onunhandledrejection = t.unreached_func('unhandledrejection event should not fire');
    portal.click();
    await new Promise(resolve => t.step_timeout(resolve, 3000));
  } finally {
    w.close();
  }
}, "Failed activation should not surface as an unhandled promise rejection.");
</script>
