v3: src/ gets one layout rule and keeps to it — each layer holds one kind of module, and every layer is split into the same domains — the previous pass sorted components into folders but left hooks, helpers and a barrel inside them, kept hooks/, utils/ and contexts/ flat, and still grouped most tests by theme. The rule: components/ holds only components (.tsx), contexts/ holds FooContext.ts + FooProvider.tsx pairs, hooks/ every hook, utils/ every non-React module, pages/ one component per route and nothing else. Each of components/, contexts/, hooks/ and utils/ is split into the same domains — auth, category, chat, comment, dump, editor, feed, form, layout, player, playlist, profile, social, theme, ws — plus shared/ for what belongs to no one domain, so the chat is components/chat, contexts/chat, hooks/chat and utils/chat. components/ui becomes components/shared to match. Out of components/: useApiForm goes to hooks/form, chat's message.ts and time.ts to utils/chat (with chatDraft and chatText, now draft.ts and text.ts), the emoji skin tone to utils/editor, the remembered volume to utils/player; player/icons.tsx is PlayerIcons.tsx. components/form/index.ts is gone: everything is imported from its own file, FormProvider straight from react-hook-form, and expectOk sits beside friendlyFetchError in utils/shared/api.ts (apiError.ts), since pages that have no form used it too. Out of pages/: the index's feed views, tab bar and presence row move to components/feed; HotFeed and NewFeed, identical but for the sort, are one DumpFeed with an order prop, which also takes over MainFeedProps from pages/index/types.ts. App is a named export like everything else. Tests mirror the tree one file per module — test/<layer>/<domain>/<Module>.test.tsx — so the themed files (hooks/misc, data, editor, sync; utils/misc, text, storage, remote, journal; contexts/providers; pages/auth and UserSubpages; layout/Fabs) are split by subject, the setup each piece needs kept and the rest dropped; the floating-button test becomes one test per button, 627 tests now. The README states the rule. No behaviour changes; the catalogues only move their source references.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-27 19:44:14 +00:00
parent 07d0344be7
commit 2b6e68391b
242 changed files with 4390 additions and 4229 deletions

View File

@@ -0,0 +1,32 @@
import { useCallback, useState } from "react";
import {
DEFAULT_FEED_TAB,
FEED_TABS,
type FeedTab,
} from "../../config/feedTabs.ts";
const STORAGE_KEY = "default-feed-tab";
function readStored(): FeedTab {
const stored = localStorage.getItem(STORAGE_KEY);
return stored && (FEED_TABS as readonly string[]).includes(stored)
? stored as FeedTab
: DEFAULT_FEED_TAB;
}
/**
* User preference for which feed tab the index opens on, persisted to
* localStorage (defaults to DEFAULT_FEED_TAB). Returns the stored tab and a setter that
* persists the choice. Consumers that only need to honour the preference (e.g.
* the index default) can ignore the setter.
*/
export function useDefaultFeedTab(): [FeedTab, (tab: FeedTab) => void] {
const [tab, setTabState] = useState<FeedTab>(readStored);
const setTab = useCallback((t: FeedTab) => {
localStorage.setItem(STORAGE_KEY, t);
setTabState(t);
}, []);
return [tab, setTab];
}

View File

@@ -0,0 +1,78 @@
import { useCallback, useEffect, useRef, useState } from "react";
/**
* Manages a 2-second cooldown + 350ms dismissal animation for a set of items.
*
* Call `startFading(id)` when an item should begin fading out.
* Call `cancelFading(id)` to abort the animation (e.g. the action was reversed).
* Use the returned `fading` record to apply CSS classes:
* - `"cooldown"` → item is in the 2-second grace period (darkened)
* - `"dismissing"` → item is collapsing (opacity 0 + grid-row collapse)
*/
export function useFading() {
const [fading, setFading] = useState<
Record<string, "cooldown" | "dismissing">
>({});
const cancels = useRef<Map<string, () => void>>(new Map());
useEffect(() => () => {
cancels.current.forEach((c) => c());
}, []);
const startFading = useCallback((id: string) => {
if (cancels.current.has(id)) return;
let dead = false;
let kill = () => {};
kill = () => {
dead = true;
setFading((f) => {
const n = { ...f };
delete n[id];
return n;
});
cancels.current.delete(id);
};
cancels.current.set(id, () => kill());
setFading((f) => ({ ...f, [id]: "cooldown" }));
const t1 = setTimeout(() => {
if (dead) return;
setFading((f) => ({ ...f, [id]: "dismissing" }));
const t2 = setTimeout(() => {
if (!dead) kill();
}, 350);
kill = () => {
dead = true;
clearTimeout(t2);
setFading((f) => {
const n = { ...f };
delete n[id];
return n;
});
cancels.current.delete(id);
};
cancels.current.set(id, () => kill());
}, 2000);
kill = () => {
dead = true;
clearTimeout(t1);
setFading((f) => {
const n = { ...f };
delete n[id];
return n;
});
cancels.current.delete(id);
};
cancels.current.set(id, () => kill());
}, []);
const cancelFading = useCallback((id: string) => {
cancels.current.get(id)?.();
}, []);
/** Cancel all in-progress animations (e.g. on page navigation). */
const cancelAll = useCallback(() => {
cancels.current.forEach((c) => c());
}, []);
return { fading, startFading, cancelFading, cancelAll };
}

View File

@@ -0,0 +1,65 @@
import { useCallback, useState } from "react";
import { useNavigationType } from "react-router";
const TTL = 10 * 60 * 1000; // 10 minutes
interface FeedCacheEntry<T> {
items: T[];
page: number;
hasMore: boolean;
scrollY: number;
savedAt: number;
}
export interface FeedCacheResult<T> {
cached: Omit<FeedCacheEntry<T>, "savedAt"> | null;
saveState: (
items: T[],
page: number,
hasMore: boolean,
scrollY: number,
) => void;
}
export function useFeedCache<T>(
key: string,
hydrateItem: (raw: T) => T,
): FeedCacheResult<T> {
const navType = useNavigationType();
// useState initializer runs exactly once on mount — correct for a cache read.
const [cached] = useState<Omit<FeedCacheEntry<T>, "savedAt"> | null>(() => {
if (navType !== "POP") return null;
try {
const raw = sessionStorage.getItem(key);
if (!raw) return null;
const entry = JSON.parse(raw) as FeedCacheEntry<T>;
if (Date.now() - entry.savedAt > TTL) return null;
return { ...entry, items: entry.items.map(hydrateItem) };
} catch {
return null;
}
});
const saveState = useCallback(
(items: T[], page: number, hasMore: boolean, scrollY: number) => {
try {
sessionStorage.setItem(
key,
JSON.stringify({
items,
page,
hasMore,
scrollY,
savedAt: Date.now(),
}),
);
} catch {
// QuotaExceededError or SecurityError — degrade silently
}
},
[key],
);
return { cached, saveState };
}

View File

@@ -0,0 +1,80 @@
import { useCallback, useEffect, useRef, useState } from "react";
/** Longest wait between two loads while the sentinel never left the view. */
const MAX_RETRY_DELAY_MS = 30_000;
/**
* Observe a sentinel element and call `onLoadMore` when it scrolls into view.
*
* The sentinel is tracked via a state-backed callback ref rather than a plain
* `useRef` so the observer re-attaches whenever the underlying DOM node
* changes — e.g. when the index page swaps the active feed tab and a fresh
* sentinel `<div>` mounts in place of the old one. A static ref would keep
* observing the now-detached node and silently stop loading more.
*
* Each change of `enabled` makes a new observer, which reports the sentinel
* at once if it's still in view. After a load that added items that's what
* fills a tall screen; after one that failed it would ask again straight
* away, and again, as fast as the request can fail. So a sentinel that stays
* put in view waits longer each time — 1s, 2s, 4s… up to 30s — and goes back
* to asking at once when it leaves the view or is pushed down by new items.
*/
export function useInfiniteScroll(onLoadMore: () => void, enabled: boolean) {
const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
// Loads asked for since the sentinel last left the view or moved.
const attemptsRef = useRef(0);
const lastLoadAtRef = useRef(0);
const lastTopRef = useRef<number | null>(null);
const handleIntersect = useCallback(
(entries: IntersectionObserverEntry[]): (() => void) | undefined => {
const entry = entries[0];
const top = entry.boundingClientRect?.top ?? null;
if (!entry.isIntersecting) {
attemptsRef.current = 0;
lastTopRef.current = null;
return;
}
if (
top !== null && lastTopRef.current !== null && top > lastTopRef.current
) {
attemptsRef.current = 0;
}
lastTopRef.current = top;
if (!enabled) return;
const attempts = attemptsRef.current;
const load = () => {
attemptsRef.current = attempts + 1;
lastLoadAtRef.current = Date.now();
onLoadMore();
};
// Counted from the last load, not from now: the observer is remade on
// every render that changes onLoadMore, which mustn't restart the wait.
const wait = attempts === 0 ? 0 : lastLoadAtRef.current +
Math.min(1000 * 2 ** (attempts - 1), MAX_RETRY_DELAY_MS) - Date.now();
if (wait <= 0) {
load();
return;
}
const timer = setTimeout(load, wait);
return () => clearTimeout(timer);
},
[onLoadMore, enabled],
);
useEffect(() => {
if (!sentinel) return;
let cancelPending: (() => void) | undefined;
const observer = new IntersectionObserver((entries) => {
cancelPending?.();
cancelPending = handleIntersect(entries);
}, { rootMargin: "200px" });
observer.observe(sentinel);
return () => {
cancelPending?.();
observer.disconnect();
};
}, [handleIntersect, sentinel]);
return setSentinel;
}

View File

@@ -0,0 +1,63 @@
import { useEffect, useLayoutEffect, useRef } from "react";
/**
* Keeps track of item positions as items leave a list and re-inserts them
* at their original positions when they become visible again.
*
* MUST be called BEFORE the corresponding sync hook (useDumpListSync /
* usePlaylistListSync) so the save-position effect fires before the hook's
* removal effect in the same render cycle.
*
* @param items The current list (pass [] when state is not loaded).
* @param setItems The list setter (same one passed to the sync hook).
* @param lastEvent The latest changed item (Dump | Playlist | null).
* @param isRemoving Return true when the item is about to leave the list
* (e.g. it just became private). Used to save its index.
* @param shouldReinsert Return true when the item should come back at its
* original position (e.g. it just became public again).
*/
export function usePositionAwareSync<T extends { id: string }>(
items: T[],
setItems: (fn: (prev: T[]) => T[]) => void,
lastEvent: T | null,
isRemoving: (item: T) => boolean,
shouldReinsert: (item: T) => boolean,
): void {
const itemsRef = useRef<T[]>(items);
const setItemsRef = useRef(setItems);
const isRemovingRef = useRef(isRemoving);
const shouldReinsertRef = useRef(shouldReinsert);
useLayoutEffect(() => {
itemsRef.current = items;
setItemsRef.current = setItems;
isRemovingRef.current = isRemoving;
shouldReinsertRef.current = shouldReinsert;
});
const removedPositionsRef = useRef<Map<string, number>>(new Map());
// Save position BEFORE the sync hook removes the item.
useEffect(() => {
if (!lastEvent || !isRemovingRef.current(lastEvent)) return;
const idx = itemsRef.current.findIndex((item) => item.id === lastEvent.id);
if (idx !== -1) {
removedPositionsRef.current.set(lastEvent.id, idx);
}
}, [lastEvent]);
// Re-insert at the saved position. Fires before the sync hook's effect for
// the same event; skipReinsert on the sync hook prevents double-insertion.
useEffect(() => {
if (!lastEvent || !shouldReinsertRef.current(lastEvent)) return;
const savedIdx = removedPositionsRef.current.get(lastEvent.id);
if (savedIdx === undefined) return;
removedPositionsRef.current.delete(lastEvent.id);
const item = lastEvent;
setItemsRef.current((prev) => {
if (prev.some((i) => i.id === item.id)) return prev;
const next = [...prev];
next.splice(Math.min(savedIdx, next.length), 0, item);
return next;
});
}, [lastEvent]);
}

View File

@@ -0,0 +1,37 @@
import { useEffect, useLayoutEffect, useRef } from "react";
/**
* Calls `onSave(scrollY)` when the page is left — the component unmounts (a
* navigation within the app) or the tab goes away (`pagehide`) — as long as
* `enabled` is true (e.g. the page is loaded).
*
* Scrolling itself only notes the position: saving serializes the whole feed
* into sessionStorage, which on every pause in scrolling cost a long task.
*/
export function useScrollSave(
enabled: boolean,
onSave: (scrollY: number) => void,
) {
const onSaveRef = useRef(onSave);
useLayoutEffect(() => {
onSaveRef.current = onSave;
});
useEffect(() => {
if (!enabled) return;
// Tracked as it happens: by the time the unmount runs, the next page may
// already have scrolled the window back to the top.
let y = globalThis.scrollY;
const onScroll = () => {
y = globalThis.scrollY;
};
const save = () => onSaveRef.current(y);
globalThis.addEventListener("scroll", onScroll, { passive: true });
globalThis.addEventListener("pagehide", save);
return () => {
globalThis.removeEventListener("scroll", onScroll);
globalThis.removeEventListener("pagehide", save);
save();
};
}, [enabled]);
}