Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 12769x 12769x 12769x 12769x 12769x 3015x 3015x 3015x 3015x 3015x 3015x 3015x 3015x 3001x 9x 3010x 12769x 2955x 2955x 2955x 12769x 825x 126x 126x 126x 5x 825x 130x 130x 825x 34x 34x 34x 34x 34x 34x 34x 34x 13x 13x 35x 35x 35x 34x 34x 34x 34x 27x 2x 34x 35x 35x 16x 16x 2x 16x 16x 16x 1x 1x 28x 14x 16x 14x 14x 7x 7x 7x 14x 28x 13x 35x 35x 35x 13x 13x 13x 13x 34x 827x 827x 827x 187x 184x 184x 82x 81x 81x 131x 131x 927x 927x 927x 50x 50x 50x 48x 50x 927x 8x 927x 7x 927x 12x 12x 11x 11x 8x 8x 8x 8x 8x 12x 3x 927x 7x 7x 6x 6x 4x 4x 4x 4x 7x 2x 927x 6x 6x 5x 5x 3x 3x 3x 3x 6x 2x 927x 8x 8x 7x 7x 5x 5x 5x 5x 5x 8x 2x 927x 8x 8x 7x 5x 5x 4x 4x 4x 4x 4x 5x 5x 1x 5x 2x 927x 841x 841x 841x 841x 10x 10x 22x 10x 10x 10x 10x 841x 6x 6x 5x 5x 6x 6x 6x 6x 1x 1x 841x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 1x 1x 841x 10x 5x 10x 9x 10x 2x 2x 7x 7x 19x 10x 7x 7x 6x 6x 6x 10x 2x 1x 1x 1x 1x 1x 1x 1x 841x 4x 3x 3x 3x 3x 2x 2x 2x 2x 4x 1x 841x 844x 844x 844x 844x 844x 844x 844x 844x 145x 3x 3x 142x 3x 139x 139x 139x 2x 137x 2x 135x 134x 1x 844x 264x 3x 3x 3x 3x 261x 7x 7x 7x 7x 254x 122x 122x 122x 132x 132x 132x 132x 844x 4x 4x 4x 3x 3x 2x 2x 1x 3x 844x 826x 826x 826x 826x 826x 826x 282x 242x 118x 118x 118x 826x 282x 158x 3x 3x 155x 155x 155x 118x 37x 826x 5x 5x 4x 4x 126x 126x 734x 734x 242x 242x 242x 796x 5x 5x 5x 5x 4x 4x 4x 4x 2x 1x 1x 2x 1x 1x 242x 242x 231x 231x 242x 242x 242x 242x 851x 145x 9x 851x 3x 2x 2x 2x 851x 5x 5x 4x 3x 2x 5x 5x 851x | import { type RefObject, useCallback, useEffect, useRef, useState } from "react";
import type { Folder, GlobalSyncStatus, Label, MessageSummary } from "./api";
import { api } from "./api";
import { toast } from "./components/Toast";
import { getPageSize, isFlagged, isUnread, parseFlags } from "./utils";
/** Simple data-fetching hook with loading/error states.
* Cancels in-flight requests via AbortController when deps change,
* preventing stale responses from overwriting fresh ones. */
export function useAsync<T>(
fn: (signal: AbortSignal) => Promise<T>,
deps: unknown[] = [],
): { data: T | null; loading: boolean; error: string | null; refetch: () => void } {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const abortRef = useRef<AbortController | null>(null);
const refetch = useCallback(() => {
// Abort any previous in-flight request
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
setError(null);
const promise = fn(controller.signal);
Iif (!promise || typeof promise.then !== "function") {
setLoading(false);
return;
}
promise
.then((result) => {
if (!controller.signal.aborted) setData(result);
})
.catch((e: Error) => {
if (!controller.signal.aborted) setError(e.message);
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
// biome-ignore lint/correctness/useExhaustiveDependencies: fn is intentionally controlled by caller-provided deps
}, deps);
useEffect(() => {
refetch();
return () => {
abortRef.current?.abort();
};
}, [refetch]);
return { data, loading, error, refetch };
}
/** Dark mode hook — persists to localStorage */
export function useDarkMode(): [boolean, () => void] {
const [dark, setDark] = useState(() => {
Iif (typeof window === "undefined") return false;
const stored = localStorage.getItem("stork-dark-mode");
if (stored !== null) return stored === "true";
return window.matchMedia("(prefers-color-scheme: dark)").matches;
});
useEffect(() => {
document.documentElement.classList.toggle("dark", dark);
localStorage.setItem("stork-dark-mode", String(dark));
}, [dark]);
return [dark, () => setDark((d) => !d)];
}
/**
* Polls sync status and fires a callback when any identity transitions
* from running → idle (i.e., a sync cycle just completed).
*/
export function useSyncPoller(onSyncComplete: () => void): {
syncing: boolean;
lastError: string | null;
syncStatus: GlobalSyncStatus | null;
} {
const [syncing, setSyncing] = useState(false);
const [lastError, setLastError] = useState<string | null>(null);
const [syncStatus, setSyncStatus] = useState<GlobalSyncStatus | null>(null);
const prevStatusRef = useRef<GlobalSyncStatus | null>(null);
const onSyncCompleteRef = useRef(onSyncComplete);
onSyncCompleteRef.current = onSyncComplete;
// Tracks the last time we fired a progress-based refetch to debounce rapid updates.
// Initialized to -Infinity so the first progress update always fires immediately.
const lastProgressRefetchRef = useRef(Number.NEGATIVE_INFINITY);
useEffect(() => {
let active = true;
// Track the last total message count to detect new messages during sync
let lastMessageTotal = 0;
async function poll() {
Iif (!active) return;
try {
const status = await api.sync.status();
const anyRunning = Object.values(status).some((s) => s.running);
setSyncing(anyRunning);
setSyncStatus(status);
// Check for errors
const errors = Object.values(status)
.filter((s) => s.lastError)
.map((s) => s.lastError);
setLastError(errors.length > 0 ? (errors[0] ?? null) : null);
// Detect transition: was running → now idle (sync just completed)
const prev = prevStatusRef.current;
if (prev) {
const wasRunning = Object.values(prev).some((s) => s.running);
if (wasRunning && !anyRunning) {
onSyncCompleteRef.current();
}
// Also detect new data: lastSync changed
for (const [id, s] of Object.entries(status)) {
const prevS = prev[id];
if (prevS && s.lastSync && prevS.lastSync !== s.lastSync) {
onSyncCompleteRef.current();
break;
}
}
}
// During active sync, refetch when new messages have been synced
// so the UI shows messages progressively instead of only at the end.
// Debounced to at most once per 2s to avoid flooding during fast downloads.
if (anyRunning) {
const currentTotal = Object.values(status).reduce(
(sum, s) => sum + (s.progress?.messagesNew ?? 0),
0,
);
const now = Date.now();
if (currentTotal > lastMessageTotal && now - lastProgressRefetchRef.current >= 2000) {
lastMessageTotal = currentTotal;
lastProgressRefetchRef.current = now;
onSyncCompleteRef.current();
}
} else {
lastMessageTotal = 0;
}
prevStatusRef.current = status;
} catch {
// Poll errors are mostly harmless (server briefly unavailable).
// But check if the container went back to locked state — the 423
// handler in fetchJSON dispatches an event that App.tsx picks up,
// so we just need to let the error propagate through fetchJSON.
}
}
// Use sequential scheduling (setTimeout after completion) instead of
// setInterval to avoid concurrent in-flight requests when the server
// is slow to respond (e.g. large database on first UI load after restart).
let timeoutId: ReturnType<typeof setTimeout> | null = null;
async function scheduleNextPoll() {
await poll();
Eif (active) {
timeoutId = setTimeout(scheduleNextPoll, 3000);
}
}
scheduleNextPoll();
return () => {
active = false;
Eif (timeoutId !== null) clearTimeout(timeoutId);
};
}, []);
return { syncing, lastError, syncStatus };
}
/** Keyboard shortcut hook — uses a ref so the handler always sees the latest
* shortcuts without re-registering the event listener on every render. */
export function useKeyboardShortcuts(shortcuts: Record<string, (e: KeyboardEvent) => void>) {
const shortcutsRef = useRef(shortcuts);
shortcutsRef.current = shortcuts;
useEffect(() => {
function handler(e: KeyboardEvent) {
// Don't intercept browser shortcuts (Ctrl+C, Ctrl+V, etc.)
if (e.ctrlKey || e.metaKey || e.altKey) return;
// Don't fire shortcuts when typing in inputs
const tag = (e.target as HTMLElement).tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
if ((e.target as HTMLElement).isContentEditable) return;
const fn = shortcutsRef.current[e.key];
if (fn) fn(e);
}
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, []);
}
/**
* Manages bulk message selection state and actions (delete, mark read/unread, move).
* Extracted from App.tsx to reduce component complexity.
*/
export function useBulkSelection(opts: {
messages: MessageSummary[];
selectedMessageId: number | null;
setSelectedMessageId: (id: number | null) => void;
refetchMessages: () => void;
refetchLabels: () => void;
effectiveLabelId?: number | null;
isAllMail?: boolean;
refetchAllMailCount?: () => void;
refetchUnreadCount?: () => void;
}) {
const {
messages,
selectedMessageId,
setSelectedMessageId,
refetchMessages,
refetchLabels,
effectiveLabelId,
isAllMail,
refetchAllMailCount,
refetchUnreadCount,
} = opts;
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const toggle = useCallback((id: number) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}, []);
const selectAll = useCallback(() => {
setSelectedIds(new Set(messages.map((m) => m.id)));
}, [messages]);
const clear = useCallback(() => {
setSelectedIds(new Set());
}, []);
const bulkDelete = useCallback(async () => {
const ids = [...selectedIds];
if (ids.length === 0) return;
try {
await api.messages.bulk(ids, "delete");
setSelectedIds(new Set());
if (ids.includes(selectedMessageId ?? -1)) setSelectedMessageId(null);
refetchMessages();
refetchLabels();
refetchUnreadCount?.();
toast(`Deleted ${ids.length} message${ids.length !== 1 ? "s" : ""}`, "success");
} catch (err) {
toast(`Failed to delete: ${err instanceof Error ? err.message : "Unknown error"}`, "error");
}
}, [
selectedIds,
selectedMessageId,
setSelectedMessageId,
refetchMessages,
refetchLabels,
refetchUnreadCount,
]);
const markRead = useCallback(async () => {
const ids = [...selectedIds];
if (ids.length === 0) return;
try {
await api.messages.bulk(ids, "flag", { add: ["\\Seen"] });
setSelectedIds(new Set());
refetchMessages();
refetchLabels();
refetchUnreadCount?.();
toast(`Marked ${ids.length} message${ids.length !== 1 ? "s" : ""} as read`, "success");
} catch (err) {
toast(
`Failed to mark read: ${err instanceof Error ? err.message : "Unknown error"}`,
"error",
);
}
}, [selectedIds, refetchMessages, refetchLabels, refetchUnreadCount]);
const markUnread = useCallback(async () => {
const ids = [...selectedIds];
if (ids.length === 0) return;
try {
await api.messages.bulk(ids, "flag", { remove: ["\\Seen"] });
setSelectedIds(new Set());
refetchMessages();
refetchLabels();
refetchUnreadCount?.();
toast(`Marked ${ids.length} message${ids.length !== 1 ? "s" : ""} as unread`, "success");
} catch (err) {
toast(
`Failed to mark unread: ${err instanceof Error ? err.message : "Unknown error"}`,
"error",
);
}
}, [selectedIds, refetchMessages, refetchLabels, refetchUnreadCount]);
const move = useCallback(
async (folderId: number) => {
const ids = [...selectedIds];
if (ids.length === 0) return;
try {
await api.messages.bulk(ids, "move", { folder_id: folderId });
setSelectedIds(new Set());
if (ids.includes(selectedMessageId ?? -1)) setSelectedMessageId(null);
refetchMessages();
refetchLabels();
refetchUnreadCount?.();
toast(`Moved ${ids.length} message${ids.length !== 1 ? "s" : ""}`, "success");
} catch (err) {
toast(`Failed to move: ${err instanceof Error ? err.message : "Unknown error"}`, "error");
}
},
[
selectedIds,
selectedMessageId,
setSelectedMessageId,
refetchMessages,
refetchLabels,
refetchUnreadCount,
],
);
const archive = useCallback(async () => {
const ids = [...selectedIds];
if (ids.length === 0) return;
// Archive = remove the Inbox label from selected messages. Only available from Inbox view.
if (effectiveLabelId && effectiveLabelId > 0 && !isAllMail) {
try {
await api.messages.bulk(ids, "remove_label", { label_id: effectiveLabelId });
setSelectedIds(new Set());
if (ids.includes(selectedMessageId ?? -1)) setSelectedMessageId(null);
refetchMessages();
refetchLabels();
refetchAllMailCount?.();
refetchUnreadCount?.();
toast(`Archived ${ids.length} message${ids.length !== 1 ? "s" : ""}`, "success");
} catch (err) {
toast(
`Failed to archive: ${err instanceof Error ? err.message : "Unknown error"}`,
"error",
);
}
return;
}
toast("Archive is only available from Inbox", "error");
}, [
selectedIds,
selectedMessageId,
setSelectedMessageId,
refetchMessages,
refetchLabels,
refetchAllMailCount,
refetchUnreadCount,
effectiveLabelId,
isAllMail,
]);
return {
selectedIds,
setSelectedIds,
toggle,
selectAll,
clear,
bulkDelete,
markRead,
markUnread,
move,
archive,
};
}
/**
* Manages per-message action handlers for the focused message in the list:
* optimistic star/unstar, mark read/unread, archive, and delete.
* Extracted from App.tsx to reduce component complexity.
*/
export function useMessageActions(opts: {
messages: MessageSummary[];
messageListIndex: number;
selectedMessageId: number | null;
setSelectedMessageId: (id: number | null) => void;
setAllMessages: React.Dispatch<React.SetStateAction<MessageSummary[]>>;
labels: Label[] | null;
folders: Folder[] | null;
effectiveLabelId: number | null;
isAllMail: boolean;
refetchMessages: () => void;
refetchLabels: () => void;
refetchAllMailCount: () => void;
refetchUnreadCount?: () => void;
}) {
const {
messages,
messageListIndex,
selectedMessageId,
setSelectedMessageId,
setAllMessages,
labels,
effectiveLabelId,
isAllMail,
refetchMessages,
refetchLabels,
refetchAllMailCount,
refetchUnreadCount,
} = opts;
const [pendingDelete, setPendingDelete] = useState<number | null>(null);
const focusedMessage = messages[messageListIndex] ?? null;
// Optimistic flag update — immediately updates local message list state.
// Uses parseFlags() for consistent comma-separated flag manipulation.
const optimisticFlagUpdate = useCallback(
(messageId: number, flagsUpdate: { add?: string[]; remove?: string[] }) => {
setAllMessages((prev) =>
prev.map((m) => {
if (m.id !== messageId) return m;
const flagSet = parseFlags(m.flags);
for (const flag of flagsUpdate.add ?? []) flagSet.add(flag);
for (const flag of flagsUpdate.remove ?? []) flagSet.delete(flag);
return { ...m, flags: [...flagSet].join(",") };
}),
);
},
[setAllMessages],
);
const star = useCallback(async () => {
const msg = messages[messageListIndex];
if (!msg) return;
const flagged = isFlagged(msg.flags);
const flagsUpdate = flagged ? { remove: ["\\Flagged"] } : { add: ["\\Flagged"] };
optimisticFlagUpdate(msg.id, flagsUpdate);
toast(flagged ? "Removed star" : "Starred", "success");
try {
await api.messages.updateFlags(msg.id, flagsUpdate);
} catch (err) {
refetchMessages(); // Revert on failure
toast(`Failed to star: ${err instanceof Error ? err.message : "Unknown error"}`, "error");
}
}, [messages, messageListIndex, optimisticFlagUpdate, refetchMessages]);
const toggleRead = useCallback(async () => {
const msg = messages[messageListIndex];
Iif (!msg) return;
const unread = isUnread(msg.flags);
const flagsUpdate = unread ? { add: ["\\Seen"] } : { remove: ["\\Seen"] };
optimisticFlagUpdate(msg.id, flagsUpdate);
toast(unread ? "Marked as read" : "Marked as unread", "success");
try {
await api.messages.updateFlags(msg.id, flagsUpdate);
refetchLabels();
refetchUnreadCount?.();
} catch (err) {
refetchMessages(); // Revert on failure
toast(`Failed to update: ${err instanceof Error ? err.message : "Unknown error"}`, "error");
}
}, [
messages,
messageListIndex,
optimisticFlagUpdate,
refetchMessages,
refetchLabels,
refetchUnreadCount,
]);
const archive = useCallback(
async (messageId?: number) => {
const msg = messageId
? (messages.find((m) => m.id === messageId) ?? null)
: (messages[messageListIndex] ?? null);
if (!msg) return;
// Archive = remove the current label from the message.
// Available from any real label view; disabled for All Mail / Unread / unified views.
const currentLabel = labels?.find((l) => l.id === effectiveLabelId);
if (!currentLabel || isAllMail) {
toast("Remove label is only available in label views", "error");
return;
}
const isInboxLabel = currentLabel.name.toLowerCase() === "inbox";
const successText = isInboxLabel ? "Archived" : `Removed from ${currentLabel.name}`;
// Optimistic: remove from list
setAllMessages((prev) => prev.filter((m) => m.id !== msg.id));
Iif (selectedMessageId === msg.id) setSelectedMessageId(null);
try {
await api.messages.removeLabel(msg.id, currentLabel.id);
refetchLabels();
refetchAllMailCount();
refetchUnreadCount?.();
toast(successText, "success", {
label: "Undo",
onClick: () => {
api.messages
.addLabels(msg.id, [currentLabel.id])
.then(() => {
refetchMessages();
refetchLabels();
refetchAllMailCount();
refetchUnreadCount?.();
})
.catch(() => toast("Failed to undo", "error"));
},
});
} catch (err) {
refetchMessages(); // Revert on failure
toast(
`Failed to archive: ${err instanceof Error ? err.message : "Unknown error"}`,
"error",
);
}
},
[
messages,
messageListIndex,
labels,
effectiveLabelId,
isAllMail,
selectedMessageId,
setSelectedMessageId,
setAllMessages,
refetchMessages,
refetchLabels,
refetchAllMailCount,
refetchUnreadCount,
],
);
const confirmDelete = useCallback(async () => {
if (pendingDelete === null) return;
const id = pendingDelete;
setPendingDelete(null);
try {
await api.messages.delete(id);
Iif (selectedMessageId === id) setSelectedMessageId(null);
refetchMessages();
refetchLabels();
refetchUnreadCount?.();
toast("Message deleted", "success");
} catch (err) {
toast(`Failed to delete: ${err instanceof Error ? err.message : "Unknown error"}`, "error");
}
}, [
pendingDelete,
selectedMessageId,
setSelectedMessageId,
refetchMessages,
refetchLabels,
refetchUnreadCount,
]);
return {
focusedMessage,
pendingDelete,
setPendingDelete,
star,
toggleRead,
archive,
confirmDelete,
};
}
/**
* Manages message list fetching and pagination for the active label/identity.
* Encapsulates all messages state, loading, error, hasMore, and loadMore logic.
* Extracted from App.tsx to reduce component complexity.
*/
export function useMessagePagination(opts: {
effectiveLabelId: number | null;
isAllMail: boolean;
isUnread?: boolean;
isUnifiedInbox?: boolean;
isUnifiedAllMail?: boolean;
isUnifiedUnread?: boolean;
filterLabelIds?: number[];
}) {
const {
effectiveLabelId,
isAllMail,
isUnread,
isUnifiedInbox,
isUnifiedAllMail,
isUnifiedUnread,
filterLabelIds = [],
} = opts;
const [allMessages, setAllMessages] = useState<MessageSummary[]>([]);
const [hasMore, setHasMore] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const isAnyUnified = isUnifiedInbox || isUnifiedAllMail || isUnifiedUnread;
const isMultiFilter = filterLabelIds.length > 1;
// Stable stringified key for dep arrays (avoids re-renders on same-content arrays)
const filterKey = filterLabelIds.join(",");
const getFetchFn = useCallback(
(paginationOpts: { limit: number; offset?: number }) => {
// Multi-label filter takes priority over all other views
if (isMultiFilter) {
// Parse IDs from the stable key to avoid referencing the array directly
const ids = filterKey.split(",").map(Number);
return api.labels.filter(ids, paginationOpts);
}
if (isUnifiedInbox) {
return api.inbox.unified.list(paginationOpts);
}
Iif (isUnifiedAllMail) {
return api.inbox.allMessages.list(paginationOpts);
}
Iif (isUnifiedUnread) {
return api.inbox.unreadMessages.list(paginationOpts);
}
if (isUnread) {
return api.inbox.unreadMessages.list(paginationOpts);
}
if (isAllMail) {
return api.inbox.allMessages.list(paginationOpts);
}
if (effectiveLabelId && effectiveLabelId > 0) {
return api.labels.messages(effectiveLabelId, paginationOpts);
}
return Promise.resolve([]);
},
[
isMultiFilter,
filterKey,
isUnifiedInbox,
isUnifiedAllMail,
isUnifiedUnread,
isUnread,
isAllMail,
effectiveLabelId,
],
);
const {
loading: messagesLoading,
error: messagesError,
refetch: refetchMessages,
} = useAsync(() => {
if (isMultiFilter) {
return getFetchFn({ limit: getPageSize() }).then((msgs) => {
setAllMessages(msgs);
setHasMore(msgs.length >= getPageSize());
return msgs;
});
}
if (isAnyUnified || isAllMail || isUnread) {
return getFetchFn({ limit: getPageSize() }).then((msgs) => {
setAllMessages(msgs);
setHasMore(msgs.length >= getPageSize());
return msgs;
});
}
if (!effectiveLabelId) {
setAllMessages([]);
setHasMore(false);
return Promise.resolve([]);
}
return getFetchFn({ limit: getPageSize() }).then((msgs) => {
setAllMessages(msgs);
setHasMore(msgs.length >= getPageSize());
return msgs;
});
}, [effectiveLabelId, isAllMail, isUnread, isAnyUnified, isMultiFilter, filterKey, getFetchFn]);
const handleLoadMore = useCallback(() => {
Iif (loadingMore) return;
Eif (!isMultiFilter) {
if (!isAnyUnified && !isAllMail && !isUnread && !effectiveLabelId) return;
}
setLoadingMore(true);
getFetchFn({ limit: getPageSize(), offset: allMessages.length })
.then((more) => {
setAllMessages((prev) => [...prev, ...more]);
setHasMore(more.length >= getPageSize());
})
.catch(() => {
toast("Failed to load more messages", "error");
})
.finally(() => setLoadingMore(false));
}, [
effectiveLabelId,
isAllMail,
isUnread,
isAnyUnified,
isMultiFilter,
allMessages.length,
loadingMore,
getFetchFn,
]);
return {
allMessages,
setAllMessages,
messagesLoading,
messagesError,
refetchMessages,
hasMore,
loadingMore,
handleLoadMore,
};
}
/**
* Navigation state tracked in browser history. Enables back/forward buttons.
*/
interface NavState {
identityId: number | null;
labelId: number | null;
messageId: number | null;
searchActive?: boolean;
}
/**
* Syncs navigation state (identity, label, message) with the browser history API.
* Pushes state on navigation changes, restores state on back/forward (popstate).
*/
export function useHistoryNavigation(opts: {
identityId: number | null;
labelId: number | null;
messageId: number | null;
searchActive?: boolean;
onNavigate: (state: NavState) => void;
}) {
const { identityId, labelId, messageId, searchActive, onNavigate } = opts;
const isPopstateRef = useRef(false);
const initializedRef = useRef(false);
const onNavigateRef = useRef(onNavigate);
onNavigateRef.current = onNavigate;
// Replace the initial history entry with the current state
useEffect(() => {
if (initializedRef.current) return;
if (identityId === null) return; // Wait until identities are loaded
initializedRef.current = true;
const state: NavState = { identityId, labelId, messageId, searchActive };
history.replaceState(state, "");
}, [identityId, labelId, messageId, searchActive]);
// Push state when navigation changes (but not when handling popstate)
useEffect(() => {
if (!initializedRef.current) return;
if (isPopstateRef.current) {
isPopstateRef.current = false;
return;
}
const state: NavState = { identityId, labelId, messageId, searchActive };
const current = history.state as NavState | null;
// Don't push if the state hasn't actually changed
if (
current &&
current.identityId === state.identityId &&
current.labelId === state.labelId &&
current.messageId === state.messageId &&
(current.searchActive ?? false) === (state.searchActive ?? false)
) {
return;
}
history.pushState(state, "");
}, [identityId, labelId, messageId, searchActive]);
// Listen for popstate (back/forward) and restore navigation state
useEffect(() => {
function handlePopstate(e: PopStateEvent) {
const state = e.state as NavState | null;
if (!state) return;
isPopstateRef.current = true;
onNavigateRef.current(state);
}
window.addEventListener("popstate", handlePopstate);
return () => window.removeEventListener("popstate", handlePopstate);
}, []);
}
/**
* Traps keyboard focus within a container element — Tab and Shift+Tab cycle
* through focusable elements without escaping the modal. Also restores focus
* to the previously-focused element on unmount.
*/
export function useFocusTrap(containerRef: RefObject<HTMLElement | null>) {
const previousFocusRef = useRef<Element | null>(null);
useEffect(() => {
const container = containerRef.current;
Iif (!container) return;
// Save the currently focused element to restore on unmount
previousFocusRef.current = document.activeElement;
function handleKeyDown(e: KeyboardEvent) {
if (e.key !== "Tab") return;
const el = containerRef.current;
Iif (!el) return;
const focusable = el.querySelectorAll<HTMLElement>(
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
);
if (focusable.length === 0) return;
const first = focusable[0] as HTMLElement | undefined;
const last = focusable[focusable.length - 1] as HTMLElement | undefined;
Iif (!first || !last) return;
if (e.shiftKey) {
if (document.activeElement === first) {
e.preventDefault();
last.focus();
}
} else {
if (document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
}
container.addEventListener("keydown", handleKeyDown);
// Auto-focus the first focusable element if nothing inside is focused yet
if (!container.contains(document.activeElement)) {
const first = container.querySelector<HTMLElement>(
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
);
first?.focus();
}
return () => {
container.removeEventListener("keydown", handleKeyDown);
// Restore focus to the element that was focused before the modal opened
Eif (previousFocusRef.current instanceof HTMLElement) {
previousFocusRef.current.focus();
}
};
}, [containerRef]);
}
/**
* Desktop notification support.
*
* Returns:
* - `permission` — current Notification.permission state
* - `requestPermission()` — prompts the user for permission; updates state
* - `notifyNewMail(count, folder?)` — fires a notification if:
* - browser permission is granted
* - the user has notifications enabled in settings
* - the page is not currently focused (tab is in the background)
*/
export function useDesktopNotifications(): {
permission: NotificationPermission;
requestPermission: () => Promise<NotificationPermission>;
notifyNewMail: (count: number, folder?: string) => void;
} {
const [permission, setPermission] = useState<NotificationPermission>(() => {
if (typeof Notification === "undefined") return "denied";
return Notification.permission;
});
const requestPermission = useCallback(async (): Promise<NotificationPermission> => {
if (typeof Notification === "undefined") return "denied";
const result = await Notification.requestPermission();
setPermission(result);
return result;
}, []);
const notifyNewMail = useCallback((count: number, folder?: string) => {
Iif (typeof Notification === "undefined") return;
if (Notification.permission !== "granted") return;
if (localStorage.getItem("stork-notifications") === "false") return;
if (document.hasFocus()) return;
const title = count === 1 ? "1 new message" : `${count} new messages`;
const body = folder ? `in ${folder}` : "";
new Notification(title, {
body,
icon: "/favicon.svg",
// Use a tag so rapid syncs coalesce into one notification
tag: "stork-new-mail",
});
}, []);
return { permission, requestPermission, notifyNewMail };
}
|