-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.tsx
More file actions
2381 lines (2174 loc) · 105 KB
/
Copy pathapp.tsx
File metadata and controls
2381 lines (2174 loc) · 105 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 WisdomTree Watchlist Application
* Client-side static feed viewer for api/wisdomtree/** with multi-ETF Watchlist
* aggregation. Same single-file approach as daggerok/Amplify: the paginated
* static API and lazy sheet loading follow daggerok/iShares.
*
* Babel standalone note: the inline pipeline strips type annotations, but it
* does not accept every TypeScript-only expression. Follow the Amplify dev
* style — plain `byId()` instead of DOM casts, no `as` casts, no non-null
* `!`, no interfaces or enums.
*/
/// <reference types="bun" />
// =========================================================================
// 1. Types, constants & column tooltips
// =========================================================================
type ActiveTab = string;
type SortDirection = 'asc' | 'desc';
type TableRow = Record<string, unknown> & { searchIndex?: string };
type TabInfo = { id: ActiveTab; label: string; count: number | string };
type IndexFund = {
ticker: string;
name: string;
category: string;
fundPage: string;
dataFile: string;
ter: string;
terValue: number;
nav: string;
navValue: number;
aum: string;
aumValue: number;
asOfDate: string;
inceptionDate: string;
exchange: string;
closePrice: string;
premiumDiscount: string;
cusip?: string | null;
isin?: string | null;
distributions: { frequency: string; exDate: string; dividend: string };
returns: { monthEnd: Record<string, any>; quarterEnd: Record<string, any> };
metrics?: {
tr1y?: number | null;
tr3y?: number | null;
tr5y?: number | null;
tr10y?: number | null;
cagr3y?: number | null;
cagr5y?: number | null;
cagr10y?: number | null;
siAnn?: number | null;
dividendYield?: number | null;
dividendYieldText?: string | null;
secYield?: number | null;
secYieldText?: string | null;
};
holdings: number;
history: number;
};
type FundRow = TableRow & {
ticker: string;
name: string;
category: string;
fundPage: string;
ter: string;
terValue: number;
nav: string;
navValue: number;
aum: string;
aumValue: number;
asOfDate: string;
inceptionDate: string;
exchange: string;
closePrice: string;
premiumDiscount: string;
ytd: number;
yr1: number;
yr3: number;
yr5: number;
yr10: number;
si: number;
tr3y?: number | null;
tr5y?: number | null;
tr10y?: number | null;
cagr3y?: number | null;
cagr5y?: number | null;
cagr10y?: number | null;
dividendYield?: number | null;
dividendFrequency: string;
secYield?: number | null;
returnAsOf: string;
returns?: { monthEnd: Record<string, any>; quarterEnd: Record<string, any> };
distributions?: { frequency: string; exDate: string; dividend: string };
holdings: number;
history: number;
};
type WatchlistRow = TableRow & {
key: string;
symbol: string;
name: string;
funds: string[];
fundCount: number;
weightSum: number;
maxWeight: number;
cusips: string[];
identifier: string;
};
const INDEX_URL = './api/wisdomtree/index.json';
const THEME_KEY = 'wisdomtree-theme';
const SELECTED_KEY = 'wisdomtree-selected-etfs';
const BLACKLIST_KEY = 'wisdomtree-blacklisted-etfs';
const ACTIVE_FUND_KEY = 'wisdomtree-active-fund';
const FILTERS_KEY = 'wisdomtree-tab-filters';
const LEGACY_FILTERS_KEY = 'wisdomtree-searches'; // pre-rename key, migrated at boot
const SORTS_KEY = 'wisdomtree-tab-sorts';
const SITE_STATE_KEY = 'wisdomtree-site-state';
const HOLDINGS_CONCURRENCY = 6; // bounded whole-catalog aggregation workers
const WATCHLIST_CHUNK = 250; // rows per rendered Watchlist DOM chunk
const DEFAULT_SELECTED_TICKERS: string[] = []; // start clean: no pre-selected funds
const DETAIL_TABS: Array<{ key: string; label: string }> = [
{ key: 'overview', label: 'Overview' },
{ key: 'holdings', label: 'Holdings' },
{ key: 'history', label: 'History' },
{ key: 'distributions', label: 'Distributions' },
];
const NUMERIC_SHEET_HEADERS = ['Weight', 'Shares Held', 'Shares Outstanding', 'Total Net Assets', 'Par Value', 'Market Value', 'Coupon', 'NAV'];
// Hover explanations for table headers. Native `title` tooltips, same pattern as daggerok/iShares.
const COLUMN_TOOLTIPS: Record<string, string> = {
'#': 'Row index in current table view.',
Use: 'Use / Multi-ETF Selection — Check this box to include this ETF\'s underlying holdings in the combined Watchlist tab.',
Ticker: 'Ticker Symbol — Unique stock market identifier. For holdings: the exchange ticker resolved from public SEC / exchange data at data-build time. "—" when the position has no exchange ticker (bond, private debt) — then the Identifier is the key.',
'Fund Name': 'Fund Name — Official WisdomTree product-page name of the exchange-traded fund (ETF).',
Category: 'Category — WisdomTree groups its ETFs by asset class and sub-category (for example, Fixed Income / Treasury / Government); the tab shows the asset class, the full grouping is kept in meta.json.',
Name: 'Security Name — Full registered legal name of the company or underlying financial asset.',
Identifier: 'CUSIP / ISIN — Security identifier from the official product page or N-PORT filing. Positions without an exchange ticker (bonds, cash, futures) are identified in the Watchlist by this.',
SEDOL: 'SEDOL — Stock Exchange Daily Official List identifier.',
TER: 'Gross Expense Ratio — Total annual fund operating expenses as a % of assets.',
NAV: 'NAV (Net Asset Value) — Per-share dollar value of the fund.',
'Net Assets': 'Net Assets (AUM) — Total market value of all fund assets minus liabilities.',
Weight: 'Weight — Position weight as a percentage of the fund\'s total net assets.',
'Weight Sum': 'Weight Sum — Summed weight of this holding across all selected ETFs (%).',
'Max Weight': 'Max Weight — Highest single-fund weight for this holding across selected ETFs (%).',
'# ETFs': 'Number of selected ETFs that currently hold this security.',
ETFs: 'Selected ETFs holding this security.',
Type: 'Category — the asset-class part of the official WisdomTree grouping (see the Category column). Same source as the category tabs.',
Expense: 'Gross Expense Ratio — Total annual fund operating expenses as a % of assets.',
'Dividend Yield': 'Dividend Yield — the trailing-12-month yield published in the WisdomTree catalog when present; otherwise indicated (latest distribution per share x payments per year / market price) from Yahoo dividend history.',
'SEC Yield': 'SEC Yield (30-Day) — The 30-day SEC yield as published on the official WisdomTree product page; "—" when that page does not publish one.',
'YTD Return': 'YTD Return — Market-price total return since the start of the year, computed from adjusted closes (Yahoo). Not an official NAV return.',
'TR 1Y': 'TR 1Y (1-Year Total Return) — Official WisdomTree Market Price Return where published, otherwise adjusted market-price return from Yahoo.',
'TR 3Y': 'TR 3Y (3-Year Total Return) — Cumulative market-price return over 3 years, derived exactly from the 3Y CAGR: (1 + CAGR 3Y)^3 - 1 (adjusted closes).',
'TR 5Y': 'TR 5Y (5-Year Total Return) — Cumulative market-price return over 5 years, derived exactly from the 5Y CAGR: (1 + CAGR 5Y)^5 - 1 (adjusted closes).',
'TR 10Y': 'TR 10Y (10-Year Total Return) — Cumulative market-price return over 10 years, derived exactly from the 10Y CAGR: (1 + CAGR 10Y)^10 - 1 (adjusted closes).',
'CAGR 3Y': 'CAGR 3Y (3-Year Compound Annual Growth Rate) — Annualized market-price return over 3 years, computed from adjusted closes.',
'CAGR 5Y': 'CAGR 5Y (5-Year Compound Annual Growth Rate) — Annualized market-price return over 5 years, computed from adjusted closes.',
'CAGR 10Y': 'CAGR 10Y (10-Year Compound Annual Growth Rate) — Annualized market-price return over 10 years, computed from adjusted closes.',
YTD: 'YTD market-price total return, last trading day (adjusted closes).',
'1Y': '1-year official WisdomTree Market Price Return where published, otherwise adjusted market-price return, month-end series.',
'3Y': '3-year average annual market-price return (CAGR), official WisdomTree Market Price Return where published, otherwise Yahoo adjusted close.',
'5Y': '5-year average annual market-price return (CAGR), official WisdomTree Market Price Return where published, otherwise Yahoo adjusted close.',
'10Y': '10-year average annual market-price return (CAGR), official WisdomTree Market Price Return where published, otherwise Yahoo adjusted close.',
'SI Ann.': 'Since-inception annualized market-price return, official WisdomTree Market Price Return where published, otherwise Yahoo adjusted close.',
'Return As Of': 'As-of date of the month-end return series.',
Inception: 'Fund inception date.',
Exchange: 'Primary listing exchange.',
Close: 'Most recent closing market price.',
'Prem/Disc': 'Premium / Discount — Closing price versus NAV (%).',
Holdings: 'Rows in the fund\'s latest daily holdings file.',
History: 'Rows in the fund\'s NAV history file.',
'As Of': 'NAV / AUM as-of date.',
Frequency: 'Frequency — sortable payment cadence from the Yahoo dividend history: 01 - Monthly, 04 - Quarterly, 06 - Semi-annually, 12 - Annually; 00 denotes unavailable/unknown and 99 denotes irregular.',
'Ex-Date': 'Ex-dividend date of the latest distribution.',
Dividend: 'Latest dividend per share.',
Coupon: 'Bond annual coupon rate (%).',
Maturity: 'Bond maturity date.',
'Market Value': 'Position market value in local currency.',
Section: 'Section — Grouping of the overview metric (Fund, Cost, Price, Assets, Returns, Distributions, Holdings).',
Metric: 'Metric — Overview metric name.',
Value: 'Overview metric value.',
Date: 'NAV history date.',
'Shares Outstanding': 'Fund shares outstanding on that date.',
'Total Net Assets': 'Fund total net assets on that date (USD).',
};
// =========================================================================
// 2. DOM references, application state & lazy fund data
// =========================================================================
function byId(id: string): any {
const element = document.getElementById(id);
if (!element) throw new Error(`Missing element #${id}`);
return element;
}
const dropzone = document.getElementById('dropzone');
const dropzoneText = document.getElementById('dropzone-text');
const fileInput = document.getElementById('file-input');
const el = {
themeToggle: byId('theme-toggle'),
tickerCount: byId('ticker-count'),
subtitle: byId('app-subtitle'),
searchInput: byId('search-input'),
searchClearBtn: byId('search-clear-btn'),
tabsBar: byId('tabs-bar'),
selectedTabsPanel: byId('selected-tabs-panel'),
selectedTabsBar: byId('selected-tabs-bar'),
copyBtn: byId('copy-btn'),
exportCsvBtn: byId('export-csv-btn'),
exportTxtBtn: byId('export-txt-btn'),
resetBtn: byId('reset-btn'),
blacklistBtn: byId('blacklist-btn'),
blacklistPanel: byId('blacklist-panel'),
blacklistInput: byId('blacklist-input'),
blacklistAddBtn: byId('blacklist-add-btn'),
blacklistClearBtn: byId('blacklist-clear-btn'),
blacklistChips: byId('blacklist-chips'),
blacklistEmpty: byId('blacklist-empty'),
tableHead: byId('table-head'),
tableBody: byId('table-body'),
tableScroll: byId('table-scroll'),
staticLoadSentinel: byId('static-load-sentinel'),
staticLoadStatus: byId('static-load-status'),
};
type AppState = {
funds: FundRow[];
selected: Set<string>;
blacklist: Set<string>;
activeTab: ActiveTab;
activeFundTicker: string | null;
queryByTab: Record<string, string>;
sortKey: string;
sortDir: SortDirection;
// Last sort the user explicitly chose (column-header click) per tab. Tab
// switches restore it instead of falling back to the tab default, so an
// All ETFs sort like "YTD Return" survives Watchlist / detail round trips.
sortByTab: Record<string, { key: string; dir: SortDirection }>;
generatedAt: string | null;
counts: { funds: number; holdings: number; history: number } | null;
};
const state: AppState = {
funds: [],
selected: new Set(),
blacklist: new Set(),
activeTab: 'All',
activeFundTicker: null,
queryByTab: {},
sortKey: 'rank',
sortDir: 'asc',
sortByTab: {},
generatedAt: null,
counts: null,
};
// Holdings pipeline bookkeeping (see docs/ui-contract.md §4–§6):
// per-ticker in-flight meta.json dedupe, one serialized page-load chain per
// ticker (the detail-view pager and the background Watchlist loader share it,
// so pages can never be fetched twice or skipped), per-ticker completion
// flags powering the Watchlist "Loading… / N+" label, and the chunked
// Watchlist rendering cursor.
const metaInFlight: Map<string, Promise<any>> = new Map();
const holdingsChains: Map<string, Promise<void>> = new Map();
const holdingsComplete = new Set<string>();
let watchlistChunkSig = '';
let watchlistRenderedCount = 0;
let watchlistRefreshTimer: any = null;
// Lazy per-fund data: meta.json plus accumulated sheet pages (iShares-style).
type SheetEntry = {
headers: string[];
rows: string[][];
nextPage: number;
manifest: any;
loading: boolean;
};
const fundMetaCache: Map<string, any> = new Map();
const sheetState: Map<string, SheetEntry> = new Map();
let sheetGeneration = 0;
init();
// =========================================================================
// 3. Theme & small helpers
// =========================================================================
function applyTheme(dark: boolean): void {
document.documentElement.classList.toggle('dark', dark);
el.themeToggle.textContent = dark ? '☀️' : '🌙';
}
function escapeHtml(value: unknown): string {
return String(value ?? '').replace(/[&<>"']/g, char => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
}[char] || char));
}
function numberOrNull(value: unknown): number | null {
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
if (typeof value !== 'string' || value.trim() === '' || value.trim() === '-') return null;
const parsed = Number(value.replace(/[$,%\s,]/g, ''));
return Number.isFinite(parsed) ? parsed : null;
}
function numberCell(value: unknown): string {
const parsed = numberOrNull(value);
return parsed === null ? '' : String(parsed);
}
function formatPercent(value: unknown): string {
const parsed = numberOrNull(value);
return parsed === null ? '—' : `${parsed.toFixed(2)}%`;
}
function formatDividendFrequency(value: unknown): string {
const raw = String(value ?? '').trim();
const normalized = raw.toLowerCase().replace(/[‐‑‒–—]/g, '-').replace(/\s+/g, ' ');
if (!normalized || normalized === '-') return '00 - —';
if (normalized === 'monthly') return '01 - Monthly';
if (normalized === 'quarterly') return '04 - Quarterly';
if (normalized === 'semi-annual' || normalized === 'semi-annually' || normalized === 'semiannual') return '06 - Semi-annually';
if (normalized === 'annual' || normalized === 'annually') return '12 - Annually';
if (normalized === 'none') return '00 - None';
if (normalized === 'unknown') return '00 - Unknown';
if (normalized === 'irregular') return '99 - Irregular';
return raw;
}
function formatInteger(value: unknown): string {
const parsed = numberOrNull(value);
return parsed === null || parsed === 0 ? '—' : parsed.toLocaleString('en-US');
}
function formatMoney(value: unknown): string {
const parsed = numberOrNull(value);
if (parsed === null) return '—';
if (Math.abs(parsed) >= 1e12) return `$${(parsed / 1e12).toFixed(2)}T`;
if (Math.abs(parsed) >= 1e9) return `$${(parsed / 1e9).toFixed(2)}B`;
if (Math.abs(parsed) >= 1e6) return `$${(parsed / 1e6).toFixed(2)}M`;
if (Math.abs(parsed) >= 1e3) return `$${(parsed / 1e3).toFixed(2)}K`;
return `$${parsed.toFixed(2)}`;
}
function sanitizeTicker(value: unknown): string {
return String(value ?? '').replace(/[^A-Za-z0-9]/g, '').toUpperCase();
}
function normalizeSearchText(value: string): string {
return value.trim().toLowerCase();
}
function getHeaderTooltip(header: string): string {
if (!header) return '';
if (COLUMN_TOOLTIPS[header]) return COLUMN_TOOLTIPS[header];
const clean = String(header).trim();
const keys = Object.keys(COLUMN_TOOLTIPS);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key.toLowerCase() === clean.toLowerCase()) return COLUMN_TOOLTIPS[key];
}
return clean;
}
async function copyText(text: string): Promise<void> {
try {
await navigator.clipboard.writeText(text);
return;
} catch {
// Fall through to the legacy path.
}
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
document.execCommand('copy');
textarea.remove();
}
function downloadText(text: string, fileName: string, mime: string): void {
const blob = new Blob([text], { type: mime });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
function toCsv(rows: string[][]): string {
return rows
.map(row => row.map(cell => {
const value = String(cell ?? '');
return /[",\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
}).join(','))
.join('\n');
}
function exportFileName(scope: string, extension: string): string {
const stamp = new Date().toISOString().slice(0, 10);
return `wisdomtree-${scope.toLowerCase().replace(/\s+/g, '-')}-${stamp}.${extension}`;
}
function setStatus(message: string, tone: 'info' | 'success' | 'error'): void {
console.debug(`[${tone}] ${message}`);
}
// =========================================================================
// 4. Static API loading & paginated sheets (api/wisdomtree/**, iShares-style)
// =========================================================================
async function fetchJson(url: string): Promise<any> {
const response = await fetch(url, { headers: { Accept: 'application/json' }, cache: 'no-cache' });
if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
return response.json();
}
/** Flattens index.json month-end metrics onto the row so sorting works. */
function normalizeFundRow(fund: IndexFund): FundRow {
const monthEnd = (fund.returns && fund.returns.monthEnd) || {};
const metrics = fund.metrics || {};
const row: any = {
...fund,
ytd: monthEnd.ytd ?? null,
yr1: metrics.tr1y ?? monthEnd.yr1 ?? null,
yr3: monthEnd.yr3 ?? null,
yr5: monthEnd.yr5 ?? null,
yr10: monthEnd.yr10 ?? null,
si: metrics.siAnn ?? monthEnd.sinceInception ?? null,
tr3y: metrics.tr3y ?? null,
tr5y: metrics.tr5y ?? null,
tr10y: metrics.tr10y ?? null,
cagr3y: metrics.cagr3y ?? monthEnd.yr3 ?? null,
cagr5y: metrics.cagr5y ?? monthEnd.yr5 ?? null,
cagr10y: metrics.cagr10y ?? monthEnd.yr10 ?? null,
dividendYield: metrics.dividendYield ?? null,
dividendFrequency: formatDividendFrequency(fund.distributions && fund.distributions.frequency ? fund.distributions.frequency : '—'),
secYield: metrics.secYield ?? null, // official WisdomTree product pages publish it for many funds.
returnAsOf: monthEnd.asOfDate ?? null,
searchIndex: '',
};
row.searchIndex = [
fund.ticker, fund.name, fund.category, fund.ter, fund.nav, fund.aum,
fund.exchange, fund.inceptionDate, fund.asOfDate, monthEnd.asOfDate,
fund.distributions && fund.distributions.frequency, metrics.dividendYieldText, metrics.secYieldText,
fund.cusip, fund.isin,
].map(value => String(value ?? '').toLowerCase()).join(' ');
return row;
}
async function loadCatalog(): Promise<void> {
setStatus('Loading WisdomTree ETF data from api/wisdomtree/index.json…', 'info');
const data = await fetchJson(INDEX_URL);
state.funds = (data.funds || [])
.map((fund: IndexFund) => normalizeFundRow(fund))
.sort((a: FundRow, b: FundRow) => a.ticker.localeCompare(b.ticker));
state.generatedAt = data.generatedAt || null;
state.counts = data.counts || null;
// A restored selection/blacklist must reference known funds only.
state.blacklist = new Set([...state.blacklist].filter(ticker => state.funds.some(fund => fund.ticker === ticker)));
state.selected = new Set([...state.selected].filter(ticker => state.funds.some(fund => fund.ticker === ticker) && !state.blacklist.has(ticker)));
if (!state.activeFundTicker && state.selected.size) state.activeFundTicker = [...state.selected][0] || null;
if (state.activeFundTicker && !state.selected.has(state.activeFundTicker)) {
state.activeFundTicker = [...state.selected][0] || null;
}
el.searchInput.disabled = false;
[el.copyBtn, el.exportCsvBtn, el.exportTxtBtn, el.resetBtn].forEach(button => { button.disabled = false; });
applyRestoredTab();
applySortForTab(state.activeTab);
render();
void ensureHoldingsForSelection();
const activeTicker = state.activeFundTicker;
if (activeTicker) {
void loadFundMeta(activeTicker).then(meta => {
if (meta && state.activeTab === 'detail:holdings') void ensureSheet('holdings', meta.holdings);
});
}
}
/**
* meta.json requests are deduplicated per ticker while in flight: the
* detail view and the background Watchlist loader share one request.
* Catalog-only funds (no holdings, no history) short-circuit to null and
* are cached as such; failed fetches are not cached so they can retry.
*/
async function loadFundMeta(ticker: string): Promise<any> {
const cached = fundMetaCache.get(ticker);
if (cached !== undefined) return cached;
const inflight = metaInFlight.get(ticker);
if (inflight) return inflight;
const known = state.funds.find(fund => fund.ticker === ticker);
if (known && !known.holdings && !known.history) {
fundMetaCache.set(ticker, null); // catalog-only fund: no workbook exists
return null;
}
const request = (async () => {
try {
const meta = await fetchJson(`./api/wisdomtree/funds/${encodeURIComponent(ticker)}/meta.json`);
fundMetaCache.set(ticker, meta);
return meta;
} catch (error) {
console.warn(`Failed to load meta.json for ${ticker}:`, error);
return null;
}
})();
metaInFlight.set(ticker, request.finally(() => metaInFlight.delete(ticker)));
return metaInFlight.get(ticker);
}
function sheetKey(sheet: string): string {
return `${state.activeFundTicker}:${sheet}`;
}
function resetSheetPaging(): void {
sheetGeneration += 1;
}
async function fetchPage(ticker: string, pagePath: string): Promise<{ headers: string[]; rows: string[][] }> {
const path = String(pagePath).replace(/^\.?\//, '');
const page = await fetchJson(`./api/wisdomtree/funds/${encodeURIComponent(ticker)}/${path}`);
const headers: string[] = Array.isArray(page.headers) ? page.headers : [];
const rows: any[] = Array.isArray(page.rows) ? page.rows : [];
return { headers, rows: rows.map(row => headers.map(header => String(row[header] ?? ''))) };
}
/** Loads the first page of a paginated sheet and prepares lazy appending. */
async function ensureSheet(sheet: 'holdings' | 'history', manifest: any): Promise<void> {
const key = sheetKey(sheet);
if (sheetState.has(key) || !manifest || !Array.isArray(manifest.pages) || !manifest.pages.length) return;
sheetState.set(key, { headers: [], rows: [], nextPage: 0, manifest, loading: false });
await loadNextSheetPage(sheet);
}
/**
* Serializes page-load work per ticker: the detail-view pager and the
* background Watchlist loader enqueue onto the same chain, and each unit of
* work re-checks `nextPage` while holding the chain — so two rapid selection
* updates can never fetch the same holdings page twice or skip one.
*/
function withTickerChain<T>(ticker: string, fn: () => Promise<T>): Promise<T> {
const previous = holdingsChains.get(ticker) ?? Promise.resolve();
const work = previous.then(fn, fn);
holdingsChains.set(ticker, work.catch(() => undefined));
return work;
}
/** Fetches the next page of `entry`. The caller must already hold the
* per-ticker chain (loadAllHoldingsForTicker) or use appendSheetPage. */
async function fetchNextSheetPage(ticker: string, entry: SheetEntry): Promise<void> {
if (entry.nextPage >= entry.manifest.pages.length) return;
const page = await fetchPage(ticker, entry.manifest.pages[entry.nextPage]);
if (!entry.headers.length && page.headers.length) entry.headers = page.headers;
entry.rows = entry.rows.concat(page.rows);
entry.nextPage += 1;
}
/** Enqueues the next page fetch of `entry` under the per-ticker chain (no-op when the manifest is exhausted). */
function appendSheetPage(ticker: string, entry: SheetEntry): Promise<void> {
return withTickerChain(ticker, () => fetchNextSheetPage(ticker, entry));
}
async function loadNextSheetPage(sheet: 'holdings' | 'history'): Promise<void> {
const key = sheetKey(sheet);
const entry = sheetState.get(key);
const ticker = state.activeFundTicker;
if (!entry || !ticker || entry.loading || entry.nextPage >= entry.manifest.pages.length) return;
entry.loading = true;
renderStaticLoadSentinel();
try {
const generation = sheetGeneration;
await appendSheetPage(ticker, entry);
if (generation !== sheetGeneration) return;
if (state.activeTab === `detail:${sheet}`) render();
} catch (error) {
console.error(`Failed to load ${ticker} ${sheet} page:`, error);
} finally {
entry.loading = false;
renderStaticLoadSentinel();
}
}
/** True while any selected ETF's holdings have not finished loading. */
function isHoldingsLoading(): boolean {
for (const ticker of state.selected) {
if (!holdingsComplete.has(ticker)) return true;
}
return false;
}
/**
* Loads every holdings page of one ticker. Runs inside the per-ticker chain,
* so it composes safely with the detail-view pager (shared cache entry, no
* duplicate or skipped pages). Queued work for an ETF that was deselected in
* the meantime is skipped; in-flight loads finish into the cache and are
* ignored by the aggregation, which only reads the current selection.
*/
async function loadAllHoldingsForTicker(ticker: string): Promise<void> {
await withTickerChain(ticker, async () => {
if (!state.selected.has(ticker)) return; // deselected while queued: skip
const meta = await loadFundMeta(ticker);
if (!meta || !meta.holdings || !Array.isArray(meta.holdings.pages) || !meta.holdings.pages.length) return;
const key = `${ticker}:holdings`;
let entry = sheetState.get(key);
if (!entry) {
entry = { headers: [], rows: [], nextPage: 0, manifest: meta.holdings, loading: false };
sheetState.set(key, entry);
}
while (entry.nextPage < entry.manifest.pages.length) {
if (!state.selected.has(ticker)) return; // deselected mid-load: skip the rest
await fetchNextSheetPage(ticker, entry); // chain already held: no re-queue
}
});
}
/**
* Watchlist aggregation needs every holdings page of every selected ETF
* (same pipeline as daggerok/iShares). Runs with bounded concurrency (6
* funds at a time) so a whole-catalog selection cannot overload the static
* feed; Watchlist holdings are cached under each fund's own key,
* independent of the active fund.
*/
async function ensureHoldingsForSelection(): Promise<void> {
const queue = [...state.selected].filter(ticker => !holdingsComplete.has(ticker));
if (!queue.length) return;
const workers = Array.from({ length: Math.min(HOLDINGS_CONCURRENCY, queue.length) }, async () => {
for (;;) {
const ticker = queue.shift();
if (!ticker) break;
try {
await loadAllHoldingsForTicker(ticker);
} catch (error) {
console.error(`Failed to load ${ticker} holdings:`, error);
} finally {
holdingsComplete.add(ticker);
if (state.selected.size > 0) {
// Keep the Watchlist tab label honest (Loading… -> N+ -> exact)
// even while the user stays on another tab.
if (state.activeTab === 'watchlist') scheduleWatchlistRefresh();
else renderTabs();
}
}
}
});
await Promise.all(workers);
if (state.selected.size > 0) {
if (state.activeTab === 'watchlist') renderWatchlistTable();
else renderTabs();
}
}
/** Progressive Watchlist rerenders are throttled (~150 ms) while rows stream in. */
function scheduleWatchlistRefresh(): void {
if (state.activeTab !== 'watchlist') return;
if (watchlistRefreshTimer !== null) return;
watchlistRefreshTimer = setTimeout(() => {
watchlistRefreshTimer = null;
if (state.activeTab === 'watchlist') renderWatchlistTable();
}, 150);
}
function activeSheetTab(): 'holdings' | 'history' | null {
if (state.activeTab === 'detail:holdings') return 'holdings';
if (state.activeTab === 'detail:history') return 'history';
return null;
}
function maybeLoadMoreRows(): void {
const sheet = activeSheetTab();
if (!sheet) return;
void loadNextSheetPage(sheet);
}
function renderStaticLoadSentinel(): void {
const sheet = activeSheetTab();
if (!sheet || !state.activeFundTicker) {
el.staticLoadSentinel.classList.add('hidden');
return;
}
const entry = sheetState.get(sheetKey(sheet));
if (!entry) {
el.staticLoadSentinel.classList.add('hidden');
return;
}
const more = entry.nextPage < entry.manifest.pages.length;
el.staticLoadSentinel.classList.toggle('hidden', !more);
el.staticLoadStatus.textContent = entry.loading ? 'Loading more rows…' : more ? 'Scroll or click to load more rows…' : '';
}
// =========================================================================
// 5. Navigation tabs & tab switching
// =========================================================================
function categoryLabel(category: string): string {
return category || 'ETF';
}
function uniqueCategories(): string[] {
const categories = [...new Set(state.funds.map(fund => fund.category).filter(Boolean))];
return categories.sort((a, b) => b.length - a.length || a.localeCompare(b));
}
function visibleFunds(): FundRow[] {
const tab = isEtfCatalogTab(state.activeTab) ? state.activeTab : 'All';
return state.funds.filter(fund => (tab === 'All' || fund.category === tab) && !state.blacklist.has(fund.ticker));
}
function getTabs(): TabInfo[] {
const tabs: TabInfo[] = [];
tabs.push({ id: 'All', label: 'All ETFs', count: state.funds.filter(fund => !state.blacklist.has(fund.ticker)).length });
uniqueCategories().forEach(category => {
tabs.push({
id: category,
label: categoryLabel(category),
count: state.funds.filter(fund => fund.category === category && !state.blacklist.has(fund.ticker)).length,
});
});
return tabs;
}
function getSelectedTabs(): TabInfo[] {
const tabs: TabInfo[] = [];
const activeFund = getActiveFund();
if (activeFund) {
DETAIL_TABS.forEach(tab => {
tabs.push({
id: `detail:${tab.key}`,
label: tab.key === 'overview' ? `${activeFund.ticker} ${tab.label}` : tab.label,
count: getDetailCount(tab.key),
});
});
}
if (state.selected.size > 0) {
const rowCount = getDedupedWatchlistRows().length;
// While holdings are still loading, never show a misleading exact count:
// "Loading…" (nothing aggregated yet) or "N+" (partial aggregation that
// can only grow). The exact deduplicated count appears on completion.
const count = isHoldingsLoading() ? (rowCount ? `${rowCount}+` : 'Loading…') : rowCount;
tabs.push({ id: 'watchlist', label: 'Watchlist', count });
}
return tabs;
}
function getAllTabIds(): ActiveTab[] {
return [...getTabs(), ...getSelectedTabs()].map(tab => tab.id);
}
function getActiveFund(): FundRow | null {
if (!state.activeFundTicker || !state.selected.has(state.activeFundTicker)) return null;
return state.funds.find(fund => fund.ticker === state.activeFundTicker) || null;
}
function getDetailCount(key: string): number {
const activeFund = getActiveFund();
if (!activeFund) return 0;
if (key === 'holdings') return activeFund.holdings || 0;
if (key === 'history') return activeFund.history || 0;
if (key === 'distributions') {
const meta = fundMetaCache.get(activeFund.ticker);
return meta && meta.distributions && Array.isArray(meta.distributions.rows) ? meta.distributions.rows.length : 0;
}
return 0;
}
function ensureValidTab(): void {
const tabIds = getAllTabIds();
if (!tabIds.includes(state.activeTab)) {
state.activeTab = 'All';
applySortForTab(state.activeTab);
}
}
function applyRestoredTab(): void {
const tabIds = getAllTabIds();
if (!tabIds.includes(state.activeTab)) state.activeTab = 'All';
syncSearchInput();
}
function renderTabs(): void {
renderTabButtons(el.tabsBar, getTabs());
const selectedTabs = getSelectedTabs();
el.selectedTabsPanel.classList.toggle('is-visible', selectedTabs.length > 0);
renderTabButtons(el.selectedTabsBar, selectedTabs);
}
function renderTabButtons(container: any, tabs: TabInfo[]): void {
container.classList.toggle('hidden', tabs.length <= 1);
// All ETFs pill checkbox: checked iff EVERY non-blacklisted catalog ETF is
// selected (.every over the whole catalog, never a size comparison).
const catalogFunds = state.funds.filter(fund => !state.blacklist.has(fund.ticker));
const allSelected = catalogFunds.length > 0 && catalogFunds.every(fund => state.selected.has(fund.ticker));
container.innerHTML = tabs.map(tab => {
const isActive = tab.id === state.activeTab;
const activeClasses = 'bg-blue-600 text-white font-medium border-blue-500 shadow-sm';
const inactiveClasses = 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100 hover:bg-slate-200 dark:hover:bg-slate-700 border-slate-200 dark:border-slate-700';
if (tab.id === 'All') {
return `
<div class="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full text-xs transition border whitespace-nowrap ${isActive ? activeClasses : inactiveClasses}">
<input type="checkbox" id="select-all-toggle" ${allSelected ? 'checked' : ''} class="w-3.5 h-3.5 accent-blue-600 cursor-pointer" title="Select / Deselect all ETFs" />
<button data-tab="All" class="font-medium hover:underline focus:outline-none">
${escapeHtml(tab.label)} (${tab.count})
</button>
</div>
`;
}
return `
<button
data-tab="${escapeHtml(tab.id)}"
class="px-3.5 py-1.5 rounded-full text-xs transition border whitespace-nowrap ${isActive ? activeClasses : inactiveClasses}">
${escapeHtml(tab.label)} (${tab.count})
</button>
`;
}).join('');
container.querySelectorAll('button[data-tab]').forEach((button: any) => {
button.addEventListener('click', () => {
const next = button.dataset.tab || 'All';
// Transition guard: leave the current tab's search query saved before
// the destination tab restores its own (never overwrite when staying
// on the same tab, e.g. at boot before DOM hydration).
if (state.activeTab && state.activeTab !== next) saveActiveTabQuery();
state.activeTab = next;
// Coming back to a tab (e.g. All ETFs after visiting Watchlist) must
// show the sort the user last chose there, not the tab default.
applySortForTab(state.activeTab);
resetSheetPaging();
syncSearchInput();
persistSiteState();
render();
maybeLoadMoreRows();
});
});
const selectAllToggle = container.querySelector('#select-all-toggle');
if (selectAllToggle) {
selectAllToggle.addEventListener('change', (event: any) => {
event.stopPropagation();
// All ETFs pill: whole non-blacklisted catalog from any tab, no navigation.
toggleAllCatalogEfts(Boolean(event.target.checked));
});
selectAllToggle.addEventListener('click', (event: any) => event.stopPropagation());
}
}
function applyDefaultSortForTab(tab: ActiveTab): void {
if (tab === 'watchlist') {
state.sortKey = 'weightSum';
state.sortDir = 'desc';
} else if (tab === 'detail:overview') {
state.sortKey = 'section';
state.sortDir = 'asc';
} else {
// Holdings, History and Distributions arrive already ordered by the
// source workbook (weight / date); keep the source order by default.
state.sortKey = 'rank';
state.sortDir = 'asc';
}
}
/**
* Restores the sort the user last chose on this tab (recorded on every
* column-header click, persisted in localStorage) or falls back to the tab
* default when the tab was never explicitly sorted.
*/
function applySortForTab(tab: ActiveTab): void {
const remembered = state.sortByTab[tab];
if (remembered) {
state.sortKey = remembered.key;
state.sortDir = remembered.dir;
return;
}
applyDefaultSortForTab(tab);
}
/** Records the current sort as this tab's remembered sort. */
function rememberSortForCurrentTab(): void {
state.sortByTab[state.activeTab] = { key: state.sortKey, dir: state.sortDir };
persistTabSorts();
}
function tabLabel(tab: ActiveTab): string {
const match = /^detail:(.+)$/.exec(tab);
if (match) {
const found = DETAIL_TABS.find(item => item.key === match[1]);
return found ? found.label : tab;
}
return tab === 'watchlist' ? 'Watchlist' : categoryLabel(tab);
}
function isEtfCatalogTab(tab: ActiveTab): boolean {
return tab === 'All' || uniqueCategories().includes(tab);
}
function isDetailTab(tab: ActiveTab): boolean {
return /^detail:(overview|holdings|history|distributions)$/.test(tab);
}
function detailTabKey(tab: ActiveTab): string {
const match = /^detail:(.+)$/.exec(tab);
return match ? match[1] : 'overview';
}
// =========================================================================
// 6. Table rendering, sorting & tooltips
// =========================================================================
function render(): void {
ensureValidTab();
updateSearchClearBtn();
renderTabs();
renderBlacklistPanel();
animateTableUpdate();
if (state.activeTab === 'watchlist') renderWatchlistTable();
else if (isDetailTab(state.activeTab)) renderDetailTable(detailTabKey(state.activeTab));
else renderFundsTable();
fitTableHeight();
renderStaticLoadSentinel();
}
function animateTableUpdate(): void {
el.tableBody.classList.remove('table-content-enter');
void el.tableBody.offsetWidth; // reflow to restart the animation
el.tableBody.classList.add('table-content-enter');
}
function currentQuery(): string {
return state.queryByTab[state.activeTab] || '';
}
function setCurrentQuery(value: string): void {
if (value) state.queryByTab[state.activeTab] = value;
else delete state.queryByTab[state.activeTab];
persistSearches();
}
/** Transition guard: stores the current input text under the tab being left. */
function saveActiveTabQuery(): void {
const query = (el.searchInput.value || '').trim();
if (query) state.queryByTab[state.activeTab] = query;
else delete state.queryByTab[state.activeTab];
persistSearches();
}
/** 1-click clear button visibility: shown iff the input has text. */
function updateSearchClearBtn(): void {
el.searchClearBtn.classList.toggle('hidden', !el.searchInput.value);
}
function syncSearchInput(): void {
const query = currentQuery();
if (document.activeElement !== el.searchInput && el.searchInput.value !== query) {
el.searchInput.value = query;
}
el.searchInput.placeholder = isEtfCatalogTab(state.activeTab)
? 'Search ETFs, fund names, holdings, tickers, CUSIPs/ISINs, SEDOLs...'
: `Search ${tabLabel(state.activeTab)}...`;
updateSearchClearBtn();
}
function filterRows(rows: any[]): any[] {
const query = normalizeSearchText(currentQuery());
if (!query) return rows;
return rows.filter(row => String(row.searchIndex || '').includes(query));
}
function sortValue(row: Record<string, unknown>, key: string): unknown {
return row[key];
}
function compareValues(a: unknown, b: unknown): number {
const an = numberOrNull(a);
const bn = numberOrNull(b);
if (an !== null && bn !== null) return an - bn;
const as = String(a ?? '');
const bs = String(b ?? '');
// History dates ("Aug 21 2026") sort chronologically.
if (/^\d{1,2}-[A-Za-z]{3}-\d{4}$/.test(as) || /^\d{1,2}-[A-Za-z]{3}-\d{4}$/.test(bs)) {
const ad = Date.parse(as.replace(/-/g, ' '));
const bd = Date.parse(bs.replace(/-/g, ' '));
if (!Number.isNaN(ad) && !Number.isNaN(bd)) return ad - bd;
}
return as.localeCompare(bs, undefined, { numeric: true });