-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathuseCharts.ts
More file actions
725 lines (597 loc) · 23.3 KB
/
useCharts.ts
File metadata and controls
725 lines (597 loc) · 23.3 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
import type { MaybeRefOrGetter } from 'vue'
import { toValue } from 'vue'
import type {
DailyDataPoint,
DailyRawPoint,
EvolutionOptions,
MonthlyDataPoint,
WeeklyDataPoint,
YearlyDataPoint,
} from '~/types/chart'
import type { RepoRef } from '#shared/utils/git-providers'
import { parseRepoUrl } from '#shared/utils/git-providers'
import type { PackageMetaResponse } from '#shared/types'
import { encodePackageName } from '#shared/utils/npm'
import { fetchNpmDownloadsRange } from '~/utils/npm/api'
import type { AltCopyArgs } from 'vue-data-ui'
import {
computeLineChartAnalysis,
type TrendLineConfig,
type TrendLineDataset,
} from '../utils/charts'
export type PackumentLikeForTime = {
time?: Record<string, string>
}
function toIsoDateString(date: Date): string {
return date.toISOString().slice(0, 10)
}
function addDays(date: Date, days: number): Date {
const updatedDate = new Date(date)
updatedDate.setUTCDate(updatedDate.getUTCDate() + days)
return updatedDate
}
function startOfUtcMonth(date: Date): Date {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1))
}
function startOfUtcYear(date: Date): Date {
return new Date(Date.UTC(date.getUTCFullYear(), 0, 1))
}
function parseIsoDateOnly(value: string): Date {
return new Date(`${value}T00:00:00.000Z`)
}
function formatIsoDateOnly(date: Date): string {
return date.toISOString().slice(0, 10)
}
function differenceInUtcDaysInclusive(startIso: string, endIso: string): number {
const start = parseIsoDateOnly(startIso)
const end = parseIsoDateOnly(endIso)
return Math.floor((end.getTime() - start.getTime()) / 86400000) + 1
}
function splitIsoRangeIntoChunksInclusive(
startIso: string,
endIso: string,
maximumDaysPerRequest: number,
): Array<{ startIso: string; endIso: string }> {
const totalDays = differenceInUtcDaysInclusive(startIso, endIso)
if (totalDays <= maximumDaysPerRequest) return [{ startIso, endIso }]
const chunks: Array<{ startIso: string; endIso: string }> = []
let cursorStart = parseIsoDateOnly(startIso)
const finalEnd = parseIsoDateOnly(endIso)
while (cursorStart.getTime() <= finalEnd.getTime()) {
const cursorEnd = addDays(cursorStart, maximumDaysPerRequest - 1)
const actualEnd = cursorEnd.getTime() < finalEnd.getTime() ? cursorEnd : finalEnd
chunks.push({
startIso: formatIsoDateOnly(cursorStart),
endIso: formatIsoDateOnly(actualEnd),
})
cursorStart = addDays(actualEnd, 1)
}
return chunks
}
function mergeDailyPoints(points: DailyRawPoint[]): DailyRawPoint[] {
const valuesByDay = new Map<string, number>()
for (const point of points) {
valuesByDay.set(point.day, (valuesByDay.get(point.day) ?? 0) + point.value)
}
return Array.from(valuesByDay.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([day, value]) => ({ day, value }))
}
export function buildDailyEvolutionFromDaily(daily: DailyRawPoint[]): DailyDataPoint[] {
return daily
.slice()
.sort((a, b) => a.day.localeCompare(b.day))
.map(item => {
const dayDate = parseIsoDateOnly(item.day)
const timestamp = dayDate.getTime()
return { day: item.day, value: item.value, timestamp }
})
}
export function buildRollingWeeklyEvolutionFromDaily(
daily: DailyRawPoint[],
rangeStartIso: string,
rangeEndIso: string,
): WeeklyDataPoint[] {
const sorted = daily.slice().sort((a, b) => a.day.localeCompare(b.day))
const rangeStartDate = parseIsoDateOnly(rangeStartIso)
const rangeEndDate = parseIsoDateOnly(rangeEndIso)
const groupedByIndex = new Map<number, number>()
for (const item of sorted) {
const itemDate = parseIsoDateOnly(item.day)
const dayOffset = Math.floor((itemDate.getTime() - rangeStartDate.getTime()) / 86400000)
if (dayOffset < 0) continue
const weekIndex = Math.floor(dayOffset / 7)
groupedByIndex.set(weekIndex, (groupedByIndex.get(weekIndex) ?? 0) + item.value)
}
return Array.from(groupedByIndex.entries())
.sort(([a], [b]) => a - b)
.map(([weekIndex, value]) => {
const weekStartDate = addDays(rangeStartDate, weekIndex * 7)
const weekEndDate = addDays(weekStartDate, 6)
// Clamp weekEnd to the actual data range end date
const clampedWeekEndDate =
weekEndDate.getTime() > rangeEndDate.getTime() ? rangeEndDate : weekEndDate
const weekStartIso = toIsoDateString(weekStartDate)
const weekEndIso = toIsoDateString(clampedWeekEndDate)
const timestampStart = weekStartDate.getTime()
const timestampEnd = clampedWeekEndDate.getTime()
return {
value,
weekKey: `${weekStartIso}_${weekEndIso}`,
weekStart: weekStartIso,
weekEnd: weekEndIso,
timestampStart,
timestampEnd,
}
})
}
export function buildMonthlyEvolutionFromDaily(daily: DailyRawPoint[]): MonthlyDataPoint[] {
const sorted = daily.slice().sort((a, b) => a.day.localeCompare(b.day))
const valuesByMonth = new Map<string, number>()
for (const item of sorted) {
const month = item.day.slice(0, 7)
valuesByMonth.set(month, (valuesByMonth.get(month) ?? 0) + item.value)
}
return Array.from(valuesByMonth.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([month, value]) => {
const monthStartDate = parseIsoDateOnly(`${month}-01`)
const timestamp = monthStartDate.getTime()
return { month, value, timestamp }
})
}
export function buildYearlyEvolutionFromDaily(daily: DailyRawPoint[]): YearlyDataPoint[] {
const sorted = daily.slice().sort((a, b) => a.day.localeCompare(b.day))
const valuesByYear = new Map<string, number>()
for (const item of sorted) {
const year = item.day.slice(0, 4)
valuesByYear.set(year, (valuesByYear.get(year) ?? 0) + item.value)
}
return Array.from(valuesByYear.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([year, value]) => {
const yearStartDate = parseIsoDateOnly(`${year}-01-01`)
const timestamp = yearStartDate.getTime()
return { year, value, timestamp }
})
}
const npmDailyRangeCache = import.meta.client ? new Map<string, Promise<DailyRawPoint[]>>() : null
const likesEvolutionCache = import.meta.client ? new Map<string, Promise<DailyRawPoint[]>>() : null
const contributorsEvolutionCache = import.meta.client
? new Map<string, Promise<GitHubContributorStats[]>>()
: null
const repoMetaCache = import.meta.client ? new Map<string, Promise<RepoRef | null>>() : null
/** Clears client-side promise caches. Exported for use in tests. */
export function clearClientCaches() {
npmDailyRangeCache?.clear()
likesEvolutionCache?.clear()
contributorsEvolutionCache?.clear()
repoMetaCache?.clear()
}
type GitHubContributorWeek = {
w: number
a: number
d: number
c: number
}
type GitHubContributorStats = {
total: number
weeks: GitHubContributorWeek[]
}
function pad2(value: number): string {
return value.toString().padStart(2, '0')
}
function toIsoMonthKey(date: Date): string {
return `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}`
}
function isOverlappingRange(start: Date, end: Date, rangeStart: Date, rangeEnd: Date): boolean {
return end.getTime() >= rangeStart.getTime() && start.getTime() <= rangeEnd.getTime()
}
function buildWeeklyEvolutionFromContributorCounts(
weeklyCounts: Map<number, number>,
rangeStart: Date,
rangeEnd: Date,
): WeeklyDataPoint[] {
return Array.from(weeklyCounts.entries())
.sort(([a], [b]) => a - b)
.map(([weekStartSeconds, value]) => {
const weekStartDate = new Date(weekStartSeconds * 1000)
const weekEndDate = addDays(weekStartDate, 6)
if (!isOverlappingRange(weekStartDate, weekEndDate, rangeStart, rangeEnd)) return null
const clampedWeekEndDate = weekEndDate.getTime() > rangeEnd.getTime() ? rangeEnd : weekEndDate
const weekStartIso = toIsoDateString(weekStartDate)
const weekEndIso = toIsoDateString(clampedWeekEndDate)
return {
value,
weekKey: `${weekStartIso}_${weekEndIso}`,
weekStart: weekStartIso,
weekEnd: weekEndIso,
timestampStart: weekStartDate.getTime(),
timestampEnd: clampedWeekEndDate.getTime(),
}
})
.filter((item): item is WeeklyDataPoint => Boolean(item))
}
function buildMonthlyEvolutionFromContributorCounts(
monthlyCounts: Map<string, number>,
rangeStart: Date,
rangeEnd: Date,
): MonthlyDataPoint[] {
return Array.from(monthlyCounts.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([month, value]) => {
const [year, monthNumber] = month.split('-').map(Number)
if (!year || !monthNumber) return null
const monthStartDate = new Date(Date.UTC(year, monthNumber - 1, 1))
const monthEndDate = new Date(Date.UTC(year, monthNumber, 0))
if (!isOverlappingRange(monthStartDate, monthEndDate, rangeStart, rangeEnd)) return null
return {
month,
value,
timestamp: monthStartDate.getTime(),
}
})
.filter((item): item is MonthlyDataPoint => Boolean(item))
}
function buildYearlyEvolutionFromContributorCounts(
yearlyCounts: Map<string, number>,
rangeStart: Date,
rangeEnd: Date,
): YearlyDataPoint[] {
return Array.from(yearlyCounts.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([year, value]) => {
const yearNumber = Number(year)
if (!yearNumber) return null
const yearStartDate = new Date(Date.UTC(yearNumber, 0, 1))
const yearEndDate = new Date(Date.UTC(yearNumber, 11, 31))
if (!isOverlappingRange(yearStartDate, yearEndDate, rangeStart, rangeEnd)) return null
return {
year,
value,
timestamp: yearStartDate.getTime(),
}
})
.filter((item): item is YearlyDataPoint => Boolean(item))
}
function buildContributorCounts(stats: GitHubContributorStats[]) {
const weeklyCounts = new Map<number, number>()
const monthlyCounts = new Map<string, number>()
const yearlyCounts = new Map<string, number>()
for (const contributor of stats ?? []) {
const monthSet = new Set<string>()
const yearSet = new Set<string>()
for (const week of contributor?.weeks ?? []) {
if (!week || week.c <= 0) continue
weeklyCounts.set(week.w, (weeklyCounts.get(week.w) ?? 0) + 1)
const weekStartDate = new Date(week.w * 1000)
monthSet.add(toIsoMonthKey(weekStartDate))
yearSet.add(String(weekStartDate.getUTCFullYear()))
}
for (const key of monthSet) {
monthlyCounts.set(key, (monthlyCounts.get(key) ?? 0) + 1)
}
for (const key of yearSet) {
yearlyCounts.set(key, (yearlyCounts.get(key) ?? 0) + 1)
}
}
return { weeklyCounts, monthlyCounts, yearlyCounts }
}
async function fetchDailyRangeCached(packageName: string, startIso: string, endIso: string) {
const cache = npmDailyRangeCache
if (!cache) {
const response = await fetchNpmDownloadsRange(packageName, startIso, endIso)
return [...response.downloads]
.sort((a, b) => a.day.localeCompare(b.day))
.map(d => ({ day: d.day, value: d.downloads }))
}
const cacheKey = `${packageName}:${startIso}:${endIso}`
const cachedPromise = cache.get(cacheKey)
if (cachedPromise) return cachedPromise
const promise = fetchNpmDownloadsRange(packageName, startIso, endIso)
.then(response =>
[...response.downloads]
.sort((a, b) => a.day.localeCompare(b.day))
.map(d => ({ day: d.day, value: d.downloads })),
)
.catch(error => {
cache.delete(cacheKey)
throw error
})
cache.set(cacheKey, promise)
return promise
}
/**
* API limit workaround:
* If the requested range is larger than the API allows (≈18 months),
* split into multiple requests, then merge/sum by day.
*/
async function fetchDailyRangeChunked(packageName: string, startIso: string, endIso: string) {
const maximumDaysPerRequest = 540
const ranges = splitIsoRangeIntoChunksInclusive(startIso, endIso, maximumDaysPerRequest)
if (ranges.length === 1) {
return fetchDailyRangeCached(packageName, startIso, endIso)
}
const all: DailyRawPoint[] = []
for (const range of ranges) {
const part = await fetchDailyRangeCached(packageName, range.startIso, range.endIso)
all.push(...part)
}
return mergeDailyPoints(all)
}
function toDateOnly(value?: string): string | null {
if (!value) return null
const dateOnly = value.slice(0, 10)
return /^\d{4}-\d{2}-\d{2}$/.test(dateOnly) ? dateOnly : null
}
export function getNpmPackageCreationDate(packument: PackumentLikeForTime): string | null {
const time = packument.time
if (!time) return null
if (time.created) return time.created
const versionDates = Object.entries(time)
.filter(([key, value]) => key !== 'modified' && key !== 'created' && Boolean(value))
.map(([, value]) => value)
.sort((a, b) => a.localeCompare(b))
return versionDates[0] ?? null
}
export function useCharts() {
const compactNumberFormatter = useCompactNumberFormatter()
function resolveDateRange(
evolutionOptions: EvolutionOptions,
packageCreatedIso: string | null,
): { start: Date; end: Date } {
const today = new Date()
const yesterday = new Date(
Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - 1),
)
const endDateOnly = toDateOnly(evolutionOptions.endDate)
const end = endDateOnly ? parseIsoDateOnly(endDateOnly) : yesterday
const startDateOnly = toDateOnly(evolutionOptions.startDate)
if (startDateOnly) {
const start = parseIsoDateOnly(startDateOnly)
return { start, end }
}
let start: Date
if (evolutionOptions.granularity === 'year') {
if (packageCreatedIso) {
start = startOfUtcYear(new Date(packageCreatedIso))
} else {
start = addDays(end, -(5 * 365) + 1)
}
} else if (evolutionOptions.granularity === 'month') {
const monthCount = evolutionOptions.months ?? 12
const firstOfThisMonth = startOfUtcMonth(end)
start = new Date(
Date.UTC(
firstOfThisMonth.getUTCFullYear(),
firstOfThisMonth.getUTCMonth() - (monthCount - 1),
1,
),
)
} else if (evolutionOptions.granularity === 'week') {
const weekCount = evolutionOptions.weeks ?? 52
// Full rolling weeks ending on `end` (yesterday by default)
// Range length is exactly weekCount * 7 days (inclusive)
start = addDays(end, -(weekCount * 7) + 1)
} else {
start = addDays(end, -30 + 1)
}
return { start, end }
}
async function fetchPackageDownloadEvolution(
packageName: MaybeRefOrGetter<string>,
createdIso: MaybeRefOrGetter<string | null | undefined>,
evolutionOptions: MaybeRefOrGetter<EvolutionOptions>,
): Promise<DailyDataPoint[] | WeeklyDataPoint[] | MonthlyDataPoint[] | YearlyDataPoint[]> {
const resolvedPackageName = toValue(packageName)
const resolvedCreatedIso = toValue(createdIso) ?? null
const resolvedOptions = toValue(evolutionOptions)
const { start, end } = resolveDateRange(resolvedOptions, resolvedCreatedIso)
const startIso = toIsoDateString(start)
const endIso = toIsoDateString(end)
const sortedDaily = await fetchDailyRangeChunked(resolvedPackageName, startIso, endIso)
if (resolvedOptions.granularity === 'day') return buildDailyEvolutionFromDaily(sortedDaily)
if (resolvedOptions.granularity === 'week')
return buildRollingWeeklyEvolutionFromDaily(sortedDaily, startIso, endIso)
if (resolvedOptions.granularity === 'month') return buildMonthlyEvolutionFromDaily(sortedDaily)
return buildYearlyEvolutionFromDaily(sortedDaily)
}
async function fetchPackageLikesEvolution(
packageName: MaybeRefOrGetter<string>,
evolutionOptions: MaybeRefOrGetter<EvolutionOptions>,
): Promise<DailyDataPoint[] | WeeklyDataPoint[] | MonthlyDataPoint[] | YearlyDataPoint[]> {
const resolvedPackageName = toValue(packageName)
const resolvedOptions = toValue(evolutionOptions)
// Fetch daily likes data (with client-side promise caching)
const cache = likesEvolutionCache
const cacheKey = resolvedPackageName
let dailyLikesPromise: Promise<DailyRawPoint[]>
if (cache?.has(cacheKey)) {
dailyLikesPromise = cache.get(cacheKey)!
} else {
dailyLikesPromise = $fetch<Array<{ day: string; likes: number }>>(
`/api/social/likes-evolution/${resolvedPackageName}`,
)
.then(data => (data ?? []).map(d => ({ day: d.day, value: d.likes })))
.catch(error => {
cache?.delete(cacheKey)
throw error
})
cache?.set(cacheKey, dailyLikesPromise)
}
const sortedDaily = await dailyLikesPromise
const { start, end } = resolveDateRange(resolvedOptions, null)
const startIso = toIsoDateString(start)
const endIso = toIsoDateString(end)
const filteredDaily = sortedDaily.filter(d => d.day >= startIso && d.day <= endIso)
if (resolvedOptions.granularity === 'day') return buildDailyEvolutionFromDaily(filteredDaily)
if (resolvedOptions.granularity === 'week')
return buildRollingWeeklyEvolutionFromDaily(filteredDaily, startIso, endIso)
if (resolvedOptions.granularity === 'month')
return buildMonthlyEvolutionFromDaily(filteredDaily)
return buildYearlyEvolutionFromDaily(filteredDaily)
}
async function fetchRepoContributorsEvolution(
repoRef: MaybeRefOrGetter<RepoRef | null | undefined>,
evolutionOptions: MaybeRefOrGetter<EvolutionOptions>,
): Promise<DailyDataPoint[] | WeeklyDataPoint[] | MonthlyDataPoint[] | YearlyDataPoint[]> {
const resolvedRepoRef = toValue(repoRef)
if (!resolvedRepoRef || resolvedRepoRef.provider !== 'github') return []
const resolvedOptions = toValue(evolutionOptions)
const cache = contributorsEvolutionCache
const cacheKey = `${resolvedRepoRef.owner}/${resolvedRepoRef.repo}`
let statsPromise: Promise<GitHubContributorStats[]>
if (cache?.has(cacheKey)) {
statsPromise = cache.get(cacheKey)!
} else {
statsPromise = $fetch<GitHubContributorStats[]>(
`/api/github/contributors-evolution/${resolvedRepoRef.owner}/${resolvedRepoRef.repo}`,
)
.then(data => (Array.isArray(data) ? data : []))
.catch(error => {
cache?.delete(cacheKey)
throw error
})
cache?.set(cacheKey, statsPromise)
}
const stats = await statsPromise
const { start, end } = resolveDateRange(resolvedOptions, null)
const { weeklyCounts, monthlyCounts, yearlyCounts } = buildContributorCounts(stats)
if (resolvedOptions.granularity === 'week') {
return buildWeeklyEvolutionFromContributorCounts(weeklyCounts, start, end)
}
if (resolvedOptions.granularity === 'month') {
return buildMonthlyEvolutionFromContributorCounts(monthlyCounts, start, end)
}
if (resolvedOptions.granularity === 'year') {
return buildYearlyEvolutionFromContributorCounts(yearlyCounts, start, end)
}
return []
}
async function fetchRepoRefsForPackages(
packageNames: MaybeRefOrGetter<string[]>,
): Promise<Record<string, RepoRef | null>> {
const names = (toValue(packageNames) ?? []).map(n => String(n).trim()).filter(Boolean)
if (!import.meta.client || !names.length) return {}
const settled = await Promise.allSettled(
names.map(async name => {
const cacheKey = name
const cache = repoMetaCache
if (cache?.has(cacheKey)) {
const ref = await cache.get(cacheKey)!
return { name, ref }
}
const promise = $fetch<PackageMetaResponse>(
`/api/registry/package-meta/${encodePackageName(name)}`,
)
.then(meta => {
const repoUrl = meta?.links?.repository
return repoUrl ? parseRepoUrl(repoUrl) : null
})
.catch(error => {
cache?.delete(cacheKey)
throw error
})
cache?.set(cacheKey, promise)
const ref = await promise
return { name, ref }
}),
)
const next: Record<string, RepoRef | null> = {}
for (const [index, entry] of settled.entries()) {
const name = names[index]
if (!name) continue
if (entry.status === 'fulfilled') {
next[name] = entry.value.ref ?? null
} else {
next[name] = null
}
}
return next
}
function createAltTextForTrendLineChart({
dataset,
config,
}: AltCopyArgs<TrendLineDataset, TrendLineConfig>): string {
if (!dataset) return ''
const analysis = dataset.lines.map(({ name, series }) => ({
name,
...computeLineChartAnalysis(series),
dates: config.formattedDates,
hasEstimation: config.hasEstimation,
}))
const granularityKeyByGranularity: Record<string, string> = {
daily: 'package.trends.granularity_dayly',
weekly: 'package.trends.granularity_weekly',
monthly: 'package.trends.granularity_monthly',
yearly: 'package.trends.granularity_yearly',
}
const granularityKey =
granularityKeyByGranularity[config.granularity as unknown as string] ??
'package.trends.granularity_day'
const granularity = String(config.$t(granularityKey)).toLocaleLowerCase()
const packages_analysis = analysis
.map((pkg, i) => {
const trendText = (() => {
switch (pkg.interpretation.trend) {
case 'none':
return config.$t('package.trends.copy_alt.trend_none')
case 'weak':
return config.$t('package.trends.copy_alt.trend_weak')
case 'strong':
return config.$t('package.trends.copy_alt.trend_strong')
case 'undefined':
default:
return config.$t('package.trends.copy_alt.trend_undefined')
}
})()
return config.$t('package.trends.copy_alt.analysis', {
package_name: pkg.name,
start_value: config.formattedDatasetValues[i]?.[0] ?? 0,
end_value: config.formattedDatasetValues[i]?.at(-1) ?? 0,
trend: trendText,
downloads_slope: compactNumberFormatter.value.format(pkg.slope),
growth_percentage: `${pkg.progressionPercent?.toFixed(1)}%`,
})
})
.join(', ')
const isSinglePackage = analysis.length === 1
const estimation_notice = config.hasEstimation
? ` ${
isSinglePackage
? config.$t('package.trends.copy_alt.estimation')
: config.$t('package.trends.copy_alt.estimations')
}`
: ''
const compareText = `${config.$t('package.trends.copy_alt.compare', {
packages: analysis.map(a => a.name).join(', '),
})} `
const singlePackageText = `${config.$t('package.trends.copy_alt.single_package', {
package: analysis?.[0]?.name ?? '',
})} `
const generalAnalysis = config.$t('package.trends.copy_alt.general_description', {
start_date: analysis?.[0]?.dates[0]?.text,
end_date: analysis?.[0]?.dates.at(-1)?.text,
granularity,
packages_analysis,
watermark: config.$t('package.trends.copy_alt.watermark'),
estimation_notice,
})
return (isSinglePackage ? singlePackageText : compareText) + generalAnalysis
}
async function copyAltTextForTrendLineChart({
dataset,
config,
}: AltCopyArgs<TrendLineDataset, TrendLineConfig>) {
const altText = createAltTextForTrendLineChart({ dataset, config })
await config.copy(altText)
}
return {
fetchPackageDownloadEvolution,
fetchPackageLikesEvolution,
fetchRepoContributorsEvolution,
fetchRepoRefsForPackages,
getNpmPackageCreationDate,
copyAltTextForTrendLineChart,
}
}