terry-wallet-login #15

Merged
terry merged 95 commits from terry-wallet-login into terry-staging 2026-06-05 16:32:43 +00:00
Showing only changes of commit 4f6cbbc314 - Show all commits

View File

@@ -1,4 +1,4 @@
import { Heart, RotateCcw, Search, SlidersHorizontal, X } from "lucide-react";
import { Heart, RotateCcw } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import {
@@ -10,14 +10,9 @@ import {
type Resource,
} from "../../api";
import { FavoriteButton } from "../../favorites/FavoriteButton";
import {
isFavoritesAuthError,
listFavorites,
type FavoriteSort,
} from "../../favorites/api";
import { isFavoritesAuthError, listFavorites } from "../../favorites/api";
import { useFavorites } from "../../favorites/FavoritesProvider";
import { langQuery, useI18n, type Lang } from "../../i18n";
import { homePathForLang } from "../../languageRoutes";
import { Reveal } from "../../motion";
import { useSetPageTitle } from "../../components/PageTitleContext";
import { Skeleton } from "../../components/Skeleton";
@@ -25,16 +20,18 @@ import { useWallet } from "../../wallet/WalletProvider";
import { useLocalizedPath } from "../../useLocalizedPath";
import { cleanCategoryDisplayName } from "../../utils/categoryDisplay";
import { formatDateYmd } from "../../utils/format";
import { resourceTypeLabel } from "../../resourceTypeLabels";
const pageSize = 24;
const pageSize = 50;
function useCategories(lang: Lang) {
function useCategoryNameBySlug(lang: Lang): Map<string, string> {
const [categories, setCategories] = useState<Category[]>([]);
useEffect(() => {
const url = `/api/categories?lang=${encodeURIComponent(langQuery(lang))}`;
const cached = readJSONCache<Category[]>(url);
if (cached) setCategories(itemsOrEmpty(cached));
let cancelled = false;
getJSON<Category[]>(url)
.then((items) => {
@@ -43,19 +40,100 @@ function useCategories(lang: Lang) {
.catch(() => {
if (!cancelled && !cached) setCategories([]);
});
return () => {
cancelled = true;
};
}, [lang]);
return categories;
return useMemo(() => {
const map = new Map<string, string>();
categories.forEach((category) => map.set(category.slug, category.name));
return map;
}, [categories]);
}
function FavoriteResourceCard({ resource }: { resource: Resource }) {
const { t } = useI18n();
type FavoriteAttachment = {
thumbnailUrl?: string;
thumbUrl?: string;
posterUrl?: string;
url?: string;
};
type FavoriteLocalization = {
title?: string;
text?: string;
description?: string;
};
type FavoriteResource = Resource & {
postType?: string;
sourceLanguage?: string;
createdAt?: string;
attachments?: FavoriteAttachment[];
localizations?: Record<string, FavoriteLocalization>;
};
function localizationKeys(lang: Lang): string[] {
if (lang === "zh-CN") return ["zh", "zh-CN", "zh-Hans"];
return [lang];
}
function localizedResourceText(
resource: FavoriteResource,
lang: Lang,
field: "title" | "description",
): string {
for (const key of localizationKeys(lang)) {
const localized = resource.localizations?.[key];
if (!localized) continue;
if (field === "title" && localized.title?.trim()) return localized.title;
if (field === "description") {
const text = localized.description || localized.text;
if (text?.trim()) return text;
}
}
if (field === "title") return resource.title;
return resource.description || resource.bodyText || "";
}
function firstAttachmentUrl(resource: FavoriteResource): string {
const attachment = resource.attachments?.[0];
return (
attachment?.thumbnailUrl ||
attachment?.thumbUrl ||
attachment?.posterUrl ||
attachment?.url ||
""
);
}
function FavoriteResourceCard({
categoryNameBySlug,
resource,
}: {
categoryNameBySlug: Map<string, string>;
resource: FavoriteResource;
}) {
const { lang, t } = useI18n();
const lp = useLocalizedPath();
const unavailable = resource.availability === "unavailable";
const cover = resource.coverImage || resource.previewUrl;
const cover =
resource.coverImage || resource.previewUrl || firstAttachmentUrl(resource);
const categoryLabel =
(resource.categorySlug && categoryNameBySlug.get(resource.categorySlug)) ||
resource.categoryName ||
resource.categorySlug ||
"ARK";
const typeLabel = resourceTypeLabel(
t,
resource.type || resource.postType || "resource",
);
const date =
resource.updatedAt || resource.publishedAt || resource.createdAt || "";
const title = localizedResourceText(resource, lang, "title");
const description = localizedResourceText(resource, lang, "description");
return (
<article
className={`group relative flex min-h-[132px] gap-4 rounded-2xl border bg-[#272632] p-3 transition md:p-4 ${
@@ -67,7 +145,7 @@ function FavoriteResourceCard({ resource }: { resource: Resource }) {
{!unavailable ? (
<Link
to={lp(`/resource/${resource.id}`)}
aria-label={resource.title}
aria-label={title}
className="absolute inset-0 z-0 rounded-2xl outline-none focus-visible:ring-2 focus-visible:ring-ark-gold/80"
/>
) : null}
@@ -94,22 +172,24 @@ function FavoriteResourceCard({ resource }: { resource: Resource }) {
<div className="pointer-events-none relative z-10 flex min-w-0 flex-1 flex-col gap-2 pr-11">
<h2 className="line-clamp-2 text-base font-bold leading-snug text-white md:text-lg">
{resource.title}
{title}
</h2>
{resource.description ? (
{description ? (
<p className="line-clamp-2 text-sm leading-6 text-neutral-400">
{resource.description}
{description}
</p>
) : null}
<div className="mt-auto flex flex-wrap items-center gap-2 text-xs text-neutral-400">
<span className="rounded-full bg-[#1f2028] px-2.5 py-1 text-neutral-200">
{cleanCategoryDisplayName(resource.categoryName)}
{cleanCategoryDisplayName(categoryLabel)}
</span>
<span>{resource.type}</span>
<span>{typeLabel}</span>
{date ? (
<>
<span>·</span>
<time dateTime={resource.updatedAt}>
{formatDateYmd(resource.updatedAt)}
</time>
<time dateTime={date}>{formatDateYmd(date)}</time>
</>
) : null}
{typeof resource.favoriteCount === "number" ? (
<span>· {resource.favoriteCount}</span>
) : null}
@@ -128,51 +208,37 @@ export default function Favorites() {
const { lang, t } = useI18n();
const wallet = useWallet();
const { markFavorite } = useFavorites();
const categories = useCategories(lang);
const [sort, setSort] = useState<FavoriteSort>("favorited_at");
const [category, setCategory] = useState("");
const [queryInput, setQueryInput] = useState("");
const [query, setQuery] = useState("");
const [page, setPage] = useState(1);
const [items, setItems] = useState<Resource[]>([]);
const [total, setTotal] = useState(0);
const categoryNameBySlug = useCategoryNameBySlug(lang);
const [items, setItems] = useState<FavoriteResource[]>([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const [showFilters, setShowFilters] = useState(false);
useSetPageTitle(t("favorites"));
useEffect(() => {
setPage(1);
}, [sort, category, query]);
useEffect(() => {
if (!wallet.token || wallet.status !== "loggedIn") {
setItems([]);
setTotal(0);
setLoading(false);
setLoaded(false);
setError("");
return;
}
let cancelled = false;
setLoading(true);
setLoaded(false);
setError("");
listFavorites(wallet.token, {
sort,
category,
q: query,
page,
limit: pageSize,
includeUnavailable: true,
})
.then((data) => {
if (cancelled) return;
const resources = itemsOrEmpty(data.items);
const resources = itemsOrEmpty(data.items) as FavoriteResource[];
setItems(resources);
setTotal(data.total ?? resources.length);
resources.forEach((resource) => markFavorite(resource.id, true));
setLoaded(true);
})
@@ -189,22 +255,11 @@ export default function Favorites() {
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [category, markFavorite, page, query, reloadKey, sort, t, wallet]);
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const hasFilters = Boolean(category || query || sort !== "favorited_at");
const sortOptions = useMemo(
() => [
{ value: "favorited_at" as const, label: t("favoritesSortFavoritedAt") },
{ value: "published_at" as const, label: t("favoritesSortPublishedAt") },
{ value: "hot" as const, label: t("favoritesSortHot") },
],
[t],
);
}, [markFavorite, reloadKey, t, wallet]);
if (wallet.status === "loading") {
return (
@@ -240,118 +295,11 @@ export default function Favorites() {
}
return (
<Reveal className="mx-auto grid max-w-[980px] gap-5 px-0 py-2 md:py-4">
<div className="rounded-3xl border border-white/10 bg-[#17171d] p-4 shadow-xl shadow-black/20 md:p-5">
<div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
<div>
<p className="text-sm font-semibold text-ark-gold2">
{t("favorites")}
</p>
<h1 className="mt-1 text-2xl font-bold text-white md:text-3xl">
{t("favoritesLibraryTitle")}
</h1>
</div>
<Link
to={homePathForLang(lang)}
className="inline-flex h-10 items-center justify-center rounded-full border border-ark-gold/50 px-4 text-sm font-semibold text-ark-gold transition hover:bg-ark-gold/10"
>
{t("backToHome")}
</Link>
</div>
<form
className="mt-5 grid gap-3 md:grid-cols-[1fr_180px_180px_auto]"
onSubmit={(event) => {
event.preventDefault();
setQuery(queryInput.trim());
}}
>
<label className="relative block">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral-500" />
<input
value={queryInput}
onChange={(event) => setQueryInput(event.target.value)}
placeholder={t("favoritesSearchPlaceholder")}
className="h-11 w-full rounded-full border border-white/10 bg-[#101016] pl-10 pr-4 text-sm text-white outline-none transition placeholder:text-neutral-500 focus:border-ark-gold/60"
/>
</label>
{/* Mobile-only toggle: collapse sort/category into a "Filters" drawer. */}
<button
type="button"
onClick={() => setShowFilters((value) => !value)}
aria-expanded={showFilters}
className="inline-flex h-11 items-center justify-center gap-2 rounded-full border border-white/10 bg-[#101016] px-4 text-sm font-medium text-neutral-200 transition hover:border-ark-gold/40 hover:text-ark-gold md:hidden"
>
<SlidersHorizontal className="h-4 w-4" />
{t("favoritesFilters")}
</button>
<div
className={`${showFilters ? "grid" : "hidden"} gap-3 md:contents`}
>
<label className="relative block">
<SlidersHorizontal className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral-500" />
<select
value={sort}
onChange={(event) =>
setSort(event.target.value as FavoriteSort)
}
className="h-11 w-full appearance-none rounded-full border border-white/10 bg-[#101016] pl-10 pr-4 text-sm text-white outline-none focus:border-ark-gold/60"
>
{sortOptions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<select
value={category}
onChange={(event) => setCategory(event.target.value)}
className="h-11 w-full rounded-full border border-white/10 bg-[#101016] px-4 text-sm text-white outline-none focus:border-ark-gold/60"
>
<option value="">{t("favoritesFilterAllCategories")}</option>
{categories.map((cat) => (
<option key={cat.slug} value={cat.slug}>
{cleanCategoryDisplayName(cat.name)}
</option>
))}
</select>
</div>
<button
type="submit"
className="inline-flex h-11 items-center justify-center rounded-full bg-ark-gold px-5 text-sm font-bold text-black transition hover:bg-ark-gold2"
>
{t("search")}
</button>
</form>
{hasFilters ? (
<button
type="button"
onClick={() => {
setSort("favorited_at");
setCategory("");
setQuery("");
setQueryInput("");
}}
className="mt-3 inline-flex items-center gap-1 rounded-full border border-white/10 px-3 py-1.5 text-xs font-medium text-neutral-300 transition hover:border-ark-gold/40 hover:text-ark-gold"
>
<X className="h-3.5 w-3.5" />
{t("favoritesClearFilters")}
</button>
) : null}
</div>
<div className="mx-auto grid max-w-[980px] gap-3 px-0 py-2 md:py-4">
{loading || !loaded ? (
<div className="grid gap-3">
{Array.from({ length: 4 }).map((_, index) => (
Array.from({ length: 4 }).map((_, index) => (
<Skeleton key={index} className="h-[132px] rounded-2xl" />
))}
</div>
))
) : error ? (
<div className="flex flex-col items-start gap-3 rounded-2xl border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-200">
<p>{error}</p>
@@ -368,49 +316,21 @@ export default function Favorites() {
<div className="flex min-h-[280px] flex-col items-center justify-center gap-4 rounded-3xl border border-white/10 bg-[#17171d] p-8 text-center">
<Heart className="h-10 w-10 text-ark-gold/60" strokeWidth={1.8} />
<h2 className="text-xl font-semibold text-white">
{hasFilters
? t("favoritesNoFilteredTitle")
: t("favoritesEmptyTitle")}
{t("favoritesEmptyTitle")}
</h2>
<p className="max-w-md text-sm leading-6 text-neutral-400">
{hasFilters
? t("favoritesNoFilteredDesc")
: t("favoritesEmptyDesc")}
{t("favoritesEmptyDesc")}
</p>
</div>
) : (
<div className="grid gap-3">
{items.map((resource) => (
<FavoriteResourceCard key={resource.id} resource={resource} />
))}
</div>
items.map((resource) => (
<FavoriteResourceCard
key={resource.id}
categoryNameBySlug={categoryNameBySlug}
resource={resource}
/>
))
)}
{totalPages > 1 ? (
<div className="flex items-center justify-center gap-3">
<button
type="button"
disabled={page <= 1}
onClick={() => setPage((value) => Math.max(1, value - 1))}
className="rounded-full border border-white/10 px-4 py-2 text-sm text-neutral-200 transition hover:border-ark-gold/50 disabled:cursor-not-allowed disabled:opacity-40"
>
{t("paginationPrev")}
</button>
<span className="text-sm text-neutral-400">
{t("pageIndicator")
.replace("{{c}}", String(page))
.replace("{{p}}", String(totalPages))}
</span>
<button
type="button"
disabled={page >= totalPages}
onClick={() => setPage((value) => Math.min(totalPages, value + 1))}
className="rounded-full border border-white/10 px-4 py-2 text-sm text-neutral-200 transition hover:border-ark-gold/50 disabled:cursor-not-allowed disabled:opacity-40"
>
{t("paginationNext")}
</button>
</div>
) : null}
</Reveal>
);
}