Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(845)

Side by Side Diff: lib/i18n/bidi_formatter.dart

Issue 10592011: Add BiDirectional Text formatting utilites to the i18n library. (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 8 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | lib/i18n/bidi_utils.dart » ('j') | lib/i18n/bidi_utils.dart » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 #library('bidi_formatter');
6
7 #import('bidi_utils.dart');
8
9 /**
10 * Bidi stands for Bi-directional text.
11 * According to http://en.wikipedia.org/wiki/Bi-directional_text:
12 * Bi-directional text is text containing text in both text directionalities,
13 * both right-to-left (RTL) and left-to-right (LTR). It generally involves text
14 * containing different types of alphabets, but may also refer to boustrophedon,
15 * which is changing text directionality in each row.
16 * Go to https://sites.google.com/a/google.com/bidi-howto/ to learn more about
Alan Knight 2012/06/22 00:16:53 This site isn't accessible outside Google. Shouldn
Alan Knight 2012/06/25 23:29:56 Do we do anything about this?
Emily Fortuna 2012/06/26 01:04:29 You should look at the new version of these files
17 * dealing with BiDi correctly.
18 *
19 * Utility class for formatting display text in a potentially
20 * opposite-directionality context without garbling layout issues.
21 * Mostly a very "slimmed-down" and dart-ified port of the Closure Birectional
22 * formatting libary. If there is a utility in the Closure library (or ICU, or
23 * elsewhere) that you would like this formatter to make available, please
24 * contact the Dart team.
25 *
26 * Provides the following functionality:
27 *
28 * 1. *BiDi Wrapping*
29 * When text in one language is mixed into a document in another, opposite-
30 * directionality language, e.g. when an English business name is embedded in a
31 * Hebrew web page, both the inserted string and the text following it may be
32 * displayed incorrectly unless the inserted string is explicitly separated
33 * from the surrounding text in a "wrapper" that declares its directionality at
34 * the start and then resets it back at the end. This wrapping can be done in
35 * HTML mark-up (e.g. a 'span dir=rtl' tag) or - only in contexts where mark-up
36 * can not be used - in Unicode BiDi formatting codes (LRE|RLE and PDF).
37 * Providing such wrapping services is the basic purpose of the BiDi formatter.
38 *
39 * 2. *Directionality estimation*
40 * How does one know whether a string about to be inserted into surrounding
41 * text has the same directionality? Well, in many cases, one knows that this
42 * must be the case when writing the code doing the insertion, e.g. when a
43 * localized message is inserted into a localized page. In such cases there is
44 * no need to involve the BiDi formatter at all. In the remaining cases, e.g.
45 * when the string is user-entered or comes from a database, the language of
46 * the string (and thus its directionality) is not known a priori, and must be
47 * estimated at run-time. The BiDi formatter does this automatically.
48 *
49 * 3. *Escaping*
50 * When wrapping plain text - i.e. text that is not already HTML or HTML-
51 * escaped - in HTML mark-up, the text must first be HTML-escaped to prevent XSS
52 * attacks and other nasty business. This of course is always true, but the
53 * escaping cannot be done after the string has already been wrapped in
54 * mark-up, so the BiDi formatter also serves as a last chance and includes
55 * escaping services.
56 *
57 * Thus, in a single call, the formatter will escape the input string as
58 * specified, determine its directionality, and wrap it as necessary. It is
59 * then up to the caller to insert the return value in the output.
60 */
61
62 #import('dart:web');
63
64 class BidiFormatter {
65
66 /** The direction of the surrounding text (the context). */
67 TextDirection contextDirection;
68
69 /**
70 * Indicates if we should always wrap the formatted text in a <span<,.
71 */
72 bool _alwaysSpan;
73
74 /**
75 * Create a formatting object with a direction. If [alwaysSpan] is true we
76 * should always use a `span' tag, even when the input directionality is
77 * neutral or matches the context, so that the DOM structure of the output
78 * does not depend on the combination of directionalities.
79 */
80 BidiFormatter.LTR([alwaysSpan=false]) : contextDirection = TextDirection.LTR,
81 _alwaysSpan = alwaysSpan;
82 BidiFormatter.RTL([alwaysSpan=false]) : contextDirection = TextDirection.RTL,
83 _alwaysSpan = alwaysSpan;
84 BidiFormatter.UNKNOWN([alwaysSpan=false]) :
85 contextDirection = TextDirection.UNKNOWN, _alwaysSpan = alwaysSpan;
86
87 /** Is true if the context direction for this formatter is RTL. */
88 bool get isRTL() => contextDirection == TextDirection.RTL;
89
90 /**
91 * Formats a string of a given (or estimated, if not provided)
92 * [direction] for use in HTML output of the context directionality, so
93 * an opposite-directionality string is neither garbled nor garbles what
94 * follows it.
95 * If the input string's directionality doesn't match the context
96 * directionality, we wrap it with a `span' tag and adds a `dir' attribute
Alan Knight 2012/06/22 00:16:53 Grammar nitpicking on comments, but "we" and "adds
Emily Fortuna 2012/06/25 20:25:35 The backticks are for marking code sections in mar
Alan Knight 2012/06/25 23:29:56 Ah, ok.
97 * (either "dir=rtl" or "dir=ltr").
98 * If alwaysSpan was true when constructing the formatter, the input is always
99 * wrapped with `span' tag, skipping the dir attribute when it's not needed.
100 *
101 * If [resetDir] is true and the overall directionality or the exit
102 * directionality of [text] is opposite to the context directionality,
103 * a trailing unicode BiDi mark matching the context directionality is
104 * appended (LRM or RLM). If [isHtml] is false, we HTML-escape the [text].
Alan Knight 2012/06/22 00:16:53 The comment says that the unicode bidi characters
Emily Fortuna 2012/06/25 20:25:35 This is what the closure and python libraries do.
Alan Knight 2012/06/25 23:29:56 OK.
105 */
106 String spanWrap(String text, [bool isHtml=false, bool resetDir=true,
107 TextDirection direction]) {
108 if (direction == null) direction = estimateDirection(text, isHtml);
109 var result = '';
Alan Knight 2012/06/22 00:16:53 Is there a point initializing this to a value that
Emily Fortuna 2012/06/25 20:25:35 Result has to be in scope to return it at line 121
Alan Knight 2012/06/25 23:29:56 Yes, it needs to be declared there, but there seem
Emily Fortuna 2012/06/26 01:04:29 Done.
110 if (!isHtml) text = htmlEscape(text);
111 var directionChange = _requiresDirectionChange(direction);
112 if (_alwaysSpan || directionChange) {
113 var spanDirection = '';
114 if (directionChange) {
115 spanDirection = ' dir=${direction.spanText}';
116 }
117 result= '<span$spanDirection>$text</span>';
118 } else {
119 result = text;
120 }
121 return result.concat(_resetDirIfNeeded(text, direction, isHtml, resetDir));
122 }
123
124 /**
125 * Format [text] of a known (if specified) or estimated [direction] for use
126 * in *plain-text* output of the context directionality, so an
127 * opposite-directionality text is neither garbled nor garbles what follows
128 * it. Unlike spanWrap, this makes use of unicode BiDi formatting characters
129 * instead of spans for wrapping. The returned string would be
130 * RLE+text+PDF for RTL text, or LRE+text+PDF for LTR text.
131 *
132 * If [resetDir] is true, and if the overall directionality or the exit
133 * directionality of text are opposite to the context directionality,
134 * a trailing unicode BiDi mark matching the context directionality is
135 * appended (LRM or RLM).
136 *
137 * In HTML, the *only* valid use of this function is inside of elements that
138 * do not allow markup, e.g. an 'option' tag.
139 * This function does *not* do HTML-escaping regardless of the value of
140 * [isHtml].
Alan Knight 2012/06/22 00:16:53 What's the point of having a parameter that's igno
Emily Fortuna 2012/06/25 20:25:35 isHtml is needed in the call to estimateDirection,
Alan Knight 2012/06/25 23:29:56 But it sounds like this is only applicable to plai
Emily Fortuna 2012/06/26 01:04:29 There's the (admittedly) obscure case the comments
141 */
142 String unicodeWrap(String text, [bool isHtml=false, bool resetDir=true,
143 TextDirection direction]) {
Alan Knight 2012/06/22 00:16:53 I found the name unicodeWrap initially confusing.
Emily Fortuna 2012/06/25 20:25:35 These names were taken directly from closure. I've
Alan Knight 2012/06/25 23:29:56 OK.
144 if (direction == null) direction = estimateDirection(text, isHtml);
145 var result = text;
146 if (_requiresDirectionChange(direction)) {
147 result = '''${direction == TextDirection.RTL ?
148 BidiUtils.RLE :
149 BidiUtils.LRE}$text${BidiUtils.PDF}''';
150 }
151 return result.concat(_resetDirIfNeeded(text, direction, isHtml, resetDir));
Alan Knight 2012/06/22 00:16:53 If we're always ending with PDF, wouldn't do that
Emily Fortuna 2012/06/25 20:25:35 It's needed to mark the end of the text that is be
Alan Knight 2012/06/25 23:29:56 OK, I think I understand that. It's ending the tex
152 }
153
154 /**
155 * Returns a Unicode BiDi mark matching the context directionality
156 * (LRM or RLM) if either the directionality or the exit directionality of
157 * [text] is opposite to the context directionality. Otherwise returns
158 * the empty string. [isHtml] is true if the text is HTML or HTML-escaped.
159 */
160 String markAfter(String text, [bool isHtml=false]) {
161 text = BidiUtils.stripHtmlIfNeeded(text, isHtml);
162 return _resetDirIfNeeded(text, estimateDirection(text), false, true);
163 }
164
165 /**
166 * Returns the Unicode BiDi mark matching the context directionality.
167 */
Alan Knight 2012/06/22 00:16:53 Maybe it's just my ignorance of the usage of these
Emily Fortuna 2012/06/25 20:25:35 This one, like the others, I took from the library
Alan Knight 2012/06/25 23:29:56 Yeah, I worry about us just reproducing a bunch of
Emily Fortuna 2012/06/26 01:04:29 *Please* look at the updated version of the file I
168 String mark() {
169 if (contextDirection == TextDirection.LTR) {
170 return BidiUtils.LRM;
171 } else if (contextDirection == TextDirection.RTL) {
172 return BidiUtils.RLM;
173 } else {
174 return '';
175 }
176 }
177
178 /**
179 * Estimates the directionality of [text] using the best known
180 * general-purpose method (using relative word counts). A
181 * TextDirection.UNKNOWN return value indicates completely neutral input.
182 * [isHtml] is true if [text] HTML or HTML-escaped.
183 */
184 TextDirection estimateDirection(String text, [bool isHtml=false]) {
185 return BidiUtils.estimateDirection(text, isHtml);
186 }
187
188 /**
189 * Returns a unicode BiDi mark matching the context [direction].
Alan Knight 2012/06/22 00:16:53 When you say "the context" that makes me think you
Emily Fortuna 2012/06/25 20:25:35 rephrased.
190 * If [resetDir] is true, and if the overall directionality or the exit
191 * directionality of [text] is opposite the context directionality, it will
192 * return LRM or RLM according to the directionality. Otherwise return the
193 * empty string. [isHtml] is true if [text] is HTML or HTML-escaped.
Alan Knight 2012/06/22 00:16:53 I find the name resetDirIfNeeded much clearer than
Emily Fortuna 2012/06/25 20:25:35 Good thing I changed the name differently from the
194 */
195 String _resetDirIfNeeded(final String text, TextDirection direction,
Alan Knight 2012/06/22 00:16:53 Why is the text final here, but nowhere else? What
Emily Fortuna 2012/06/25 20:25:35 That was for an optimization that is no longer nee
196 bool isHtml, bool resetDir) {
197 // endsWithRtl and endsWithLtr are called only if needed (short-circuit).
198 if (resetDir &&
Alan Knight 2012/06/22 00:16:53 We've defined the class TextDirection. Couldn't we
Emily Fortuna 2012/06/25 20:25:35 This function requires knowledge of the last stron
Alan Knight 2012/06/25 23:29:56 So we can go from an 8 clause if statement to 3 (a
Emily Fortuna 2012/06/26 01:04:29 You can't get rewrite this and preserve the "short
199 ((contextDirection == TextDirection.LTR &&
200 (direction == TextDirection.RTL ||
201 BidiUtils.endsWithRtl(text, isHtml))) ||
202 (contextDirection == TextDirection.RTL &&
203 (direction == TextDirection.LTR ||
204 BidiUtils.endsWithLtr(text, isHtml))))) {
205 if (contextDirection == TextDirection.LTR) {
206 return BidiUtils.LRM;
207 } else {
208 return BidiUtils.RLM;
209 }
210 } else {
211 return '';
212 }
213 }
214
215 /**
216 * Returns true if the new text [direction] requires a direction change, given
217 * the surrounding contextDirection.
218 */
219 bool _requiresDirectionChange(TextDirection direction) {
Alan Knight 2012/06/22 00:16:53 This seems like it could be a method on TextDirect
Emily Fortuna 2012/06/25 20:25:35 Done.
220 return direction != TextDirection.UNKNOWN && direction != contextDirection;
221 }
222 }
OLDNEW
« no previous file with comments | « no previous file | lib/i18n/bidi_utils.dart » ('j') | lib/i18n/bidi_utils.dart » ('J')

Powered by Google App Engine
This is Rietveld 408576698