Repository navigation
Expand file tree
/
Copy pathModel.js
More file actions
1249 lines (1162 loc) · 53.5 KB
/
Copy pathModel.js
File metadata and controls
1249 lines (1162 loc) · 53.5 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
.pragma library
// Pure data helpers for C411 Trend: history parsing, formatting, linear
// forecasts and chart geometry. No Qt imports so node can test it.
var DAY = 86400
var METRICS = ["up", "down", "ratio"]
// Chart ranges, in days; 0 = everything recorded. Labels come from the locale.
var RANGES = [
{ key: "24h", days: 1 },
{ key: "7d", days: 7 },
{ key: "30d", days: 30 },
{ key: "all", days: 0 }
]
// --- Locales ------------------------------------------------------------------
//
// Every user-facing string lives here. Sizes use binary multiples in both
// languages, as the tracker counts: 1 TB (1 To) is 1024^4 bytes.
var EN = {
code: "en",
decimal: ".",
units: ["B", "KB", "MB", "GB", "TB", "PB", "EB"],
months: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
perDay: "/day",
metricNames: { up: "Upload", down: "Download", ratio: "Ratio", xp: "XP", zen: "Zen" },
tiers: { bronze: "Bronze", argent: "Silver", or: "Gold", platine: "Platinum", diamant: "Diamond" },
rangeLabels: { "24h": "24h", "7d": "7d", "30d": "30d", "all": "All" },
words: { day: ["day", "days"], week: ["week", "weeks"], month: ["month", "months"], year: ["year", "years"] },
t: {
date: "{m} {d}, {y}",
shortDate: "{m} {d}",
shortDateYear: "{m} {d}, {y}",
dateTime: "{m} {d}, {hm}",
axisDay: "{m} {d}",
axisMonth: "{m} {y}",
inTime: "in {0}",
ago: "{0} ago",
justNow: "just now",
minAgo: "{0} min ago",
hAgo: "{0} h ago",
fetching: "fetching…",
updated: "updated {0}",
lastReading: "last reading {0}",
noReading: "no reading yet",
loginHint: "Log in to c411.org in your browser, then middle-click the bar icon to retry.",
paceNeedHour: "Forecasts need at least an hour of readings.",
paceOverPartial: "over the last {0} (all there is so far)",
paceOver: "over {0} days",
pace: "Pace {0}: ↑ {1} · ↓ {2}",
paceDaily: "Pace per day, {0} – {1} · dashed line: forecast pace",
paceDay: "{0}: ↑ {1} · ↓ {2}",
pacePoints: "Pace {0}: {1}",
paceDailyPoints: "Daily gains ({0}), {1} – {2} · dashed line: forecast pace",
paceDayMetric: "{0}: {1}",
paceNeedPoints: "This series needs readings with profile data.",
paceDayNone: "{0}: no readings",
resetNote: "C411's counters went back on {0} ({1}): forecasts count your activity, not the drop.",
// 2.0: profile data from the API key
tileLevel: "Level",
tileZen: "Zen",
tileClass: "Class",
levelValue: "Level {0}",
levelNext: "{0} XP to level {1}",
levelMax: "{0} XP",
perDayXp: "{0} XP",
zenEarnedPace: "{0} earned",
classQuests: "{0}/{1} quests",
classNone: "No class yet",
creditUp: "incl. {0} credit",
creditDown: "{0} credit off",
alertBlocked: "Downloads are blocked: {0}",
alertBlockedNoReason: "Downloads are blocked",
alertFreeleech: "Freeleech is on ({0})",
alertFreeleechNoSource: "Freeleech is on",
alertSilver: "Silver leech is on",
alertBonuses: "{0} leech bonuses active",
alertBonus: "1 leech bonus active",
levelRow: "Level {0}",
keyTitle: "API KEY",
keyIntro: "C411 Trend reads your stats with a personal API key. On c411.org, open your profile settings, create a key with the \"Profile (read)\" scope ticked, then paste it here. It is stored in ~/.config/c411trend/api-key, readable by you only.",
keyPlaceholder: "Paste your API key",
keySave: "Save",
keySaving: "Saving…",
keyCancel: "Cancel",
keyStored: "Key saved, fetching…",
keyReplace: "k replace API key",
barFreeleech: "FL",
barSilver: "SL",
simZenNote: "Assuming you spend none meanwhile.",
simWhyNoXp: "No XP gained over the last {0} days.",
simWhyNoZen: "No Zen earned over the last {0} days.",
simNoSeriesHead: "{0}: not tracked yet",
simNoSeriesDetail: "This series starts with the API key; give it an hour of readings.",
outOfReach: "out of reach at this pace",
reached: "reached",
forecast: "FORECAST",
whatIf: "WHAT IF",
horizonRow: "+{0} days · {1}",
whatIfHint: "Type an upload amount (10 TB), a ratio (ratio 5, 5x), a Zen balance (2000 zen) or an XP total (20000 xp) to see when you would get there at your current pace. A bare number gets both upload and ratio answers.",
placeholderTarget: "10 TB, ratio 5, 2000 zen…",
footerField: "⏎ keep · Esc back · \"10 TB\", \"ratio 5\", \"5x\", \"5\" for both",
footer: "u/r/d/x/z metric · 1-4 or ←/→ range · f what-if · R refresh · o c411.org · {0} readings",
in7days: "{0} in 7 days",
since: "{0} since {1}",
uploadedRow: "{0} uploaded",
ratioRow: "Ratio {0}",
noRange: "No readings in this range yet",
fetchingTitle: "Fetching…",
now: "now",
forecastHover: "forecast · ",
noData: "No data yet",
summaryPace: "{0} upload pace ({1} average)",
errPython: "python3 not found: c411trend-fetch cannot start",
errExit: "c411trend-fetch exited without an answer (code {0})",
errUnknown: "unknown error",
errWatchdog: "c411trend-fetch stopped responding, poll abandoned",
ipcUsage: "usage: when \"10 TB\" | when \"ratio 5\"",
ipcNoHistory: "not enough history",
simNoDataHead: "No readings yet",
simNoDataDetail: "Forecasts start once the first poll lands.",
simNoPaceHead: "Not enough history yet",
simRatio: "Ratio {0}",
simUp: "{0} uploaded",
simAlready: "{0}: already there",
simRatioHolding: "Your ratio is {0} and not falling.",
simBeforeFirst: "Reached before your first reading.",
simCrossed: "Crossed on {0}.",
simEta: "{0} {1}",
simFall: "Ratio falls to {0} {1}",
simAround: "Around {0}, at {1}.",
simPaceDays: "{0} over {1} days",
simPaceLast: "{0} over the last {1}",
simRatioPace: "↑ {0} · ↓ {1}",
simCeiling: "At this pace your ratio levels off near {0}.",
simFallNote: "You are downloading faster than your ratio can hold.",
simOut: "{0}: out of reach at this pace",
simWhyNoUpload: "Nothing uploaded over the last {0} days.",
simWhyNotRising: "Your ratio is not rising at the moment ({0}).",
simWhyCeiling: "Your ratio cannot climb that high at this pace.",
simWhyFloor: "Your ratio is falling but levels off near {0} at this pace, above that.",
targetHint: "Try \"10 TB\", \"ratio 5\", \"5x\", \"2000 zen\" or \"20000 xp\"",
targetRatioUnit: "A ratio has no unit",
targetUnknownUnit: "Unknown unit \"{0}\"",
targetAboveZero: "The target must be above zero",
targetRatioRange: "That ratio is out of range",
targetAmountRange: "That amount is out of range",
targetRatioText: "ratio {0}",
goalReached: "✓",
goalNever: "∞"
}
}
var FR = {
code: "fr",
decimal: ",",
units: ["o", "Ko", "Mo", "Go", "To", "Po", "Eo"],
months: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
perDay: "/j",
metricNames: { up: "Upload", down: "Download", ratio: "Ratio", xp: "XP", zen: "Zen" },
tiers: { bronze: "Bronze", argent: "Argent", or: "Or", platine: "Platine", diamant: "Diamant" },
rangeLabels: { "24h": "24 h", "7d": "7 j", "30d": "30 j", "all": "Tout" },
words: { day: ["jour", "jours"], week: ["semaine", "semaines"], month: ["mois", "mois"], year: ["an", "ans"] },
t: {
date: "{d} {m} {y}",
shortDate: "{d} {m}",
shortDateYear: "{d} {m} {y}",
dateTime: "{d} {m} {hm}",
axisDay: "{d} {m}",
axisMonth: "{m} {y}",
inTime: "dans {0}",
ago: "il y a {0}",
justNow: "à l'instant",
minAgo: "il y a {0} min",
hAgo: "il y a {0} h",
fetching: "récupération…",
updated: "mis à jour {0}",
lastReading: "dernier relevé {0}",
noReading: "pas encore de relevé",
loginHint: "Connecte-toi sur c411.org dans ton navigateur, puis clic milieu sur l'icône pour réessayer.",
paceNeedHour: "Les prévisions demandent au moins une heure de relevés.",
paceOverPartial: "sur les {0} disponibles",
paceOver: "sur {0} jours",
pace: "Rythme {0} : ↑ {1} · ↓ {2}",
paceDaily: "Rythme par jour, du {0} au {1} · pointillés : rythme des prévisions",
paceDay: "{0} : ↑ {1} · ↓ {2}",
pacePoints: "Rythme {0} : {1}",
paceDailyPoints: "Gains quotidiens ({0}), du {1} au {2} · pointillés : rythme prévu",
paceDayMetric: "{0} : {1}",
paceNeedPoints: "Cette série demande des relevés avec les données de profil.",
paceDayNone: "{0} : pas de relevé",
resetNote: "Les compteurs de C411 ont reculé le {0} ({1}) : les prévisions comptent ton activité, pas la chute.",
tileLevel: "Niveau",
tileZen: "Zen",
tileClass: "Classe",
levelValue: "Niveau {0}",
levelNext: "{0} XP avant le niveau {1}",
levelMax: "{0} XP",
perDayXp: "{0} XP",
zenEarnedPace: "{0} gagnés",
classQuests: "{0}/{1} quêtes",
classNone: "Pas encore de classe",
creditUp: "dont {0} de crédit",
creditDown: "{0} de crédit déduit",
alertBlocked: "Téléchargement bloqué : {0}",
alertBlockedNoReason: "Téléchargement bloqué",
alertFreeleech: "Freeleech actif ({0})",
alertFreeleechNoSource: "Freeleech actif",
alertSilver: "Silver leech actif",
alertBonuses: "{0} bonus de leech actifs",
alertBonus: "1 bonus de leech actif",
levelRow: "Niveau {0}",
keyTitle: "CLÉ API",
keyIntro: "C411 Trend lit tes stats avec une clé API personnelle. Sur c411.org, ouvre les réglages de ton profil, crée une clé en cochant le scope « Profil (lecture) », puis colle-la ici. Elle est rangée dans ~/.config/c411trend/api-key, lisible par toi seul.",
keyPlaceholder: "Colle ta clé API",
keySave: "Enregistrer",
keySaving: "Enregistrement…",
keyCancel: "Annuler",
keyStored: "Clé enregistrée, récupération…",
keyReplace: "k remplacer la clé API",
barFreeleech: "FL",
barSilver: "SL",
simZenNote: "En supposant que tu n'en dépenses pas d'ici là.",
simWhyNoXp: "Aucune XP gagnée sur les {0} derniers jours.",
simWhyNoZen: "Aucun Zen gagné sur les {0} derniers jours.",
simNoSeriesHead: "{0} : pas encore suivi",
simNoSeriesDetail: "Cette série démarre avec la clé API : laisse-lui une heure de relevés.",
outOfReach: "hors d'atteinte à ce rythme",
reached: "atteint",
forecast: "PRÉVISIONS",
whatIf: "ET SI…",
horizonRow: "+{0} j · {1}",
whatIfHint: "Tape un volume d'upload (10 To), un ratio (ratio 5, 5x), un solde de Zen (2000 zen) ou un total d'XP (20000 xp) pour savoir quand tu l'atteindras à ton rythme actuel. Un nombre seul donne les réponses upload et ratio.",
placeholderTarget: "10 To, ratio 5, 2000 zen…",
footerField: "⏎ garder · Échap retour · « 10 To », « ratio 5 », « 5x », « 5 » pour les deux",
footer: "u/r/d/x/z métrique · 1-4 ou ←/→ période · f et si · R actualiser · o c411.org · {0} relevés",
in7days: "{0} sur 7 j",
since: "{0} depuis le {1}",
uploadedRow: "{0} d'upload",
ratioRow: "Ratio {0}",
noRange: "Pas encore de relevé sur cette période",
fetchingTitle: "Récupération…",
now: "maintenant",
forecastHover: "prévu · ",
noData: "Pas encore de données",
summaryPace: "rythme d'upload {0} (moyenne sur {1})",
errPython: "python3 introuvable : c411trend-fetch ne peut pas démarrer",
errExit: "c411trend-fetch s'est arrêté sans réponse (code {0})",
errUnknown: "erreur inconnue",
errWatchdog: "c411trend-fetch ne répond plus, relevé abandonné",
ipcUsage: "usage : when \"10 To\" | when \"ratio 5\"",
ipcNoHistory: "pas assez d'historique",
simNoDataHead: "Aucun relevé pour l'instant",
simNoDataDetail: "Les prévisions démarrent dès le premier relevé.",
simNoPaceHead: "Pas encore assez d'historique",
simRatio: "Ratio {0}",
simUp: "{0} d'upload",
simAlready: "{0} : déjà atteint",
simRatioHolding: "Ton ratio est à {0} et ne baisse pas.",
simBeforeFirst: "Atteint avant ton premier relevé.",
simCrossed: "Franchi le {0}.",
simEta: "{0} {1}",
simFall: "Ratio à {0} {1}",
simAround: "Vers le {0}, à {1}.",
simPaceDays: "{0} sur {1} jours",
simPaceLast: "{0} sur {1}",
simRatioPace: "↑ {0} · ↓ {1}",
simCeiling: "À ce rythme, ton ratio plafonne vers {0}.",
simFallNote: "Tu télécharges plus vite que ton ratio ne peut suivre.",
simOut: "{0} : hors d'atteinte à ce rythme",
simWhyNoUpload: "Aucun upload sur les {0} derniers jours.",
simWhyNotRising: "Ton ratio ne monte pas en ce moment ({0}).",
simWhyCeiling: "Ton ratio ne peut pas monter aussi haut à ce rythme.",
simWhyFloor: "Ton ratio baisse mais se stabilise vers {0} à ce rythme, au-dessus de la cible.",
targetHint: "Essaie « 10 To », « ratio 5 », « 5x », « 2000 zen » ou « 20000 xp »",
targetRatioUnit: "Un ratio n'a pas d'unité",
targetUnknownUnit: "Unité « {0} » inconnue",
targetAboveZero: "La cible doit être supérieure à zéro",
targetRatioRange: "Ce ratio est hors limites",
targetAmountRange: "Ce volume est hors limites",
targetRatioText: "ratio {0}",
goalReached: "✓",
goalNever: "∞"
}
}
var LOCALES = { en: EN, fr: FR }
var LANGUAGES = ["Auto", "English", "Français"]
// Setting ("Auto", "English", "Français", or a code) + the environment's
// LC_MESSAGES/LANG -> "en" | "fr".
function resolveLanguage(setting, envLang) {
var s = String(setting || "").toLowerCase()
if (s === "english" || s === "en" || s === "en-us" || s === "en_us") return "en"
if (s === "français" || s === "francais" || s === "french" || s === "fr" || s === "fr-fr" || s === "fr_fr") return "fr"
return /^fr/i.test(String(envLang || "")) ? "fr" : "en"
}
function loc(l) { return l && l.t ? l : EN }
// "{0} since {1}" + ["a", "b"] -> "a since b"; named keys from an object.
function fill(template, args) {
return String(template).replace(/\{(\w+)\}/g, function(m, k) {
return args && args[k] !== undefined ? String(args[k]) : m
})
}
function tr(l, key, args) {
var L = loc(l)
var s = L.t[key]
if (s === undefined) s = EN.t[key]
return fill(s === undefined ? key : s, args || [])
}
function fixed(v, decimals, l) {
return v.toFixed(decimals).replace(".", loc(l).decimal)
}
function plural(n, word, l) {
var forms = loc(l).words[word]
return n + " " + (n === 1 || (loc(l).code === "fr" && n < 2) ? forms[0] : forms[1])
}
// Same scale as the site (powers of 1024), three decimals from TB upwards so
// the pill matches the figures c411.org shows.
function formatBytes(bytes, decimals, l) {
var units = loc(l).units
if (bytes === null || bytes === undefined || isNaN(bytes)) return "—"
var sign = bytes < 0 ? "-" : ""
var b = Math.abs(bytes)
if (b < 1) return "0 " + units[0]
var i = Math.floor(Math.log(b) / Math.log(1024))
i = Math.max(0, Math.min(units.length - 1, i))
var v = b / Math.pow(1024, i)
if (v >= 1000 && i < units.length - 1) { i++; v = b / Math.pow(1024, i) }
var d = decimals !== undefined && decimals !== null ? decimals : (i >= 4 ? 3 : 1)
if (i === 0) d = 0
return sign + fixed(v, d, l) + " " + units[i]
}
function formatRate(bytesPerDay, l) {
if (bytesPerDay === null || bytesPerDay === undefined || isNaN(bytesPerDay)) return "—"
return (bytesPerDay >= 0 ? "+" : "") + formatBytes(bytesPerDay, 1, l) + loc(l).perDay
}
function formatRatio(r, l) {
if (r === null || r === undefined) return "∞"
if (isNaN(r)) return "—"
return fixed(r, r >= 100 ? 0 : 2, l)
}
// Points (XP, Zen): whole numbers with thousands separators, "18,420" / "18 420".
function formatCount(v, l) {
if (v === null || v === undefined || isNaN(v)) return "—"
var n = Math.round(Math.abs(v)).toString()
var sep = loc(l).code === "fr" ? "\u202f" : ","
return (v < 0 ? "-" : "") + n.replace(/\B(?=(\d{3})+(?!\d))/g, sep)
}
function formatPointsRate(perDay, l) {
if (perDay === null || perDay === undefined || isNaN(perDay)) return "—"
var v = Math.abs(perDay) >= 10 ? Math.round(perDay) : Math.round(perDay * 10) / 10
return (perDay >= 0 ? "+" : "") + (Math.abs(v) >= 10 ? formatCount(v, l) : fixed(v, v % 1 ? 1 : 0, l)) + loc(l).perDay
}
function pad2(n) { return n < 10 ? "0" + n : String(n) }
function dateParts(t, l) {
var d = new Date(t * 1000)
return { d: d.getDate(), m: loc(l).months[d.getMonth()], y: d.getFullYear(), hm: pad2(d.getHours()) + ":" + pad2(d.getMinutes()) }
}
function formatDate(t, l) {
return tr(l, "date", dateParts(t, l))
}
// "Sep 26" / "26 sept.", with the year only when it is not the current one.
function formatShortDate(t, now, l) {
var p = dateParts(t, l)
var ref = new Date((now === undefined || now === null ? Date.now() / 1000 : now) * 1000)
return tr(l, p.y === ref.getFullYear() ? "shortDate" : "shortDateYear", p)
}
function formatDateTime(t, l) {
return tr(l, "dateTime", dateParts(t, l))
}
// Short axis label: hours inside a day, month+day otherwise.
function formatAxis(t, spanSec, l) {
var p = dateParts(t, l)
if (spanSec <= 2 * DAY) return p.hm
if (spanSec <= 400 * DAY) return tr(l, "axisDay", p)
return tr(l, "axisMonth", p)
}
// "3 days", "5 weeks", "1.5 years": a duration without the "in".
function formatDuration(seconds, l) {
if (seconds === null || seconds === undefined || !isFinite(seconds)) return ""
var days = seconds / DAY
if (days < 1) return Math.max(1, Math.round(seconds / 3600)) + " h"
if (days < 14) return plural(Math.round(days), "day", l)
if (days < 60) return plural(Math.round(days / 7), "week", l)
if (days < 730) return plural(Math.round(days / 30.44), "month", l)
return fixed(days / 365.25, 1, l) + " " + loc(l).words.year[1]
}
function formatIn(seconds, l) {
var d = formatDuration(seconds, l)
return d === "" ? "" : tr(l, "inTime", [d])
}
function formatAgo(seconds, l) {
if (seconds < 90) return tr(l, "justNow")
if (seconds < 3600) return tr(l, "minAgo", [Math.round(seconds / 60)])
if (seconds < 2 * DAY) return tr(l, "hAgo", [Math.round(seconds / 3600)])
return tr(l, "ago", [plural(Math.round(seconds / DAY), "day", l)])
}
// history.jsonl -> [{t, up, down, ratio, credit}] sorted by time. Broken
// lines (a crash mid-write) are skipped rather than poisoning the lot.
// The file is ours, but a hand edit or a disk hiccup must not take the panel
// down: only finite, non-negative numbers survive, and a runaway file is read
// from its tail (MAX_HISTORY_CHARS, ~5 years of 30-minute polls).
var MAX_HISTORY_CHARS = 16 * 1024 * 1024
function goodNumber(v) {
return typeof v === "number" && isFinite(v) && v >= 0
}
function parseHistory(text) {
var out = []
var src = String(text || "")
if (src.length > MAX_HISTORY_CHARS) src = src.slice(src.length - MAX_HISTORY_CHARS)
var lines = src.split("\n")
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim()
if (line === "") continue
try {
var s = JSON.parse(line)
if (!s || typeof s !== "object") continue
if (!goodNumber(s.t) || !goodNumber(s.up) || !goodNumber(s.down)) continue
var ratio = goodNumber(s.ratio) ? s.ratio : (s.down > 0 ? s.up / s.down : null)
out.push({
t: s.t, up: s.up, down: s.down, ratio: ratio,
credit: goodNumber(s.credit) ? s.credit : 0,
downCredit: goodNumber(s.downCredit) ? s.downCredit : 0,
// Series the API key brought (2.0): absent from older readings.
xp: goodNumber(s.xp) ? s.xp : null,
level: goodNumber(s.level) ? s.level : null,
zen: goodNumber(s.zen) ? s.zen : null,
zenEarned: goodNumber(s.zenEarned) ? s.zenEarned : null,
manual: s.manual === true
})
} catch (e) {}
}
out.sort(function(a, b) { return a.t - b.t })
return out
}
function ratioOf(s) {
if (typeof s.ratio === "number") return s.ratio
return s.down > 0 ? s.up / s.down : null
}
function valueOf(sample, metric) {
if (metric === "ratio") return ratioOf(sample)
var v = sample[metric]
return v === undefined ? null : v
}
function since(samples, t0) {
var out = []
for (var i = 0; i < samples.length; i++) if (samples[i].t >= t0) out.push(samples[i])
return out
}
// Least-squares slope of `metric` against time, per second.
// Both axes are taken relative to the first sample: counters are ~10^12
// bytes, and summing their raw squares loses enough precision that a flat
// series comes out with a tiny non-zero slope.
function slope(samples, metric) {
var n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0
var t0 = samples.length ? samples[0].t : 0
var y0 = null
for (var i = 0; i < samples.length; i++) {
var v = valueOf(samples[i], metric)
if (v === null || v === undefined || isNaN(v)) continue
if (y0 === null) y0 = v
var y = v - y0
var x = samples[i].t - t0
n++; sx += x; sy += y; sxx += x * x; sxy += x * y
}
if (n < 2) return null
var den = n * sxx - sx * sx
if (den <= 0) return null
return (n * sxy - sx * sy) / den
}
// Below this a pace is rounding noise, not torrent activity; it counts as
// zero so it can never become a divisor (a ratio "levelling off near 10^13").
var MIN_PACE = 1024 * 1024 // bytes per day
function pace(perSecond) {
var perDay = Math.max(0, perSecond) * DAY
return perDay < MIN_PACE ? 0 : perDay
}
// Upload and download rates over the last `windowDays`, in bytes per day.
// Needs at least an hour of data, otherwise a single poll's jitter would be
// extrapolated to months.
// Cumulative counters only ever grow, unless the tracker loses data (a crash,
// a restore from backup). Such a drop is not negative activity: for paces and
// gains, keep only the increases between readings, like a monitoring rate()
// over a counter reset. Same length and order as `samples`; values are
// shifted so the last one equals the real, current counter.
// Counters treated this way: transfers, total XP, Zen ever earned. The Zen
// balance is not one (spending lowers it for real) and is left as is.
var COUNTERS = ["up", "down", "xp", "zenEarned"]
function continuous(samples) {
if (samples.length === 0) return []
var out = []
for (var i = 0; i < samples.length; i++) out.push({ t: samples[i].t, zen: valueOf(samples[i], "zen") })
for (var k = 0; k < COUNTERS.length; k++) {
var key = COUNTERS[k], sum = 0, prev = null, lastReal = null, lastSum = 0
for (var j = 0; j < samples.length; j++) {
var v = valueOf(samples[j], key)
if (v === null) { out[j][key] = null; continue } // series not recorded yet
if (prev !== null) sum += Math.max(0, v - prev)
prev = v; lastReal = v; lastSum = sum
out[j][key] = sum
}
// Shift so the newest value is the real, current counter.
var shift = lastReal === null ? 0 : lastReal - lastSum
for (var m = 0; m < out.length; m++) if (out[m][key] !== null) out[m][key] += shift
}
for (var r = 0; r < out.length; r++) out[r].ratio = out[r].down > 0 ? out[r].up / out[r].down : null
return out
}
// Drops of a counter by more than `minDrop` bytes: [{t, metric, drop}],
// oldest first. Used to tell the user why a pace ignores them.
var MIN_RESET = 1024 * 1024 * 1024 // 1 GiB: below that it is not worth a word
function resets(samples, minDrop) {
var floor = minDrop === undefined ? MIN_RESET : minDrop
var out = []
for (var i = 1; i < samples.length; i++) {
for (var k = 0; k < 2; k++) {
var m = k === 0 ? "up" : "down"
var drop = samples[i - 1][m] - samples[i][m]
if (drop > floor) out.push({ t: samples[i].t, metric: m, drop: drop })
}
}
return out
}
function rates(samples, now, windowDays) {
var win = continuous(since(samples, now - windowDays * DAY))
if (win.length < 2) win = continuous(samples.slice(-2))
if (win.length < 2) return null
var span = win[win.length - 1].t - win[0].t
if (span < 3600) return null
var up = slope(win, "up"), down = slope(win, "down")
if (up === null || down === null) return null
// XP and Zen: points, not bytes, so no MiB noise floor; null without data.
var xp = slope(win, "xp"), zen = slope(win, "zenEarned")
return {
up: pace(up),
down: pace(down),
xp: xp === null ? null : Math.max(0, xp) * DAY,
zen: zen === null ? null : Math.max(0, zen) * DAY,
samples: win.length,
spanDays: span / DAY,
partial: span < windowDays * DAY * 0.9
}
}
// Where the counters will be at time `t` if the current pace holds.
function projectAt(last, r, t) {
var dt = (t - last.t) / DAY
var up = last.up + r.up * dt
var down = last.down + r.down * dt
var xp = last.xp !== null && last.xp !== undefined && r.xp !== null && r.xp !== undefined ? last.xp + r.xp * dt : null
// Zen balance, assuming nothing is spent meanwhile.
var zen = last.zen !== null && last.zen !== undefined && r.zen !== null && r.zen !== undefined ? last.zen + r.zen * dt : null
return { t: t, up: up, down: down, ratio: down > 0 ? up / down : null, xp: xp, zen: zen }
}
// Unix time at which a cumulative counter reaches `target`, or null.
function timeToReach(last, r, metric, target) {
if (!r) return null
if (metric === "ratio") {
// (U + a·d) / (D + b·d) = R => d = (R·D − U) / (a − R·b)
var U = last.up, D = last.down, a = r.up, b = r.down
var cur = D > 0 ? U / D : null
if (cur !== null && cur >= target) return last.t
var den = a - target * b
if (den <= 0) return null
var d = (target * D - U) / den
return d >= 0 ? last.t + d * DAY : null
}
var rate = r[metric]
var cur = valueOf(last, metric)
if (cur === null) return null
if (cur >= target) return last.t
if (!(rate > 0)) return null
return last.t + (target - cur) / rate * DAY
}
// Next round figures above `value`: 1-2-5 steps one decade below its size, so
// 12.3 TB gives 13, 14, 15 TB and 850 GB gives 900 GB, 950 GB, 1 TB.
function niceStep(value) {
if (!(value > 0)) return 1
var mag = Math.pow(10, Math.floor(Math.log(value) / Math.LN10) - 1)
var f = value / mag
return mag * (f < 20 ? 1 : f < 50 ? 2 : 5)
}
function nextRound(value, count) {
var out = []
var step = niceStep(value)
var next = (Math.floor(value / step + 1e-9) + 1) * step
for (var i = 0; i < count; i++) { out.push(next); next += step }
return out
}
// Upload milestones in bytes, rounded in the unit the pill uses.
function uploadMilestones(up, count) {
var i = Math.max(0, Math.floor(Math.log(Math.max(up, 1)) / Math.log(1024)))
var unit = Math.pow(1024, i)
var inUnit = up / unit
if (inUnit >= 1000) { unit *= 1024; inUnit = up / unit }
var vals = nextRound(inUnit, count)
return vals.map(function(v) { return v * unit })
}
function ratioMilestones(ratio, count) {
if (ratio === null || ratio === undefined) return []
var step = ratio < 2 ? 0.25 : ratio < 5 ? 0.5 : ratio < 20 ? 1 : 5
var out = []
var next = (Math.floor(ratio / step + 1e-9) + 1) * step
for (var i = 0; i < count; i++) { out.push(next); next += step }
return out
}
// Forecast rows for the panel: {label, value, when, whenText, inText}.
function forecast(samples, now, opts) {
opts = opts || {}
var last = samples.length ? samples[samples.length - 1] : null
var r = last ? rates(samples, now, opts.windowDays || 14) : null
var out = { rates: r, last: last, upload: [], ratio: [], horizons: [] }
if (!last || !r) return out
var upTargets = uploadMilestones(last.up, 3)
if (opts.uploadTarget > 0) upTargets.push(opts.uploadTarget)
for (var i = 0; i < upTargets.length; i++) {
var t = timeToReach(last, r, "up", upTargets[i])
out.upload.push({ value: upTargets[i], custom: i >= 3, when: t, text: formatBytes(upTargets[i], upTargets[i] >= Math.pow(1024, 4) ? 1 : 0, opts.loc) })
}
var ratioTargets = ratioMilestones(ratioOf(last), 2)
if (opts.ratioTarget > 0) ratioTargets.push(opts.ratioTarget)
for (var j = 0; j < ratioTargets.length; j++) {
var tRatio = timeToReach(last, r, "ratio", ratioTargets[j])
out.ratio.push({ isRatio: true, value: ratioTargets[j], custom: j >= 2, when: tRatio, text: formatRatio(ratioTargets[j], opts.loc) })
}
// Next level: XP left from the profile, at the XP pace.
var lv = opts.profile && opts.profile.level ? opts.profile.level : null
out.level = null
if (lv && lv.level !== null && lv.xpToNextLevel !== null && lv.xpToNextLevel !== undefined) {
var whenLevel = lv.xpToNextLevel <= 0 ? last.t
: r.xp > 0 ? last.t + lv.xpToNextLevel / r.xp * DAY : null
out.level = { level: lv.level + 1, when: whenLevel, xpLeft: lv.xpToNextLevel }
}
// Next round Zen balance, if nothing is spent.
out.zen = []
if (last.zen !== null && last.zen !== undefined) {
var zenTargets = nextRound(Math.max(1, last.zen), 1)
for (var z = 0; z < zenTargets.length; z++)
out.zen.push({ value: zenTargets[z], when: timeToReach(last, r, "zen", zenTargets[z]), text: formatCount(zenTargets[z], opts.loc) + " Zen" })
}
var horizons = [30, 90, 365]
for (var k = 0; k < horizons.length; k++) {
var p = projectAt(last, r, last.t + horizons[k] * DAY)
p.days = horizons[k]
out.horizons.push(p)
}
return out
}
// Reduce a series to at most `maxPoints` by averaging time buckets, so a year
// of 30-minute polls still paints fast.
function downsample(points, maxPoints) {
if (points.length <= maxPoints) return points
var t0 = points[0].t, t1 = points[points.length - 1].t
var width = (t1 - t0) / maxPoints
var out = []
var bucket = null
for (var i = 0; i < points.length; i++) {
var b = Math.min(maxPoints - 1, Math.floor((points[i].t - t0) / width))
if (!bucket || bucket.b !== b) {
if (bucket) out.push({ t: bucket.st / bucket.n, v: bucket.sv / bucket.n })
bucket = { b: b, st: 0, sv: 0, n: 0 }
}
bucket.st += points[i].t; bucket.sv += points[i].v; bucket.n++
}
if (bucket) out.push({ t: bucket.st / bucket.n, v: bucket.sv / bucket.n })
// Keep the true latest value as the line's end.
out[out.length - 1] = points[points.length - 1]
return out
}
// Everything the chart canvas needs, in 0..1 coordinates:
// {history: [{x, y, t, v}], projection: [{x, y, t, v}], t0, t1, vMin, vMax, now}.
function chartModel(samples, metric, rangeDays, now, r, maxPoints) {
var start = rangeDays > 0 ? now - rangeDays * DAY : (samples.length ? samples[0].t : now)
var pts = []
for (var i = 0; i < samples.length; i++) {
if (samples[i].t < start) continue
var v = valueOf(samples[i], metric)
if (v === null || v === undefined || isNaN(v)) continue
pts.push({ t: samples[i].t, v: v })
}
if (pts.length === 0) return null
pts = downsample(pts, maxPoints || 240)
var last = samples[samples.length - 1]
var histEnd = pts[pts.length - 1].t
var histStart = Math.min(pts[0].t, histEnd - 3600)
// Projection runs a third of the visible span past the last sample.
var ahead = Math.max(3600, (histEnd - histStart) / 3)
var proj = []
if (r) {
var steps = metric === "ratio" ? 24 : 1
for (var s = 0; s <= steps; s++) {
var p = projectAt(last, r, last.t + ahead * s / steps)
var pv = valueOf(p, metric)
if (pv !== null) proj.push({ t: p.t, v: pv })
}
}
var t0 = histStart, t1 = r ? last.t + ahead : histEnd
var vMin = Infinity, vMax = -Infinity
var all = pts.concat(proj)
for (var j = 0; j < all.length; j++) {
vMin = Math.min(vMin, all[j].v); vMax = Math.max(vMax, all[j].v)
}
if (vMax - vMin < Math.abs(vMax) * 1e-6 || vMax === vMin) {
var padV = Math.max(Math.abs(vMax) * 0.01, metric === "ratio" ? 0.01 : metric === "xp" || metric === "zen" ? 1 : 1024)
vMin -= padV; vMax += padV
} else {
var m = (vMax - vMin) * 0.08
vMin -= m; vMax += m
}
if (metric !== "ratio" || vMin < 0) vMin = Math.max(0, vMin)
function place(p) { return { t: p.t, v: p.v, x: (p.t - t0) / (t1 - t0), y: (p.v - vMin) / (vMax - vMin) } }
return { history: pts.map(place), projection: proj.map(place), t0: t0, t1: t1, vMin: vMin, vMax: vMax, lastT: last.t }
}
function nearest(points, x) {
var best = null, dist = Infinity
for (var i = 0; i < points.length; i++) {
var d = Math.abs(points[i].x - x)
if (d < dist) { dist = d; best = points[i] }
}
return best
}
function formatMetric(metric, v, l) {
if (metric === "ratio") return formatRatio(v, l)
if (metric === "xp") return formatCount(v, l) + " XP"
if (metric === "zen") return formatCount(v, l) + " Zen"
return formatBytes(v, undefined, l)
}
// Change over the last `days`: {delta, from} or null when history is shorter.
// Local midnight at or before `t`.
function dayStart(t) {
var d = new Date(t * 1000)
d.setHours(0, 0, 0, 0)
return d.getTime() / 1000
}
// Daily upload/download and XP/Zen gains, oldest first. Each interval between
// readings is spread over the days it overlaps; Zen uses the earned counter,
// not balance changes. Sparse or missing series stay null rather than guessed.
var MIN_COVERAGE = 3600
function dailyPace(samples, now, days) {
var first = dayStart(now) - (Math.max(1, days) - 1) * DAY
var out = []
// Walk day boundaries with Date so DST days (23 h / 25 h) stay aligned.
for (var d = new Date(first * 1000); d.getTime() / 1000 <= now; d.setDate(d.getDate() + 1)) {
var start = d.getTime() / 1000
var next = new Date(d.getTime()); next.setDate(next.getDate() + 1)
out.push({ t: start, end: next.getTime() / 1000, up: 0, down: 0, xp: 0, zen: 0,
covered: 0, xpCovered: 0, zenCovered: 0 })
}
for (var i = 1; i < samples.length; i++) {
var a = samples[i - 1], b = samples[i]
var span = b.t - a.t
if (!(span > 0) || b.t <= first) continue
var du = Math.max(0, b.up - a.up), dd = Math.max(0, b.down - a.down)
var ax = valueOf(a, "xp"), bx = valueOf(b, "xp")
var az = valueOf(a, "zenEarned"), bz = valueOf(b, "zenEarned")
for (var k = 0; k < out.length; k++) {
var lo = Math.max(a.t, out[k].t), hi = Math.min(b.t, out[k].end)
if (hi <= lo) continue
var share = (hi - lo) / span
out[k].up += du * share
out[k].down += dd * share
out[k].covered += hi - lo
if (ax !== null && ax !== undefined && bx !== null && bx !== undefined) {
out[k].xp += Math.max(0, bx - ax) * share
out[k].xpCovered += hi - lo
}
if (az !== null && az !== undefined && bz !== null && bz !== undefined) {
out[k].zen += Math.max(0, bz - az) * share
out[k].zenCovered += hi - lo
}
}
}
return out.map(function(day) {
var ok = day.covered >= MIN_COVERAGE
return {
t: day.t,
up: ok ? pace(day.up / day.covered) : null,
down: ok ? pace(day.down / day.covered) : null,
xp: day.xpCovered >= MIN_COVERAGE ? day.xp / day.xpCovered * DAY : null,
zen: day.zenCovered >= MIN_COVERAGE ? day.zen / day.zenCovered * DAY : null,
covered: day.covered
}
})
}
function deltaOver(samples, metric, now, days) {
if (samples.length < 2) return null
var last = samples[samples.length - 1]
var target = now - days * DAY
var base = null
for (var i = 0; i < samples.length; i++) {
if (samples[i].t <= target) base = samples[i]
else break
}
if (!base) base = samples[0]
if (base === last) return null
var a, b
if (metric === "ratio" || metric === "zen") {
// Ratio and Zen balance: the real change (spending Zen is real).
a = valueOf(base, metric); b = valueOf(last, metric)
} else {
// Upload/download gained: increases only, so a tracker-side drop in the
// window does not show as negative activity.
var c = continuous(samples)
a = c[samples.indexOf(base)][metric]; b = c[c.length - 1][metric]
}
if (a === null || b === null) return null
return { delta: b - a, from: base.t, full: base.t <= target }
}
function formatDelta(metric, d, l) {
if (!d) return ""
if (metric === "ratio") return (d.delta >= 0 ? "+" : "") + fixed(d.delta, 3, l)
if (metric === "xp" || metric === "zen") return (d.delta >= 0 ? "+" : "-") + formatCount(Math.abs(d.delta), l)
return (d.delta >= 0 ? "+" : "") + formatBytes(d.delta, 1, l)
}
// --- Bar label ------------------------------------------------------------------
//
// A Python-style template, as in Dockarchy: `{key}` is replaced, `{{`/`}}` are
// literal braces, keys are case-insensitive and may carry spaces (`{ up }`),
// unknown keys are left as typed so a typo shows. Anything else is free text,
// so "↑{up} · {ratio} ({ratio7d})" composes several values.
var BAR_KEYS = [
"up", "down", "ratio", "credit", "buffer",
"rate", "downrate",
"up24h", "up7d", "up30d", "down24h", "down7d", "down30d", "ratio24h", "ratio7d", "ratio30d",
"next", "nexteta", "goal", "ratiogoal", "user",
"upreal", "downreal", "downcredit",
"level", "xp", "xpnext", "leveleta", "xprate", "zen", "zenrate", "zen7d",
"fl", "sl", "grade", "quests", "team"
]
var BAR_ALIASES = { upload: "up", ul: "up", download: "down", dl: "down", bonus: "credit", uprate: "rate" }
// The bar is a pill, not a paragraph: a runaway template is cut here.
var MAX_BAR_CHARS = 160
function own(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) }
// Compact time-to-target for the bar: "7 weeks", "✓" once there, "∞" if the
// current pace never gets there, "" when there is no pace yet.
function barEta(when, lastT, now, l) {
if (when === undefined) return ""
if (when === null) return tr(l, "goalNever")
if (when <= lastT) return tr(l, "goalReached")
return formatDuration(when - now, l)
}
// ctx: {samples, now, rates, user, uploadGoal (bytes), ratioGoal, profile}
function barValues(ctx, l) {
var samples = ctx.samples || []
var last = samples.length ? samples[samples.length - 1] : null
if (!last) return null
var r = ctx.rates || null
var now = ctx.now || last.t
function gain(metric, days) { return formatDelta(metric, deltaOver(samples, metric, now, days), l) }
function eta(metric, target) {
if (!(target > 0)) return ""
if (!r) return valueOf(last, metric) >= target ? tr(l, "goalReached") : ""
return barEta(timeToReach(last, r, metric, target), last.t, now, l)
}
var next = uploadMilestones(last.up, 1)[0]
var p = ctx.profile || {}
var tf = p.transfer || {}
var lv = p.level || {}
var lvl = r ? forecast(samples, now, { windowDays: ctx.windowDays || 14, profile: p, loc: l }).level : null
return {
up: formatBytes(last.up, undefined, l),
down: formatBytes(last.down, undefined, l),
ratio: formatRatio(ratioOf(last), l),
credit: formatBytes(last.credit || 0, undefined, l),
buffer: formatBytes(Math.max(0, last.up - last.down), undefined, l),
rate: r ? formatRate(r.up, l) : "",
downrate: r ? formatRate(r.down, l) : "",
up24h: gain("up", 1), up7d: gain("up", 7), up30d: gain("up", 30),
down24h: gain("down", 1), down7d: gain("down", 7), down30d: gain("down", 30),
ratio24h: gain("ratio", 1), ratio7d: gain("ratio", 7), ratio30d: gain("ratio", 30),
next: formatBytes(next, next >= Math.pow(1024, 4) ? 1 : 0, l),
nexteta: eta("up", next),
goal: eta("up", ctx.uploadGoal),
ratiogoal: eta("ratio", ctx.ratioGoal),
user: ctx.user && ctx.user.username ? String(ctx.user.username) : "",
upreal: tf.uploaded && tf.uploaded.actual !== null ? formatBytes(tf.uploaded.actual, undefined, l) : "",
downreal: tf.downloaded && tf.downloaded.actual !== null ? formatBytes(tf.downloaded.actual, undefined, l) : "",
downcredit: formatBytes(last.downCredit || 0, undefined, l),
level: lv.level !== null && lv.level !== undefined ? String(lv.level) : "",
xp: last.xp !== null ? formatCount(last.xp, l) : "",
xpnext: lv.xpToNextLevel !== null && lv.xpToNextLevel !== undefined ? formatCount(lv.xpToNextLevel, l) : "",
leveleta: lvl ? barEta(lvl.when, last.t, now, l) : "",
xprate: r && r.xp !== null ? formatPointsRate(r.xp, l) : "",
zen: last.zen !== null ? formatCount(last.zen, l) : "",
zenrate: r && r.zen !== null ? formatPointsRate(r.zen, l) : "",
zen7d: last.zen !== null ? formatDelta("zen", deltaOver(samples, "zen", now, 7), l) : "",
fl: p.freeleech && p.freeleech.active === true ? tr(l, "barFreeleech") : "",
sl: p.silverLeech === true ? tr(l, "barSilver") : "",
grade: gradeText(p["class"], l),
quests: p["class"] && p["class"].questsTotal ? p["class"].questsCompleted + "/" + p["class"].questsTotal : "",
team: p.team && p.team.tag ? p.team.tag : ""
}
}
// "Argent 2" / "Silver 2": the class grade, tier capitalised as on the site.
function gradeText(klass, l) {
if (!klass || !klass.gradeTier) return ""
var tier = String(klass.gradeTier)
var name = loc(l).tiers && own(loc(l).tiers, tier) ? loc(l).tiers[tier] : tier.charAt(0).toUpperCase() + tier.slice(1)
return klass.gradeLevel !== null && klass.gradeLevel !== undefined ? name + " " + klass.gradeLevel : name
}
function formatBar(template, ctx, l) {
var values = barValues(ctx || {}, l)
if (!values) return ""
var out = String(template || "")
.replace(/\{\{/g, "\u0001").replace(/\}\}/g, "\u0002")
.replace(/\{\s*([a-zA-Z0-9_]+)\s*\}/g, function(match, name) {
var key = name.toLowerCase()
if (own(BAR_ALIASES, key)) key = BAR_ALIASES[key]
return own(values, key) ? values[key] : match
})
.replace(/\u0001/g, "{").replace(/\u0002/g, "}")
// Collapse the template's own spacing only: values keep their no-break
// spaces (French thousands, "4,305 To").
.replace(/[ \t\r\n]+/g, " ")
.replace(/^ | $/g, "")
return out.length > MAX_BAR_CHARS ? out.slice(0, MAX_BAR_CHARS - 1) + "…" : out
}
// --- What-if forecasts --------------------------------------------------------
// Panel tiles, left to right: ratio sits in the middle.
var TILE_ORDER = ["up", "ratio", "down"]
// Second row (2.0): level/XP and Zen drive the chart too; the class tile does not.
var TILE_ORDER_2 = ["xp", "zen"]
var CHART_METRICS = ["up", "ratio", "down", "xp", "zen"]
var UNIT_POWERS = {
b: 0, o: 0,
k: 1, kb: 1, kib: 1, ko: 1,
m: 2, mb: 2, mib: 2, mo: 2,
g: 3, gb: 3, gib: 3, go: 3,
t: 4, tb: 4, tib: 4, to: 4,
p: 5, pb: 5, pib: 5, po: 5
}
var MAX_TARGET_BYTES = 1e21
var MAX_SHOWN_CEILING = 1000