Add TKMind platform extensions, H5/MindSpace stack, and deployment tooling.
Deploy Documentation / deploy (push) Has been cancelled
Canary / Prepare Version (push) Has been cancelled
Canary / build-cli (push) Has been cancelled
Canary / Upload Install Script (push) Has been cancelled
Canary / bundle-desktop (push) Has been cancelled
Canary / bundle-desktop-intel (push) Has been cancelled
Canary / bundle-desktop-linux (push) Has been cancelled
Canary / bundle-desktop-windows (push) Has been cancelled
Canary / bundle-desktop-windows-cuda (push) Has been cancelled
Canary / Release (push) Has been cancelled
Unused Dependencies / machete (push) Has been cancelled
CI / changes (push) Has been cancelled
CI / Check Rust Code Format (push) Has been cancelled
CI / Build and Test Rust Project (push) Has been cancelled
CI / Build Rust Project on Windows (push) Has been cancelled
CI / Check MSRV (push) Has been cancelled
CI / Lint Rust Code (push) Has been cancelled
CI / Check Generated Schemas are Up-to-Date (push) Has been cancelled
CI / Test and Lint Electron Desktop App (push) Has been cancelled
CI / H5 Plaza Tests and Build (push) Has been cancelled
Live Provider Tests / check-fork (push) Has been cancelled
Live Provider Tests / changes (push) Has been cancelled
Live Provider Tests / Build Binary (push) Has been cancelled
Live Provider Tests / Smoke Tests (push) Has been cancelled
Live Provider Tests / Smoke Tests (Code Execution) (push) Has been cancelled
Live Provider Tests / Compaction Tests (push) Has been cancelled
Live Provider Tests / goose server HTTP integration tests (push) Has been cancelled
Publish Ask AI Bot Docker Image / docker (push) Has been cancelled
Publish Docker Image / docker (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled

Fork goose with custom MCP widgets, platform extensions (aider, git, web, search),
MindSpace H5 backend/frontend, Plaza/Ops UIs, and deploy scripts for tkmind.cn.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
john
2026-06-14 21:30:20 +08:00
parent e5fd568e01
commit 4e21ca937a
359 changed files with 70658 additions and 56 deletions
+41
View File
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+5
View File
@@ -0,0 +1,5 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+36
View File
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+19
View File
@@ -0,0 +1,19 @@
@import "tailwindcss";
:root {
--background: #f5f0e5;
--foreground: #17221d;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
body {
background: var(--background);
color: var(--foreground);
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
}
+41
View File
@@ -0,0 +1,41 @@
import type { Metadata } from 'next';
import { Geist, Geist_Mono } from 'next/font/google';
import { Suspense } from 'react';
import { Footer } from '@/components/layout/Footer';
import { Header } from '@/components/layout/Header';
import { MobileNav } from '@/components/layout/MobileNav';
import { AttributionTracker } from '@/components/seo/AttributionTracker';
import { homeMetadata } from '@/lib/metadata';
import './globals.css';
const geistSans = Geist({
variable: '--font-geist-sans',
subsets: ['latin'],
});
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin'],
});
export const metadata: Metadata = homeMetadata();
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN" className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}>
<body className="min-h-full flex flex-col bg-[#f5f0e5] pb-16 text-[#17221d] md:pb-0">
<Suspense fallback={null}>
<AttributionTracker />
</Suspense>
<Header />
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-6">{children}</main>
<Footer />
<MobileNav />
</body>
</html>
);
}
+6
View File
@@ -0,0 +1,6 @@
import { redirect } from 'next/navigation';
import { plazaPath } from '@/lib/site';
export default function Home() {
redirect(plazaPath());
}
+78
View File
@@ -0,0 +1,78 @@
import { notFound } from 'next/navigation';
import { CategoryNav } from '@/components/feed/CategoryNav';
import { FeedLoadMore } from '@/components/feed/FeedLoadMore';
import { FeedTabs } from '@/components/feed/FeedTabs';
import { fetchCategories, fetchFeed } from '@/lib/api';
import { categoryJsonLd, categoryMetadata } from '@/lib/metadata';
export const dynamic = 'force-dynamic';
export async function generateStaticParams() {
try {
const { categories } = await fetchCategories();
return categories.map((cat) => ({ slug: cat.slug }));
} catch {
return [];
}
}
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
try {
const { categories } = await fetchCategories();
const category = categories.find((item) => item.slug === slug);
if (!category) return { title: '分类未找到' };
return categoryMetadata(category.name, category.slug, category.description);
} catch {
return { title: 'Plaza 分类' };
}
}
export default async function PlazaCategoryPage({
params,
searchParams,
}: {
params: Promise<{ slug: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const { slug } = await params;
const query = await searchParams;
const sort = query.sort === 'new' ? 'new' : 'hot';
const { categories } = await fetchCategories();
const category = categories.find((item) => item.slug === slug);
if (!category) notFound();
const feed = await fetchFeed({ sort, category: slug, limit: 20 });
return (
<div className="space-y-6">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(categoryJsonLd(category.name, category.slug, category.description)),
}}
/>
<div className="space-y-2">
<p className="text-sm font-semibold uppercase tracking-[0.2em] text-[#68716c]"></p>
<h1 className="text-3xl font-bold text-[#17221d]">
{category.icon} {category.name}
</h1>
{category.description ? (
<p className="text-[#4a5751]">{category.description}</p>
) : (
<p className="text-[#4a5751]">{category.post_count ?? 0} </p>
)}
</div>
<CategoryNav categories={categories} activeSlug={slug} />
<FeedTabs sort={sort} categorySlug={slug} />
<FeedLoadMore
initialPosts={feed.posts}
initialCursor={feed.next_cursor}
initialHasMore={feed.has_more}
sort={sort}
categorySlug={slug}
/>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { PostGridSkeleton } from '@/components/feed/PostGridSkeleton';
export default function PlazaLoading() {
return (
<div className="space-y-6">
<div className="space-y-2">
<div className="h-4 w-16 animate-pulse rounded bg-[#ebe4d6]" />
<div className="h-9 w-2/3 animate-pulse rounded bg-[#ebe4d6]" />
<div className="h-4 w-full max-w-xl animate-pulse rounded bg-[#f0ebe0]" />
</div>
<PostGridSkeleton />
</div>
);
}
@@ -0,0 +1,43 @@
import { ImageResponse } from 'next/og';
import { fetchPost, PlazaApiError } from '@/lib/api';
export const runtime = 'edge';
export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';
export default async function PostOpenGraphImage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
let title = 'MindSpace Plaza';
let author = '创作者';
try {
const { post } = await fetchPost(id, { revalidate: false, cache: 'no-store' });
title = post.title;
author = post.author.display_name;
} catch (error) {
if (!(error instanceof PlazaApiError)) throw error;
}
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
padding: '64px',
background: 'linear-gradient(135deg, #2f6f57 0%, #1f4f3f 55%, #17221d 100%)',
color: '#fffdf7',
}}
>
<div style={{ fontSize: 28, opacity: 0.85 }}>MindSpace Plaza</div>
<div style={{ fontSize: 56, fontWeight: 700, lineHeight: 1.15, maxWidth: 980 }}>{title}</div>
<div style={{ fontSize: 28, opacity: 0.9 }}>{author}</div>
</div>
),
{ ...size },
);
}
+79
View File
@@ -0,0 +1,79 @@
import { notFound } from 'next/navigation';
import Link from 'next/link';
import { cookies } from 'next/headers';
import { CommentSection } from '@/components/comment/CommentSection';
import { PostReportButton } from '@/components/post/PostReportButton';
import { PostActions } from '@/components/post/PostActions';
import { PostEmbed } from '@/components/post/PostEmbed';
import { PostMeta } from '@/components/post/PostMeta';
import { mindSpaceSignupUrl } from '@/lib/utm';
import { fetchPost } from '@/lib/api';
import { PlazaApiError } from '@/lib/api';
import { postJsonLd, postMetadata } from '@/lib/metadata';
export const dynamic = 'force-dynamic';
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
try {
const { post } = await fetchPost(id);
return postMetadata(post);
} catch {
return { title: '帖子未找到' };
}
}
export default async function PlazaPostPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const cookieStore = await cookies();
const cookieHeader = cookieStore.toString();
let post;
try {
({ post } = await fetchPost(id, { cookie: cookieHeader }));
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'POST_NOT_FOUND') notFound();
throw error;
}
const embedUrl = post.publication_url;
const jsonLd = postJsonLd(post);
return (
<article className="space-y-6">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<PostMeta post={post} />
{embedUrl ? (
<PostEmbed src={embedUrl} title={post.title} />
) : (
<div className="rounded-2xl border border-dashed border-[#d6d0c3] bg-[#fffdf7] px-6 py-12 text-center text-[#68716c]">
</div>
)}
<PostActions
postId={post.id}
stats={post.stats}
viewerReacted={post.viewer_reacted}
/>
<div className="flex justify-end">
<PostReportButton postId={post.id} />
</div>
<CommentSection postId={post.id} allowComment={post.allow_comment !== false} />
<div className="rounded-2xl border border-[#d6d0c3] bg-[#f0ebe0] px-5 py-4 text-center">
<Link
href={mindSpaceSignupUrl({
medium: 'footer',
campaign: 'post_watermark',
ref: post.id,
})}
className="inline-flex items-center gap-2 text-sm font-semibold text-[#2f6f57]"
>
MindSpace
</Link>
</div>
</article>
);
}
+63
View File
@@ -0,0 +1,63 @@
import { CategoryNav } from '@/components/feed/CategoryNav';
import { FeaturedBanner } from '@/components/feed/FeaturedBanner';
import { FeedLoadMore } from '@/components/feed/FeedLoadMore';
import { FeedTabs } from '@/components/feed/FeedTabs';
import { fetchCategories, fetchFeed } from '@/lib/api';
import { REVALIDATE_HOME } from '@/lib/cache';
import { homeJsonLd, homeMetadata } from '@/lib/metadata';
export const metadata = homeMetadata();
export const dynamic = 'force-dynamic';
export default async function PlazaHomePage({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const params = await searchParams;
const sort = params.sort === 'new' ? 'new' : 'hot';
let categories: Awaited<ReturnType<typeof fetchCategories>>['categories'] = [];
let feed: Awaited<ReturnType<typeof fetchFeed>> = {
posts: [],
featured: { homepage_banner: [], trending: [] },
next_cursor: null,
has_more: false,
};
try {
const [categoryData, feedData] = await Promise.all([
fetchCategories({ revalidate: REVALIDATE_HOME }),
fetchFeed({ sort, limit: 20 }, { revalidate: REVALIDATE_HOME }),
]);
categories = categoryData.categories;
feed = feedData;
} catch {
categories = [];
}
return (
<div className="space-y-6">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(homeJsonLd()) }}
/>
<div className="space-y-2">
<p className="text-sm font-semibold uppercase tracking-[0.2em] text-[#68716c]">Plaza</p>
<h1 className="text-3xl font-bold text-[#17221d]"> AI </h1>
<p className="max-w-2xl text-[#4a5751]">
MindSpace
</p>
</div>
<CategoryNav categories={categories} />
<FeedTabs sort={sort} />
<FeaturedBanner posts={feed.featured.homepage_banner} />
<FeedLoadMore
initialPosts={feed.posts}
initialCursor={feed.next_cursor}
initialHasMore={feed.has_more}
sort={sort}
/>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import type { MetadataRoute } from 'next';
import { siteOrigin } from '@/lib/site';
export default function robots(): MetadataRoute.Robots {
return {
rules: [
{
userAgent: '*',
allow: ['/plaza', '/u/'],
disallow: ['/ops', '/api', '/_next'],
},
],
sitemap: `${siteOrigin()}/sitemap.xml`,
};
}
+42
View File
@@ -0,0 +1,42 @@
import type { MetadataRoute } from 'next';
import { fetchSitemapData } from '@/lib/api';
import { plazaPath, siteOrigin } from '@/lib/site';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const origin = siteOrigin();
const now = new Date();
const staticPages: MetadataRoute.Sitemap = [
{
url: `${origin}${plazaPath()}`,
lastModified: now,
changeFrequency: 'hourly',
priority: 1,
},
];
try {
const data = await fetchSitemapData({ revalidate: 3600 });
const categoryPages = data.categories.map((category) => ({
url: `${origin}${plazaPath(`cat/${category.slug}`)}`,
lastModified: now,
changeFrequency: 'hourly' as const,
priority: 0.8,
}));
const postPages = data.posts.map((post) => ({
url: `${origin}${plazaPath(`p/${post.id}`)}`,
lastModified: new Date(post.updated_at),
changeFrequency: 'weekly' as const,
priority: 0.6,
}));
const userPages = data.users.map((user) => ({
url: `${origin}/u/${user.slug}`,
lastModified: new Date(user.last_post_at),
changeFrequency: 'weekly' as const,
priority: 0.5,
}));
return [...staticPages, ...categoryPages, ...postPages, ...userPages];
} catch {
return staticPages;
}
}
+52
View File
@@ -0,0 +1,52 @@
import { notFound } from 'next/navigation';
import { cookies } from 'next/headers';
import { UserCard } from '@/components/user/UserCard';
import { UserPostGrid } from '@/components/user/UserPostGrid';
import { fetchUserProfile, fetchUserPosts, PlazaApiError } from '@/lib/api';
import { userJsonLd, userMetadata } from '@/lib/metadata';
export const revalidate = 300;
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
try {
const { user } = await fetchUserProfile(slug, { revalidate: 300 });
return userMetadata(user);
} catch {
return { title: '用户未找到' };
}
}
export default async function UserProfilePage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const cookieStore = await cookies();
const cookieHeader = cookieStore.toString();
let profile;
let postsData;
try {
[profile, postsData] = await Promise.all([
fetchUserProfile(slug, { revalidate: 300, cookie: cookieHeader }),
fetchUserPosts(slug, { limit: 20 }, { revalidate: 300 }),
]);
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'user_not_found') notFound();
throw error;
}
return (
<div className="space-y-6">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(userJsonLd(profile.user)) }}
/>
<UserCard user={profile.user} />
<UserPostGrid
slug={slug}
initialPosts={postsData.posts}
initialCursor={postsData.next_cursor}
initialHasMore={postsData.has_more}
/>
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
'use client';
import { mindSpaceSignupUrl } from '@/lib/utm';
type LoginPromptProps = {
open: boolean;
onClose: () => void;
message?: string;
};
export function LoginPrompt({
open,
onClose,
message = '登录 MindSpace 后即可继续',
}: LoginPromptProps) {
if (!open) return null;
const returnTo = typeof window !== 'undefined' ? window.location.href : undefined;
const loginUrl = mindSpaceSignupUrl({ medium: 'login_prompt', campaign: 'plaza_interaction', returnTo });
return (
<div
className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-4 md:items-center"
role="dialog"
aria-modal="true"
onClick={onClose}
>
<div
className="w-full max-w-md rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] p-6 shadow-xl"
onClick={(event) => event.stopPropagation()}
>
<h3 className="text-lg font-semibold text-[#17221d]"></h3>
<p className="mt-2 text-sm text-[#68716c]">{message}</p>
<div className="mt-5 flex gap-3">
<button
type="button"
onClick={onClose}
className="flex-1 rounded-full border border-[#d6d0c3] px-4 py-2.5 text-sm font-semibold text-[#4a5751]"
>
</button>
<a
href={loginUrl}
className="flex-1 rounded-full bg-[#2f6f57] px-4 py-2.5 text-center text-sm font-semibold text-white"
>
/
</a>
</div>
</div>
</div>
);
}
@@ -0,0 +1,64 @@
'use client';
import { useState } from 'react';
type CommentInputProps = {
placeholder?: string;
submitLabel?: string;
onSubmit: (content: string) => Promise<void>;
onCancel?: () => void;
};
export function CommentInput({
placeholder = '写下你的评论…',
submitLabel = '发布',
onSubmit,
onCancel,
}: CommentInputProps) {
const [content, setContent] = useState('');
const [busy, setBusy] = useState(false);
const handleSubmit = async () => {
const trimmed = content.trim();
if (!trimmed || busy) return;
setBusy(true);
try {
await onSubmit(trimmed);
setContent('');
onCancel?.();
} finally {
setBusy(false);
}
};
return (
<div className="space-y-3">
<textarea
value={content}
onChange={(event) => setContent(event.target.value)}
rows={3}
placeholder={placeholder}
className="w-full resize-none rounded-xl border border-[#d6d0c3] bg-white px-4 py-3 text-sm text-[#17221d] outline-none focus:border-[#2f6f57]"
/>
<div className="flex justify-end gap-2">
{onCancel ? (
<button
type="button"
onClick={onCancel}
className="rounded-full border border-[#d6d0c3] px-4 py-2 text-sm text-[#68716c]"
>
</button>
) : null}
<button
type="button"
disabled={busy || !content.trim()}
onClick={handleSubmit}
className="rounded-full bg-[#2f6f57] px-5 py-2 text-sm font-semibold text-white disabled:opacity-50"
>
{busy ? '发送中…' : submitLabel}
</button>
</div>
</div>
);
}
@@ -0,0 +1,32 @@
'use client';
import type { PlazaComment } from '@/types/plaza';
import { CommentThread } from '@/components/comment/CommentThread';
type CommentListProps = {
postId: string;
comments: PlazaComment[];
onReply: (comment: PlazaComment) => void;
onToggleLike: (comment: PlazaComment) => void;
};
export function CommentList({ postId, comments, onReply, onToggleLike }: CommentListProps) {
if (comments.length === 0) {
return <p className="py-6 text-center text-sm text-[#8a928c]"></p>;
}
return (
<ul className="divide-y divide-[#ebe4d6]">
{comments.map((comment) => (
<li key={comment.id} className="py-4">
<CommentThread
postId={postId}
comment={comment}
onReply={onReply}
onToggleLike={onToggleLike}
/>
</li>
))}
</ul>
);
}
@@ -0,0 +1,155 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import type { PlazaComment } from '@/types/plaza';
import { LoginPrompt } from '@/components/auth/LoginPrompt';
import { CommentInput } from '@/components/comment/CommentInput';
import { CommentList } from '@/components/comment/CommentList';
import {
PlazaApiError,
createComment,
fetchComments,
toggleCommentLike,
} from '@/lib/api';
type CommentSectionProps = {
postId: string;
allowComment?: boolean;
};
export function CommentSection({ postId, allowComment = true }: CommentSectionProps) {
const [comments, setComments] = useState<PlazaComment[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(false);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [replyTo, setReplyTo] = useState<PlazaComment | null>(null);
const [loginOpen, setLoginOpen] = useState(false);
const loadComments = useCallback(
async (nextCursor?: string | null) => {
const data = await fetchComments(postId, { cursor: nextCursor ?? undefined });
if (nextCursor) {
setComments((current) => [...current, ...data.comments]);
} else {
setComments(data.comments);
}
setCursor(data.next_cursor);
setHasMore(data.has_more);
},
[postId],
);
useEffect(() => {
let cancelled = false;
setLoading(true);
loadComments()
.catch(() => {
if (!cancelled) setComments([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [loadComments]);
const handleCreate = async (content: string) => {
try {
await createComment(postId, content, replyTo?.id ?? null);
setReplyTo(null);
await loadComments();
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'unauthorized') {
setLoginOpen(true);
}
throw error;
}
};
const handleToggleLike = async (comment: PlazaComment) => {
try {
const liked = !comment.viewer_liked;
await toggleCommentLike(comment.id, liked);
setComments((current) =>
current.map((item) =>
item.id === comment.id
? {
...item,
viewer_liked: liked,
like_count: Math.max(0, item.like_count + (liked ? 1 : -1)),
}
: item,
),
);
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'unauthorized') {
setLoginOpen(true);
}
}
};
const handleLoadMore = async () => {
if (!cursor || loadingMore) return;
setLoadingMore(true);
try {
await loadComments(cursor);
} finally {
setLoadingMore(false);
}
};
if (!allowComment) {
return (
<div className="rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] px-5 py-4 text-sm text-[#68716c]">
</div>
);
}
return (
<section className="rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] px-5 py-5">
<h2 className="text-lg font-semibold text-[#17221d]"></h2>
<div className="mt-4">
{replyTo ? (
<p className="mb-2 text-sm text-[#68716c]">
@{replyTo.author.display_name}
</p>
) : null}
<CommentInput
placeholder={replyTo ? `回复 @${replyTo.author.display_name}` : '写下你的评论…'}
onSubmit={handleCreate}
onCancel={replyTo ? () => setReplyTo(null) : undefined}
/>
</div>
<div className="mt-6">
{loading ? (
<p className="py-6 text-center text-sm text-[#8a928c]"></p>
) : (
<CommentList
postId={postId}
comments={comments}
onReply={setReplyTo}
onToggleLike={handleToggleLike}
/>
)}
{hasMore ? (
<button
type="button"
disabled={loadingMore}
onClick={handleLoadMore}
className="mt-4 w-full rounded-full border border-[#d6d0c3] py-2.5 text-sm font-semibold text-[#2f6f57]"
>
{loadingMore ? '加载中…' : '加载更多评论'}
</button>
) : null}
</div>
<LoginPrompt
open={loginOpen}
onClose={() => setLoginOpen(false)}
message="登录后即可发表评论"
/>
</section>
);
}
@@ -0,0 +1,108 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import type { PlazaComment } from '@/types/plaza';
import { formatCount, formatRelativeTime } from '@/lib/format';
import { fetchComments } from '@/lib/api';
import { CommentReportButton } from '@/components/post/CommentReportButton';
type CommentThreadProps = {
postId: string;
comment: PlazaComment;
depth?: number;
onReply: (comment: PlazaComment) => void;
onToggleLike: (comment: PlazaComment) => void;
};
export function CommentThread({
postId,
comment,
depth = 0,
onReply,
onToggleLike,
}: CommentThreadProps) {
const [replies, setReplies] = useState<PlazaComment[]>([]);
const [expanded, setExpanded] = useState(false);
const [loadingReplies, setLoadingReplies] = useState(false);
const loadReplies = async () => {
if (loadingReplies || expanded) return;
setLoadingReplies(true);
try {
const data = await fetchComments(postId, { parent_id: comment.id });
setReplies(data.comments);
setExpanded(true);
} finally {
setLoadingReplies(false);
}
};
const canReply = depth === 0;
return (
<div className={depth > 0 ? 'border-l border-[#ebe4d6] pl-4' : undefined}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<Link
href={`/u/${comment.author.slug}`}
className="font-semibold text-[#17221d] hover:text-[#2f6f57]"
>
{comment.author.display_name}
</Link>
<p className="mt-1 text-sm leading-relaxed text-[#4a5751]">{comment.content}</p>
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-[#8a928c]">
<span>{formatRelativeTime(comment.created_at)}</span>
{canReply ? (
<button
type="button"
onClick={() => onReply(comment)}
className="font-semibold text-[#68716c] hover:text-[#2f6f57]"
>
</button>
) : null}
<CommentReportButton commentId={comment.id} />
</div>
{canReply && comment.reply_count > 0 && !expanded ? (
<button
type="button"
onClick={() => void loadReplies()}
className="mt-2 text-xs font-semibold text-[#2f6f57]"
>
{loadingReplies
? '加载回复中…'
: `查看 ${formatCount(comment.reply_count)} 条回复`}
</button>
) : null}
</div>
<button
type="button"
onClick={() => onToggleLike(comment)}
className={`shrink-0 rounded-full px-3 py-1 text-xs font-semibold ${
comment.viewer_liked
? 'bg-[#2f6f57] text-white'
: 'border border-[#d6d0c3] text-[#68716c]'
}`}
>
👍 {formatCount(comment.like_count)}
</button>
</div>
{expanded && replies.length > 0 ? (
<ul className="mt-3 space-y-3">
{replies.map((reply) => (
<li key={reply.id}>
<CommentThread
postId={postId}
comment={reply}
depth={depth + 1}
onReply={onReply}
onToggleLike={onToggleLike}
/>
</li>
))}
</ul>
) : null}
</div>
);
}
+39
View File
@@ -0,0 +1,39 @@
import Link from 'next/link';
import type { PlazaCategory } from '@/types/plaza';
import { plazaPath } from '@/lib/site';
export function CategoryNav({
categories,
activeSlug,
}: {
categories: PlazaCategory[];
activeSlug?: string;
}) {
return (
<div className="flex gap-2 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<Link
href={plazaPath()}
className={`shrink-0 rounded-full px-4 py-2 text-sm font-medium transition ${
!activeSlug
? 'bg-[#2f6f57] text-white'
: 'bg-[#ebe4d6] text-[#4a5751] hover:bg-[#dfd7c8]'
}`}
>
</Link>
{categories.map((cat) => (
<Link
key={cat.id}
href={plazaPath(`cat/${cat.slug}`)}
className={`shrink-0 rounded-full px-4 py-2 text-sm font-medium transition ${
activeSlug === cat.slug
? 'bg-[#2f6f57] text-white'
: 'bg-[#ebe4d6] text-[#4a5751] hover:bg-[#dfd7c8]'
}`}
>
{cat.icon} {cat.name}
</Link>
))}
</div>
);
}
@@ -0,0 +1,26 @@
import Link from 'next/link';
import type { PlazaPost } from '@/types/plaza';
import { plazaPath } from '@/lib/site';
export function FeaturedBanner({ posts }: { posts: PlazaPost[] }) {
if (posts.length === 0) return null;
return (
<section className="space-y-3">
<h2 className="text-lg font-semibold text-[#17221d]"></h2>
<div className="grid gap-3 md:grid-cols-2">
{posts.slice(0, 5).map((post) => (
<Link
key={post.id}
href={plazaPath(`p/${post.id}`)}
className="rounded-2xl border border-[#d6d0c3] bg-gradient-to-r from-[#2f6f57] to-[#1f4f3f] p-5 text-[#fffdf7] shadow-sm transition hover:-translate-y-0.5"
>
<p className="text-sm opacity-80">{post.category.icon} {post.category.name}</p>
<h3 className="mt-2 text-lg font-semibold leading-snug">{post.title}</h3>
<p className="mt-2 text-sm opacity-90">{post.author.display_name}</p>
</Link>
))}
</div>
</section>
);
}
+93
View File
@@ -0,0 +1,93 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import type { PlazaPost } from '@/types/plaza';
import { PostGrid } from '@/components/feed/PostGrid';
async function loadFeedPage(url: string) {
const response = await fetch(url);
const payload = await response.json();
if (!response.ok) throw new Error(payload?.error?.message ?? '加载失败');
return payload.data as {
posts: PlazaPost[];
next_cursor: string | null;
has_more: boolean;
};
}
export function FeedLoadMore({
initialPosts,
initialCursor,
initialHasMore,
sort,
categorySlug,
}: {
initialPosts: PlazaPost[];
initialCursor: string | null;
initialHasMore: boolean;
sort: 'hot' | 'new';
categorySlug?: string;
}) {
const [posts, setPosts] = useState(initialPosts);
const [cursor, setCursor] = useState(initialCursor);
const [hasMore, setHasMore] = useState(initialHasMore);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const sentinelRef = useRef<HTMLDivElement | null>(null);
const loadingRef = useRef(false);
const loadMore = useCallback(async () => {
if (!hasMore || loadingRef.current || !cursor) return;
loadingRef.current = true;
setLoading(true);
setError(null);
try {
const query = new URLSearchParams({ sort, limit: '20', cursor });
if (categorySlug) query.set('category', categorySlug);
const data = await loadFeedPage(`/api/plaza/v1/feed?${query.toString()}`);
setPosts((prev) => [...prev, ...data.posts]);
setCursor(data.next_cursor);
setHasMore(data.has_more);
} catch (err) {
setError(err instanceof Error ? err.message : '加载失败');
} finally {
loadingRef.current = false;
setLoading(false);
}
}, [categorySlug, cursor, hasMore, sort]);
useEffect(() => {
if (!hasMore || !cursor) return;
const node = sentinelRef.current;
if (!node) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
void loadMore();
}
},
{ rootMargin: '240px' },
);
observer.observe(node);
return () => observer.disconnect();
}, [cursor, hasMore, loadMore]);
return (
<div className="space-y-6">
<PostGrid posts={posts} />
{error ? <p className="text-center text-sm text-red-700">{error}</p> : null}
{hasMore ? (
<div ref={sentinelRef} className="flex justify-center pb-8">
<button
type="button"
onClick={() => void loadMore()}
disabled={loading || !cursor}
className="rounded-full border border-[#2f6f57] px-6 py-2.5 text-sm font-semibold text-[#2f6f57] transition hover:bg-[#2f6f57] hover:text-white disabled:opacity-60"
>
{loading ? '加载中…' : '加载更多'}
</button>
</div>
) : null}
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import Link from 'next/link';
import { plazaPath } from '@/lib/site';
export function FeedTabs({
sort,
categorySlug,
}: {
sort: 'hot' | 'new';
categorySlug?: string;
}) {
const base = categorySlug ? plazaPath(`cat/${categorySlug}`) : plazaPath();
return (
<div className="inline-flex rounded-full bg-[#ebe4d6] p-1">
<Link
href={`${base}?sort=hot`}
className={`rounded-full px-4 py-2 text-sm font-semibold transition ${
sort === 'hot' ? 'bg-[#fffdf7] text-[#17221d] shadow-sm' : 'text-[#68716c]'
}`}
>
</Link>
<Link
href={`${base}?sort=new`}
className={`rounded-full px-4 py-2 text-sm font-semibold transition ${
sort === 'new' ? 'bg-[#fffdf7] text-[#17221d] shadow-sm' : 'text-[#68716c]'
}`}
>
</Link>
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
'use client';
import Image from 'next/image';
import Link from 'next/link';
import { useState } from 'react';
import type { PlazaPost } from '@/types/plaza';
import { categoryAccent, formatCount, formatRelativeTime } from '@/lib/format';
import { plazaPath } from '@/lib/site';
export function PostCard({ post, priority = false }: { post: PlazaPost; priority?: boolean }) {
const [coverFailed, setCoverFailed] = useState(false);
const showFallback = !post.cover_url || coverFailed;
const accent = categoryAccent(post.category.slug);
const initial = post.title.trim().charAt(0) || '页';
return (
<Link
href={plazaPath(`p/${post.id}`)}
className="group flex flex-col overflow-hidden rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] shadow-sm transition hover:-translate-y-0.5 hover:shadow-md"
>
<div className="relative aspect-[16/10] overflow-hidden bg-[#ebe4d6]">
{showFallback ? (
<div
className={`flex h-full w-full items-center justify-center bg-gradient-to-br ${accent} text-5xl font-bold text-white/90`}
>
{initial}
</div>
) : (
<Image
src={post.cover_url}
alt={post.title}
fill
priority={priority}
loading={priority ? undefined : 'lazy'}
className="object-cover transition group-hover:scale-[1.02]"
sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
onError={() => setCoverFailed(true)}
/>
)}
</div>
<div className="flex flex-1 flex-col gap-2 p-4">
<h3 className="line-clamp-2 text-base font-semibold leading-snug text-[#17221d]">
{post.title}
</h3>
{post.summary ? (
<p className="line-clamp-2 text-sm leading-relaxed text-[#68716c]">{post.summary}</p>
) : null}
<div className="mt-auto flex items-center justify-between gap-2 pt-2 text-xs text-[#8a928c]">
<span className="truncate">{post.author.display_name}</span>
<span>{formatRelativeTime(post.published_at)}</span>
</div>
<div className="flex gap-3 text-xs text-[#4a5751]">
<span>👍 {formatCount(post.stats.like_count)}</span>
<span>💬 {formatCount(post.stats.comment_count)}</span>
</div>
</div>
</Link>
);
}
+21
View File
@@ -0,0 +1,21 @@
import type { PlazaPost } from '@/types/plaza';
import { PostCard } from '@/components/feed/PostCard';
export function PostGrid({ posts }: { posts: PlazaPost[] }) {
if (posts.length === 0) {
return (
<div className="rounded-2xl border border-dashed border-[#d6d0c3] bg-[#fffdf7] px-6 py-16 text-center">
<p className="text-lg font-semibold text-[#17221d]"></p>
<p className="mt-2 text-sm text-[#68716c]">广</p>
</div>
);
}
return (
<div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
{posts.map((post, index) => (
<PostCard key={post.id} post={post} priority={index < 4} />
))}
</div>
);
}
@@ -0,0 +1,19 @@
export function PostGridSkeleton({ count = 8 }: { count?: number }) {
return (
<div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
{Array.from({ length: count }, (_, index) => (
<div
key={index}
className="overflow-hidden rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] shadow-sm"
>
<div className="aspect-[16/10] animate-pulse bg-[#ebe4d6]" />
<div className="space-y-3 p-4">
<div className="h-4 animate-pulse rounded bg-[#ebe4d6]" />
<div className="h-4 w-2/3 animate-pulse rounded bg-[#ebe4d6]" />
<div className="h-3 w-1/2 animate-pulse rounded bg-[#f0ebe0]" />
</div>
</div>
))}
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import Link from 'next/link';
import { mindSpaceSignupUrl } from '@/lib/utm';
export function Footer({ postId }: { postId?: string }) {
const href = mindSpaceSignupUrl({
medium: 'footer',
campaign: postId ? 'post_watermark' : 'site',
ref: postId,
});
return (
<footer className="mt-auto border-t border-[#d6d0c3] bg-[#f0ebe0]">
<div className="mx-auto flex max-w-6xl flex-col gap-4 px-4 py-8 md:flex-row md:items-center md:justify-between">
<div>
<p className="font-semibold text-[#17221d]">MindSpace Plaza</p>
<p className="mt-1 text-sm text-[#68716c]"> AI </p>
</div>
<Link
href={href}
className="inline-flex items-center gap-2 rounded-full border border-[#2f6f57] px-5 py-2.5 text-sm font-semibold text-[#2f6f57] transition hover:bg-[#2f6f57] hover:text-white"
>
MindSpace
</Link>
</div>
<div className="border-t border-[#d6d0c3] px-4 py-3 text-center text-xs text-[#8a928c]">
© {new Date().getFullYear()} MindSpace
</div>
</footer>
);
}
+62
View File
@@ -0,0 +1,62 @@
import Link from 'next/link';
import { cookies } from 'next/headers';
import { fetchAuthStatus, fetchCategories } from '@/lib/api';
import { mindSpaceOrigin, plazaPath } from '@/lib/site';
export async function Header() {
const cookieStore = await cookies();
const cookieHeader = cookieStore.toString();
let categories: Awaited<ReturnType<typeof fetchCategories>>['categories'] = [];
let authStatus: Awaited<ReturnType<typeof fetchAuthStatus>> = { authenticated: false };
try {
[{ categories }, authStatus] = await Promise.all([
fetchCategories(),
fetchAuthStatus(cookieHeader),
]);
} catch {
categories = [];
}
return (
<header className="sticky top-0 z-40 border-b border-[#d6d0c3] bg-[#fffdf7]/95 backdrop-blur">
<div className="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-3">
<Link href={plazaPath()} className="flex items-center gap-2 font-bold text-[#17221d]">
<span className="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-[#2f6f57] text-sm text-white">
P
</span>
<span>MindSpace Plaza</span>
</Link>
<nav className="hidden items-center gap-1 md:flex">
{categories.slice(0, 6).map((cat) => (
<Link
key={cat.id}
href={plazaPath(`cat/${cat.slug}`)}
className="rounded-full px-3 py-1.5 text-sm text-[#4a5751] transition hover:bg-[#ebe4d6] hover:text-[#17221d]"
>
{cat.icon} {cat.name}
</Link>
))}
</nav>
{authStatus.authenticated && authStatus.user ? (
<Link
href={authStatus.user.slug ? `/u/${authStatus.user.slug}` : mindSpaceOrigin()}
className="flex items-center gap-2 rounded-full border border-[#d6d0c3] px-4 py-2 text-sm font-semibold text-[#17221d] transition hover:bg-[#ebe4d6]"
>
<span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-[#2f6f57] text-xs text-white">
{(authStatus.user.displayName || authStatus.user.username).charAt(0).toUpperCase()}
</span>
{authStatus.user.displayName || authStatus.user.username}
</Link>
) : (
<Link
href={mindSpaceOrigin()}
className="rounded-full bg-[#2f6f57] px-4 py-2 text-sm font-semibold text-white transition hover:bg-[#245742]"
>
/
</Link>
)}
</div>
</header>
);
}
+23
View File
@@ -0,0 +1,23 @@
import Link from 'next/link';
import { mindSpaceOrigin, plazaPath } from '@/lib/site';
export function MobileNav() {
return (
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-[#d6d0c3] bg-[#fffdf7]/95 backdrop-blur md:hidden">
<div className="mx-auto grid max-w-lg grid-cols-4 gap-1 px-2 py-2 text-center text-xs">
<Link href={plazaPath()} className="rounded-xl px-2 py-2 text-[#17221d]">
</Link>
<Link href={plazaPath('cat/work-report')} className="rounded-xl px-2 py-2 text-[#68716c]">
</Link>
<Link href={mindSpaceOrigin()} className="rounded-xl px-2 py-2 text-[#68716c]">
</Link>
<Link href={mindSpaceOrigin()} className="rounded-xl px-2 py-2 text-[#68716c]">
</Link>
</div>
</nav>
);
}
@@ -0,0 +1,84 @@
'use client';
import { useState } from 'react';
import { LoginPrompt } from '@/components/auth/LoginPrompt';
import { PlazaApiError, submitCommentReport } from '@/lib/api';
const REPORT_REASONS = [
{ value: 'spam', label: '垃圾广告' },
{ value: 'violence', label: '暴力内容' },
{ value: 'porn', label: '色情低俗' },
{ value: 'political', label: '政治敏感' },
{ value: 'privacy', label: '侵犯隐私' },
{ value: 'other', label: '其他' },
] as const;
type CommentReportButtonProps = {
commentId: string;
};
export function CommentReportButton({ commentId }: CommentReportButtonProps) {
const [open, setOpen] = useState(false);
const [reason, setReason] = useState<(typeof REPORT_REASONS)[number]['value']>('spam');
const [busy, setBusy] = useState(false);
const [loginOpen, setLoginOpen] = useState(false);
const submit = async () => {
setBusy(true);
try {
await submitCommentReport(commentId, reason);
setOpen(false);
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'unauthorized') {
setLoginOpen(true);
}
} finally {
setBusy(false);
}
};
if (!open) {
return (
<>
<button
type="button"
onClick={() => setOpen(true)}
className="font-semibold text-[#8a928c] hover:text-red-700"
>
</button>
<LoginPrompt open={loginOpen} onClose={() => setLoginOpen(false)} message="登录后可举报" />
</>
);
}
return (
<span className="inline-flex flex-wrap items-center gap-2">
<select
value={reason}
onChange={(event) =>
setReason(event.target.value as (typeof REPORT_REASONS)[number]['value'])
}
className="rounded border border-[#d6d0c3] bg-white px-2 py-0.5 text-xs"
>
{REPORT_REASONS.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
<button
type="button"
disabled={busy}
onClick={() => void submit()}
className="font-semibold text-red-700"
>
</button>
<button type="button" onClick={() => setOpen(false)} className="text-[#68716c]">
</button>
<LoginPrompt open={loginOpen} onClose={() => setLoginOpen(false)} message="登录后可举报" />
</span>
);
}
+142
View File
@@ -0,0 +1,142 @@
'use client';
import { useState } from 'react';
import type { PlazaStats } from '@/types/plaza';
import { LoginPrompt } from '@/components/auth/LoginPrompt';
import { formatCount } from '@/lib/format';
import { PlazaApiError, togglePostReaction } from '@/lib/api';
import { plazaPath, siteOrigin } from '@/lib/site';
type PostActionsProps = {
postId: string;
stats: PlazaStats;
viewerReacted?: { liked: boolean; collected: boolean } | null;
};
export function PostActions({ postId, stats, viewerReacted }: PostActionsProps) {
const [liked, setLiked] = useState(viewerReacted?.liked ?? false);
const [collected, setCollected] = useState(viewerReacted?.collected ?? false);
const [likeCount, setLikeCount] = useState(stats.like_count);
const [collectCount, setCollectCount] = useState(stats.collect_count);
const [shareHint, setShareHint] = useState('');
const [shareOpen, setShareOpen] = useState(false);
const [loginOpen, setLoginOpen] = useState(false);
const [busy, setBusy] = useState<'like' | 'collect' | null>(null);
const handleReaction = async (type: 'like' | 'collect') => {
if (busy) return;
const active = type === 'like' ? liked : collected;
setBusy(type);
try {
await togglePostReaction(postId, type, active);
if (type === 'like') {
setLiked(!active);
setLikeCount((value) => Math.max(0, value + (active ? -1 : 1)));
} else {
setCollected(!active);
setCollectCount((value) => Math.max(0, value + (active ? -1 : 1)));
}
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'unauthorized') {
setLoginOpen(true);
}
} finally {
setBusy(null);
}
};
const shareUrl = `${siteOrigin()}${plazaPath(`p/${postId}`)}`;
const shareImageUrl = `${siteOrigin()}${plazaPath(`p/${postId}/opengraph-image`)}`;
const handleShare = async () => {
try {
await navigator.clipboard.writeText(shareUrl);
setShareHint('链接已复制');
} catch {
setShareHint(shareUrl);
}
try {
await togglePostReaction(postId, 'share', false);
} catch {
// 未登录时忽略 share 计数
}
window.setTimeout(() => setShareHint(''), 2500);
};
const handleCopyImageLink = async () => {
try {
await navigator.clipboard.writeText(shareImageUrl);
setShareHint('分享图链接已复制');
} catch {
setShareHint(shareImageUrl);
}
setShareOpen(false);
window.setTimeout(() => setShareHint(''), 2500);
};
return (
<>
<div className="flex flex-wrap items-center gap-3 rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] px-5 py-4">
<button
type="button"
disabled={busy === 'like'}
onClick={() => handleReaction('like')}
className={`inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold transition ${
liked
? 'bg-[#2f6f57] text-white'
: 'border border-[#d6d0c3] text-[#17221d] hover:border-[#2f6f57] hover:text-[#2f6f57]'
}`}
>
👍 {formatCount(likeCount)}
</button>
<button
type="button"
disabled={busy === 'collect'}
onClick={() => handleReaction('collect')}
className={`inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold transition ${
collected
? 'bg-amber-600 text-white'
: 'border border-[#d6d0c3] text-[#17221d] hover:border-amber-600 hover:text-amber-700'
}`}
>
🔖 {formatCount(collectCount)}
</button>
<button
type="button"
onClick={() => setShareOpen((open) => !open)}
className="inline-flex items-center gap-2 rounded-full border border-[#d6d0c3] px-4 py-2 text-sm font-semibold text-[#17221d] transition hover:border-[#2f6f57] hover:text-[#2f6f57]"
>
📤
</button>
{shareOpen ? (
<div className="flex w-full flex-wrap gap-2 border-t border-[#ebe4d6] pt-3">
<button
type="button"
onClick={() => void handleShare()}
className="rounded-full border border-[#d6d0c3] px-4 py-2 text-sm text-[#17221d]"
>
</button>
<button
type="button"
onClick={() => void handleCopyImageLink()}
className="rounded-full border border-[#d6d0c3] px-4 py-2 text-sm text-[#17221d]"
>
</button>
<a
href={shareImageUrl}
target="_blank"
rel="noopener noreferrer"
className="rounded-full border border-[#d6d0c3] px-4 py-2 text-sm text-[#17221d]"
>
</a>
</div>
) : null}
{shareHint ? <span className="text-sm text-[#2f6f57]">{shareHint}</span> : null}
</div>
<LoginPrompt open={loginOpen} onClose={() => setLoginOpen(false)} />
</>
);
}
+33
View File
@@ -0,0 +1,33 @@
'use client';
import { useEffect, useRef, useState } from 'react';
export function PostEmbed({ src, title }: { src: string; title: string }) {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [height, setHeight] = useState(480);
useEffect(() => {
const onMessage = (event: MessageEvent) => {
if (event.source !== iframeRef.current?.contentWindow) return;
const data = event.data;
if (data && typeof data === 'object' && data.type === 'plaza:embed-height') {
const next = Number(data.height);
if (Number.isFinite(next) && next > 0) setHeight(Math.min(next, 4000));
}
};
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
}, []);
return (
<iframe
ref={iframeRef}
src={src}
title={title}
sandbox="allow-scripts allow-same-origin"
className="w-full rounded-2xl border border-[#d6d0c3] bg-white"
style={{ height }}
loading="lazy"
/>
);
}
+37
View File
@@ -0,0 +1,37 @@
import Link from 'next/link';
import type { PlazaPost } from '@/types/plaza';
import { FollowButton } from '@/components/user/FollowButton';
import { formatCount, formatRelativeTime } from '@/lib/format';
export function PostMeta({ post }: { post: PlazaPost }) {
return (
<div className="flex flex-wrap items-center justify-between gap-4 border-b border-[#d6d0c3] pb-5">
<div>
<p className="text-sm text-[#68716c]">
{post.category.icon} {post.category.name} · {formatRelativeTime(post.published_at)}
</p>
<h1 className="mt-2 text-2xl font-bold leading-tight text-[#17221d] md:text-3xl">
{post.title}
</h1>
{post.summary ? <p className="mt-3 text-[#4a5751]">{post.summary}</p> : null}
</div>
<div className="flex items-center gap-3">
<div>
<Link
href={`/u/${post.author.slug}`}
className="font-semibold text-[#17221d] hover:text-[#2f6f57]"
>
{post.author.display_name}
</Link>
<p className="text-xs text-[#8a928c]">@{post.author.slug}</p>
</div>
<FollowButton slug={post.author.slug} />
</div>
<div className="flex w-full gap-4 text-sm text-[#4a5751] md:w-auto">
<span>👍 {formatCount(post.stats.like_count)}</span>
<span>👁 {formatCount(post.stats.view_count)}</span>
<span>💬 {formatCount(post.stats.comment_count)}</span>
</div>
</div>
);
}
@@ -0,0 +1,108 @@
'use client';
import { useState } from 'react';
import { LoginPrompt } from '@/components/auth/LoginPrompt';
import { PlazaApiError, submitPostReport } from '@/lib/api';
const REPORT_REASONS = [
{ value: 'spam', label: '垃圾广告' },
{ value: 'violence', label: '暴力内容' },
{ value: 'porn', label: '色情低俗' },
{ value: 'political', label: '政治敏感' },
{ value: 'privacy', label: '侵犯隐私' },
{ value: 'other', label: '其他' },
] as const;
type PostReportButtonProps = {
postId: string;
};
export function PostReportButton({ postId }: PostReportButtonProps) {
const [open, setOpen] = useState(false);
const [reason, setReason] = useState<(typeof REPORT_REASONS)[number]['value']>('spam');
const [detail, setDetail] = useState('');
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [loginOpen, setLoginOpen] = useState(false);
const submit = async () => {
setBusy(true);
setMessage('');
try {
await submitPostReport(postId, reason, detail.trim() || undefined);
setMessage('举报已提交,感谢反馈');
setOpen(false);
setDetail('');
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'unauthorized') {
setLoginOpen(true);
} else {
setMessage(error instanceof Error ? error.message : '提交失败');
}
} finally {
setBusy(false);
}
};
return (
<>
<button
type="button"
onClick={() => setOpen((value) => !value)}
className="text-sm font-semibold text-[#8a928c] hover:text-red-700"
>
</button>
{open ? (
<div className="mt-3 rounded-xl border border-[#ebe4d6] bg-[#faf7f0] p-4">
<p className="text-sm font-semibold text-[#17221d]"></p>
<label className="mt-3 block text-xs text-[#68716c]">
<select
value={reason}
onChange={(event) =>
setReason(event.target.value as (typeof REPORT_REASONS)[number]['value'])
}
className="mt-1 w-full rounded-lg border border-[#d6d0c3] bg-white px-3 py-2 text-sm text-[#17221d]"
>
{REPORT_REASONS.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</label>
<label className="mt-3 block text-xs text-[#68716c]">
<textarea
value={detail}
onChange={(event) => setDetail(event.target.value)}
maxLength={500}
rows={3}
className="mt-1 w-full rounded-lg border border-[#d6d0c3] bg-white px-3 py-2 text-sm text-[#17221d]"
/>
</label>
<div className="mt-3 flex gap-2">
<button
type="button"
disabled={busy}
onClick={() => void submit()}
className="rounded-full bg-red-700 px-4 py-2 text-sm font-semibold text-white disabled:opacity-60"
>
{busy ? '提交中…' : '提交举报'}
</button>
<button
type="button"
onClick={() => setOpen(false)}
className="rounded-full border border-[#d6d0c3] px-4 py-2 text-sm text-[#68716c]"
>
</button>
</div>
</div>
) : null}
{message ? <p className="mt-2 text-sm text-[#2f6f57]">{message}</p> : null}
<LoginPrompt open={loginOpen} onClose={() => setLoginOpen(false)} message="登录后可举报" />
</>
);
}
@@ -0,0 +1,26 @@
'use client';
import { useEffect, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import { recordAttributionEvent } from '@/lib/api';
export function AttributionTracker() {
const searchParams = useSearchParams();
const tracked = useRef(false);
useEffect(() => {
if (tracked.current) return;
const utmSource = searchParams.get('utm_source');
if (!utmSource) return;
tracked.current = true;
void recordAttributionEvent({
event_type: 'landing',
utm_source: utmSource,
utm_medium: searchParams.get('utm_medium') ?? '',
utm_campaign: searchParams.get('utm_campaign') ?? '',
ref_id: searchParams.get('ref') ?? '',
}).catch(() => {});
}, [searchParams]);
return null;
}
+54
View File
@@ -0,0 +1,54 @@
'use client';
import { useState } from 'react';
import { LoginPrompt } from '@/components/auth/LoginPrompt';
import { PlazaApiError, toggleFollow } from '@/lib/api';
type FollowButtonProps = {
slug: string;
initialFollowing?: boolean;
className?: string;
};
export function FollowButton({ slug, initialFollowing, className = '' }: FollowButtonProps) {
const [following, setFollowing] = useState(initialFollowing ?? false);
const [loginOpen, setLoginOpen] = useState(false);
const [busy, setBusy] = useState(false);
const handleClick = async () => {
if (busy) return;
setBusy(true);
try {
const result = await toggleFollow(slug, following);
setFollowing(result.following);
} catch (error) {
if (error instanceof PlazaApiError && error.code === 'unauthorized') {
setLoginOpen(true);
}
} finally {
setBusy(false);
}
};
return (
<>
<button
type="button"
disabled={busy}
onClick={handleClick}
className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
following
? 'border-[#d6d0c3] bg-[#f0ebe0] text-[#4a5751]'
: 'border-[#2f6f57] text-[#2f6f57] hover:bg-[#2f6f57] hover:text-white'
} ${className}`}
>
{following ? '已关注' : '关注'}
</button>
<LoginPrompt
open={loginOpen}
onClose={() => setLoginOpen(false)}
message="登录后即可关注创作者"
/>
</>
);
}
+28
View File
@@ -0,0 +1,28 @@
import type { PlazaUserProfile } from '@/types/plaza';
import { FollowButton } from '@/components/user/FollowButton';
import { formatCount } from '@/lib/format';
export function UserCard({ user }: { user: PlazaUserProfile }) {
return (
<div className="rounded-2xl border border-[#d6d0c3] bg-[#fffdf7] px-6 py-6">
<div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
<div className="flex items-start gap-4">
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-[#2f6f57] to-teal-500 text-2xl font-bold text-white">
{user.display_name.trim().charAt(0) || '@'}
</div>
<div>
<h1 className="text-2xl font-bold text-[#17221d]">{user.display_name}</h1>
<p className="text-sm text-[#8a928c]">@{user.slug}</p>
{user.bio ? <p className="mt-3 max-w-xl text-[#4a5751]">{user.bio}</p> : null}
<div className="mt-4 flex flex-wrap gap-4 text-sm text-[#4a5751]">
<span>📝 {formatCount(user.stats.post_count)} </span>
<span>👥 {formatCount(user.stats.follower_count)} </span>
<span> {formatCount(user.stats.total_likes)} </span>
</div>
</div>
</div>
<FollowButton slug={user.slug} initialFollowing={user.viewer_following} />
</div>
</div>
);
}
+55
View File
@@ -0,0 +1,55 @@
'use client';
import { useState } from 'react';
import type { PlazaPost } from '@/types/plaza';
import { PostGrid } from '@/components/feed/PostGrid';
import { fetchUserPosts } from '@/lib/api';
type UserPostGridProps = {
slug: string;
initialPosts: PlazaPost[];
initialCursor: string | null;
initialHasMore: boolean;
};
export function UserPostGrid({
slug,
initialPosts,
initialCursor,
initialHasMore,
}: UserPostGridProps) {
const [posts, setPosts] = useState(initialPosts);
const [cursor, setCursor] = useState(initialCursor);
const [hasMore, setHasMore] = useState(initialHasMore);
const [loading, setLoading] = useState(false);
const loadMore = async () => {
if (!cursor || loading) return;
setLoading(true);
try {
const data = await fetchUserPosts(slug, { cursor });
setPosts((current) => [...current, ...data.posts]);
setCursor(data.next_cursor);
setHasMore(data.has_more);
} finally {
setLoading(false);
}
};
return (
<div className="space-y-4">
<h2 className="text-lg font-semibold text-[#17221d]"></h2>
<PostGrid posts={posts} />
{hasMore ? (
<button
type="button"
disabled={loading}
onClick={loadMore}
className="w-full rounded-full border border-[#d6d0c3] py-2.5 text-sm font-semibold text-[#2f6f57]"
>
{loading ? '加载中…' : '加载更多'}
</button>
) : null}
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;
+300
View File
@@ -0,0 +1,300 @@
import type {
PlazaCategoriesResponse,
PlazaCommentsResponse,
PlazaCreatePostResponse,
PlazaFeedResponse,
PlazaPostResponse,
PlazaSitemapData,
PlazaUserProfileResponse,
} from '@/types/plaza';
import { apiBase } from '@/lib/site';
type FetchOptions = {
revalidate?: number | false;
cache?: RequestCache;
cookie?: string;
};
export type PlazaAuthStatus = {
authenticated: boolean;
user?: { id: string; username: string; slug?: string; displayName: string } | null;
};
class PlazaApiError extends Error {
code: string;
constructor(message: string, code: string) {
super(message);
this.code = code;
}
}
async function plazaFetch<T>(path: string, init?: RequestInit, options?: FetchOptions): Promise<T> {
const base = apiBase();
const url = `${base}${path.startsWith('/') ? path : `/${path}`}`;
const headers = new Headers(init?.headers);
if (options?.cookie) headers.set('cookie', options.cookie);
if (!headers.has('Accept')) headers.set('Accept', 'application/json');
const next =
options?.revalidate === false
? { revalidate: 0 }
: options?.revalidate != null
? { revalidate: options.revalidate }
: undefined;
const response = await fetch(url, {
...init,
headers,
credentials: typeof window !== 'undefined' ? 'include' : init?.credentials,
cache: options?.cache ?? (options?.revalidate === false ? 'no-store' : undefined),
next,
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const code = payload?.error?.code ?? 'request_failed';
const message = payload?.error?.message ?? `请求失败 (${response.status})`;
throw new PlazaApiError(message, code);
}
return payload.data as T;
}
export async function fetchAuthStatus(cookie?: string): Promise<PlazaAuthStatus> {
try {
const base = apiBase();
const url = `${base}/auth/status`;
const headers = new Headers({ Accept: 'application/json' });
if (cookie) headers.set('cookie', cookie);
const response = await fetch(url, {
headers,
credentials: typeof window !== 'undefined' ? 'include' : undefined,
cache: 'no-store',
});
if (!response.ok) return { authenticated: false };
const status = (await response.json()) as PlazaAuthStatus;
return status;
} catch {
return { authenticated: false };
}
}
export async function fetchCategories(options?: FetchOptions) {
return plazaFetch<PlazaCategoriesResponse>('/api/plaza/v1/categories', undefined, {
revalidate: 300,
...options,
});
}
export async function fetchFeed(
params: {
sort?: 'hot' | 'new';
category?: string;
cursor?: string;
limit?: number;
} = {},
options?: FetchOptions,
) {
const query = new URLSearchParams();
if (params.sort) query.set('sort', params.sort);
if (params.category) query.set('category', params.category);
if (params.cursor) query.set('cursor', params.cursor);
if (params.limit) query.set('limit', String(params.limit));
const suffix = query.size ? `?${query.toString()}` : '';
return plazaFetch<PlazaFeedResponse>(`/api/plaza/v1/feed${suffix}`, undefined, {
revalidate: 60,
...options,
});
}
export async function fetchPost(id: string, options?: FetchOptions) {
return plazaFetch<PlazaPostResponse>(`/api/plaza/v1/posts/${encodeURIComponent(id)}`, undefined, {
revalidate: false,
cache: 'no-store',
...options,
});
}
export async function createPlazaPost(
body: {
publication_id: string;
category_id: string;
tags?: string[];
cover_url?: string;
allow_comment?: boolean;
},
cookie: string,
) {
return plazaFetch<PlazaCreatePostResponse>(
'/api/plaza/v1/posts',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
{ revalidate: false, cookie },
);
}
export async function togglePostReaction(
postId: string,
type: 'like' | 'collect' | 'share',
active: boolean,
) {
if (type === 'share') {
return plazaFetch<{ post_id: string; type: string; active: boolean }>(
`/api/plaza/v1/posts/${encodeURIComponent(postId)}/reactions`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'share' }),
},
{ revalidate: false },
);
}
if (active) {
return plazaFetch<{ post_id: string; type: string; active: boolean }>(
`/api/plaza/v1/posts/${encodeURIComponent(postId)}/reactions/${type}`,
{ method: 'DELETE' },
{ revalidate: false },
);
}
return plazaFetch<{ post_id: string; type: string; active: boolean }>(
`/api/plaza/v1/posts/${encodeURIComponent(postId)}/reactions`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type }),
},
{ revalidate: false },
);
}
export async function fetchComments(
postId: string,
params: { parent_id?: string; cursor?: string } = {},
) {
const query = new URLSearchParams();
if (params.parent_id) query.set('parent_id', params.parent_id);
if (params.cursor) query.set('cursor', params.cursor);
const suffix = query.size ? `?${query.toString()}` : '';
return plazaFetch<PlazaCommentsResponse>(
`/api/plaza/v1/posts/${encodeURIComponent(postId)}/comments${suffix}`,
undefined,
{ revalidate: false, cache: 'no-store' },
);
}
export async function createComment(postId: string, content: string, parentId?: string | null) {
return plazaFetch<{ comment: { id: string } }>(
`/api/plaza/v1/posts/${encodeURIComponent(postId)}/comments`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content, parent_id: parentId ?? null }),
},
{ revalidate: false },
);
}
export async function toggleCommentLike(commentId: string, liked: boolean) {
return plazaFetch<{ id: string; liked: boolean }>(
`/api/plaza/v1/comments/${encodeURIComponent(commentId)}/reactions`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ liked }),
},
{ revalidate: false },
);
}
export async function fetchUserProfile(slug: string, options?: FetchOptions) {
return plazaFetch<PlazaUserProfileResponse>(
`/api/plaza/v1/users/${encodeURIComponent(slug)}`,
undefined,
{ revalidate: 300, ...options },
);
}
export async function fetchUserPosts(
slug: string,
params: { cursor?: string; limit?: number } = {},
options?: FetchOptions,
) {
const query = new URLSearchParams();
if (params.cursor) query.set('cursor', params.cursor);
if (params.limit) query.set('limit', String(params.limit));
const suffix = query.size ? `?${query.toString()}` : '';
return plazaFetch<Pick<PlazaFeedResponse, 'posts' | 'next_cursor' | 'has_more'>>(
`/api/plaza/v1/users/${encodeURIComponent(slug)}/posts${suffix}`,
undefined,
{ revalidate: false, cache: 'no-store', ...options },
);
}
export async function toggleFollow(slug: string, following: boolean) {
if (following) {
return plazaFetch<{ following: boolean }>(
`/api/plaza/v1/users/${encodeURIComponent(slug)}/follow`,
{ method: 'DELETE' },
{ revalidate: false },
);
}
return plazaFetch<{ following: boolean }>(
`/api/plaza/v1/users/${encodeURIComponent(slug)}/follow`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' },
{ revalidate: false },
);
}
export async function fetchSitemapData(options?: FetchOptions) {
return plazaFetch<PlazaSitemapData>('/api/plaza/v1/seo/sitemap', undefined, {
revalidate: 3600,
...options,
});
}
export async function recordAttributionEvent(body: {
event_type: 'landing' | 'signup';
utm_source: string;
utm_medium?: string;
utm_campaign?: string;
ref_id?: string;
}) {
return plazaFetch<{ id: string; event_type: string }>(
'/api/plaza/v1/attribution/events',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
{ revalidate: false },
);
}
export async function submitPostReport(postId: string, reason: string, detail?: string) {
return plazaFetch<{ report: { id: string; status: string } }>(
`/api/plaza/v1/posts/${encodeURIComponent(postId)}/reports`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason, detail: detail ?? '' }),
},
{ revalidate: false },
);
}
export async function submitCommentReport(commentId: string, reason: string, detail?: string) {
return plazaFetch<{ report: { id: string; status: string } }>(
`/api/plaza/v1/comments/${encodeURIComponent(commentId)}/reports`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason, detail: detail ?? '' }),
},
{ revalidate: false },
);
}
export { PlazaApiError };
+3
View File
@@ -0,0 +1,3 @@
export const REVALIDATE_HOME = 60;
export const REVALIDATE_CATEGORY = 300;
export const REVALIDATE_USER = 300;
+35
View File
@@ -0,0 +1,35 @@
export function formatCount(value: number): string {
const n = Number(value ?? 0);
if (n >= 100_000) return `${Math.round(n / 10_000)}`;
if (n >= 10_000) return `${(n / 10_000).toFixed(1).replace(/\.0$/, '')}`;
if (n >= 1_000) return `${(n / 1_000).toFixed(1).replace(/\.0$/, '')}k`;
return String(n);
}
export function formatRelativeTime(iso: string): string {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return '';
const diffMs = Date.now() - date.getTime();
const minutes = Math.floor(diffMs / 60_000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes} 分钟前`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} 小时前`;
const days = Math.floor(hours / 24);
if (days < 30) return `${days} 天前`;
return date.toLocaleDateString('zh-CN');
}
export function categoryAccent(slug: string): string {
const palette = [
'from-emerald-700 to-teal-500',
'from-amber-700 to-orange-500',
'from-violet-700 to-purple-500',
'from-sky-700 to-cyan-500',
'from-rose-700 to-pink-500',
'from-lime-700 to-green-500',
];
let hash = 0;
for (let i = 0; i < slug.length; i += 1) hash = (hash + slug.charCodeAt(i) * (i + 1)) % palette.length;
return palette[hash] ?? palette[0];
}
+180
View File
@@ -0,0 +1,180 @@
import type { Metadata } from 'next';
import type { PlazaPost, PlazaUserProfile } from '@/types/plaza';
import { plazaPath, siteOrigin } from '@/lib/site';
const DEFAULT_OG = `${siteOrigin()}/plaza-og.png`;
function postOgImage(post: PlazaPost): string {
if (post.cover_url) return post.cover_url;
return `${siteOrigin()}${plazaPath(`p/${post.id}/opengraph-image`)}`;
}
export function homeMetadata(): Metadata {
const url = `${siteOrigin()}${plazaPath()}`;
return {
title: 'Plaza - 发现 AI 创作的精彩内容',
description: '浏览来自全球用户用 MindSpace 创作的报告、作品和页面',
openGraph: {
type: 'website',
title: 'Plaza - 发现 AI 创作的精彩内容',
description: '浏览来自全球用户用 MindSpace 创作的报告、作品和页面',
url,
siteName: 'MindSpace Plaza',
images: [{ url: DEFAULT_OG, width: 1200, height: 630 }],
},
alternates: { canonical: url },
robots: { index: true, follow: true },
};
}
export function categoryMetadata(name: string, slug: string, description?: string): Metadata {
const url = `${siteOrigin()}${plazaPath(`cat/${slug}`)}`;
return {
title: `${name} - Plaza | MindSpace`,
description: description || `浏览 Plaza「${name}」分类下的 AI 创作内容`,
openGraph: {
type: 'website',
title: `${name} - Plaza`,
description: description || `Plaza「${name}」分类`,
url,
siteName: 'MindSpace Plaza',
images: [{ url: DEFAULT_OG, width: 1200, height: 630 }],
},
alternates: { canonical: url },
robots: { index: true, follow: true },
};
}
export function postMetadata(post: PlazaPost): Metadata {
const url = `${siteOrigin()}${plazaPath(`p/${post.id}`)}`;
const image = postOgImage(post);
const description =
post.summary || `${post.author.display_name} 用 MindSpace 创作的作品`;
return {
title: `${post.title} - Plaza | MindSpace`,
description,
keywords: post.tags.join(', '),
openGraph: {
title: post.title,
description,
url,
siteName: 'MindSpace Plaza',
images: [{ url: image, width: 1200, height: 630, alt: post.title }],
type: 'article',
publishedTime: post.published_at,
authors: [`${siteOrigin()}/u/${post.author.slug}`],
tags: post.tags,
},
twitter: {
card: 'summary_large_image',
title: post.title,
description,
images: [image],
creator: `@${post.author.slug}`,
},
alternates: { canonical: url },
robots: { index: true, follow: true },
};
}
export function postJsonLd(post: PlazaPost) {
return {
'@context': 'https://schema.org',
'@type': 'Article',
headline: post.title,
description: post.summary,
image: post.cover_url || postOgImage(post),
datePublished: post.published_at,
author: {
'@type': 'Person',
name: post.author.display_name,
url: `${siteOrigin()}/u/${post.author.slug}`,
},
publisher: {
'@type': 'Organization',
name: 'MindSpace',
logo: {
'@type': 'ImageObject',
url: `${siteOrigin()}/logo.png`,
},
},
};
}
export function userMetadata(user: PlazaUserProfile): Metadata {
const url = `${siteOrigin()}/u/${user.slug}`;
const description =
user.bio || `${user.display_name} 在 MindSpace Plaza 发布了 ${user.stats.post_count} 篇作品`;
const image = user.avatar_url || DEFAULT_OG;
return {
title: `${user.display_name} (@${user.slug}) - Plaza | MindSpace`,
description,
openGraph: {
type: 'profile',
title: user.display_name,
description,
url,
siteName: 'MindSpace Plaza',
images: user.avatar_url
? [{ url: image, width: 400, height: 400, alt: user.display_name }]
: [{ url: DEFAULT_OG, width: 1200, height: 630 }],
},
twitter: {
card: user.avatar_url ? 'summary' : 'summary_large_image',
title: user.display_name,
description,
images: [image],
},
alternates: { canonical: url },
robots: { index: true, follow: true },
};
}
export function userJsonLd(user: PlazaUserProfile) {
return {
'@context': 'https://schema.org',
'@type': 'ProfilePage',
name: user.display_name,
description: user.bio || `${user.display_name} 的 MindSpace Plaza 主页`,
url: `${siteOrigin()}/u/${user.slug}`,
mainEntity: {
'@type': 'Person',
name: user.display_name,
alternateName: user.slug,
url: `${siteOrigin()}/u/${user.slug}`,
},
};
}
export function homeJsonLd() {
const url = `${siteOrigin()}${plazaPath()}`;
return {
'@context': 'https://schema.org',
'@type': 'WebSite',
name: 'MindSpace Plaza',
url,
description: '浏览来自全球用户用 MindSpace 创作的报告、作品和页面',
publisher: {
'@type': 'Organization',
name: 'MindSpace',
},
};
}
export function categoryJsonLd(name: string, slug: string, description?: string) {
const url = `${siteOrigin()}${plazaPath(`cat/${slug}`)}`;
return {
'@context': 'https://schema.org',
'@type': 'CollectionPage',
name: `${name} - Plaza`,
description: description || `Plaza「${name}」分类下的 AI 创作内容`,
url,
isPartOf: {
'@type': 'WebSite',
name: 'MindSpace Plaza',
url: `${siteOrigin()}${plazaPath()}`,
},
};
}
+24
View File
@@ -0,0 +1,24 @@
export function apiBase(): string {
if (typeof window === 'undefined') {
return (
process.env.PLAZA_API_BASE ??
process.env.NEXT_PUBLIC_API_BASE ??
'http://127.0.0.1:8080'
);
}
return process.env.NEXT_PUBLIC_API_BASE ?? '';
}
export function siteOrigin(): string {
return process.env.NEXT_PUBLIC_SITE_BASE ?? 'https://go.tkmind.cn';
}
export function mindSpaceOrigin(): string {
return process.env.NEXT_PUBLIC_MINDSPACE_BASE ?? siteOrigin();
}
export function plazaPath(path = ''): string {
const base = process.env.NEXT_PUBLIC_PLAZA_BASE ?? '/plaza';
if (!path) return base;
return `${base.replace(/\/$/, '')}/${path.replace(/^\//, '')}`;
}
+25
View File
@@ -0,0 +1,25 @@
export function plazaUtmQuery(params: {
source?: string;
medium: string;
campaign: string;
ref?: string;
}) {
const query = new URLSearchParams();
query.set('utm_source', params.source ?? 'plaza');
query.set('utm_medium', params.medium);
query.set('utm_campaign', params.campaign);
if (params.ref) query.set('ref', params.ref);
return query.toString();
}
export function mindSpaceSignupUrl(params: {
medium: string;
campaign: string;
ref?: string;
returnTo?: string;
}) {
const base = process.env.NEXT_PUBLIC_MINDSPACE_BASE ?? process.env.NEXT_PUBLIC_SITE_BASE ?? 'https://go.tkmind.cn';
const query = plazaUtmQuery(params);
const returnParam = params.returnTo ? `&return_to=${encodeURIComponent(params.returnTo)}` : '';
return `${base.replace(/\/$/, '')}?${query}${returnParam}`;
}
+17
View File
@@ -0,0 +1,17 @@
import type { NextConfig } from 'next';
const apiProxy = process.env.PLAZA_API_PROXY ?? 'http://127.0.0.1:8080';
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: '**' },
{ protocol: 'http', hostname: '**' },
],
},
async rewrites() {
return [{ source: '/api/:path*', destination: `${apiProxy}/api/:path*` }];
},
};
export default nextConfig;
+28
View File
@@ -0,0 +1,28 @@
{
"name": "plaza",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p 3001",
"lint": "eslint",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"next": "16.2.9",
"react": "19.2.4",
"react-dom": "19.2.4",
"swr": "^2.4.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.2.9",
"tailwindcss": "^4",
"typescript": "^5"
}
}
+4155
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+1
View File
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}
+105
View File
@@ -0,0 +1,105 @@
export type PlazaCategory = {
id: string;
name: string;
slug: string;
icon: string;
post_count?: number;
description?: string;
};
export type PlazaAuthor = {
user_id: string;
slug: string;
display_name: string;
avatar_url: string;
};
export type PlazaStats = {
view_count: number;
like_count: number;
collect_count: number;
comment_count: number;
share_count?: number;
};
export type PlazaPost = {
id: string;
title: string;
summary: string;
cover_url: string;
category: Pick<PlazaCategory, 'id' | 'name' | 'slug' | 'icon'>;
tags: string[];
author: PlazaAuthor;
stats: PlazaStats;
viewer_reacted?: { liked: boolean; collected: boolean } | null;
published_at: string;
publication_url?: string;
allow_comment?: boolean;
status?: string;
};
export type PlazaFeedResponse = {
posts: PlazaPost[];
featured: {
homepage_banner: PlazaPost[];
trending: PlazaPost[];
};
next_cursor: string | null;
has_more: boolean;
};
export type PlazaCategoriesResponse = {
categories: PlazaCategory[];
};
export type PlazaPostResponse = {
post: PlazaPost;
};
export type PlazaCreatePostResponse = {
post: { id: string; status: string };
};
export type PlazaComment = {
id: string;
content: string;
author: PlazaAuthor;
like_count: number;
reply_count: number;
viewer_liked?: boolean;
created_at: string;
status: string;
parent_id?: string | null;
};
export type PlazaCommentsResponse = {
comments: PlazaComment[];
next_cursor: string | null;
has_more: boolean;
};
export type PlazaUserProfile = {
user_id: string;
slug: string;
display_name: string;
avatar_url: string;
bio: string;
stats: {
post_count: number;
follower_count: number;
following_count: number;
total_likes: number;
};
viewer_following?: boolean;
};
export type PlazaUserProfileResponse = {
user: PlazaUserProfile;
recent_posts: PlazaPost[];
};
export type PlazaSitemapData = {
categories: Array<{ slug: string; name: string }>;
posts: Array<{ id: string; updated_at: string; published_at: string }>;
users: Array<{ slug: string; last_post_at: string }>;
};