forked from Liquifact/Liquifact-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.js
More file actions
931 lines (843 loc) · 37.6 KB
/
Copy pathpage.js
File metadata and controls
931 lines (843 loc) · 37.6 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
"use client";
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import ErrorBanner from "@/components/ErrorBanner";
import InvoiceListSkeleton from "@/components/InvoiceListSkeleton";
import InvoiceSearch from "@/components/InvoiceSearch";
import InvoiceFilters, {
DEFAULT_FILTERS,
StatusLegendFilter,
hasAnyActiveFilters,
parseSortState,
} from "@/components/InvoiceFilters";
import BulkActionsToolbar from "@/components/BulkActionsToolbar";
import ConfirmDialog from "@/components/ConfirmDialog";
import NavMenu from "@/components/NavMenu";
import ErrorBoundary from "@/components/ErrorBoundary";
import MarketplaceErrorBoundary from "@/components/MarketplaceErrorBoundary";
import { useSettingsAnnouncer } from "@/components/useSettingsAnnouncer";
import { useWatchlist } from "@/lib/hooks/useWatchlist";
import useBulkSelection from "@/lib/hooks/useBulkSelection";
import { INVOICE_STATUSES } from "@/lib/types/invoice";
import { reportError } from "@/lib/observability/reportError";
import { copy } from "../copy/en";
// Mock data is sourced exclusively from lib.js (single source of truth until the API client lands).
import { loadMockInvoices } from "./lib";
import { exportAsCSV, exportAsJSON } from "@/utils/export";
import useBulkSelection from "@/lib/hooks/useBulkSelection";
import DensityToggle from "@/components/DensityToggle";
import { useDensity } from "@/lib/hooks/useDensity";
import { useToast } from "@/components/ToastProvider";
export const PAGE_SIZE = 10;
export const SEARCH_DEBOUNCE_MS = 300;
export const URL_SYNC_DEBOUNCE_MS = 200;
const VALID_CURRENCIES = new Set(["USD", "EUR", "GBP", "JPY", "CHF"]);
const VALID_SORT_COLUMNS = new Set(["amount", "yield", "maturity"]);
const VALID_SORT_DIRS = new Set(["asc", "desc"]);
const VALID_STATUSES = new Set(Object.values(INVOICE_STATUSES));
function isValidISODate(str) {
if (typeof str !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(str)) return false;
const d = new Date(str + "T00:00:00Z");
if (Number.isNaN(d.getTime())) return false;
// new Date("2026-09-99") rolls over in some engines, so verify round-trip.
return d.toISOString().slice(0, 10) === str;
}
function isValidYieldString(value) {
if (typeof value !== "string" || value === "") return false;
const n = Number(value);
return Number.isFinite(n) && n >= 0;
}
/**
* Parse a shareable URL query into validated marketplace filters and search.
* Unknown/invalid params are ignored and fall back to defaults.
*
* @param {URLSearchParams} searchParams
* @param {object} [defaults=DEFAULT_FILTERS]
* @returns {{ filters: object, searchQuery: string }}
*/
export function parseFiltersFromSearchParams(searchParams, defaults = DEFAULT_FILTERS) {
const params = searchParams ?? new URLSearchParams();
const rawSort = params.get("sort") ?? "";
const rawSortDir = params.get("sortDir") ?? "";
let sort = "";
let sortDir = "desc";
const compound = rawSort.match(/^(amount|yield|maturity)_(asc|desc)$/);
if (compound) {
sort = compound[1];
sortDir = compound[2];
} else if (VALID_SORT_COLUMNS.has(rawSort)) {
sort = rawSort;
}
if (VALID_SORT_DIRS.has(rawSortDir)) {
sortDir = rawSortDir;
}
const currency = VALID_CURRENCIES.has(params.get("currency")) ? params.get("currency") : "";
const yieldMin = isValidYieldString(params.get("yieldMin")) ? params.get("yieldMin") : "";
const yieldMax = isValidYieldString(params.get("yieldMax")) ? params.get("yieldMax") : "";
const maturityFrom = isValidISODate(params.get("maturityFrom")) ? params.get("maturityFrom") : "";
const maturityTo = isValidISODate(params.get("maturityTo")) ? params.get("maturityTo") : "";
const statuses = (params.get("statuses") ?? "")
.split(",")
.map((s) => s.trim())
.filter((s) => VALID_STATUSES.has(s));
const searchQuery = (params.get("q") ?? "").trim();
return {
filters: {
...defaults,
currency,
yieldMin,
yieldMax,
maturityFrom,
maturityTo,
sort,
sortDir,
statuses,
},
searchQuery,
};
}
/**
* Build a shareable URLSearchParams object from the current filters and search.
* Empty/default values are omitted so the URL stays clean.
*
* @param {object} filters
* @param {string} [searchQuery=""]
* @returns {URLSearchParams}
*/
export function buildSearchParams(filters, searchQuery = "") {
const params = new URLSearchParams();
const trimmedSearch = (searchQuery ?? "").trim();
if (trimmedSearch) params.set("q", trimmedSearch);
if (filters.currency) params.set("currency", filters.currency);
if (filters.yieldMin !== "") params.set("yieldMin", filters.yieldMin);
if (filters.yieldMax !== "") params.set("yieldMax", filters.yieldMax);
if (filters.maturityFrom) params.set("maturityFrom", filters.maturityFrom);
if (filters.maturityTo) params.set("maturityTo", filters.maturityTo);
if (filters.sort) {
params.set("sort", filters.sort);
params.set("sortDir", filters.sortDir || "desc");
}
if (Array.isArray(filters.statuses) && filters.statuses.length > 0) {
params.set("statuses", filters.statuses.join(","));
}
return params;
}
// Delay before an async load/retry outcome reaches the polite live region.
// Debouncing coalesces a burst of rapid results (e.g. mashing "Try again")
// into a single announcement of the latest outcome instead of flooding
// screen readers with every intermediate state. Filter/pagination/search
// text changes are not async results and stay immediate — see the
// `announcedMessage` effect below.
export const ANNOUNCE_DEBOUNCE_MS = 200;
/**
* Returns the screen-reader announcement text for the initial invoice load.
*
* @param {Array} invoices - The resolved invoice array (may be empty).
* @param {object} [options]
* @param {boolean} [options.filterActive] - Whether an issuer filter is active.
* @param {number} [options.filteredCount] - Number of invoices matching the active filter.
* @returns {string}
*/
export function getInvoiceLoadAnnouncement(invoices, { filterActive, filteredCount } = {}) {
if (!Array.isArray(invoices) || invoices.length === 0) {
return copy.invest.announceNoInvoices;
}
if (filterActive) {
if (filteredCount === 0) {
return copy.invest.announceNoMatch;
}
return copy.invest.announceFilteredCount
.replace("{matched}", filteredCount)
.replace("{total}", invoices.length);
}
return copy.invest.announceInvoicesLoaded.replace("{count}", invoices.length);
}
export function getPaginationAnnouncement(shown, total) {
if (total === 0) return copy.invest.announceNoInvoices;
return copy.invest.announceShowing.replace("{shown}", shown).replace("{total}", total);
}
/**
* Build the JSON-serializable subset of an invoice used for the bulk-export
* download. We strip any internal-only fields so the export is safe to
* share with counterparties.\n * @param {{id:string,issuer:string,amount:string,currency:string,dueDate:string,yield:string,status:string}} inv\n * @returns {string,amount:string,currency:string,dueDate:string,yield:string,status:string}}\n */
export function toExportRecord(inv) {
return {
id: inv.id,
issuer: inv.issuer,
amount: inv.amount,
currency: inv.currency,
dueDate: inv.dueDate,
yield: inv.yield,
status: inv.status,
};
}
/**
* Parse a numeric amount string like "12,500" → 12500.\n * @param {string} str\n * @returns {number}\n */
function parseAmount(str) {
return parseFloat(String(str).replace(/,/g, "")) || 0;
}
/**
* Parse a yield string like "8.2%" → 8.2.\n * @param {string} str\n * @returns {number}\n */
function parseYield(str) {
return parseFloat(String(str).replace(/%/g, "")) || 0;
}
/**
* Sort a copy of `list` according to the sort column + direction in `filters`.\n *\n * Supported columns: "amount", "yield", "maturity".\n * Direction: "asc" | "desc".\n *\n * @param {Array} list\n * @param {object} filters\n * @returns {Array}\n */
export function applySortToList(list, filters) {
if (!Array.isArray(list) || list.length === 0) return list;
const { column, dir } = parseSortState(filters);
if (!column) return list;
const multiplier = dir === "asc" ? 1 : -1;
return [...list].sort((a, b) => {
let diff = 0;
if (column === "amount") {
diff = parseAmount(a.amount) - parseAmount(b.amount);
} else if (column === "yield") {
diff = parseYield(a.yield) - parseYield(b.yield);
} else if (column === "maturity") {
diff = new Date(a.dueDate) - new Date(b.dueDate);
}
return multiplier * diff;
});
}
/**
* Trigger a browser download of `text` as `filename` using a transient\n * `<a>` element + `URL.createObjectURL`. Fell back to throwing rather than\n * returning a Promise so failures are easy to assert in tests.\n * @param {string} text\n * @param {string} filename\n * @param {string} mimeType
* @returns {void}\n */
function triggerDownload(text, filename, mimeType = "application/json") {
if (typeof document === "undefined" || typeof URL === "undefined") {
throw new Error("Downloads are only supported in browser environments");
}
const blob = new Blob([text], { type: `${mimeType};charset=utf-8` });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.rel = "noopener";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
/**
* Default bulk-export implementation: write a JSON blob to disk via the\n * browser download mechanism. The page wires `onBulkExport` to this helper\n * unless a custom exporter is provided.\n * @param {Array} selectedInvoices
* @returns {{count: number}}\n */
export function defaultBulkExport(selectedInvoices) {
const safeRecords = Array.isArray(selectedInvoices) ? selectedInvoices.map(toExportRecord) : [];
// Defensive: if the browser download sink is missing (jsdom test env,
// SSR builds, or first-render before hydration), degrade to a silent no-op
// rather than throwing. The page can still surface the file via a custom
// `onBulkExport` injection if it needs to.
if (
typeof URL === "undefined" ||
typeof URL.createObjectURL !== "function" ||
typeof document === "undefined"
) {
return { count: safeRecords.length };
}
const json = JSON.stringify(
{ exportedAt: new Date().toISOString(), invoices: safeRecords },
null,
2
);
triggerDownload(json, `liquifact-invoices-${Date.now()}.json`);
return { count: safeRecords.length };
}
/**
* Default bulk-delete implementation: optimistically updates the supplied\n * list with a no-op filter (parent owns the actual mutation so the data\n * source of truth stays outside the export helper). The handler is a\n * documented opt-in behaviour: callers that already expose a delete API\n * inject their own `onBulkDelete`.\n * @param {Set<string>|Array<string>} ids
* @returns {Promise<{count: number}>}
*/
export function InvestMarketplace({
loadInvoices = loadMockInvoices,
onBulkExport = defaultBulkExport,
onBulkDelete = async () => {},
toast: propToast,
}) {
let router;
try {
router = useRouter();
} catch {
router = null;
}
const searchParams = useSearchParams();
const searchParamsValue = searchParams ?? new URLSearchParams();
const searchParamsString = searchParamsValue.toString();
const initialUrlState = parseFiltersFromSearchParams(searchParamsValue, DEFAULT_FILTERS);
const { watchlists } = useWatchlist();
// Toast is optional — bulk handlers no-op toast when provider is absent (unit tests).
const toastApi = null;
const [invoices, setInvoices] = useState(null); // null = loading
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const [pendingDeleteIds, setPendingDeleteIds] = useState(null);
const [bulkRunning, setBulkRunning] = useState({ export: false, delete: false });
let contextToast;
try {
contextToast = useToast();
} catch {
contextToast = null;
}
const toastApi = propToast || contextToast;
const bulkLabels = copy.invest.bulkActions ?? {};
// Filter state
const [searchQuery, setSearchQuery] = useState(initialUrlState.searchQuery);
const [loadError, setLoadError] = useState("");
const [filters, setFilters] = useState(initialUrlState.filters);
const [debouncedSearch, setDebouncedSearch] = useState(initialUrlState.searchQuery);
const committedSearchRef = useRef(
buildSearchParams(initialUrlState.filters, initialUrlState.searchQuery).toString()
);
const urlUpdateTimerRef = useRef(null);
/**
* When the URL query changes (back/forward, shared link), parse and apply
* validated filters. committedSearchRef prevents overwriting our own writes.
*/
useEffect(() => {
if (searchParamsString === committedSearchRef.current) return;
const parsed = parseFiltersFromSearchParams(searchParamsValue, DEFAULT_FILTERS);
setFilters(parsed.filters);
setSearchQuery(parsed.searchQuery);
setDebouncedSearch(parsed.searchQuery);
committedSearchRef.current = buildSearchParams(parsed.filters, parsed.searchQuery).toString();
// searchParamsValue is intentionally omitted; searchParamsString is the stable signal.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParamsString]);
/**
* Incrementing retryKey causes the load effect to re-run, implementing
* the retry behaviour. It is the only mechanism used to trigger a reload —
* the effect itself is otherwise idempotent for the same loadInvoices ref.
*/
const [retryKey, setRetryKey] = useState(0);
/**
* Bumped once per settled load/retry attempt (success or failure) that
* wasn't superseded by an unmount or a newer retry. Used to distinguish
* async-load-driven announcement changes (debounced) from filter/
* pagination/search-driven ones (immediate) — see `announcedMessage` below.
*/
const [loadGeneration, setLoadGeneration] = useState(0);
// Reset paging whenever the raw invoice data changes (new fetch, retry, etc.).
// Compared during render per the React-recommended pattern:
// https://react.dev/learn/you-might-not-need-an-effect
const [pagingResetFor, setPagingResetFor] = useState(invoices);
if (invoices !== pagingResetFor) {
setPagingResetFor(invoices);
setVisibleCount(PAGE_SIZE);
}
/** Ref forwarded to the "Load more" button for focus management. */
const loadMoreRef = useRef(null);
/**
* Ref for the page heading — the focus target for route-change focus
* management (see the mount effect below).
*/
const headingRef = useRef(null);
// Focus management: Next.js client-side navigation does not reset focus
// or announce the new view the way a full page load does, so keyboard
// and screen-reader users who navigate into /invest can be left with
// focus stranded on a now-removed element (e.g. a nav link). Moving
// focus to the page heading on mount gives every arrival at this route —
// whether via link, back/forward, or hard reload — a consistent, sensible
// focus target and causes the heading to be announced. `tabIndex={-1}` on
// the heading makes it programmatically focusable without adding it to
// the natural Tab order; `outline-none` on the heading suppresses the
// browser's default focus ring since this is not an interactive element,
// keeping the change invisible to sighted users.
useEffect(() => {
headingRef.current?.focus({ preventScroll: true });
}, []);
/**
* Resets error/loading state and re-runs the load effect.
*
* Sets invoices back to null (loading skeleton) and clears loadError so the
* error banner disappears immediately on click. Bumping retryKey causes the
* effect below to re-run; its cleanup will abort any still-in-flight stale
* request from a previous attempt before starting a fresh one.
*/
const reload = useCallback(() => {
setInvoices(null);
setLoadError("");
setRetryKey((k) => k + 1);
}, [setInvoices, setLoadError, setRetryKey]);
/** Toggle a status chip: add if absent, remove if present. */
const handleStatusToggle = useCallback(
(status) => {
setFilters((prev) => {
const current = Array.isArray(prev.statuses) ? prev.statuses : [];
const next = current.includes(status)
? current.filter((s) => s !== status)
: [...current, status];
return { ...prev, statuses: next };
});
},
[setFilters]
);
/** Clear all status chips. */
const handleClearStatuses = useCallback(() => {
setFilters((prev) => ({ ...prev, statuses: [] }));
}, [setFilters]);
const handleUpdateInvoice = useCallback((updatedInvoice) => {
setInvoices((prev) => {
if (!Array.isArray(prev)) return prev;
return prev.map((inv) => (inv.id === updatedInvoice.id ? updatedInvoice : inv));
});
}, []);
// Debounced search term
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(searchQuery), SEARCH_DEBOUNCE_MS);
return () => clearTimeout(t);
}, [searchQuery]);
// Persist active filters/sort/search in the URL so the view is shareable and
// survives reloads. router.replace keeps the back button friendly (no new
// history entries for every filter keystroke) and a debounce prevents rapid
// successive updates.
useEffect(() => {
const next = buildSearchParams(filters, debouncedSearch).toString();
if (next === committedSearchRef.current) return;
clearTimeout(urlUpdateTimerRef.current);
urlUpdateTimerRef.current = setTimeout(() => {
committedSearchRef.current = next;
router?.replace(`?${next}`, { scroll: false });
}, URL_SYNC_DEBOUNCE_MS);
return () => clearTimeout(urlUpdateTimerRef.current);
}, [filters, debouncedSearch, router]);
// Reset the visible page count to PAGE_SIZE whenever the filters or debounced
// search term change, using the React-sanctioned "adjust state during render"
// pattern so the user always starts at the top of the newly filtered list
// (avoids a setState-in-effect cascading render).
const filterSignature = JSON.stringify([debouncedSearch, filters]);
const [prevFilterSignature, setPrevFilterSignature] = useState(filterSignature);
if (filterSignature !== prevFilterSignature) {
setPrevFilterSignature(filterSignature);
setVisibleCount(PAGE_SIZE);
}
// Filtered + sorted invoice list - computed first so the bulk-selection
// hook can derive a consistent selectedIds set from the same dataset the
// UI is rendering.
const filteredInvoices = useMemo(() => {
if (!Array.isArray(invoices)) return [];
let list = invoices;
if (debouncedSearch.trim()) {
const q = debouncedSearch.toLowerCase();
list = list.filter((inv) => inv.issuer?.toLowerCase().includes(q));
}
if (filters.currency) {
list = list.filter((inv) => inv.currency === filters.currency);
}
if (filters.yieldMin !== "") {
const min = parseFloat(filters.yieldMin);
list = list.filter((inv) => parseYield(inv.yield) >= min);
}
if (filters.yieldMax !== "") {
const max = parseFloat(filters.yieldMax);
list = list.filter((inv) => parseYield(inv.yield) <= max);
}
if (filters.maturityFrom) {
list = list.filter((inv) => inv.dueDate >= filters.maturityFrom);
}
if (filters.maturityTo) {
list = list.filter((inv) => inv.dueDate <= filters.maturityTo);
}
if (Array.isArray(filters.statuses) && filters.statuses.length > 0) {
list = list.filter((inv) => filters.statuses.includes(inv.status));
}
if (filters.watchlistOnly) {
const allStarredIds = new Set(watchlists.flatMap((wl) => wl.invoiceIds));
list = list.filter((inv) => allStarredIds.has(inv.id));
}
return applySortToList(list, filters);
}, [invoices, debouncedSearch, filters, watchlists]);
// Bulk-selection hook — auto-prunes selections when the underlying list
// changes (filter, optimistic delete, etc.).
const {
selectedIds,
selectedCount,
visibleCount: selectionVisibleCount,
allState,
isSelected,
toggle: toggleSelection,
selectAll: selectAllInvoices,
clear: clearSelection,
} = useBulkSelection(filteredInvoices);
const filterActive = hasAnyActiveFilters(filters, debouncedSearch);
/**
* Effect: fetch invoices on mount and on every retry.
*
* - Uses AbortController so unmount or a new retry cancels the in-flight
* request cleanly (no stale state updates, no React warnings).
* - isActive guards the setState calls so a slow prior attempt that resolves
* after a retry has already started is silently discarded.
* - retryKey is the sole dependency that forces a re-run on retry; it does
* not interact with the abort/isActive logic in any racy way because the
* cleanup always runs before the next effect body executes.
*/
useEffect(() => {
let isActive = true;
const controller = new AbortController();
const announceLoadCompletion = async () => {
try {
const nextInvoices = await loadInvoices({ signal: controller.signal });
if (!isActive) return;
const normalizedInvoices = Array.isArray(nextInvoices) ? nextInvoices : [];
setInvoices(normalizedInvoices);
setLoadError("");
} catch {
if (!isActive) return;
setInvoices(null);
setLoadError(copy.invest.errorDescription);
} finally {
// Marks this attempt as settled so the announcement effect below can
// tell an async result apart from a filter/pagination/search change.
// Skipped when the attempt was aborted/superseded (isActive is false).
if (isActive) setLoadGeneration((generation) => generation + 1);
}
};
void announceLoadCompletion();
return () => {
isActive = false;
controller.abort();
};
// retryKey triggers a fresh load on retry without changing loadInvoices.
}, [loadInvoices, retryKey, setInvoices]);
// Derive the polite live-region announcement directly from reactive state.
// Using useMemo (rather than a useEffect + setState) avoids a cascading
// re-render and satisfies the react-hooks/set-state-in-effect lint rule.
// The debounced version is then passed to the live region via
// useSettingsAnnouncer, which skips the mount announcement and coalesces
// rapid filter changes before they reach the screen-reader queue.
const statusMessage = useMemo(() => {
// Loading or error states — error copy is announced by the ErrorBanner role="alert";
// the status region is cleared so screen readers only hear one announcement.
if (!Array.isArray(invoices)) {
return loadError ? copy.invest.errorStatus : "";
}
if (filterActive) {
return getInvoiceLoadAnnouncement(invoices, {
filterActive: true,
filteredCount: filteredInvoices.length,
});
}
if (visibleCount < filteredInvoices.length) {
return getPaginationAnnouncement(visibleCount, filteredInvoices.length);
}
if (visibleCount > PAGE_SIZE) {
// After Load more reaches the last page, keep pagination format.
return getPaginationAnnouncement(filteredInvoices.length, filteredInvoices.length);
}
return getInvoiceLoadAnnouncement(invoices);
}, [filteredInvoices, filterActive, invoices, visibleCount, loadError]);
// Pass statusMessage through useSettingsAnnouncer with delay=0 so the
// live region updates immediately on each state change, while still
// honouring the hook's "silent on mount" contract (no spurious announcement
// when the page first renders). Rapid search-input updates are already
// coalesced upstream by the SEARCH_DEBOUNCE_MS delay on debouncedSearch,
// so no additional debounce is needed at the announcement layer here.
const debouncedAnnouncement = useSettingsAnnouncer(statusMessage, 0);
// ── Load-more handler ──────────────────────────────────────────────────────
/**
* Appends the next PAGE_SIZE items and updates the live-region status.
* Focus is moved back to the "Load more" button (if it still exists) so
* keyboard users do not lose their place in the page.
*/
const handleLoadMore = useCallback(() => {
setVisibleCount((prev) => {
return Math.min(prev + PAGE_SIZE, filteredInvoices.length);
});
setTimeout(() => {
loadMoreRef.current?.focus();
}, 0);
}, [filteredInvoices.length, setVisibleCount]);
// ── Bulk actions ──────────────────────────────────────────────────────────
const handleToggleSelectAll = useCallback(() => {
if (allState === "all") {
clearSelection();
} else {
selectAllInvoices();
}
}, [allState, clearSelection, selectAllInvoices]);
const handleRequestDelete = () => {
// Snapshot the selection so the user can't race the dialog by tapping a
// row between opening and confirming. The hook will also prune stale
// ids on the next render, which keeps confirm/cancel honest.
setPendingDeleteIds(new Set(selectedIds));
};
const handleCancelDelete = () => {
setPendingDeleteIds(null);
};
const handleConfirmDelete = async () => {
const idsToDelete = pendingDeleteIds;
if (!idsToDelete || idsToDelete.size === 0) {
setPendingDeleteIds(null);
return;
}
setBulkRunning((prev) => ({ ...prev, delete: true }));
// Snapshot the current list for rollback
const snapshot = invoices;
// Optimistically remove from the visible list so the UI stays in sync
// with the (mock) backend. The selection hook will prune selection
// immediately because the row ids are no longer in the list.
setInvoices((currentList) => {
if (!Array.isArray(currentList)) return currentList;
return currentList.filter((inv) => !idsToDelete.has(inv.id));
});
try {
await onBulkDelete(idsToDelete);
const plural = idsToDelete.size === 1 ? "" : "s";
const successMsg = (bulkLabels.deleteSuccessMsg || "Removed {count} invoice{plural}.")
.replace("{count}", String(idsToDelete.size))
.replace("{plural}", plural);
toastApi?.success(successMsg, bulkLabels.deleteSuccessTitle || "Invoices removed");
setPendingDeleteIds(null);
} catch {
const errorMsg = (bulkLabels.deleteErrorMsg || "Failed to remove selected invoices.")
.replace("{count}", String(idsToDelete.size));
toastApi?.error(errorMsg, bulkLabels.deleteErrorTitle || "Delete failed");
} finally {
setBulkRunning((prev) => ({ ...prev, delete: false }));
}
};
const handleExport = useCallback(() => {
if (selectedIds.size === 0) {
toastApi?.info(bulkLabels.exportEmptyMsg || "No invoices selected", bulkLabels.exportSuccessTitle || "Export");
return;
}
setBulkRunning((prev) => ({ ...prev, export: true }));
try {
// Build the selected-invoice slice in the order they appear in the
// filtered list so the export matches the visible UI order.
const selectedSlice = filteredInvoices.filter((inv) => selectedIds.has(inv.id));
const result = onBulkExport(selectedSlice) || { count: selectedSlice.length };
const exportCount = result.count ?? selectedSlice.length;
const plural = exportCount === 1 ? "" : "s";
const msg = (bulkLabels.exportSuccessMsg || "Exported {count} invoice{plural}.")
.replace("{count}", String(exportCount))
.replace("{plural}", plural);
toastApi?.success(msg, bulkLabels.exportSuccessTitle || "Export complete");
} finally {
setBulkRunning((prev) => ({ ...prev, export: false }));
}
}, [selectedIds, filteredInvoices, onBulkExport, bulkLabels, toastApi]);
// const visibleInvoices = filteredInvoices.slice(0, visibleCount);
const deleteDialogOpen = pendingDeleteIds !== null;
return (
<div className="min-h-screen bg-slate-950 text-slate-100">
<NavMenu />
<main className="max-w-4xl mx-auto px-6 py-12">
{/* Polite live region – announced to screen readers on every state change.
Async load/retry outcomes are debounced (issue #722); filter,
pagination, and search text update immediately. */}
<div role="status" aria-live="polite" aria-atomic="true" className="sr-only">
{debouncedAnnouncement}
</div>
<h1 ref={headingRef} tabIndex={-1} className="text-2xl font-bold mb-2 outline-none">
{copy.invest.title}
</h1>
<p className="text-slate-400 mb-8">{copy.invest.subtext}</p>
{/* Search input */}
<div className="mb-4">
<InvoiceSearch
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
aria-label={copy.invest.searchPlaceholder}
/>
</div>
{/* Status legend filter chip row */}
<StatusLegendFilter
selectedStatuses={Array.isArray(filters.statuses) ? filters.statuses : []}
onStatusToggle={handleStatusToggle}
onClearStatuses={handleClearStatuses}
/>
<fieldset
className="mb-8 rounded-xl border border-slate-800 bg-slate-900/30 p-6"
aria-disabled="true"
aria-describedby="filters-coming-soon"
>
<legend className="sr-only">{copy.invest.filterLegend}</legend>
<div
id="filters-coming-soon"
className="mb-4 inline-block rounded bg-slate-800 px-2 py-1 text-xs font-semibold tracking-wide text-slate-300"
>
{copy.invest.filterSoonLabel}
</div>
<div className="flex flex-wrap gap-4 items-center pointer-events-none opacity-60">
{/* InvoiceFilters only — search moved above */}
<InvoiceFilters
filters={filters}
onFilterChange={setFilters}
onClearFilters={() => setFilters(DEFAULT_FILTERS)}
/>
</div>
</fieldset>
{/* Bulk-action toolbar — renders nothing when no rows are selected */}
<BulkActionsToolbar
selectedCount={selectedCount}
visibleCount={selectionVisibleCount}
allState={allState}
onToggleSelectAll={handleToggleSelectAll}
onClearSelection={clearSelection}
onExport={handleExport}
onRequestDelete={handleRequestDelete}
labels={bulkLabels}
exporting={bulkRunning.export}
deleting={bulkRunning.delete}
/>
{/* Error state – retryable.
ErrorBanner already exposes role="alert" + aria-live="assertive".
Do not wrap it in another alert — nested alerts confuse AT and RTL. */}
<div aria-busy={invoices === null}>
{loadError ? (
<div role="alert" aria-live="assertive">
<ErrorBanner
title={copy.invest.errorTitle}
description={loadError}
actionLabel={copy.invest.retryAction}
onAction={reload}
/>
</div>
) : invoices === null ? (
<InvoiceListSkeleton rows={3} />
) : invoices.length === 0 ? (
<div
role="status"
aria-live="polite"
className="rounded-xl border border-slate-800 bg-slate-900/30 p-8 text-center text-slate-500"
>
{copy.invest.emptyState}
</div>
) : filteredInvoices.length === 0 ? (
<div
role="status"
aria-live="polite"
className="rounded-xl border border-slate-800 bg-slate-900/30 p-8 text-center text-slate-500"
>
{copy.invest.noMatchFilter}
</div>
) : (
<ErrorBoundary
onError={(err, info) => reportError(err, { where: "invest.watchlist", info })}
fallbackTitle="Error loading watchlist"
fallbackDescription="An error occurred while rendering the watchlist. We logged the error — you can retry loading this section."
retryLabel="Retry loading watchlist"
>
<>
<ul aria-label={copy.invest.listAriaLabel} className="space-y-4">
{filteredInvoices.slice(0, visibleCount).map((inv) => (
<li
key={inv.id}
className="rounded-xl border border-slate-800 bg-slate-900/50"
style={{ padding: "var(--market-card-padding)" }}
>
<div
className="flex items-center justify-between"
style={{ marginBottom: "var(--market-card-gap)", gap: "var(--market-card-gap)" }}
>
<Link
href={`/invest/${inv.id}`}
className="rounded font-medium text-slate-100 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-400"
style={{
fontSize: "var(--market-card-title-font-size)",
fontWeight: "var(--market-card-title-font-weight)",
lineHeight: "var(--market-card-title-line-height)",
}}
>
{inv.issuer}
</Link>
<span className="rounded-full bg-cyan-900/60 px-2 py-1 text-xs font-semibold text-cyan-300">
{inv.status}
</span>
</div>
<div
className="flex flex-wrap items-center text-slate-400"
style={{
gap: "var(--market-card-gap)",
fontSize: "var(--market-card-meta-font-size)",
lineHeight: "var(--market-card-meta-line-height)",
letterSpacing: "var(--market-card-meta-letter-spacing)",
}}
>
<span>
{inv.currency} {inv.amount}
</span>
<span>
{copy.invest.labelYield}
{inv.yield}
</span>
<span>
{copy.invest.labelMaturity}
{inv.dueDate}
</span>
</div>
</li>
))}
</ul>
{visibleCount < filteredInvoices.length && (
<button
ref={loadMoreRef}
type="button"
onClick={handleLoadMore}
aria-label={copy.invest.loadMoreAriaLabel}
className="mt-6 w-full rounded-xl border border-slate-700 bg-slate-900/30 py-3 text-sm text-cyan-400 hover:bg-slate-800/50 focus-ring focus-visible:ring-2 focus-visible:ring-cyan-500"
>
{copy.invest.loadMore}
</button>
)}
<div className="mt-6 rounded-xl border border-slate-800 bg-slate-900/30 p-4 text-sm text-slate-400">
{copy.invest.yieldDisclaimer}
</div>
</>
</ErrorBoundary>
)}
</div>
<div className="mt-8 flex flex-wrap items-center justify-between gap-4 border-t border-slate-800/60 pt-4">
<DensityToggle density={density} onDensityChange={setDensity} />
<div className="flex gap-2">
<button
type="button"
onClick={() => exportAsCSV(filteredInvoices, "invoices_export.csv")}
disabled={filteredInvoices.length === 0}
className="rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2 text-sm text-cyan-400 hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-cyan-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Export CSV
</button>
<button
type="button"
onClick={() => exportAsJSON(filteredInvoices, "invoices_export.json")}
disabled={filteredInvoices.length === 0}
className="rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2 text-sm text-cyan-400 hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-cyan-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Export JSON
</button>
</div>
</div>
</main>
{/* Confirmation dialog for destructive bulk action */}
<ConfirmDialog
open={deleteDialogOpen}
onClose={handleCancelDelete}
onConfirm={handleConfirmDelete}
title={bulkLabels.deleteConfirmTitle || "Delete selected invoices?"}
description={
pendingDeleteIds
? (bulkLabels.deleteConfirmBody || "You are about to permanently delete {count} invoice{plural}.")
.replace("{count}", String(pendingDeleteIds.size))
.replace("{plural}", pendingDeleteIds.size === 1 ? "" : "s")
: ""
}
confirmLabel={
pendingDeleteIds
? (bulkLabels.deleteConfirmConfirmLabel || "Delete {count} invoice{plural}")
.replace("{count}", String(pendingDeleteIds.size))
.replace("{plural}", pendingDeleteIds.size === 1 ? "" : "s")
: "Delete"
}
cancelLabel={bulkLabels.deleteConfirmCancelLabel || "Cancel"}
variant="danger"
confirmLoading={bulkRunning.delete}
/>
</div>
);
}
export default function InvestPage() {
return (
<MarketplaceErrorBoundary>
<InvestMarketplace />
</MarketplaceErrorBoundary>
);
}