chromium/third_party/blink/web_tests/accessibility/inline-text-bounds-for-range.html

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta charset="utf-8">
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
</head>
<body>

<p id="paragraph" style="width: 30em;">
The  Hitchhiker's   Guide to the

Galaxy has a few things to say on the subject of resumés.
A resumé, it says, is about the most massively useful thing an interstellar hitch hiker can have.
</p>

<script>
function parseObject(str) {
    return Function('"use strict"; return (' + str  + ');')();
}

test((t) => {
    var axParagraph = accessibilityController.accessibleElementById('paragraph');
    var axStaticText = axParagraph.childAtIndex(0);

    var text = axStaticText.name;
    assert_equals(text.length, 185);

    // Append the text from all of the inline text boxes and make sure we get the same text.
    var appendedInlineText = '';
    for (var i = 0; i < axStaticText.childrenCount; i++) {
        var axInlineTextBox = axStaticText.childAtIndex(i);
        appendedInlineText += axInlineTextBox.name;
    }
    assert_equals(appendedInlineText, text);

    // For several possible words in the text, get the bounds of the word in the accessibility
    // tree, and also in the DOM, and assert that they're the same, within one pixel.
    var paragraph = document.getElementById('paragraph');
    var domText = paragraph.innerHTML;
    function testWord(word) {
        // Get the bounds from the accessibility tree.
        window.wordAxIndex = text.indexOf(word);
        var axBounds = parseObject(axStaticText.boundsForRange(wordAxIndex, wordAxIndex + word.length));

        // Get the bounds from the DOM.
        window.domIndex = domText.indexOf(word);
        var range = new Range();
        range.setStart(paragraph.firstChild, domIndex);
        range.setEnd(paragraph.firstChild, domIndex + word.length);
        var rangeBounds = range.getBoundingClientRect();

        // Make sure they're the same, within one pixel.
        assert_approx_equals(axBounds.x, rangeBounds.left, 1);
        assert_approx_equals(axBounds.y, rangeBounds.top, 1);
        assert_approx_equals(axBounds.width, rangeBounds.width, 1);
        assert_approx_equals(axBounds.height, rangeBounds.height, 1);
    }
    testWord('The');
    testWord('Hitchhiker');
    testWord('Guide');
    testWord('interstellar');
}, "Tests that we can compute the bounds of a range of text from the accessibility tree.");
</script>

</body>
</html>