<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="../../../../resources/js-test.js"></script>
<script src="../../../../resources/ui-helper.js"></script>
<style>
.target {
    width: 150px;
    height: 150px;
    margin-bottom: 1em;
    border: 4px solid black;
    color: white;
    font-size: 20px;
}

#target1 {
    background-color: rgb(52, 199, 89);
}

#target2 {
    background-color: rgb(52, 199, 89);
}
</style>
<script>
jsTestIsAsync = true;
handledFirstTouch = false;
handledSecondTouch = false;

function spinForDuration(duration) {
    const startTime = Date.now();
    while (true) {
        if (Date.now() - startTime > duration)
            break;
    }
}

function handleClick(event) {
    event.target.style.backgroundColor = "rgb(255, 59, 48)";
    event.target.textContent = "A click event was dispatched.";
    testFailed("Should not have handled a click");
}

addEventListener("load", async () => {
    const target1 = document.getElementById("target1");
    target1.addEventListener("touchstart", event => {
        spinForDuration(100);
        event.preventDefault();
    });
    target1.addEventListener("touchend", event => handledFirstTouch = true);
    target1.addEventListener("click", handleClick);

    const target2 = document.getElementById("target2");
    target2.addEventListener("touchstart", () => spinForDuration(100));
    target2.addEventListener("touchend", event => {
        event.preventDefault();
        handledSecondTouch = true;
    });
    target2.addEventListener("click", handleClick);

    description("Verifies that calling preventDefault() in touchstart and touchend listeners prevents click events from being dispatched when the web page takes a long time to process the touchstart event. To manually run the test, tap the two boxes and verify that no click events are dispatched.");

    if (!window.testRunner)
        return;

    await UIHelper.activateElement(target1);
    await new Promise(resolve => shouldBecomeEqual("handledFirstTouch", "true", resolve));

    await UIHelper.activateElement(target2);
    await new Promise(resolve => shouldBecomeEqual("handledSecondTouch", "true", resolve));

    finishJSTest();
});
</script>
</head>
<body>
    <div class="target" id="target1"></div>
    <div class="target" id="target2"></div>
</body>
</html>