estimateDirectionOfText method
Estimates the directionality of text
using the best known
general-purpose method (using relative word counts). A
TextDirection.UNKNOWN return value indicates completely neutral input.
isHtml
is true if text
HTML or HTML-escaped.
If the number of RTL words is above a certain percentage of the total
number of strongly directional words, returns RTL.
Otherwise, if any words are strongly or weakly LTR, returns LTR.
Otherwise, returns UNKNOWN, which is used to mean neutral
.
Numbers and URLs are counted as weakly LTR.
Implementation
static TextDirection estimateDirectionOfText(String text,
{bool isHtml: false}) {
text = isHtml ? stripHtmlIfNeeded(text) : text;
var rtlCount = 0;
var total = 0;
var hasWeaklyLtr = false;
// Split a string into 'words' for directionality estimation based on
// relative word counts.
for (String token in text.split(new RegExp(r'\s+'))) {
if (startsWithRtl(token)) {
rtlCount++;
total++;
} else if (new RegExp(r'^http://').hasMatch(token)) {
// Checked if token looks like something that must always be LTR even in
// RTL text, such as a URL.
hasWeaklyLtr = true;
} else if (hasAnyLtr(token)) {
total++;
} else if (new RegExp(r'\d').hasMatch(token)) {
// Checked if token contains any numerals.
hasWeaklyLtr = true;
}
}
if (total == 0) {
return hasWeaklyLtr ? TextDirection.LTR : TextDirection.UNKNOWN;
} else if (rtlCount > _RTL_DETECTION_THRESHOLD * total) {
return TextDirection.RTL;
} else {
return TextDirection.LTR;
}
}