export function getTailoredTextOrDefault()

in src/textMeasurementService.ts [274:328]


    export function getTailoredTextOrDefault(textProperties: TextProperties, maxWidth: number): string {
        ensureDOM();

        let strLength: number = textProperties.text.length;

        if (strLength === 0) {
            return textProperties.text;
        }

        let width: number = measureSvgTextWidth(textProperties);

        if (width < maxWidth) {
            return textProperties.text;
        }

        // Create a copy of the textProperties so we don't modify the one that's passed in.
        let copiedTextProperties = Prototype.inherit(textProperties);

        // Take the properties and apply them to svgTextElement
        // Then, do the binary search to figure out the substring we want
        // Set the substring on textElement argument
        let text = copiedTextProperties.text = ellipsis + copiedTextProperties.text;

        let min = 1;
        let max = text.length;
        let i = ellipsis.length;

        while (min <= max) {
            // num | 0 prefered to Math.floor(num) for performance benefits
            i = (min + max) / 2 | 0;

            copiedTextProperties.text = text.substr(0, i);
            width = measureSvgTextWidth(copiedTextProperties);

            if (maxWidth > width) {
                min = i + 1;
            } else if (maxWidth < width) {
                max = i - 1;
            } else {
                break;
            }
        }

        // Since the search algorithm almost never finds an exact match,
        // it will pick one of the closest two, which could result in a
        // value bigger with than 'maxWidth' thus we need to go back by
        // one to guarantee a smaller width than 'maxWidth'.
        copiedTextProperties.text = text.substr(0, i);
        width = measureSvgTextWidth(copiedTextProperties);
        if (width > maxWidth) {
            i--;
        }

        return text.substr(ellipsis.length, i - ellipsis.length) + ellipsis;
    }