forked from palantir/plottable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plottable.js
9538 lines (9456 loc) · 446 KB
/
plottable.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
/*!
Plottable 0.37.0 (https://github.com/palantir/plottable)
Copyright 2014 Palantir Technologies
Licensed under MIT (https://github.com/palantir/plottable/blob/master/LICENSE)
*/
///<reference path="../reference.ts" />
var Plottable;
(function (Plottable) {
(function (_Util) {
(function (Methods) {
/**
* Checks if x is between a and b.
*
* @param {number} x The value to test if in range
* @param {number} a The beginning of the (inclusive) range
* @param {number} b The ending of the (inclusive) range
* @return {boolean} Whether x is in [a, b]
*/
function inRange(x, a, b) {
return (Math.min(a, b) <= x && x <= Math.max(a, b));
}
Methods.inRange = inRange;
/** Print a warning message to the console, if it is available.
*
* @param {string} The warnings to print
*/
function warn(warning) {
if (!Plottable.Config.SHOW_WARNINGS) {
return;
}
/* tslint:disable:no-console */
if (window.console != null) {
if (window.console.warn != null) {
console.warn(warning);
}
else if (window.console.log != null) {
console.log(warning);
}
}
/* tslint:enable:no-console */
}
Methods.warn = warn;
/**
* Takes two arrays of numbers and adds them together
*
* @param {number[]} alist The first array of numbers
* @param {number[]} blist The second array of numbers
* @return {number[]} An array of numbers where x[i] = alist[i] + blist[i]
*/
function addArrays(alist, blist) {
if (alist.length !== blist.length) {
throw new Error("attempted to add arrays of unequal length");
}
return alist.map(function (_, i) { return alist[i] + blist[i]; });
}
Methods.addArrays = addArrays;
/**
* Takes two sets and returns the intersection
*
* Due to the fact that D3.Sets store strings internally, return type is always a string set
*
* @param {D3.Set<T>} set1 The first set
* @param {D3.Set<T>} set2 The second set
* @return {D3.Set<string>} A set that contains elements that appear in both set1 and set2
*/
function intersection(set1, set2) {
var set = d3.set();
set1.forEach(function (v) {
if (set2.has(v)) {
set.add(v);
}
});
return set;
}
Methods.intersection = intersection;
/**
* Take an accessor object (may be a string to be made into a key, or a value, or a color code)
* and "activate" it by turning it into a function in (datum, index, metadata)
*/
function accessorize(accessor) {
if (typeof (accessor) === "function") {
return accessor;
}
else if (typeof (accessor) === "string" && accessor[0] !== "#") {
return function (d, i, s) { return d[accessor]; };
}
else {
return function (d, i, s) { return accessor; };
}
;
}
Methods.accessorize = accessorize;
/**
* Takes two sets and returns the union
*
* Due to the fact that D3.Sets store strings internally, return type is always a string set
*
* @param {D3.Set<T>} set1 The first set
* @param {D3.Set<T>} set2 The second set
* @return {D3.Set<string>} A set that contains elements that appear in either set1 or set2
*/
function union(set1, set2) {
var set = d3.set();
set1.forEach(function (v) { return set.add(v); });
set2.forEach(function (v) { return set.add(v); });
return set;
}
Methods.union = union;
/**
* Populates a map from an array of keys and a transformation function.
*
* @param {string[]} keys The array of keys.
* @param {(string, number) => T} transform A transformation function to apply to the keys.
* @return {D3.Map<T>} A map mapping keys to their transformed values.
*/
function populateMap(keys, transform) {
var map = d3.map();
keys.forEach(function (key, i) {
map.set(key, transform(key, i));
});
return map;
}
Methods.populateMap = populateMap;
/**
* Take an array of values, and return the unique values.
* Will work iff ∀ a, b, a.toString() == b.toString() => a == b; will break on Object inputs
*
* @param {T[]} values The values to find uniqueness for
* @return {T[]} The unique values
*/
function uniq(arr) {
var seen = d3.set();
var result = [];
arr.forEach(function (x) {
if (!seen.has(x)) {
seen.add(x);
result.push(x);
}
});
return result;
}
Methods.uniq = uniq;
function createFilledArray(value, count) {
var out = [];
for (var i = 0; i < count; i++) {
out[i] = typeof (value) === "function" ? value(i) : value;
}
return out;
}
Methods.createFilledArray = createFilledArray;
/**
* @param {T[][]} a The 2D array that will have its elements joined together.
* @return {T[]} Every array in a, concatenated together in the order they appear.
*/
function flatten(a) {
return Array.prototype.concat.apply([], a);
}
Methods.flatten = flatten;
/**
* Check if two arrays are equal by strict equality.
*/
function arrayEq(a, b) {
// Technically, null and undefined are arrays too
if (a == null || b == null) {
return a === b;
}
if (a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
Methods.arrayEq = arrayEq;
/**
* @param {any} a Object to check against b for equality.
* @param {any} b Object to check against a for equality.
*
* @returns {boolean} whether or not two objects share the same keys, and
* values associated with those keys. Values will be compared
* with ===.
*/
function objEq(a, b) {
if (a == null || b == null) {
return a === b;
}
var keysA = Object.keys(a).sort();
var keysB = Object.keys(b).sort();
var valuesA = keysA.map(function (k) { return a[k]; });
var valuesB = keysB.map(function (k) { return b[k]; });
return arrayEq(keysA, keysB) && arrayEq(valuesA, valuesB);
}
Methods.objEq = objEq;
function max(arr, one, two) {
if (arr.length === 0) {
if (typeof (one) !== "function") {
return one;
}
else {
return two;
}
}
/* tslint:disable:ban */
var acc = typeof (one) === "function" ? one : typeof (two) === "function" ? two : undefined;
return acc === undefined ? d3.max(arr) : d3.max(arr, acc);
/* tslint:enable:ban */
}
Methods.max = max;
function min(arr, one, two) {
if (arr.length === 0) {
if (typeof (one) !== "function") {
return one;
}
else {
return two;
}
}
/* tslint:disable:ban */
var acc = typeof (one) === "function" ? one : typeof (two) === "function" ? two : undefined;
return acc === undefined ? d3.min(arr) : d3.min(arr, acc);
/* tslint:enable:ban */
}
Methods.min = min;
/**
* Creates shallow copy of map.
* @param {{ [key: string]: any }} oldMap Map to copy
*
* @returns {[{ [key: string]: any }} coppied map.
*/
function copyMap(oldMap) {
var newMap = {};
d3.keys(oldMap).forEach(function (key) { return newMap[key] = oldMap[key]; });
return newMap;
}
Methods.copyMap = copyMap;
function range(start, stop, step) {
if (step === void 0) { step = 1; }
if (step === 0) {
throw new Error("step cannot be 0");
}
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = [];
for (var i = 0; i < length; ++i) {
range[i] = start + step * i;
}
return range;
}
Methods.range = range;
/** Is like setTimeout, but activates synchronously if time=0
* We special case 0 because of an observed issue where calling setTimeout causes visible flickering.
* We believe this is because when requestAnimationFrame calls into the paint function, as soon as that function finishes
* evaluating, the results are painted to the screen. As a result, if we want something to occur immediately but call setTimeout
* with time=0, then it is pushed to the call stack and rendered in the next frame, so the component that was rendered via
* setTimeout appears out-of-sync with the rest of the plot.
*/
function setTimeout(f, time) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (time === 0) {
f(args);
return -1;
}
else {
return window.setTimeout(f, time, args);
}
}
Methods.setTimeout = setTimeout;
function colorTest(colorTester, className) {
colorTester.classed(className, true);
// Use regex to get the text inside the rgb parentheses
var colorStyle = colorTester.style("background-color");
if (colorStyle === "transparent") {
return null;
}
var rgb = /\((.+)\)/.exec(colorStyle)[1].split(",").map(function (colorValue) {
var colorNumber = +colorValue;
var hexValue = colorNumber.toString(16);
return colorNumber < 16 ? "0" + hexValue : hexValue;
});
if (rgb.length === 4 && rgb[3] === "00") {
return null;
}
var hexCode = "#" + rgb.join("");
colorTester.classed(className, false);
return hexCode;
}
Methods.colorTest = colorTest;
})(_Util.Methods || (_Util.Methods = {}));
var Methods = _Util.Methods;
})(Plottable._Util || (Plottable._Util = {}));
var _Util = Plottable._Util;
})(Plottable || (Plottable = {}));
///<reference path="../reference.ts" />
// This file contains open source utilities, along with their copyright notices
var Plottable;
(function (Plottable) {
(function (_Util) {
(function (OpenSource) {
function sortedIndex(val, arr, accessor) {
var low = 0;
var high = arr.length;
while (low < high) {
/* tslint:disable:no-bitwise */
var mid = (low + high) >>> 1;
/* tslint:enable:no-bitwise */
var x = accessor == null ? arr[mid] : accessor(arr[mid]);
if (x < val) {
low = mid + 1;
}
else {
high = mid;
}
}
return low;
}
OpenSource.sortedIndex = sortedIndex;
;
})(_Util.OpenSource || (_Util.OpenSource = {}));
var OpenSource = _Util.OpenSource;
})(Plottable._Util || (Plottable._Util = {}));
var _Util = Plottable._Util;
})(Plottable || (Plottable = {}));
///<reference path="../reference.ts" />
var Plottable;
(function (Plottable) {
(function (_Util) {
var IDCounter = (function () {
function IDCounter() {
this.counter = {};
}
IDCounter.prototype.setDefault = function (id) {
if (this.counter[id] == null) {
this.counter[id] = 0;
}
};
IDCounter.prototype.increment = function (id) {
this.setDefault(id);
return ++this.counter[id];
};
IDCounter.prototype.decrement = function (id) {
this.setDefault(id);
return --this.counter[id];
};
IDCounter.prototype.get = function (id) {
this.setDefault(id);
return this.counter[id];
};
return IDCounter;
})();
_Util.IDCounter = IDCounter;
})(Plottable._Util || (Plottable._Util = {}));
var _Util = Plottable._Util;
})(Plottable || (Plottable = {}));
///<reference path="../reference.ts" />
var Plottable;
(function (Plottable) {
(function (_Util) {
/**
* An associative array that can be keyed by anything (inc objects).
* Uses pointer equality checks which is why this works.
* This power has a price: everything is linear time since it is actually backed by an array...
*/
var StrictEqualityAssociativeArray = (function () {
function StrictEqualityAssociativeArray() {
this.keyValuePairs = [];
}
/**
* Set a new key/value pair in the store.
*
* @param {any} key Key to set in the store
* @param {any} value Value to set in the store
* @return {boolean} True if key already in store, false otherwise
*/
StrictEqualityAssociativeArray.prototype.set = function (key, value) {
if (key !== key) {
throw new Error("NaN may not be used as a key to the StrictEqualityAssociativeArray");
}
for (var i = 0; i < this.keyValuePairs.length; i++) {
if (this.keyValuePairs[i][0] === key) {
this.keyValuePairs[i][1] = value;
return true;
}
}
this.keyValuePairs.push([key, value]);
return false;
};
/**
* Get a value from the store, given a key.
*
* @param {any} key Key associated with value to retrieve
* @return {any} Value if found, undefined otherwise
*/
StrictEqualityAssociativeArray.prototype.get = function (key) {
for (var i = 0; i < this.keyValuePairs.length; i++) {
if (this.keyValuePairs[i][0] === key) {
return this.keyValuePairs[i][1];
}
}
return undefined;
};
/**
* Test whether store has a value associated with given key.
*
* Will return true if there is a key/value entry,
* even if the value is explicitly `undefined`.
*
* @param {any} key Key to test for presence of an entry
* @return {boolean} Whether there was a matching entry for that key
*/
StrictEqualityAssociativeArray.prototype.has = function (key) {
for (var i = 0; i < this.keyValuePairs.length; i++) {
if (this.keyValuePairs[i][0] === key) {
return true;
}
}
return false;
};
/**
* Return an array of the values in the key-value store
*
* @return {any[]} The values in the store
*/
StrictEqualityAssociativeArray.prototype.values = function () {
return this.keyValuePairs.map(function (x) { return x[1]; });
};
/**
* Return an array of keys in the key-value store
*
* @return {any[]} The keys in the store
*/
StrictEqualityAssociativeArray.prototype.keys = function () {
return this.keyValuePairs.map(function (x) { return x[0]; });
};
/**
* Execute a callback for each entry in the array.
*
* @param {(key: any, val?: any, index?: number) => any} callback The callback to eecute
* @return {any[]} The results of mapping the callback over the entries
*/
StrictEqualityAssociativeArray.prototype.map = function (cb) {
return this.keyValuePairs.map(function (kv, index) {
return cb(kv[0], kv[1], index);
});
};
/**
* Delete a key from the key-value store. Return whether the key was present.
*
* @param {any} The key to remove
* @return {boolean} Whether a matching entry was found and removed
*/
StrictEqualityAssociativeArray.prototype.delete = function (key) {
for (var i = 0; i < this.keyValuePairs.length; i++) {
if (this.keyValuePairs[i][0] === key) {
this.keyValuePairs.splice(i, 1);
return true;
}
}
return false;
};
return StrictEqualityAssociativeArray;
})();
_Util.StrictEqualityAssociativeArray = StrictEqualityAssociativeArray;
})(Plottable._Util || (Plottable._Util = {}));
var _Util = Plottable._Util;
})(Plottable || (Plottable = {}));
///<reference path="../reference.ts" />
var Plottable;
(function (Plottable) {
(function (_Util) {
var Cache = (function () {
/**
* @constructor
*
* @param {string} compute The function whose results will be cached.
* @param {string} [canonicalKey] If present, when clear() is called,
* this key will be re-computed. If its result hasn't been changed,
* the cache will not be cleared.
* @param {(v: T, w: T) => boolean} [valueEq]
* Used to determine if the value of canonicalKey has changed.
* If omitted, defaults to === comparision.
*/
function Cache(compute, canonicalKey, valueEq) {
if (valueEq === void 0) { valueEq = function (v, w) { return v === w; }; }
this.cache = d3.map();
this.canonicalKey = null;
this.compute = compute;
this.canonicalKey = canonicalKey;
this.valueEq = valueEq;
if (canonicalKey !== undefined) {
this.cache.set(this.canonicalKey, this.compute(this.canonicalKey));
}
}
/**
* Attempt to look up k in the cache, computing the result if it isn't
* found.
*
* @param {string} k The key to look up in the cache.
* @return {T} The value associated with k; the result of compute(k).
*/
Cache.prototype.get = function (k) {
if (!this.cache.has(k)) {
this.cache.set(k, this.compute(k));
}
return this.cache.get(k);
};
/**
* Reset the cache empty.
*
* If canonicalKey was provided at construction, compute(canonicalKey)
* will be re-run. If the result matches what is already in the cache,
* it will not clear the cache.
*
* @return {Cache<T>} The calling Cache.
*/
Cache.prototype.clear = function () {
if (this.canonicalKey === undefined || !this.valueEq(this.cache.get(this.canonicalKey), this.compute(this.canonicalKey))) {
this.cache = d3.map();
}
return this;
};
return Cache;
})();
_Util.Cache = Cache;
})(Plottable._Util || (Plottable._Util = {}));
var _Util = Plottable._Util;
})(Plottable || (Plottable = {}));
///<reference path="../reference.ts" />
var Plottable;
(function (Plottable) {
(function (_Util) {
(function (Text) {
Text.HEIGHT_TEXT = "bqpdl";
;
;
/**
* Returns a quasi-pure function of typesignature (t: string) => Dimensions which measures height and width of text
* in the given text selection
*
* @param {D3.Selection} selection: A temporary text selection that the string will be placed into for measurement.
* Will be removed on function creation and appended only for measurement.
* @returns {Dimensions} width and height of the text
*/
function getTextMeasurer(selection) {
var parentNode = selection.node().parentNode;
selection.remove();
return function (s) {
if (s.trim() === "") {
return { width: 0, height: 0 };
}
parentNode.appendChild(selection.node());
selection.text(s);
var bb = _Util.DOM.getBBox(selection);
selection.remove();
return { width: bb.width, height: bb.height };
};
}
Text.getTextMeasurer = getTextMeasurer;
/**
* @return {TextMeasurer} A test measurer that will treat all sequences
* of consecutive whitespace as a single " ".
*/
function combineWhitespace(tm) {
return function (s) { return tm(s.replace(/\s+/g, " ")); };
}
/**
* Returns a text measure that measures each individual character of the
* string with tm, then combines all the individual measurements.
*/
function measureByCharacter(tm) {
return function (s) {
var whs = s.trim().split("").map(tm);
return {
width: d3.sum(whs, function (wh) { return wh.width; }),
height: _Util.Methods.max(whs, function (wh) { return wh.height; }, 0)
};
};
}
var CANONICAL_CHR = "a";
/**
* Some TextMeasurers get confused when measuring something that's only
* whitespace: only whitespace in a dom node takes up 0 x 0 space.
*
* @return {TextMeasurer} A function that if its argument is all
* whitespace, it will wrap its argument in CANONICAL_CHR before
* measuring in order to get a non-zero size of the whitespace.
*/
function wrapWhitespace(tm) {
return function (s) {
if (/^\s*$/.test(s)) {
var whs = s.split("").map(function (c) {
var wh = tm(CANONICAL_CHR + c + CANONICAL_CHR);
var whWrapping = tm(CANONICAL_CHR);
return {
width: wh.width - 2 * whWrapping.width,
height: wh.height
};
});
return {
width: d3.sum(whs, function (x) { return x.width; }),
height: _Util.Methods.max(whs, function (x) { return x.height; }, 0)
};
}
else {
return tm(s);
}
};
}
/**
* This class will measure text by measuring each character individually,
* then adding up the dimensions. It will also cache the dimensions of each
* letter.
*/
var CachingCharacterMeasurer = (function () {
/**
* @param {D3.Selection} textSelection The element that will have text inserted into
* it in order to measure text. The styles present for text in
* this element will to the text being measured.
*/
function CachingCharacterMeasurer(textSelection) {
var _this = this;
this.cache = new _Util.Cache(getTextMeasurer(textSelection), CANONICAL_CHR, _Util.Methods.objEq);
this.measure = combineWhitespace(measureByCharacter(wrapWhitespace(function (s) { return _this.cache.get(s); })));
}
/**
* Clear the cache, if it seems that the text has changed size.
*/
CachingCharacterMeasurer.prototype.clear = function () {
this.cache.clear();
return this;
};
return CachingCharacterMeasurer;
})();
Text.CachingCharacterMeasurer = CachingCharacterMeasurer;
/**
* Gets a truncated version of a sting that fits in the available space, given the element in which to draw the text
*
* @param {string} text: The string to be truncated
* @param {number} availableWidth: The available width, in pixels
* @param {D3.Selection} element: The text element used to measure the text
* @returns {string} text - the shortened text
*/
function getTruncatedText(text, availableWidth, measurer) {
if (measurer(text).width <= availableWidth) {
return text;
}
else {
return addEllipsesToLine(text, availableWidth, measurer);
}
}
Text.getTruncatedText = getTruncatedText;
/**
* Takes a line, a width to fit it in, and a text measurer. Will attempt to add ellipses to the end of the line,
* shortening the line as required to ensure that it fits within width.
*/
function addEllipsesToLine(line, width, measureText) {
var mutatedLine = line.trim(); // Leave original around for debugging utility
var widthMeasure = function (s) { return measureText(s).width; };
var lineWidth = widthMeasure(line);
var ellipsesWidth = widthMeasure("...");
if (width < ellipsesWidth) {
var periodWidth = widthMeasure(".");
var numPeriodsThatFit = Math.floor(width / periodWidth);
return "...".substr(0, numPeriodsThatFit);
}
while (lineWidth + ellipsesWidth > width) {
mutatedLine = mutatedLine.substr(0, mutatedLine.length - 1).trim();
lineWidth = widthMeasure(mutatedLine);
}
if (widthMeasure(mutatedLine + "...") > width) {
throw new Error("addEllipsesToLine failed :(");
}
return mutatedLine + "...";
}
Text.addEllipsesToLine = addEllipsesToLine;
function writeLineHorizontally(line, g, width, height, xAlign, yAlign) {
if (xAlign === void 0) { xAlign = "left"; }
if (yAlign === void 0) { yAlign = "top"; }
var xOffsetFactor = { left: 0, center: 0.5, right: 1 };
var yOffsetFactor = { top: 0, center: 0.5, bottom: 1 };
if (xOffsetFactor[xAlign] === undefined || yOffsetFactor[yAlign] === undefined) {
throw new Error("unrecognized alignment x:" + xAlign + ", y:" + yAlign);
}
var innerG = g.append("g");
var textEl = innerG.append("text");
textEl.text(line);
var bb = _Util.DOM.getBBox(textEl);
var h = bb.height;
var w = bb.width;
if (w > width || h > height) {
_Util.Methods.warn("Insufficient space to fit text: " + line);
textEl.text("");
return { width: 0, height: 0 };
}
var anchorConverter = { left: "start", center: "middle", right: "end" };
var anchor = anchorConverter[xAlign];
var xOff = width * xOffsetFactor[xAlign];
var yOff = height * yOffsetFactor[yAlign];
var ems = 0.85 - yOffsetFactor[yAlign];
textEl.attr("text-anchor", anchor).attr("y", ems + "em");
_Util.DOM.translate(innerG, xOff, yOff);
return { width: w, height: h };
}
Text.writeLineHorizontally = writeLineHorizontally;
function writeLineVertically(line, g, width, height, xAlign, yAlign, rotation) {
if (xAlign === void 0) { xAlign = "left"; }
if (yAlign === void 0) { yAlign = "top"; }
if (rotation === void 0) { rotation = "right"; }
if (rotation !== "right" && rotation !== "left") {
throw new Error("unrecognized rotation: " + rotation);
}
var isRight = rotation === "right";
var rightTranslator = { left: "bottom", right: "top", center: "center", top: "left", bottom: "right" };
var leftTranslator = { left: "top", right: "bottom", center: "center", top: "right", bottom: "left" };
var alignTranslator = isRight ? rightTranslator : leftTranslator;
var innerG = g.append("g");
var wh = writeLineHorizontally(line, innerG, height, width, alignTranslator[yAlign], alignTranslator[xAlign]);
var xForm = d3.transform("");
xForm.rotate = rotation === "right" ? 90 : -90;
xForm.translate = [isRight ? width : 0, isRight ? 0 : height];
innerG.attr("transform", xForm.toString());
innerG.classed("rotated-" + rotation, true);
return { width: wh.height, height: wh.width };
}
Text.writeLineVertically = writeLineVertically;
function writeTextHorizontally(brokenText, g, width, height, xAlign, yAlign) {
if (xAlign === void 0) { xAlign = "left"; }
if (yAlign === void 0) { yAlign = "top"; }
var h = getTextMeasurer(g.append("text"))(Text.HEIGHT_TEXT).height;
var maxWidth = 0;
var blockG = g.append("g");
brokenText.forEach(function (line, i) {
var innerG = blockG.append("g");
_Util.DOM.translate(innerG, 0, i * h);
var wh = writeLineHorizontally(line, innerG, width, h, xAlign, yAlign);
if (wh.width > maxWidth) {
maxWidth = wh.width;
}
});
var usedSpace = h * brokenText.length;
var freeSpace = height - usedSpace;
var translator = { center: 0.5, top: 0, bottom: 1 };
_Util.DOM.translate(blockG, 0, freeSpace * translator[yAlign]);
return { width: maxWidth, height: usedSpace };
}
function writeTextVertically(brokenText, g, width, height, xAlign, yAlign, rotation) {
if (xAlign === void 0) { xAlign = "left"; }
if (yAlign === void 0) { yAlign = "top"; }
if (rotation === void 0) { rotation = "left"; }
var h = getTextMeasurer(g.append("text"))(Text.HEIGHT_TEXT).height;
var maxHeight = 0;
var blockG = g.append("g");
brokenText.forEach(function (line, i) {
var innerG = blockG.append("g");
_Util.DOM.translate(innerG, i * h, 0);
var wh = writeLineVertically(line, innerG, h, height, xAlign, yAlign, rotation);
if (wh.height > maxHeight) {
maxHeight = wh.height;
}
});
var usedSpace = h * brokenText.length;
var freeSpace = width - usedSpace;
var translator = { center: 0.5, left: 0, right: 1 };
_Util.DOM.translate(blockG, freeSpace * translator[xAlign], 0);
return { width: usedSpace, height: maxHeight };
}
;
/**
* @param {write} [IWriteOptions] If supplied, the text will be written
* To the given g. Will align the text vertically if it seems like
* that is appropriate.
* Returns an IWriteTextResult with info on whether the text fit, and how much width/height was used.
*/
function writeText(text, width, height, tm, orientation, write) {
if (orientation === void 0) { orientation = "horizontal"; }
if (["left", "right", "horizontal"].indexOf(orientation) === -1) {
throw new Error("Unrecognized orientation to writeText: " + orientation);
}
var orientHorizontally = orientation === "horizontal";
var primaryDimension = orientHorizontally ? width : height;
var secondaryDimension = orientHorizontally ? height : width;
var wrappedText = _Util.WordWrap.breakTextToFitRect(text, primaryDimension, secondaryDimension, tm);
if (wrappedText.lines.length === 0) {
return { textFits: wrappedText.textFits, usedWidth: 0, usedHeight: 0 };
}
var usedWidth, usedHeight;
if (write == null) {
var widthFn = orientHorizontally ? _Util.Methods.max : d3.sum;
var heightFn = orientHorizontally ? d3.sum : _Util.Methods.max;
var heightAcc = function (line) { return orientHorizontally ? tm(line).height : tm(line).width; };
var widthAcc = function (line) { return orientHorizontally ? tm(line).width : tm(line).height; };
usedWidth = widthFn(wrappedText.lines, widthAcc, 0);
usedHeight = heightFn(wrappedText.lines, heightAcc, 0);
}
else {
var innerG = write.g.append("g").classed("writeText-inner-g", true); // unleash your inner G
// the outerG contains general transforms for positining the whole block, the inner g
// will contain transforms specific to orienting the text properly within the block.
var writeTextFn = orientHorizontally ? writeTextHorizontally : writeTextVertically;
var wh = writeTextFn.call(this, wrappedText.lines, innerG, width, height, write.xAlign, write.yAlign, orientation);
usedWidth = wh.width;
usedHeight = wh.height;
}
return { textFits: wrappedText.textFits, usedWidth: usedWidth, usedHeight: usedHeight };
}
Text.writeText = writeText;
})(_Util.Text || (_Util.Text = {}));
var Text = _Util.Text;
})(Plottable._Util || (Plottable._Util = {}));
var _Util = Plottable._Util;
})(Plottable || (Plottable = {}));
///<reference path="../reference.ts" />
var Plottable;
(function (Plottable) {
(function (_Util) {
(function (WordWrap) {
var LINE_BREAKS_BEFORE = /[{\[]/;
var LINE_BREAKS_AFTER = /[!"%),-.:;?\]}]/;
var SPACES = /^\s+$/;
;
/**
* Takes a block of text, a width and height to fit it in, and a 2-d text measurement function.
* Wraps words and fits as much of the text as possible into the given width and height.
*/
function breakTextToFitRect(text, width, height, measureText) {
var widthMeasure = function (s) { return measureText(s).width; };
var lines = breakTextToFitWidth(text, width, widthMeasure);
var textHeight = measureText("hello world").height;
var nLinesThatFit = Math.floor(height / textHeight);
var textFit = nLinesThatFit >= lines.length;
if (!textFit) {
lines = lines.splice(0, nLinesThatFit);
if (nLinesThatFit > 0) {
// Overwrite the last line to one that has had a ... appended to the end
lines[nLinesThatFit - 1] = _Util.Text.addEllipsesToLine(lines[nLinesThatFit - 1], width, measureText);
}
}
return { originalText: text, lines: lines, textFits: textFit };
}
WordWrap.breakTextToFitRect = breakTextToFitRect;
/**
* Splits up the text so that it will fit in width (or splits into a list of single characters if it is impossible
* to fit in width). Tries to avoid breaking words on non-linebreak-or-space characters, and will only break a word if
* the word is too big to fit within width on its own.
*/
function breakTextToFitWidth(text, width, widthMeasure) {
var ret = [];
var paragraphs = text.split("\n");
for (var i = 0, len = paragraphs.length; i < len; i++) {
var paragraph = paragraphs[i];
if (paragraph !== null) {
ret = ret.concat(breakParagraphToFitWidth(paragraph, width, widthMeasure));
}
else {
ret.push("");
}
}
return ret;
}
/**
* Determines if it is possible to fit a given text within width without breaking any of the words.
* Simple algorithm, split the text up into tokens, and make sure that the widest token doesn't exceed
* allowed width.
*/
function canWrapWithoutBreakingWords(text, width, widthMeasure) {
var tokens = tokenize(text);
var widths = tokens.map(widthMeasure);
var maxWidth = _Util.Methods.max(widths, 0);
return maxWidth <= width;
}
WordWrap.canWrapWithoutBreakingWords = canWrapWithoutBreakingWords;
/**
* A paragraph is a string of text containing no newlines.
* Given a paragraph, break it up into lines that are no
* wider than width. widthMeasure is a function that takes
* text as input, and returns the width of the text in pixels.
*/
function breakParagraphToFitWidth(text, width, widthMeasure) {
var lines = [];
var tokens = tokenize(text);
var curLine = "";
var i = 0;
var nextToken;
while (nextToken || i < tokens.length) {
if (typeof nextToken === "undefined" || nextToken === null) {
nextToken = tokens[i++];
}
var brokenToken = breakNextTokenToFitInWidth(curLine, nextToken, width, widthMeasure);
var canAdd = brokenToken[0];
var leftOver = brokenToken[1];
if (canAdd !== null) {
curLine += canAdd;
}
nextToken = leftOver;
if (leftOver) {
lines.push(curLine);
curLine = "";
}
}
if (curLine) {
lines.push(curLine);
}
return lines;
}
/**
* Breaks up the next token and so that some part of it can be
* added to curLine and fits in the width. the return value
* is an array with 2 elements, the part that can be added
* and the left over part of the token
* widthMeasure is a function that takes text as input,
* and returns the width of the text in pixels.
*/
function breakNextTokenToFitInWidth(curLine, nextToken, width, widthMeasure) {
if (isBlank(nextToken)) {
return [nextToken, null];
}
if (widthMeasure(curLine + nextToken) <= width) {
return [nextToken, null];
}
if (!isBlank(curLine)) {
return [null, nextToken];
}
var i = 0;
while (i < nextToken.length) {
if (widthMeasure(curLine + nextToken[i] + "-") <= width) {
curLine += nextToken[i++];
}
else {
break;
}
}
var append = "-";
if (isBlank(curLine) && i === 0) {
i = 1;
append = "";
}
return [nextToken.substring(0, i) + append, nextToken.substring(i)];
}
/**
* Breaks up into tokens for word wrapping
* Each token is comprised of either:
* 1) Only word and non line break characters
* 2) Only spaces characters
* 3) Line break characters such as ":" or ";" or ","
* (will be single character token, unless there is a repeated linebreak character)
*/
function tokenize(text) {
var ret = [];
var token = "";
var lastChar = "";
for (var i = 0, len = text.length; i < len; i++) {
var curChar = text[i];
if (token === "" || isTokenizedTogether(token[0], curChar, lastChar)) {
token += curChar;
}
else {
ret.push(token);
token = curChar;
}
lastChar = curChar;
}
if (token) {
ret.push(token);
}
return ret;
}
/**
* Returns whether a string is blank.
*
* @param {string} str: The string to test for blank-ness
* @returns {boolean} Whether the string is blank
*/
function isBlank(text) {
return text == null ? true : text.trim() === "";
}
/**
* Given a token (ie a string of characters that are similar and shouldn't be broken up) and a character, determine
* whether that character should be added to the token. Groups of characters that don't match the space or line break
* regex are always tokenzied together. Spaces are always tokenized together. Line break characters are almost always
* split into their own token, except that two subsequent identical line break characters are put into the same token.
* For isTokenizedTogether(":", ",") == False but isTokenizedTogether("::") == True.
*/
function isTokenizedTogether(text, nextChar, lastChar) {
if (!(text && nextChar)) {
false;
}
if (SPACES.test(text) && SPACES.test(nextChar)) {
return true;
}