<script>

function runTest() {
    document.write(`<a><p><span tabindex="0">dummy</span><iframe onload="didLoadIframe()"></iframe><script> document.body.innerHTML = ''; <\/script>`);
}

let callCount = 0;
let span;
let range;
function didLoadIframe() {
    callCount++;
    if (callCount == 1)
        document.write('</a>');
    else if (callCount == 2) {
        // Test ContainerNode::takeAllChildrenFrom adjusts focused node and update ranges.
        span = document.querySelector('span');
        span.focus();
        range = new Range;
        range.selectNode(span.firstChild);
    } else if (callCount == 3) {
        setTimeout(() => {
            let activeElementResult = (document.activeElement == span) ? 'PASS' : `FAIL - it was set on ${document.activeElement}`;
            let rangeStartResult = (range.startContainer == span) ? 'PASS' : `FAIL - it was set on ${range.startContainer}`;

            document.documentElement.innerHTML = `<body>
            Active Element must be moved to span: ${activeElementResult}<br>
            range.startContainer must be moved to span: ${rangeStartResult}<br>`;

            if (window.testRunner)
                testRunner.notifyDone();
        }, 0);
    }
}

/*

 0. The outer document.write creates the following tree:
    body
      + a
        + p
          + span
          + iframe

 1. iframe's load event fires, and invokes the inner document.write,
    which forces <script> from the outer document.write to be parsed:
    body
      + a
        + p
          + span
          + iframe
          + script

   1.a. The script runs, and invokes document.body.innerHTML = '':
        body

   1.b. The adoption agency algorithm is involved, and p is removed from a
        while both of them are detached from body.

   1.c. The adoption agency algorithm inserts p back into body along with iframe.
        body
          + p
            + span
            + iframe
            + script

 2. iframe's load event fires for the second time per step 1.c.

    2.a. the focus is set on span and a range is created inside span.

    2.b. The adoption agency algorithm now takes all children of p
         and inserts them back under "a", and then inserts "p" under body.

3. iframe's load event fires for the third time per step 2.b.

*/

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

runTest();

</script>
