forked from dmester/jdenticon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdenticon.js
1347 lines (1158 loc) · 43.1 KB
/
jdenticon.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
/**
* Jdenticon 2.1.0
* http://jdenticon.com
*
* Built: 2018-04-15T17:32:59.846Z
*
* Copyright (c) 2014-2018 Daniel Mester Pirttijärvi
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jslint bitwise: true */
(function (global, name, factory) {
var jQuery = global["jQuery"],
jdenticon = factory(global, jQuery);
// Node.js
if (typeof module !== "undefined" && "exports" in module) {
module["exports"] = jdenticon;
}
// RequireJS
else if (typeof define === "function" && define["amd"]) {
define([], function () { return jdenticon; });
}
// No module loader
else {
global[name] = jdenticon;
}
})(this, "jdenticon", function (global, jQuery) {
"use strict";
/**
* Creates a new element and adds it to the specified parent.
* @param {Element} parentNode
* @param {string} name
* @param {...*} keyValuePairs
*/
function SvgElement_append(parentNode, name, keyValuePairs) {
var el = document.createElementNS("http://www.w3.org/2000/svg", name);
for (var i = 2; i + 1 < arguments.length; i += 2) {
el.setAttribute(arguments[i], arguments[i + 1]);
}
parentNode.appendChild(el);
}
/**
* Renderer producing SVG output.
* @private
* @constructor
*/
function SvgElement(element) {
// Don't use the clientWidth and clientHeight properties on SVG elements
// since Firefox won't serve a proper value of these properties on SVG
// elements (https://bugzilla.mozilla.org/show_bug.cgi?id=874811)
// Instead use 100px as a hardcoded size (the svg viewBox will rescale
// the icon to the correct dimensions)
this.size = Math.min(
(Number(element.getAttribute("width")) || 100),
(Number(element.getAttribute("height")) || 100)
);
this._el = element;
// Clear current SVG child elements
while (element.firstChild) {
element.removeChild(element.firstChild);
}
// Set viewBox attribute to ensure the svg scales nicely.
element.setAttribute("viewBox", "0 0 " + this.size + " " + this.size);
element.setAttribute("preserveAspectRatio", "xMidYMid meet");
}
SvgElement.prototype = {
/**
* Fills the background with the specified color.
* @param {string} fillColor Fill color on the format #rrggbb.
* @param {number} opacity Opacity in the range [0.0, 1.0].
*/
setBackground: function (fillColor, opacity) {
if (opacity) {
SvgElement_append(this._el, "rect",
"width", "100%",
"height", "100%",
"fill", fillColor,
"opacity", opacity);
}
},
/**
* Appends a path to the SVG element.
* @param {string} color Fill color on format #xxxxxx.
* @param {string} dataString The SVG path data string.
*/
append: function (color, dataString) {
SvgElement_append(this._el, "path",
"fill", color,
"d", dataString);
}
};
/**
* Renderer producing SVG output.
* @private
* @constructor
*/
function SvgWriter(size) {
this.size = size;
this._s =
'<svg xmlns="http://www.w3.org/2000/svg" width="' +
size + '" height="' + size + '" viewBox="0 0 ' +
size + ' ' + size + '" preserveAspectRatio="xMidYMid meet">';
}
SvgWriter.prototype = {
/**
* Fills the background with the specified color.
* @param {string} fillColor Fill color on the format #rrggbb.
* @param {number} opacity Opacity in the range [0.0, 1.0].
*/
setBackground: function (fillColor, opacity) {
if (opacity) {
this._s += '<rect width="100%" height="100%" fill="' +
fillColor + '" opacity="' + opacity.toFixed(2) + '"/>';
}
},
/**
* Writes a path to the SVG string.
* @param {string} color Fill color on format #rrggbb.
* @param {string} dataString The SVG path data string.
*/
append: function (color, dataString) {
this._s +=
'<path fill="' + color + '" d="' + dataString + '"/>';
},
/**
* Gets the rendered image as an SVG string.
*/
toString: function () {
return this._s + "</svg>";
}
};
var dom = {
/** @const */
ICON_TYPE_SVG: 1,
/** @const */
ICON_TYPE_CANVAS: 2,
/** @const */
HASH_ATTRIBUTE: "data-jdenticon-hash",
/** @const */
VALUE_ATTRIBUTE: "data-jdenticon-value",
supportsQuerySelectorAll: typeof document !== "undefined" && "querySelectorAll" in document,
getIdenticonType: dom_getIdenticonType
};
/** @const */
dom.ICON_SELECTOR = "[" + dom.HASH_ATTRIBUTE +"],[" + dom.VALUE_ATTRIBUTE +"]";
function dom_getIdenticonType(el) {
if (el) {
var tagName = el["tagName"];
if (/svg/i.test(tagName)) {
return dom.ICON_TYPE_SVG;
}
if (/canvas/i.test(tagName) && "getContext" in el) {
return dom.ICON_TYPE_CANVAS;
}
}
}
/**
* Computes a SHA1 hash for any value and returns it as a hexadecimal string.
* @param {string} message
*/
function sha1(message) {
/**
* Converts an array of 32-bit unsigned numbers to a hexadecimal string in big endian format.
* @param {Array<number>} words
*/
function wordsToHexString(words) {
var hashOctets = [];
for (var i = 0; i < words.length; i++) {
var val = words[i];
for (var shift = 28; shift >= 0; shift -= 4) {
var octet = (val >>> shift) & 0xf;
hashOctets.push(octet.toString(16));
}
}
return hashOctets.join("");
}
/**
* Converts the specified message to a sequence of UTF8 encoded and padded 64 byte blocks.
* @param {string} message Any value that will be padded to 64 byte blocks.
*/
function getBlocks(message) {
var percentEncoded = encodeURI(message),
binaryMessage = [],
binaryMessageLength = 0,
i, b,
blocks = [],
BLOCK_SIZE_BYTES = 64,
BLOCK_SIZE_WORDS = BLOCK_SIZE_BYTES >>> 2,
MESSAGE_LENGTH_SIZE_BYTES = 8;
// UTF8 encode message
for (i = 0; i < percentEncoded.length; i++) {
if (percentEncoded[i] == "%") {
b = parseHex(percentEncoded, i + 1, 2);
i += 2;
}
else {
b = percentEncoded.charCodeAt(i);
}
binaryMessage[binaryMessageLength++] = b;
}
// Trailing '1' bit
binaryMessage[binaryMessageLength++] = 0x80;
function getWordBlock(startIndex, byteCount) {
var words = [];
var wordIndex = -1;
for (var i = 0; i < byteCount; i++) {
wordIndex = (i / 4) | 0;
words[wordIndex] = (words[wordIndex] || 0) +
(binaryMessage[startIndex + i] << ((3 - (i & 3)) * 8));
}
while (++wordIndex < BLOCK_SIZE_WORDS) {
words[wordIndex] = 0;
}
return words;
}
// Full blocks
for (i = 0; i + BLOCK_SIZE_BYTES <= binaryMessageLength; i+= BLOCK_SIZE_BYTES) {
blocks.push(getWordBlock(i, BLOCK_SIZE_BYTES));
}
// Final block(s)
// Rest of message
var lastBlockDataLength = binaryMessageLength - i;
var block = getWordBlock(i, lastBlockDataLength);
// If there is no room for the message size in this block,
// return the block and put the size in the following block.
if (lastBlockDataLength + MESSAGE_LENGTH_SIZE_BYTES > BLOCK_SIZE_BYTES) {
// Message size goes in next block
blocks.push(block);
block = getWordBlock(0, 0);
}
var messageSizeBits = binaryMessageLength * 8 - 8;
block[BLOCK_SIZE_WORDS - 1] = messageSizeBits;
blocks.push(block);
return blocks;
}
/**
* Rotates the value a specified number of bits to the left.
* @param {number} value Value to rotate
* @param {number} shift Bit count to shift.
*/
function rotl(value, shift) {
return (value << shift) | (value >>> (32 - shift));
}
/**
* Computes a SHA1 hash for the specified array of 64 byte blocks.
* @param {Array<Array<number>>} blocks
*/
function computeHash(blocks) {
var a = 0x67452301,
b = 0xefcdab89,
c = 0x98badcfe,
d = 0x10325476,
e = 0xc3d2e1f0,
hash = [a, b, c, d, e];
for (var i = 0; i < blocks.length; i++) {
var w = blocks[i];
for (var t = 16; t < 80; t++) {
w[t] = rotl(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1);
}
for (var t = 0; t < 80; t++) {
var f =
// Ch
t < 20 ? ((b & c) ^ ((~b) & d)) + 0x5a827999 :
// Parity
t < 40 ? (b ^ c ^ d) + 0x6ed9eba1 :
// Maj
t < 60 ? ((b & c) ^ (b & d) ^ (c & d)) + 0x8f1bbcdc :
// Parity
(b ^ c ^ d) + 0xca62c1d6;
var T = rotl(a, 5) + f + e + w[t];
e = d;
d = c;
c = rotl(b, 30);
b = a;
a = T | 0;
}
hash[0] = a = ((hash[0] + a) | 0);
hash[1] = b = ((hash[1] + b) | 0);
hash[2] = c = ((hash[2] + c) | 0);
hash[3] = d = ((hash[3] + d) | 0);
hash[4] = e = ((hash[4] + e) | 0);
}
return hash;
}
return wordsToHexString(computeHash(getBlocks(message)));
}
/**
* Renderer redirecting drawing commands to a canvas context.
* @param {number=} size
* @private
* @constructor
*/
function CanvasRenderer(ctx, size) {
var width = ctx.canvas.width,
height = ctx.canvas.height;
ctx.save();
this._ctx = ctx;
if (size) {
this.size = size;
}
else {
this.size = Math.min(width, height);
ctx.translate(
((width - this.size) / 2) | 0,
((height - this.size) / 2) | 0);
}
ctx.clearRect(0, 0, this.size, this.size);
}
CanvasRenderer.prototype = {
/**
* Fills the background with the specified color.
* @param {string} fillColor Fill color on the format #rrggbb[aa].
*/
setBackground: function (fillColor) {
var ctx = this._ctx,
size = this.size;
ctx.fillStyle = color.toCss3(fillColor);
ctx.fillRect(0, 0, size, size);
},
/**
* Marks the beginning of a new shape of the specified color. Should be ended with a call to endShape.
* @param {string} fillColor Fill color on format #rrggbb[aa].
*/
beginShape: function (fillColor) {
this._ctx.fillStyle = color.toCss3(fillColor);
this._ctx.beginPath();
},
/**
* Marks the end of the currently drawn shape. This causes the queued paths to be rendered on the canvas.
*/
endShape: function () {
this._ctx.fill();
},
/**
* Adds a polygon to the rendering queue.
* @param points An array of Point objects.
*/
addPolygon: function (points) {
var ctx = this._ctx, i;
ctx.moveTo(points[0].x, points[0].y);
for (i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
},
/**
* Adds a circle to the rendering queue.
* @param {Point} point The upper left corner of the circle bounding box.
* @param {number} diameter The diameter of the circle.
* @param {boolean} counterClockwise True if the circle is drawn counter-clockwise (will result in a hole if rendered on a clockwise path).
*/
addCircle: function (point, diameter, counterClockwise) {
var ctx = this._ctx,
radius = diameter / 2;
ctx.moveTo(point.x + radius, point.y + radius);
ctx.arc(point.x + radius, point.y + radius, radius, 0, Math.PI * 2, counterClockwise);
ctx.closePath();
},
/**
* Called when the icon has been completely drawn.
*/
finish: function () {
this._ctx.restore();
}
};
function decToHex(v) {
v |= 0; // Ensure integer value
return v < 0 ? "00" :
v < 16 ? "0" + v.toString(16) :
v < 256 ? v.toString(16) :
"ff";
}
function hueToRgb(m1, m2, h) {
h = h < 0 ? h + 6 : h > 6 ? h - 6 : h;
return decToHex(255 * (
h < 1 ? m1 + (m2 - m1) * h :
h < 3 ? m2 :
h < 4 ? m1 + (m2 - m1) * (4 - h) :
m1));
}
/**
* Functions for converting colors to hex-rgb representations.
* @private
*/
var color = {
/**
* @param {number} r Red channel [0, 255]
* @param {number} g Green channel [0, 255]
* @param {number} b Blue channel [0, 255]
*/
rgb: function (r, g, b) {
return "#" + decToHex(r) + decToHex(g) + decToHex(b);
},
/**
* @param {string} color Color value to parse. Curently hexadecimal strings on the format #rgb[a] and #rrggbb[aa] are supported.
*/
parse: function (color) {
if (/^#[0-9a-f]{3,8}$/i.test(color)) {
if (color.length < 6) {
var r = color[1],
g = color[2],
b = color[3],
a = color[4] || "";
return "#" + r + r + g + g + b + b + a + a;
}
if (color.length == 7 || color.length > 8) {
return color;
}
}
},
/**
* @param {string} hexColor Color on the format "#RRGGBB" or "#RRGGBBAA"
*/
toCss3: function (hexColor) {
var a = parseHex(hexColor, 7, 2);
if (isNaN(a)) {
return hexColor;
}
var r = parseHex(hexColor, 1, 2),
g = parseHex(hexColor, 3, 2),
b = parseHex(hexColor, 5, 2);
return "rgba(" + r + "," + g + "," + b + "," + (a / 255).toFixed(2) + ")";
},
/**
* @param h Hue [0, 1]
* @param s Saturation [0, 1]
* @param l Lightness [0, 1]
*/
hsl: function (h, s, l) {
// Based on http://www.w3.org/TR/2011/REC-css3-color-20110607/#hsl-color
if (s == 0) {
var partialHex = decToHex(l * 255);
return "#" + partialHex + partialHex + partialHex;
}
else {
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s,
m1 = l * 2 - m2;
return "#" +
hueToRgb(m1, m2, h * 6 + 2) +
hueToRgb(m1, m2, h * 6) +
hueToRgb(m1, m2, h * 6 - 2);
}
},
// This function will correct the lightness for the "dark" hues
correctedHsl: function (h, s, l) {
// The corrector specifies the perceived middle lightnesses for each hue
var correctors = [ 0.55, 0.5, 0.5, 0.46, 0.6, 0.55, 0.55 ],
corrector = correctors[(h * 6 + 0.5) | 0];
// Adjust the input lightness relative to the corrector
l = l < 0.5 ? l * corrector * 2 : corrector + (l - 0.5) * (1 - corrector) * 2;
return color.hsl(h, s, l);
}
};
function observer(updateCallback) {
if (typeof MutationObserver != "undefined") {
var mutationObserver = new MutationObserver(function onmutation(mutations) {
for (var mutationIndex = 0; mutationIndex < mutations.length; mutationIndex++) {
var mutation = mutations[mutationIndex];
var addedNodes = mutation.addedNodes;
for (var addedNodeIndex = 0; addedNodes && addedNodeIndex < addedNodes.length; addedNodeIndex++) {
var addedNode = addedNodes[addedNodeIndex];
// Skip other types of nodes than element nodes, since they might not support
// the querySelectorAll method => runtime error.
if (addedNode.nodeType == Node.ELEMENT_NODE) {
if (dom.getIdenticonType(addedNode)) {
updateCallback(addedNode);
}
else {
var icons = addedNode.querySelectorAll(dom.ICON_SELECTOR);
for (var iconIndex = 0; iconIndex < icons.length; iconIndex++) {
updateCallback(icons[iconIndex]);
}
}
}
}
if (mutation.type == "attributes" && dom.getIdenticonType(mutation.target)) {
updateCallback(mutation.target);
}
}
});
mutationObserver.observe(document.body, {
"childList": true,
"attributes": true,
"attributeFilter": [dom.VALUE_ATTRIBUTE, dom.HASH_ATTRIBUTE, "width", "height"],
"subtree": true
});
}
}
var shapes = {
center: [
/** @param {Graphics} g */
function (g, cell, index) {
var k = cell * 0.42;
g.addPolygon([
0, 0,
cell, 0,
cell, cell - k * 2,
cell - k, cell,
0, cell
]);
},
/** @param {Graphics} g */
function (g, cell, index) {
var w = 0 | (cell * 0.5),
h = 0 | (cell * 0.8);
g.addTriangle(cell - w, 0, w, h, 2);
},
/** @param {Graphics} g */
function (g, cell, index) {
var s = 0 | (cell / 3);
g.addRectangle(s, s, cell - s, cell - s);
},
/** @param {Graphics} g */
function (g, cell, index) {
var inner = cell * 0.1,
// Use fixed outer border widths in small icons to ensure the border is drawn
outer =
cell < 6 ? 1 :
cell < 8 ? 2 :
(0 | (cell * 0.25));
inner =
inner > 1 ? (0 | inner) : // large icon => truncate decimals
inner > 0.5 ? 1 : // medium size icon => fixed width
inner; // small icon => anti-aliased border
g.addRectangle(outer, outer, cell - inner - outer, cell - inner - outer);
},
/** @param {Graphics} g */
function (g, cell, index) {
var m = 0 | (cell * 0.15),
s = 0 | (cell * 0.5);
g.addCircle(cell - s - m, cell - s - m, s);
},
/** @param {Graphics} g */
function (g, cell, index) {
var inner = cell * 0.1,
outer = inner * 4;
// Align edge to nearest pixel in large icons
if (outer > 3) {
outer = 0 | outer;
}
g.addRectangle(0, 0, cell, cell);
g.addPolygon([
outer, outer,
cell - inner, outer,
outer + (cell - outer - inner) / 2, cell - inner
], true);
},
/** @param {Graphics} g */
function (g, cell, index) {
g.addPolygon([
0, 0,
cell, 0,
cell, cell * 0.7,
cell * 0.4, cell * 0.4,
cell * 0.7, cell,
0, cell
]);
},
/** @param {Graphics} g */
function (g, cell, index) {
g.addTriangle(cell / 2, cell / 2, cell / 2, cell / 2, 3);
},
/** @param {Graphics} g */
function (g, cell, index) {
g.addRectangle(0, 0, cell, cell / 2);
g.addRectangle(0, cell / 2, cell / 2, cell / 2);
g.addTriangle(cell / 2, cell / 2, cell / 2, cell / 2, 1);
},
/** @param {Graphics} g */
function (g, cell, index) {
var inner = cell * 0.14,
// Use fixed outer border widths in small icons to ensure the border is drawn
outer =
cell < 4 ? 1 :
cell < 6 ? 2 :
(0 | (cell * 0.35));
inner =
cell < 8 ? inner : // small icon => anti-aliased border
(0 | inner); // large icon => truncate decimals
g.addRectangle(0, 0, cell, cell);
g.addRectangle(outer, outer, cell - outer - inner, cell - outer - inner, true);
},
/** @param {Graphics} g */
function (g, cell, index) {
var inner = cell * 0.12,
outer = inner * 3;
g.addRectangle(0, 0, cell, cell);
g.addCircle(outer, outer, cell - inner - outer, true);
},
/** @param {Graphics} g */
function (g, cell, index) {
g.addTriangle(cell / 2, cell / 2, cell / 2, cell / 2, 3);
},
/** @param {Graphics} g */
function (g, cell, index) {
var m = cell * 0.25;
g.addRectangle(0, 0, cell, cell);
g.addRhombus(m, m, cell - m, cell - m, true);
},
/** @param {Graphics} g */
function (g, cell, index) {
var m = cell * 0.4, s = cell * 1.2;
if (!index) {
g.addCircle(m, m, s);
}
}
],
outer: [
/** @param {Graphics} g */
function (g, cell, index) {
g.addTriangle(0, 0, cell, cell, 0);
},
/** @param {Graphics} g */
function (g, cell, index) {
g.addTriangle(0, cell / 2, cell, cell / 2, 0);
},
/** @param {Graphics} g */
function (g, cell, index) {
g.addRhombus(0, 0, cell, cell);
},
/** @param {Graphics} g */
function (g, cell, index) {
var m = cell / 6;
g.addCircle(m, m, cell - 2 * m);
}
]
};
/**
* Parses a substring of the hash as a number.
* @param {number} startPosition
* @param {number=} octets
* @noinline
*/
function parseHex(hash, startPosition, octets) {
return parseInt(hash.substr(startPosition, octets), 16);
}
/**
* Prepares a measure to be used as a measure in an SVG path, by
* rounding the measure to a single decimal. This reduces the file
* size of the generated SVG with more than 50% in some cases.
*/
function svgValue(value) {
return ((value * 10 + 0.5) | 0) / 10;
}
/**
* Represents an SVG path element.
* @private
* @constructor
*/
function SvgPath() {
/**
* This property holds the data string (path.d) of the SVG path.
*/
this.dataString = "";
}
SvgPath.prototype = {
/**
* Adds a polygon with the current fill color to the SVG path.
* @param points An array of Point objects.
*/
addPolygon: function (points) {
var dataString = "M" + svgValue(points[0].x) + " " + svgValue(points[0].y);
for (var i = 1; i < points.length; i++) {
dataString += "L" + svgValue(points[i].x) + " " + svgValue(points[i].y);
}
this.dataString += dataString + "Z";
},
/**
* Adds a circle with the current fill color to the SVG path.
* @param {Point} point The upper left corner of the circle bounding box.
* @param {number} diameter The diameter of the circle.
* @param {boolean} counterClockwise True if the circle is drawn counter-clockwise (will result in a hole if rendered on a clockwise path).
*/
addCircle: function (point, diameter, counterClockwise) {
var sweepFlag = counterClockwise ? 0 : 1,
svgRadius = svgValue(diameter / 2),
svgDiameter = svgValue(diameter);
this.dataString +=
"M" + svgValue(point.x) + " " + svgValue(point.y + diameter / 2) +
"a" + svgRadius + "," + svgRadius + " 0 1," + sweepFlag + " " + svgDiameter + ",0" +
"a" + svgRadius + "," + svgRadius + " 0 1," + sweepFlag + " " + (-svgDiameter) + ",0";
}
};
/**
* Renderer producing SVG output.
* @private
* @constructor
* @param {SvgElement|SvgWriter} target
*/
function SvgRenderer(target) {
this._pathsByColor = { };
this._target = target;
this.size = target.size;
}
SvgRenderer.prototype = {
/**
* Fills the background with the specified color.
* @param {string} fillColor Fill color on the format #rrggbb[aa].
*/
setBackground: function (fillColor) {
var match = /^(#......)(..)?/.exec(fillColor),
opacity = match[2] ? parseHex(match[2], 0) / 255 : 1;
this._target.setBackground(match[1], opacity);
},
/**
* Marks the beginning of a new shape of the specified color. Should be ended with a call to endShape.
* @param {string} color Fill color on format #xxxxxx.
*/
beginShape: function (color) {
this._path = this._pathsByColor[color] || (this._pathsByColor[color] = new SvgPath());
},
/**
* Marks the end of the currently drawn shape.
*/
endShape: function () { },
/**
* Adds a polygon with the current fill color to the SVG.
* @param points An array of Point objects.
*/
addPolygon: function (points) {
this._path.addPolygon(points);
},
/**
* Adds a circle with the current fill color to the SVG.
* @param {Point} point The upper left corner of the circle bounding box.
* @param {number} diameter The diameter of the circle.
* @param {boolean} counterClockwise True if the circle is drawn counter-clockwise (will result in a hole if rendered on a clockwise path).
*/
addCircle: function (point, diameter, counterClockwise) {
this._path.addCircle(point, diameter, counterClockwise);
},
/**
* Called when the icon has been completely drawn.
*/
finish: function () {
for (var color in this._pathsByColor) {
this._target.append(color, this._pathsByColor[color].dataString);
}
}
};
/**
* Provides helper functions for rendering common basic shapes.
* @private
* @constructor
*/
function Graphics(renderer) {
this._renderer = renderer;
this._transform = Transform.noTransform;
}
Graphics.prototype = {
/**
* Adds a polygon to the underlying renderer.
* @param {Array} points The points of the polygon clockwise on the format [ x0, y0, x1, y1, ..., xn, yn ]
* @param {boolean=} invert Specifies if the polygon will be inverted.
*/
addPolygon: function (points, invert) {
var di = invert ? -2 : 2,
transform = this._transform,
transformedPoints = [],
i;
for (i = invert ? points.length - 2 : 0; i < points.length && i >= 0; i += di) {
transformedPoints.push(transform.transformPoint(points[i], points[i + 1]));
}
this._renderer.addPolygon(transformedPoints);
},
/**
* Adds a polygon to the underlying renderer.
* Source: http://stackoverflow.com/a/2173084
* @param {number} x The x-coordinate of the upper left corner of the rectangle holding the entire ellipse.
* @param {number} y The y-coordinate of the upper left corner of the rectangle holding the entire ellipse.
* @param {number} size The size of the ellipse.
* @param {boolean=} invert Specifies if the ellipse will be inverted.
*/
addCircle: function (x, y, size, invert) {
var p = this._transform.transformPoint(x, y, size, size);
this._renderer.addCircle(p, size, invert);
},
/**
* Adds a rectangle to the underlying renderer.
* @param {number} x The x-coordinate of the upper left corner of the rectangle.
* @param {number} y The y-coordinate of the upper left corner of the rectangle.
* @param {number} w The width of the rectangle.
* @param {number} h The height of the rectangle.
* @param {boolean=} invert Specifies if the rectangle will be inverted.
*/
addRectangle: function (x, y, w, h, invert) {
this.addPolygon([
x, y,
x + w, y,
x + w, y + h,
x, y + h
], invert);
},
/**
* Adds a right triangle to the underlying renderer.
* @param {number} x The x-coordinate of the upper left corner of the rectangle holding the triangle.
* @param {number} y The y-coordinate of the upper left corner of the rectangle holding the triangle.
* @param {number} w The width of the triangle.
* @param {number} h The height of the triangle.
* @param {number} r The rotation of the triangle (clockwise). 0 = right corner of the triangle in the lower left corner of the bounding rectangle.
* @param {boolean=} invert Specifies if the triangle will be inverted.
*/
addTriangle: function (x, y, w, h, r, invert) {
var points = [
x + w, y,
x + w, y + h,
x, y + h,
x, y
];
points.splice(((r || 0) % 4) * 2, 2);
this.addPolygon(points, invert);
},
/**
* Adds a rhombus to the underlying renderer.
* @param {number} x The x-coordinate of the upper left corner of the rectangle holding the rhombus.
* @param {number} y The y-coordinate of the upper left corner of the rectangle holding the rhombus.
* @param {number} w The width of the rhombus.
* @param {number} h The height of the rhombus.
* @param {boolean=} invert Specifies if the rhombus will be inverted.
*/
addRhombus: function (x, y, w, h, invert) {
this.addPolygon([
x + w / 2, y,
x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2
], invert);
}
};
/**
* Gets a set of identicon color candidates for a specified hue and config.
*/
function colorTheme(hue, config) {
hue = config.hue(hue);
return [
// Dark gray
color.correctedHsl(hue, config.grayscaleSaturation, config.grayscaleLightness(0)),
// Mid color
color.correctedHsl(hue, config.colorSaturation, config.colorLightness(0.5)),
// Light gray
color.correctedHsl(hue, config.grayscaleSaturation, config.grayscaleLightness(1)),
// Light color
color.correctedHsl(hue, config.colorSaturation, config.colorLightness(1)),
// Dark color
color.correctedHsl(hue, config.colorSaturation, config.colorLightness(0))
];
}
/**
* Represents a point.
* @private
* @constructor
*/
function Point(x, y) {
this.x = x;
this.y = y;
};