-
-
Notifications
You must be signed in to change notification settings - Fork 23.7k
/
Copy pathtop-languages-card.js
398 lines (365 loc) · 10.7 KB
/
top-languages-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
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
// @ts-check
import { Card } from "../common/Card.js";
import { createProgressNode } from "../common/createProgressNode.js";
import { I18n } from "../common/I18n.js";
import {
chunkArray,
clampValue,
flexLayout,
getCardColors,
lowercaseTrim,
measureText,
} from "../common/utils.js";
import { langCardLocales } from "../translations.js";
const DEFAULT_CARD_WIDTH = 300;
const MIN_CARD_WIDTH = 230;
const DEFAULT_LANGS_COUNT = 5;
const DEFAULT_LANG_COLOR = "#858585";
const CARD_PADDING = 25;
/**
* @typedef {import("../fetchers/types").Lang} Lang
*/
/**
* Retrieves the programming language whose name is the longest.
*
* @param {Lang[]} arr Array of programming languages.
* @returns {Object} Longest programming language object.
*/
const getLongestLang = (arr) =>
arr.reduce(
(savedLang, lang) =>
lang.name.length > savedLang.name.length ? lang : savedLang,
{ name: "", size: null, color: "" },
);
/**
* Creates a node to display usage of a programming language in percentage
* using text and a horizontal progress bar.
*
* @param {object} props Function properties.
* @param {number} props.width The card width
* @param {string} props.name Name of the programming language.
* @param {string} props.color Color of the programming language.
* @param {string} props.progress Usage of the programming language in percentage.
* @param {number} props.index Index of the programming language.
* @returns {string} Programming language SVG node.
*/
const createProgressTextNode = ({ width, color, name, progress, index }) => {
const staggerDelay = (index + 3) * 150;
const paddingRight = 95;
const progressTextX = width - paddingRight + 10;
const progressWidth = width - paddingRight;
return `
<g class="stagger" style="animation-delay: ${staggerDelay}ms">
<text data-testid="lang-name" x="2" y="15" class="lang-name">${name}</text>
<text x="${progressTextX}" y="34" class="lang-name">${progress}%</text>
${createProgressNode({
x: 0,
y: 25,
color,
width: progressWidth,
progress,
progressBarBackgroundColor: "#ddd",
delay: staggerDelay + 300,
})}
</g>
`;
};
/**
* Creates a text only node to display usage of a programming language in percentage.
*
* @param {object} props Function properties.
* @param {Lang} props.lang Programming language object.
* @param {number} props.totalSize Total size of all languages.
* @param {boolean} props.hideProgress Whether to hide percentage.
* @param {number} props.index Index of the programming language.
* @returns {string} Compact layout programming language SVG node.
*/
const createCompactLangNode = ({ lang, totalSize, hideProgress, index }) => {
const percentage = ((lang.size / totalSize) * 100).toFixed(2);
const staggerDelay = (index + 3) * 150;
const color = lang.color || "#858585";
return `
<g class="stagger" style="animation-delay: ${staggerDelay}ms">
<circle cx="5" cy="6" r="5" fill="${color}" />
<text data-testid="lang-name" x="15" y="10" class='lang-name'>
${lang.name} ${hideProgress ? "" : percentage + "%"}
</text>
</g>
`;
};
/**
* Creates compact layout of text only language nodes.
*
* @param {object[]} props Function properties.
* @param {Lang[]} props.langs Array of programming languages.
* @param {number} props.totalSize Total size of all languages.
* @param {boolean} props.hideProgress Whether to hide percentage.
* @returns {string} Programming languages SVG node.
*/
const createLanguageTextNode = ({ langs, totalSize, hideProgress }) => {
const longestLang = getLongestLang(langs);
const chunked = chunkArray(langs, langs.length / 2);
const layouts = chunked.map((array) => {
// @ts-ignore
const items = array.map((lang, index) =>
createCompactLangNode({
lang,
totalSize,
hideProgress,
index,
}),
);
return flexLayout({
items,
gap: 25,
direction: "column",
}).join("");
});
const percent = ((longestLang.size / totalSize) * 100).toFixed(2);
const minGap = 150;
const maxGap = 20 + measureText(`${longestLang.name} ${percent}%`, 11);
return flexLayout({
items: layouts,
gap: maxGap < minGap ? minGap : maxGap,
}).join("");
};
/**
* Renders layout to display user's most frequently used programming languages.
*
* @param {Lang[]} langs Array of programming languages.
* @param {number} width Card width.
* @param {number} totalLanguageSize Total size of all languages.
* @returns {string} Normal layout card SVG object.
*/
const renderNormalLayout = (langs, width, totalLanguageSize) => {
return flexLayout({
items: langs.map((lang, index) => {
return createProgressTextNode({
width,
name: lang.name,
color: lang.color || DEFAULT_LANG_COLOR,
progress: ((lang.size / totalLanguageSize) * 100).toFixed(2),
index,
});
}),
gap: 40,
direction: "column",
}).join("");
};
/**
* Renders compact layout to display user's most frequently used programming languages.
*
* @param {Lang[]} langs Array of programming languages.
* @param {number} width Card width.
* @param {number} totalLanguageSize Total size of all languages.
* @param {boolean} hideProgress Whether to hide progress bar.
* @returns {string} Compact layout card SVG object.
*/
const renderCompactLayout = (langs, width, totalLanguageSize, hideProgress) => {
const paddingRight = 50;
const offsetWidth = width - paddingRight;
// progressOffset holds the previous language's width and used to offset the next language
// so that we can stack them one after another, like this: [--][----][---]
let progressOffset = 0;
const compactProgressBar = langs
.map((lang) => {
const percentage = parseFloat(
((lang.size / totalLanguageSize) * offsetWidth).toFixed(2),
);
const progress = percentage < 10 ? percentage + 10 : percentage;
const output = `
<rect
mask="url(#rect-mask)"
data-testid="lang-progress"
x="${progressOffset}"
y="0"
width="${progress}"
height="8"
fill="${lang.color || "#858585"}"
/>
`;
progressOffset += percentage;
return output;
})
.join("");
return `
${
!hideProgress
? `
<mask id="rect-mask">
<rect x="0" y="0" width="${offsetWidth}" height="8" fill="white" rx="5"/>
</mask>
${compactProgressBar}
`
: ""
}
<g transform="translate(0, ${hideProgress ? "0" : "25"})">
${createLanguageTextNode({
langs,
totalSize: totalLanguageSize,
hideProgress: hideProgress,
})}
</g>
`;
};
/**
* Calculates height for the compact layout.
*
* @param {number} totalLangs Total number of languages.
* @returns {number} Card height.
*/
const calculateCompactLayoutHeight = (totalLangs) => {
return 90 + Math.round(totalLangs / 2) * 25;
};
/**
* Calculates height for the normal layout.
*
* @param {number} totalLangs Total number of languages.
* @returns {number} Card height.
*/
const calculateNormalLayoutHeight = (totalLangs) => {
return 45 + (totalLangs + 1) * 40;
};
/**
* Hides languages and trims the list to show only the top N languages.
*
* @param {Record<string, Lang>} topLangs Top languages.
* @param {string[]} hide Languages to hide.
* @param {string} langs_count Number of languages to show.
*/
const useLanguages = (topLangs, hide, langs_count) => {
let langs = Object.values(topLangs);
let langsToHide = {};
let langsCount = clampValue(parseInt(langs_count), 1, 10);
// populate langsToHide map for quick lookup
// while filtering out
if (hide) {
hide.forEach((langName) => {
langsToHide[lowercaseTrim(langName)] = true;
});
}
// filter out languages to be hidden
langs = langs
.sort((a, b) => b.size - a.size)
.filter((lang) => {
return !langsToHide[lowercaseTrim(lang.name)];
})
.slice(0, langsCount);
const totalLanguageSize = langs.reduce((acc, curr) => acc + curr.size, 0);
return { langs, totalLanguageSize };
};
/**
* Renders card to display user's most frequently used programming languages.
*
* @param {import('../fetchers/types').TopLangData} topLangs User's most frequently used programming languages.
* @param {Partial<import("./types").TopLangOptions>} options Card options.
* @returns {string} Language card SVG object.
*/
const renderTopLanguages = (topLangs, options = {}) => {
const {
hide_title = false,
hide_border,
card_width,
title_color,
text_color,
bg_color,
hide,
hide_progress,
theme,
layout,
custom_title,
locale,
langs_count = DEFAULT_LANGS_COUNT,
border_radius,
border_color,
disable_animations,
} = options;
const i18n = new I18n({
locale,
translations: langCardLocales,
});
const { langs, totalLanguageSize } = useLanguages(
topLangs,
hide,
String(langs_count),
);
let width = isNaN(card_width)
? DEFAULT_CARD_WIDTH
: card_width < MIN_CARD_WIDTH
? MIN_CARD_WIDTH
: card_width;
let height = calculateNormalLayoutHeight(langs.length);
let finalLayout = "";
if (layout === "compact" || hide_progress == true) {
width = width + 50; // padding
height =
calculateCompactLayoutHeight(langs.length) + (hide_progress ? -25 : 0);
finalLayout = renderCompactLayout(
langs,
width,
totalLanguageSize,
hide_progress,
);
} else {
finalLayout = renderNormalLayout(langs, width, totalLanguageSize);
}
// returns theme based colors with proper overrides and defaults
const colors = getCardColors({
title_color,
text_color,
bg_color,
border_color,
theme,
});
const card = new Card({
customTitle: custom_title,
defaultTitle: i18n.t("langcard.title"),
width,
height,
border_radius,
colors,
});
if (disable_animations) card.disableAnimations();
card.setHideBorder(hide_border);
card.setHideTitle(hide_title);
card.setCSS(
`
@keyframes slideInAnimation {
from {
width: 0;
}
to {
width: calc(100%-100px);
}
}
@keyframes growWidthAnimation {
from {
width: 0;
}
to {
width: 100%;
}
}
.lang-name {
font: 400 11px "Segoe UI", Ubuntu, Sans-Serif;
fill: ${colors.textColor};
}
.stagger {
opacity: 0;
animation: fadeInAnimation 0.3s ease-in-out forwards;
}
#rect-mask rect{
animation: slideInAnimation 1s ease-in-out forwards;
}
.lang-progress{
animation: growWidthAnimation 0.6s ease-in-out forwards;
}
`,
);
return card.render(`
<svg data-testid="lang-items" x="${CARD_PADDING}">
${finalLayout}
</svg>
`);
};
export { renderTopLanguages, MIN_CARD_WIDTH };