All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 51s
Search: GET /api/search sent each matching user's full row — password hash and email included — to anyone, signed in or not, because searchUsersGlobal returned User[] and the route passed it through. It returns profiles only now, stripped where the rows are read, and the search test fails on the old code. Types alone wouldn't have caught it (a User is structurally a PublicUser), so the strip is explicit and tested.
Typed routes. Every JSON response is declared as APIResponse<T>, the way the typed routes already did, with the missing shapes named in api/model/interfaces.ts: PublicUser (no hash, no email) and SelfUser (your own profile, with email) plus toPublicUser/toSelfUser in place of ten hand-written destructurings, AuthTokens, AuthResponse, MediaTokenResponse, InviteResponse, AttachmentResponse, SearchResults, LinkPreview, UserSuggestion and Invitee. Request bodies are `unknown` and narrowed by the existing guards, or by a new fieldOf(obj, key) where a route reads one field — no more reading off Oak's `any` or casting to Record<string, unknown>. The password-reset routes answer `{ success: true, data: null }` rather than a bare `{ success: true }`, so every success fits the envelope; the frontend only reads `success`.
Socket protocol: routes/ws.ts had its own send() taking Record<string, unknown>, so nothing checked what it sent. It takes ServerToClientMessage now, which turned up two mismatches: `pong` was missing from the union although the server answers every client ping with one, and vote_ack carried a `success: true` no type declares and no client reads. The union has PongMessage and vote_ack lost the field.
No explicit any. The YouTube playlist parse reads ytInitialData as `unknown` through a small at(node, …path) that checks each step, instead of `type Json = any`. The backend test helpers type the response body as the server's envelope: request<T>() and get/post/put/patch/del<T>() name what `data` holds, res.data throws with the server's message when the call didn't succeed and res.error when it didn't fail, and each test says which API type it expects, so a test reading a field the route doesn't send no longer compiles. Assertions that a field is absent are `assertFalse("passwordHash" in …)` rather than reading a field the type says isn't there. The socket tests' messages are ServerToClientMessage, with next()/all() keyed by type so each returns that message's shape.
No double casts in src/ either. window.YT and onYouTubeIframeAPIReady are declared on Window; the test's fake player is a class forwarding to the spies the tests inspect. WSContext, FollowContext and PlayerContext export their defaults (defaultWSValue, defaultFollowValue, defaultPlayerValue), which the tests import instead of reading React's private _currentValue. handleMentionKeyDown takes a MentionKey — the key fields it reads — so the test builds a plain object; useUserDumpFeed declares sentinelRef as the callback ref it is. In src/test/setup.ts the IntersectionObserver fake implements IntersectionObserver, and report(isIntersecting, top?) builds complete entries in place of partial ones cast in five files; the Animation fake implements Animation; the canvas getContext stub goes in through defineProperty. The XHR fake's last request is optional behind a getter that fails if none was made, the keyframes are checked with matchers, and the roleless legacy session is built by leaving the role out. One test changes meaning slightly: "leaving the view…" relied on entries with no position at all, and now leaves and re-enters at the same height, which is what it describes. The one cast left is in api/test/ws.test.ts: deno.json's "dom" lib hides Deno's WebSocket overload that takes handshake headers, and dropping that lib would break the editor's view of src/; it's commented and names the real signature.
Also: the notifications test answered a Response-typed promise with a plain object, which failed `tsc -b`; it uses the fetch stub's deferred() now. ESLint didn't read the `deno-lint-ignore no-explicit-any` comments, so `eslint .` failed on three files; those anys are gone. `deno fmt` over api/ and src/ (not the compiled src/locales/*.js); the reflow left all 332 message ids intact, and the .po files only have their source line references updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
365 lines
11 KiB
TypeScript
365 lines
11 KiB
TypeScript
import {
|
|
useCallback,
|
|
useEffect,
|
|
useLayoutEffect,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
} from "react";
|
|
import { useLocation, useParams } from "react-router";
|
|
|
|
import { AppHeader } from "../components/AppHeader.tsx";
|
|
import { PresenceRow } from "../components/PresenceRow.tsx";
|
|
import { FeedTabBar } from "../components/FeedTabBar.tsx";
|
|
import {
|
|
DEFAULT_FEED_TAB,
|
|
FEED_TABS,
|
|
type FeedTab,
|
|
} from "../config/feedTabs.ts";
|
|
import { useDefaultFeedTab } from "../hooks/useDefaultFeedTab.ts";
|
|
|
|
import { API_URL, DEFAULT_PAGE_SIZE } from "../config/api.ts";
|
|
|
|
import {
|
|
deserializeDump,
|
|
type Dump,
|
|
hydrateDump,
|
|
type PaginatedData,
|
|
type RawDump,
|
|
} from "../model.ts";
|
|
|
|
import { friendlyFetchError } from "../utils/apiError.ts";
|
|
import { useFeedCache } from "../hooks/useFeedCache.ts";
|
|
import { useScrollSave } from "../hooks/useScrollSave.ts";
|
|
import { useDocumentTitle } from "../hooks/useDocumentTitle.ts";
|
|
import { useAuth } from "../hooks/useAuth.ts";
|
|
import { useWS } from "../hooks/useWS.ts";
|
|
import { useCategories } from "../hooks/useCategories.ts";
|
|
import { useDumpListSync } from "../hooks/useDumpListSync.ts";
|
|
import { useInfiniteScroll } from "../hooks/useInfiniteScroll.ts";
|
|
|
|
import { HotFeed } from "./index/HotFeed.tsx";
|
|
import { NewFeed } from "./index/NewFeed.tsx";
|
|
import { JournalFeed } from "./index/JournalFeed.tsx";
|
|
import { FollowedFeed } from "./index/FollowedFeed.tsx";
|
|
import { NotFound } from "./NotFound.tsx";
|
|
import type { MainFeedProps } from "./index/types.ts";
|
|
|
|
type DumpsState =
|
|
| { status: "loading" }
|
|
| { status: "error"; error: string }
|
|
| {
|
|
status: "loaded";
|
|
dumps: Dump[];
|
|
hasMore: boolean;
|
|
page: number;
|
|
loadingMore: boolean;
|
|
};
|
|
|
|
/**
|
|
* The shared feed page. `categorySlug` scopes it to a single category; when
|
|
* absent it shows every dump. The router keys this component by scope, so each
|
|
* category gets its own mount/fetch while switching feed tabs reuses it.
|
|
*/
|
|
export function Index({ categorySlug }: { categorySlug?: string }) {
|
|
const location = useLocation();
|
|
const justDeletedId = (location.state as { deletedDumpId?: string } | null)
|
|
?.deletedDumpId;
|
|
|
|
const { user, token } = useAuth();
|
|
const {
|
|
voteCounts,
|
|
myVotes,
|
|
recentDumps,
|
|
deletedDumpIds,
|
|
castVote,
|
|
removeVote,
|
|
connectionEpoch,
|
|
} = useWS();
|
|
|
|
// Resolve the scope to a real category (for its id, name, and 404 handling).
|
|
const { categories, isLoaded: categoriesLoaded } = useCategories();
|
|
const category = categorySlug
|
|
? categories.find((c) => c.slug === categorySlug)
|
|
: undefined;
|
|
const categoryNotFound = !!categorySlug && categoriesLoaded && !category;
|
|
|
|
useDocumentTitle(
|
|
categorySlug ? (category ? category.name : undefined) : null,
|
|
);
|
|
|
|
// ── Active feed tab (from the URL) ──
|
|
|
|
const { feedTab: rawTab } = useParams();
|
|
const [preferredTab] = useDefaultFeedTab();
|
|
const defaultTab: FeedTab = preferredTab === "followed" && !user
|
|
? DEFAULT_FEED_TAB
|
|
: preferredTab;
|
|
// "followed" needs a session: a guest there (a shared link, or signed out
|
|
// on it) gets the default feed rather than an empty page.
|
|
const tab: FeedTab =
|
|
(FEED_TABS as readonly string[]).includes(rawTab ?? "") &&
|
|
(rawTab !== "followed" || !!user)
|
|
? (rawTab as FeedTab)
|
|
: defaultTab;
|
|
|
|
// ── Main feed state ──
|
|
|
|
const feedUrl = useCallback(
|
|
(page: number) =>
|
|
categorySlug
|
|
? `${API_URL}/api/categories/${
|
|
encodeURIComponent(categorySlug)
|
|
}/dumps?page=${page}&limit=${DEFAULT_PAGE_SIZE}`
|
|
: `${API_URL}/api/dumps/?page=${page}&limit=${DEFAULT_PAGE_SIZE}`,
|
|
[categorySlug],
|
|
);
|
|
|
|
const { cached, saveState } = useFeedCache<Dump>(
|
|
`feed:index:${categorySlug ?? "all"}:${user?.id ?? "guest"}`,
|
|
hydrateDump,
|
|
);
|
|
const [dumpsState, setDumpsState] = useState<DumpsState>(() =>
|
|
cached
|
|
? {
|
|
status: "loaded",
|
|
dumps: cached.items,
|
|
hasMore: cached.hasMore,
|
|
page: cached.page,
|
|
loadingMore: false,
|
|
}
|
|
: { status: "loading" }
|
|
);
|
|
const mainFetchDone = useRef(false);
|
|
|
|
// Web Share Target: Android share sheet navigates to /?share_url=...
|
|
const searchParams = new URLSearchParams(location.search);
|
|
const shareUrl = searchParams.get("share_url") ??
|
|
searchParams.get("share_text") ?? "";
|
|
|
|
useEffect(() => {
|
|
if (!shareUrl) return;
|
|
globalThis.history.replaceState({}, "", location.pathname);
|
|
}, [shareUrl, location.pathname]);
|
|
|
|
// ── Main feed fetch ──
|
|
|
|
useEffect(() => {
|
|
if (mainFetchDone.current || cached) return;
|
|
mainFetchDone.current = true;
|
|
const controller = new AbortController();
|
|
(async () => {
|
|
try {
|
|
const res = await fetch(feedUrl(1), {
|
|
signal: controller.signal,
|
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
});
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
const body = await res.json();
|
|
const { items, hasMore } = body.data as PaginatedData<RawDump>;
|
|
setDumpsState({
|
|
status: "loaded",
|
|
dumps: items.map(deserializeDump),
|
|
hasMore,
|
|
page: 1,
|
|
loadingMore: false,
|
|
});
|
|
} catch (err) {
|
|
if ((err as Error).name === "AbortError") return;
|
|
setDumpsState({ status: "error", error: friendlyFetchError(err) });
|
|
}
|
|
})();
|
|
return () => {
|
|
mainFetchDone.current = false;
|
|
controller.abort();
|
|
};
|
|
}, [cached, token, feedUrl]);
|
|
|
|
// ── WS sync for main feed ──
|
|
|
|
const setDumpsItems = useCallback(
|
|
(fn: (prev: Dump[]) => Dump[]) =>
|
|
setDumpsState((s) =>
|
|
s.status !== "loaded" ? s : { ...s, dumps: fn(s.dumps) }
|
|
),
|
|
[],
|
|
);
|
|
useDumpListSync(setDumpsItems);
|
|
|
|
// ── Reconnect backfill ──
|
|
|
|
// New dumps that arrived while the socket was down weren't delivered. On
|
|
// reconnect, re-fetch page 1 and merge anything not already present on top,
|
|
// preserving loaded pages and scroll position.
|
|
const backfillEpochRef = useRef(connectionEpoch);
|
|
useEffect(() => {
|
|
if (connectionEpoch === backfillEpochRef.current) return;
|
|
backfillEpochRef.current = connectionEpoch;
|
|
const controller = new AbortController();
|
|
fetch(feedUrl(1), {
|
|
signal: controller.signal,
|
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
})
|
|
.then((r) => r.json())
|
|
.then((body) => {
|
|
const { items } = body.data as PaginatedData<RawDump>;
|
|
const fresh = items.map(deserializeDump);
|
|
setDumpsState((s) => {
|
|
if (s.status !== "loaded") return s;
|
|
const known = new Set(s.dumps.map((d) => d.id));
|
|
const newOnes = fresh.filter((d) => !known.has(d.id));
|
|
if (newOnes.length === 0) return s;
|
|
return { ...s, dumps: [...newOnes, ...s.dumps] };
|
|
});
|
|
})
|
|
.catch(() => {});
|
|
return () => controller.abort();
|
|
}, [connectionEpoch, feedUrl, token]);
|
|
|
|
// ── Load more ──
|
|
|
|
const loadMore = useCallback(() => {
|
|
if (
|
|
dumpsState.status !== "loaded" || !dumpsState.hasMore ||
|
|
dumpsState.loadingMore
|
|
) return;
|
|
const nextPage = dumpsState.page + 1;
|
|
setDumpsState((s) =>
|
|
s.status === "loaded" ? { ...s, loadingMore: true } : s
|
|
);
|
|
fetch(feedUrl(nextPage), {
|
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
})
|
|
.then((r) => r.json())
|
|
.then((body) => {
|
|
const { items, hasMore } = body.data as PaginatedData<RawDump>;
|
|
setDumpsState((s) =>
|
|
s.status === "loaded"
|
|
? {
|
|
...s,
|
|
dumps: [...s.dumps, ...items.map(deserializeDump)],
|
|
hasMore,
|
|
page: nextPage,
|
|
loadingMore: false,
|
|
}
|
|
: s
|
|
);
|
|
})
|
|
.catch(() =>
|
|
setDumpsState((s) =>
|
|
s.status === "loaded" ? { ...s, loadingMore: false } : s
|
|
)
|
|
);
|
|
}, [dumpsState, token, feedUrl]);
|
|
|
|
// ── Scroll save / restore ──
|
|
|
|
const sentinelRef = useInfiniteScroll(
|
|
loadMore,
|
|
dumpsState.status === "loaded" && dumpsState.hasMore &&
|
|
!dumpsState.loadingMore,
|
|
);
|
|
|
|
useScrollSave(
|
|
dumpsState.status === "loaded",
|
|
useCallback((y) => {
|
|
if (dumpsState.status !== "loaded") return;
|
|
saveState(dumpsState.dumps, dumpsState.page, dumpsState.hasMore, y);
|
|
}, [dumpsState, saveState]),
|
|
);
|
|
|
|
const scrollRestored = useRef(false);
|
|
useLayoutEffect(() => {
|
|
if (cached?.scrollY == null || scrollRestored.current) return;
|
|
if (dumpsState.status === "loaded") {
|
|
globalThis.scrollTo(0, cached.scrollY);
|
|
scrollRestored.current = true;
|
|
}
|
|
}, [dumpsState.status, cached]);
|
|
|
|
// ── Derived values ──
|
|
|
|
const loading = dumpsState.status === "loading";
|
|
const error = dumpsState.status === "error" ? dumpsState.error : null;
|
|
const dumps = useMemo(
|
|
() => dumpsState.status === "loaded" ? dumpsState.dumps : [],
|
|
[dumpsState],
|
|
);
|
|
const loadingMore = dumpsState.status === "loaded" && dumpsState.loadingMore;
|
|
const hasMore = dumpsState.status === "loaded" ? dumpsState.hasMore : false;
|
|
|
|
// New dumps arriving over the WS only belong in this feed if they're in scope.
|
|
const categoryId = category?.id;
|
|
const inScope = useCallback(
|
|
(d: Dump) =>
|
|
categorySlug
|
|
? !!categoryId && !!d.categoryIds?.includes(categoryId)
|
|
: true,
|
|
[categorySlug, categoryId],
|
|
);
|
|
|
|
const restIds = useMemo(() => new Set(dumps.map((d) => d.id)), [dumps]);
|
|
const combined = useMemo(
|
|
() =>
|
|
[...recentDumps.filter((d) => inScope(d) && !restIds.has(d.id)), ...dumps]
|
|
.filter((d) => !deletedDumpIds.has(d.id) && d.id !== justDeletedId),
|
|
[recentDumps, restIds, dumps, deletedDumpIds, justDeletedId, inScope],
|
|
);
|
|
|
|
const mainFeedProps: MainFeedProps = {
|
|
dumps: combined,
|
|
loading,
|
|
error,
|
|
hasMore,
|
|
loadingMore,
|
|
sentinelRef,
|
|
voteCounts,
|
|
myVotes,
|
|
user,
|
|
castVote,
|
|
removeVote,
|
|
};
|
|
|
|
// ── Render ──
|
|
|
|
if (categoryNotFound) return <NotFound />;
|
|
|
|
return (
|
|
<div className="index-page">
|
|
<AppHeader
|
|
centerSlot={
|
|
<div className="header-center-slot">
|
|
<PresenceRow
|
|
fitWithin=".app-header-center"
|
|
fitBeside=".feed-sort"
|
|
/>
|
|
<FeedTabBar />
|
|
</div>
|
|
}
|
|
disableNew={dumpsState.status === "error"}
|
|
initialDumpUrl={shareUrl || undefined}
|
|
/>
|
|
|
|
<div className="index-below-header">
|
|
<FeedTabBar />
|
|
<PresenceRow fitWithin=".index-below-header" fitBeside=".feed-sort" />
|
|
</div>
|
|
|
|
{tab === "hot" && <HotFeed {...mainFeedProps} />}
|
|
{tab === "new" && <NewFeed {...mainFeedProps} />}
|
|
{tab === "journal" && <JournalFeed {...mainFeedProps} />}
|
|
{tab === "followed" && user && (
|
|
<FollowedFeed
|
|
categorySlug={categorySlug}
|
|
voteCounts={voteCounts}
|
|
myVotes={myVotes}
|
|
user={user}
|
|
castVote={castVote}
|
|
removeVote={removeVote}
|
|
deletedDumpIds={deletedDumpIds}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|