<!DOCTYPE html>
<html>
<body>
<p>This tests that JS wrappers of rects in an IntersectionObserverEntry do not get collected.</p>
<pre id="log"></pre>
<script src="../resources/gc.js"></script>
<script>

if (window.testRunner)
    testRunner.dumpAsText();

const targetCount = 5;
const iterationCount = 5;

for (let i = 0; i < targetCount; ++i) {
    let target = document.createElement('div');
    document.body.appendChild(target);
}

async function observe() {
    return new Promise((resolve) => {
        const observer = new IntersectionObserver(entries => {
            for (const entry of entries) {
                entry.rootBounds.myState = 'live';
                entry.boundingClientRect.myState = 'live';
                entry.intersectionRect.myState = 'live';
            }
            resolve(entries);
            observer.disconnect();
        });
        document.querySelectorAll('div').forEach(target => { observer.observe(target); });
    });
}

function check(entries) {
    let deadCount = 0;
    for (const entry of entries) {
        if (entry.rootBounds.myState != 'live')
            deadCount++;
        if (entry.boundingClientRect.myState != 'live')
            deadCount++;
        if (entry.intersectionRect.myState != 'live')
            deadCount++;
    }
    document.getElementById('log').textContent += (deadCount ? `FAIL - ${deadCount} rects lost JS wrappers` : 'PASS') + '\n';
}

async function runAll() {
    if (window.testRunner)
        testRunner.waitUntilDone();

    for (let j = 0; j < iterationCount; ++j) {
        const entries = await observe();
        await Promise.resolve();
        gc();
        check(entries);
    }

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

runAll();

</script>
</body>
</html>
