Debian Codegraph @

closure-library/closure/goog/format/format.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Provides utility functions for formatting strings, numbers etc.
17 *
18 */
19
20 goog.provide('goog.format');
21
22 goog.require('goog.i18n.GraphemeBreak');
23 goog.require('goog.string');
24 goog.require('goog.userAgent');
25
26
27 /**
28 * Formats a number of bytes in human readable form.
29 * 54, 450K, 1.3M, 5G etc.
30 * @param {number} bytes The number of bytes to show.
31 * @param {number=} opt_decimals The number of decimals to use. Defaults to 2.
32 * @return {string} The human readable form of the byte size.
33 */
34 goog.format.fileSize = function(bytes, opt_decimals) {
35 return goog.format.numBytesToString(bytes, opt_decimals, false);
36 };
37
38
39 /**
40 * Checks whether string value containing scaling units (K, M, G, T, P, m,
41 * u, n) can be converted to a number.
42 *
43 * Where there is a decimal, there must be a digit to the left of the
44 * decimal point.
45 *
46 * Negative numbers are valid.
47 *
48 * Examples:
49 * 0, 1, 1.0, 10.4K, 2.3M, -0.3P, 1.2m
50 *
51 * @param {string} val String value to check.
52 * @return {boolean} True if string could be converted to a numeric value.
53 */
54 goog.format.isConvertableScaledNumber = function(val) {
55 return goog.format.SCALED_NUMERIC_RE_.test(val);
56 };
57
58
59 /**
60 * Converts a string to numeric value, taking into account the units.
61 * If string ends in 'B', use binary conversion.
62 * @param {string} stringValue String to be converted to numeric value.
63 * @return {number} Numeric value for string.
64 */
65 goog.format.stringToNumericValue = function(stringValue) {
66 if (goog.string.endsWith(stringValue, 'B')) {
67 return goog.format.stringToNumericValue_(
68 stringValue, goog.format.NUMERIC_SCALES_BINARY_);
69 }
70 return goog.format.stringToNumericValue_(
71 stringValue, goog.format.NUMERIC_SCALES_SI_);
72 };
73
74
75 /**
76 * Converts a string to number of bytes, taking into account the units.
77 * Binary conversion.
78 * @param {string} stringValue String to be converted to numeric value.
79 * @return {number} Numeric value for string.
80 */
81 goog.format.stringToNumBytes = function(stringValue) {
82 return goog.format.stringToNumericValue_(
83 stringValue, goog.format.NUMERIC_SCALES_BINARY_);
84 };
85
86
87 /**
88 * Converts a numeric value to string representation. SI conversion.
89 * @param {number} val Value to be converted.
90 * @param {number=} opt_decimals The number of decimals to use. Defaults to 2.
91 * @return {string} String representation of number.
92 */
93 goog.format.numericValueToString = function(val, opt_decimals) {
94 return goog.format.numericValueToString_(
95 val, goog.format.NUMERIC_SCALES_SI_, opt_decimals);
96 };
97
98
99 /**
100 * Converts number of bytes to string representation. Binary conversion.
101 * Default is to return the additional 'B' suffix only for scales greater than
102 * 1K, e.g. '10.5KB' to minimize confusion with counts that are scaled by powers
103 * of 1000. Otherwise, suffix is empty string.
104 * @param {number} val Value to be converted.
105 * @param {number=} opt_decimals The number of decimals to use. Defaults to 2.
106 * @param {boolean=} opt_suffix If true, include trailing 'B' in returned
107 * string. Default is true.
108 * @param {boolean=} opt_useSeparator If true, number and scale will be
109 * separated by a no break space. Default is false.
110 * @return {string} String representation of number of bytes.
111 */
112 goog.format.numBytesToString = function(
113 val, opt_decimals, opt_suffix, opt_useSeparator) {
114 var suffix = '';
115 if (!goog.isDef(opt_suffix) || opt_suffix) {
116 suffix = 'B';
117 }
118 return goog.format.numericValueToString_(
119 val, goog.format.NUMERIC_SCALES_BINARY_, opt_decimals, suffix,
120 opt_useSeparator);
121 };
122
123
124 /**
125 * Converts a string to numeric value, taking into account the units.
126 * @param {string} stringValue String to be converted to numeric value.
127 * @param {Object} conversion Dictionary of conversion scales.
128 * @return {number} Numeric value for string. If it cannot be converted,
129 * returns NaN.
130 * @private
131 */
132 goog.format.stringToNumericValue_ = function(stringValue, conversion) {
133 var match = stringValue.match(goog.format.SCALED_NUMERIC_RE_);
134 if (!match) {
135 return NaN;
136 }
137 var val = Number(match[1]) * conversion[match[2]];
138 return val;
139 };
140
141
142 /**
143 * Converts a numeric value to string, using specified conversion
144 * scales.
145 * @param {number} val Value to be converted.
146 * @param {Object} conversion Dictionary of scaling factors.
147 * @param {number=} opt_decimals The number of decimals to use. Default is 2.
148 * @param {string=} opt_suffix Optional suffix to append.
149 * @param {boolean=} opt_useSeparator If true, number and scale will be
150 * separated by a space. Default is false.
151 * @return {string} The human readable form of the byte size.
152 * @private
153 */
154 goog.format.numericValueToString_ = function(
155 val, conversion, opt_decimals, opt_suffix, opt_useSeparator) {
156 var prefixes = goog.format.NUMERIC_SCALE_PREFIXES_;
157 var orig_val = val;
158 var symbol = '';
159 var separator = '';
160 var scale = 1;
161 if (val < 0) {
162 val = -val;
163 }
164 for (var i = 0; i < prefixes.length; i++) {
165 var unit = prefixes[i];
166 scale = conversion[unit];
167 if (val >= scale || (scale <= 1 && val > 0.1 * scale)) {
168 // Treat values less than 1 differently, allowing 0.5 to be "0.5" rather
169 // than "500m"
170 symbol = unit;
171 break;
172 }
173 }
174 if (!symbol) {
175 scale = 1;
176 } else {
177 if (opt_suffix) {
178 symbol += opt_suffix;
179 }
180 if (opt_useSeparator) {
181 separator = ' ';
182 }
183 }
184 var ex = Math.pow(10, goog.isDef(opt_decimals) ? opt_decimals : 2);
185 return Math.round(orig_val / scale * ex) / ex + separator + symbol;
186 };
187
188
189 /**
190 * Regular expression for detecting scaling units, such as K, M, G, etc. for
191 * converting a string representation to a numeric value.
192 *
193 * Also allow 'k' to be aliased to 'K'. These could be used for SI (powers
194 * of 1000) or Binary (powers of 1024) conversions.
195 *
196 * Also allow final 'B' to be interpreted as byte-count, implicitly triggering
197 * binary conversion (e.g., '10.2MB').
198 *
199 * @type {RegExp}
200 * @private
201 */
202 goog.format.SCALED_NUMERIC_RE_ =
203 /^([-]?\d+\.?\d*)([K,M,G,T,P,E,Z,Y,k,m,u,n]?)[B]?$/;
204
205
206 /**
207 * Ordered list of scaling prefixes in decreasing order.
208 * @private {Array<string>}
209 */
210 goog.format.NUMERIC_SCALE_PREFIXES_ =
211 ['Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'K', '', 'm', 'u', 'n'];
212
213
214 /**
215 * Scaling factors for conversion of numeric value to string. SI conversion.
216 * @type {Object}
217 * @private
218 */
219 goog.format.NUMERIC_SCALES_SI_ = {
220 '': 1,
221 'n': 1e-9,
222 'u': 1e-6,
223 'm': 1e-3,
224 'k': 1e3,
225 'K': 1e3,
226 'M': 1e6,
227 'G': 1e9,
228 'T': 1e12,
229 'P': 1e15,
230 'E': 1e18,
231 'Z': 1e21,
232 'Y': 1e24
233 };
234
235
236 /**
237 * Scaling factors for conversion of numeric value to string. Binary
238 * conversion.
239 * @type {Object}
240 * @private
241 */
242 goog.format.NUMERIC_SCALES_BINARY_ = {
243 '': 1,
244 'n': Math.pow(1024, -3),
245 'u': Math.pow(1024, -2),
246 'm': 1.0 / 1024,
247 'k': 1024,
248 'K': 1024,
249 'M': Math.pow(1024, 2),
250 'G': Math.pow(1024, 3),
251 'T': Math.pow(1024, 4),
252 'P': Math.pow(1024, 5),
253 'E': Math.pow(1024, 6),
254 'Z': Math.pow(1024, 7),
255 'Y': Math.pow(1024, 8)
256 };
257
258
259 /**
260 * First Unicode code point that has the Mark property.
261 * @type {number}
262 * @private
263 */
264 goog.format.FIRST_GRAPHEME_EXTEND_ = 0x300;
265
266
267 /**
268 * Returns true if and only if given character should be treated as a breaking
269 * space. All ASCII control characters, the main Unicode range of spacing
270 * characters (U+2000 to U+200B inclusive except for U+2007), and several other
271 * Unicode space characters are treated as breaking spaces.
272 * @param {number} charCode The character code under consideration.
273 * @return {boolean} True if the character is a breaking space.
274 * @private
275 */
276 goog.format.isTreatedAsBreakingSpace_ = function(charCode) {
277 return (charCode <= goog.format.WbrToken_.SPACE) ||
278 (charCode >= 0x1000 &&
279 ((charCode >= 0x2000 && charCode <= 0x2006) ||
280 (charCode >= 0x2008 && charCode <= 0x200B) || charCode == 0x1680 ||
281 charCode == 0x180E || charCode == 0x2028 || charCode == 0x2029 ||
282 charCode == 0x205f || charCode == 0x3000));
283 };
284
285
286 /**
287 * Returns true if and only if given character is an invisible formatting
288 * character.
289 * @param {number} charCode The character code under consideration.
290 * @return {boolean} True if the character is an invisible formatting character.
291 * @private
292 */
293 goog.format.isInvisibleFormattingCharacter_ = function(charCode) {
294 // See: http://unicode.org/charts/PDF/U2000.pdf
295 return (charCode >= 0x200C && charCode <= 0x200F) ||
296 (charCode >= 0x202A && charCode <= 0x202E);
297 };
298
299
300 /**
301 * Inserts word breaks into an HTML string at a given interval. The counter is
302 * reset if a space or a character which behaves like a space is encountered,
303 * but it isn't incremented if an invisible formatting character is encountered.
304 * WBRs aren't inserted into HTML tags or entities. Entities count towards the
305 * character count, HTML tags do not.
306 *
307 * With common strings aliased, objects allocations are constant based on the
308 * length of the string: N + 3. This guarantee does not hold if the string
309 * contains an element >= U+0300 and hasGraphemeBreak is non-trivial.
310 *
311 * @param {string} str HTML to insert word breaks into.
312 * @param {function(number, number, boolean): boolean} hasGraphemeBreak A
313 * function determining if there is a grapheme break between two characters,
314 * in the same signature as goog.i18n.GraphemeBreak.hasGraphemeBreak.
315 * @param {number=} opt_maxlen Maximum length after which to ensure
316 * there is a break. Default is 10 characters.
317 * @return {string} The string including word breaks.
318 * @private
319 */
320 goog.format.insertWordBreaksGeneric_ = function(
321 str, hasGraphemeBreak, opt_maxlen) {
322 var maxlen = opt_maxlen || 10;
323 if (maxlen > str.length) return str;
324
325 var rv = [];
326 var n = 0; // The length of the current token
327
328 // This will contain the ampersand or less-than character if one of the
329 // two has been seen; otherwise, the value is zero.
330 var nestingCharCode = 0;
331
332 // First character position from input string that has not been outputted.
333 var lastDumpPosition = 0;
334
335 var charCode = 0;
336 for (var i = 0; i < str.length; i++) {
337 // Using charCodeAt versus charAt avoids allocating new string objects.
338 var lastCharCode = charCode;
339 charCode = str.charCodeAt(i);
340
341 // Don't add a WBR before characters that might be grapheme extending.
342 var isPotentiallyGraphemeExtending =
343 charCode >= goog.format.FIRST_GRAPHEME_EXTEND_ &&
344 !hasGraphemeBreak(lastCharCode, charCode, true);
345
346 // Don't add a WBR at the end of a word. For the purposes of determining
347 // work breaks, all ASCII control characters and some commonly encountered
348 // Unicode spacing characters are treated as breaking spaces.
349 if (n >= maxlen && !goog.format.isTreatedAsBreakingSpace_(charCode) &&
350 !isPotentiallyGraphemeExtending) {
351 // Flush everything seen so far, and append a word break.
352 rv.push(str.substring(lastDumpPosition, i), goog.format.WORD_BREAK_HTML);
353 lastDumpPosition = i;
354 n = 0;
355 }
356
357 if (!nestingCharCode) {
358 // Not currently within an HTML tag or entity
359
360 if (charCode == goog.format.WbrToken_.LT ||
361 charCode == goog.format.WbrToken_.AMP) {
362 // Entering an HTML Entity '&' or open tag '<'
363 nestingCharCode = charCode;
364 } else if (goog.format.isTreatedAsBreakingSpace_(charCode)) {
365 // A space or control character -- reset the token length
366 n = 0;
367 } else if (!goog.format.isInvisibleFormattingCharacter_(charCode)) {
368 // A normal flow character - increment. For grapheme extending
369 // characters, this is not *technically* a new character. However,
370 // since the grapheme break detector might be overly conservative,
371 // we have to continue incrementing, or else we won't even be able
372 // to add breaks when we get to things like punctuation. For the
373 // case where we have a full grapheme break detector, it is okay if
374 // we occasionally break slightly early.
375 n++;
376 }
377 } else if (
378 charCode == goog.format.WbrToken_.GT &&
379 nestingCharCode == goog.format.WbrToken_.LT) {
380 // Leaving an HTML tag, treat the tag as zero-length
381 nestingCharCode = 0;
382 } else if (
383 charCode == goog.format.WbrToken_.SEMI_COLON &&
384 nestingCharCode == goog.format.WbrToken_.AMP) {
385 // Leaving an HTML entity, treat it as length one
386 nestingCharCode = 0;
387 n++;
388 }
389 }
390
391 // Take care of anything we haven't flushed so far.
392 rv.push(str.substr(lastDumpPosition));
393
394 return rv.join('');
395 };
396
397
398 /**
399 * Inserts word breaks into an HTML string at a given interval.
400 *
401 * This method is as aggressive as possible, using a full table of Unicode
402 * characters where it is legal to insert word breaks; however, this table
403 * comes at a 2.5k pre-gzip (~1k post-gzip) size cost. Consider using
404 * insertWordBreaksBasic to minimize the size impact.
405 *
406 * @param {string} str HTML to insert word breaks into.
407 * @param {number=} opt_maxlen Maximum length after which to ensure there is a
408 * break. Default is 10 characters.
409 * @return {string} The string including word breaks.
410 * @deprecated Prefer wrapping with CSS word-wrap: break-word.
411 */
412 goog.format.insertWordBreaks = function(str, opt_maxlen) {
413 return goog.format.insertWordBreaksGeneric_(
414 str, goog.i18n.GraphemeBreak.hasGraphemeBreak, opt_maxlen);
415 };
416
417
418 /**
419 * Determines conservatively if a character has a Grapheme break.
420 *
421 * Conforms to a similar signature as goog.i18n.GraphemeBreak, but is overly
422 * conservative, returning true only for characters in common scripts that
423 * are simple to account for.
424 *
425 * @param {number} lastCharCode The previous character code. Ignored.
426 * @param {number} charCode The character code under consideration. It must be
427 * at least \u0300 as a precondition -- this case is covered by
428 * insertWordBreaksGeneric_.
429 * @param {boolean=} opt_extended Ignored, to conform with the interface.
430 * @return {boolean} Whether it is one of the recognized subsets of characters
431 * with a grapheme break.
432 * @private
433 */
434 goog.format.conservativelyHasGraphemeBreak_ = function(
435 lastCharCode, charCode, opt_extended) {
436 // Return false for everything except the most common Cyrillic characters.
437 // Don't worry about Latin characters, because insertWordBreaksGeneric_
438 // itself already handles those.
439 // TODO(gboyer): Also account for Greek, Armenian, and Georgian if it is
440 // simple to do so.
441 return charCode >= 0x400 && charCode < 0x523;
442 };
443
444
445 // TODO(gboyer): Consider using a compile-time flag to switch implementations
446 // rather than relying on the developers to toggle implementations.
447 /**
448 * Inserts word breaks into an HTML string at a given interval.
449 *
450 * This method is less aggressive than insertWordBreaks, only inserting
451 * breaks next to punctuation and between Latin or Cyrillic characters.
452 * However, this is good enough for the common case of URLs. It also
453 * works for all Latin and Cyrillic languages, plus CJK has no need for word
454 * breaks. When this method is used, goog.i18n.GraphemeBreak may be dead
455 * code eliminated.
456 *
457 * @param {string} str HTML to insert word breaks into.
458 * @param {number=} opt_maxlen Maximum length after which to ensure there is a
459 * break. Default is 10 characters.
460 * @return {string} The string including word breaks.
461 * @deprecated Prefer wrapping with CSS word-wrap: break-word.
462 */
463 goog.format.insertWordBreaksBasic = function(str, opt_maxlen) {
464 return goog.format.insertWordBreaksGeneric_(
465 str, goog.format.conservativelyHasGraphemeBreak_, opt_maxlen);
466 };
467
468
469 /**
470 * True iff the current userAgent is IE8 or above.
471 * @type {boolean}
472 * @private
473 */
474 goog.format.IS_IE8_OR_ABOVE_ =
475 goog.userAgent.IE && goog.userAgent.isVersionOrHigher(8);
476
477
478 /**
479 * Constant for the WBR replacement used by insertWordBreaks. Safari requires
480 * <wbr></wbr>, Opera needs the &shy; entity, though this will give a visible
481 * hyphen at breaks. IE8 uses a zero width space.
482 * Other browsers just use <wbr>.
483 * @type {string}
484 */
485 goog.format.WORD_BREAK_HTML =
486 goog.userAgent.WEBKIT ? '<wbr></wbr>' : goog.userAgent.OPERA ?
487 '&shy;' :
488 goog.format.IS_IE8_OR_ABOVE_ ? '&#8203;' : '<wbr>';
489
490
491 /**
492 * Tokens used within insertWordBreaks.
493 * @private
494 * @enum {number}
495 */
496 goog.format.WbrToken_ = {
497 LT: 60, // '<'.charCodeAt(0)
498 GT: 62, // '>'.charCodeAt(0)
499 AMP: 38, // '&'.charCodeAt(0)
500 SEMI_COLON: 59, // ';'.charCodeAt(0)
501 SPACE: 32 // ' '.charCodeAt(0)
502 };