forked from mbostock/protovis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protovis.js
15326 lines (14298 loc) · 498 KB
/
protovis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @class The built-in Array class.
* @name Array
*/
/**
* Creates a new array with the results of calling a provided function on every
* element in this array. Implemented in Javascript 1.6.
*
* @function
* @name Array.prototype.map
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map">map</a>
* documentation.
* @param {function} f function that produces an element of the new Array from
* an element of the current one.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
if (!Array.prototype.map) Array.prototype.map = function(f, o) {
var n = this.length;
var result = new Array(n);
for (var i = 0; i < n; i++) {
if (i in this) {
result[i] = f.call(o, this[i], i, this);
}
}
return result;
};
/**
* Creates a new array with all elements that pass the test implemented by the
* provided function. Implemented in Javascript 1.6.
*
* @function
* @name Array.prototype.filter
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter">filter</a>
* documentation.
* @param {function} f function to test each element of the array.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
if (!Array.prototype.filter) Array.prototype.filter = function(f, o) {
var n = this.length;
var result = new Array();
for (var i = 0; i < n; i++) {
if (i in this) {
var v = this[i];
if (f.call(o, v, i, this)) result.push(v);
}
}
return result;
};
/**
* Executes a provided function once per array element. Implemented in
* Javascript 1.6.
*
* @function
* @name Array.prototype.forEach
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/ForEach">forEach</a>
* documentation.
* @param {function} f function to execute for each element.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
if (!Array.prototype.forEach) Array.prototype.forEach = function(f, o) {
var n = this.length >>> 0;
for (var i = 0; i < n; i++) {
if (i in this) f.call(o, this[i], i, this);
}
};
/**
* Apply a function against an accumulator and each value of the array (from
* left-to-right) as to reduce it to a single value. Implemented in Javascript
* 1.8.
*
* @function
* @name Array.prototype.reduce
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Reduce">reduce</a>
* documentation.
* @param {function} f function to execute on each value in the array.
* @param [v] object to use as the first argument to the first call of
* <tt>t</tt>.
*/
if (!Array.prototype.reduce) Array.prototype.reduce = function(f, v) {
var len = this.length;
if (!len && (arguments.length == 1)) {
throw new Error("reduce: empty array, no initial value");
}
var i = 0;
if (arguments.length < 2) {
while (true) {
if (i in this) {
v = this[i++];
break;
}
if (++i >= len) {
throw new Error("reduce: no values, no initial value");
}
}
}
for (; i < len; i++) {
if (i in this) {
v = f(v, this[i], i, this);
}
}
return v;
};
/**
* The top-level Protovis namespace. All public methods and fields should be
* registered on this object. Note that core Protovis source is surrounded by an
* anonymous function, so any other declared globals will not be visible outside
* of core methods. This also allows multiple versions of Protovis to coexist,
* since each version will see their own <tt>pv</tt> namespace.
*
* @namespace The top-level Protovis namespace, <tt>pv</tt>.
*/
var pv = {};
/**
* Protovis version number. See <a href="http://semver.org">semver.org</a>.
*
* @type string
* @constant
*/
pv.version = "3.3.1";
/**
* Returns the passed-in argument, <tt>x</tt>; the identity function. This method
* is provided for convenience since it is used as the default behavior for a
* number of property functions.
*
* @param x a value.
* @returns the value <tt>x</tt>.
*/
pv.identity = function(x) { return x; };
/**
* Returns <tt>this.index</tt>. This method is provided for convenience for use
* with scales. For example, to color bars by their index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.index))</pre>
*
* This method is equivalent to <tt>function() this.index</tt>, but more
* succinct. Note that the <tt>index</tt> property is also supported for
* accessor functions with {@link pv.max}, {@link pv.min} and other array
* utility methods.
*
* @see pv.Scale
* @see pv.Mark#index
*/
pv.index = function() { return this.index; };
/**
* Returns <tt>this.childIndex</tt>. This method is provided for convenience for
* use with scales. For example, to color bars by their child index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.child))</pre>
*
* This method is equivalent to <tt>function() this.childIndex</tt>, but more
* succinct.
*
* @see pv.Scale
* @see pv.Mark#childIndex
*/
pv.child = function() { return this.childIndex; };
/**
* Returns <tt>this.parent.index</tt>. This method is provided for convenience
* for use with scales. This method is provided for convenience for use with
* scales. For example, to color bars by their parent index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.parent))</pre>
*
* Tthis method is equivalent to <tt>function() this.parent.index</tt>, but more
* succinct.
*
* @see pv.Scale
* @see pv.Mark#index
*/
pv.parent = function() { return this.parent.index; };
/**
* Stores the current event. This field is only set within event handlers.
*
* @type Event
* @name pv.event
*/
/**
* @private Returns a prototype object suitable for extending the given class
* <tt>f</tt>. Rather than constructing a new instance of <tt>f</tt> to serve as
* the prototype (which unnecessarily runs the constructor on the created
* prototype object, potentially polluting it), an anonymous function is
* generated internally that shares the same prototype:
*
* <pre>function g() {}
* g.prototype = f.prototype;
* return new g();</pre>
*
* For more details, see Douglas Crockford's essay on prototypal inheritance.
*
* @param {function} f a constructor.
* @returns a suitable prototype object.
* @see Douglas Crockford's essay on <a
* href="http://javascript.crockford.com/prototypal.html">prototypal
* inheritance</a>.
*/
pv.extend = function(f) {
function g() {}
g.prototype = f.prototype || f;
return new g();
};
try {
eval("pv.parse = function(x) x;"); // native support
} catch (e) {
/**
* @private Parses a Protovis specification, which may use JavaScript 1.8
* function expresses, replacing those function expressions with proper
* functions such that the code can be run by a JavaScript 1.6 interpreter. This
* hack only supports function expressions (using clumsy regular expressions, no
* less), and not other JavaScript 1.8 features such as let expressions.
*
* @param {string} s a Protovis specification (i.e., a string of JavaScript 1.8
* source code).
* @returns {string} a conformant JavaScript 1.6 source code.
*/
pv.parse = function(js) { // hacky regex support
var re = new RegExp("function\\s*(\\b\\w+)?\\s*\\([^)]*\\)\\s*", "mg"), m, d, i = 0, s = "";
while (m = re.exec(js)) {
var j = m.index + m[0].length;
if (js.charAt(j) != '{') {
s += js.substring(i, j) + "{return ";
i = j;
for (var p = 0; p >= 0 && j < js.length; j++) {
var c = js.charAt(j);
switch (c) {
case '"': case '\'': {
while (++j < js.length && (d = js.charAt(j)) != c) {
if (d == '\\') j++;
}
break;
}
case '[': case '(': p++; break;
case ']': case ')': p--; break;
case ';':
case ',': if (p == 0) p--; break;
}
}
s += pv.parse(js.substring(i, --j)) + ";}";
i = j;
}
re.lastIndex = j;
}
s += js.substring(i);
return s;
};
}
/**
* @private Computes the value of the specified CSS property <tt>p</tt> on the
* specified element <tt>e</tt>.
*
* @param {string} p the name of the CSS property.
* @param e the element on which to compute the CSS property.
*/
pv.css = function(e, p) {
return window.getComputedStyle
? window.getComputedStyle(e, null).getPropertyValue(p)
: e.currentStyle[p];
};
/**
* @private Reports the specified error to the JavaScript console. Mozilla only
* allows logging to the console for privileged code; if the console is
* unavailable, the alert dialog box is used instead.
*
* @param e the exception that triggered the error.
*/
pv.error = function(e) {
(typeof console == "undefined") ? alert(e) : console.error(e);
};
/**
* @private Registers the specified listener for events of the specified type on
* the specified target. For standards-compliant browsers, this method uses
* <tt>addEventListener</tt>; for Internet Explorer, <tt>attachEvent</tt>.
*
* @param target a DOM element.
* @param {string} type the type of event, such as "click".
* @param {function} the event handler callback.
*/
pv.listen = function(target, type, listener) {
listener = pv.listener(listener);
return target.addEventListener
? target.addEventListener(type, listener, false)
: target.attachEvent("on" + type, listener);
};
/**
* @private Returns a wrapper for the specified listener function such that the
* {@link pv.event} is set for the duration of the listener's invocation. The
* wrapper is cached on the returned function, such that duplicate registrations
* of the wrapped event handler are ignored.
*
* @param {function} f an event handler.
* @returns {function} the wrapped event handler.
*/
pv.listener = function(f) {
return f.$listener || (f.$listener = function(e) {
try {
pv.event = e;
return f.call(this, e);
} finally {
delete pv.event;
}
});
};
/**
* @private Returns true iff <i>a</i> is an ancestor of <i>e</i>. This is useful
* for ignoring mouseout and mouseover events that are contained within the
* target element.
*/
pv.ancestor = function(a, e) {
while (e) {
if (e == a) return true;
e = e.parentNode;
}
return false;
};
/** @private Returns a locally-unique positive id. */
pv.id = function() {
var id = 1; return function() { return id++; };
}();
/** @private Returns a function wrapping the specified constant. */
pv.functor = function(v) {
return typeof v == "function" ? v : function() { return v; };
};
/*
* Parses the Protovis specifications on load, allowing the use of JavaScript
* 1.8 function expressions on browsers that only support JavaScript 1.6.
*
* @see pv.parse
*/
pv.listen(window, "load", function() {
/*
* Note: in Firefox any variables declared here are visible to the eval'd
* script below. Even worse, any global variables declared by the script
* could overwrite local variables here (such as the index, `i`)! To protect
* against this, all variables are explicitly scoped on a pv.$ object.
*/
pv.$ = {i:0, x:document.getElementsByTagName("script")};
for (; pv.$.i < pv.$.x.length; pv.$.i++) {
pv.$.s = pv.$.x[pv.$.i];
if (pv.$.s.type == "text/javascript+protovis") {
try {
window.eval(pv.parse(pv.$.s.text));
} catch (e) {
pv.error(e);
}
}
}
delete pv.$;
});
/**
* Abstract; see an implementing class.
*
* @class Represents an abstract text formatter and parser. A <i>format</i> is a
* function that converts an object of a given type, such as a <tt>Date</tt>, to
* a human-readable string representation. The format may also have a
* {@link #parse} method for converting a string representation back to the
* given object type.
*
* <p>Because formats are themselves functions, they can be used directly as
* mark properties. For example, if the data associated with a label are dates,
* a date format can be used as label text:
*
* <pre> .text(pv.Format.date("%m/%d/%y"))</pre>
*
* And as with scales, if the format is used in multiple places, it can be
* convenient to declare it as a global variable and then reference it from the
* appropriate property functions. For example, if the data has a <tt>date</tt>
* attribute, and <tt>format</tt> references a given date format:
*
* <pre> .text(function(d) format(d.date))</pre>
*
* Similarly, to parse a string into a date:
*
* <pre>var date = format.parse("4/30/2010");</pre>
*
* Not all format implementations support parsing. See the implementing class
* for details.
*
* @see pv.Format.date
* @see pv.Format.number
* @see pv.Format.time
*/
pv.Format = {};
/**
* Formats the specified object, returning the string representation.
*
* @function
* @name pv.Format.prototype.format
* @param {object} x the object to format.
* @returns {string} the formatted string.
*/
/**
* Parses the specified string, returning the object representation.
*
* @function
* @name pv.Format.prototype.parse
* @param {string} x the string to parse.
* @returns {object} the parsed object.
*/
/**
* @private Given a string that may be used as part of a regular expression,
* this methods returns an appropriately quoted version of the specified string,
* with any special characters escaped.
*
* @param {string} s a string to quote.
* @returns {string} the quoted string.
*/
pv.Format.re = function(s) {
return s.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g, "\\$&");
};
/**
* @private Optionally pads the specified string <i>s</i> so that it is at least
* <i>n</i> characters long, using the padding character <i>c</i>.
*
* @param {string} c the padding character.
* @param {number} n the minimum string length.
* @param {string} s the string to pad.
* @returns {string} the padded string.
*/
pv.Format.pad = function(c, n, s) {
var m = n - String(s).length;
return (m < 1) ? s : new Array(m + 1).join(c) + s;
};
/**
* Constructs a new date format with the specified string pattern.
*
* @class The format string is in the same format expected by the
* <tt>strftime</tt> function in C. The following conversion specifications are
* supported:<ul>
*
* <li>%a - abbreviated weekday name.</li>
* <li>%A - full weekday name.</li>
* <li>%b - abbreviated month names.</li>
* <li>%B - full month names.</li>
* <li>%c - locale's appropriate date and time.</li>
* <li>%C - century number.</li>
* <li>%d - day of month [01,31] (zero padded).</li>
* <li>%D - same as %m/%d/%y.</li>
* <li>%e - day of month [ 1,31] (space padded).</li>
* <li>%h - same as %b.</li>
* <li>%H - hour (24-hour clock) [00,23] (zero padded).</li>
* <li>%I - hour (12-hour clock) [01,12] (zero padded).</li>
* <li>%m - month number [01,12] (zero padded).</li>
* <li>%M - minute [0,59] (zero padded).</li>
* <li>%n - newline character.</li>
* <li>%p - locale's equivalent of a.m. or p.m.</li>
* <li>%r - same as %I:%M:%S %p.</li>
* <li>%R - same as %H:%M.</li>
* <li>%S - second [00,61] (zero padded).</li>
* <li>%t - tab character.</li>
* <li>%T - same as %H:%M:%S.</li>
* <li>%x - same as %m/%d/%y.</li>
* <li>%X - same as %I:%M:%S %p.</li>
* <li>%y - year with century [00,99] (zero padded).</li>
* <li>%Y - year including century.</li>
* <li>%% - %.</li>
*
* </ul>The following conversion specifications are currently <i>unsupported</i>
* for formatting:<ul>
*
* <li>%j - day number [1,366].</li>
* <li>%u - weekday number [1,7].</li>
* <li>%U - week number [00,53].</li>
* <li>%V - week number [01,53].</li>
* <li>%w - weekday number [0,6].</li>
* <li>%W - week number [00,53].</li>
* <li>%Z - timezone name or abbreviation.</li>
*
* </ul>In addition, the following conversion specifications are currently
* <i>unsupported</i> for parsing:<ul>
*
* <li>%a - day of week, either abbreviated or full name.</li>
* <li>%A - same as %a.</li>
* <li>%c - locale's appropriate date and time.</li>
* <li>%C - century number.</li>
* <li>%D - same as %m/%d/%y.</li>
* <li>%I - hour (12-hour clock) [1,12].</li>
* <li>%n - any white space.</li>
* <li>%p - locale's equivalent of a.m. or p.m.</li>
* <li>%r - same as %I:%M:%S %p.</li>
* <li>%R - same as %H:%M.</li>
* <li>%t - same as %n.</li>
* <li>%T - same as %H:%M:%S.</li>
* <li>%x - locale's equivalent to %m/%d/%y.</li>
* <li>%X - locale's equivalent to %I:%M:%S %p.</li>
*
* </ul>
*
* @see <a
* href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">strftime</a>
* documentation.
* @see <a
* href="http://www.opengroup.org/onlinepubs/007908799/xsh/strptime.html">strptime</a>
* documentation.
* @extends pv.Format
* @param {string} pattern the format pattern.
*/
pv.Format.date = function(pattern) {
var pad = pv.Format.pad;
/** @private */
function format(d) {
return pattern.replace(/%[a-zA-Z0-9]/g, function(s) {
switch (s) {
case '%a': return [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
][d.getDay()];
case '%A': return [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"
][d.getDay()];
case '%h':
case '%b': return [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"
][d.getMonth()];
case '%B': return [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
][d.getMonth()];
case '%c': return d.toLocaleString();
case '%C': return pad("0", 2, Math.floor(d.getFullYear() / 100) % 100);
case '%d': return pad("0", 2, d.getDate());
case '%x':
case '%D': return pad("0", 2, d.getMonth() + 1)
+ "/" + pad("0", 2, d.getDate())
+ "/" + pad("0", 2, d.getFullYear() % 100);
case '%e': return pad(" ", 2, d.getDate());
case '%H': return pad("0", 2, d.getHours());
case '%I': {
var h = d.getHours() % 12;
return h ? pad("0", 2, h) : 12;
}
// TODO %j: day of year as a decimal number [001,366]
case '%m': return pad("0", 2, d.getMonth() + 1);
case '%M': return pad("0", 2, d.getMinutes());
case '%n': return "\n";
case '%p': return d.getHours() < 12 ? "AM" : "PM";
case '%T':
case '%X':
case '%r': {
var h = d.getHours() % 12;
return (h ? pad("0", 2, h) : 12)
+ ":" + pad("0", 2, d.getMinutes())
+ ":" + pad("0", 2, d.getSeconds())
+ " " + (d.getHours() < 12 ? "AM" : "PM");
}
case '%R': return pad("0", 2, d.getHours()) + ":" + pad("0", 2, d.getMinutes());
case '%S': return pad("0", 2, d.getSeconds());
case '%Q': return pad("0", 3, d.getMilliseconds());
case '%t': return "\t";
case '%u': {
var w = d.getDay();
return w ? w : 1;
}
// TODO %U: week number (sunday first day) [00,53]
// TODO %V: week number (monday first day) [01,53] ... with weirdness
case '%w': return d.getDay();
// TODO %W: week number (monday first day) [00,53] ... with weirdness
case '%y': return pad("0", 2, d.getFullYear() % 100);
case '%Y': return d.getFullYear();
// TODO %Z: timezone name or abbreviation
case '%%': return "%";
}
return s;
});
}
/**
* Converts a date to a string using the associated formatting pattern.
*
* @function
* @name pv.Format.date.prototype.format
* @param {Date} date a date to format.
* @returns {string} the formatted date as a string.
*/
format.format = format;
/**
* Parses a date from a string using the associated formatting pattern.
*
* @function
* @name pv.Format.date.prototype.parse
* @param {string} s the string to parse as a date.
* @returns {Date} the parsed date.
*/
format.parse = function(s) {
var year = 1970, month = 0, date = 1, hour = 0, minute = 0, second = 0;
var fields = [function() {}];
/* Register callbacks for each field in the format pattern. */
var re = pv.Format.re(pattern).replace(/%[a-zA-Z0-9]/g, function(s) {
switch (s) {
// TODO %a: day of week, either abbreviated or full name
// TODO %A: same as %a
case '%b': {
fields.push(function(x) { month = {
Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7,
Sep: 8, Oct: 9, Nov: 10, Dec: 11
}[x]; });
return "([A-Za-z]+)";
}
case '%h':
case '%B': {
fields.push(function(x) { month = {
January: 0, February: 1, March: 2, April: 3, May: 4, June: 5,
July: 6, August: 7, September: 8, October: 9, November: 10,
December: 11
}[x]; });
return "([A-Za-z]+)";
}
// TODO %c: locale's appropriate date and time
// TODO %C: century number[0,99]
case '%e':
case '%d': {
fields.push(function(x) { date = x; });
return "([0-9]+)";
}
// TODO %D: same as %m/%d/%y
case '%I':
case '%H': {
fields.push(function(x) { hour = x; });
return "([0-9]+)";
}
// TODO %j: day number [1,366]
case '%m': {
fields.push(function(x) { month = x - 1; });
return "([0-9]+)";
}
case '%M': {
fields.push(function(x) { minute = x; });
return "([0-9]+)";
}
// TODO %n: any white space
// TODO %p: locale's equivalent of a.m. or p.m.
case '%p': { // TODO this is a hack
fields.push(function(x) {
if (hour == 12) {
if (x == "am") hour = 0;
} else if (x == "pm") {
hour = Number(hour) + 12;
}
});
return "(am|pm)";
}
// TODO %r: %I:%M:%S %p
// TODO %R: %H:%M
case '%S': {
fields.push(function(x) { second = x; });
return "([0-9]+)";
}
// TODO %t: any white space
// TODO %T: %H:%M:%S
// TODO %U: week number [00,53]
// TODO %w: weekday [0,6]
// TODO %W: week number [00, 53]
// TODO %x: locale date (%m/%d/%y)
// TODO %X: locale time (%I:%M:%S %p)
case '%y': {
fields.push(function(x) {
x = Number(x);
year = x + (((0 <= x) && (x < 69)) ? 2000
: (((x >= 69) && (x < 100) ? 1900 : 0)));
});
return "([0-9]+)";
}
case '%Y': {
fields.push(function(x) { year = x; });
return "([0-9]+)";
}
case '%%': {
fields.push(function() {});
return "%";
}
}
return s;
});
var match = s.match(re);
if (match) match.forEach(function(m, i) { fields[i](m); });
return new Date(year, month, date, hour, minute, second);
};
return format;
};
/**
* Returns a time format of the given type, either "short" or "long".
*
* @class Represents a time format, converting between a <tt>number</tt>
* representing a duration in milliseconds, and a <tt>string</tt>. Two types of
* time formats are supported: "short" and "long". The <i>short</i> format type
* returns a string such as "3.3 days" or "12.1 minutes", while the <i>long</i>
* format returns "13:04:12" or similar.
*
* @extends pv.Format
* @param {string} type the type; "short" or "long".
*/
pv.Format.time = function(type) {
var pad = pv.Format.pad;
/*
* MILLISECONDS = 1
* SECONDS = 1e3
* MINUTES = 6e4
* HOURS = 36e5
* DAYS = 864e5
* WEEKS = 6048e5
* MONTHS = 2592e6
* YEARS = 31536e6
*/
/** @private */
function format(t) {
t = Number(t); // force conversion from Date
switch (type) {
case "short": {
if (t >= 31536e6) {
return (t / 31536e6).toFixed(1) + " years";
} else if (t >= 6048e5) {
return (t / 6048e5).toFixed(1) + " weeks";
} else if (t >= 864e5) {
return (t / 864e5).toFixed(1) + " days";
} else if (t >= 36e5) {
return (t / 36e5).toFixed(1) + " hours";
} else if (t >= 6e4) {
return (t / 6e4).toFixed(1) + " minutes";
}
return (t / 1e3).toFixed(1) + " seconds";
}
case "long": {
var a = [],
s = ((t % 6e4) / 1e3) >> 0,
m = ((t % 36e5) / 6e4) >> 0;
a.push(pad("0", 2, s));
if (t >= 36e5) {
var h = ((t % 864e5) / 36e5) >> 0;
a.push(pad("0", 2, m));
if (t >= 864e5) {
a.push(pad("0", 2, h));
a.push(Math.floor(t / 864e5).toFixed());
} else {
a.push(h.toFixed());
}
} else {
a.push(m.toFixed());
}
return a.reverse().join(":");
}
}
}
/**
* Formats the specified time, returning the string representation.
*
* @function
* @name pv.Format.time.prototype.format
* @param {number} t the duration in milliseconds. May also be a <tt>Date</tt>.
* @returns {string} the formatted string.
*/
format.format = format;
/**
* Parses the specified string, returning the time in milliseconds.
*
* @function
* @name pv.Format.time.prototype.parse
* @param {string} s a formatted string.
* @returns {number} the parsed duration in milliseconds.
*/
format.parse = function(s) {
switch (type) {
case "short": {
var re = /([0-9,.]+)\s*([a-z]+)/g, a, t = 0;
while (a = re.exec(s)) {
var f = parseFloat(a[0].replace(",", "")), u = 0;
switch (a[2].toLowerCase()) {
case "year": case "years": u = 31536e6; break;
case "week": case "weeks": u = 6048e5; break;
case "day": case "days": u = 864e5; break;
case "hour": case "hours": u = 36e5; break;
case "minute": case "minutes": u = 6e4; break;
case "second": case "seconds": u = 1e3; break;
}
t += f * u;
}
return t;
}
case "long": {
var a = s.replace(",", "").split(":").reverse(), t = 0;
if (a.length) t += parseFloat(a[0]) * 1e3;
if (a.length > 1) t += parseFloat(a[1]) * 6e4;
if (a.length > 2) t += parseFloat(a[2]) * 36e5;
if (a.length > 3) t += parseFloat(a[3]) * 864e5;
return t;
}
}
}
return format;
};
/**
* Returns a default number format.
*
* @class Represents a number format, converting between a <tt>number</tt> and a
* <tt>string</tt>. This class allows numbers to be formatted with variable
* precision (both for the integral and fractional part of the number), optional
* thousands grouping, and optional padding. The thousands (",") and decimal
* (".") separator can be customized.
*
* @returns {pv.Format.number} a number format.
*/
pv.Format.number = function() {
var mini = 0, // default minimum integer digits
maxi = Infinity, // default maximum integer digits
mins = 0, // mini, including group separators
minf = 0, // default minimum fraction digits
maxf = 0, // default maximum fraction digits
maxk = 1, // 10^maxf
padi = "0", // default integer pad
padf = "0", // default fraction pad
padg = true, // whether group separator affects integer padding
decimal = ".", // default decimal separator
group = ",", // default group separator
np = "\u2212", // default negative prefix
ns = ""; // default negative suffix
/** @private */
function format(x) {
/* Round the fractional part, and split on decimal separator. */
if (Infinity > maxf) x = Math.round(x * maxk) / maxk;
var s = String(Math.abs(x)).split(".");
/* Pad, truncate and group the integral part. */
var i = s[0];
if (i.length > maxi) i = i.substring(i.length - maxi);
if (padg && (i.length < mini)) i = new Array(mini - i.length + 1).join(padi) + i;
if (i.length > 3) i = i.replace(/\B(?=(?:\d{3})+(?!\d))/g, group);
if (!padg && (i.length < mins)) i = new Array(mins - i.length + 1).join(padi) + i;
s[0] = x < 0 ? np + i + ns : i;
/* Pad the fractional part. */
var f = s[1] || "";
if (f.length < minf) s[1] = f + new Array(minf - f.length + 1).join(padf);
return s.join(decimal);
}
/**
* @function
* @name pv.Format.number.prototype.format
* @param {number} x
* @returns {string}
*/
format.format = format;
/**
* Parses the specified string as a number. Before parsing, leading and
* trailing padding is removed. Group separators are also removed, and the
* decimal separator is replaced with the standard point ("."). The integer
* part is truncated per the maximum integer digits, and the fraction part is
* rounded per the maximum fraction digits.
*
* @function
* @name pv.Format.number.prototype.parse
* @param {string} x the string to parse.
* @returns {number} the parsed number.
*/
format.parse = function(x) {
var re = pv.Format.re;
/* Remove leading and trailing padding. Split on the decimal separator. */
var s = String(x)
.replace(new RegExp("^(" + re(padi) + ")*"), "")
.replace(new RegExp("(" + re(padf) + ")*$"), "")
.split(decimal);
/* Remove grouping and truncate the integral part. */
var i = s[0].replace(new RegExp(re(group), "g"), "");
if (i.length > maxi) i = i.substring(i.length - maxi);
/* Round the fractional part. */
var f = s[1] ? Number("0." + s[1]) : 0;
if (Infinity > maxf) f = Math.round(f * maxk) / maxk;
return Math.round(i) + f;
};
/**
* Sets or gets the minimum and maximum number of integer digits. This
* controls the number of decimal digits to display before the decimal
* separator for the integral part of the number. If the number of digits is
* smaller than the minimum, the digits are padded; if the number of digits is
* larger, the digits are truncated, showing only the lower-order digits. The
* default range is [0, Infinity].
*
* <p>If only one argument is specified to this method, this value is used as
* both the minimum and maximum number. If no arguments are specified, a
* two-element array is returned containing the minimum and the maximum.
*
* @function
* @name pv.Format.number.prototype.integerDigits
* @param {number} [min] the minimum integer digits.
* @param {number} [max] the maximum integer digits.
* @returns {pv.Format.number} <tt>this</tt>, or the current integer digits.
*/
format.integerDigits = function(min, max) {
if (arguments.length) {
mini = Number(min);
maxi = (arguments.length > 1) ? Number(max) : mini;
mins = mini + Math.floor(mini / 3) * group.length;
return this;
}
return [mini, maxi];
};
/**
* Sets or gets the minimum and maximum number of fraction digits. The
* controls the number of decimal digits to display after the decimal
* separator for the fractional part of the number. If the number of digits is
* smaller than the minimum, the digits are padded; if the number of digits is
* larger, the fractional part is rounded, showing only the higher-order
* digits. The default range is [0, 0].
*
* <p>If only one argument is specified to this method, this value is used as
* both the minimum and maximum number. If no arguments are specified, a
* two-element array is returned containing the minimum and the maximum.
*
* @function
* @name pv.Format.number.prototype.fractionDigits
* @param {number} [min] the minimum fraction digits.
* @param {number} [max] the maximum fraction digits.
* @returns {pv.Format.number} <tt>this</tt>, or the current fraction digits.
*/
format.fractionDigits = function(min, max) {
if (arguments.length) {
minf = Number(min);
maxf = (arguments.length > 1) ? Number(max) : minf;
maxk = Math.pow(10, maxf);
return this;
}
return [minf, maxf];
};
/**
* Sets or gets the character used to pad the integer part. The integer pad is
* used when the number of integer digits is smaller than the minimum. The
* default pad character is "0" (zero).
*
* @param {string} [x] the new pad character.
* @returns {pv.Format.number} <tt>this</tt> or the current pad character.
*/
format.integerPad = function(x) {
if (arguments.length) {
padi = String(x);
padg = /\d/.test(padi);
return this;
}
return padi;
};
/**
* Sets or gets the character used to pad the fration part. The fraction pad
* is used when the number of fraction digits is smaller than the minimum. The
* default pad character is "0" (zero).
*
* @param {string} [x] the new pad character.
* @returns {pv.Format.number} <tt>this</tt> or the current pad character.
*/
format.fractionPad = function(x) {
if (arguments.length) {
padf = String(x);
return this;
}