Files
Bedrock/dashboard/components/bedrock.tsx
T

333 lines
17 KiB
TypeScript

"use client";
import {
ArrowDownRight, ArrowLeft, ArrowUpRight, Bell, Bookmark, CalendarDays,
Check, CircleHelp, Compass, Grid2X2, Heart, House, LayoutGrid, Link2,
MapPin, MessageCircle, MoreHorizontal, Play, Search, Square, UserRound, X,
} from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { feedNotes, notes, profile, type Note } from "@/lib/demo-data";
import { cn } from "@/lib/utils";
const channels = ["推荐", "旅行", "游戏", "视频", "职场", "情感"];
const profileTabs = ["笔记", "收藏", "点赞", "浏览记录"] as const;
const ownedNotes = ["workspace", "ai-tools", "voxel-model"];
const accounts = [
{ name: "极客小分队", handle: "@geek_squad_cn", initials: "极" },
{ name: "Low Quality Memes", handle: "@ipostlqmemes", initials: "LM" },
];
const count = new Intl.NumberFormat("zh-CN");
const columns = [
{ value: 1, icon: Square },
{ value: 2, icon: Grid2X2 },
{ value: 3, icon: LayoutGrid },
] as const;
function Picture({ src, alt, className }: { src: string; alt: string; className?: string }) {
// The prototype supplies remote image URLs with no fixed source dimensions.
// eslint-disable-next-line @next/next/no-img-element
return <img src={src} alt={alt} className={className} loading="lazy" />;
}
function Card({
note, liked, onLike, onOpen, pinned,
}: {
note: Note;
liked: boolean;
onLike: () => void;
onOpen: () => void;
pinned?: boolean;
}) {
const likes = note.likes + Number(liked) - Number(note.initiallyLiked);
return (
<article className="note-card">
<button className="note-open group w-full text-left" onClick={onOpen}>
<div className="note-image" style={{ aspectRatio: note.ratio }}>
<Picture src={note.cover} alt={note.alt} className="size-full object-cover transition-transform duration-300 group-hover:scale-[1.04]" />
{note.video && <span className="media-icon" title="视频封面"><Play size={14} fill="currentColor" /></span>}
{pinned && <span className="pin">置顶</span>}
</div>
<h2 className="px-3 pt-3 text-[15px] font-bold">{note.title}</h2>
</button>
<div className="flex items-center justify-between gap-1 px-3 pb-2 pt-1 text-xs text-muted-foreground">
<span className="flex min-w-0 items-center gap-2">
<Picture src={note.avatar} alt="" className="size-5 shrink-0 rounded-full bg-muted object-cover" />
<span className="truncate">{note.author}</span>
</span>
<Button variant="ghost" size="sm" className={cn("gap-1 px-1.5", liked && "text-like")} aria-pressed={liked} aria-label={liked ? "取消点赞" : "点赞"} onClick={onLike}>
<Heart fill={liked ? "currentColor" : "none"} /> {count.format(likes)}
</Button>
</div>
</article>
);
}
type ProfileTab = (typeof profileTabs)[number];
type DialogContent =
| { type: "note"; note: Note }
| { type: "about" }
| { type: "topics" }
| { type: "notifications" }
| { type: "messages" };
export function Bedrock() {
const [view, setView] = useState<"home" | "profile">("home");
const [feed, setFeed] = useState<"all" | "following">("all");
const [channel, setChannel] = useState("推荐");
const [columnCount, setColumnCount] = useState<1 | 2 | 3>();
const [compact, setCompact] = useState(false);
const activeColumns = columnCount ?? (compact ? 2 : 3);
const [query, setQuery] = useState("");
const [tab, setTab] = useState<ProfileTab>("笔记");
const [liked, setLiked] = useState(() => notes.filter((note) => note.initiallyLiked).map((note) => note.id));
const [saved, setSaved] = useState(["stairs"]);
const [history, setHistory] = useState<string[]>([]);
const [follows, setFollows] = useState<string[]>([]);
const [dialogContent, setDialogContent] = useState<DialogContent | null>(null);
const [notice, setNotice] = useState("");
const dialog = useRef<HTMLDialogElement>(null);
const search = useRef<HTMLInputElement>(null);
const menu = useRef<HTMLDetailsElement>(null);
const normalizedQuery = query.trim().toLowerCase();
useEffect(() => {
function openLinkedProfile() {
setView(window.location.hash === "#" + profile.handle ? "profile" : "home");
}
const viewport = window.matchMedia("(max-width: 720px)");
const syncViewport = () => setCompact(viewport.matches);
openLinkedProfile();
syncViewport();
window.addEventListener("hashchange", openLinkedProfile);
viewport.addEventListener("change", syncViewport);
return () => {
window.removeEventListener("hashchange", openLinkedProfile);
viewport.removeEventListener("change", syncViewport);
};
}, []);
function changeView(next: "home" | "profile") {
setView(next);
const url = new URL(window.location.href);
url.hash = next === "profile" ? profile.handle : "";
window.history.replaceState(window.history.state, "", url);
window.scrollTo(0, 0);
}
function browse(next = "推荐") {
setFeed("all");
setChannel(next);
setQuery("");
changeView("home");
}
function toggleInList(set: (update: (current: string[]) => string[]) => void, id: string) {
set((current) => current.includes(id) ? current.filter((entry) => entry !== id) : [...current, id]);
}
function show(content: DialogContent) {
setDialogContent(content);
dialog.current?.showModal();
}
function openNote(note: Note) {
setHistory((current) => [note.id, ...current.filter((id) => id !== note.id)]);
show({ type: "note", note });
}
async function copyProfile() {
menu.current?.removeAttribute("open");
const url = new URL(window.location.pathname, window.location.href);
url.hash = profile.handle;
try {
await navigator.clipboard.writeText(url.href);
setNotice("已复制主页链接");
} catch {
setNotice(url.href);
}
}
const following = follows.includes(profile.handle);
const matches = feedNotes.filter((note) =>
(feed === "all" || note.following || (following && note.author === profile.name)) &&
(channel === "推荐" || note.category === channel) &&
(!normalizedQuery || [note.title, note.author, note.category].some((value) => value.toLowerCase().includes(normalizedQuery))),
);
const profileIds = { 笔记: ownedNotes, 收藏: saved, 点赞: liked, 浏览记录: history }[tab];
const profileNotes = profileIds.flatMap((id) => notes.find((note) => note.id === id) ?? []);
function renderCard(note: Note, pinned = false) {
return <Card key={note.id} note={note} pinned={pinned} liked={liked.includes(note.id)} onLike={() => toggleInList(setLiked, note.id)} onOpen={() => openNote(note)} />;
}
function followButton(id: string, className?: string) {
const active = follows.includes(id);
return <Button variant={active ? "outline" : "default"} size="sm" className={className} aria-pressed={active} onClick={() => toggleInList(setFollows, id)}>{active ? "已关注" : "关注"}</Button>;
}
function closeMenuAndShow(content: DialogContent) {
menu.current?.removeAttribute("open");
show(content);
}
let modal: ReactNode;
if (dialogContent?.type === "note") {
const { note } = dialogContent;
modal = <>
<Picture src={note.cover} alt={note.alt} className="modal-cover" />
<p className="text-sm text-muted-foreground">{note.category} · {note.author}</p>
<h2 id="dialog-title" className="text-2xl font-bold">{note.title}</h2>
{note.video && <p className="text-sm text-muted-foreground">示例笔记仅提供视频封面。</p>}
<div className="flex gap-2">
<Button variant="outline" aria-pressed={liked.includes(note.id)} onClick={() => toggleInList(setLiked, note.id)}>
<Heart fill={liked.includes(note.id) ? "currentColor" : "none"} /> {liked.includes(note.id) ? "已点赞" : "点赞"}
</Button>
<Button variant="outline" aria-pressed={saved.includes(note.id)} onClick={() => toggleInList(setSaved, note.id)}>
<Bookmark fill={saved.includes(note.id) ? "currentColor" : "none"} /> {saved.includes(note.id) ? "已收藏" : "收藏"}
</Button>
</div>
</>;
} else if (dialogContent?.type === "about") {
modal = <>
<h2 id="dialog-title" className="text-2xl font-bold">关于此账号</h2>
<p>{profile.name} · @{profile.handle}</p>
<dl className="account-details">
<div><dt>加入时间</dt><dd>2022 年 4 月</dd></div>
<div><dt>账号属地</dt><dd>中国 · 四川</dd></div>
<div><dt>认证时间</dt><dd>2024 年 3 月</dd></div>
</dl>
</>;
} else if (dialogContent?.type === "topics") {
modal = <>
<h2 id="dialog-title" className="text-2xl font-bold">关注的话题</h2>
<div className="flex flex-wrap gap-2">{["游戏", "视频", "职场"].map((topic) =>
<Button key={topic} variant="outline" onClick={() => { dialog.current?.close(); browse(topic); }}>{topic}</Button>,
)}</div>
</>;
} else if (dialogContent) {
const label = dialogContent.type === "messages" ? "消息" : "通知";
modal = <><h2 id="dialog-title" className="text-2xl font-bold">{label}</h2><p className="text-muted-foreground">暂无{label}</p></>;
}
return (
<div className="site-shell" onClick={() => { if (notice) setNotice(""); }}>
<header className="site-header">
<div className="header-inner">
<button className="brand" onClick={() => browse()} aria-label="Bedrock 首页">
<span className="brand-mark"><ArrowDownRight size={23} strokeWidth={2.7} /></span>
Bedrock<span className="brand-period">.</span>
</button>
<form className="search" role="search" onSubmit={(event) => { event.preventDefault(); changeView("home"); }}>
<Search aria-hidden="true" size={18} />
<input ref={search} type="search" aria-label="搜索笔记" placeholder="搜索笔记、创作者" value={query} onChange={(event) => { setQuery(event.target.value); changeView("home"); }} />
</form>
<Button variant="ghost" size="icon" aria-label="通知" onClick={() => show({ type: "notifications" })}><Bell /></Button>
<button className="header-avatar" aria-label="打开个人主页" onClick={() => changeView("profile")}>
<Picture src={profile.avatar} alt="" className="size-full object-cover" />
</button>
</div>
</header>
<div className="site-grid">
<aside className="rail">
<nav aria-label="主导航" className="rail-nav">
<button className={cn("nav-entry", view === "home" && "nav-active")} aria-current={view === "home" ? "page" : undefined} onClick={() => browse()}><House size={19} /><span>首页</span></button>
<button className="nav-entry" onClick={() => { browse(); search.current?.focus(); }}><Compass size={19} /><span>探索</span></button>
<button className="nav-entry" onClick={() => show({ type: "messages" })}><MessageCircle size={19} /><span>消息</span></button>
<button className={cn("nav-entry", view === "profile" && "nav-active")} aria-current={view === "profile" ? "page" : undefined} onClick={() => changeView("profile")}><UserRound size={19} /><span>个人主页</span></button>
</nav>
</aside>
<main id="main" className="min-w-0">
{view === "home" ? <>
<div className="view-heading">
<h1>发现</h1>
<div className="feed-switch" aria-label="信息流">
<button aria-pressed={feed === "all"} onClick={() => setFeed("all")}>为你推荐</button>
<button aria-pressed={feed === "following"} onClick={() => setFeed("following")}>正在关注</button>
</div>
</div>
<div className="feed-toolbar">
<div className="channels" aria-label="频道">
{channels.map((item) => <button key={item} className="chip" aria-pressed={channel === item} onClick={() => setChannel(item)}>{item}</button>)}
</div>
<div className="column-switch" aria-label="瀑布流列数">
{columns.map(({ value, icon: Icon }) => <Button key={value} variant="ghost" size="icon" aria-pressed={activeColumns === value} aria-label={value + " 列"} onClick={() => setColumnCount(value)}><Icon /></Button>)}
</div>
</div>
{matches.length ? <div className="note-grid" data-columns={activeColumns}>{matches.map((note) => renderCard(note))}</div> :
<p className="empty-state">没有符合条件的笔记。</p>}
</> : <>
<div className="flex items-center gap-2 pb-4">
<Button variant="outline" size="icon" aria-label="返回首页" onClick={() => changeView("home")}><ArrowLeft /></Button>
<span className="text-sm font-semibold">个人主页</span>
</div>
<section className="profile-card">
<Picture src={profile.cover} alt="" className="profile-cover" />
<div className="profile-body">
<div className="profile-actions">
<Picture src={profile.avatar} alt="" className="profile-avatar" />
<div className="ml-auto flex items-center gap-2">
<details className="profile-menu" ref={menu}>
<summary aria-label="更多账号操作"><MoreHorizontal size={19} /></summary>
<div className="menu-panel">
<button onClick={() => closeMenuAndShow({ type: "about" })}><CircleHelp size={16} /> 关于此账号</button>
<button onClick={() => closeMenuAndShow({ type: "topics" })}><Compass size={16} /> 查看话题</button>
<button onClick={() => void copyProfile()}><Link2 size={16} /> 复制主页链接</button>
</div>
</details>
<Button variant="outline" size="icon" aria-label="消息" onClick={() => show({ type: "messages" })}><MessageCircle /></Button>
{followButton(profile.handle)}
</div>
</div>
<h1 className="profile-name">{profile.name}<span className="verified" aria-label="已认证"><Check size={13} strokeWidth={3} /></span></h1>
<p className="text-sm text-muted-foreground">@{profile.handle} · 小红书号 {profile.account}</p>
<p className="profile-bio">Software is eating the world, AI is eating software. 分享 AI 产品拆解、独立开发实验与数字生活灵感。</p>
<div className="profile-meta">
<span><MapPin size={15} /> 成都 · 四川</span>
<button onClick={() => show({ type: "about" })}><CalendarDays size={15} /> 2022 年 4 月加入 <ArrowUpRight size={12} /></button>
</div>
<div className="profile-stats">
<span><b>128</b> 笔记</span><span><b>10</b> 关注</span><span><b>{87 + Number(following)}</b> 粉丝</span><span><b>2,987</b> 获赞与收藏</span>
</div>
</div>
</section>
<nav className="profile-tabs" aria-label="个人主页内容">
{profileTabs.map((item) => <button key={item} aria-pressed={tab === item} onClick={() => setTab(item)}>{item}</button>)}
</nav>
{profileNotes.length ? <div className="note-grid" data-columns={compact ? 2 : 3}>{profileNotes.map((note) => renderCard(note, tab === "笔记" && note.id === "workspace"))}</div> :
<p className="empty-state">{tab === "浏览记录" ? "近期浏览的笔记会显示在这里,仅自己可见。" : "这里暂时没有笔记。"}</p>}
</>}
</main>
<aside className="discovery" aria-label="发现更多">
<section className="discovery-panel">
<h2>热门话题</h2>
<button className="topic" onClick={() => browse("职场")}><span><b>#AICoding2026</b><small>科技 · 热门</small></span><ArrowUpRight size={16} /></button>
<button className="topic" onClick={() => browse("旅行")}><span><b>城市漫游</b><small>旅行 · 热门</small></span><ArrowUpRight size={16} /></button>
</section>
<section className="discovery-panel">
<h2>推荐关注</h2>
{accounts.map(({ name, handle, initials }) => <div className="suggestion" key={handle}>
<span className="suggestion-avatar">{initials}</span>
<span className="min-w-0 flex-1"><b className="block truncate">{name}</b><small className="block truncate text-muted-foreground">{handle}</small></span>
{followButton(handle)}
</div>)}
</section>
</aside>
</div>
<dialog ref={dialog} className="dialog" aria-labelledby="dialog-title" onClick={(event) => { if (event.target === event.currentTarget) dialog.current?.close(); }}>
<div className="dialog-content">
<Button variant="outline" size="icon" aria-label="关闭" className="dialog-close" onClick={() => dialog.current?.close()}><X /></Button>
{modal}
</div>
</dialog>
<p className={cn("notice", !notice && "sr-only")} role="status">{notice}</p>
</div>
);
}