<!DOCTYPE html> <!-- webkit-test-runner [ useFlexibleViewport=true ] -->

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script src="../../../resources/ui-helper.js"></script>
<style>
#editable {
    width: 200px;
    height: 200px;
    top: 0;
    left: 0;
    position: absolute;
}
</style>
</head>

<body style="margin: 0;">
<div contenteditable id="editable"></div>
<p>This test verifies that input events of type "insertReplacementText" target the right ranges.</p>
<p>To manually test, type 'T' into the input field and try to select a candidate. The output should indicate that the beforeinput and input events for the text replacement were handled, and that the range of the beforeinput event is from 0 to 1.</p>
<div id="output"></div>
<script>
let write = (message) => output.innerHTML += (message + "<br>");

function checkForCompletion() {
    doneCount = window.doneCount ? doneCount : 0;
    if (++doneCount == 3 && window.testRunner)
        testRunner.notifyDone();
}

function logInputEvent(event)
{
    if (event.inputType !== "insertReplacementText")
        return;

    if (event.type === "beforeinput") {
        let firstRange = event.getTargetRanges()[0];
        write(`Observed text replacement before input event with range: [${firstRange.startOffset}, ${firstRange.endOffset}] and data: "${event.dataTransfer.getData("text/plain")}"`);
    } else
        write(`Observed text replacement input event with data: "${event.dataTransfer.getData("text/plain")}"`);

    checkForCompletion();
}

function triggerAutocorrectionAfterFirstInput() {
    editable.removeEventListener("input", triggerAutocorrectionAfterFirstInput);
    write(`Replacing "T" with "The"...`);
    getSelection().setBaseAndExtent(editable, 0, editable, 1);
    UIHelper.applyAutocorrection("The", "T").then(checkForCompletion);
}

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

editable.addEventListener("beforeinput", logInputEvent);
editable.addEventListener("input", logInputEvent);
editable.addEventListener("input", triggerAutocorrectionAfterFirstInput);
UIHelper.activateAndWaitForInputSessionAt(100, 100).then(() => UIHelper.typeCharacter("T"));
</script>
</body>
</html>
