forked from mf-dashboard/mf-dashboard.github.io
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.js
More file actions
1381 lines (1191 loc) · 40.3 KB
/
Copy pathutils.js
File metadata and controls
1381 lines (1191 loc) · 40.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
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
/**
* @file utils.js
* @description Utility functions for my-mf-dashboard
* @author Pabitra Swain https://github.com/the-sdet
* @license MIT
*/
// ============================================
// CONSTANTS & THEME
// ============================================
const themeColors = [
"#667eea",
"#10b981",
"#f59e0b",
"#3b82f6",
"#ef4444",
"#8b5cf6",
"#14b8a6",
"#f472b6",
"#93c5fd",
"#764ba2",
];
const ICONS = {
success: "✅",
error: "❌",
warning: "⚠️",
info: "ℹ️",
};
function getChartTheme() {
const isDark = isDarkMode();
return {
textColor: isDark ? "#C8B8A8" : "#2F241D",
gridColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(231,222,211,0.7)",
borderColor: isDark ? "rgba(255,255,255,0.12)" : "#E7DED3",
tooltipBg: isDark ? "rgba(36,28,22,0.96)" : "rgba(47,36,29,0.92)",
tooltipBorder: isDark ? "#9A6B46" : "#9A6B46",
growthValuation: isDark ? "#C9944A" : "#9A6B46",
growthCost: isDark ? "#6B8C6E" : "#2F8F5B",
};
}
// ============================================
// FORMATTING UTILITIES
// ============================================
function formatNumber(num) {
const rounded = Math.round(num);
return Object.is(rounded, -0) ? "0" : rounded.toLocaleString("en-IN");
}
function fmtAbbr(v) {
const abs = Math.abs(v);
if (abs >= 100000) return `₹${(abs / 100000).toFixed(2)}L`;
if (abs >= 1000) return `₹${(abs / 1000).toFixed(1)}K`;
return `₹${Math.round(abs)}`;
}
function sortData(labels, data) {
const combined = labels.map((label, i) => ({ label, value: data[i] }));
combined.sort((a, b) => b.value - a.value);
return [combined.map((d) => d.label), combined.map((d) => d.value)];
}
const titleCache = new Map();
function sanitizeSchemeName(schemeName) {
if (!schemeName) return "";
// Step 1: strip trailing parenthetical qualifiers like:
// "( formerly Parag Parikh Long Term Value Fund )"
// "( Non - Demat )" "( Non Demat )"
let name = schemeName
.replace(/\(\s*formerly\b[^)]*\)/gi, "") // ( formerly ... )
.replace(/\(\s*non\s*-?\s*demat\s*\)/gi, "") // ( Non - Demat )
.trim();
// Step 2: split on " - " and keep only the fund name part
// (everything before the first plan/option/growth/direct segment)
const segments = name.split(/\s+-\s+/);
const planKeywords =
/^(direct|regular|growth|dividend|idcw|option|plan|reinvest|payout)/i;
let fundNameParts = [];
for (const seg of segments) {
if (planKeywords.test(seg.trim())) break;
fundNameParts.push(seg.trim());
}
const fundName = fundNameParts.join(" - ").trim() || segments[0].trim();
// Step 3: extract up to and including the first occurrence of "Fund"
const fundMatch = fundName.match(/^.*?\bFund\b/i);
const result = fundMatch ? fundMatch[0].trim() : fundName;
return fixCapitalization(result);
}
// Returns a stable grouping key for a scheme/folio so that the same fund
// (identified by ISIN) is always grouped together in fundWiseData, even if
// the raw scheme name string differs across folios (e.g. one folio's CAS
// entry says "... Direct Plan Growth ( Non Demat )" while another says
// "... Direct Plan Growth"). Falls back to a sanitized scheme name when ISIN
// is unavailable.
function getFundKey(schemeOrFolio) {
if (!schemeOrFolio) return "";
const isin = schemeOrFolio.isin;
if (isin && typeof isin === "string" && isin.trim()) {
return isin.trim().toUpperCase();
}
const name = schemeOrFolio.scheme || "";
return sanitizeSchemeName(name).toLowerCase();
}
function fixCapitalization(text) {
if (!text) return "";
const words = text.split(" ");
const allUpperCase = words.every(
(word) => word === word.toUpperCase() && word.length > 0,
);
const uppercaseWords = [
"SBI",
"ICICI",
"HDFC",
"UTI",
"LIC",
"IDFC",
"BOI",
"BOB",
"PNB",
"HSBC",
"JM",
"DSP",
"ITI",
"PGIM",
"PPFAS",
"IIFL",
];
const lowercaseWords = [
"of",
"and",
"or",
"the",
"a",
"an",
"in",
"on",
"at",
"to",
"for",
];
return words
.map((word, index) => {
if (uppercaseWords.includes(word.toUpperCase())) {
return word.toUpperCase();
}
if (allUpperCase) {
if (index === 0) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
if (lowercaseWords.includes(word.toLowerCase())) {
return word.toLowerCase();
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
if (index === 0 && word === word.toUpperCase() && word.length <= 6) {
return word;
}
if (index === 0 && word === word.toLowerCase()) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
if (word === word.toLowerCase() && !lowercaseWords.includes(word)) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return word;
})
.join(" ");
}
function standardizeTitle(title) {
if (!title) return "";
if (titleCache.has(title)) {
return titleCache.get(title);
}
const words = title.split(" ");
const result = words
.map((word, index) => {
if (index === 0) {
const specialWords = ["NIPPON", "QUANT", "MOTILAL"];
if (specialWords.includes(word.toUpperCase())) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
} else {
return word;
}
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join(" ");
titleCache.set(title, result);
return result;
}
// ============================================
// DATE UTILITIES
// ============================================
function parseDate(dateStr) {
if (!dateStr) return null;
const dmy = dateStr.match(/(\d{1,2})-([A-Z]{3}|\d{1,2})-(\d{4})/i);
if (dmy) {
const day = parseInt(dmy[1]);
let month;
if (isNaN(parseInt(dmy[2]))) {
const months = {
jan: 0,
feb: 1,
mar: 2,
apr: 3,
may: 4,
jun: 5,
jul: 6,
aug: 7,
sep: 8,
oct: 9,
nov: 10,
dec: 11,
};
month = months[dmy[2].toLowerCase()];
} else {
month = parseInt(dmy[2]) - 1;
}
const year = parseInt(dmy[3]);
return new Date(year, month, day, 12, 0, 0, 0);
}
const parsed = new Date(dateStr);
if (!isNaN(parsed.getTime())) {
parsed.setHours(12, 0, 0, 0);
return parsed;
}
return null;
}
function getFinancialYear(date) {
const d = new Date(date);
if (isNaN(d)) throw new Error("Invalid date");
const year = d.getFullYear();
const month = d.getMonth();
const fyStartYear = month >= 3 ? year : year - 1;
const fyEndYear = fyStartYear + 1;
return `FY ${fyStartYear}-${String(fyEndYear).slice(-2)}`;
}
// ============================================
// CHART UTILITIES
// ============================================
function destroyIfExists(chartRef) {
if (chartRef) {
try {
if (typeof chartRef.destroy === "function") {
chartRef.destroy();
}
} catch (e) {
console.warn("Error destroying chart:", e);
}
}
return null;
}
// Registry of live doughnut chart instances, keyed by canvas id, so repeat
// renders destroy the previous Chart.js instance before creating a new one.
const _donutChartRegistry = {};
/**
* Renders a doughnut chart into `canvasId` plus a label list below it in the
* consistent format: "Name: ₹value (pct%)". Used across the Dashboard and
* Family Dashboard for Asset Allocation, Equity Split, Debt Split, AMC
* Split, Equity Sectors, Debt Sectors and Portfolio Holdings.
*
* @param {string} canvasId id of the <canvas> element
* @param {string[]} labels slice labels
* @param {number[]} data slice values as percentages (0-100)
* @param {number} [totalValue] portfolio rupee value used to compute the
* rupee amount shown next to each label
*/
// One-time registration of the doughnut center-text plugin.
if (!Chart.registry.plugins.get("doughnutCenterText")) {
Chart.register({
id: "doughnutCenterText",
afterDraw(chart) {
const cfg = chart.options.plugins?.centerText;
if (!cfg?.display || !cfg.value) return;
const { ctx, chartArea } = chart;
const cx = (chartArea.left + chartArea.right) / 2;
const cy = (chartArea.top + chartArea.bottom) / 2;
// Shift the whole block up slightly so it reads as optically centred
const blockOffset = -3;
const lineGap = 9;
ctx.save();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
// "Total" — small, muted, above value
ctx.font = `500 10px Inter, system-ui, sans-serif`;
ctx.fillStyle = cfg.labelColor || "rgba(107,114,128,0.85)";
ctx.fillText("Total", cx, cy + blockOffset - lineGap);
// Rupee value — bold, below label
ctx.font = `700 13px Inter, system-ui, sans-serif`;
ctx.fillStyle = cfg.valueColor || "#374151";
ctx.fillText(cfg.value, cx, cy + blockOffset + lineGap);
ctx.restore();
},
});
}
function buildDoughnutChart(canvasId, labels, data, totalValue = 0) {
const canvas = document.getElementById(canvasId);
if (!canvas) {
console.warn(`Canvas element '${canvasId}' not found`);
return null;
}
// Destroy any previous chart instance bound to this canvas
_donutChartRegistry[canvasId] = destroyIfExists(
_donutChartRegistry[canvasId],
);
const colors = getChartTheme();
const isDark = isDarkMode();
// Ensure the canvas sits inside a fixed-size box so Chart.js can size
// itself correctly, with a label list rendered below it.
let canvasBox = canvas.closest(".donut-canvas-box");
if (!canvasBox) {
canvasBox = document.createElement("div");
canvasBox.className = "donut-canvas-box";
canvas.parentNode.insertBefore(canvasBox, canvas);
canvasBox.appendChild(canvas);
}
const wrapper = canvasBox.parentElement;
let labelsContainer = wrapper.querySelector(".donut-labels");
if (!labelsContainer) {
labelsContainer = document.createElement("div");
labelsContainer.className = "donut-labels";
wrapper.appendChild(labelsContainer);
}
const sliceColors = getDoughnutColors(labels.length, labels);
// Neutral gap between slices — matches card background so segments feel
// cleanly separated without any coloured border artifact.
const gapColor = isDark ? "#1c1f2e" : "#ffffff";
const centerTextCfg = {
display: true,
value:
totalValue > 0
? `₹${formatNumber(Math.round(totalValue))}`
: `${labels.length} items`,
labelColor: isDark ? "rgba(156,163,175,0.85)" : "rgba(107,114,128,0.85)",
valueColor: isDark ? "#e5e7eb" : "#1f2937",
};
const ctx = canvas.getContext("2d");
const chart = new Chart(ctx, {
type: "doughnut",
data: {
labels,
datasets: [
{
data,
backgroundColor: sliceColors,
borderColor: gapColor,
borderWidth: 2,
hoverOffset: 10,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: "64%",
plugins: {
legend: {
display: false,
},
centerText: centerTextCfg,
tooltip: {
enabled: true,
backgroundColor: colors.tooltipBg,
borderColor: colors.tooltipBorder,
borderWidth: 2,
cornerRadius: 8,
titleFont: { size: 13, weight: "bold" },
bodyFont: { size: 12 },
titleColor: "#fff",
bodyColor: "#fff",
displayColors: false,
padding: 8,
callbacks: {
title: (items) => items[0].label,
label: (ctx) => {
const val = ctx.parsed ?? 0;
if (totalValue > 0) {
const rupeeValue = (totalValue * val) / 100;
return `₹${formatNumber(Math.round(rupeeValue))} (${val.toFixed(2)}%)`;
}
return `${val.toFixed(2)}%`;
},
},
},
},
layout: {
padding: { top: 5, right: 5, bottom: 5, left: 5 },
},
animation: {
animateRotate: true,
animateScale: true,
duration: 800,
easing: "easeInOutQuart",
},
},
});
_donutChartRegistry[canvasId] = chart;
// Build the label list below the chart in "Name: ₹value (pct%)" or "Name: pct%" format
labelsContainer.innerHTML = labels
.map((label, i) => {
const pct = data[i];
const valueText =
totalValue > 0
? `₹${formatNumber(Math.round((totalValue * pct) / 100))} (${pct.toFixed(2)}%)`
: `${pct.toFixed(2)}%`;
return `
<div class="donut-label-item">
<span class="donut-label-color" style="background-color: ${sliceColors[i]};"></span>
<span class="donut-label-name" title="${label}">${label}</span>
<span class="donut-label-value">${valueText}</span>
</div>`;
})
.join("");
return chart;
}
function adjustXAxisLabels(chart) {
const ctx = chart.ctx;
const xAxis = chart.scales.x;
if (!xAxis) return;
const ticks = xAxis.ticks;
if (ticks.length < 2) return;
ctx.font = `${chart.options.scales.x.ticks.font?.size || 12}px ${
chart.options.scales.x.ticks.font?.family || "sans-serif"
}`;
const labelWidth = Math.max(
...ticks.map((t) => ctx.measureText(t.label).width),
);
const tickDistance = xAxis.width / (ticks.length - 1) || 1;
if (labelWidth > tickDistance * 0.9) {
chart.options.scales.x.ticks.maxRotation = 45;
chart.options.scales.x.ticks.minRotation = 30;
} else {
chart.options.scales.x.ticks.maxRotation = 0;
chart.options.scales.x.ticks.minRotation = 0;
}
chart.update("none");
}
// ============================================
// XIRR CALCULATOR
// ============================================
class XIRRCalculator {
constructor() {
this.transactions = [];
this.xirrResult = null;
}
addTransaction(type, date, amount) {
const normalizedAmount =
type.toLowerCase() === "buy" ? -Math.abs(amount) : Math.abs(amount);
this.transactions.push({
type: type,
date: new Date(date),
amount: normalizedAmount,
displayAmount: Math.abs(amount),
});
this.sortTransactions();
}
sortTransactions() {
this.transactions.sort((a, b) => a.date - b.date);
}
parseDate(dateStr) {
if (!dateStr) return null;
const dmy = dateStr.match(/(\d{1,2})-([A-Z]{3})-(\d{4})/i);
if (dmy) {
const months = {
jan: 0,
feb: 1,
mar: 2,
apr: 3,
may: 4,
jun: 5,
jul: 6,
aug: 7,
sep: 8,
oct: 9,
nov: 10,
dec: 11,
};
const day = parseInt(dmy[1]);
const month = months[dmy[2].toLowerCase()];
const year = parseInt(dmy[3]);
return new Date(year, month, day);
}
const dmy2 = dateStr.match(/(\d{1,2})\/(\d{1,2})\/(\d{2,4})/);
if (dmy2) {
const day = parseInt(dmy2[1]);
const month = parseInt(dmy2[2]) - 1;
let year = parseInt(dmy2[3]);
if (year < 100) {
year = year < 50 ? 2000 + year : 1900 + year;
}
return new Date(year, month, day);
}
const parsed = new Date(dateStr);
if (!isNaN(parsed.getTime())) {
return parsed;
}
return null;
}
daysBetween(d1, d2) {
return (d2 - d1) / (1000 * 60 * 60 * 24);
}
npv(rate) {
const firstDate = this.transactions[0].date;
return this.transactions.reduce((sum, t) => {
const years = this.daysBetween(firstDate, t.date) / 365;
return sum + t.amount / Math.pow(1 + rate, years);
}, 0);
}
dNpv(rate) {
const firstDate = this.transactions[0].date;
return this.transactions.reduce((sum, t) => {
const years = this.daysBetween(firstDate, t.date) / 365;
const factor = Math.pow(1 + rate, years);
return sum - (years * t.amount) / (factor * (1 + rate));
}, 0);
}
calculateXIRR(guess = 0.1) {
if (this.transactions.length < 2) {
throw new Error("At least 2 transactions required");
}
const hasPositive = this.transactions.some((t) => t.amount > 0);
const hasNegative = this.transactions.some((t) => t.amount < 0);
if (!hasPositive || !hasNegative) {
throw new Error("Need both positive and negative cash flows");
}
const maxIterations = 100;
const precision = 1e-6;
let rate = guess;
for (let i = 0; i < maxIterations; i++) {
const npvValue = this.npv(rate);
const npvDerivative = this.dNpv(rate);
if (Math.abs(npvValue) < precision) {
this.xirrResult = rate;
return rate * 100;
}
if (Math.abs(npvDerivative) < 1e-10) {
break;
}
const newRate = rate - npvValue / npvDerivative;
if (newRate < -0.99) {
rate = -0.99;
} else if (newRate > 10) {
rate = 10;
} else {
rate = newRate;
}
if (
i > 0 &&
Math.abs(rate - (rate - npvValue / npvDerivative)) < precision
) {
break;
}
}
let low = -0.99;
let high = 5;
let npvLow = this.npv(low);
let npvHigh = this.npv(high);
if (npvLow * npvHigh > 0) {
for (let i = 0; i < 50; i++) {
if (Math.abs(npvLow) < Math.abs(npvHigh)) {
low = low - (high - low);
low = Math.max(low, -0.99);
npvLow = this.npv(low);
} else {
high = high + (high - low);
high = Math.min(high, 10);
npvHigh = this.npv(high);
}
if (npvLow * npvHigh < 0) {
break;
}
}
}
if (npvLow * npvHigh < 0) {
for (let i = 0; i < maxIterations; i++) {
rate = (low + high) / 2;
const npvMid = this.npv(rate);
if (Math.abs(npvMid) < precision) {
this.xirrResult = rate;
return rate * 100;
}
if (npvMid * npvLow < 0) {
high = rate;
npvHigh = npvMid;
} else {
low = rate;
npvLow = npvMid;
}
if (Math.abs(high - low) < precision) {
this.xirrResult = rate;
return rate * 100;
}
}
}
this.xirrResult = rate;
return rate * 100;
}
clear() {
this.transactions = [];
this.xirrResult = null;
}
}
// ============================================
// UI UTILITIES
// ============================================
function getToastContainer() {
let container = document.querySelector(".toast-container");
if (!container) {
container = document.createElement("div");
container.className = "toast-container";
document.body.appendChild(container);
}
return container;
}
function showToast(message, type = "info") {
const container = getToastContainer();
const toast = document.createElement("div");
toast.className = `toast ${type}`;
const icon = ICONS[type] || "";
toast.innerText = `${icon} ${message}`;
container.appendChild(toast);
setTimeout(() => toast.classList.add("show"), 10);
setTimeout(() => {
toast.classList.remove("show");
setTimeout(() => toast.remove(), 300);
}, 3000);
}
function lockBodyScroll() {
const scrollY = window.scrollY;
const scrollBarWidth =
window.innerWidth - document.documentElement.clientWidth;
document.body.dataset.scrollY = scrollY;
document.documentElement.style.overflow = "hidden";
document.body.style.overflow = "hidden";
document.body.style.position = "fixed";
document.body.style.top = `-${scrollY}px`;
document.body.style.width = "100%";
document.body.style.paddingRight = `${scrollBarWidth}px`;
}
function unlockBodyScroll() {
const scrollY = parseInt(document.body.dataset.scrollY || "0", 10);
document.documentElement.style.overflow = "";
document.body.style.overflow = "";
document.body.style.position = "";
document.body.style.top = "";
document.body.style.width = "";
document.body.style.paddingRight = "";
window.scrollTo(0, scrollY);
}
// ─── Processing Splash ────────────────────────────────────────────────────────
// Step definitions drive the animated progress sequence shown to the user.
// percent thresholds MUST match updateProcessingProgress() call-sites in scripts.js:
// 0 → showProcessingSplash() – CAS file handed to backend
// 20 → updateProcessingProgress(20, …) – CAS parsed and read
// 40 → updateProcessingProgress(40, …) – MF stats fetch started
// 70 → updateProcessingProgress(70, …) – Stats received, aggregating data
// 90 → updateProcessingProgress(90, …) – Rendering charts & dashboard
// 100 → hideProcessingSplash() – All done
const SPLASH_STEPS = [
{ at: 0, label: "Reading CAS", icon: "📄" },
{ at: 20, label: "CAS Read", icon: "✅" },
{ at: 40, label: "Pulling MF stats", icon: "🔍" },
{ at: 70, label: "Data Aggregated", icon: "🗂️" },
{ at: 90, label: "Rendering Dashboard", icon: "📊" },
{ at: 100, label: "Done!", icon: "🎉" },
];
function _getOrCreateSplashOverlay() {
let overlay = document.getElementById("folio-splash-overlay");
if (overlay) return overlay;
overlay = document.createElement("div");
overlay.id = "folio-splash-overlay";
overlay.innerHTML = `
<style>
#folio-splash-overlay {
position: fixed; inset: 0; z-index: 9999;
display: flex; align-items: center; justify-content: center;
background: rgba(var(--bg-primary-rgb, 15,15,20), 0.82);
backdrop-filter: blur(18px);
opacity: 0; transition: opacity 0.25s ease;
pointer-events: none;
}
#folio-splash-overlay.fsp-visible {
opacity: 1; pointer-events: all;
}
.fsp-card {
background: var(--card-bg, #16161e);
border: 1px solid var(--border-color, rgba(255,255,255,0.08));
border-radius: 20px;
padding: 36px 40px 32px;
width: min(420px, 88vw);
box-shadow: 0 32px 80px rgba(0,0,0,0.55);
display: flex; flex-direction: column; gap: 28px;
}
.fsp-header {
display: flex; flex-direction: column; align-items: center; gap: 10px;
text-align: center;
}
.fsp-logo-ring {
width: 56px; height: 56px; border-radius: 50%;
background: linear-gradient(135deg, var(--accent, #7c6ef7) 0%, var(--accent-secondary, #5bb8f5) 100%);
display: flex; align-items: center; justify-content: center;
font-size: 24px;
box-shadow: 0 0 0 8px rgba(124,110,247,0.12);
animation: fsp-pulse 2.4s ease-in-out infinite;
}
@keyframes fsp-pulse {
0%, 100% { box-shadow: 0 0 0 8px rgba(124,110,247,0.12); }
50% { box-shadow: 0 0 0 16px rgba(124,110,247,0.04); }
}
.fsp-title {
font-size: 15px; font-weight: 600; letter-spacing: 0.01em;
color: #fff;
}
.fsp-steps { display: flex; flex-direction: column; gap: 10px; }
.fsp-step {
display: flex; align-items: center; gap: 12px;
padding: 10px 14px; border-radius: 12px;
background: var(--bg-secondary, rgba(255,255,255,0.04));
border: 1px solid transparent;
transition: all 0.35s cubic-bezier(.4,0,.2,1);
opacity: 0.35;
}
.fsp-step.fsp-step--done {
opacity: 1;
border-color: rgba(80,210,140,0.25);
background: rgba(80,210,140,0.06);
}
.fsp-step.fsp-step--active {
opacity: 1;
border-color: rgba(var(--accent-rgb, 124,110,247), 0.4);
background: rgba(var(--accent-rgb, 124,110,247), 0.08);
}
.fsp-step-icon {
width: 30px; height: 30px; border-radius: 50%; flex-shrink: 0;
display: flex; align-items: center; justify-content: center;
font-size: 14px;
background: var(--bg-tertiary, rgba(255,255,255,0.06));
border: 1.5px solid rgba(255,255,255,0.08);
transition: all 0.3s ease;
}
.fsp-step--active .fsp-step-icon {
background: rgba(var(--accent-rgb, 124,110,247), 0.18);
border-color: rgba(var(--accent-rgb, 124,110,247), 0.5);
animation: fsp-spin-soft 1.8s linear infinite;
}
.fsp-step--done .fsp-step-icon {
background: rgba(80,210,140,0.15);
border-color: rgba(80,210,140,0.4);
animation: none;
}
@keyframes fsp-spin-soft {
0% { box-shadow: 3px 0 0 0 rgba(var(--accent-rgb,124,110,247),0.6); }
25% { box-shadow: 0 3px 0 0 rgba(var(--accent-rgb,124,110,247),0.6); }
50% { box-shadow: -3px 0 0 0 rgba(var(--accent-rgb,124,110,247),0.6); }
75% { box-shadow: 0 -3px 0 0 rgba(var(--accent-rgb,124,110,247),0.6); }
100% { box-shadow: 3px 0 0 0 rgba(var(--accent-rgb,124,110,247),0.6); }
}
.fsp-step-label {
font-size: 13px; font-weight: 500;
color: #fff;
transition: color 0.3s ease;
}
.fsp-step--active .fsp-step-label,
.fsp-step--done .fsp-step-label {
color: #fff;
}
.fsp-step-check {
margin-left: auto; font-size: 13px; opacity: 0; color: #fff;
transition: opacity 0.3s ease;
}
.fsp-step--done .fsp-step-check { opacity: 1; }
/* Bubbles */
.fsp-bubbles {
position: absolute; inset: 0; overflow: hidden;
pointer-events: none; border-radius: 20px;
}
.fsp-bubble {
position: absolute; border-radius: 50%;
background: radial-gradient(circle at 35% 35%,
rgba(var(--accent-rgb,124,110,247),0.25),
rgba(var(--accent-rgb,124,110,247),0.04) 70%);
animation: fsp-float linear infinite;
}
@keyframes fsp-float {
0% { transform: translateY(0) scale(1); opacity: 0; }
10% { opacity: 1; }
90% { opacity: 0.6; }
100% { transform: translateY(-340px) scale(1.1); opacity: 0; }
}
</style>
<div class="fsp-card" style="position:relative;overflow:hidden;">
<div class="fsp-bubbles" id="fsp-bubbles"></div>
<div class="fsp-header">
<div class="fsp-logo-ring" id="fsp-ring">📄</div>
<div class="fsp-title">Processing your portfolio…</div>
</div>
<div class="fsp-steps" id="fsp-steps"></div>
</div>
`;
document.body.appendChild(overlay);
// Build step rows
const stepsContainer = overlay.querySelector("#fsp-steps");
SPLASH_STEPS.forEach((step, i) => {
const row = document.createElement("div");
row.className = "fsp-step";
row.id = `fsp-step-${i}`;
row.innerHTML = `
<div class="fsp-step-icon">${step.icon}</div>
<span class="fsp-step-label">${step.label}</span>
<span class="fsp-step-check">✓</span>
`;
stepsContainer.appendChild(row);
});
// Spawn bubbles
const bubbleContainer = overlay.querySelector("#fsp-bubbles");
for (let b = 0; b < 9; b++) {
const bEl = document.createElement("div");
bEl.className = "fsp-bubble";
const size = 18 + Math.random() * 36;
bEl.style.cssText = `
width:${size}px; height:${size}px;
left:${5 + Math.random() * 90}%;
bottom:${-size}px;
animation-duration:${3.5 + Math.random() * 4}s;
animation-delay:${Math.random() * 5}s;
`;
bubbleContainer.appendChild(bEl);
}
return overlay;
}
function _splashSetStep(percent) {
const overlay = document.getElementById("folio-splash-overlay");
if (!overlay) return;
// Find active step index: last step whose threshold ≤ current percent
let activeIdx = 0;
SPLASH_STEPS.forEach((s, i) => {
if (percent >= s.at) activeIdx = i;
});
SPLASH_STEPS.forEach((_, i) => {
const row = overlay.querySelector(`#fsp-step-${i}`);
if (!row) return;
row.classList.remove("fsp-step--active", "fsp-step--done");
if (i < activeIdx) row.classList.add("fsp-step--done");
else if (i === activeIdx) row.classList.add("fsp-step--active");
});
// Update ring emoji to match active step
const ring = overlay.querySelector("#fsp-ring");
if (ring) ring.textContent = SPLASH_STEPS[activeIdx].icon;
}
function showProcessingSplash() {
// Hide legacy .loader if present (no-op if absent)
const legacy = document.querySelector(".loader");
if (legacy) legacy.classList.add("hidden");
const overlay = _getOrCreateSplashOverlay();
// Reset to step 0
_splashSetStep(0);
// Trigger fade-in on next frame
requestAnimationFrame(() => overlay.classList.add("fsp-visible"));
}
function hideProcessingSplash() {
const overlay = document.getElementById("folio-splash-overlay");
if (!overlay) return;
// Jump to 100 % and flash Done state briefly before fading out
// _splashSetStep(100);
updateProcessingProgress(100, "Done!");
setTimeout(() => {
overlay.classList.remove("fsp-visible");
}, 620);
}
function updateProcessingProgress(percent, message) {
_splashSetStep(percent);
// Optionally drive the title text if a message is provided
const overlay = document.getElementById("folio-splash-overlay");
if (overlay && message) {