feat(project): init
This commit is contained in:
411
components/admin-dashboard.tsx
Normal file
411
components/admin-dashboard.tsx
Normal file
@@ -0,0 +1,411 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import type {
|
||||
AdminSnapshot,
|
||||
AdminUserSummary,
|
||||
SettingsSnapshot,
|
||||
UserRole,
|
||||
} from "@/lib/types";
|
||||
|
||||
interface SettingsResponse {
|
||||
ok?: boolean;
|
||||
error?: string;
|
||||
settings?: SettingsSnapshot;
|
||||
}
|
||||
|
||||
interface UserResponse {
|
||||
ok?: boolean;
|
||||
error?: string;
|
||||
user?: AdminUserSummary;
|
||||
}
|
||||
|
||||
interface SettingsFormState {
|
||||
defaultMonthlyQuota: string;
|
||||
}
|
||||
|
||||
interface CreateUserDraft {
|
||||
username: string;
|
||||
password: string;
|
||||
role: UserRole;
|
||||
monthlyQuota: string;
|
||||
}
|
||||
|
||||
type EditableAdminUser = Omit<AdminUserSummary, "monthlyQuota"> & {
|
||||
monthlyQuota: string | null;
|
||||
passwordDraft: string;
|
||||
};
|
||||
|
||||
function toEditableUser(user: AdminUserSummary): EditableAdminUser {
|
||||
return {
|
||||
...user,
|
||||
monthlyQuota: user.monthlyQuota === null ? null : String(user.monthlyQuota),
|
||||
passwordDraft: "",
|
||||
};
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown, fallbackMessage: string): string {
|
||||
return error instanceof Error ? error.message : fallbackMessage;
|
||||
}
|
||||
|
||||
export default function AdminDashboard({
|
||||
initialSnapshot,
|
||||
}: {
|
||||
initialSnapshot: AdminSnapshot;
|
||||
}) {
|
||||
const [settings, setSettings] = useState<SettingsFormState>({
|
||||
defaultMonthlyQuota: String(initialSnapshot.settings.defaultMonthlyQuota),
|
||||
});
|
||||
const [users, setUsers] = useState<EditableAdminUser[]>(
|
||||
initialSnapshot.users.map(toEditableUser),
|
||||
);
|
||||
const [feedback, setFeedback] = useState("");
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [isSavingSettings, setIsSavingSettings] = useState(false);
|
||||
const [createDraft, setCreateDraft] = useState<CreateUserDraft>({
|
||||
username: "",
|
||||
password: "",
|
||||
role: "user",
|
||||
monthlyQuota: settings.defaultMonthlyQuota,
|
||||
});
|
||||
|
||||
async function saveSettings(): Promise<void> {
|
||||
setFeedback("");
|
||||
setErrorMessage("");
|
||||
setIsSavingSettings(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/settings", {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
defaultMonthlyQuota: settings.defaultMonthlyQuota,
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json()) as SettingsResponse;
|
||||
|
||||
if (!response.ok || payload.ok !== true || !payload.settings) {
|
||||
throw new Error(payload.error || "保存默认额度失败。");
|
||||
}
|
||||
|
||||
setSettings({
|
||||
defaultMonthlyQuota: String(payload.settings.defaultMonthlyQuota),
|
||||
});
|
||||
setFeedback("默认额度已更新。");
|
||||
} catch (error) {
|
||||
setErrorMessage(getErrorMessage(error, "保存默认额度失败。"));
|
||||
} finally {
|
||||
setIsSavingSettings(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function createUser(): Promise<void> {
|
||||
setFeedback("");
|
||||
setErrorMessage("");
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/users", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(createDraft),
|
||||
});
|
||||
const payload = (await response.json()) as UserResponse;
|
||||
|
||||
if (!response.ok || payload.ok !== true || !payload.user) {
|
||||
throw new Error(payload.error || "创建用户失败。");
|
||||
}
|
||||
|
||||
const createdUser = payload.user;
|
||||
|
||||
setUsers((currentUsers) => [
|
||||
...currentUsers,
|
||||
toEditableUser(createdUser),
|
||||
]);
|
||||
setCreateDraft({
|
||||
username: "",
|
||||
password: "",
|
||||
role: "user",
|
||||
monthlyQuota: settings.defaultMonthlyQuota,
|
||||
});
|
||||
setFeedback("用户已创建。");
|
||||
} catch (error) {
|
||||
setErrorMessage(getErrorMessage(error, "创建用户失败。"));
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUser(user: EditableAdminUser): Promise<void> {
|
||||
setFeedback("");
|
||||
setErrorMessage("");
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${user.id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
role: user.role,
|
||||
monthlyQuota: user.role === "admin" ? null : user.monthlyQuota,
|
||||
isActive: user.isActive,
|
||||
password: user.passwordDraft || undefined,
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json()) as UserResponse;
|
||||
|
||||
if (!response.ok || payload.ok !== true || !payload.user) {
|
||||
throw new Error(payload.error || "保存用户失败。");
|
||||
}
|
||||
|
||||
const savedUser = payload.user;
|
||||
|
||||
setUsers((currentUsers) =>
|
||||
currentUsers.map((item) =>
|
||||
item.id === user.id ? toEditableUser(savedUser) : item,
|
||||
),
|
||||
);
|
||||
setFeedback(`已保存 ${savedUser.username}。`);
|
||||
} catch (error) {
|
||||
setErrorMessage(getErrorMessage(error, "保存用户失败。"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-grid">
|
||||
<section className="card settings-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Policy</p>
|
||||
<h3>默认额度设置</h3>
|
||||
</div>
|
||||
<span className="subtle-pill">{initialSnapshot.periodKey}</span>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>默认月额度</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={settings.defaultMonthlyQuota}
|
||||
onChange={(event) =>
|
||||
setSettings((current) => ({
|
||||
...current,
|
||||
defaultMonthlyQuota: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<p className="muted block-copy">
|
||||
没有单独指定额度的普通用户,将继承这里的月额度。
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="primary-button"
|
||||
onClick={saveSettings}
|
||||
disabled={isSavingSettings}
|
||||
>
|
||||
{isSavingSettings ? "保存中..." : "保存默认额度"}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section className="card create-user-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Users</p>
|
||||
<h3>创建用户</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-grid">
|
||||
<label className="field">
|
||||
<span>用户名</span>
|
||||
<input
|
||||
type="text"
|
||||
value={createDraft.username}
|
||||
onChange={(event) =>
|
||||
setCreateDraft((current) => ({
|
||||
...current,
|
||||
username: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>密码</span>
|
||||
<input
|
||||
type="password"
|
||||
value={createDraft.password}
|
||||
onChange={(event) =>
|
||||
setCreateDraft((current) => ({
|
||||
...current,
|
||||
password: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>角色</span>
|
||||
<select
|
||||
value={createDraft.role}
|
||||
onChange={(event) =>
|
||||
setCreateDraft((current) => ({
|
||||
...current,
|
||||
role: event.target.value as UserRole,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="user">普通用户</option>
|
||||
<option value="admin">管理员</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>月额度</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={createDraft.monthlyQuota}
|
||||
onChange={(event) =>
|
||||
setCreateDraft((current) => ({
|
||||
...current,
|
||||
monthlyQuota: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button type="button" className="primary-button" onClick={createUser}>
|
||||
创建用户
|
||||
</button>
|
||||
</section>
|
||||
|
||||
{(feedback || errorMessage) && (
|
||||
<div className={errorMessage ? "error-banner" : "success-banner"}>
|
||||
{errorMessage || feedback}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="card user-table-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Manage</p>
|
||||
<h3>用户管理</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="user-table">
|
||||
<div className="user-table-head">
|
||||
<span>用户</span>
|
||||
<span>角色</span>
|
||||
<span>额度</span>
|
||||
<span>本月已用</span>
|
||||
<span>状态</span>
|
||||
<span>重置密码</span>
|
||||
<span>操作</span>
|
||||
</div>
|
||||
|
||||
{users.map((user) => (
|
||||
<div key={user.id} className="user-table-row">
|
||||
<div className="user-cell user-cell-name">
|
||||
<strong>{user.username}</strong>
|
||||
<small>
|
||||
{user.isUnlimited ? "无限额" : `剩余 ${user.remaining}`}
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={user.role}
|
||||
onChange={(event) =>
|
||||
setUsers((currentUsers) =>
|
||||
currentUsers.map((item) =>
|
||||
item.id === user.id
|
||||
? { ...item, role: event.target.value as UserRole }
|
||||
: item,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="user">普通用户</option>
|
||||
<option value="admin">管理员</option>
|
||||
</select>
|
||||
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
value={user.monthlyQuota ?? ""}
|
||||
placeholder={String(settings.defaultMonthlyQuota)}
|
||||
onChange={(event) =>
|
||||
setUsers((currentUsers) =>
|
||||
currentUsers.map((item) =>
|
||||
item.id === user.id
|
||||
? {
|
||||
...item,
|
||||
monthlyQuota:
|
||||
event.target.value === ""
|
||||
? null
|
||||
: event.target.value,
|
||||
}
|
||||
: item,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<span>{user.usedThisPeriod}</span>
|
||||
|
||||
<select
|
||||
value={String(user.isActive)}
|
||||
onChange={(event) =>
|
||||
setUsers((currentUsers) =>
|
||||
currentUsers.map((item) =>
|
||||
item.id === user.id
|
||||
? {
|
||||
...item,
|
||||
isActive: event.target.value === "true",
|
||||
}
|
||||
: item,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="true">启用</option>
|
||||
<option value="false">禁用</option>
|
||||
</select>
|
||||
|
||||
<input
|
||||
type="password"
|
||||
value={user.passwordDraft}
|
||||
placeholder="留空则不修改"
|
||||
onChange={(event) =>
|
||||
setUsers((currentUsers) =>
|
||||
currentUsers.map((item) =>
|
||||
item.id === user.id
|
||||
? { ...item, passwordDraft: event.target.value }
|
||||
: item,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="ghost-button"
|
||||
onClick={() => saveUser(user)}
|
||||
>
|
||||
保存
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
183
components/history-gallery.tsx
Normal file
183
components/history-gallery.tsx
Normal file
@@ -0,0 +1,183 @@
|
||||
import type { ImageHistoryItem, PublicUser } from "@/lib/types";
|
||||
|
||||
interface HistoryGalleryProps {
|
||||
currentUser: PublicUser;
|
||||
items: ImageHistoryItem[];
|
||||
}
|
||||
|
||||
const dateTimeFormatter = new Intl.DateTimeFormat("zh-CN", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
export default function HistoryGallery({
|
||||
currentUser,
|
||||
items,
|
||||
}: HistoryGalleryProps) {
|
||||
const totalUsers = new Set(items.map((item) => item.userId)).size;
|
||||
const latestItem = items[0] ?? null;
|
||||
|
||||
return (
|
||||
<div className="history-grid">
|
||||
<div className="history-overview-grid">
|
||||
<section className="card history-overview-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Archive</p>
|
||||
<h3>
|
||||
{currentUser.role === "admin" ? "全站生成历史" : "我的生成历史"}
|
||||
</h3>
|
||||
</div>
|
||||
<span className="subtle-pill">{items.length} 张图片</span>
|
||||
</div>
|
||||
|
||||
<div className="history-stat-grid">
|
||||
<article className="history-stat-card">
|
||||
<span>图片总数</span>
|
||||
<strong>{items.length}</strong>
|
||||
</article>
|
||||
<article className="history-stat-card">
|
||||
<span>{currentUser.role === "admin" ? "涉及用户" : "当前身份"}</span>
|
||||
<strong>
|
||||
{currentUser.role === "admin" ? `${totalUsers} 位` : "普通用户"}
|
||||
</strong>
|
||||
</article>
|
||||
<article className="history-stat-card">
|
||||
<span>最近一张</span>
|
||||
<strong>
|
||||
{latestItem
|
||||
? dateTimeFormatter.format(new Date(latestItem.createdAt))
|
||||
: "暂无记录"}
|
||||
</strong>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card history-overview-card history-overview-card-muted">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Access</p>
|
||||
<h3>权限与查看范围</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="muted block-copy">
|
||||
{currentUser.role === "admin"
|
||||
? "管理员可以查看所有用户的历史记录、原始提示词和生成参数,页面会额外标注每张图所属的账号。"
|
||||
: "普通用户只能查看自己的历史记录和图片内容,接口会按当前登录账号做隔离。"}
|
||||
</p>
|
||||
|
||||
<div className="meta-pills history-info-pills">
|
||||
<span>Prompt 可回看</span>
|
||||
<span>按账号隔离</span>
|
||||
<span>原图可下载</span>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<section className="card history-empty-card">
|
||||
<div className="placeholder-orb" />
|
||||
<h4>还没有历史图片</h4>
|
||||
<p>
|
||||
生成成功后的图片会自动保存到服务器,这里会展示图片、提示词和模型参数。
|
||||
</p>
|
||||
</section>
|
||||
) : (
|
||||
<section className="history-gallery-list">
|
||||
{items.map((item) => (
|
||||
<article key={item.id} className="card history-card">
|
||||
<div className="history-card-media">
|
||||
<img src={item.imageUrl} alt={item.fileName} loading="lazy" />
|
||||
</div>
|
||||
|
||||
<div className="history-card-header">
|
||||
<div>
|
||||
<h4>{item.fileName}</h4>
|
||||
<p className="muted">
|
||||
{dateTimeFormatter.format(new Date(item.createdAt))}
|
||||
</p>
|
||||
</div>
|
||||
{currentUser.role === "admin" ? (
|
||||
<span className="subtle-pill history-owner-pill">
|
||||
{item.username}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="meta-pills history-meta-pills">
|
||||
<span>{item.model ?? "未知模型"}</span>
|
||||
<span>{item.size ?? "未知尺寸"}</span>
|
||||
<span>{item.quality ?? "未知质量"}</span>
|
||||
</div>
|
||||
|
||||
<div className="history-meta-list">
|
||||
<div>
|
||||
<span>格式</span>
|
||||
<strong>{formatOutputFormatLabel(item)}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>背景</span>
|
||||
<strong>{item.background ?? "auto"}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>文件大小</span>
|
||||
<strong>{formatFileSize(item.fileSize)}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details className="history-disclosure" open>
|
||||
<summary>查看提示词</summary>
|
||||
<p>{item.prompt}</p>
|
||||
</details>
|
||||
|
||||
{item.revisedPrompt ? (
|
||||
<details className="history-disclosure">
|
||||
<summary>查看模型调整后的提示词</summary>
|
||||
<p>{item.revisedPrompt}</p>
|
||||
</details>
|
||||
) : null}
|
||||
|
||||
<div className="history-actions">
|
||||
<a
|
||||
className="ghost-button"
|
||||
href={item.imageUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
查看原图
|
||||
</a>
|
||||
<a className="primary-button history-download-button" href={item.downloadUrl}>
|
||||
下载图片
|
||||
</a>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatFileSize(fileSize: number): string {
|
||||
if (fileSize < 1024) {
|
||||
return `${fileSize} B`;
|
||||
}
|
||||
|
||||
if (fileSize < 1024 * 1024) {
|
||||
return `${(fileSize / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
|
||||
return `${(fileSize / (1024 * 1024)).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
function formatOutputFormatLabel(item: ImageHistoryItem): string {
|
||||
if (item.outputFormat) {
|
||||
return item.outputFormat.toUpperCase();
|
||||
}
|
||||
|
||||
return item.mimeType.replace(/^image\//, "").toUpperCase();
|
||||
}
|
||||
113
components/login-form.tsx
Normal file
113
components/login-form.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { startTransition, useMemo, useState, type FormEvent } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import type { UserRole } from "@/lib/types";
|
||||
|
||||
interface LoginResponse {
|
||||
ok?: boolean;
|
||||
error?: string;
|
||||
user?: {
|
||||
role: UserRole;
|
||||
};
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown, fallbackMessage: string): string {
|
||||
return error instanceof Error ? error.message : fallbackMessage;
|
||||
}
|
||||
|
||||
export default function LoginForm() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
const notice = useMemo(() => {
|
||||
const reason = searchParams.get("reason");
|
||||
|
||||
if (reason === "inactive") {
|
||||
return "当前账号不可用,请联系管理员。";
|
||||
}
|
||||
|
||||
return "使用管理员或已创建的普通用户登录。";
|
||||
}, [searchParams]);
|
||||
|
||||
async function handleSubmit(
|
||||
event: FormEvent<HTMLFormElement>,
|
||||
): Promise<void> {
|
||||
event.preventDefault();
|
||||
setErrorMessage("");
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json()) as LoginResponse;
|
||||
|
||||
if (!response.ok || payload.ok !== true || !payload.user) {
|
||||
throw new Error(payload.error || "登录失败,请稍后重试。");
|
||||
}
|
||||
|
||||
const currentUser = payload.user;
|
||||
|
||||
startTransition(() => {
|
||||
router.push(currentUser.role === "admin" ? "/admin" : "/studio");
|
||||
router.refresh();
|
||||
});
|
||||
} catch (error) {
|
||||
setErrorMessage(getErrorMessage(error, "登录失败,请稍后重试。"));
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="login-form" onSubmit={handleSubmit}>
|
||||
<div className="login-copy">
|
||||
<p className="eyebrow">Secure Access</p>
|
||||
<h1>登录后才能使用图片生成与后台管理。</h1>
|
||||
<p>{notice}</p>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>用户名</span>
|
||||
<input
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
placeholder="admin"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>密码</span>
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="输入密码"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
{errorMessage ? <div className="error-banner">{errorMessage}</div> : null}
|
||||
|
||||
<button type="submit" className="primary-button" disabled={isPending}>
|
||||
{isPending ? "登录中..." : "登录"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
36
components/logout-button.tsx
Normal file
36
components/logout-button.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useState, startTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function LogoutButton() {
|
||||
const router = useRouter();
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
async function handleLogout(): Promise<void> {
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
await fetch("/api/auth/logout", {
|
||||
method: "POST",
|
||||
});
|
||||
} finally {
|
||||
startTransition(() => {
|
||||
router.push("/login");
|
||||
router.refresh();
|
||||
});
|
||||
setIsPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="ghost-button"
|
||||
onClick={handleLogout}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? "退出中..." : "退出登录"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
107
components/navigation-shell.tsx
Normal file
107
components/navigation-shell.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Link from "next/link";
|
||||
import LogoutButton from "@/components/logout-button";
|
||||
import type { PublicUser } from "@/lib/types";
|
||||
|
||||
interface NavigationShellProps {
|
||||
currentUser: PublicUser;
|
||||
activePath: string;
|
||||
title: string;
|
||||
description: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function NavigationShell({
|
||||
currentUser,
|
||||
activePath,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
}: NavigationShellProps) {
|
||||
const navigationItems = [
|
||||
{
|
||||
href: "/studio",
|
||||
label: "生成中心",
|
||||
description: "输入 Prompt,生成并下载图片",
|
||||
},
|
||||
{
|
||||
href: "/history",
|
||||
label: "历史记录",
|
||||
description:
|
||||
currentUser.role === "admin"
|
||||
? "查看所有用户生成过的图片"
|
||||
: "回看自己曾经生成的图片",
|
||||
},
|
||||
...(currentUser.role === "admin"
|
||||
? [
|
||||
{
|
||||
href: "/admin",
|
||||
label: "管理后台",
|
||||
description: "用户、角色和额度配置",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="dashboard-shell">
|
||||
<aside className="dashboard-sidebar">
|
||||
<div className="brand-lockup">
|
||||
<div className="brand-mark" />
|
||||
<div>
|
||||
<p className="eyebrow">Image Prompt Studio</p>
|
||||
<h1>Apple-like Workspace</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sidebar-card">
|
||||
<span className="sidebar-label">当前用户</span>
|
||||
<strong>{currentUser.username}</strong>
|
||||
<p className="sidebar-copy">
|
||||
{currentUser.role === "admin"
|
||||
? "管理员,无限额"
|
||||
: "普通用户,受额度限制"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<nav className="sidebar-nav">
|
||||
{navigationItems.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={
|
||||
item.href === activePath
|
||||
? "sidebar-link sidebar-link-active"
|
||||
: "sidebar-link"
|
||||
}
|
||||
>
|
||||
<strong>{item.label}</strong>
|
||||
<span>{item.description}</span>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-actions">
|
||||
<LogoutButton />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="dashboard-main">
|
||||
<header className="page-hero">
|
||||
<div>
|
||||
<p className="eyebrow">Workspace</p>
|
||||
<h2>{title}</h2>
|
||||
<p className="hero-copy">{description}</p>
|
||||
</div>
|
||||
<div className="hero-orbs" aria-hidden="true">
|
||||
<div className="hero-orb hero-orb-blue" />
|
||||
<div className="hero-orb hero-orb-pink" />
|
||||
<div className="hero-orb hero-orb-silver" />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="page-content">{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
703
components/studio-client.tsx
Normal file
703
components/studio-client.tsx
Normal file
@@ -0,0 +1,703 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import type {
|
||||
GenerateMeta,
|
||||
GeneratedImage,
|
||||
PublicUser,
|
||||
QuotaSnapshot,
|
||||
} from "@/lib/types";
|
||||
|
||||
const QUICK_PROMPTS = [
|
||||
"一款银白色耳机悬浮在纯白背景中,柔和边缘光,苹果官网产品摄影质感。",
|
||||
"安静的极简客厅,浅木地板,大窗户自然光,室内设计杂志封面风格。",
|
||||
"未来感城市夜景中的电动车,低饱和电影光影,写实概念海报。",
|
||||
];
|
||||
|
||||
const PROCESSING_STAGES = [
|
||||
"验证账号和额度",
|
||||
"发送 Prompt 到 gpt-image-2",
|
||||
"等待模型渲染图像",
|
||||
"整理图片并准备下载",
|
||||
];
|
||||
|
||||
type StudioStatus = "idle" | "pending" | "success" | "error";
|
||||
|
||||
type StudioResult = GeneratedImage & {
|
||||
previewUrl: string;
|
||||
};
|
||||
|
||||
type NotificationPermissionState = NotificationPermission | "unsupported";
|
||||
type ServiceWorkerStatus = "checking" | "ready" | "error";
|
||||
|
||||
interface BeforeInstallPromptEvent extends Event {
|
||||
prompt(): Promise<void>;
|
||||
userChoice: Promise<{
|
||||
outcome: "accepted" | "dismissed";
|
||||
platform: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface GenerateResponse {
|
||||
ok?: boolean;
|
||||
error?: string;
|
||||
images?: GeneratedImage[];
|
||||
meta?: GenerateMeta;
|
||||
quota?: QuotaSnapshot;
|
||||
}
|
||||
|
||||
interface StudioClientProps {
|
||||
currentUser: PublicUser;
|
||||
initialQuota: QuotaSnapshot;
|
||||
}
|
||||
|
||||
interface ProcessingCardProps {
|
||||
status: StudioStatus;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
interface PwaFeedback {
|
||||
tone: "success" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown, fallbackMessage: string): string {
|
||||
return error instanceof Error ? error.message : fallbackMessage;
|
||||
}
|
||||
|
||||
function truncateText(text: string, maxLength: number): string {
|
||||
if (text.length <= maxLength) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return `${text.slice(0, maxLength - 1)}...`;
|
||||
}
|
||||
|
||||
function getIsStandaloneMode(): boolean {
|
||||
if (typeof window === "undefined") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const iosStandalone = Boolean(
|
||||
(window.navigator as Navigator & { standalone?: boolean }).standalone,
|
||||
);
|
||||
|
||||
return window.matchMedia("(display-mode: standalone)").matches || iosStandalone;
|
||||
}
|
||||
|
||||
async function showGenerationNotification({
|
||||
prompt,
|
||||
image,
|
||||
meta,
|
||||
}: {
|
||||
prompt: string;
|
||||
image: GeneratedImage;
|
||||
meta: GenerateMeta | null;
|
||||
}): Promise<void> {
|
||||
if (typeof window === "undefined" || !("Notification" in window)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Notification.permission !== "granted") {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [
|
||||
meta?.model,
|
||||
meta?.size,
|
||||
meta?.durationMs ? `${meta.durationMs} ms` : null,
|
||||
].filter(Boolean);
|
||||
const body = [truncateText(prompt, 42), details.join(" · ")]
|
||||
.filter(Boolean)
|
||||
.join(" | ");
|
||||
const options: NotificationOptions = {
|
||||
body,
|
||||
icon: "/pwa-icon.svg",
|
||||
badge: "/pwa-badge.svg",
|
||||
tag: `generation-${image.id}`,
|
||||
data: {
|
||||
url: "/studio",
|
||||
},
|
||||
};
|
||||
|
||||
if ("serviceWorker" in navigator) {
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
await registration.showNotification("图片生成完成", options);
|
||||
return;
|
||||
}
|
||||
|
||||
const notification = new Notification("图片生成完成", options);
|
||||
notification.onclick = () => {
|
||||
window.focus();
|
||||
window.location.href = "/studio";
|
||||
};
|
||||
}
|
||||
|
||||
export default function StudioClient({
|
||||
currentUser,
|
||||
initialQuota,
|
||||
}: StudioClientProps) {
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [status, setStatus] = useState<StudioStatus>("idle");
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [requestMeta, setRequestMeta] = useState<GenerateMeta | null>(null);
|
||||
const [result, setResult] = useState<StudioResult | null>(null);
|
||||
const [quota, setQuota] = useState(initialQuota);
|
||||
const [startedAt, setStartedAt] = useState(0);
|
||||
const [serviceWorkerStatus, setServiceWorkerStatus] =
|
||||
useState<ServiceWorkerStatus>("checking");
|
||||
const [notificationPermission, setNotificationPermission] =
|
||||
useState<NotificationPermissionState>("default");
|
||||
const [installPromptEvent, setInstallPromptEvent] =
|
||||
useState<BeforeInstallPromptEvent | null>(null);
|
||||
const [isStandalone, setIsStandalone] = useState(false);
|
||||
const [pwaFeedback, setPwaFeedback] = useState<PwaFeedback | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
setNotificationPermission(
|
||||
"Notification" in window ? Notification.permission : "unsupported",
|
||||
);
|
||||
setIsStandalone(getIsStandaloneMode());
|
||||
|
||||
const handleBeforeInstallPrompt = (event: Event) => {
|
||||
event.preventDefault();
|
||||
setInstallPromptEvent(event as BeforeInstallPromptEvent);
|
||||
};
|
||||
const handleAppInstalled = () => {
|
||||
setInstallPromptEvent(null);
|
||||
setIsStandalone(true);
|
||||
setPwaFeedback({
|
||||
tone: "success",
|
||||
message: "应用已安装完成,之后可以直接从桌面或启动器打开。",
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("beforeinstallprompt", handleBeforeInstallPrompt);
|
||||
window.addEventListener("appinstalled", handleAppInstalled);
|
||||
|
||||
if (!("serviceWorker" in navigator)) {
|
||||
setServiceWorkerStatus("error");
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(
|
||||
"beforeinstallprompt",
|
||||
handleBeforeInstallPrompt,
|
||||
);
|
||||
window.removeEventListener("appinstalled", handleAppInstalled);
|
||||
};
|
||||
}
|
||||
|
||||
navigator.serviceWorker
|
||||
.register("/sw.js")
|
||||
.then(async () => {
|
||||
await navigator.serviceWorker.ready;
|
||||
setServiceWorkerStatus("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
setServiceWorkerStatus("error");
|
||||
});
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("beforeinstallprompt", handleBeforeInstallPrompt);
|
||||
window.removeEventListener("appinstalled", handleAppInstalled);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const promptStats = useMemo(() => {
|
||||
const cleanPrompt = prompt.trim();
|
||||
|
||||
if (!cleanPrompt) {
|
||||
return "输入一句尽可能具体的画面描述即可。";
|
||||
}
|
||||
|
||||
return `${cleanPrompt.length} 个字符`;
|
||||
}, [prompt]);
|
||||
|
||||
const serviceWorkerLabel = useMemo(() => {
|
||||
if (serviceWorkerStatus === "ready") {
|
||||
return "已就绪";
|
||||
}
|
||||
|
||||
if (serviceWorkerStatus === "error") {
|
||||
return "不可用";
|
||||
}
|
||||
|
||||
return "注册中";
|
||||
}, [serviceWorkerStatus]);
|
||||
|
||||
const notificationLabel = useMemo(() => {
|
||||
if (notificationPermission === "granted") {
|
||||
return "已开启";
|
||||
}
|
||||
|
||||
if (notificationPermission === "denied") {
|
||||
return "已拒绝";
|
||||
}
|
||||
|
||||
if (notificationPermission === "unsupported") {
|
||||
return "浏览器不支持";
|
||||
}
|
||||
|
||||
return "等待授权";
|
||||
}, [notificationPermission]);
|
||||
|
||||
const installLabel = useMemo(() => {
|
||||
if (isStandalone) {
|
||||
return "已作为应用运行";
|
||||
}
|
||||
|
||||
if (installPromptEvent) {
|
||||
return "可直接安装";
|
||||
}
|
||||
|
||||
return "可通过浏览器菜单安装";
|
||||
}, [installPromptEvent, isStandalone]);
|
||||
|
||||
async function handleInstallApp(): Promise<void> {
|
||||
if (isStandalone) {
|
||||
setPwaFeedback({
|
||||
tone: "success",
|
||||
message: "当前已经在 PWA 模式下运行。",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!installPromptEvent) {
|
||||
setPwaFeedback({
|
||||
tone: "error",
|
||||
message:
|
||||
"当前浏览器没有暴露安装弹窗,可以使用地址栏或浏览器菜单中的“安装应用/添加到主屏幕”。",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await installPromptEvent.prompt();
|
||||
const choice = await installPromptEvent.userChoice;
|
||||
|
||||
setPwaFeedback({
|
||||
tone: choice.outcome === "accepted" ? "success" : "error",
|
||||
message:
|
||||
choice.outcome === "accepted"
|
||||
? "浏览器已接受安装请求,应用会加入桌面或启动器。"
|
||||
: "这次没有完成安装,你之后仍然可以再次安装。",
|
||||
});
|
||||
setInstallPromptEvent(null);
|
||||
}
|
||||
|
||||
async function handleEnableNotifications(): Promise<void> {
|
||||
if (!("Notification" in window)) {
|
||||
setNotificationPermission("unsupported");
|
||||
setPwaFeedback({
|
||||
tone: "error",
|
||||
message: "当前浏览器不支持系统通知。",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (Notification.permission === "denied") {
|
||||
setNotificationPermission("denied");
|
||||
setPwaFeedback({
|
||||
tone: "error",
|
||||
message: "通知权限已被拒绝,请在浏览器的站点设置里手动重新开启。",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const permission = await Notification.requestPermission();
|
||||
setNotificationPermission(permission);
|
||||
|
||||
setPwaFeedback({
|
||||
tone: permission === "granted" ? "success" : "error",
|
||||
message:
|
||||
permission === "granted"
|
||||
? "系统通知已开启,图片生成成功后会立刻提醒你。"
|
||||
: "你还没有授予通知权限,本次不会发送系统通知。",
|
||||
});
|
||||
}
|
||||
|
||||
async function handleGenerate(): Promise<void> {
|
||||
const cleanPrompt = prompt.trim();
|
||||
|
||||
if (!cleanPrompt) {
|
||||
setErrorMessage("请输入 Prompt 后再开始生成。");
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("pending");
|
||||
setErrorMessage("");
|
||||
setResult(null);
|
||||
setRequestMeta(null);
|
||||
setStartedAt(Date.now());
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/generate", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
prompt: cleanPrompt,
|
||||
size: "1024x1024",
|
||||
quality: "high",
|
||||
outputFormat: "png",
|
||||
background: "auto",
|
||||
count: 1,
|
||||
moderation: "auto",
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json()) as GenerateResponse;
|
||||
|
||||
if (!response.ok || payload.ok !== true) {
|
||||
throw new Error(payload.error || "生成失败,请稍后重试。");
|
||||
}
|
||||
|
||||
const image = payload.images?.[0];
|
||||
|
||||
if (!image) {
|
||||
throw new Error("没有拿到可用图片。");
|
||||
}
|
||||
|
||||
setResult({
|
||||
...image,
|
||||
previewUrl: `data:${image.mimeType};base64,${image.base64}`,
|
||||
});
|
||||
setRequestMeta(payload.meta ?? null);
|
||||
setQuota(payload.quota ?? initialQuota);
|
||||
setStatus("success");
|
||||
|
||||
try {
|
||||
await showGenerationNotification({
|
||||
prompt: cleanPrompt,
|
||||
image,
|
||||
meta: payload.meta ?? null,
|
||||
});
|
||||
} catch {
|
||||
setPwaFeedback({
|
||||
tone: "error",
|
||||
message: "图片已生成成功,但系统通知发送失败,请刷新后重试。",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
setErrorMessage(getErrorMessage(error, "生成失败,请稍后重试。"));
|
||||
setStatus("error");
|
||||
}
|
||||
}
|
||||
|
||||
function handleDownload() {
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = base64ToBlob(result.base64, result.mimeType);
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement("a");
|
||||
|
||||
anchor.href = blobUrl;
|
||||
anchor.download = result.fileName;
|
||||
anchor.click();
|
||||
|
||||
window.setTimeout(() => URL.revokeObjectURL(blobUrl), 2000);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="studio-grid">
|
||||
<section className="card composer-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Prompt</p>
|
||||
<h3>Describe your image</h3>
|
||||
</div>
|
||||
<span className="subtle-pill">
|
||||
{quota.isUnlimited
|
||||
? "Unlimited"
|
||||
: `剩余 ${quota.remaining} / ${quota.limit}`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="pwa-panel">
|
||||
<div>
|
||||
<p className="section-kicker">PWA</p>
|
||||
<h4>安装应用并接收生成完成通知</h4>
|
||||
<p className="block-copy">
|
||||
允许通知后,当前页面调用 <code>/api/generate</code>{" "}
|
||||
成功返回图片时,会通过 Service Worker 发送系统提醒。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="pwa-status-grid">
|
||||
<div className="pwa-status-card">
|
||||
<span>应用状态</span>
|
||||
<strong>{installLabel}</strong>
|
||||
</div>
|
||||
<div className="pwa-status-card">
|
||||
<span>通知权限</span>
|
||||
<strong>{notificationLabel}</strong>
|
||||
</div>
|
||||
<div className="pwa-status-card">
|
||||
<span>Service Worker</span>
|
||||
<strong>{serviceWorkerLabel}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pwa-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="ghost-button"
|
||||
onClick={handleInstallApp}
|
||||
disabled={isStandalone}
|
||||
>
|
||||
{isStandalone ? "已安装" : "安装应用"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="ghost-button"
|
||||
onClick={handleEnableNotifications}
|
||||
disabled={notificationPermission === "granted"}
|
||||
>
|
||||
{notificationPermission === "granted"
|
||||
? "通知已开启"
|
||||
: "开启通知"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{pwaFeedback ? (
|
||||
<div
|
||||
className={
|
||||
pwaFeedback.tone === "success"
|
||||
? "success-banner"
|
||||
: "error-banner"
|
||||
}
|
||||
>
|
||||
{pwaFeedback.message}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>画面描述</span>
|
||||
<textarea
|
||||
rows={8}
|
||||
value={prompt}
|
||||
onChange={(event) => setPrompt(event.target.value)}
|
||||
placeholder="例如:一台银白色笔记本电脑放在浅灰色桌面上,清晨自然光从左侧落下,极简静物摄影,细节干净,像苹果官网产品页。"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="composer-meta">
|
||||
<span>{promptStats}</span>
|
||||
<span className="muted">
|
||||
{currentUser.role === "admin"
|
||||
? "管理员不会被扣减额度"
|
||||
: `当前计费周期:${quota.periodKey}`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="quick-prompt-list">
|
||||
{QUICK_PROMPTS.map((item) => (
|
||||
<button
|
||||
key={item}
|
||||
type="button"
|
||||
className="ghost-chip"
|
||||
onClick={() => setPrompt(item)}
|
||||
>
|
||||
{item}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{errorMessage ? (
|
||||
<div className="error-banner">{errorMessage}</div>
|
||||
) : null}
|
||||
|
||||
<div className="composer-actions">
|
||||
<div className="meta-pills">
|
||||
<span>Default size 1024</span>
|
||||
<span>PNG</span>
|
||||
<span>High quality</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="primary-button"
|
||||
onClick={handleGenerate}
|
||||
disabled={status === "pending"}
|
||||
>
|
||||
{status === "pending" ? "生成中..." : "生成图片"}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<ProcessingCard key={startedAt} status={status} startedAt={startedAt} />
|
||||
|
||||
<section className="card result-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Result</p>
|
||||
<h3>生成结果</h3>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="ghost-button"
|
||||
disabled={!result}
|
||||
onClick={handleDownload}
|
||||
>
|
||||
下载图片
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="muted block-copy">
|
||||
{requestMeta
|
||||
? `${requestMeta.model} · ${requestMeta.size} · ${requestMeta.outputFormat.toUpperCase()} · ${requestMeta.durationMs} ms`
|
||||
: "生成完成后会在这里显示耗时和图片。"}
|
||||
</p>
|
||||
|
||||
{result ? (
|
||||
<div className="result-stack">
|
||||
<div className="image-frame">
|
||||
<img
|
||||
src={result.previewUrl}
|
||||
alt={result.fileName}
|
||||
width="1024"
|
||||
height="1024"
|
||||
/>
|
||||
</div>
|
||||
{result.revisedPrompt ? (
|
||||
<div className="result-copy">
|
||||
<span className="result-caption">模型调整后的 Prompt</span>
|
||||
<p>{result.revisedPrompt}</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<div className="result-placeholder">
|
||||
<div className="placeholder-orb" />
|
||||
<h4>结果会出现在这里</h4>
|
||||
<p>滚动性能已收敛优化,结果区只在真正返回图片时更新。</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessingCard({ status, startedAt }: ProcessingCardProps) {
|
||||
const [elapsedMs, setElapsedMs] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (status !== "pending") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setElapsedMs(Date.now() - startedAt);
|
||||
}, 220);
|
||||
|
||||
return () => window.clearInterval(timer);
|
||||
}, [status, startedAt]);
|
||||
|
||||
const progressSnapshot = useMemo(() => {
|
||||
if (status === "success") {
|
||||
return {
|
||||
progress: 100,
|
||||
activeIndex: PROCESSING_STAGES.length - 1,
|
||||
lead: "图片已生成完成,可以直接查看和下载。",
|
||||
};
|
||||
}
|
||||
|
||||
if (status === "error") {
|
||||
return {
|
||||
progress: 0,
|
||||
activeIndex: -1,
|
||||
lead: "本次生成未完成,请检查 Prompt 或额度后重试。",
|
||||
};
|
||||
}
|
||||
|
||||
if (status !== "pending") {
|
||||
return {
|
||||
progress: 0,
|
||||
activeIndex: -1,
|
||||
lead: "准备就绪,输入 Prompt 后即可开始生成。",
|
||||
};
|
||||
}
|
||||
|
||||
const progress = Math.min(92, Math.round(elapsedMs / 250));
|
||||
const activeIndex = Math.min(
|
||||
PROCESSING_STAGES.length - 1,
|
||||
Math.floor(elapsedMs / 5000),
|
||||
);
|
||||
|
||||
return {
|
||||
progress,
|
||||
activeIndex,
|
||||
lead: `处理中:${PROCESSING_STAGES[activeIndex]}`,
|
||||
};
|
||||
}, [elapsedMs, status]);
|
||||
|
||||
return (
|
||||
<section className="card processing-card">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="section-kicker">Processing</p>
|
||||
<h3>等待过程</h3>
|
||||
</div>
|
||||
<span className="subtle-pill">
|
||||
{status === "pending"
|
||||
? "进行中"
|
||||
: status === "success"
|
||||
? "完成"
|
||||
: status === "error"
|
||||
? "失败"
|
||||
: "待命"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="block-copy">{progressSnapshot.lead}</p>
|
||||
|
||||
<div className="progress-track" aria-hidden="true">
|
||||
<div
|
||||
className="progress-fill"
|
||||
style={{ width: `${progressSnapshot.progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ol className="processing-list">
|
||||
{PROCESSING_STAGES.map((stage, index) => {
|
||||
const isDone =
|
||||
status === "success" || index < progressSnapshot.activeIndex;
|
||||
const isActive =
|
||||
status === "pending" && index === progressSnapshot.activeIndex;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={stage}
|
||||
className={
|
||||
isDone
|
||||
? "processing-item processing-item-done"
|
||||
: isActive
|
||||
? "processing-item processing-item-active"
|
||||
: "processing-item"
|
||||
}
|
||||
>
|
||||
<div className="step-dot" />
|
||||
<span>{stage}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function base64ToBlob(base64: string, mimeType: string): Blob {
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
|
||||
return new Blob([bytes], { type: mimeType });
|
||||
}
|
||||
Reference in New Issue
Block a user