forked from JhaSourav07/commitpulse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.ts
More file actions
2718 lines (2362 loc) · 106 KB
/
Copy pathgenerator.ts
File metadata and controls
2718 lines (2362 loc) · 106 KB
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
// lib/svg/generator.ts
import type { BadgeParams, ContributionCalendar, StreakStats, MonthlyStats } from '../../types';
import { getLabels, type BadgeLabels } from '../i18n/badgeLabels';
import { AUTO_THEME_DARK, AUTO_THEME_LIGHT, themes } from './themes';
import { getTowerAnimationCSS } from './animations';
import { computeTowers, type TowerData } from './layout';
import {
sanitizeFont,
sanitizeHexColor,
sanitizeRadius,
sanitizeGoogleFontUrl,
getLuminance,
parseGradientStops,
getGradientCoordinates,
} from './sanitizer';
import { GRID_ORIGIN_X, GRID_ORIGIN_Y, TILE_HEIGHT_HALF, TILE_WIDTH_HALF } from './layoutConstants';
import { SVG_WIDTH, SVG_HEIGHT } from './generatorConstants';
const FONT_MAP = {
// ── Pre-existing entries ────────────────────────────────────────────────
jetbrains: '"JetBrains Mono", monospace',
fira: '"Fira Code", monospace',
roboto: '"Roboto", sans-serif',
// ── Previously missing — both fonts are in the unconditional @import ───
// Without these entries, passing ?font=syncopate or ?font=spacegrotesk
// incorrectly triggers a duplicate dynamic Google Fonts fetch.
syncopate: '"Syncopate", sans-serif',
spacegrotesk: '"Space Grotesk", sans-serif',
'space grotesk': '"Space Grotesk", sans-serif', // handles spaced user input
// ── Aliases for common variations ───────────────────────────────────────
firacode: '"Fira Code", monospace', // alias: fira is the canonical key
'jetbrains mono': '"JetBrains Mono", monospace', // handles spaced user input
// ── Legacy keys for backward compatibility ──────────────────────────────
inter: '"Inter", sans-serif',
space: '"Space Grotesk", sans-serif', // old key for spacegrotesk
} as const;
export function resolveFont(sanitizedFont?: string | null): string | null {
if (!sanitizedFont) return null;
return (
FONT_MAP[sanitizedFont.toLowerCase() as keyof typeof FONT_MAP] ??
`"${sanitizedFont}", sans-serif`
);
}
function isBundledFont(sanitizedFont?: string | null): boolean {
if (!sanitizedFont) return false;
const fontKey = sanitizedFont.toLowerCase() as keyof typeof FONT_MAP;
return fontKey in FONT_MAP && fontKey !== 'inter';
}
// helpers
export function getSizeScale(size?: 'small' | 'medium' | 'large') {
if (size === 'small') return 400 / SVG_WIDTH;
if (size === 'large') return 800 / SVG_WIDTH;
return 1;
}
export function truncateUsername(username: string): string {
return username.length > 12 ? `${username.slice(0, 12)}...` : username;
}
export function deterministicRandom(seed: string): number {
let hash = 2166136261;
for (let i = 0; i < seed.length; i++) {
hash ^= seed.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0) / 4294967296;
}
function scaleTowerData(towerData: TowerData[], sf: number): TowerData[] {
if (sf === 1) return towerData;
return towerData.map((t) => ({
...t,
x: Math.round(t.x * sf),
y: Math.round(t.y * sf),
h: t.h * sf,
}));
}
type Scaler = (n: number) => number;
function createScaler(sf: number): Scaler {
return (n: number): number => Math.round(n * sf);
}
export function escapeXML(str: string): string {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
export function particleCount(count: number): number {
if (count === 0) return 0;
return Math.min(5, Math.max(3, Math.floor(count / 4)));
}
export interface TowerPaths {
left: string;
right: string;
top: string;
}
/**
* Builds the SVG path strings for the three faces of an isometric 3D tower.
*
* @param h - The height of the tower.
* @param scale - Optional scale factor (defaults to 1, which represents the standard 16x10 grid).
*/
export function buildTowerPaths(h: number, scale: number = 1): TowerPaths {
const tileHalfWidth = 16 * scale;
const tileHalfHeight = 10 * scale;
const tileFullHeight = 20 * scale;
return {
left: `M0 ${tileHalfHeight - h} L0 ${tileHalfHeight} L-${tileHalfWidth} 0 L-${tileHalfWidth} ${-h} Z`,
right: `M0 ${tileHalfHeight - h} L0 ${tileHalfHeight} L${tileHalfWidth} 0 L${tileHalfWidth} ${-h} Z`,
top: `M0 ${-h} L${tileHalfWidth} ${tileHalfHeight - h} L0 ${tileFullHeight - h} L-${tileHalfWidth} ${tileHalfHeight - h} Z`,
};
}
function generateParticles(
x: number,
y: number,
height: number,
count: number,
sf: number,
autoTheme: boolean = false,
color: string = '',
animate: boolean = true
): string {
let particles = '';
const numParticles = particleCount(count);
for (let i = 0; i < numParticles; i++) {
const themeSeed = autoTheme ? 'auto' : color;
const seed = `${x}:${y}:${height}:${themeSeed}:${count}:${i}`;
const offsetX = deterministicRandom(`${seed}:offsetX`) * 6 - 3;
const delay = deterministicRandom(`${seed}:delay`) * 1.5;
const fillAttr = autoTheme ? 'class="cp-accent-fill"' : `fill="${color}"`;
particles += `
<circle ${fillAttr} cx="${x + offsetX}" cy="${y - height}" r="${1.5 * sf}" opacity="1" pointer-events="none">
${
animate
? `
<animate attributeName="cy" from="${y - height}" to="${y - height - Math.round(20 * sf)}" dur="1.5s" begin="${delay}s" repeatCount="indefinite" />
<animate attributeName="opacity" from="1" to="0" dur="1.5s" begin="${delay}s" repeatCount="indefinite" />
`
: ''
}
</circle>
`;
}
return `<g class="heat-particles" pointer-events="none">${particles}</g>`;
}
export function getInteractiveTowerCSS(accentColorExpr: string): string {
return `
.interactive-tower { transition: transform 0.2s ease, filter 0.2s ease; cursor: pointer; }
.interactive-tower:hover { transform: translateY(-4px); filter: brightness(1.2) drop-shadow(0 4px 8px ${accentColorExpr}); }
`;
}
// ── Section helpers for generateSVG ──────────────────────────────────────
function renderHeader(
safeUser: string,
stats: StreakStats,
sf: number,
params: BadgeParams,
safeId: string
): string {
const unit = params.mode === 'loc' ? 'lines of code' : 'total contributions';
const entity = params.org ? 'Organization' : params.repo ? 'Repository' : 'User';
return `
<title id="cp-title-${safeId}">CommitPulse ${entity} Stats for ${safeUser}</title>
<desc id="cp-desc-${safeId}">
${safeUser} has ${stats.totalContributions} ${unit} and a longest streak of ${stats.longestStreak} days.
</desc>
${renderDefs(sf, params)}`;
}
/**
* Generates custom SVG gradient definitions from gradient_stops and gradient_dir parameters.
* Returns an object with gradient SVG elements and the gradient ID (or empty string if invalid).
* If custom stops are invalid or insufficient, returns { gradients: '', gradientId: '' }.
* Also stores the gradient ID on the params object for tower rendering to use.
*/
function generateCustomGradients(params: BadgeParams): { gradients: string; gradientId: string } {
const stops = parseGradientStops(params.gradient_stops);
// Require at least 2 valid colors for custom gradient
if (stops.length < 2) {
return { gradients: '', gradientId: '' };
}
const coords = getGradientCoordinates(params.gradient_dir);
// Create a deterministic gradient ID based on the color stops and direction
// This ensures consistent output and avoids random/duplicate IDs
const gradientSignature = `${stops.join('-')}-${params.gradient_dir || 'vertical'}`;
const gradientId = `custom-grad-${deterministicRandom(gradientSignature)
.toString()
.slice(2, 10)}`;
let gradients = '';
// Generate 4 gradient definitions (one for each intensity level)
// Each uses the same color stops but with different opacity progression
for (let i = 0; i < 4; i++) {
const level = i + 1;
const levelId = `${gradientId}-level-${level}`;
// Build the stop elements
let stopElements = '';
const stopCount = stops.length;
stops.forEach((color, stopIdx) => {
const offset = (stopIdx / (stopCount - 1)) * 100;
// Increase opacity with intensity level (0.4 to 0.8)
const baseOpacity = 0.4 + i * 0.2;
const stopOpacity = Math.min(1, baseOpacity + stopIdx * 0.1);
const colorHex = color.startsWith('#') ? color : `#${color}`;
stopElements += `
<stop offset="${offset}%" stop-color="${colorHex}" stop-opacity="${stopOpacity}" />`;
});
gradients += `
<linearGradient id="${levelId}" x1="${coords.x1}" y1="${coords.y1}" x2="${coords.x2}" y2="${coords.y2}">
${stopElements}
</linearGradient>`;
}
// Store the gradient ID on params for tower rendering to use
params.__customGradientId = gradientId;
return { gradients, gradientId };
}
function renderDefs(sf: number, params: BadgeParams): string {
const fs = (n: number): number => Math.round(n * sf * 10) / 10;
let gradients = '';
if (params.gradient) {
// Try to use custom gradient if gradient_stops is provided
const result = generateCustomGradients(params);
if (result.gradientId) {
// Custom gradient stops were valid and used
gradients = result.gradients;
} else {
// Fallback to default gradient behavior
const bgStr = params.bg || '0d1117';
const bgHex = bgStr.startsWith('#') ? bgStr : `#${bgStr}`;
if (params.autoTheme) {
for (let i = 0; i < 4; i++) {
const level = i + 1;
gradients += `
<linearGradient id="tower-grad-level-${level}" x1="0" y1="1" x2="0" y2="0">
<stop offset="0%" stop-color="var(--cp-bg)" stop-opacity="0.1" />
<stop offset="100%" stop-color="var(--cp-accent)" stop-opacity="${0.4 + i * 0.2}" />
</linearGradient>`;
}
} else {
const accent = params.accent;
const colors = Array.isArray(accent)
? [0, 1, 2, 3].map((i) => {
const idx = Math.min(i, accent.length - 1);
const c = accent[idx] || accent[accent.length - 1] || '00ffaa';
return c.startsWith('#') ? c : `#${c}`;
})
: [0, 1, 2, 3].map(() =>
String(accent).startsWith('#') ? String(accent) : `#${accent}`
);
colors.forEach((c, idx) => {
const level = idx + 1;
gradients += `
<linearGradient id="tower-grad-level-${level}" x1="0" y1="1" x2="0" y2="0">
<stop offset="0%" stop-color="${bgHex}" stop-opacity="0.1" />
<stop offset="100%" stop-color="${c}" stop-opacity="${0.4 + idx * 0.2}" />
</linearGradient>`;
});
}
}
}
const filterGlow =
params.glow !== false
? `<filter id="glow" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="${fs(
5
)}" result="blur" /><feComposite in="SourceGraphic" in2="blur" operator="over" /></filter>`
: '';
return `<defs>
${filterGlow}
${gradients}
</defs>`;
}
function renderStatsSection(
stats: StreakStats,
labels: BadgeLabels,
s: Scaler,
params: BadgeParams
): string {
const totalLabel = params.mode === 'loc' ? 'TOTAL LINES OF CODE' : labels.ANNUAL_SYNC_TOTAL;
const glowAttr = params.glow !== false ? ' filter="url(#glow)"' : '';
return `
<g transform="translate(${s(100)}, ${s(340)})" text-anchor="middle">
<text class="label">${labels.CURRENT_STREAK}</text>
<text y="${s(40)}" class="stats"${glowAttr}>${stats.currentStreak}</text>
</g>
<g transform="translate(${s(300)}, ${s(340)})" text-anchor="middle">
<text class="label">${totalLabel}</text>
<text y="${s(40)}" class="total-val"${glowAttr}>${stats.totalContributions}</text>
</g>
<g transform="translate(${s(500)}, ${s(340)})" text-anchor="middle">
<text class="label">${labels.PEAK_STREAK}</text>
<text y="${s(40)}" class="stats">${stats.longestStreak}</text>
</g>`;
}
function renderStyle(
selectedFont: string | null,
statsFont: string,
googleFontsImport: string,
text: string,
accent: string,
sf: number,
bg: string,
entrance: 'rise' | 'fade' | 'slide' | 'none' = 'rise'
): string {
const fs = (n: number) => Math.round(n * sf * 10) / 10;
const isLightBg = getLuminance(bg) > 0.5;
const labelFill = isLightBg ? text : accent;
const labelOpacity = isLightBg ? 0.8 : 0.7;
return `
<style>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code&family=JetBrains+Mono&family=Roboto&family=Syncopate:wght@400;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');
${googleFontsImport}
${getTowerAnimationCSS(entrance, sf)}
.scan-line {
animation: scan-sweep var(--scan-speed, 8s) linear infinite;
transform-box: fill-box;
transform-origin: center;
}
@keyframes scan-sweep {
from { transform: translateY(var(--scan-start, ${fs(0)}px)); }
to { transform: translateY(var(--scan-end, ${fs(240)}px)); }
}
.title { font-family: ${selectedFont || '"Syncopate", sans-serif'}; fill: ${text}; font-size: ${fs(18)}px; letter-spacing: ${fs(6)}px; font-weight: 400; opacity: 0.8; }
.stats { font-family: ${statsFont}; fill: ${text}; font-size: ${fs(42)}px; font-weight: 500; letter-spacing: 0; }
.total-val { font-family: ${statsFont}; fill: ${accent}; font-size: ${fs(24)}px; font-weight: 500; }
.label { font-family: "Roboto", sans-serif; fill: ${labelFill}; font-size: ${fs(11)}px; font-weight: 400; letter-spacing: ${fs(2)}px; opacity: ${labelOpacity}; }
@media (prefers-reduced-motion: reduce) {
.heat-particles { display: none; }
.scan-line {
animation: none !important;
transition: none !important;
transform: translateY(var(--scan-start, ${fs(0)}px)) !important;
}
}
.isometric-label { font-family: ${selectedFont || '"Roboto", sans-serif'}; font-size: ${fs(10)}px; font-weight: 400; letter-spacing: 1px; fill-opacity: 0.6; }
${getInteractiveTowerCSS(`${accent}66`)}
</style>`;
}
function renderTowers(
towerData: TowerData[],
params: BadgeParams,
accent: string | string[],
text: string,
sf: number,
isAutoTheme: boolean = false,
opacity: number = 1.0,
animate: boolean = true
): string {
let towers = '';
const opacityMultipliers = [0.4, 0.6, 0.8, 1.0];
for (const t of towerData) {
const isGhost = t.isGhost;
let strokeColor = '';
let leftRightFillAttr = '';
let topFillAttr = '';
if (isAutoTheme) {
strokeColor = isGhost ? 'var(--cp-text)' : 'var(--cp-accent)';
leftRightFillAttr = isGhost ? 'class="cp-text-fill"' : 'class="cp-accent-fill"';
topFillAttr = leftRightFillAttr;
} else {
const baseAccentColor = Array.isArray(accent)
? accent[accent.length - 1] || '00ffaa'
: accent || '00ffaa';
const accentColorHex = baseAccentColor.startsWith('#')
? baseAccentColor
: `#${baseAccentColor}`;
const textColorHex = text.startsWith('#') ? text : `#${text}`;
let resolvedSolidColor = isGhost ? textColorHex : accentColorHex;
if (!isGhost && t.intensityLevel > 0 && Array.isArray(accent)) {
const quartileIdx = Math.min(t.intensityLevel - 1, accent.length - 1);
const quartileColor = accent[quartileIdx] || accent[accent.length - 1] || '00ffaa';
resolvedSolidColor = quartileColor.startsWith('#') ? quartileColor : `#${quartileColor}`;
}
strokeColor = resolvedSolidColor;
leftRightFillAttr = `fill="${resolvedSolidColor}"`;
topFillAttr = leftRightFillAttr;
}
// opacity scalar: clamp 0.1–1.0, applied globally to all tower faces
let leftFaceOpacity = Math.round(t.faceOpacity.left * opacity * 100) / 100;
let rightFaceOpacity = Math.round(t.faceOpacity.right * opacity * 100) / 100;
let topFaceOpacity = Math.round(t.faceOpacity.top * opacity * 100) / 100;
if (!isGhost && t.intensityLevel > 0 && params.shading === true) {
const mult = opacityMultipliers[t.intensityLevel - 1];
leftFaceOpacity = Math.round(leftFaceOpacity * mult * 100) / 100;
rightFaceOpacity = Math.round(rightFaceOpacity * mult * 100) / 100;
topFaceOpacity = Math.round(topFaceOpacity * mult * 100) / 100;
}
let leftFillAttr = leftRightFillAttr;
let rightFillAttr = leftRightFillAttr;
let finalTopFillAttr = topFillAttr;
if (!isGhost && t.intensityLevel > 0 && params.gradient === true) {
// Use custom gradient ID if available, otherwise use default gradient ID
const customGradId = params.__customGradientId;
const gradId = customGradId
? `${customGradId}-level-${t.intensityLevel}`
: `tower-grad-level-${t.intensityLevel}`;
leftFillAttr = `fill="url(#${gradId})"`;
rightFillAttr = `fill="url(#${gradId})"`;
if (isAutoTheme) {
finalTopFillAttr = 'class="cp-accent-fill"';
} else {
const capIdx = Math.min(t.intensityLevel - 1, accent.length - 1);
const baseAccentColor = Array.isArray(accent)
? accent[capIdx] || accent[accent.length - 1]
: accent;
const capColor = baseAccentColor.startsWith('#') ? baseAccentColor : `#${baseAccentColor}`;
finalTopFillAttr = `fill="${capColor}"`;
}
}
const strokeAttr = isGhost
? `stroke="${strokeColor}" stroke-opacity="${t.strokeOpacity}" stroke-width="${t.strokeWidth}"`
: '';
let leftStrokeAttr = strokeAttr;
let rightStrokeAttr = strokeAttr;
let topStrokeAttr = strokeAttr;
if (t.isToday && t.contributionCount === 0) {
const todayStrokeColor = isAutoTheme ? 'var(--cp-accent)' : strokeColor;
leftStrokeAttr = isGhost
? `stroke="${strokeColor}" stroke-opacity="${t.strokeOpacity}" stroke-width="${t.strokeWidth}"`
: '';
rightStrokeAttr = leftStrokeAttr;
topStrokeAttr = `stroke="${todayStrokeColor}" stroke-opacity="0.8" stroke-width="${1.2 * sf}"`;
}
const delay = ((t.row + t.col) * 0.015).toFixed(3);
const metric =
t.contributionCount === 0 ? 'Rest day' : t.intensityLevel === 4 ? 'Peak day' : 'Active day';
const paths = buildTowerPaths(t.h, 1);
towers += `
<g transform="translate(${t.x}, ${t.y})">
<g class="cp-tower interactive-tower" data-date="${escapeXML(t.date)}" data-count="${t.contributionCount}" data-metric="${escapeXML(metric)}" style="animation-delay: ${delay}s;">
${animate && t.isToday ? '<animate attributeName="opacity" values="1;0.4;1" dur="1.5s" repeatCount="indefinite" />' : ''}
<title>${escapeXML(t.tooltip)}</title>
<path d="${paths.left}" ${leftFillAttr} fill-opacity="${leftFaceOpacity}" ${leftStrokeAttr} />
<path d="${paths.right}" ${rightFillAttr} fill-opacity="${rightFaceOpacity}" ${rightStrokeAttr} />
<path d="${paths.top}" ${finalTopFillAttr} fill-opacity="${topFaceOpacity}" ${topStrokeAttr} />
${t.contributionCount > 5 ? `<path d="${paths.top}" fill="white" fill-opacity="0.2" />` : ''}
</g>
</g>`;
if (t.contributionCount >= 10 && !params.disable_particles) {
const pIdx = Math.min(t.intensityLevel - 1, accent.length - 1);
const pColorResolved = Array.isArray(accent)
? accent[pIdx] || accent[accent.length - 1] || '00ffaa'
: accent || '00ffaa';
const pColor = isAutoTheme
? ''
: pColorResolved.startsWith('#')
? pColorResolved
: `#${pColorResolved}`;
towers += generateParticles(
t.x,
t.y,
t.h,
t.contributionCount,
sf,
isAutoTheme,
pColor,
animate
);
}
}
return towers;
}
function renderRadarScan(
speed: string,
sf: number,
accentColor: string,
autoTheme: boolean
): string {
const s = createScaler(sf);
const fillAttr = autoTheme
? 'class="cp-accent-fill scan-line"'
: `fill="${accentColor}" class="cp-accent-fill scan-line"`;
return `<rect
x="${s(100)}"
y="${s(80)}"
width="${s(400)}"
height="${s(1)}"
${fillAttr}
fill-opacity="0.3"
style="--scan-speed: ${speed}; --scan-start: ${s(0)}px; --scan-end: ${s(240)}px;"
/>`;
}
function renderFooter(
stats: StreakStats,
params: BadgeParams,
labels: ReturnType<typeof getLabels>,
safeUser: string,
accent: string,
sf: number
): string {
const s = createScaler(sf);
return `
${!params.hide_stats ? renderStatsSection(stats, labels, s, params) : ''}
${!params.hide_title ? `<text x="${s(300)}" y="${s(50)}" text-anchor="middle" class="title">${truncateUsername(safeUser).toUpperCase()}${params.isOfflineFallback ? '<tspan fill="#ff9f43" font-size="10px" font-weight="bold"> [STALE CACHE]</tspan>' : ''}</text>` : ''}
<rect
x="${s(100)}"
y="${s(80)}"
width="${s(400)}"
height="${s(1)}"
class="cp-accent-fill scan-line"
fill-opacity="0.3"
style="--scan-speed: ${params.speed || '8s'}; --scan-start: ${s(0)}px; --scan-end: ${s(240)}px;"
/>`;
}
const MONTH_NAMES = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
// Layout constants for 3D isometric label positioning
const ISOMETRIC_VERTICAL_OFFSET = 20;
const MONTH_LABEL_ROW_OFFSET = 7.2;
const WEEKDAY_LABEL_COL_OFFSET = -1.2;
function renderIsometricLabels(
calendar: ContributionCalendar,
params: BadgeParams,
color: string,
sf: number
): string {
if (!params.labels) return '';
const s = createScaler(sf);
let elements = '';
const weeks = calendar.weeks.slice(-14);
const monthLabels: { text: string; col: number }[] = [];
let prevMonthStr = '';
weeks.forEach((week, i) => {
if (week.contributionDays.length === 0) return;
const firstDay = week.contributionDays[0];
const monthNum = parseInt(firstDay.date.substring(5, 7), 10);
const monthStr = MONTH_NAMES[monthNum - 1];
if (i === 0 || monthStr !== prevMonthStr) {
monthLabels.push({ text: monthStr, col: i });
prevMonthStr = monthStr;
}
});
const labelColorHex = params.labelColor ? `#${params.labelColor}` : color;
monthLabels.forEach((label) => {
const tx = s(GRID_ORIGIN_X + (label.col - MONTH_LABEL_ROW_OFFSET) * TILE_WIDTH_HALF + 8);
const ty =
s(
GRID_ORIGIN_Y +
(label.col + MONTH_LABEL_ROW_OFFSET) * TILE_HEIGHT_HALF +
ISOMETRIC_VERTICAL_OFFSET
) + Math.round(20 * sf);
elements += `
<text x="${tx}" y="${ty}" text-anchor="middle" fill="${labelColorHex}" class="isometric-label">${label.text}</text>`;
});
const weekdays = [
{ text: 'Mon', row: 1 },
{ text: 'Wed', row: 3 },
{ text: 'Fri', row: 5 },
];
weekdays.forEach((day) => {
const tx = s(GRID_ORIGIN_X + (WEEKDAY_LABEL_COL_OFFSET - day.row) * TILE_WIDTH_HALF);
const ty =
s(
GRID_ORIGIN_Y +
(WEEKDAY_LABEL_COL_OFFSET + day.row) * TILE_HEIGHT_HALF +
ISOMETRIC_VERTICAL_OFFSET
) + Math.round(20 * sf);
elements += `
<text x="${tx}" y="${ty}" text-anchor="end" fill="${labelColorHex}" class="isometric-label">${day.text}</text>`;
});
return `<g class="isometric-labels">${elements}</g>`;
}
function renderMilestoneBadges(stats: StreakStats, params: BadgeParams, sf: number): string {
if (!params.badges) return '';
const badges = [];
if (stats.longestStreak >= 365) badges.push({ text: '🔥 Unstoppable', color: '#FFD700' });
else if (stats.longestStreak >= 100) badges.push({ text: '💯 Century Club', color: '#C0C0C0' });
if (stats.totalContributions >= 5000) badges.push({ text: '🌟 Elite', color: '#b9f2ff' });
else if (stats.totalContributions >= 1000) badges.push({ text: '🚀 1K Club', color: '#cd7f32' });
else if (stats.totalContributions >= 500)
badges.push({ text: '⭐ 500+ Commits', color: '#cd7f32' });
if (badges.length === 0) return '';
const fs = (n: number) => Math.round(n * sf * 10) / 10;
const s = createScaler(sf);
let elements = '';
const badgeWidth = 110;
const spacing = 10;
const totalWidth = badges.length * badgeWidth + (badges.length - 1) * spacing;
const startX = 300 - totalWidth / 2 + badgeWidth / 2;
badges.forEach((b, i) => {
const cx = s(startX + i * (badgeWidth + spacing));
const cy = s(400);
const glowAttr = params.glow !== false ? ' filter="url(#glow)"' : '';
elements += `
<g transform="translate(${cx}, ${cy})" class="badge-group">
<rect x="${s(-badgeWidth / 2)}" y="${s(-12)}" width="${s(badgeWidth)}" height="${s(24)}" rx="${s(12)}" fill="${b.color}" fill-opacity="0.1" stroke="${b.color}" stroke-opacity="0.5" stroke-width="1" />
<text y="${s(4)}" text-anchor="middle" font-family='"Roboto", sans-serif' font-size="${fs(11)}px" font-weight="bold" fill="${b.color}" ${glowAttr}>${b.text}</text>
</g>
`;
});
return `<g class="milestone-badges">${elements}</g>`;
}
// ── Main static-theme renderer ────────────────────────────────────────────
export function generateSVG(
stats: StreakStats,
params: BadgeParams,
calendar: ContributionCalendar
): string {
if (params.autoTheme) return generateAutoThemeSVG(stats, params, calendar);
const animate = params.animate ?? true;
const safeUser = escapeXML(params.user || 'GitHub User');
const bg = `#${sanitizeHexColor(params.bg, '0d1117')}`;
const accent = Array.isArray(params.accent)
? params.accent.map((c) => sanitizeHexColor(c, '00ffaa'))
: sanitizeHexColor(params.accent, '00ffaa');
const text = `#${sanitizeHexColor(params.text, 'ffffff')}`;
const borderAttr = params.border ? `stroke="#${params.border}" stroke-width="2"` : '';
const sanitizedFont = sanitizeFont(params.font);
const selectedFont = resolveFont(sanitizedFont);
const isPredefinedFont = isBundledFont(sanitizedFont);
const statsFont = selectedFont || '"Space Grotesk", sans-serif';
const googleFontUrlPart =
sanitizedFont && !isPredefinedFont ? sanitizeGoogleFontUrl(sanitizedFont) : null;
const googleFontsImport = googleFontUrlPart
? `@import url('https://fonts.googleapis.com/css2?family=${googleFontUrlPart}&display=swap');`
: '';
const sf = getSizeScale(params.size);
const radius = sanitizeRadius(params.radius, 8) * sf;
const labels = getLabels(params.lang);
const W = Math.round(SVG_WIDTH * sf);
const H = Math.round(SVG_HEIGHT * sf);
const towerData = scaleTowerData(
computeTowers(calendar, params.scale, stats.todayDate, params.mode),
sf
);
if (params.gradient) {
generateCustomGradients(params);
}
const towers = renderTowers(
towerData,
params,
accent,
text,
sf,
false,
params.opacity ?? 1.0,
animate
);
const mainAccent = Array.isArray(accent)
? accent[accent.length - 1] || '00ffaa'
: accent || '00ffaa';
const mainAccentHex = mainAccent.startsWith('#') ? mainAccent : `#${mainAccent}`;
const safeId = safeUser.replace(/[^a-zA-Z0-9-]/g, '_').toLowerCase();
return `
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 ${W} ${H}" fill="none" role="img" aria-labelledby="cp-title-${safeId}" aria-describedby="cp-desc-${safeId}">
${renderHeader(safeUser, stats, sf, params, safeId)}
${renderStyle(selectedFont, statsFont, googleFontsImport, text, mainAccentHex, sf, bg, params.entrance || 'rise')}
<rect width="${W}" height="${H}" rx="${radius}" fill="${params.hideBackground ? 'transparent' : bg}" ${borderAttr} />
<g id="cp-towers" style="transform-origin: center; transform-box: fill-box;" transform="translate(0, ${Math.round(20 * sf)})">${towers}</g>
${renderIsometricLabels(calendar, params, text, sf)}
${renderFooter(stats, params, labels, safeUser, mainAccentHex, sf)}
${renderMilestoneBadges(stats, params, sf)}
</svg>`;
}
function generateAutoThemeSVG(
stats: StreakStats,
params: BadgeParams,
calendar: ContributionCalendar
): string {
const light = AUTO_THEME_LIGHT;
const dark = AUTO_THEME_DARK;
const lightLabelFill = getLuminance(light.bg) > 0.5 ? 'var(--cp-text)' : 'var(--cp-accent)';
const lightLabelOpacity = getLuminance(light.bg) > 0.5 ? '0.8' : '0.7';
const darkLabelFill = getLuminance(dark.bg) > 0.5 ? 'var(--cp-text)' : 'var(--cp-accent)';
const darkLabelOpacity = getLuminance(dark.bg) > 0.5 ? '0.8' : '0.7';
const safeUser = escapeXML(params.user || 'GitHub User');
const sanitizedFont = sanitizeFont(params.font);
const selectedFont = resolveFont(sanitizedFont);
const statsFont = selectedFont || '"Space Grotesk", sans-serif';
const googleFontUrlPart = sanitizedFont ? sanitizeGoogleFontUrl(sanitizedFont) : null;
const googleFontsImport = googleFontUrlPart
? `@import url('https://fonts.googleapis.com/css2?family=${googleFontUrlPart}&display=swap');`
: '';
const sf = getSizeScale(params.size);
const radius = sanitizeRadius(params.radius, 8) * sf;
const labels = getLabels(params.lang);
const W = Math.round(SVG_WIDTH * sf);
const H = Math.round(SVG_HEIGHT * sf);
const towerData = scaleTowerData(
computeTowers(calendar, params.scale, stats.todayDate, params.mode),
sf
);
const towers = renderTowers(towerData, params, '', '', sf, true, params.opacity ?? 1.0);
const s = createScaler(sf);
const fs = (n: number): number => Math.round(n * sf * 10) / 10;
const safeId = safeUser.replace(/[^a-zA-Z0-9-]/g, '_').toLowerCase();
return `
<svg
xmlns="http://www.w3.org/2000/svg"
width="100%"
viewBox="0 0 ${W} ${H}"
fill="none"
role="img"
aria-labelledby="cp-title-${safeId}"
aria-describedby="cp-desc-${safeId}"
>
${renderHeader(safeUser, stats, sf, params, safeId)}
<style>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code&family=JetBrains+Mono&family=Roboto&family=Syncopate:wght@400;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');
${googleFontsImport}
:root { --cp-bg: #${light.bg}; --cp-text: #${light.text}; --cp-accent: #${light.accent}; --cp-label-fill: ${lightLabelFill}; --cp-label-opacity: ${lightLabelOpacity}; }
@media (prefers-color-scheme: dark) { :root { --cp-bg: #${dark.bg}; --cp-text: #${dark.text}; --cp-accent: #${dark.accent}; --cp-label-fill: ${darkLabelFill}; --cp-label-opacity: ${darkLabelOpacity}; } }
.cp-bg-fill { fill: var(--cp-bg); } .cp-text-fill { fill: var(--cp-text); color: var(--cp-text); } .cp-accent-fill { fill: var(--cp-accent); color: var(--cp-accent); }
${getTowerAnimationCSS(params.entrance || 'rise', sf)}
.scan-line {
animation: scan-sweep var(--scan-speed, 8s) linear infinite;
transform-box: fill-box;
transform-origin: center;
}
@keyframes scan-sweep {
from { transform: translateY(var(--scan-start, ${s(0)}px)); }
to { transform: translateY(var(--scan-end, ${s(240)}px)); }
}
.title { font-family: ${selectedFont || '"Syncopate", sans-serif'}; fill: var(--cp-text); font-size: ${fs(18)}px; letter-spacing: ${fs(6)}px; font-weight: 400; opacity: 0.8; }
.stats { font-family: ${statsFont}; fill: var(--cp-text); font-size: ${fs(42)}px; font-weight: 500; letter-spacing: 0; }
.total-val { font-family: ${statsFont}; fill: var(--cp-accent); font-size: ${fs(24)}px; font-weight: 500; }
.label { font-family: "Roboto", sans-serif; fill: var(--cp-label-fill); font-size: ${fs(11)}px; font-weight: 400; letter-spacing: ${fs(2)}px; opacity: var(--cp-label-opacity); }
.isometric-label { font-family: ${selectedFont || '"Roboto", sans-serif'}; font-size: ${fs(10)}px; font-weight: 400; letter-spacing: 1px; fill-opacity: 0.6; }
${getInteractiveTowerCSS('var(--cp-accent)')}
@media (prefers-reduced-motion: reduce) {
.heat-particles { display: none; }
.scan-line {
animation: none !important;
transition: none !important;
transform: translateY(var(--scan-start, ${s(0)}px)) !important;
}
}
</style>
<rect width="${W}" height="${H}" rx="${radius}" ${params.hideBackground ? 'fill="transparent"' : 'class="cp-bg-fill"'} />
<g id="cp-towers" style="transform-origin: center; transform-box: fill-box;" transform="translate(0, ${s(20)})">
${towers}
</g>
${renderIsometricLabels(calendar, params, 'var(--cp-text)', sf)}
${!params.hide_stats ? renderStatsSection(stats, labels, s, params) : ''}
${
!params.hide_title
? `<text x="${s(300)}" y="${s(50)}" text-anchor="middle" class="title">${truncateUsername(safeUser).toUpperCase()}${params.isOfflineFallback ? '<tspan fill="#ff9f43" font-size="10px" font-weight="bold"> [STALE CACHE]</tspan>' : ''}</text>`
: ''
}
${renderRadarScan(params.speed || '8s', sf, '', true)}
${renderMilestoneBadges(stats, params, sf)}
</svg>
`;
}
export function generateMonthlySVG(stats: MonthlyStats, params: BadgeParams): string {
if (params.autoTheme) {
return generateAutoThemeMonthlySVG(stats, params);
}
const safeUser = escapeXML(params.user || 'GitHub User');
const bg = `#${sanitizeHexColor(params.bg, '0d1117')}`;
const rawAccent = Array.isArray(params.accent)
? params.accent[params.accent.length - 1]
: params.accent;
const accent = `#${sanitizeHexColor(rawAccent, '00ffaa')}`;
const text = `#${sanitizeHexColor(params.text, 'ffffff')}`;
const sanitizedFont = sanitizeFont(params.font);
const selectedFont = resolveFont(sanitizedFont);
const isPredefinedFont = isBundledFont(sanitizedFont);
const statsFont = selectedFont || '"Space Grotesk", sans-serif';
const radius = sanitizeRadius(params.radius, 8);
const labels = getLabels(params.lang);
const width = params.width || 300;
const height = params.height || 120;
const googleFontUrlPart =
sanitizedFont && !isPredefinedFont ? sanitizeGoogleFontUrl(sanitizedFont) : null;
const googleFontsImport = googleFontUrlPart
? `@import url('https://fonts.googleapis.com/css2?family=${googleFontUrlPart}&display=swap');`
: '';
const commitsLabel = params.mode === 'loc' ? 'LINES THIS MONTH' : labels.COMMITS_THIS_MONTH;
const deltaUnit = params.mode === 'loc' ? 'lines' : 'commits';
let deltaText = '';
if (params.delta_format === 'absolute') {
deltaText =
stats.deltaAbsolute > 0
? `+${stats.deltaAbsolute} ${deltaUnit}`
: stats.deltaAbsolute === 0
? `0 ${deltaUnit}`
: `${stats.deltaAbsolute} ${deltaUnit}`;
} else if (params.delta_format === 'both') {
deltaText =
stats.deltaPercentage === null
? `N/A (${stats.deltaAbsolute > 0 ? '+' : ''}${stats.deltaAbsolute})`
: stats.deltaPercentage > 0
? `+${stats.deltaPercentage}% (+${stats.deltaAbsolute})`
: stats.deltaPercentage < 0
? `${stats.deltaPercentage}% (${stats.deltaAbsolute})`
: `0% (${stats.deltaAbsolute > 0 ? '+' : ''}${stats.deltaAbsolute})`;
} else {
deltaText =
stats.deltaPercentage === null
? 'N/A'
: stats.deltaPercentage > 0
? `+${stats.deltaPercentage}%`
: stats.deltaPercentage < 0
? `${stats.deltaPercentage}%`
: `0%`;
}
// Resolve negative color
let negativeColor = '#ff4444';
const cleanBg = sanitizeHexColor(params.bg, '0d1117');
const matchedTheme = Object.values(themes).find(
(t) => t.bg.toLowerCase() === cleanBg.toLowerCase()
);
if (matchedTheme && matchedTheme.negative) {
negativeColor = `#${matchedTheme.negative}`;
} else {
// Dynamic fallback based on background luminance
const luminance = getLuminance(cleanBg);
negativeColor = luminance > 0.5 ? '#cf222e' : '#f85149';
}
const deltaColor = stats.deltaAbsolute >= 0 ? accent : negativeColor;
const safeId = safeUser.replace(/[^a-zA-Z0-9-]/g, '_').toLowerCase();
return `
<svg
xmlns="http://www.w3.org/2000/svg"
width="${width}"
height="${height}"
viewBox="0 0 ${width} ${height}"
fill="none"
role="img"
aria-labelledby="cp-title-${safeId}"
aria-describedby="cp-desc-${safeId}"
>
<title id="cp-title-${safeId}">Monthly Stats for ${safeUser}</title>
<desc id="cp-desc-${safeId}">Monthly stats for ${safeUser}: ${stats.currentMonthTotal} ${commitsLabel} vs previous month delta of ${deltaText}.</desc>
<style>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code&family=JetBrains+Mono&family=Roboto&family=Syncopate:wght@400;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');
${googleFontsImport}
.title { font-family: ${selectedFont || '"Syncopate", sans-serif'}; fill: ${text}; font-size: 14px; letter-spacing: 2px; font-weight: 400; opacity: 0.8; }
.stats { font-family: ${statsFont}; fill: ${accent}; font-size: 36px; font-weight: 600; letter-spacing: 0; }
.label { font-family: "Roboto", sans-serif; fill: ${text}; font-size: 10px; font-weight: 400; letter-spacing: 1px; opacity: 0.7; }
.delta { font-family: "Roboto", sans-serif; fill: ${deltaColor}; font-size: 12px; font-weight: 500; }
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}
</style>
<rect width="${width}" height="${height}" rx="${radius}" fill="${params.hideBackground ? 'transparent' : bg}" />
<text x="20" y="40" class="title">${stats.currentMonthName.toUpperCase()}</text>
<text x="20" y="85" class="stats">${stats.currentMonthTotal}</text>
<text x="20" y="105" class="label">${commitsLabel}</text>
<g transform="translate(${width - 20}, 80)" text-anchor="end">
<text class="delta">${deltaText}</text>
<text y="20" class="label">${labels.VS_LAST_MONTH}</text>
</g>
</svg>
`;
}
export function generateWrappedSVG(
stats: import('../../types/dashboard').WrappedStats,
params: BadgeParams,
year: string,
calendar: ContributionCalendar
): string {
const safeUser = escapeXML(params.user || 'GitHub User');
const bg = `#${sanitizeHexColor(params.bg, '0d1117')}`;
const rawAccent = Array.isArray(params.accent)
? params.accent[params.accent.length - 1]
: params.accent;
const accent = `#${sanitizeHexColor(rawAccent, '00ffaa')}`;