Initial frontend import

This commit is contained in:
TerryM
2026-05-16 00:18:22 +08:00
commit 9c54ffec76
99 changed files with 14992 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
import { useEffect, useState } from "react";
import { getJSONAuth } from "../../api";
import { getToken } from "../../admin/token";
import { useAdminT } from "../../admin/useAdminT";
type Dash = {
totalResources: number;
published: number;
todayNew: number;
totalViews: number;
totalDownloads: number;
totalFavorites: number;
totalShares: number;
hotResources: {
id: string;
title: string;
downloads: number;
favorites: number;
views: number;
}[];
};
export function AdminDashboard() {
const t = useAdminT();
const [d, setD] = useState<Dash | null>(null);
const token = getToken();
useEffect(() => {
getJSONAuth<Dash>("/api/admin/dashboard", token)
.then(setD)
.catch(() => setD(null));
}, [token]);
if (!d) return <div className="text-neutral-400">{t("loading")}</div>;
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">{t("dashboard")}</h1>
<div className="grid gap-3 md:grid-cols-3">
<Stat label={t("total")} value={d.totalResources} />
<Stat label={t("published")} value={d.published} />
<Stat label={t("adminStatTodayNew")} value={d.todayNew} />
<Stat label={t("views")} value={d.totalViews} />
<Stat label={t("downloads")} value={d.totalDownloads} />
<Stat label={t("adminStatFavorites")} value={d.totalFavorites} />
<Stat label={t("adminMetricShares")} value={d.totalShares} />
</div>
<div className="rounded-2xl border border-ark-line bg-ark-panel p-4">
<div className="font-semibold mb-3">{t("popular")}</div>
<div className="divide-y divide-ark-line">
{(d.hotResources ?? []).map((x) => (
<div
key={x.id}
className="py-2 flex items-center justify-between gap-3"
>
<div className="text-sm">{x.title}</div>
<div className="text-xs text-neutral-400">
{t("adminMetricDownloads")} {x.downloads} ·{" "}
{t("adminMetricFavorites")} {x.favorites} ·{" "}
{t("adminMetricViews")} {x.views}
</div>
</div>
))}
</div>
</div>
</div>
);
}
function Stat({ label, value }: { label: string; value: number }) {
return (
<div className="rounded-2xl border border-ark-line bg-ark-panel p-4">
<div className="text-xs text-neutral-400">{label}</div>
<div className="text-2xl font-bold mt-1">{value}</div>
</div>
);
}

View File

@@ -0,0 +1,64 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { postJSON } from "../../api";
import { setToken } from "../../admin/token";
import { useAdminT } from "../../admin/useAdminT";
import { useAdminRouterMode } from "../../adminRouterMode";
import { adminUiPrefix } from "../../adminPaths";
export function AdminLogin() {
const t = useAdminT();
const mode = useAdminRouterMode();
const nav = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [err, setErr] = useState<string | null>(null);
return (
<div className="min-h-[70vh] flex items-center justify-center">
<form
className="w-full max-w-md space-y-4 rounded-3xl border border-ark-line bg-ark-panel p-8"
onSubmit={async (e) => {
e.preventDefault();
setErr(null);
try {
const r = await postJSON<{ token: string }>("/api/admin/login", {
email,
password,
});
setToken(r.token);
nav(mode === "basename" ? "/" : adminUiPrefix);
} catch (e) {
setErr(String(e));
}
}}
>
<h1 className="text-2xl font-bold">{t("adminLoginTitle")}</h1>
<label className="block text-sm text-neutral-300">
{t("email")}
<input
className="mt-1 w-full rounded-xl border border-ark-line bg-black px-3 py-2"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<label className="block text-sm text-neutral-300">
{t("password")}
<input
type="password"
className="mt-1 w-full rounded-xl border border-ark-line bg-black px-3 py-2"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
{err ? <div className="text-sm text-red-300">{err}</div> : null}
<button
type="submit"
className="w-full rounded-xl bg-ark-gold py-3 font-semibold text-black"
>
{t("login")}
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,405 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import {
getJSON,
getJSONAuth,
postJSON,
putJSON,
uploadFile,
type Category,
} from "../../api";
import { getToken } from "../../admin/token";
import { useAdminT } from "../../admin/useAdminT";
import { resourceTypeDisplay } from "../../resourceTypeLabels";
import { adminUiPrefix } from "../../adminPaths";
import { useAdminRouterMode } from "../../adminRouterMode";
const types = [
"image",
"video",
"ppt",
"pdf",
"text",
"link",
"archive",
] as const;
export function AdminResourceForm() {
const { id } = useParams();
const isNew = !id || id === "new";
const t = useAdminT();
const mode = useAdminRouterMode();
const token = getToken();
const nav = useNavigate();
const [cats, setCats] = useState<Category[]>([]);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [rtype, setRtype] = useState<string>("image");
const [language, setLanguage] = useState("zh-TW");
const [categoryId, setCategoryId] = useState(1);
const [coverImage, setCoverImage] = useState("");
const [fileUrl, setFileUrl] = useState("");
const [previewUrl, setPreviewUrl] = useState("");
const [externalUrl, setExternalUrl] = useState("");
const [bodyText, setBodyText] = useState("");
const [badgeLabel, setBadgeLabel] = useState("");
const [isPublic, setIsPublic] = useState(true);
const [isDownloadable, setIsDownloadable] = useState(true);
const [isRecommended, setIsRecommended] = useState(false);
const [sortOrder, setSortOrder] = useState(0);
const [status, setStatus] = useState("published");
const [tags, setTags] = useState("");
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
getJSON<Category[]>("/api/categories?lang=zh-TW")
.then(setCats)
.catch(() => setCats([]));
}, []);
useEffect(() => {
if (isNew || !id) return;
getJSONAuth<any>(`/api/admin/resources/${id}`, token)
.then((r) => {
setTitle(r.title || "");
setDescription(r.description || "");
setRtype(r.type || "image");
setLanguage(r.language || "zh-TW");
setCategoryId(r.categoryId || 1);
setCoverImage(r.coverImage || "");
setFileUrl(r.fileUrl || "");
setPreviewUrl(r.previewUrl || "");
setExternalUrl(r.externalUrl || "");
setBodyText(r.bodyText || "");
setBadgeLabel(r.badgeLabel || "");
setIsPublic(!!r.isPublic);
setIsDownloadable(!!r.isDownloadable);
setIsRecommended(!!r.isRecommended);
setSortOrder(r.sortOrder || 0);
setStatus(r.status || "draft");
setTags((r.tags || []).join(", "));
})
.catch((e) => setErr(String(e)));
}, [id, isNew, token]);
const payload = useMemo(
() => ({
title,
description,
type: rtype,
language,
categoryId,
coverImage,
fileUrl,
previewUrl,
externalUrl,
bodyText,
badgeLabel,
isPublic,
isDownloadable,
isRecommended,
sortOrder,
status,
tags: tags
.split(",")
.map((x) => x.trim())
.filter(Boolean),
}),
[
title,
description,
rtype,
language,
categoryId,
coverImage,
fileUrl,
previewUrl,
externalUrl,
bodyText,
badgeLabel,
isPublic,
isDownloadable,
isRecommended,
sortOrder,
status,
tags,
],
);
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h1 className="text-2xl font-bold">
{isNew ? t("newResource") : t("adminEditResource")}
</h1>
<Link
to={mode === "basename" ? ".." : `${adminUiPrefix}/resources`}
className="text-sm text-neutral-400 hover:text-white"
>
{t("backToList")}
</Link>
</div>
{err ? <div className="text-red-300">{err}</div> : null}
<div className="grid gap-3 md:grid-cols-2">
<Field label={t("title")}>
<input
className="input"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</Field>
<Field label={t("category")}>
<select
className="input"
value={categoryId}
onChange={(e) => setCategoryId(Number(e.target.value))}
>
{cats.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</Field>
<Field label={t("type")}>
<select
className="input"
value={rtype}
onChange={(e) => setRtype(e.target.value)}
>
{types.map((x) => (
<option key={x} value={x}>
{resourceTypeDisplay(t, x)}
</option>
))}
</select>
</Field>
<Field label={t("language")}>
<select
className="input"
value={language}
onChange={(e) => setLanguage(e.target.value)}
>
<option value="zh-TW">{t("lang_zh_TW")}</option>
<option value="zh-CN">{t("lang_zh_CN")}</option>
<option value="en">{t("lang_en")}</option>
</select>
</Field>
<Field label={t("status")}>
<select
className="input"
value={status}
onChange={(e) => setStatus(e.target.value)}
>
<option value="draft">{t("draft")}</option>
<option value="published">{t("published")}</option>
<option value="archived">{t("archived")}</option>
</select>
</Field>
<Field label={t("sortOrderLabel")}>
<input
className="input"
type="number"
value={sortOrder}
onChange={(e) => setSortOrder(Number(e.target.value))}
/>
</Field>
</div>
<Field label={t("description")}>
<textarea
className="input min-h-[90px]"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</Field>
<Field label={t("body")}>
<textarea
className="input min-h-[120px]"
value={bodyText}
onChange={(e) => setBodyText(e.target.value)}
/>
</Field>
<div className="grid gap-3 md:grid-cols-2">
<Field label={t("cover")}>
<div className="flex gap-2">
<input
className="input flex-1"
value={coverImage}
onChange={(e) => setCoverImage(e.target.value)}
/>
<UploadButton
token={token}
accept="image/*"
onUploaded={(u) => {
setCoverImage(u);
}}
/>
</div>
</Field>
<Field label={t("fileUrl")}>
<p className="mb-1 text-xs text-neutral-500">
{rtype === "video" ? t("adminVideoFileHint") : null}
</p>
<div className="flex gap-2">
<input
className="input flex-1"
value={fileUrl}
onChange={(e) => setFileUrl(e.target.value)}
/>
<UploadButton
token={token}
accept={
rtype === "video"
? "video/*,.mp4,.webm,.mov,.mkv,.m4v,.ogv"
: undefined
}
onUploaded={(u, file) => {
setFileUrl(u);
if (file?.type.startsWith("video/")) setRtype("video");
}}
/>
</div>
</Field>
<Field label={t("previewUrlLabel")}>
<div className="flex gap-2">
<input
className="input flex-1"
value={previewUrl}
onChange={(e) => setPreviewUrl(e.target.value)}
/>
<UploadButton
token={token}
accept={
rtype === "video"
? "video/*,.mp4,.webm,.mov,.mkv,.m4v,.ogv"
: undefined
}
onUploaded={(u, file) => {
setPreviewUrl(u);
if (file?.type.startsWith("video/")) setRtype("video");
}}
/>
</div>
</Field>
<Field label={t("externalUrl")}>
<input
className="input"
value={externalUrl}
onChange={(e) => setExternalUrl(e.target.value)}
/>
</Field>
</div>
<Field label={`${t("recommended")} / ${t("badge")}`}>
<div className="flex flex-col gap-2">
<label className="flex items-center gap-2 text-sm text-neutral-300">
<input
type="checkbox"
checked={isRecommended}
onChange={(e) => setIsRecommended(e.target.checked)}
/>
{t("recommended")}
</label>
<input
className="input"
value={badgeLabel}
onChange={(e) => setBadgeLabel(e.target.value)}
/>
</div>
</Field>
<div className="flex flex-wrap gap-4">
<label className="flex items-center gap-2 text-sm text-neutral-300">
<input
type="checkbox"
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
/>
{t("public")}
</label>
<label className="flex items-center gap-2 text-sm text-neutral-300">
<input
type="checkbox"
checked={isDownloadable}
onChange={(e) => setIsDownloadable(e.target.checked)}
/>
{t("downloadable")}
</label>
</div>
<Field label={t("tagsCommaLabel")}>
<input
className="input"
value={tags}
onChange={(e) => setTags(e.target.value)}
/>
</Field>
<button
type="button"
className="rounded-xl bg-ark-gold px-6 py-3 font-semibold text-black"
onClick={async () => {
setErr(null);
try {
if (isNew) {
await postJSON("/api/admin/resources", payload, token);
} else {
await putJSON(`/api/admin/resources/${id}`, payload, token);
}
nav(mode === "basename" ? ".." : `${adminUiPrefix}/resources`);
} catch (e) {
setErr(String(e));
}
}}
>
{t("save")}
</button>
<style>{`
.input { width: 100%; border: 1px solid #1f1f1f; background: #070707; border-radius: 12px; padding: 10px 12px; }
`}</style>
</div>
);
}
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="block text-sm text-neutral-300">
<div className="mb-1">{label}</div>
{children}
</label>
);
}
function UploadButton({
token,
onUploaded,
accept,
}: {
token: string;
onUploaded: (url: string, file?: File) => void;
accept?: string;
}) {
const t = useAdminT();
return (
<label className="inline-flex cursor-pointer items-center rounded-xl border border-ark-line px-3 py-2 text-xs hover:border-ark-gold">
{t("uploadFile")}
<input
type="file"
className="hidden"
accept={accept}
onChange={async (e) => {
const f = e.target.files?.[0];
if (!f) return;
const r = await uploadFile(f, token);
onUploaded(r.url, f);
e.target.value = "";
}}
/>
</label>
);
}

View File

@@ -0,0 +1,146 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
getJSON,
getJSONAuth,
itemsOrEmpty,
type AdminResource,
type Category,
} from "../../api";
import { getToken } from "../../admin/token";
import { resourceTypeDisplay } from "../../resourceTypeLabels";
import { useAdminT } from "../../admin/useAdminT";
import { adminUiPrefix } from "../../adminPaths";
import { useAdminRouterMode } from "../../adminRouterMode";
function statusLabel(t: (k: string) => string, s: string) {
if (s === "published") return t("published");
if (s === "draft") return t("draft");
if (s === "archived") return t("archived");
return s;
}
const pageSize = 25;
export function AdminResources() {
const t = useAdminT();
const mode = useAdminRouterMode();
const token = getToken();
const [items, setItems] = useState<AdminResource[]>([]);
const [catNames, setCatNames] = useState<Record<number, string>>({});
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
useEffect(() => {
getJSON<Category[]>("/api/categories?lang=zh-TW")
.then((cats) => {
const m: Record<number, string> = {};
for (const c of cats) m[c.id] = c.name;
setCatNames(m);
})
.catch(() => setCatNames({}));
}, []);
useEffect(() => {
getJSONAuth<{ items: AdminResource[]; total?: number }>(
`/api/admin/resources?limit=${pageSize}&page=${page}`,
token,
)
.then((r) => {
setItems(itemsOrEmpty(r.items));
setTotal(typeof r.total === "number" ? r.total : 0);
})
.catch(() => setItems([]));
}, [token, page]);
const pages = Math.max(1, Math.ceil(total / pageSize));
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h1 className="text-2xl font-bold">{t("resources")}</h1>
<Link
to={mode === "basename" ? "new" : `${adminUiPrefix}/resources/new`}
className="rounded-xl bg-ark-gold px-4 py-2 text-sm font-semibold text-black"
>
{t("newResource")}
</Link>
</div>
<p className="text-sm text-neutral-500">
{t("listRange")
.replace(
"{{from}}",
String(total === 0 ? 0 : (page - 1) * pageSize + 1),
)
.replace("{{to}}", String(Math.min(page * pageSize, total)))
.replace("{{total}}", String(total))}
</p>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
className="rounded-full border border-ark-line px-4 py-2 text-sm text-neutral-200 outline-none hover:border-ark-gold disabled:opacity-40"
>
{t("paginationPrev")}
</button>
<span className="flex items-center px-2 text-sm text-ark-muted tabular-nums">
{t("pageIndicator")
.replace("{{c}}", String(page))
.replace("{{p}}", String(pages))}
</span>
<button
type="button"
disabled={page >= pages}
onClick={() => setPage((p) => Math.min(pages, p + 1))}
className="rounded-full border border-ark-line px-4 py-2 text-sm text-neutral-200 outline-none hover:border-ark-gold disabled:opacity-40"
>
{t("paginationNext")}
</button>
</div>
<div className="overflow-x-auto rounded-2xl border border-ark-line">
<table className="w-full text-sm">
<thead className="bg-ark-panel text-left text-neutral-400">
<tr>
<th className="p-3">{t("title")}</th>
<th className="p-3">{t("category")}</th>
<th className="p-3">{t("type")}</th>
<th className="p-3">{t("status")}</th>
<th className="p-3">{t("downloads")}</th>
<th className="p-3" />
</tr>
</thead>
<tbody>
{items.map((r) => (
<tr key={r.id} className="border-t border-ark-line">
<td className="p-3 font-medium">{r.title}</td>
<td className="p-3 text-neutral-400">
{catNames[r.categoryId] ?? r.categoryId}
</td>
<td className="p-3 text-neutral-400">
{resourceTypeDisplay(t, r.type)}
</td>
<td className="p-3 text-neutral-400">
{statusLabel(t, r.status)}
</td>
<td className="p-3 text-neutral-400">{r.downloadCount ?? 0}</td>
<td className="p-3 text-right">
<Link
className="text-ark-gold2 hover:underline"
to={
mode === "basename"
? String(r.id)
: `${adminUiPrefix}/resources/${r.id}`
}
>
{t("edit")}
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,49 @@
import { useEffect, useState } from "react";
import { getJSONAuth } from "../../api";
import { getToken } from "../../admin/token";
import { useAdminT } from "../../admin/useAdminT";
type Row = { id: number; query: string; createdAt: string };
export function AdminSearchLogs() {
const t = useAdminT();
const token = getToken();
const [items, setItems] = useState<Row[]>([]);
useEffect(() => {
getJSONAuth<{ items: Row[] }>("/api/admin/search-logs?limit=300", token)
.then((r) => setItems(Array.isArray(r.items) ? r.items : []))
.catch(() => setItems([]));
}, [token]);
return (
<div className="space-y-4">
<h1 className="text-2xl font-bold">{t("adminSearchLogs")}</h1>
<div className="overflow-x-auto rounded-2xl border border-ark-line">
<table className="w-full text-sm">
<thead className="bg-ark-panel text-left text-neutral-400">
<tr>
<th className="p-3">{t("adminSearchId")}</th>
<th className="p-3">{t("adminSearchQuery")}</th>
<th className="p-3">{t("adminSearchTime")}</th>
</tr>
</thead>
<tbody>
{items.map((x) => (
<tr key={x.id} className="border-t border-ark-line">
<td className="p-3 text-neutral-500">{x.id}</td>
<td className="p-3 font-medium">{x.query}</td>
<td className="p-3 text-neutral-400 whitespace-nowrap">
{x.createdAt}
</td>
</tr>
))}
</tbody>
</table>
</div>
{items.length === 0 ? (
<p className="text-neutral-500 text-sm">{t("noResults")}</p>
) : null}
</div>
);
}