-
-
Notifications
You must be signed in to change notification settings - Fork 23.6k
/
Copy pathstats-card.js
322 lines (300 loc) · 8.19 KB
/
stats-card.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
// @ts-check
import { Card } from "../common/Card.js";
import { I18n } from "../common/I18n.js";
import { icons } from "../common/icons.js";
import {
clampValue,
flexLayout,
getCardColors,
kFormatter,
measureText,
} from "../common/utils.js";
import { getStyles } from "../getStyles.js";
import { statCardLocales } from "../translations.js";
/**
* Create a stats card text item.
*
* @param {object[]} createTextNodeParams Object that contains the createTextNode parameters.
* @param {string} createTextNodeParams.label The label to display.
* @param {string} createTextNodeParams.value The value to display.
* @param {string} createTextNodeParams.id The id of the stat.
* @param {number} createTextNodeParams.index The index of the stat.
* @param {boolean} createTextNodeParams.showIcons Whether to show icons.
* @param {number} createTextNodeParams.shiftValuePos Number of pixels the value has to be shifted to the right.
* @param {boolean} createTextNodeParams.bold Whether to bold the label.
* @returns
*/
const createTextNode = ({
icon,
label,
value,
id,
index,
showIcons,
shiftValuePos,
bold,
}) => {
const kValue = kFormatter(value);
const staggerDelay = (index + 3) * 150;
const labelOffset = showIcons ? `x="25"` : "";
const iconSvg = showIcons
? `
<svg data-testid="icon" class="icon" viewBox="0 0 16 16" version="1.1" width="16" height="16">
${icon}
</svg>
`
: "";
return `
<g class="stagger" style="animation-delay: ${staggerDelay}ms" transform="translate(25, 0)">
${iconSvg}
<text class="stat ${
bold ? " bold" : "not_bold"
}" ${labelOffset} y="12.5">${label}:</text>
<text
class="stat ${bold ? " bold" : "not_bold"}"
x="${(showIcons ? 140 : 120) + shiftValuePos}"
y="12.5"
data-testid="${id}"
>${kValue}</text>
</g>
`;
};
/**
* Renders the stats card.
*
* @param {Partial<import('../fetchers/types').StatsData>} stats The stats data.
* @param {Partial<import("./types").StatCardOptions>} options The card options.
* @returns {string} The stats card SVG object.
*/
const renderStatsCard = (stats = {}, options = { hide: [] }) => {
const {
name,
totalStars,
totalCommits,
totalIssues,
totalPRs,
contributedTo,
rank,
} = stats;
const {
hide = [],
show_icons = false,
hide_title = false,
hide_border = false,
card_width,
hide_rank = false,
include_all_commits = false,
line_height = 25,
title_color,
ring_color,
icon_color,
text_color,
text_bold = true,
bg_color,
theme = "default",
custom_title,
border_radius,
border_color,
locale,
disable_animations = false,
} = options;
const lheight = parseInt(String(line_height), 10);
// returns theme based colors with proper overrides and defaults
const { titleColor, iconColor, textColor, bgColor, borderColor, ringColor } =
getCardColors({
title_color,
text_color,
icon_color,
bg_color,
border_color,
ring_color,
theme,
});
const apostrophe = ["x", "s"].includes(name.slice(-1).toLocaleLowerCase())
? ""
: "s";
const i18n = new I18n({
locale,
translations: statCardLocales({ name, apostrophe }),
});
// Meta data for creating text nodes with createTextNode function
const STATS = {
stars: {
icon: icons.star,
label: i18n.t("statcard.totalstars"),
value: totalStars,
id: "stars",
},
commits: {
icon: icons.commits,
label: `${i18n.t("statcard.commits")}${
include_all_commits ? "" : ` (${new Date().getFullYear()})`
}`,
value: totalCommits,
id: "commits",
},
prs: {
icon: icons.prs,
label: i18n.t("statcard.prs"),
value: totalPRs,
id: "prs",
},
issues: {
icon: icons.issues,
label: i18n.t("statcard.issues"),
value: totalIssues,
id: "issues",
},
contribs: {
icon: icons.contribs,
label: i18n.t("statcard.contribs") + " (last year)",
value: contributedTo,
id: "contribs",
},
};
const longLocales = [
"cn",
"es",
"fr",
"pt-br",
"ru",
"uk-ua",
"id",
"my",
"pl",
"de",
"nl",
"zh-tw",
];
const isLongLocale = longLocales.includes(locale) === true;
// filter out hidden stats defined by user & create the text nodes
const statItems = Object.keys(STATS)
.filter((key) => !hide.includes(key))
.map((key, index) =>
// create the text nodes, and pass index so that we can calculate the line spacing
createTextNode({
...STATS[key],
index,
showIcons: show_icons,
shiftValuePos: 79.01 + (isLongLocale ? 50 : 0),
bold: text_bold,
}),
);
// Calculate the card height depending on how many items there are
// but if rank circle is visible clamp the minimum height to `150`
let height = Math.max(
45 + (statItems.length + 1) * lheight,
hide_rank ? 0 : 150,
);
// the better user's score the the rank will be closer to zero so
// subtracting 100 to get the progress in 100%
const progress = 100 - rank.score;
const cssStyles = getStyles({
titleColor,
ringColor,
textColor,
iconColor,
show_icons,
progress,
});
const calculateTextWidth = () => {
return measureText(custom_title ? custom_title : i18n.t("statcard.title"));
};
/*
When hide_rank=true, the minimum card width is 270 px + the title length and padding.
When hide_rank=false, the minimum card_width is 340 px + the icon width (if show_icons=true).
Numbers are picked by looking at existing dimensions on production.
*/
const iconWidth = show_icons ? 16 : 0;
const minCardWidth = hide_rank
? clampValue(50 /* padding */ + calculateTextWidth() * 2, 270, Infinity)
: 340 + iconWidth;
const defaultCardWidth = hide_rank ? 270 : 495;
let width = isNaN(card_width) ? defaultCardWidth : card_width;
if (width < minCardWidth) {
width = minCardWidth;
}
const card = new Card({
customTitle: custom_title,
defaultTitle: i18n.t("statcard.title"),
width,
height,
border_radius,
colors: {
titleColor,
textColor,
iconColor,
bgColor,
borderColor,
},
});
card.setHideBorder(hide_border);
card.setHideTitle(hide_title);
card.setCSS(cssStyles);
if (disable_animations) card.disableAnimations();
/**
* Calculates the right rank circle translation values such that the rank circle
* keeps respecting the padding.
*
* width > 450: The default left padding of 50 px will be used.
* width < 450: The left and right padding will shrink equally.
*
* @returns {number} - Rank circle translation value.
*/
const calculateRankXTranslation = () => {
if (width < 450) {
return width - 95 + (45 * (450 - 340)) / 110;
} else {
return width - 95;
}
};
// Conditionally rendered elements
const rankCircle = hide_rank
? ""
: `<g data-testid="rank-circle"
transform="translate(${calculateRankXTranslation()}, ${
height / 2 - 50
})">
<circle class="rank-circle-rim" cx="-10" cy="8" r="40" />
<circle class="rank-circle" cx="-10" cy="8" r="40" />
<g class="rank-text">
<text
x="-5"
y="3"
alignment-baseline="central"
dominant-baseline="central"
text-anchor="middle"
>
${rank.level}
</text>
</g>
</g>`;
// Accessibility Labels
const labels = Object.keys(STATS)
.filter((key) => !hide.includes(key))
.map((key) => {
if (key === "commits") {
return `${i18n.t("statcard.commits")} ${
include_all_commits ? "" : `in ${new Date().getFullYear()}`
} : ${totalStars}`;
}
return `${STATS[key].label}: ${STATS[key].value}`;
})
.join(", ");
card.setAccessibilityLabel({
title: `${card.title}, Rank: ${rank.level}`,
desc: labels,
});
return card.render(`
${rankCircle}
<svg x="0" y="0">
${flexLayout({
items: statItems,
gap: lheight,
direction: "column",
}).join("")}
</svg>
`);
};
export { renderStatsCard };
export default renderStatsCard;