Rename the unified application to dashboard

This commit is contained in:
2026-11-04 23:01:32 +08:00
parent 4ec83f2603
commit 61d80f352f
223 changed files with 42 additions and 42 deletions
@@ -0,0 +1,11 @@
import type { GetServerSideProps } from "next";
import { Feed } from "@/components/Feed";
import { feed } from "@/lib/library";
import { validSection } from "@/lib/model";
export default Feed;
export const getServerSideProps:GetServerSideProps=async({params,query})=>{
const section=String(params?.section||'');const item=validSection(section);if(!item)return {notFound:true};
const tagPath=Array.isArray(params?.taxonomy)?params.taxonomy.join('/'):'';
try{return {props:{initial:await feed({kind:item.kind,path:tagPath,q:String(query.q||'').slice(0,200)}),section,tagPath}};}
catch(e){if(e instanceof Error&&e.message==='Tag not found')return {notFound:true};return {props:{initial:{posts:[],tags:[],contributions:[],nextCursor:null,unavailable:true},section,tagPath}};}
};
+15
View File
@@ -0,0 +1,15 @@
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import type { AppProps } from "next/app";
import "@/styles/globals.css";
import "@/styles/skill-docs.css";
import "@/styles/learning-series.css";
import "@/styles/brand.css";
import "@/studio/styles/globals.css";
export default function App({ Component, pageProps }: AppProps) {
const router = useRouter();
useEffect(() => { const scope = /^\/(?:studio\/)?(?:graphic|infinite_canvas|layouts|template-layout)(?:\/|$)/.test(router.pathname) ? 'canvas' : 'home'; document.documentElement.dataset.theme = `${scope}-${document.documentElement.dataset.mode === 'dark' ? 'dark' : 'light'}`; }, [router.pathname]);
const studio = /^\/(?:studio(?:\/|$)|graphic(?:\/|$)|infinite_canvas(?:\/|$))/.test(router.pathname);
return studio ? <div className="studio-app"><Component {...pageProps} /></div> : <Component {...pageProps} />;
}
+3
View File
@@ -0,0 +1,3 @@
import { Html, Head, Main, NextScript } from 'next/document';
const initializeTheme = String.raw`(function(){try{var mode=localStorage.getItem('endoleap.theme')==='dark'?'dark':'light';var canvas=/^\/(?:studio\/)?(?:graphic|infinite_canvas|layouts|template-layout)(?:\/|$)/.test(location.pathname);document.documentElement.dataset.mode=mode;document.documentElement.dataset.theme=(canvas?'canvas':'home')+'-'+mode;}catch(e){}})();`;
export default function Document() { return <Html lang="zh-CN" data-theme="home-light" data-mode="light" suppressHydrationWarning><Head><link rel="icon" href="/favicon.ico?v=endoleap-1.2" sizes="any"/><link rel="icon" type="image/svg+xml" href="/brand/icon-dark.svg?v=endoleap-1.2"/><link rel="apple-touch-icon" href="/apple-touch-icon.png"/><script dangerouslySetInnerHTML={{__html:initializeTheme}}/></Head><body><Main/><NextScript/></body></Html>; }
+135
View File
@@ -0,0 +1,135 @@
import { Brand } from "@/components/Brand";
import a from "@/styles/account.module.css";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState, type FormEvent } from "react";
import {
ArrowRight,
CheckCircle2,
Eye,
EyeOff,
LogOut,
MailCheck,
} from "lucide-react";
import GuidanceShell, { useGuidanceAccount } from "@/components/GuidanceShell";
import s from "@/styles/guidance.module.css";
type Mode = "login" | "register" | "resend" | "forgot" | "reset" | "verify";
function localNext(value: string | string[] | undefined) {
if (
typeof value !== "string" ||
!value.startsWith("/") ||
value.startsWith("//") ||
/[\\\u0000-\u001f]/.test(value)
)
return "/workspace";
try {
const url = new URL(value, "https://local.invalid");
return url.origin === "https://local.invalid"
? url.pathname + url.search + url.hash
: "/workspace";
} catch {
return "/workspace";
}
}
export default function AccountPage() {
return <GuidanceShell title="登录与注册" standalone><AccountContent /></GuidanceShell>;
}
function AccountContent() {
const account = useGuidanceAccount(), router = useRouter();
const [mode, setMode] = useState<Mode>("login");
const [email, setEmail] = useState(""), [password, setPassword] = useState(""), [confirm, setConfirm] = useState("");
const [showPassword, setShowPassword] = useState(false), [busy, setBusy] = useState(false);
const [token, setToken] = useState("");
const [feedback, setFeedback] = useState<{tone: "success" | "error"; text: string} | null>(null);
useEffect(() => {
const url = new URL(window.location.href);
const reset = url.searchParams.get("reset"), verify = url.searchParams.get("verify");
if (reset || verify) {
setToken(reset || verify || ""); setMode(reset ? "reset" : "verify");
url.searchParams.delete("reset"); url.searchParams.delete("verify");
window.history.replaceState({}, "", url.pathname + url.search + url.hash);
}
}, []);
function switchMode(value: Mode) { setMode(value); setFeedback(null); setPassword(""); setConfirm(""); setShowPassword(false); }
async function action(name: Mode | "logout", body: object = {}) {
if (busy) return;
setBusy(true); setFeedback(null);
try {
const response = await fetch("/api/account/" + name, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body)});
const data = await response.json();
if (!response.ok) throw Error(data.error || "暂时无法完成操作,请重试");
if (name === "verify" || name === "reset") { setToken(""); switchMode("login"); }
if (name === "login" || name === "logout" || name === "reset") { setPassword(""); setConfirm(""); }
setFeedback({tone: "success", text: name === "verify" ? "邮箱已验证,现在可以登录。" : name === "reset" ? "密码已更新,请使用新密码登录。" : name === "login" ? "登录成功,欢迎回到啡跃。" : name === "logout" ? "已退出登录。" : data.message || "若账户符合条件,邮件将发送到你的邮箱。"});
if (["verify", "login", "logout", "reset"].includes(name)) await account.refresh();
if (name === "login") await router.push(localNext(router.query.next));
} catch (error) { setFeedback({tone: "error", text: error instanceof Error ? error.message : "网络异常,请稍后重试"}); }
finally { setBusy(false); }
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (mode === "reset" && password !== confirm) { setFeedback({tone: "error", text: "两次输入的密码不一致。"}); return; }
void action(mode, mode === "reset" ? {token, password} : mode === "verify" ? {token} : {email, password});
}
const user = mode === "reset" || mode === "verify" || mode === "forgot" ? null : account.user;
const title = user ? "你的账户" : ({login: "欢迎回来", register: "创建你的账户", resend: "重发验证邮件", forgot: "找回你的账户", reset: "设置新密码", verify: "确认验证邮箱"})[mode];
const description = user ? "你的知识与创作,随时继续。" : ({login: "使用邮箱与密码登录,继续你的创作。", register: "用邮箱建立你的知识与创作空间。", resend: "仅适用于尚未验证的账户,输入邮箱和原密码。", forgot: "输入注册邮箱,我们会发送重设密码链接。", reset: "由你设置新密码,原有内容会完整保留。", verify: "确认后,即可使用邮箱和密码登录。"})[mode];
const toast = feedback || (account.error ? {tone: "error" as const, text: account.error} : null);
return <div className={a.layout}>
<section className={a.intro} data-theme="home-dark" aria-label="啡跃创作空间">
<Link className={a.brand} href="/" aria-label="啡跃首页"><Brand /></Link>
<div className={a.story}>
<p className={a.eyebrow}>A SPACE FOR YOUR NEXT IDEA</p>
<h1>给想法留白,<br />让灵感有形。</h1>
<p className={a.description}>收集一闪而过的灵感,把有用的知识连接起来。下一件作品,从这里开始。</p>
<div className={a.art} aria-hidden="true">
<div className={a.orbit} />
<div className={a.idea}><span>01 / THE IDEA</span><strong>留住清晨<br />的一束光。</strong><i>灵感片段 · 随手记下</i></div>
<div className={a.work}><span>02 / IN THE MAKING</span><div className={a.artwork} /><strong>光的形状</strong><i>让一个念头,慢慢成形。</i></div>
<span className={a.artCaption}>COLLECT. CONNECT. CREATE.</span>
</div>
</div>
<p className={a.signature}>啡跃 Endoleap <span>为下一次创作,留一个起点。</span></p>
</section>
<section className={a.form} aria-label="邮箱账户">
<div className={a.frame}>
<h2 key={title}>{title}</h2><p className={a.formDescription}>{description}</p>
{account.loading ? <div className={a.loading} aria-busy="true">正在检查账户状态…</div> : user ? <>
<div className={a.accountDetails}><CheckCircle2 size={22} /><strong>{user.email}</strong><span>邮箱已验证</span></div>
<Link className={s.primaryButton} href={localNext(router.query.next)}>继续使用啡跃 <ArrowRight size={15} /></Link>
<button className={a.secondary} type="button" disabled={busy} onClick={() => void action("logout")}><LogOut size={14} />退出登录</button>
</> : <>
<div className={a.tabSlot}>
{(mode === "login" || mode === "register") && <nav className={a.tabs} aria-label="账户操作" data-active={mode}>
<button type="button" aria-pressed={mode === "login"} disabled={busy} onClick={() => switchMode("login")}>登录</button>
<button type="button" aria-pressed={mode === "register"} disabled={busy} onClick={() => switchMode("register")}>创建账户</button>
</nav>}
</div>
<form onSubmit={submit}>
<fieldset className={a.fieldset} disabled={busy}>
<div className={a.fields} key={mode}>
{mode !== "reset" && mode !== "verify" && <div className={a.field}>
<label htmlFor="account-email">邮箱地址</label>
<input id="account-email" className={s.input} type="email" name="email" autoComplete="email" placeholder="you@example.com" required maxLength={254} value={email} onChange={event => setEmail(event.target.value)} />
</div>}
{mode !== "forgot" && mode !== "verify" && <div className={a.field}>
<div className={a.labelRow}><label htmlFor="account-password">{mode === "reset" ? "新密码" : "密码"}</label>{mode === "login" && <button type="button" onClick={() => switchMode("forgot")}>忘记密码?</button>}</div>
<div className={s.passwordField}>
<input id="account-password" className={s.input} type={showPassword ? "text" : "password"} name="password" autoComplete={mode === "register" || mode === "reset" ? "new-password" : "current-password"} placeholder={mode === "register" || mode === "reset" ? "设置至少 12 个字符的密码" : "输入你的密码"} minLength={12} maxLength={256} required value={password} onChange={event => setPassword(event.target.value)} />
<button type="button" aria-label={showPassword ? "隐藏密码" : "显示密码"} onClick={() => setShowPassword(value => !value)}>{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}</button>
</div>
</div>}
{mode === "reset" && <div className={a.field}><label htmlFor="account-confirm">确认新密码</label><input id="account-confirm" className={s.input} type={showPassword ? "text" : "password"} autoComplete="new-password" required minLength={12} maxLength={256} value={confirm} onChange={event => setConfirm(event.target.value)} /></div>}
{mode === "verify" && <div className={a.verifyInfo}><MailCheck size={28} /><p>验证链接有效期为 30 分钟。请确认这是你注册的邮箱。</p></div>}
</div>
<button className={`${s.primaryButton} ${a.submit}`} type="submit">{busy ? "正在处理…" : ({login: "登录", register: "创建账户", resend: "发送验证邮件", forgot: "发送重设链接", reset: "保存新密码", verify: "确认验证邮箱"})[mode]}{!busy && <ArrowRight size={15} />}</button>
</fieldset>
</form>
<div className={a.secondarySlot}>{mode === "login" || mode === "register" ? <button className={a.secondary} type="button" disabled={busy} onClick={() => switchMode("resend")}>没有收到验证邮件?重新发送</button> : <button className={a.secondary} type="button" disabled={busy} onClick={() => switchMode("login")}>返回登录</button>}</div>
<p className={a.footnote}>{mode === "forgot" || mode === "reset" ? "链接仅供本人使用。重设成功后,所有旧会话将退出。" : "首次注册需要验证邮箱;已验证的账户可直接登录。"}</p>
</>}
</div>
</section>
{toast && <div className={a.toast} data-tone={toast.tone} role={toast.tone === "error" ? "alert" : "status"}><span aria-hidden="true">{toast.tone === "error" ? "!" : "✓"}</span><p>{toast.text}</p><button type="button" aria-label={!feedback && account.error ? "重新连接" : "关闭提示"} onClick={() => {setFeedback(null); if (account.error) void account.refresh();}}>×</button></div>}
</div>;
}
@@ -0,0 +1,12 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { GET, POST } from '@/lib/account-handler';
export default async function handler(req: NextApiRequest,res: NextApiResponse) {
res.setHeader('Cache-Control','private, no-store');res.setHeader('Referrer-Policy','no-referrer');
if(req.method!=='GET'&&req.method!=='POST'){res.setHeader('Allow','GET, POST');return res.status(405).end();}
const headers = new Headers();for(const [key,value] of Object.entries(req.headers))if(value)headers.set(key,Array.isArray(value)?value.join(','):value);
const origin=process.env.ACCOUNT_PUBLIC_ORIGIN || 'http://'+req.headers.host;
const request=new Request(new URL(req.url || '/',origin),{method:req.method,headers,...(req.method==='POST'?{body:JSON.stringify(req.body)}:{})});
const response=await (req.method==='GET'?GET:POST)(request,{params:Promise.resolve({action:String(req.query.action)})});
response.headers.forEach((v,k)=>res.setHeader(k,v));res.status(response.status).send(await response.text());
}
export const config={api:{bodyParser:{sizeLimit:'4kb'}}};
@@ -0,0 +1,4 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {linkedGuidanceIndex} from '@/lib/guidance-discovery';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){return sendMarkdown(req,res,linkedGuidanceIndex());}
@@ -0,0 +1,20 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { authConfig, sessionCookie, signSession } from '@/lib/auth';
import { consumeCode } from '@/lib/auth-store';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Cache-Control','no-store');
if (req.method !== 'POST') { res.setHeader('Allow','POST'); return res.status(405).end(); }
try {
const origin = req.headers.origin;
if (!origin || new URL(origin).host !== req.headers.host || req.headers['sec-fetch-site'] === 'cross-site') return res.status(403).json({error:'请求来源不受信任'});
const config = authConfig();
if (!config) return res.status(503).json({error:'尚未配置动态码登录,请联系管理员'});
const code = typeof req.body?.code === 'string' ? req.body.code.trim() : '';
const result = await consumeCode(config,code);
if (result === 'limited') { res.setHeader('Retry-After','300'); return res.status(429).json({error:'尝试次数过多,请五分钟后再试'}); }
if (result !== 'ok') return res.status(401).json({error:'动态码不正确或已使用,请等待下一组动态码'});
res.setHeader('Set-Cookie',sessionCookie(signSession(config)));
return res.status(200).json({ok:true});
} catch { return res.status(503).json({error:'登录服务暂时不可用,请稍后重试'}); }
}
export const config = {api:{bodyParser:{sizeLimit:'1kb'}}};
@@ -0,0 +1,8 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { sessionCookie } from '@/lib/auth';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Cache-Control','no-store');
if (req.method !== 'POST') { res.setHeader('Allow','POST'); return res.status(405).end(); }
try { if (!req.headers.origin || new URL(req.headers.origin).host !== req.headers.host || req.headers['sec-fetch-site'] === 'cross-site') return res.status(403).end(); } catch { return res.status(403).end(); }
res.setHeader('Set-Cookie',sessionCookie('',true)); return res.status(200).json({ok:true});
}
@@ -0,0 +1,55 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {serveApiDocumentation} from '@/lib/api-documentation';
import {currentAccount} from '@/lib/account';
import {trustedOrigin} from '@/lib/account-crypto';
import {db} from '@/lib/db';
import {CanvasError,uuid,authorizeCanvas,canvasState,createCanvas,saveCanvas,createCanvasLink,queueCanvasTask,readCanvasTask,updateCanvasTask} from '@/lib/canvas-store';
export const config={api:{bodyParser:{sizeLimit:'15mb'}}};
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/canvases/{...path}'))return;
res.setHeader('Cache-Control','private, no-store');res.setHeader('Referrer-Policy','no-referrer');
const path=req.query.path||[];if(!Array.isArray(path)||path.length>3)return res.status(404).end();
const [id,section,taskId]=path;
if(id&&!uuid(id)||taskId&&!uuid(taskId))return res.status(404).end();
if(!['GET','POST','PUT','PATCH','DELETE'].includes(req.method||'')){res.setHeader('Allow','GET, POST, PUT, PATCH, DELETE');return res.status(405).end()}
const input=req.body;
if(req.method!=='GET'&&(!input||typeof input!=='object'||Array.isArray(input)))return res.status(400).json({error:'请发送 JSON 对象'});
try{
const headers=new Headers(Object.entries(req.headers).filter(([,v])=>typeof v==='string') as [string,string][]);
const request=new Request(new URL(req.url||'/',process.env.ACCOUNT_PUBLIC_ORIGIN||'http://'+req.headers.host),{headers});
const bearer=req.headers.authorization?.startsWith('Bearer ')?req.headers.authorization.slice(7):null;
if(bearer&&req.headers['sec-fetch-site']==='cross-site')throw new CanvasError(403,'请求来源不受信任');
if(!bearer&&req.method!=='GET'&&!trustedOrigin(request))throw new CanvasError(403,'请求来源不受信任');
const user=bearer?null:await currentAccount(request);
if(!id){
if(!user)throw new CanvasError(401,'请先登录邮箱账户');
if(req.method==='GET'){const rows=await db().query('SELECT id,name,revision,updated_at AS "updatedAt" FROM canvas_documents WHERE owner_id=$1 ORDER BY updated_at DESC LIMIT 100',[user.id]);return res.json({canvases:rows.rows})}
if(req.method==='POST')return res.status(201).json(await createCanvas(user.id,input.document,input.name));
return res.status(405).end();
}
const record=await authorizeCanvas(id,user?.id||null,bearer);
if(!section){
if(req.method==='GET')return res.json(await canvasState(record));
if(req.method==='PUT')return res.json(await canvasState(await saveCanvas(id,input.revision,input.document)));
return res.status(405).end();
}
if(section==='link'&&!taskId){
if(!user||user.id!==record.owner_id)throw new CanvasError(403,'只有画布所有者可以管理 Agent 连接');
if(req.method==='POST')return res.status(201).json({...await createCanvasLink(id),canvasId:id,documentation:`/api/canvases/${id}?agent_mode=True`});
if(req.method==='DELETE'){await db().query('DELETE FROM canvas_agent_links WHERE canvas_id=$1',[id]);return res.json({revoked:true})}
if(req.method==='GET'){const r=await db().query('SELECT expires_at AS "expiresAt",last_seen_at AS "lastSeenAt" FROM canvas_agent_links WHERE canvas_id=$1 AND expires_at>now() ORDER BY expires_at DESC LIMIT 1',[id]);return res.json({link:r.rows[0]||null})}
return res.status(405).end();
}
if(section==='tasks'){
if(!taskId&&req.method==='POST')return res.status(201).json(await queueCanvasTask(id,input.revision,input.targetId));
if(taskId&&req.method==='GET')return res.json(await readCanvasTask(id,taskId));
if(taskId&&req.method==='PATCH')return res.json(await updateCanvasTask(id,taskId,input));
return res.status(405).end();
}
return res.status(404).end();
}catch(e){
if(e instanceof CanvasError)return res.status(e.status).json({error:e.message});
if(e instanceof SyntaxError||e instanceof Error&&/格式|节点|引用|创作要求|图片|画布不能/.test(e.message))return res.status(400).json({error:'画布或任务参数无效'});
return res.status(503).json({error:'在线画布暂时不可用'});
}
}
@@ -0,0 +1,126 @@
import { ZodError } from "zod";
import type { NextApiRequest, NextApiResponse } from "next";
import { currentAccount } from "@/lib/account";
import { trustedOrigin } from "@/lib/account-crypto";
import { documentInput, parseDocumentXml } from "@/lib/guidance-input";
import {
discoverDocuments,
publishDocument,
resolveDocument,
withdrawDocument,
} from "@/lib/guidance-store";
import { guidanceXml } from "@/content/guides/catalog";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
res.setHeader("Cache-Control", "no-store");
const path = req.query.path || [];
if (!Array.isArray(path) || path.length > 1) return res.status(404).end();
const id = path[0];
try {
if (req.method === "GET") {
if (!id) {
const author = req.query.author;
if (
author !== undefined &&
(typeof author !== "string" ||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
author,
))
)
return res.status(400).json({ error: "作者 ID 无效" });
return res.json({ documents: await discoverDocuments(author) });
}
const revision = req.query.revision;
if (
revision !== undefined &&
(typeof revision !== "string" ||
!/^[1-9][0-9]{0,9}$/.test(revision) ||
Number(revision) > 2147483647)
)
return res.status(400).json({ error: "版本无效" });
const doc = await resolveDocument(
id,
revision === undefined ? undefined : Number(revision),
);
if (!doc) return res.status(404).json({ error: "文档或精确版本不存在" });
if (req.query.format === "xml") {
res.setHeader("Content-Type", "application/xml; charset=utf-8");
return res.send(guidanceXml(doc));
}
return res.json({ document: doc });
}
if (!["POST", "DELETE"].includes(req.method || "")) {
res.setHeader("Allow", "GET, POST, DELETE");
return res.status(405).end();
}
const request = new Request(
new URL(
req.url || "/",
process.env.ACCOUNT_PUBLIC_ORIGIN || "http://" + req.headers.host,
),
{
headers: new Headers(
Object.entries(req.headers).filter(
([, v]) => typeof v === "string",
) as [string, string][],
),
},
);
if (!trustedOrigin(request))
return res.status(403).json({ error: "请求来源不受信任" });
const user = await currentAccount(request);
if (!user) return res.status(401).json({ error: "请先登录已验证邮箱账户" });
if (req.method === "DELETE")
return id && (await withdrawDocument(user.id, id))
? res.json({ ok: true })
: res.status(404).json({ error: "无权删除或不存在" });
const input =
typeof req.body === "string"
? parseDocumentXml(req.body)
: documentInput.parse(req.body);
if (id === "preview") {
const links = await Promise.all(
input.links.map(async (l) => ({
...l,
resolved: !!(await resolveDocument(l.target, l.revision)),
})),
);
return res.json({ document: input, xml: guidanceXml(input), links });
}
if (id && id !== input.id)
return res.status(400).json({ error: "文档 ID 不匹配" });
return res
.status(201)
.json({ document: await publishDocument(user.id, input) });
} catch (e) {
if (e instanceof ZodError)
return res
.status(400)
.json({
error: "输入不符合协议,请检查以下字段",
fields: e.issues.slice(0, 12).map((i) => i.path.join(".") || "文档"),
});
const message = e instanceof Error ? e.message : "";
if (message === "INVALID_ID")
return res
.status(400)
.json({
error: "文档 ID 必须以 user-你的账户ID- 开头,请使用编辑器生成的前缀",
});
if (message === "FORBIDDEN")
return res.status(403).json({ error: "仅作者可编辑" });
if (message === "CONFLICT" || (e as { code?: string }).code === "23505")
return res
.status(409)
.json({ error: "版本冲突:请加载最新版本,已发布版本不可修改" });
if (
e instanceof Error &&
(e.name === "ZodError" || /XML|实体|元素|属性|协议|链接/.test(message))
)
return res.status(400).json({ error: "输入不符合协议" });
return res.status(503).json({ error: "文档服务暂不可用" });
}
}
export const config = { api: { bodyParser: { sizeLimit: "128kb" } } };
@@ -0,0 +1,6 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {InvalidDiscoveryCursor} from '@/lib/discovery';
import {exploreFeed} from '@/lib/explore';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/explore-feed'))return;if(req.method!=='GET')return res.status(405).end();try{return res.json(await exploreFeed(String(req.query.q||'').slice(0,200),String(req.query.category||''),String(req.query.cursor||'')||undefined));}catch(e){if(e instanceof InvalidDiscoveryCursor)return res.status(400).json({error:e.message});return res.status(503).json({error:'素材库暂时无法连接'});}}
+13
View File
@@ -0,0 +1,13 @@
import {z} from 'zod';
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import { feed } from "@/lib/library";
import { validSection } from "@/lib/model";
import { apiError } from "@/lib/api";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/feed'))return;
if(req.method!=='GET')return res.status(405).end();
try {const section=String(req.query.section||'');if(section&&!validSection(section))return res.status(400).json({error:'未知分类'});
res.setHeader('Cache-Control','no-store');return res.json(await feed({kind:validSection(section)?.kind,path:String(req.query.path||''),cursor:String(req.query.cursor||''),q:String(req.query.q||'').slice(0,200),archived:z.enum(['true','false']).default('false').parse(req.query.archived)==='true'}));
}catch(e){return apiError(res,e);}
}
@@ -0,0 +1,8 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceIndexMarkdown,guidanceMarkdown} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){
const parts=Array.isArray(req.query.path)?req.query.path:[];
const text=parts.length===0?guidanceIndexMarkdown(true):parts[0]!=='skills'?null:parts.length===1?guidanceIndexMarkdown():guidanceMarkdown(parts.slice(1).join('/'));
return sendMarkdown(req,res,text);
}
@@ -0,0 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {findGuide,guidanceXml} from '@/content/guides/catalog';
export default function handler(req:NextApiRequest,res:NextApiResponse){if(req.method!=='GET'){res.setHeader('Allow','GET');return res.status(405).end();}const r=req.query.revision;if(r!==undefined&&(typeof r!=='string'||!/^\d+$/.test(r)))return res.status(400).json({error:'无效版本'});const g=findGuide(String(req.query.id),r===undefined?undefined:Number(r));if(!g)return res.status(404).json({error:'文档或固定版本不存在'});res.setHeader('X-Content-Type-Options','nosniff');if(req.query.format==='xml'){res.setHeader('Content-Type','application/xml; charset=utf-8');return res.send(guidanceXml(g));}return res.json(g);}
@@ -0,0 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guides} from '@/content/guides/catalog';
export default function handler(req:NextApiRequest,res:NextApiResponse){if(req.method!=='GET'){res.setHeader('Allow','GET');return res.status(405).end();}return res.json({protocol:'linked-guidance/0.1',documents:guides.map(({id,revision,kind,title,summary,tags})=>({id,revision,kind,title,summary,tags,href:`/api/guides/${id}?revision=${revision}&format=xml`}))});}
+12
View File
@@ -0,0 +1,12 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest, NextApiResponse } from "next";
import { healthResponse } from "@/lib/health";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if(serveApiDocumentation(req,res,'/api/health'))return;
const { statusCode, body } = healthResponse(req.method, process.env.RELEASE_SHA);
res.setHeader("Cache-Control", "no-store");
if (statusCode === 405) res.setHeader("Allow", "GET, HEAD");
if (req.method === "HEAD") return res.status(statusCode).end();
return res.status(statusCode).json(body);
}
+22
View File
@@ -0,0 +1,22 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {apiDocuments} from '@/lib/api-documentation';
export default function handler(req:NextApiRequest,res:NextApiResponse){
if(!['GET','HEAD'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD');return res.status(405).end();}
const entries=[...Object.entries(apiDocuments).map(([path,doc])=>({path,title:doc[0],methods:doc[1],documentation:path+'?agent_mode=True'})),
{path:'/studio/api/export/{slug}',title:'封面渲染与方案导出',methods:'GET, POST',documentation:'/studio/api/export/{slug}?agent_mode=True'},
{path:'/studio/api/layouts',title:'标准与27套固定排版目录',methods:'GET',documentation:'/studio/api/layouts?agent_mode=True'},
{path:'/studio/api/layouts/{id}',title:'排版参数与 SVG 渲染',methods:'GET, POST',documentation:'/studio/api/layouts/{id}?agent_mode=True'},
{path:'/api/studio/series',title:'原子保存多页图文作品',methods:'POST',documentation:'/api/studio/series?agent_mode=True'},
{path:'/api/studio/series/{id}/export',title:'多页原生高清导出计划',methods:'GET',documentation:'/api/studio/series/{id}/export?agent_mode=True'},
{path:'/api/studio/series/{id}',title:'读取、修订与归档多页作品',methods:'GET, PATCH, DELETE, POST',documentation:'/api/studio/series/{id}?agent_mode=True'},
{path:'/api/studio/designs',title:'保存与列举 Studio 效果',methods:'GET, POST',documentation:'/api/studio/designs?agent_mode=True'},
{path:'/api/studio/designs/{id}',title:'读取、更新与可恢复删除页面',methods:'GET, PATCH, DELETE, POST',documentation:'/api/studio/designs/{id}?agent_mode=True'},
{path:'/api/studio/designs/{id}/post',title:'为旧页面补建 Wiki 入口',methods:'POST',documentation:'/api/studio/designs/{id}/post?agent_mode=True'},
{path:'/studio/api/health',title:'创作站健康检查',methods:'GET, HEAD',documentation:'/studio/api/health?agent_mode=True'}];
res.setHeader('Cache-Control','no-store');
const plain=typeof req.query.agent_mode==='string'&&req.query.agent_mode.toLowerCase()==='true';
res.setHeader('Content-Type',plain?'text/plain; charset=utf-8':'application/json; charset=utf-8');
if(req.method==='HEAD')return res.status(200).end();
if(plain)return res.send('# PROMPT 业务 API\n\n各接口使用 GET + agent_mode=True 读取说明;已有参数时用 & 拼接。动态路径允许保留占位符。业务调用请移除该参数。\n\n'+entries.map(e=>`- ${e.title}(${e.methods}):${e.documentation}`).join('\n')+'\n');
return res.json({entries});
}
@@ -0,0 +1,26 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import type { Readable } from "node:stream";
import { db } from "@/lib/db";
import { getObject } from "@/lib/storage";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/media/{id}'))return;
if(!['GET','HEAD'].includes(req.method||''))return res.status(405).end();
if(!/^[0-9a-f-]{36}$/.test(String(req.query.id)))return res.status(404).end();
try{
const variant=String(req.query.variant||'');
if(variant&&!['poster','silent_video','audio_track'].includes(variant))return res.status(404).end();
const result=variant?await db().query('SELECT storage_key,mime_type FROM assets WHERE source_asset_id=$1 AND derivation=$2',[req.query.id,variant]):await db().query('SELECT storage_key,mime_type FROM assets WHERE id=$1',[req.query.id]);
if(!result.rows[0]?.storage_key)return res.status(404).end();
const object=await getObject(result.rows[0].storage_key,req.headers.range);
res.status(object.ContentRange?206:200);
res.setHeader('Content-Type',object.ContentType||'application/octet-stream');res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('Accept-Ranges','bytes');
if(object.ContentLength!==undefined)res.setHeader('Content-Length',object.ContentLength);
if(object.ContentRange)res.setHeader('Content-Range',object.ContentRange);
res.setHeader('Cache-Control','private, no-store');
const stream=object.Body as Readable;
if(req.method==='HEAD'){stream.destroy();return res.end();}
res.on('close',()=>stream.destroy());stream.on('error',()=>res.destroy());return stream.pipe(res);
}catch(e){const code=(e as {$metadata?:{httpStatusCode:number}}).$metadata?.httpStatusCode;return res.status(code===416?416:404).end();}
}
export const config={api:{responseLimit:false}};
@@ -0,0 +1,20 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {getEntry} from '@/lib/explore';
import {tags} from '@/lib/library';
import {noteEditInput,noteTagsInput,saveNote,saveNoteTags,NoteEditConflict} from '@/lib/note-edits';
import {sameOrigin,apiError} from '@/lib/api';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/notes/{id}'))return;
res.setHeader('Cache-Control','no-store');
if(!['GET','PUT','PATCH'].includes(req.method||'')){res.setHeader('Allow','GET, PUT, PATCH');return res.status(405).end();}
try{
const id=String(req.query.id||'');const entry=await getEntry(id);if(!entry)return res.status(404).json({error:'笔记不存在'});
if(req.method==='GET')return res.json({entry,tags:await tags()});
sameOrigin(req);
if(req.method==='PATCH')await saveNoteTags(id,noteTagsInput.parse(req.body),client=>getEntry(id,client));
else await saveNote(id,noteEditInput.parse(req.body),client=>getEntry(id,client));
return res.json({entry:await getEntry(id)});
}catch(e){if(e instanceof NoteEditConflict)return res.status(409).json({error:e.message});return apiError(res,e);}
}
export const config={api:{bodyParser:{sizeLimit:'1mb'}}};
@@ -0,0 +1,10 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {serveApiDocumentation} from '@/lib/api-documentation';
import {sameOrigin,apiError} from '@/lib/api';
import {archiveInput,postIdentifier,setPostArchived} from '@/lib/post-archive';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/posts/{id}/archive'))return;
res.setHeader('Cache-Control','no-store');if(req.method!=='POST'){res.setHeader('Allow','POST');return res.status(405).end()}
try{sameOrigin(req);const post=await setPostArchived(postIdentifier.parse(req.query.id),archiveInput.parse(req.body).archived);return post?res.json({post}):res.status(404).json({error:'笔记不存在'})}catch(error){return apiError(res,error)}
}
export const config={api:{bodyParser:{sizeLimit:'1kb'}}};
@@ -0,0 +1,9 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import { createPost,postInput } from "@/lib/write";
import { sameOrigin,apiError } from "@/lib/api";
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/posts'))return;
if(req.method!=='POST')return res.status(405).end();
try{sameOrigin(req);return res.status(201).json(await createPost(postInput.parse(req.body)));}catch(e){return apiError(res,e);}
}
+8
View File
@@ -0,0 +1,8 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {db} from '@/lib/db';
import {getObject} from '@/lib/storage';
import {previewWidth,cachedPreview,loadStaticPreview} from '@/lib/preview';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/preview'))return;if(!['GET','HEAD'].includes(req.method||''))return res.status(405).end();const width=previewWidth(req.query.width,req.query.profile);if(!width||typeof req.query.source!=='string')return res.status(400).end();try{const source=req.query.source;let input:{identity:string;load:()=>Promise<Buffer>};if(source.startsWith('/api/media/')){const match=source.match(/^\/api\/media\/([0-9a-f-]{36})(?:\?variant=(poster))?$/);if(!match)return res.status(400).end();const result=match[2]?await db().query('SELECT storage_key,mime_type FROM assets WHERE source_asset_id=$1 AND derivation=$2',[match[1],match[2]]):await db().query('SELECT storage_key,mime_type FROM assets WHERE id=$1',[match[1]]);const row=result.rows[0];if(!row?.storage_key||!row.mime_type?.startsWith('image/'))return res.status(404).end();input={identity:row.storage_key,load:async()=>{const object=await getObject(row.storage_key);if((object.ContentLength||0)>64*1024*1024)throw Error('Image too large');const chunks:Buffer[]=[];let length=0;for await(const chunk of object.Body as AsyncIterable<Uint8Array>){length+=chunk.length;if(length>64*1024*1024)throw Error('Image too large');chunks.push(Buffer.from(chunk));}return Buffer.concat(chunks);}};}else input=await loadStaticPreview(source);const {bytes,etag}=await cachedPreview(input.identity,width,input.load,req.query.profile==='export');res.setHeader('ETag',etag);res.setHeader('Cache-Control','private, no-store');res.setHeader('Content-Type','image/webp');res.setHeader('X-Content-Type-Options','nosniff');if(req.headers['if-none-match']===etag)return res.status(304).end();res.setHeader('Content-Length',bytes.length);return req.method==='HEAD'?res.end():res.send(bytes);}catch(e){const message=(e as Error).message;if(message.includes('Invalid source'))return res.status(400).end();if((e as NodeJS.ErrnoException).code==='ENOENT')return res.status(404).end();res.setHeader('Retry-After','5');return res.status(503).end();}}
export const config={api:{responseLimit:false}};
+11
View File
@@ -0,0 +1,11 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from 'next';
import { db } from '@/lib/db';
import { storage,bucket } from '@/lib/storage';
import { HeadBucketCommand } from '@aws-sdk/client-s3';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/ready'))return;
if(req.method!=='GET')return res.status(405).end();
res.setHeader('Cache-Control','no-store');
try{await db().query('SELECT 1 FROM schema_migrations LIMIT 1');await storage().send(new HeadBucketCommand({Bucket:bucket()}));return res.json({status:'ok',database:'ready',objects:'ready'});}catch{return res.status(503).json({status:'unavailable'});}
}
@@ -0,0 +1,7 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceMarkdown,legacyDocumentPath} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){
const name=String(req.query.doc).replace(/\.md$/,'');
return sendMarkdown(req,res,guidanceMarkdown(legacyDocumentPath(String(req.query.skill),name)));
}
@@ -0,0 +1,4 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {guidanceMarkdown,legacyDocumentPath} from '@/content/skills/guidance';
import {sendMarkdown} from '@/lib/markdown-response';
export default function handler(req:NextApiRequest,res:NextApiResponse){return sendMarkdown(req,res,guidanceMarkdown(legacyDocumentPath('street-people',String(req.query.doc).replace(/\.md$/,''))));}
@@ -0,0 +1,18 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from "next";
import {upload} from "../upload";
import {streetPeople} from "@/lib/street-people";
import {guidanceMarkdown} from "@/content/skills/guidance";
import {validateCharacter} from "@/lib/character-image";
export const config={api:{bodyParser:false}};
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/skills/street-people'))return;
res.setHeader("Allow","GET, POST");
if(req.method==="GET"){
res.setHeader("Cache-Control","private, no-store");
if(req.query.format==="md")return res.setHeader("Content-Type","text/markdown; charset=utf-8").status(200).send(guidanceMarkdown("street-people"));
return res.status(200).json(streetPeople);
}
if(req.method==="POST")return upload(req,res,{validateImage:validateCharacter,defaultTitle:"街头小人 · 新生成"});
return res.status(405).json({error:"使用 GET 读取规范,POST 上传 PNG 素材包"});
}
@@ -0,0 +1,27 @@
import {embedSvgMedia} from '../../../../studio/lib/layout-images';
import {renderToStaticMarkup} from 'react-dom/server';
import {serveApiDocumentation} from '../../../../studio/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {ideas,ideaMarkdown} from '../../../../studio/content/ideas';
import {selections} from '../../../../studio/components/SourceCover';
import {renderCover} from '../../../../studio/lib/render-cover';
import {tutorialPost} from '../../../../studio/content/tool-links';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/studio/api/export/{slug}'))return;
if(!['GET','POST'].includes(req.method||'')){res.setHeader('Allow','GET, POST');return res.status(405).end();}
const slug=String(req.query.slug||''),idea=ideas.find(i=>i.slug===slug);if(!idea)return res.status(404).end();
if(req.method==='POST'||req.query.format==='svg'){
if(req.query.format!==undefined&&!['svg','json'].includes(String(req.query.format)))return res.status(400).json({error:'渲染格式必须为 svg 或 json'});
try{
const raw=req.query.slide??'0';if(req.method==='GET'&&(typeof raw!=='string'||!/^\d+$/.test(raw)))throw Error('无效 slide');
const input=req.method==='POST'?req.body:idea.tool?{layoutId:req.query.layoutId??selections[0].id}:{slide:Number(raw)};
const result=renderCover(slug,input);res.setHeader('Cache-Control','no-store');
res.setHeader('Content-Disposition',`attachment; filename="${slug}.${req.query.format==='json'?'json':'svg'}"`);
if(req.query.format==='json')return res.json(result.data);
res.setHeader('Content-Type','image/svg+xml; charset=utf-8');return res.send(await embedSvgMedia(req,renderToStaticMarkup(result.node)));
}catch(error){return res.status(400).json({error:error instanceof Error?error.message:'无效参数'});}
}
if(req.query.format==='markdown'){res.setHeader('Content-Type','text/markdown; charset=utf-8');return res.send(ideaMarkdown(idea)+'\n\n使用教程:'+tutorialPost+(idea.tool?'\n\n```json\n'+JSON.stringify(selections,null,2)+'\n```':''));}
res.setHeader('Content-Disposition',`attachment; filename="${idea.slug}.json"`);return res.json({version:idea.tool?3:idea.template?2:1,...idea,...(idea.tool?{layouts:selections}:{}),tutorialPost});
}
export const config={api:{bodyParser:{sizeLimit:'32kb'}}};
@@ -0,0 +1,3 @@
import {serveApiDocumentation} from '../../../studio/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from "next";
export default function handler(req:NextApiRequest,res:NextApiResponse){if(serveApiDocumentation(req,res,'/studio/api/health'))return;res.setHeader("Cache-Control","no-store");if(!["GET","HEAD"].includes(req.method||""))return res.status(405).end();return req.method==="HEAD"?res.status(200).end():res.status(200).json({status:"ok",service:"prompt-studio"});}
@@ -0,0 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {ideas} from '../../../studio/content/ideas';
export default function handler(_:NextApiRequest,res:NextApiResponse){res.setHeader('Content-Type','text/markdown; charset=utf-8');res.send('# 创作站\n\n- [在线画布、引用与 Agent 任务](/api/canvases?agent_mode=True)\n- [27 套排版目录与 API](/studio/api/layouts?agent_mode=True)\n- [多页作品与统一视觉](/api/studio/series?agent_mode=True)\n- [按 ID 保存效果](/api/studio/designs?agent_mode=True)\n\n'+ideas.map(i=>`- [${i.title}](/studio/ideas/${i.slug}) · [正文](/studio/api/export/${i.slug}?format=markdown)`).join('\n'));}
@@ -0,0 +1,31 @@
import {embedSvgMedia} from '../../../../studio/lib/layout-images';
import type {NextApiRequest,NextApiResponse} from 'next';
import {embedLayoutImages} from '../../../../studio/lib/layout-images';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import layouts from '../../../../studio/content/templates/layouts.json';
import standardLayout from '../../../../studio/content/standard-layout.json';
import {LayoutCanvas} from '../../../../studio/components/LayoutCanvas';
import {parameters,LayoutParameterError} from '../../../../studio/lib/layout-parameters';
const workspaceSchema={
added:'可选数组,最多100项:{id:"user-唯一ID",kind:"text|image|decoration",role:"名称",box:[x,y,width,height],direction:"horizontal",text:"文字或null",reading:"custom",shape:"rectangle|ellipse(装饰可选)"}',
layers:'按原生或新增元素ID索引:x/y -10000..10000,width/height 0.1..10000,rotation -360..360,opacity 0..1,radius 0..5000,z -1000..1000,hidden/locked 布尔值;坐标和字号均为模板单位',
texts:'原有 value/color/scale/align,加 fontFamily sans|serif|mono,fontSize 0.1..1000,fontWeight 100..900,lineHeight 0.5..4,letterSpacing -20..100',
images:'原有 assetId/color/fit,加 cropX/cropY 0..100(默认50),zoom 1..5',
export:'新增工作区参数由原生 HTML/CSS 页面呈现。旧 SVG 导出仅支持旧文本、图片与装饰参数,不反映新增元素、图层几何及扩展字体或裁切设置。使用页面打印可保存原生效果。'
};
export default async function handler(req:NextApiRequest,res:NextApiResponse){
res.setHeader('Cache-Control','no-store');
if(String(req.query.agent_mode).toLowerCase()==='true'&&['GET','HEAD'].includes(req.method||'')){res.setHeader('Content-Type','text/plain; charset=utf-8');if(req.method==='HEAD')return res.status(200).end();return res.send(`# 扩展编辑参数\n${JSON.stringify(workspaceSchema,null,2)}\n\n# 排版参数与渲染 API\n\nGET /studio/api/layouts/{id} 返回模板尺寸、T/I/D 构件 ID、坐标、原始文字可辨识状态与默认参数。id 为 standard-01(标准图文)或 ref-01 .. ref-27(固定构图)。standard-01 仅返回原生模板参数,不提供兼容 SVG。\n页面 /studio/layouts/{id} 直接提供原生 HTML/CSS 默认排版,不加载原图。保存结果直接打开 /studio/template-layout?id={designId},服务端根据 ID 读取模板、图片和文字,无需选版或编辑器;缺失或不存在的 ID 返回404。\nGET 同地址 ?format=svg 是兼容的原图图层导出,与原生页面使用的 HTML/CSS 不同。POST JSON 参数返回 SVG,不自动保存。?format=json 返回规范化参数。\n参数整体形状:{texts:{T01:{value:"标题",color:"#26362f",scale:1,align:"start"}},images:{I01:{color:"#788880",assetId:"已上传图片UUID",fit:"cover"}},decorations:{D01:{color:"#53645b",hidden:false}},paper:"#f4f2eb"}。全部可省略;构件 ID 必须属于当前模板。文字 value 可为空(移除),最多500字/8行;scale 0.25–2,align start/middle/end;fit cover/contain。图片先通过 /api/upload assetOnly=true 上传。\n未替换构件保留原始低分辨率图层;替换文字为 SVG 文字,未辨识小字不会编造。图位使用原始形状蒙版。paper 修改原底色层,不覆盖原图已有设计色块。\n文字、图像、装饰分组一一对应源图,不接受任意 URL、SVG 或未知构件。最大请求64KB。\n保存:POST /api/studio/designs {layoutId,name,parameters},返回 design.id/url/revision。再次打开返回的 /studio/template-layout?id={id}(纯结果页面);/studio/designs/{id} 自动跳转;PATCH /api/studio/designs/{id} {name,parameters,revision} 更新。\n错误400参数不合法,404模板不存在,405方法不支持。\n目录:/studio/api/layouts?agent_mode=True\n`)}
if(req.query.id==='standard-01'){
if(!['GET','HEAD','POST'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD, POST');return res.status(405).end()}
try{const p=parameters(standardLayout,req.method==='POST'?req.body:{});
if(req.query.format!==undefined&&req.query.format!=='json')return res.status(400).json({error:'标准排版提供原生 HTML 页面,不提供 SVG 导出;format 仅支持 json'});
if(req.method==='HEAD')return res.status(200).end();
return res.json({...standardLayout,schemaVersion:1,family:'standard',parameters:p,workspaceSchema,url:'/studio/layouts/standard-01',saveApi:'/api/studio/designs'});
}catch(e){return res.status(400).json({error:e instanceof Error?e.message:'参数不合法'})}
}
if(!['GET','HEAD','POST'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD, POST');return res.status(405).end()}const layout=layouts.find(l=>l.id===req.query.id);if(!layout)return res.status(404).json({error:'排版不存在'});
try{if(req.query.format!==undefined&&!['svg','json'].includes(String(req.query.format)))throw new LayoutParameterError('format 为 svg 或 json');const params=parameters(layout,req.method==='POST'?req.body:{});if(req.method==='HEAD')return res.status(200).end();if(req.query.format==='json')return res.json({layoutId:layout.id,parameters:params});if(req.method==='POST'||req.query.format==='svg'){res.setHeader('Content-Type','image/svg+xml; charset=utf-8');return res.send(await embedSvgMedia(req,renderToStaticMarkup(createElement(LayoutCanvas,{layout,params,imageSources:await embedLayoutImages(req,params)}))))}return res.json({schemaVersion:1,family:'fixed',id:layout.id,name:layout.name,width:layout.width,height:layout.height,sourceSha256:layout.sourceSha256,tutorialUrl:layout.tutorialUrl,elements:layout.elements.map(({id,kind,role,box,direction,text,reading})=>({id,kind,role,box,direction,text,reading})),parameters:params,workspaceSchema,url:'/studio/layouts/'+layout.id})}catch(e){return res.status(400).json({error:e instanceof Error?e.message:'参数不合法'})}
}
export const config={api:{bodyParser:{sizeLimit:'64kb'}}};
@@ -0,0 +1,10 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import fixed from '../../../../studio/content/templates/layouts.json';
import standard from '../../../../studio/content/standard-layout.json';
export default function handler(req:NextApiRequest,res:NextApiResponse){
if(!['GET','HEAD'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD');return res.status(405).end()}
const entries=[standard,...fixed].map(l=>({id:l.id,name:l.name,family:l.id==='standard-01'?'standard':'fixed',url:'/studio/layouts/'+l.id,api:'/studio/api/layouts/'+l.id}));
res.setHeader('Cache-Control','no-store');if(req.method==='HEAD')return res.status(200).end();
if(String(req.query.agent_mode).toLowerCase()==='true'){res.setHeader('Content-Type','text/plain; charset=utf-8');return res.send('# Studio 可视化排版 API 库\n\n'+entries.map(e=>`${e.family} / ${e.id} · ${e.name}\n页面:${e.url}\n参数:${e.api}?agent_mode=True`).join('\n\n')+'\n\n多页作品:/api/studio/series?agent_mode=True\n单页 CRUD:/api/studio/designs?agent_mode=True\n统一文档:/explore/8eb8c76500580f7a4b56ba3c')}
return res.json({version:1,seriesDocumentVersion:1,seriesApi:'/api/studio/series',layouts:entries,saveApi:'/api/studio/designs',catalogUrl:'/studio',documentationUrl:'/explore/8eb8c76500580f7a4b56ba3c'});
}
@@ -0,0 +1,20 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {z} from 'zod';
import {db} from '@/lib/db';
import {sameOrigin,apiError} from '@/lib/api';
import {designOutput,updateDesignInput,updateDesign,DesignConflict,archiveDesign,archiveDesignInput} from '@/lib/studio-designs';
import {LayoutParameterError} from '@/lib/layout-parameters';
import {studioDesignDocumentation} from '@/lib/studio-design-documentation';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(studioDesignDocumentation(req,res))return;res.setHeader('Cache-Control','no-store');
try{
if(!['GET','PATCH','DELETE','POST'].includes(req.method||'')){res.setHeader('Allow','GET, PATCH, DELETE, POST');return res.status(405).end()}
const id=z.uuid().parse(req.query.id);
if(req.method==='GET'){const row=(await db().query('SELECT * FROM studio_designs WHERE id=$1',[id])).rows[0];return row?res.json({design:designOutput(row)}):res.status(404).json({error:'效果不存在'})}
sameOrigin(req);
if(req.method==='DELETE'||req.method==='POST'){const input=(req.method==='DELETE'?archiveDesignInput.omit({archived:true}):archiveDesignInput).parse(req.body);if(req.method==='POST'&&(!('archived' in input)||input.archived!==false))return res.status(400).json({error:'恢复需 archived:false'});const design=await archiveDesign(id,input.revision,req.method==='DELETE');return design?res.json({design}):res.status(404).json({error:'效果不存在'})}
const design=await updateDesign(id,updateDesignInput.parse(req.body));
return design?res.json({design}):res.status(404).json({error:'效果不存在'});
}catch(e){if(e instanceof LayoutParameterError)return res.status(400).json({error:e.message});if(e instanceof DesignConflict)return res.status(409).json({error:e.message});return apiError(res,e)}
}
export const config={api:{bodyParser:{sizeLimit:'64kb'}}};
@@ -0,0 +1,10 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {z} from 'zod';
import {sameOrigin,apiError} from '@/lib/api';
import {publishDesignPost} from '@/lib/studio-designs';
import {studioDesignDocumentation} from '@/lib/studio-design-documentation';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(studioDesignDocumentation(req,res))return;res.setHeader('Cache-Control','no-store');
if(req.method!=='POST'){res.setHeader('Allow','POST');return res.status(405).end()}
try{sameOrigin(req);const result=await publishDesignPost(z.uuid().parse(req.query.id));return result?res.status(result.created?201:200).json(result):res.status(404).json({error:'效果不存在'})}catch(e){return apiError(res,e)}
}
@@ -0,0 +1,15 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {z} from 'zod';
import {sameOrigin,apiError} from '@/lib/api';
import {db} from '@/lib/db';
import {createDesign,designInput,designOutput} from '@/lib/studio-designs';
import {LayoutParameterError} from '@/lib/layout-parameters';
import {studioDesignDocumentation} from '@/lib/studio-design-documentation';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(studioDesignDocumentation(req,res))return;res.setHeader('Cache-Control','no-store');
try{if(req.method==='POST'){sameOrigin(req);return res.status(201).json({design:await createDesign(designInput.parse(req.body))})}
if(req.method==='GET'){const query=z.object({layoutId:z.string().regex(/^(standard-01|ref-(0[1-9]|1[0-9]|2[0-7]))$/).optional(),archived:z.enum(['true','false']).default('false'),limit:z.coerce.number().int().min(1).max(50).default(20),before:z.uuid().optional()}).parse(req.query);const r=await db().query('SELECT * FROM studio_designs WHERE archived=$4 AND ($1::text IS NULL OR layout_id=$1) AND ($2::uuid IS NULL OR (created_at,id)<(SELECT created_at,id FROM studio_designs WHERE id=$2)) ORDER BY created_at DESC,id DESC LIMIT $3',[query.layoutId||null,query.before||null,query.limit+1,query.archived==='true']);return res.json({designs:r.rows.slice(0,query.limit).map(designOutput),nextCursor:r.rows.length>query.limit?r.rows[query.limit-1].id:null})}
res.setHeader('Allow','GET, POST');return res.status(405).end();
}catch(e){if(e instanceof LayoutParameterError)return res.status(400).json({error:e.message});return apiError(res,e)}
}
export const config={api:{bodyParser:{sizeLimit:'64kb'}}};
@@ -0,0 +1,21 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {z} from 'zod';
import {sameOrigin,apiError} from '@/lib/api';
import {seriesUpdate,saveSeries,readSeries} from '@/lib/studio-series';
import {archiveDesign,archiveDesignInput,DesignConflict} from '@/lib/studio-designs';
import {LayoutParameterError} from '@/lib/layout-parameters';
import {studioDesignDocumentation} from '@/lib/studio-design-documentation';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(studioDesignDocumentation(req,res))return;res.setHeader('Cache-Control','no-store');
try{
const id=z.uuid().parse(req.query.id);if(!['GET','PATCH','DELETE','POST'].includes(req.method||'')){res.setHeader('Allow','GET, PATCH, DELETE, POST');return res.status(405).end()}
if(!await readSeries(id))return res.status(404).json({error:'作品不存在'});
if(req.method==='GET')return res.json({design:await readSeries(id)});
sameOrigin(req);
if(req.method==='PATCH'){const input=seriesUpdate.parse(req.body);return res.json({design:await saveSeries(input,id,input.revision)})}
const input=(req.method==='DELETE'?archiveDesignInput.omit({archived:true}):archiveDesignInput.required()).parse(req.body);
if(req.method==='POST'&&(!('archived' in input)||input.archived!==false))return res.status(400).json({error:'恢复需 archived:false'});
return res.json({design:await archiveDesign(id,input.revision,req.method==='DELETE')});
}catch(e){if(e instanceof LayoutParameterError)return res.status(400).json({error:e.message});if(e instanceof DesignConflict)return res.status(409).json({error:e.message});return apiError(res,e)}
}
export const config={api:{bodyParser:{sizeLimit:'512kb'}}};
@@ -0,0 +1,13 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {z} from 'zod';
import {apiError} from '@/lib/api';
import {readSeries} from '@/lib/studio-series';
import type {Series} from '@/lib/series';
import fixed from '@/content/studio-layouts.json';
import standard from '@/content/standard-layout.json';
import {studioDesignDocumentation} from '@/lib/studio-design-documentation';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(studioDesignDocumentation(req,res))return;res.setHeader('Cache-Control','no-store');
if(req.method!=='GET'){res.setHeader('Allow','GET');return res.status(405).end()}
try{const id=z.uuid().parse(req.query.id),d=await readSeries(id);if(!d||d.archived)return res.status(404).json({error:'作品不存在'});const doc=d.document as Series;return res.json({version:1,id,revision:d.revision,name:d.name,format:'png',pages:doc.pages.map((p,i)=>{const l=[standard,...fixed].find(l=>l.id===p.layoutId)!;return {number:i+1,key:p.key,role:p.role,width:1080,height:Math.round(1080*l.height/l.width),url:d.url+'&page='+(i+1)+'&export=1',filename:String(i+1).padStart(2,'0')+'-'+p.key+'.png'}})})}catch(e){return apiError(res,e)}
}
@@ -0,0 +1,11 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {sameOrigin,apiError} from '@/lib/api';
import {seriesInput,saveSeries} from '@/lib/studio-series';
import {LayoutParameterError} from '@/lib/layout-parameters';
import {studioDesignDocumentation} from '@/lib/studio-design-documentation';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(studioDesignDocumentation(req,res))return;res.setHeader('Cache-Control','no-store');
if(req.method!=='POST'){res.setHeader('Allow','POST');return res.status(405).end()}
try{sameOrigin(req);return res.status(201).json({design:await saveSeries(seriesInput.parse(req.body))})}catch(e){if(e instanceof LayoutParameterError)return res.status(400).json({error:e.message});return apiError(res,e)}
}
export const config={api:{bodyParser:{sizeLimit:'512kb'}}};
+23
View File
@@ -0,0 +1,23 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {randomUUID} from 'node:crypto';
import {z} from 'zod';
import {db} from '@/lib/db';
import {tags} from '@/lib/library';
import {sameOrigin,apiError} from '@/lib/api';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/tags'))return;
try{
if(req.method==='GET')return res.json(await tags());
if(req.method!=='POST')return res.status(405).end();
sameOrigin(req);
const data=z.object({name:z.string().trim().transform(v=>v.replace(/^#+/,'').trim()).pipe(z.string().min(1).max(60).regex(/^[^#\s,,]+$/)),slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,59}$/).optional()}).strict().parse(req.body);
const existing=(await tags()).find(t=>t.name.toLocaleLowerCase()===data.name.toLocaleLowerCase());
if(existing?.kind==='system')return res.status(400).json({error:'系统标签只能从系统标签列表搜索并勾选添加'});
const id=randomUUID();
const result=await db().query(`INSERT INTO tags(id,name,slug) VALUES($1,$2,$3)
ON CONFLICT(lower(btrim(name))) DO UPDATE SET name=tags.name WHERE tags.kind='normal' RETURNING *,slug AS path`,[id,data.name,data.slug||'tag-'+id]);
if(!result.rows.length)return res.status(400).json({error:'不能通过 # 创建或添加系统标签'});
return res.status(result.rows[0].id===id?201:200).json(result.rows[0]);
}catch(e){return apiError(res,e);}
}
+70
View File
@@ -0,0 +1,70 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import formidable,{type File} from "formidable";
import { randomUUID,createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { rm } from "node:fs/promises";
import sharp from "sharp";
import { z } from "zod";
import { transaction } from "@/lib/db";
import { putFile,removeObject } from "@/lib/storage";
import { probe } from "@/lib/probe";
import { sameOrigin,apiError } from "@/lib/api";
export const config={api:{bodyParser:false}};
export type UploadPolicy = { validateImage?: (path:string) => Promise<void>; defaultTitle?:string };
export async function upload(req:NextApiRequest,res:NextApiResponse,policy:UploadPolicy={}){
if(serveApiDocumentation(req,res,'/api/upload'))return;
if(req.method!=='POST')return res.status(405).end();
const temporary:string[]=[];const uploaded:string[]=[];
try{
sameOrigin(req);
const form=formidable({maxFileSize:250*1024*1024,maxTotalFileSize:1024*1024*1024,maxFiles:16,allowEmptyFiles:false});
// file completion events can finish out of order; preserve multipart selection order.
const items:File[]=[];
form.on('fileBegin',(_name,file)=>{temporary.push(file.filepath);items.push(file)});
const [fields]=await form.parse(req);
const assetOnly=z.enum(['true','false']).default('false').parse(fields.assetOnly?.[0])==='true';
const kind=z.enum(['image','video','audio']).parse(policy.validateImage?'image':fields.kind?.[0]);
const title=z.string().trim().min(1).max(200).parse(fields.title?.[0]||policy.defaultTitle||(assetOnly?'上传素材':undefined));
const slug=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(120).optional().parse(fields.slug?.[0]);
const description=z.string().trim().max(100000).parse(fields.description?.[0]||'');
const tagIds=z.array(z.uuid()).max(50).parse(JSON.parse(fields.tags?.[0]||'[]'));
if(!items.length) return res.status(400).json({error:'请选择文件'});
const records:{id:string;key:string;mime:string;width:number|undefined;height:number|undefined;duration:number|undefined;hasAudio:boolean|null;size:number;hash:string;filename:string}[]=[];
for(const file of items){
let mime='';let width:number|undefined,height:number|undefined,duration:number|undefined,hasAudio:boolean|null=null;
if(kind==='image'){
if(policy.validateImage)await policy.validateImage(file.filepath);
const meta=await sharp(file.filepath,{limitInputPixels:100000000}).metadata();
const formats:Record<string,string>={jpeg:'image/jpeg',png:'image/png',webp:'image/webp',gif:'image/gif',avif:'image/avif'};
mime=formats[meta.format||''];if(!mime)throw new Error('Unsupported image format');width=meta.width;height=meta.height;
}else{
const meta=await probe(file.filepath);const video=meta.streams.find(s=>s.codec_type==='video');const audio=meta.streams.some(s=>s.codec_type==='audio');
if(kind==='video'&&!video)throw new Error('File has no video stream');if(kind==='audio'&&(!audio||video))throw new Error('Select an audio file');
if(!file.mimetype?.startsWith(kind+'/'))throw new Error('Unsupported media MIME type');
mime=file.mimetype;width=video?.width;height=video?.height;duration=Number(meta.format.duration)||undefined;hasAudio=kind==='video'?audio:null;
}
const hash=createHash('sha256');for await(const chunk of createReadStream(file.filepath))hash.update(chunk);
const id=randomUUID(),key=`originals/${id}`;await putFile(key,file.filepath,mime);uploaded.push(key);
records.push({id,key,mime,width,height,duration,hasAudio,size:file.size,hash:hash.digest('hex'),filename:file.originalFilename||'未命名素材'});
}
const postId=assetOnly?null:randomUUID();
await transaction(async client=>{
if(postId)await client.query('INSERT INTO posts(id,slug,kind,title,description) VALUES($1,$2,$3,$4,$5)',[postId,slug||postId,kind,title,description.slice(0,1000)||title]);
for(const [position,a] of records.entries()){
await client.query('INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256,width,height,duration,has_audio,processing_status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',[a.id,kind,a.filename,a.key,a.mime,a.size,a.hash,a.width,a.height,a.duration,a.hasAudio,kind==='video'?'pending':'ready']);
if(postId)await client.query('INSERT INTO post_assets(post_id,asset_id,position) VALUES($1,$2,$3)',[postId,a.id,position]);
for(const tag of new Set(tagIds))await client.query('INSERT INTO asset_tags(asset_id,tag_id) VALUES($1,$2)',[a.id,tag]);
if(kind==='video')await client.query('INSERT INTO media_jobs(id,asset_id) VALUES($1,$2)',[randomUUID(),a.id]);
}
if(postId&&description){const id=randomUUID();await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[id,description]);await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'caption')",[postId,id,records.length]);}
if(postId)for(const tag of new Set(tagIds))await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[postId,tag]);
});
uploaded.length=0;
if(assetOnly)return res.status(201).json({assets:records.map(a=>a.id),files:records.map(a=>({id:a.id,filename:a.filename,sha256:a.hash}))});
return res.status(201).json({id:postId,slug:slug||postId,url:`/p/${slug||postId}`,assets:records.map(a=>a.id)});
}catch(e){if(e instanceof Error && (/maxFileSize|maxTotalFileSize|maxFiles/.test(e.message)))return res.status(413).json({error:'最多 16 个文件,单个不超过 250 MB,总计不超过 1 GB'});return apiError(res,e);}
finally{await Promise.allSettled(temporary.map(p=>rm(p,{force:true})));await Promise.allSettled(uploaded.map(removeObject));}
}
export default upload;
@@ -0,0 +1,6 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {publishedPublicIds} from '@/lib/library';
import {staticEntries} from '@/lib/explore';
import {applyStaticEdit,staticEdits} from '@/lib/note-edits';
import {exploreUrl} from '@/content/page-links';
export default async function handler(_:NextApiRequest,res:NextApiResponse){const [edits,published]=await Promise.all([staticEdits(),process.env.DATABASE_URL?publishedPublicIds():Promise.resolve([])]);const entries=staticEntries.filter(e=>!published.includes(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));res.setHeader('Content-Type','text/plain; charset=utf-8');res.send('# PROMPT\n\n'+entries.map(e=>`- [${e.title}](${exploreUrl(e.id)}?agent_mode=True)`).join('\n')+'\n\n素材分页索引:/api/explore-feed(使用 nextCursor 翻页)。所有内容均使用 /explore/{id}?agent_mode=True 读取纯文本。\n');}
@@ -0,0 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {getPost} from '@/lib/library';
export default async function handler(req:NextApiRequest,res:NextApiResponse){if(req.method!=='GET'&&req.method!=='HEAD')return res.status(405).end();try{const post=await getPost(String(req.query.slug||''));if(!post)return res.status(404).end();res.setHeader('Content-Type','text/markdown; charset=utf-8');res.send('# '+post.title+'\n\nNamespace: '+(['image','video','audio'].includes(post.kind)?'File':'Main')+'\n\n'+post.assets.map(a=>a.kind==='text'?a.body:`- ${a.kind}: [${a.filename||a.id}](/api/media/${a.id})`).join('\n\n')+'\n\nCategories: '+post.tags.map(t=>t.name).join(', '));}catch{res.status(503).send('Storage temporarily unavailable');}}
@@ -0,0 +1,4 @@
import postHandler from '../wiki-post/[slug]';
import type {NextApiRequest,NextApiResponse} from 'next';
import {findWikiPage,wikiMarkdown} from '@/content/wiki';
export default async function handler(req:NextApiRequest,res:NextApiResponse){if(req.method!=='GET'&&req.method!=='HEAD')return res.status(405).end();const page=findWikiPage(String(req.query.key||''));if(!page){const key=String(req.query.key||'');if(!/^(Main|File):/.test(key))return res.status(404).end();req.query.slug=key.slice(key.indexOf(':')+1);return postHandler(req,res);}res.setHeader('Content-Type','text/markdown; charset=utf-8');return res.send(wikiMarkdown(page));}
+15
View File
@@ -0,0 +1,15 @@
import type {GetServerSideProps} from 'next';
import Link from 'next/link';
import Head from 'next/head';
import {Shell} from '@/components/Shell';
import {ExploreFeed} from '@/components/ExploreFeed';
import {exploreFeed,type ExploreEntry} from '@/lib/explore';
import {tags} from '@/lib/library';
import {systemTags} from '@/lib/system-tags';
export default function Categories({categories,category,entries,cursor,q,total,unavailable=false}:{categories:string[];category:string;entries:ExploreEntry[];cursor:string|null;q:string;total?:number;unavailable?:boolean}){
const link=(value:string)=>({pathname:'/categories',query:{...(value?{category:value}:{}),...(q?{q}:{})}});
return <Shell><Head><title>分类 · 啡跃 Endoleap</title></Head><nav className="discovery-tabs" aria-label="系统标签分类"><Link href={link('')} className={!category?'selected':''}>全部</Link>{categories.map(c=><Link className={c===category?'selected':''} href={link(c)} key={c}>{c}</Link>)}</nav>{category&&!categories.includes(category)&&<div className="ordinary-tag-filter">#{category}<Link href={link('')}>清除筛选 ×</Link></div>}{unavailable&&<p role="status">分类暂时无法读取,请稍后重试。</p>}<ExploreFeed key={JSON.stringify([category,q])} initial={entries} cursor={cursor} q={q} category={category} total={total}/></Shell>;
}
export const getServerSideProps:GetServerSideProps=async({query})=>{
const category=String(query.category||'').slice(0,200),q=String(query.q||'').slice(0,200);try{const [all,data]=await Promise.all([tags(),exploreFeed(q,category)]);return {props:{categories:all.filter(t=>t.kind==='system').map(t=>t.name),category,q,entries:data.entries,cursor:data.nextCursor,total:data.total}};}catch{return {props:{categories:systemTags.map(t=>t.name),category,q,entries:[],cursor:null,unavailable:true}}}
};
@@ -0,0 +1,61 @@
import type { GetServerSideProps } from "next";
import GuidanceReader, { type ReaderProps } from "@/components/GuidanceReader";
export default function Read(props: ReaderProps) {
return <GuidanceReader {...props} />;
}
export const getServerSideProps: GetServerSideProps<ReaderProps> = async ({
params,
query,
res,
req,
}) => {
res.setHeader("Cache-Control", "no-store");
const revision = query.revision;
if (
revision !== undefined &&
(typeof revision !== "string" ||
!/^[1-9][0-9]{0,9}$/.test(revision) ||
Number(revision) > 2147483647)
)
return { notFound: true };
const { resolveDocument } = await import("@/lib/guidance-store");
const document = await resolveDocument(
String(params?.id),
revision === undefined ? undefined : Number(revision),
);
if (!document) return { notFound: true };
const links = await Promise.all(
document.links.map(async (link) => ({
...link,
resolved: !!(await resolveDocument(link.target, link.revision)),
})),
);
const { db } = await import("@/lib/db");
const { currentAccount } = await import("@/lib/account");
const user = await currentAccount(
new Request("http://internal", {
headers: { cookie: req.headers.cookie || "" },
}),
);
const owner = await db().query(
"SELECT owner_id,deleted_at FROM guidance_documents WHERE id=$1",
[document.id],
);
const rows = await db().query(
"SELECT revision,created_at FROM guidance_revisions WHERE document_id=$1 ORDER BY revision DESC",
[document.id],
);
return {
props: {
document,
source: "community",
links,
canEdit: !!user && owner.rows[0]?.owner_id === user.id,
withdrawn: !!owner.rows[0]?.deleted_at,
versions: rows.rows.map((r) => ({
revision: r.revision,
createdAt: new Date(r.created_at).toISOString(),
})),
},
};
};
@@ -0,0 +1,4 @@
import DocumentDirectory from "@/components/DocumentDirectory";
export default function Documents() {
return <DocumentDirectory communityOnly />;
}
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {ExploreDetail} from '@/components/ExploreDetail';
import {getEntry,entryText,exploreFeed} from '@/lib/explore';
export default ExploreDetail;
export const getServerSideProps:GetServerSideProps=async({params,query,res,req})=>{try{const entry=await getEntry(String(params?.id||''));if(!entry)return {notFound:true};if(String(query.agent_mode||'').toLowerCase()==='true'){res.setHeader('Content-Type','text/plain; charset=utf-8');res.setHeader('Cache-Control','no-cache');res.end(req.method==='HEAD'?undefined:entryText(entry));return {props:{}};}return {props:{entry,background:(await exploreFeed()).entries}};}catch{res.statusCode=503;res.setHeader('Retry-After','10');res.end('内容暂时无法读取,请稍后重试');return {props:{}};}};
@@ -0,0 +1,48 @@
import { ThemeToggle } from "../../studio/components/ThemeToggle";
import { Brand } from "../../studio/components/Brand";
import Head from 'next/head';
import {useEffect,useRef,useState,type PointerEvent} from 'react';
import {MousePointer2,Type,Square,Circle,Plus,Minus,Undo2,Redo2,Download,Layers,ImagePlus,Trash2,Copy,Eye,EyeOff,Lock,Unlock,Scan,ChevronRight,ArrowUpRight,PenTool,X,Hand,Link2,BookOpen,PanelLeft,PanelRight} from 'lucide-react';
import {newElementId} from '../../studio/lib/native-layout';
import styles from '../../studio/styles/graphic.module.css';
import {parseGraphicDocument,type GraphicItem as Item,type GraphicDocument as Doc} from '../../studio/lib/graphic-document';
const blank:Doc={name:'未命名设计',background:'#ffffff',items:[]};
const storage='studio.graphic.v1';
export default function Graphic(){
const [doc,setDoc]=useState<Doc>(blank),[selected,setSelected]=useState(''),[past,setPast]=useState<Doc[]>([]),[future,setFuture]=useState<Doc[]>([]),[zoom,setZoom]=useState(.65),[status,setStatus]=useState('本机草稿'),[tab,setTab]=useState('图层'),[user,setUser]=useState<{email:string}|null>(null),[auth,setAuth]=useState(false),[mode,setMode]=useState('login'),[message,setMessage]=useState(''),[busy,setBusy]=useState(false);
const [tool,setTool]=useState('select'),[offset,setOffset]=useState({x:0,y:0}),[showLayers,setShowLayers]=useState(true),[showProps,setShowProps]=useState(true);
const dialog=useRef<HTMLDivElement>(null);
useEffect(()=>{if(!auth)return;const old=document.activeElement as HTMLElement;const box=dialog.current;box?.querySelector<HTMLElement>('button,input')?.focus();function key(e:KeyboardEvent){if(e.key==='Escape'){setAuth(false);return}if(e.key!=='Tab'||!box)return;const nodes=Array.from(box.querySelectorAll<HTMLElement>('button:not(:disabled),input,a[href]'));const first=nodes[0],last=nodes[nodes.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last?.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first?.focus()}}document.addEventListener('keydown',key);return()=>{document.removeEventListener('keydown',key);old?.focus()}},[auth]);
const restore=useRef<HTMLInputElement>(null);
const board=useRef<HTMLDivElement>(null),upload=useRef<HTMLInputElement>(null),viewport=useRef<HTMLDivElement>(null),ready=useRef(false),dirty=useRef(false);
const item=doc.items.find(i=>i.id===selected);
useEffect(()=>{try{const raw=localStorage.getItem(storage);if(raw){setDoc(parseGraphicDocument(raw));}}catch{setStatus('无法读取草稿,请导出备份')}ready.current=true;void refresh();},[]);
useEffect(()=>{if(!ready.current)return;try{localStorage.setItem(storage,JSON.stringify(doc));setStatus('已保存到此浏览器');dirty.current=false;}catch{setStatus('本机空间不足,请导出备份');dirty.current=true;}},[doc]);
useEffect(()=>{const warn=(e:BeforeUnloadEvent)=>{if(dirty.current){e.preventDefault();e.returnValue=''}};window.addEventListener('beforeunload',warn);return()=>window.removeEventListener('beforeunload',warn)},[]);
async function refresh(){try{const r=await fetch('/api/account/session');if(r.ok)setUser((await r.json()).user);}catch{/* Guest editing remains available. */}}
function change(next:Doc){setPast(p=>[...p.slice(-49),doc]);setFuture([]);setDoc(next);dirty.current=true;}
function patch(p:Partial<Item>){if(item&&!item.locked)change({...doc,items:doc.items.map(i=>i.id===selected?{...i,...p}:i)})}
function add(kind:Item['kind'],src?:string){if(doc.items.length>=500){setStatus('单页最多 500 个图层');return;}const id=newElementId();const next:Item={id,kind,name:kind==='text'?'文字':kind==='image'?'图片':kind==='rect'?'矩形':'椭圆',text:'让灵感,有形。',x:90+doc.items.length*12%260,y:100+doc.items.length*12%400,w:kind==='text'?480:260,h:kind==='text'?90:220,fill:kind==='text'?'#282832':'#b8b3ff',size:52,hidden:false,locked:false,src};change({...doc,items:[...doc.items,next]});setSelected(id);setTab('图层');}
function undo(){if(!past.length)return;setFuture(f=>[doc,...f]);setDoc(past[past.length-1]);setPast(p=>p.slice(0,-1));}
function redo(){if(!future.length)return;setPast(p=>[...p,doc]);setDoc(future[0]);setFuture(f=>f.slice(1));}
function remove(){if(item&&!item.locked){change({...doc,items:doc.items.filter(i=>i.id!==selected)});setSelected('')}}
function duplicate(){if(item&&doc.items.length<500){const id=newElementId();change({...doc,items:[...doc.items,{...item,id,x:item.x+24,y:item.y+24,name:item.name+' 副本',locked:false}]});setSelected(id)}}
function fit(){setOffset({x:0,y:0});if(viewport.current)setZoom(Math.max(.15,Math.min(1,(viewport.current.clientWidth-100)/800,(viewport.current.clientHeight-100)/1000)))}
useEffect(()=>{fit();},[]);
useEffect(()=>{function key(e:KeyboardEvent){if((e.target as HTMLElement).closest('input,textarea,select,button'))return;if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='z'){e.preventDefault();e.shiftKey?redo():undo()}else if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='d'){e.preventDefault();duplicate()}else if(e.key==='Delete'||e.key==='Backspace'){e.preventDefault();remove()}else if(e.key==='Escape')setSelected('');else if(!e.ctrlKey&&!e.metaKey&&e.key.toLowerCase()==='v')setTool('select');else if(!e.ctrlKey&&!e.metaKey&&e.key.toLowerCase()==='h')setTool('hand');else if(item&&!item.locked&&e.key.startsWith('Arrow')){e.preventDefault();const step=e.shiftKey?10:1;patch({x:item.x+(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0),y:item.y+(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0)})}}window.addEventListener('keydown',key);return()=>window.removeEventListener('keydown',key)});
function drag(e:PointerEvent<HTMLDivElement>,i:Item){if(tool==='hand'){panBoard(e);return}e.stopPropagation();setSelected(i.id);if(i.locked||e.button!==0)return;e.preventDefault();e.currentTarget.setPointerCapture(e.pointerId);const x=e.clientX,y=e.clientY,start=doc;let next=start;const target=e.currentTarget;const move=(p:globalThis.PointerEvent)=>{next={...start,items:start.items.map(n=>n.id===i.id?{...n,x:Math.max(-4000,Math.min(4000,i.x+(p.clientX-x)/zoom)),y:Math.max(-4000,Math.min(4000,i.y+(p.clientY-y)/zoom))}:n)};setDoc(next)};const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end);if(next!==start){setPast(p=>[...p.slice(-49),start]);setFuture([])}};target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end);}
function resize(e:PointerEvent<HTMLElement>){e.stopPropagation();if(!item||item.locked)return;e.preventDefault();const start=doc,x=e.clientX,y=e.clientY,target=e.currentTarget;target.setPointerCapture(e.pointerId);let next=start;const move=(p:globalThis.PointerEvent)=>{next={...start,items:start.items.map(i=>i.id===item.id?{...i,w:Math.max(1,Math.min(4000,item.w+(p.clientX-x)/zoom)),h:Math.max(1,Math.min(4000,item.h+(p.clientY-y)/zoom))}:i)};setDoc(next)};const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end);if(next!==start){setPast(p=>[...p.slice(-49),start]);setFuture([])}};target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end)}
function panBoard(e:PointerEvent<HTMLElement>){if(tool!=='hand')return;e.preventDefault();const x=e.clientX,y=e.clientY,start=offset,target=e.currentTarget;target.setPointerCapture(e.pointerId);const move=(p:globalThis.PointerEvent)=>setOffset({x:start.x+p.clientX-x,y:start.y+p.clientY-y});const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end)};target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end)}
function download(content:string,type:string,extension:string){const url=URL.createObjectURL(new Blob([content],{type}));const a=document.createElement('a');a.href=url;a.download=doc.name+'.'+extension;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
function exportSVG(){const esc=(s:string)=>s.replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&apos;'}[c]!));const svg=doc.items.filter(i=>!i.hidden).map(i=>i.kind==='text'?`<text x="${i.x}" y="${i.y+i.size}" font-family="sans-serif" font-size="${i.size}" fill="${esc(i.fill)}">${i.text.split('\n').map((line,n)=>`<tspan x="${i.x}" dy="${n?i.size*1.3:0}">${esc(line)}</tspan>`).join('')}</text>`:i.kind==='image'?`<image x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" href="${esc(i.src||'')}" preserveAspectRatio="xMidYMid slice"/>`:i.kind==='ellipse'?`<ellipse cx="${i.x+i.w/2}" cy="${i.y+i.h/2}" rx="${i.w/2}" ry="${i.h/2}" fill="${esc(i.fill)}"/>`:`<rect x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" fill="${esc(i.fill)}"/>`).join('');download(`<svg xmlns="http://www.w3.org/2000/svg" width="800" height="1000" viewBox="0 0 800 1000"><rect width="800" height="1000" fill="${esc(doc.background)}"/>${svg}</svg>`,'image/svg+xml','svg');}
async function account(e:React.FormEvent<HTMLFormElement>){e.preventDefault();setBusy(true);setMessage('');const data=new FormData(e.currentTarget);try{const r=await fetch('/api/account/'+mode,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:data.get('email'),password:data.get('password')})});const d=await r.json();setMessage(d.error||d.message||'登录成功');if(r.ok){await refresh();if(mode==='login')setAuth(false);}}catch{setMessage('账户服务暂时无法连接')}finally{setBusy(false)}}
return <div className={styles.app} data-layers={showLayers} data-properties={showProps}><Head><title>{doc.name + " · 啡跃 Endoleap Graphic"}</title><meta name="description" content="在 Studio 中自由编排文字、图形与图片。"/></Head>
<header className={styles.top}><a href="/workspace" className={styles.brand}><Brand compact/><span className={styles.badge}>GRAPHIC</span></a><button aria-label="切换图层面板" aria-pressed={showLayers} onClick={()=>setShowLayers(v=>!v)}><PanelLeft size={17}/></button><button aria-label="切换属性面板" aria-pressed={showProps} onClick={()=>setShowProps(v=>!v)}><PanelRight size={17}/></button><ChevronRight size={14}/><input aria-label="设计名称" value={doc.name} maxLength={100} onChange={e=>change({...doc,name:e.target.value})}/><span className={styles.saved} role="status">{status}</span><button title="撤销" aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={17}/></button><button title="重做" aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={17}/></button><ThemeToggle/><button onClick={()=>setAuth(true)} className={styles.account}>{user?user.email:'邮箱登录'}</button><button className={styles.primary} onClick={exportSVG}><Download size={15}/>导出 SVG</button></header>
<div className={styles.body}><aside className={styles.left}><div className={styles.tabs}>{['图层','素材','Agent'].map(t=><button key={t} aria-pressed={tab===t} onClick={()=>setTab(t)}>{t}</button>)}</div><div className={styles.pageTitle}><span>页面 01</span><span>800 × 1000</span></div>{tab==='Agent'?<div className={styles.agentPanel}><Link2 size={24}/><h3>与你的 Agent 一起设计</h3><p>将接入文档交给 coding agent,使用已有的模板与创作 API。</p><a href="/studio/api" target="_blank" rel="noreferrer">查看接入文档 ↗</a><a href="/documents" target="_blank" rel="noreferrer"><BookOpen size={15}/>知识与教程 ↗</a><small>在 Agent 中打开文档,查看可用的创作接口与使用方式。</small></div>:tab==='图层'?<><div className={styles.layers}>{[...doc.items].reverse().map(i=><div className={styles.layer} data-selected={i.id===selected} key={i.id}><button onClick={()=>setSelected(i.id)}>{i.kind==='text'?<Type size={14}/>:<Square size={14}/>}<span>{i.name}</span></button><button aria-label={i.hidden?'显示图层':'隐藏图层'} onClick={()=>change({...doc,items:doc.items.map(n=>n.id===i.id?{...n,hidden:!n.hidden}:n)})}>{i.hidden?<EyeOff size={13}/>:<Eye size={13}/>}</button><button aria-label={i.locked?'解锁图层':'锁定图层'} onClick={()=>change({...doc,items:doc.items.map(n=>n.id===i.id?{...n,locked:!n.locked}:n)})}>{i.locked?<Lock size={13}/>:<Unlock size={13}/>}</button></div>)}{!doc.items.length&&<div className={styles.emptyLayers}><Layers size={23}/><p>好设计,从第一笔开始</p><small>从下方工具栏添加文字与图形</small></div>}</div><button className={styles.addLayer} onClick={()=>add('text')}><Plus size={15}/>添加图层</button></>:<div className={styles.assets}><h3>基础元素</h3><button onClick={()=>add('rect')}><Square/>矩形</button><button onClick={()=>add('ellipse')}><Circle/>椭圆</button><button onClick={()=>add('text')}><Type/>文字</button><button onClick={()=>upload.current?.click()}><ImagePlus/>上传图片</button><p>你的画布,由你定义。支持 PNG、JPEG、WebP。</p></div>}<div className={styles.leftFooter}><a href="/infinite_canvas">Infinite Canvas <ArrowUpRight size={14}/></a><small>⌘ Z 撤销 · 方向键微调 · Delete 删除</small></div></aside>
<main ref={viewport} className={styles.viewport} onPointerDown={e=>{setSelected('');panBoard(e)}}><div className={styles.canvasLabel}>画板 01 <span>800 × 1000</span></div><div className={styles.boardWrap} style={{width:800*zoom,height:1000*zoom,transform:`translate(${offset.x}px,${offset.y}px)`}}><div ref={board} className={styles.board} style={{background:doc.background,transform:`scale(${zoom})`}}>{doc.items.filter(i=>!i.hidden).map(i=><div key={i.id} tabIndex={0} role="button" aria-label={i.name} aria-pressed={selected===i.id} onFocus={()=>setSelected(i.id)} onPointerDown={e=>drag(e,i)} className={styles.element} data-selected={selected===i.id} style={{left:i.x,top:i.y,width:i.w,height:i.h,borderRadius:i.kind==='ellipse'?'50%':0,background:i.kind==='rect'||i.kind==='ellipse'?i.fill:undefined,color:i.fill,fontSize:i.size,whiteSpace:'pre-wrap'}}>{i.kind==='text'?i.text:i.kind==='image'?<img src={i.src} alt={i.name} draggable={false}/>:null}{selected===i.id&&<><i className={styles.corner} onPointerDown={resize}/><span className={styles.measure}>{Math.round(i.w)} × {Math.round(i.h)}</span></>}</div>)}{!doc.items.length&&<div className={styles.blankHint}><PenTool size={34} strokeWidth={1}/><h1>留白,是创作的起点。</h1><p>添加文字、图形,或放入你的第一张图片。</p><button onPointerDown={e=>e.stopPropagation()} onClick={()=>add('text')}>开始设计 <ArrowUpRight size={16}/></button></div>}</div></div><div className={styles.tools} onPointerDown={e=>e.stopPropagation()}><button title="选择" aria-label="选择工具" aria-pressed={tool==='select'} onClick={()=>{setTool('select');setSelected('')}}><MousePointer2 size={20}/></button><button title="抓手工具" aria-label="抓手工具" aria-pressed={tool==='hand'} onClick={()=>setTool('hand')}><Hand size={19}/></button><button title="文字" aria-label="添加文字" onClick={()=>add('text')}><Type size={20}/></button><button title="矩形" aria-label="添加矩形" onClick={()=>add('rect')}><Square size={19}/></button><button title="椭圆" aria-label="添加椭圆" onClick={()=>add('ellipse')}><Circle size={19}/></button><button title="图片" aria-label="上传图片" onClick={()=>upload.current?.click()}><ImagePlus size={19}/></button><span/><button aria-label="缩小" onClick={()=>setZoom(z=>Math.max(.15,z-.1))}><Minus size={16}/></button><output>{Math.round(zoom*100)}%</output><button aria-label="放大" onClick={()=>setZoom(z=>Math.min(2,z+.1))}><Plus size={16}/></button><button aria-label="适应画布" onClick={fit}><Scan size={18}/></button></div></main>
<aside className={styles.right}><div className={styles.inspectorTitle}>设计属性<span>Design</span></div>{item?<div className={styles.props}><label>图层名称<input maxLength={200} value={item.name} disabled={item.locked} onChange={e=>patch({name:e.target.value})}/></label><h3>布局</h3><div className={styles.fields}>{(['x','y','w','h'] as const).map(k=><label key={k}>{({x:'X',y:'Y',w:'宽',h:'高'})[k]}<input type="number" value={Math.round(item[k])} disabled={item.locked} onChange={e=>{const value=Number(e.target.value);if(Number.isFinite(value))patch({[k]:k==='w'||k==='h'?Math.max(1,Math.min(4000,value)):Math.max(-4000,Math.min(4000,value))})}}/></label>)}</div>{item.kind==='text'&&<><h3>文字</h3><textarea aria-label="文字内容" value={item.text} maxLength={4000} disabled={item.locked} onChange={e=>patch({text:e.target.value})}/><label>字号<input type="number" min={8} max={240} value={item.size} disabled={item.locked} onChange={e=>patch({size:Math.max(8,Math.min(240,Number(e.target.value)||8))})}/></label></>}<h3>填色</h3><label className={styles.color}><input type="color" value={item.fill} disabled={item.locked} onChange={e=>patch({fill:e.target.value})}/>{item.fill.toUpperCase()}</label><div className={styles.actions}><button onClick={duplicate}><Copy size={15}/>复制</button><button disabled={item.locked} onClick={remove}><Trash2 size={15}/>删除</button></div><button disabled={item.locked} onClick={()=>{const n=doc.items.findIndex(i=>i.id===item.id);if(n>0){const items=[...doc.items];[items[n-1],items[n]]=[items[n],items[n-1]];change({...doc,items})}}}>下移一层</button></div>:<div className={styles.props}><h3>画板</h3><p>自由画布 · 竖版</p><div className={styles.dimensions}>W <b>800</b> H <b>1000</b></div><h3>背景颜色</h3><label className={styles.color}><input type="color" value={doc.background} onChange={e=>change({...doc,background:e.target.value})}/>{doc.background.toUpperCase()}</label><div className={styles.note}><MousePointer2 size={20}/><p>选中一个图层,<br/>调整属于它的每个细节。</p></div></div>}<div className={styles.rightFooter}><button onClick={()=>download(JSON.stringify(doc,null,2),'application/json','json')}><Download size={15}/>备份设计 JSON</button><button onClick={()=>restore.current?.click()}>导入设计 JSON</button><p>草稿仅保存在此浏览器。<br/>邮箱登录共用全站账户。</p></div></aside></div>
<input ref={restore} hidden type="file" accept="application/json,.json" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;try{if(f.size>5*1024*1024)throw Error('文件不得超过 5MB');const restored=parseGraphicDocument(await f.text());change(restored);setSelected('');}catch(error){setStatus(error instanceof Error?error.message:'导入失败')}}}/>
<input ref={upload} hidden type="file" accept="image/png,image/jpeg,image/webp" onChange={e=>{const f=e.target.files?.[0];if(!f)return;if(f.size>3*1024*1024||!['image/png','image/jpeg','image/webp'].includes(f.type)){setStatus('请使用 3MB 以内的 PNG / JPEG / WebP');return}const reader=new FileReader();reader.onload=()=>add('image',String(reader.result));reader.readAsDataURL(f);e.target.value=''}}/>
{auth&&<div className={styles.overlay}><div ref={dialog} className={styles.modal} role="dialog" aria-modal="true" aria-label="邮箱账户"><button className={styles.close} aria-label="关闭" onClick={()=>setAuth(false)}><X size={20}/></button><span className={styles.modalIcon}><Brand compact/></span><h2>{user?'你的 Studio 账户':'把灵感带进 Studio'}</h2>{user?<><p>{user.email}</p><button onClick={async()=>{try{const r=await fetch('/api/account/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});if(!r.ok)throw Error();setUser(null);setAuth(false)}catch{setMessage('退出失败,请重试')}}}>退出登录</button></>:<><p>使用知识站的同一个邮箱账户</p><div className={styles.tabs}>{[['login','登录'],['register','注册'],['resend','重发邮件']].map(([v,t])=><button key={v} aria-pressed={mode===v} onClick={()=>setMode(v)}>{t}</button>)}</div><form onSubmit={account}><label>邮箱<input autoFocus required type="email" name="email" autoComplete="email" maxLength={254}/></label><label>密码<input required type="password" name="password" minLength={12} maxLength={256} autoComplete={mode==='register'?'new-password':'current-password'}/></label><small>密码至少 12 字符;新账户需通过邮件验证。</small><button className={styles.primary} disabled={busy}>{busy?'处理中…':mode==='login'?'登录 Studio':mode==='register'?'创建账户':'重发验证邮件'}</button></form></>}<p role="status">{message}</p></div></div>}
</div>
}
+44
View File
@@ -0,0 +1,44 @@
import type { GetServerSideProps } from "next";
import GuidanceReader, { type ReaderProps } from "@/components/GuidanceReader";
import { findGuide, guides } from "@/content/guides/catalog";
export default function Guide(props: ReaderProps) {
return <GuidanceReader {...props} />;
}
export const getServerSideProps: GetServerSideProps<ReaderProps> = async ({
params,
query,
}) => {
const r = query.revision;
if (r !== undefined && (typeof r !== "string" || !/^\d+$/.test(r)))
return { notFound: true };
const document = findGuide(
String(params?.id),
r === undefined ? undefined : Number(r),
);
if (!document) return { notFound: true };
return {
props: {
document,
source: "example",
versions: [{ revision: document.revision }],
links: document.links.map((link) => ({
...link,
resolved: !!findGuide(link.target, link.revision),
})),
backlinks: guides
.filter((g) =>
g.links.some(
(link) =>
link.target === document.id &&
link.revision === document.revision,
),
)
.map(({ id, title, revision }) => ({
id,
title,
revision,
source: "example",
})),
},
};
};
+22
View File
@@ -0,0 +1,22 @@
import { ThemeToggle } from "../components/ThemeToggle";
import { Brand } from "../components/Brand";
import Head from 'next/head';
import {ArrowUpRight, Workflow, Layers, ArrowRight} from 'lucide-react';
import {CreatorSketch, IdeaSketch} from "@/components/LandingSketches";
import s from '@/styles/landing.module.css';
export default function Home(){return <main className={s.page}>
<Head><title>啡跃 Endoleap · 让灵感,有形。</title><meta name="description" content="收藏灵感、连接知识,与熟悉的 Agent 一起,把想法变成作品。探索图形编辑器、无限画布与知识文档。"/></Head>
<nav className={s.nav} aria-label="主导航"><a className={s.logo} href="/"><Brand/></a><div><a href="#tools">创作工具</a><a href="/documents">知识与教程</a><a href="#workflow">工作方式</a></div><ThemeToggle/><a href="/account?next=/workspace">登录</a><a className={s.dark} href="/account?next=/workspace">进入工作台 <ArrowUpRight size={15}/></a></nav>
<section className={s.hero}><p className={s.eyebrow}>A SPACE FOR HUMAN IDEAS & AGENTS</p><h1>想法不该停在对话里。<br/><span>让灵感,有形。</span></h1><p className={s.intro}>从一闪而过的念头,到值得分享的作品。<br/>连接你的 coding agent,在一张画布上,把创作继续下去。</p><div className={s.actions}><a className={s.dark} href="/account?next=/workspace">开始创作 <ArrowRight size={17}/></a><a href="#tools">探索你的创作空间 ↓</a></div><div className={s.peopleStrip}><span className={s.stripNote}>每一种好奇,都有自己的起点。</span>{([
['collect','收藏生活的切片'],['read','遇见新的工作方法'],['idea','记下突然出现的灵感'],['dream','给想法一点自由'],['make','做一件属于你的作品']
] as const).map(([pose,label])=><figure key={pose}><CreatorSketch pose={pose}/><figcaption>{label}</figcaption></figure>)}<span className={s.stripSpark} aria-hidden="true">✳</span></div></section>
<section className={s.possibilities} id="possibilities" aria-labelledby="possibilities-title"><p className={s.eyebrow}>MAKE ROOM FOR WHAT COMES NEXT</p><h2 id="possibilities-title">给好奇心一点空间,<br/>让下一步<em>自然发生。</em></h2><div className={s.featureGrid}>{([
['collect','留住一闪而过','一句念头、一张参考图、一个还没想好的方向。先留下,再慢慢展开。'],
['connect','让线索相遇','把笔记、图片和提示词放上画布,用连接看见它们之间的新可能。'],
['read','找到有用的方法','阅读可独立使用的知识文档,需要更多背景时,沿链接继续探索。'],
['make','把创作继续下去','用熟悉的 coding agent 探索,再亲手调整细节,让想法成为自己的作品。']
] as const).map(([kind,title,copy])=><article key={kind}><IdeaSketch kind={kind}/><h3>{title}</h3><p>{copy}</p></article>)}</div></section>
<section className={s.tools} id="tools"><p className={s.eyebrow}>TWO TOOLS. ONE CREATIVE FLOW.</p><h2>给不同的想法,<br/>恰好的空间。</h2><div className={s.toolGrid}><a href="/graphic"><Layers/><span>01 / GRAPHIC</span><h3>把灵感排成作品。</h3><p>文字、图形与图片自由编排。精确调整图层和位置,把设计导出为 SVG。</p><div className={s.poster}><span>MAKE<br/>ROOM<br/><i>for ideas.</i></span><b>✳</b></div><strong>打开图形编辑器 <ArrowUpRight size={17}/></strong></a><a href="/infinite_canvas"><Workflow/><span>02 / INFINITE CANVAS</span><h3>让思路,自由生长。</h3><p>把笔记、参考图与提示词连成线索。在无限画布上平移、缩放,整理下一次创作。</p><div className={s.miniCanvas}><b>一个念头</b><i>⟶</i><b>一张参考</b><i>⟶</i><b>新的可能</b></div><strong>打开无限画布 <ArrowUpRight size={17}/></strong></a></div></section>
<section className={s.reading} aria-labelledby="reading-title"><div><p className={s.eyebrow}>GOOD IDEAS DESERVE GOOD COMPANY</p><h2 id="reading-title">不必每一次,<br/>都从空白开始。</h2><p>把有用的工作方法,留给下一次的自己。<br/>一篇文档讲清一件事,需要时再沿着链接走远一点。</p><a href="/documents">去知识空间逛逛 <ArrowUpRight size={16}/></a></div><div className={s.readingArt} aria-hidden="true"><span>读到这里,<br/><em>想到了什么?</em></span><CreatorSketch pose="read"/><small>READ. CONNECT. MAKE.</small><svg viewBox="0 0 440 380"><path d="M35 105q-20-55 35-64m-15 0 17-2-8 17M348 267q46 33 32 68m-14-13 14 15 14-13"/></svg></div></section>
<section className={s.workflow} id="workflow"><div><p className={s.eyebrow}>YOUR AGENT. YOUR WORKFLOW.</p><h2>用熟悉的 Agent,<br/>继续你的创作。</h2><p>通过项目已有的 API 与文档,让 coding agent 理解模板和创作内容。画布负责呈现,你来决定下一步。</p><a href="/studio/api">查看 Agent 接入文档 <ArrowUpRight size={16}/></a></div><ol><li><b>01</b><div><h3>找到起点</h3><p>从空白设计、素材或一段灵感出发。</p></div></li><li><b>02</b><div><h3>连接工作方式</h3><p>将接入文档交给你的 coding agent。</p></div></li><li><b>03</b><div><h3>亲手打磨,保存作品</h3><p>在编辑器中调整细节,导出并保留备份。</p></div></li></ol></section>
<section className={s.end}><div className={s.endWall} aria-hidden="true">{(['collect','read','connect','make'] as const).map(kind=><div key={kind}><IdeaSketch kind={kind}/><i/><i/><i/></div>)}</div><div className={s.endContent}><p className={s.eyebrow}>YOUR NEXT IDEA STARTS HERE</p><h2>给下一个念头,<br/><em>留一个起点。</em></h2><p>不用想好全部。带着一点好奇,先开始。</p><a className={s.dark} href="/account?next=/workspace">进入你的工作台 <ArrowRight size={17}/></a><a className={s.endSecondary} href="/documents">或先读一篇有用的文档 ↗</a></div></section><footer className={s.footer}><a className={s.logo} href="/"><Brand/></a><span>给想法留白,给创作空间。</span><a href="/documents">知识与教程 ↗</a></footer></main>}
@@ -0,0 +1,60 @@
import { ThemeToggle } from "../../studio/components/ThemeToggle";
import { Brand } from "../../studio/components/Brand";
import Head from 'next/head';
import {useEffect,useRef,useState} from 'react';
import {ArrowLeft,Plus,MousePointer2,Hand,ImagePlus,Type,Workflow,Undo2,Redo2,Minus,Maximize,Download,Upload,Trash2,Link2,Sparkles,ChevronRight,Sun,Moon} from 'lucide-react';
import s from '../../studio/styles/infinite-canvas.module.css';
import CanvasNodeView from '../../studio/components/canvas/CanvasNodeView';
import CanvasComposer from '../../studio/components/canvas/CanvasComposer';
import CanvasAgentPanel,{type CanvasAgentHandle} from '../../studio/components/canvas/CanvasAgentPanel';
import {parseCanvasDocument,deriveNode,connectNodes,removeCanvasNode,referencedNodes,agentTask,type CanvasNode as Card,type CanvasDocument as Doc} from '../../studio/lib/canvas-document';
const example:Doc={version:1,cards:[{id:'brief',kind:'text',title:'01 / 创意简报',text:'把日常,拍成一场电影。\n\n一段关于城市清晨的视觉散文。低饱和色彩、自然光与细腻颗粒,让每一帧都有呼吸感。',x:70,y:140},{id:'reference',kind:'image',title:'02 / 视觉参考',text:'晨光 · 建筑 · 胶片质感\n上传你的参考图片',x:460,y:80},{id:'shot',kind:'prompt',title:'03 / 镜头构思',text:'清晨,阳光穿过窗边的植物,落在安静的房间里。缓慢推进镜头,35mm 胶片,温暖柔和的光线。',x:850,y:160}],links:[['brief','reference'],['reference','shot']]};
const initial:Doc={version:1,cards:[],links:[]};
const key='studio.infinite-canvas.v1';
export default function InfiniteCanvas(){
const [doc,setDoc]=useState<Doc>(initial),[selected,select]=useState('shot'),[zoom,setZoom]=useState(.8),[pan,setPan]=useState({x:0,y:0}),[tool,setTool]=useState('select'),[past,setPast]=useState<Doc[]>([]),[future,setFuture]=useState<Doc[]>([]),[status,setStatus]=useState('示例项目 · 尚未保存'),[ready,setReady]=useState(false),[email,setEmail]=useState(''),[link,setLink]=useState(''),[menu,setMenu]=useState<{x:number;y:number}|null>(null),[editing,setEditing]=useState(''),[refMenu,setRefMenu]=useState(''),[taskFeedback,setTaskFeedback]=useState(''),[composerTarget,setComposerTarget]=useState(''),[pickerRequest,setPickerRequest]=useState(0);
const file=useRef<HTMLInputElement>(null),json=useRef<HTMLInputElement>(null),viewport=useRef<HTMLDivElement>(null),drag=useRef<{id:string;x:number;y:number;ox:number;oy:number;before:Doc;resize?:boolean}|null>(null);
const pickerSequence=useRef(0),agent=useRef<CanvasAgentHandle>(null);
const active=doc.cards.find(c=>c.id===selected);
useEffect(()=>{try{const raw=localStorage.getItem(key);if(raw){const d=parseCanvasDocument(raw);setDoc(d);setStatus('已恢复本机草稿')}}catch{setStatus('草稿读取失败,可导入 JSON 恢复')}try{const v=JSON.parse(localStorage.getItem(key+'.view')||'null');if(v&&Number.isFinite(v.zoom)&&v.zoom>=.2&&v.zoom<=2&&Number.isFinite(v.x)&&Number.isFinite(v.y)){setZoom(v.zoom);setPan({x:v.x,y:v.y})}}catch{}setReady(true);fetch('/api/account/session').then(r=>r.ok?r.json():null).then(d=>setEmail(d?.user?.email||'')).catch(()=>{});},[]);
useEffect(()=>{if(!ready)return;try{localStorage.setItem(key,JSON.stringify(doc));setStatus('已保存到此浏览器')}catch{setStatus('本机空间不足,请导出项目备份')}},[doc,ready]);
useEffect(()=>{if(ready)try{localStorage.setItem(key+'.view',JSON.stringify({...pan,zoom}))}catch{}},[pan,zoom,ready]);
useEffect(()=>{const el=viewport.current;if(!el)return;const block=(e:WheelEvent)=>{if(!(e.target as HTMLElement).closest('textarea,input,select'))e.preventDefault()};el.addEventListener('wheel',block,{passive:false});return()=>el.removeEventListener('wheel',block)},[]);
useEffect(()=>{const keys=(e:KeyboardEvent)=>{if(e.key==='Escape'){setMenu(null);setRefMenu('');setEditing('');return}if((e.target as HTMLElement).closest('input,textarea,select,[contenteditable]'))return;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();if(e.shiftKey)redo();else undo()}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='d'){e.preventDefault();duplicate()}};window.addEventListener('keydown',keys);return()=>window.removeEventListener('keydown',keys)});
function scaleAt(next:number,cx?:number,cy?:number){const el=viewport.current;if(!el)return;const r=el.getBoundingClientRect(),x=cx===undefined?r.width/2:cx-r.left,y=cy===undefined?r.height/2:cy-r.top;const z=Math.max(.2,Math.min(2,next));setPan({x:x-(x-pan.x)*z/zoom,y:y-(y-pan.y)*z/zoom});setZoom(z)}
function duplicate(){if(!active||doc.cards.length>=80)return;const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');commit({...doc,cards:[...doc.cards,{...active,id,title:active.title.slice(0,197)+' 副本',x:active.x+40,y:active.y+40}]});select(id)}
function commit(next:Doc){setPast(p=>[...p.slice(-29),doc]);setFuture([]);setDoc(next)}
function add(kind:Card['kind'],image?:string){if(doc.cards.length>=80){setStatus('最多 80 个节点');return}const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');const rect=viewport.current?.getBoundingClientRect();commit({...doc,cards:[...doc.cards,{id,kind,title:kind==='text'?'灵感笔记':kind==='image'?'图片节点':kind==='script'?'脚本生成器':'生成提示词',text:'',x:((menu?.x??(rect?.width||700)/2)-pan.x)/zoom-160,y:((menu?.y??(rect?.height||600)/2)-pan.y)/zoom-100,image}]});select(id)}
function change(field:'title'|'text'|'instruction',value:string,id=selected){setDoc(d=>({...d,cards:d.cards.map(c=>c.id===id?{...c,[field]:value}:c)}))}
function beginEdit(){setPast(p=>[...p.slice(-29),doc]);setFuture([])}
function undo(){if(!past.length)return;setFuture(f=>[doc,...f]);setDoc(past[past.length-1]);setPast(p=>p.slice(0,-1))}
function redo(){if(!future.length)return;setPast(p=>[...p,doc]);setDoc(future[0]);setFuture(f=>f.slice(1))}
function fit(){const el=viewport.current;if(!el||!doc.cards.length)return;const minX=Math.min(...doc.cards.map(c=>c.x)),minY=Math.min(...doc.cards.map(c=>c.y));const w=Math.max(...doc.cards.map(c=>c.x+(c.width||320)))-minX,h=Math.max(...doc.cards.map(c=>c.y+(c.height||350)))-minY;const z=Math.max(.2,Math.min(1,(el.clientWidth-80)/w,(el.clientHeight-100)/h));setZoom(z);setPan({x:(el.clientWidth-w*z)/2-minX*z,y:(el.clientHeight-h*z)/2-minY*z})}
function selectNode(id:string){if(id!==selected)setEditing('');select(id)}
function editNode(id:string){setPickerRequest(0);setComposerTarget('');select(id);setEditing(id);setMenu(null);setRefMenu('');setTaskFeedback('');setTool('select')}
function patchNode(id:string,patch:Partial<Card>){commit({...doc,cards:doc.cards.map(n=>n.id===id?{...n,...patch}:n)})}
function derive(source:string,kind:Card['kind'],operation:Card['operation']='generate'){
const parent=doc.cards.find(n=>n.id===source);if(!parent)return;
const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');
const title=operation==='upscale'?'图片高清':kind==='script'?'脚本生成器':kind==='image'?'图片节点':'文本节点';
try{commit(deriveNode(doc,source,{id,kind,operation,title,text:'',x:parent.x+(parent.width||320)+150,y:parent.y,width:360,height:300}));editNode(id);setComposerTarget(id)}catch(e){setStatus(e instanceof Error?e.message:'无法创建节点')}
}
function connect(from:string,to:string){try{const next=connectNodes(doc,from,to);if(next!==doc)commit(next);setTaskFeedback('')}catch(e){setTaskFeedback(e instanceof Error?e.message:'无法引用节点')}}
function exportTask(id:string){try{const task=agentTask(doc,id),url=URL.createObjectURL(new Blob([JSON.stringify(task,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=`canvas-task-${id}.json`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);setTaskFeedback('Agent 任务已导出')}catch(e){setTaskFeedback(e instanceof Error?e.message:'无法导出任务')}}
function exportDoc(){const url=URL.createObjectURL(new Blob([JSON.stringify(doc,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='studio-canvas.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
return <main className={s.app}><Head><title>无限画布 · 啡跃 Endoleap</title><meta name="description" content="在无限画布上组织灵感、参考素材与镜头提示词"/></Head>
<header className={s.header}><a href="/workspace" className={s.back} aria-label="返回 Studio"><ArrowLeft size={18}/></a><a href="/workspace" className={s.brand}><Brand compact/></a><i/><span className={s.crumb}>工作空间 <ChevronRight size={13}/></span><strong>未命名的灵感宇宙</strong><span className={s.badge}>本机草稿</span><div className={s.spacer}/><CanvasAgentPanel ref={agent} document={doc} email={email} onLoad={next=>{setDoc(next);setPast([]);setFuture([]);setEditing('');select('')}} onFeedback={setTaskFeedback}/><ThemeToggle/><a href="/account">{email||'登录账户'}</a><button className={s.export} onClick={exportDoc}><Download size={15}/>导出项目</button></header>
<div className={s.workspace}><nav className={s.rail} aria-label="画布工具"><button title="选择工具" aria-label="选择工具" aria-pressed={tool==='select'} onClick={()=>setTool('select')}><MousePointer2/></button><button title="移动画布" aria-label="移动画布" aria-pressed={tool==='hand'} onClick={()=>setTool('hand')}><Hand/></button><hr/><button title="添加笔记" aria-label="添加笔记" onClick={()=>add('text')}><Type/></button><button title="上传图片" aria-label="上传图片" onClick={()=>file.current?.click()}><ImagePlus/></button><button title="添加提示词" aria-label="添加提示词" onClick={()=>add('prompt')}><Sparkles/></button><button title="导入项目" aria-label="导入项目" onClick={()=>json.current?.click()}><Upload/></button><div className={s.spacer}/><span>∞</span></nav>
<section className={s.canvasArea}>{!doc.cards.length&&<div className={s.startPanel}><span>YOUR NEXT IDEA STARTS HERE</span><h2>给想法,一个无限的空间。</h2><p>双击画布添加节点,或选择一个起点。</p><div><button onClick={()=>add('text')}><Type size={19}/>灵感笔记</button><button onClick={()=>file.current?.click()}><ImagePlus size={19}/>参考图片</button><button onClick={()=>add('prompt')}><Sparkles size={19}/>创作提示词</button></div><button onClick={()=>{commit(example);select('');setPan({x:0,y:0});setZoom(.7)}}>从示例开始 ↗</button><a href="/studio/api" target="_blank" rel="noreferrer">连接你的 coding agent · 接入文档 ↗</a></div>}<div className={s.canvasTitle}><span className={s.eyebrow}>YOUR IDEAS, CONNECTED</span><h1>无限画布<span> / Infinite canvas</span></h1><p>从一个灵感,连接所有可能。</p></div>
<div className={s.viewport} style={{backgroundPosition:`${pan.x}px ${pan.y}px`,backgroundSize:`${24*zoom*Math.max(1,2**Math.ceil(Math.log2(1/zoom)))}px ${24*zoom*Math.max(1,2**Math.ceil(Math.log2(1/zoom)))}px`}} ref={viewport} onDoubleClick={e=>{if(e.target===e.currentTarget){setMenu(null);add('text')}}} onContextMenu={e=>{e.preventDefault();const id=(e.target as HTMLElement).closest('[data-node-id]')?.getAttribute('data-node-id');select(id||'');setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-330)})}} onWheel={e=>{const target=e.target as HTMLElement;if(drag.current)return;if(target.closest('textarea,input,select'))return;if(e.ctrlKey||e.metaKey){scaleAt(zoom*Math.exp(-e.deltaY*.002),e.clientX,e.clientY)}else setPan(p=>({x:p.x-e.deltaX,y:p.y-e.deltaY}))}} onPointerDown={e=>{setMenu(null);setRefMenu('');if(e.target===e.currentTarget){setEditing('');select('')};if(e.target===e.currentTarget||(tool==='hand'&&!(e.target as HTMLElement).closest('input,textarea,button,select'))||e.button===1){e.currentTarget.setPointerCapture(e.pointerId);drag.current={id:'pan',x:e.clientX,y:e.clientY,ox:pan.x,oy:pan.y,before:doc}}}} onPointerMove={e=>{const d=drag.current;if(!d)return;if(d.id==='pan')setPan({x:d.ox+e.clientX-d.x,y:d.oy+e.clientY-d.y});else {if(!d.resize&&Math.hypot(e.clientX-d.x,e.clientY-d.y)<4)return;e.currentTarget.setPointerCapture(e.pointerId);setDoc({...d.before,cards:d.before.cards.map(c=>c.id===d.id?(d.resize?{...c,width:Math.max(260,Math.min(1200,d.ox+(e.clientX-d.x)/zoom)),height:Math.max(300,Math.min(1200,d.oy+(e.clientY-d.y)/zoom))}:{...c,x:d.ox+(e.clientX-d.x)/zoom,y:d.oy+(e.clientY-d.y)/zoom}):c)})}}} onPointerUp={e=>{const d=drag.current;if(d?.id==='pan'&&tool==='select'&&Math.hypot(e.clientX-d.x,e.clientY-d.y)<4){select('');setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-230)})}if(d&&d.id!=='pan'&&doc!==d.before){setPast(p=>[...p.slice(-29),d.before]);setFuture([])}drag.current=null}} onPointerCancel={()=>{if(drag.current?.id!=='pan'&&drag.current)setDoc(drag.current.before);drag.current=null}}>
<div className={s.world} style={{transform:`translate(${pan.x}px,${pan.y}px) scale(${zoom})`}}><svg className={s.wires} aria-hidden="true">{doc.links.map(([a,b])=>{const from=doc.cards.find(c=>c.id===a),to=doc.cards.find(c=>c.id===b);if(!from||!to)return null;return <path key={a+b} d={`M ${from.x+(from.width||320)} ${from.y+(from.height||350)/2} C ${from.x+(from.width||320)+70} ${from.y+(from.height||350)/2},${to.x-45} ${to.y+(to.height||350)/2},${to.x} ${to.y+(to.height||350)/2}`}/>})}</svg>
{doc.cards.map(c=><CanvasNodeView key={c.id} node={c} selected={selected===c.id} editing={editing===c.id&&composerTarget!==c.id} hand={tool==='hand'} onSelect={()=>selectNode(c.id)} onChooseReference={()=>{editNode(c.id);setComposerTarget(c.id);setPickerRequest(++pickerSequence.current)}} onEdit={()=>editNode(c.id)} onDrag={e=>{setMenu(null);if(c.id!==editing)setEditing('');drag.current={id:c.id,x:e.clientX,y:e.clientY,ox:c.x,oy:c.y,before:doc}}} onResize={e=>{viewport.current?.setPointerCapture(e.pointerId);select(c.id);drag.current={id:c.id,x:e.clientX,y:e.clientY,ox:c.width||320,oy:c.height||350,before:doc,resize:true}}} onChange={value=>change('text',value,c.id)} onRename={value=>change('title',value,c.id)} onStyle={style=>patchNode(c.id,{style})} onReference={e=>{select(c.id);setRefMenu(c.id);setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-230)})}} onMenu={e=>{select(c.id);setRefMenu('');setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-330)})}} onUpload={()=>{select(c.id);file.current?.click()}} onUpscale={()=>derive(c.id,'image','upscale')} onExpand={()=>patchNode(c.id,{width:Math.min(1200,(c.width||320)*1.5),height:Math.min(1200,(c.height||350)*1.3)})} onBeginEdit={beginEdit}/>)}
</div></div><div className={s.canvasBottom}><span role="status">● {status}</span><div className={s.controls}><button aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={16}/></button><button aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={16}/></button><i/><button aria-label="缩小" onClick={()=>scaleAt(zoom-.1)}><Minus size={16}/></button><span>{Math.round(zoom*100)}%</span><button aria-label="放大" onClick={()=>scaleAt(zoom+.1)}><Plus size={16}/></button><button aria-label="适应画布" onClick={fit}><Maximize size={16}/></button></div></div></section>
{menu&&<div className={s.contextMenu} role="dialog" aria-label="画布操作" style={{left:Math.max(8,menu.x),top:Math.max(8,menu.y)}}><div className={s.menuTitle}>{refMenu?'引用该节点生成':active?active.title:'添加到画布'}<button aria-label="关闭画布操作" onClick={()=>setMenu(null)}>×</button></div>{refMenu?<>{(['text','image','script'] as const).map(kind=><button key={kind} onClick={()=>derive(refMenu,kind,kind==='script'?'script':'generate')}>{kind==='text'?'文本':kind==='image'?'图片':'脚本'}</button>)}</>:active?<><button onClick={()=>{editNode(active.id);setComposerTarget(active.id)}}>创作要求</button><button onClick={duplicate}>复制节点</button><button onClick={()=>{commit(removeCanvasNode(doc,selected));select('');setEditing('');setMenu(null)}}>删除节点</button><label>连接到<select value={link} onChange={e=>setLink(e.target.value)}><option value="">选择目标节点</option>{doc.cards.filter(c=>c.id!==selected).map(c=><option key={c.id} value={c.id}>{c.title}</option>)}</select></label><button disabled={!link} onClick={()=>{connect(selected,link);setLink('')}}>连接节点</button>{doc.links.filter(l=>l.includes(selected)).map(([a,b])=><button key={a+b} onClick={()=>commit({...doc,links:doc.links.filter(l=>l[0]!==a||l[1]!==b)})}>断开:{doc.cards.find(c=>c.id===(a===selected?b:a))?.title}</button>)}</>:<><button onClick={()=>{add('text');setMenu(null)}}>添加笔记</button><button onClick={()=>{add('image');setMenu(null)}}>添加图片</button><button onClick={()=>{add('script');setMenu(null)}}>添加脚本</button></>}</div>}</div>
{active&&editing===active.id&&(active.kind!=='text'||composerTarget===active.id)&&<CanvasComposer pickerRequest={pickerRequest} key={active.id} node={active} nodes={doc.cards} references={referencedNodes(doc,active.id)} onChange={value=>change('instruction',value,active.id)} onRename={value=>change('title',value,active.id)} onBeginEdit={beginEdit} onUpload={()=>file.current?.click()} onAddReference={id=>connect(id,active.id)} onRemoveReference={id=>commit({...doc,links:doc.links.filter(([from,to])=>from!==id||to!==active.id)})} onQueue={()=>void agent.current?.queue(active.id)} onExport={()=>exportTask(active.id)} onClose={()=>setEditing('')} feedback={taskFeedback}/>}
<input hidden ref={file} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;if(!['image/png','image/jpeg','image/webp'].includes(f.type)||f.size>2000000){setStatus('请选择 2MB 以内的 PNG、JPEG 或 WebP');return}const reader=new FileReader();reader.onload=()=>{const image=String(reader.result);if(active?.kind==='image')commit({...doc,cards:doc.cards.map(c=>c.id===selected?{...c,image}:c)});else add('image',image)};reader.readAsDataURL(f)}}/>
<input hidden ref={json} type="file" accept="application/json,.json" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;try{if(f.size>15000000)throw Error();const d=parseCanvasDocument(await f.text());commit(d);select(d.cards[0]?.id||'');setPan({x:0,y:0});setStatus('项目已导入')}catch{setStatus('无法导入:项目格式错误或文件过大')}}}/>
</main>;
}
@@ -0,0 +1,26 @@
import type { GetServerSideProps } from "next";
import Head from "next/head";
import { useState,type FormEvent } from "react";
import { useRouter } from "next/router";
import { Upload,Image,Film,AudioLines,ArrowUpRight,X,Check } from "lucide-react";
import {TagInput} from "@/components/TagInput";
import { Shell } from "@/components/Shell";
import { tags } from "@/lib/library";
import type { Tag } from "@/lib/model";
export default function Import({allTags}:{allTags:Tag[]}){
const router=useRouter();const [kind,setKind]=useState(['image','video','audio'].includes(String(router.query.kind))?String(router.query.kind):'image');
const [files,setFiles]=useState<File[]>([]);const [title,setTitle]=useState('');const [description,setDescription]=useState('');const [selected,setSelected]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
function choose(list:FileList|null){if(!list)return;const items=Array.from(list);setFiles(items);if(!title&&items[0])setTitle(items[0].name.replace(/\.[^.]+$/,''));}
async function submit(e:FormEvent){e.preventDefault();setError('');setBusy(true);try{const data=new FormData();data.set('kind',kind);data.set('title',title);data.set('description',description);data.set('tags',JSON.stringify(selected));files.forEach(f=>data.append('files',f));const res=await fetch('/api/upload',{method:'POST',body:data});const result=await res.json();if(!res.ok)throw new Error(result.error);await router.push('/explore/'+result.id);}catch(e){setError(e instanceof Error?e.message:'上传失败');}finally{setBusy(false);}}
return <Shell><Head><title>素材入库 · 啡跃 Endoleap</title></Head><header className="page-header"><div><span className="eyebrow">MAKE ROOM FOR INSPIRATION</span><h1>导入素材</h1><p>支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。</p></div></header><form className="editor-panel" onSubmit={submit}>
<div className="kind-picker">{[{id:'image',name:'图片',Icon:Image},{id:'video',name:'视频',Icon:Film},{id:'audio',name:'声音',Icon:AudioLines}].map(t=><button type="button" key={t.id} disabled={busy} className={kind===t.id?'selected':''} onClick={()=>{setKind(t.id);setFiles([]);}}><t.Icon size={19}/>{t.name}</button>)}</div>
<label className="drop-zone" onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault();if(!busy)choose(e.dataTransfer.files);}}><input type="file" multiple disabled={busy} accept={kind==='image'?'image/jpeg,image/png,image/webp,image/gif,image/avif':kind+'/*'} onChange={e=>choose(e.target.files)}/><span className="upload-circle"><Upload size={24}/></span><strong>选择文件或拖放到这里</strong><span>最多 16 个文件,单个不超过 250 MB</span></label>
{files.length>0&&<ul className="file-list">{files.map((f,i)=><li key={i}><Check size={15}/><span>{f.name}</span><small>{(f.size/1024/1024).toFixed(1)} MB</small><button type="button" aria-label={`移除 ${f.name}`} disabled={busy} onClick={()=>setFiles(a=>a.filter((_,j)=>i!==j))}><X size={14}/></button></li>)}</ul>}
<div className="form-field"><label htmlFor="title">标题</label><input id="title" required maxLength={200} value={title} onChange={e=>setTitle(e.target.value)} placeholder="添加标题"/></div>
<div className="form-field"><label htmlFor="description">描述 <small>选填</small></label><textarea id="description" maxLength={100000} rows={4} value={description} onChange={e=>setDescription(e.target.value)} placeholder="拍摄场景、灵感、下次想怎么用…"/></div>
<TagInput initial={allTags} selected={selected} onChange={setSelected} disabled={busy}/>
{kind==='video'&&<p className="form-note">视频入库后会自动分离画面和声音。有声、无声都会标记;生成的静音视频、音轨和封面会作为资源链接附在这篇笔记中。</p>}
{error&&<p role="alert" className="error-message">{error}</p>}<div className="form-actions"><span>原文件独立保存,素材包只记录引用。</span><button className="primary-button" disabled={!files.length||busy}>{busy?'正在入库,请稍候…':'导入素材'}<ArrowUpRight size={16}/></button></div>
</form></Shell>;
}
export const getServerSideProps:GetServerSideProps=async()=>({props:{allTags:await tags()}});
+17
View File
@@ -0,0 +1,17 @@
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useState, type FormEvent } from 'react';
// Keep this page independent of server-only authentication modules.
export default function Login() {
const router = useRouter(); const [code,setCode] = useState(''); const [error,setError] = useState(''); const [busy,setBusy] = useState(false);
async function submit(event: FormEvent) {
event.preventDefault(); if (busy) return; setBusy(true); setError('');
try {
const response = await fetch('/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code})});
const data = await response.json(); if (!response.ok) { setError(data.error || '登录没有完成'); setCode(''); return; }
const next = router.query.next;
window.location.assign(typeof next === 'string' && next.startsWith('/') && !next.startsWith('//') && !/[\\\r\n]/.test(next) && !next.startsWith('/login') ? next : '/');
} catch { setError('暂时无法连接,请稍后重试'); } finally { setBusy(false); }
}
return <><Head><title>动态码登录 · 啡跃 Endoleap</title><meta name="robots" content="noindex,nofollow"/></Head><main className="auth-page"><form className="auth-card" onSubmit={submit}><img className="auth-logo" src="/brand/icon-dark.svg" width={64} height={64} alt="啡跃 Endoleap"/><h1>输入动态码</h1><p className="auth-description">打开验证器,输入当前的 6 位动态码。</p><label htmlFor="auth-code">动态码</label><input id="auth-code" autoFocus inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{6}" maxLength={6} required value={code} onChange={e=>setCode(e.target.value.replace(/\D/g,''))} placeholder="000000" aria-describedby="auth-error"/><div id="auth-error" role="alert" className="auth-error">{error}</div><button type="submit" disabled={busy || code.length !== 6}>{busy ? '正在验证…' : '进入知识库'}</button><p className="auth-footnote">尚未绑定验证器?请联系管理员。</p></form></main></>;
}
+5
View File
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {publicPostId} from '@/lib/model';
import {getPost} from '@/lib/library';
export default function LegacyPost(){return null;}
export const getServerSideProps:GetServerSideProps=async({params,query})=>{const post=await getPost(String(params?.slug||''));return post?{redirect:{destination:'/explore/'+publicPostId(post)+(String(query.agent_mode||'').toLowerCase()==='true'?'?agent_mode=True':''),permanent:true}}:{notFound:true};};
+202
View File
@@ -0,0 +1,202 @@
import Link from "next/link";
import {
ArrowUpRight,
BookOpen,
Bot,
Braces,
GitBranch,
Link2,
ShieldCheck,
Target,
} from "lucide-react";
import GuidanceShell from "@/components/GuidanceShell";
import { CopyButton, KindBadge, PageHeading } from "@/components/GuidanceUI";
import { guides, guidanceXml } from "@/content/guides/catalog";
import s from "@/styles/guidance.module.css";
const sections = [
["idea", "独立文档"],
["start", "开始读取"],
["syntax", "文档语法"],
["relations", "三种关系"],
["reading", "读取约定"],
["permissions", "权限边界"],
["status", "协议状态"],
];
export default function Protocol() {
const xml = guidanceXml(guides[0]);
return (
<GuidanceShell title="文档协议">
<PageHeading
title="从一篇文档,连接下一种可能。"
description="Linked Guidance 0.1 · 为独立指导文档设计的实验协议"
eyebrow="DOCUMENTATION"
>
<a
href="/agent/index.md"
target="_blank"
rel="noreferrer"
className={s.secondaryButton}
>
<Bot size={15} />
Agent 读取入口
<ArrowUpRight size={13} />
</a>
</PageHeading>
<div className={s.protocolLayout}>
<article className={`${s.panel} ${s.protocolArticle}`}>
<section id="idea" className={s.proseSection}>
<h2>
<BookOpen size={17} />
文档是起点,集合只是组织方式
</h2>
<p>
每篇文档都有完整正文、适用条件和固定版本。Coding agent 与 personal
agent
都可以从一篇文档开始;需要更多帮助时,再判断关联链接是否适合当前任务。无需把一整组文档一起安装或加载。
</p>
</section>
<section id="start" className={s.proseSection}>
<h2>
<Target size={17} />
从哪里开始
</h2>
<p>
先通过目录发现摘要,再读取一篇文档的固定版本。人的阅读界面与 Agent
的 XML 接口引用同一份内容。
</p>
<div className={s.buttonRow} style={{ marginTop: 16 }}>
<Link className={s.secondaryButton} href="/">
探索文档
<ArrowUpRight size={13} />
</Link>
<Link className={s.secondaryButton} href="/documents">
社区文档
<ArrowUpRight size={13} />
</Link>
<Link className={s.secondaryButton} href="/write">
发布文档
<ArrowUpRight size={13} />
</Link>
</div>
<code className={s.machineAddress}>/agent/index.md</code>
<CopyButton
label="复制 Agent 入口"
value={() => window.location.origin + "/agent/index.md"}
/>
</section>
<section id="syntax" className={s.proseSection}>
<h2>
<Braces size={17} />
一份可独立读取的文档
</h2>
<p>
XML 描述文档本身,以及何时可能需要其他文档。固定 revision
保留精确引用;未知版本与缺失目标需要明确处理。
</p>
<pre className={s.codeBlock}>{xml}</pre>
<CopyButton label="复制示例 XML" value={xml} />
</section>
<section id="relations" className={s.proseSection}>
<h2>
<Link2 size={17} />
把关系写清楚
</h2>
<p>
链接是有条件的阅读建议,不是强制依赖。when
用自然语言说明何时可能需要目标文档。
</p>
<div className={s.relationGrid}>
<div>
<KindBadge kind="guide" />
<p>可供采用的工作方法。仍需先判断是否适用,并遵守用户授权。</p>
</div>
<div>
<KindBadge kind="context" />
<p>用于理解任务的背景知识,不会自动成为操作指令。</p>
</div>
<div>
<KindBadge kind="evidence" />
<p>为判断提供事实与依据。引用时需要保留实际来源和版本。</p>
</div>
</div>
</section>
<section id="reading" className={s.proseSection}>
<h2>
<GitBranch size={17} />
按需读取,固定版本
</h2>
<ol>
<li>先看入口文档的适用条件,再读正文与步骤。</li>
<li>只跟随 when 条件成立、且能补充当前任务所需知识的链接。</li>
<li>
以文档 ID 与版本去重,默认读取预算为 8 篇、最大深度 3 层。
</li>
<li>
固定版本缺失时不静默回退最新版;遇到循环或预算耗尽时停止扩展,并说明未完成的读取。
</li>
</ol>
</section>
<section id="permissions" className={s.proseSection}>
<h2>
<ShieldCheck size={17} />
权限不会沿链接传播
</h2>
<p>
读取文档不等于接受其中所有指令。用户任务和运行环境规则始终优先,文档不能要求获取秘密、扩大权限或改变目标。0.1
只引用本站逻辑 ID,不自动请求任意外部 URL,也不执行 XML
实体或脚本。
</p>
</section>
<section id="status" className={s.proseSection}>
<h2>协议状态</h2>
<p>
Linked Guidance 是本项目提出的实验协议,并非现有 Agent
已原生支持的标准。当前支持独立 XML/JSON
读取、已验证邮箱作者发布,以及不可变版本;跨站发现与原生 Agent
适配仍待实现。
</p>
<div className={s.protocolCallout}>
<p>
研究起点:
<a
className={s.textLink}
href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f"
target="_blank"
rel="noreferrer"
>
Karpathy 的 LLM Wiki 提案
<ArrowUpRight size={11} />
</a>
。本项目在持久交叉引用的基础上,提出独立指导单元、条件链接、关系类型和版本约定。
</p>
</div>
</section>
</article>
<aside className={s.readingSidebar}>
<section className={s.sideCard}>
<h3>本页目录</h3>
<nav className={s.toc} aria-label="协议目录">
{sections.map(([id, label]) => (
<a href={"#" + id} key={id}>
{label}
</a>
))}
</nav>
</section>
<section className={s.sideCard}>
<h3>开始编写你的第一篇</h3>
<p>从适用条件与清晰正文开始。关联链接可以在需要时再补充。</p>
<Link
className={s.textLink}
href="/write"
style={{ marginTop: 14 }}
>
创建文档
<ArrowUpRight size={12} />
</Link>
</section>
</aside>
</div>
</GuidanceShell>
);
}
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {getGuidance} from '@/content/skills/guidance';
import {guidanceUrl} from '@/content/page-links';
export default function Legacy(){return null;}
export const getServerSideProps:GetServerSideProps=async({params,query})=>{const parts=params?.path;if(parts===undefined)return {redirect:{destination:'/categories',permanent:false}};const path=Array.isArray(parts)?parts.join('/'):String(parts);return getGuidance(path)?{redirect:{destination:guidanceUrl(path)+(String(query.agent_mode||'').toLowerCase()==='true'?'?agent_mode=True':''),permanent:true}}:{notFound:true};};
@@ -0,0 +1,11 @@
import type {GetServerSideProps} from 'next';
import {readDesign} from '../../../studio/lib/design-server';
import {designUrl} from '../../../studio/lib/native-layout';
export default function DesignPage(){return null}
export const getServerSideProps:GetServerSideProps=async({params,req,res})=>{
res.setHeader('Cache-Control','private, no-store');
const design=await readDesign(params?.id,req);
if(!design)return {notFound:true};
// The unified application has no basePath; keep the full historical URL.
return {redirect:{destination:designUrl(design.layoutId,design.id),permanent:false}};
};
@@ -0,0 +1,10 @@
import type {GetStaticPaths,GetStaticProps} from 'next';
import Head from 'next/head';
import Link from 'next/link';
import {LayoutSelection} from '../../../studio/components/LayoutSelection';
import {tutorialPost} from '../../../studio/content/tool-links';
import {TemplateTrial} from '../../../studio/components/TemplateTrial';
import {ideas,type Idea} from '../../../studio/content/ideas';
export default function IdeaPage({idea}:{idea:Idea}){if(idea.tool==='layout-selection')return <LayoutSelection/>;if(idea.template)return <TemplateTrial idea={idea}/>;return <main className="editor"><Head><title>{idea.title} · 创作站</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head><header><a href={tutorialPost}>← 啡跃使用教程</a><a href={'/studio/api/export/'+idea.slug}>导出内容包 ↓</a><a href={'/studio/api/export/'+idea.slug+'?format=markdown'}>Markdown ↓</a><button onClick={()=>window.print()}>打印 / PDF</button></header><h1>{idea.title}</h1><p>{idea.summary}</p><div className="slides">{idea.slides.map((s,i)=><article className="slide" key={i} style={{background:s.color}}><small>ENDOLEAP / {String(i+1).padStart(2,'0')}</small><h2>{s.heading}</h2><p>{s.body}</p><footer>记录灵感 · 自由表达</footer></article>)}</div></main>}
export const getStaticPaths:GetStaticPaths=async()=>({paths:ideas.map(i=>({params:{slug:i.slug}})),fallback:false});
export const getStaticProps:GetStaticProps=async({params})=>{const idea=ideas.find(i=>i.slug===params?.slug);return idea?{props:{idea}}:{notFound:true}};
@@ -0,0 +1,20 @@
import type {GetServerSideProps} from 'next';
import {NativeResult} from '../../../studio/components/NativeResult';
import type {Layout} from '../../../studio/lib/layout-parameters';
import fixedLayouts from '../../../studio/content/templates/layouts.json';
import standardLayout from '../../../studio/content/standard-layout.json';
const layouts=[...fixedLayouts,standardLayout];
import {nativeLayout,designUrl} from '../../../studio/lib/native-layout';
import {readDesign} from '../../../studio/lib/design-server';
export default function LayoutPage({layout}:{layout:Layout}){return <NativeResult layout={layout} design={null}/>}
export const getServerSideProps:GetServerSideProps<{layout:Layout}>=async({params,query,req,res})=>{
res.setHeader('Cache-Control','private, no-store');
const layout=layouts.find(l=>l.id===params?.layoutId);
if(!layout)return {notFound:true};
if(query.id!==undefined){
const design=await readDesign(query.id,req);
if(!design||design.layoutId!==layout.id)return {notFound:true};
return {redirect:{destination:designUrl(design.layoutId,design.id).slice('/studio'.length),permanent:false}};
}
return {props:{layout:nativeLayout(layout)}};
};
@@ -0,0 +1,21 @@
import type {GetServerSideProps} from 'next';
import {NativeSeries} from '../../studio/components/NativeSeries';
import {NativeResult} from '../../studio/components/NativeResult';
import fixedLayouts from '../../studio/content/templates/layouts.json';
import standardLayout from '../../studio/content/standard-layout.json';
import {readDesign} from '../../studio/lib/design-server';
import {nativeLayout,type Design} from '../../studio/lib/native-layout';
import type {Layout} from '../../studio/lib/layout-parameters';
type Props={layout:Layout;design:Design;page:number|null;quality:boolean};
export default function TemplateLayout(props:Props){return props.design.document?<NativeSeries design={props.design} page={props.page} quality={props.quality}/>:<NativeResult {...props}/>}
export const getServerSideProps:GetServerSideProps<Props>=async({query,req,res})=>{
res.setHeader('Cache-Control','private, no-store');
const design=await readDesign(query.id,req);
if(!design)return {notFound:true};
const layout=[standardLayout,...fixedLayouts].find(l=>l.id===design.layoutId);
if(!layout)return {notFound:true};
const page=query.page===undefined?null:Number(query.page);
if(page!==null&&(!Number.isInteger(page)||page<1||page>(design.document?.pages.length||1)))return {notFound:true};
return {props:{layout:nativeLayout(layout),design,page,quality:query.export==='1'}};
};
+20
View File
@@ -0,0 +1,20 @@
import Head from "next/head";
import { useState } from "react";
import { Download,Copy,Sparkles } from "lucide-react";
import { Shell } from "@/components/Shell";
const strokes=[
{name:'睡眼',hint:'让石头和面包打一个盹',path:'M22 54 Q38 72 54 54 M74 54 Q90 72 106 54 M39 65 l-3 8 M89 65 l3 8'},
{name:'弯弯箭头',hint:'把目光引向一个小细节',path:'M20 87 Q15 26 92 37 M77 22 L100 37 L80 53'},
{name:'一朵小云',hint:'给天空加一点想象',path:'M30 82 C3 83 10 52 31 55 C26 22 71 20 75 47 C100 33 120 64 101 80 M32 82 L99 82'},
{name:'一点心动',hint:'给喜欢的东西圈个重点',path:'M65 99 C-4 57 35 15 64 45 C92 11 133 57 65 99'},
{name:'闪一下',hint:'把光画成一个小小的惊喜',path:'M64 20 Q61 59 28 64 Q60 67 64 106 Q69 68 102 64 Q69 60 64 20 M103 17 L103 35 M94 26 L112 26'},
{name:'草在长',hint:'沿着画面边缘悄悄长出来',path:'M24 101 Q25 73 10 64 M24 101 Q38 71 39 51 M60 101 Q49 74 48 66 M60 101 Q75 65 72 35 M96 101 Q87 71 86 62 M96 101 Q105 76 116 72'},
{name:'松松的圈',hint:'不必画得很圆',path:'M93 30 C44 8 11 40 21 79 C32 118 110 110 110 61 C109 26 76 18 45 25'},
{name:'波浪下划线',hint:'留给一句想记住的话',path:'M13 67 Q23 48 33 67 T53 67 T73 67 T93 67 T113 67'},
];
export default function Doodle(){
const [selected,setSelected]=useState(0);const [color,setColor]=useState('#fffaf0');const [copied,setCopied]=useState(false);
const svg=()=>`<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><path d="${strokes[selected].path}" fill="none" stroke="${color}" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
function download(){const url=URL.createObjectURL(new Blob([svg()],{type:'image/svg+xml'}));const a=document.createElement('a');a.href=url;a.download=`prompt-doodle-${selected+1}.svg`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
return <Shell><Head><title>线条灵感 · 啡跃 Endoleap</title></Head><header className="page-header"><div><span className="eyebrow">SMALL LINES, LITTLE STORIES</span><h1>线条工具</h1><p>选择图形、调整颜色,下载后用于照片涂鸦。</p></div><span className="pill"><Sparkles size={14}/>照片涂鸦工具箱</span></header><div className="doodle-layout"><section className="doodle-catalog">{strokes.map((s,i)=><button key={s.name} onClick={()=>{setSelected(i);setCopied(false);}} className={`doodle-card ${i===selected?'selected':''}`}><div><svg viewBox="0 0 128 128"><path d={s.path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><strong>{s.name}</strong><small>{s.hint}</small></button>)}</section><aside className="surface doodle-inspector"><span className="eyebrow">A LITTLE MARK</span><div className="doodle-large"><svg viewBox="0 0 128 128"><path d={strokes[selected].path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><h2>{strokes[selected].name}</h2><p>{strokes[selected].hint}</p><div className="swatches">{['#fffaf0','#332c28','#ef6954','#ecc75b'].map(c=><button aria-label={`线条颜色 ${c}`} key={c} style={{background:c}} className={c===color?'selected':''} onClick={()=>setColor(c)}/>)}</div><button className="primary-button" onClick={download}><Download size={16}/>下载透明底 SVG</button><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(svg());setCopied(true);}}><Copy size={16}/>{copied?'已复制':'复制线条'}</button><p className="form-note">小图用来挑选造型与记录想法。正式画进照片时,位置、比例与笔触仍需要顺着画面调整。</p></aside></div></Shell>;
}
@@ -0,0 +1,5 @@
import type {GetServerSideProps} from 'next';
import {getGuidance,legacyDocumentPath} from '@/content/skills/guidance';
import {guidanceUrl} from '@/content/page-links';
export default function Legacy(){return null;}
export const getServerSideProps:GetServerSideProps=async({params})=>{const doc=params?.doc;const path=legacyDocumentPath(String(params?.skill),Array.isArray(doc)?doc[0]:'index');return getGuidance(path)?{redirect:{destination:guidanceUrl(path),permanent:true}}:{notFound:true};};
@@ -0,0 +1 @@
export {GuidanceIndex as default} from '@/components/GuidanceIndex';
@@ -0,0 +1,4 @@
export {default} from '../../skills/[[...path]]';
import type {GetServerSideProps} from 'next';
import {guidanceUrl} from '@/content/page-links';
export const getServerSideProps:GetServerSideProps=async()=>({redirect:{destination:guidanceUrl('street-people'),permanent:true}});
@@ -0,0 +1,5 @@
export {default} from '../[skill]/[[...doc]]';
import type {GetServerSideProps} from 'next';
import {getGuidance,legacyDocumentPath} from '@/content/skills/guidance';
import {guidanceUrl} from '@/content/page-links';
export const getServerSideProps:GetServerSideProps=async({params})=>{const path=legacyDocumentPath('street-people',String(params?.doc));return getGuidance(path)?{redirect:{destination:guidanceUrl(path),permanent:true}}:{notFound:true};};
+6
View File
@@ -0,0 +1,6 @@
import type {GetServerSideProps} from 'next';
import {getPost} from '@/lib/library';
import {findWikiPage} from '@/content/wiki';
import {pageId,exploreUrl} from '@/content/page-links';
export default function Legacy(){return null;}
export const getServerSideProps:GetServerSideProps=async({params,query})=>{const key=String(params?.key||'');const page=findWikiPage(key);let destination='';if(page?.namespace==='Category')destination='/categories?category='+encodeURIComponent(page.slug);else if(page)destination=exploreUrl(pageId('wiki:'+key));else{const index=key.indexOf(':');if(!['Main','File'].includes(key.slice(0,index)))return {notFound:true};const post=await getPost(key.slice(index+1));if(post)destination=exploreUrl(post.id);}if(!destination)return {notFound:true};if(String(query.agent_mode||'').toLowerCase()==='true')destination+=(destination.includes('?')?'&':'?')+'agent_mode=True';return {redirect:{destination,permanent:true}};};
+7
View File
@@ -0,0 +1,7 @@
import { ThemeToggle } from "../components/ThemeToggle";
import { Brand } from "../components/Brand";
import Head from 'next/head';
import {useEffect,useState} from 'react';
import {ArrowUpRight, Layers, Workflow, BookOpen, Link2} from 'lucide-react';
import s from '@/styles/workspace.module.css';
export default function Workspace(){const [email,setEmail]=useState(''),[state,setState]=useState('loading');useEffect(()=>{fetch('/api/account/session').then(async r=>{if(!r.ok)throw Error();const d=await r.json();if(!d.user){window.location.replace('/account?next=/workspace');return}setEmail(d.user.email);setState('ready')}).catch(()=>setState('error'))},[]);return <main className={s.app}><Head><title>工作台 · 啡跃 Studio</title></Head><aside><a className={s.brand} href="/"><Brand/></a><span>你的工作空间</span><a aria-current="page" href="/workspace">◈ 创作概览</a><a href="/graphic"><Layers size={16}/>图形设计</a><a href="/infinite_canvas"><Workflow size={16}/>无限画布</a><a href="/documents"><BookOpen size={16}/>知识与教程</a><a href="/studio/api"><Link2 size={16}/>Agent 接入文档</a><a className={s.account} href="/account">{email||'账户设置'} ↗</a></aside><section>{state==='loading'?<p role="status">正在打开你的工作台…</p>:state==='error'?<p role="alert">暂时无法读取账户。<a href="/account?next=/workspace">重新登录</a></p>:<><header><span>WORKSPACE / OVERVIEW</span><ThemeToggle/><a href="/account">账户设置 ↗</a></header><p className={s.kicker}>MAKE SOMETHING THAT MATTERS.</p><h1>今天,让哪个想法成形?</h1><p className={s.sub}>选一个空间,开始你的下一次创作。</p><div className={s.grid}><a href="/graphic"><Layers/><small>GRAPHIC</small><h2>图形设计</h2><p>在文字、图形与图像之间,找到你的表达。</p><div className={s.poster}>Ideas,<br/><i>in shape.</i><b>✳</b></div><strong>打开编辑器 <ArrowUpRight size={18}/></strong></a><a href="/infinite_canvas"><Workflow/><small>INFINITE CANVAS</small><h2>无限画布</h2><p>收集灵感、连接参考,让思路自由生长。</p><div className={s.canvas}><span>灵感</span>⟶<span>参考</span>⟶<span>作品</span></div><strong>打开画布 <ArrowUpRight size={18}/></strong></a></div><div className={s.agent}><Link2/><div><h3>带上你的 coding agent</h3><p>从接入文档开始,使用已有的创作 API。连接由你的 Agent 发起。</p></div><a href="/studio/api">查看文档 ↗</a></div><p className={s.hint}>编辑器草稿保存在当前浏览器。更换设备前,请先导出项目备份。</p></>}</section></main>}
+729
View File
@@ -0,0 +1,729 @@
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import {
ArrowUpRight,
Braces,
CheckCircle2,
FileText,
Globe2,
Link2,
ListChecks,
Plus,
ShieldCheck,
Trash2,
} from "lucide-react";
import GuidanceShell, { useGuidanceAccount } from "@/components/GuidanceShell";
import {
EmptyState,
KindBadge,
Notice,
PageHeading,
kindNames,
} from "@/components/GuidanceUI";
import { guidanceXml, type Guidance } from "@/content/guides/catalog";
import s from "@/styles/guidance.module.css";
const blank: Guidance = {
id: "",
revision: 1,
kind: "guide",
title: "",
summary: "",
applies: "",
body: "",
steps: [],
checks: [],
links: [],
tags: [],
};
type Preview = {
document: Guidance;
xml: string;
links: { label: string; when: string; resolved: boolean }[];
};
function fieldName(path: string) {
const labels: Record<string, string> = {
id: "文档短名",
revision: "版本",
kind: "文档类型",
title: "标题",
summary: "一句话摘要",
applies: "适用条件",
body: "正文",
steps: "建议步骤",
checks: "完成检查",
tags: "标签",
target: "目标文档 ID",
relation: "关系类型",
when: "读取条件",
label: "链接标题",
};
const [group, index, field] = path.split(".");
if (group === "links")
return (
"关联文档" +
(index === undefined ? "" : " " + (Number(index) + 1)) +
(field ? " · " + (labels[field] || "内容") : "")
);
return (
(labels[group] || "文档内容") +
(index !== undefined ? " " + (Number(index) + 1) : "")
);
}
async function responseBody(response: Response) {
const body = await response
.json()
.catch(() => ({ error: "服务返回异常,请稍后重试" }));
if (!response.ok)
throw Error(
(body.error || "请求失败") +
(body.fields?.length
? ":" + body.fields.map(fieldName).join("、")
: ""),
);
return body;
}
export default function Write() {
return (
<GuidanceShell title="发布文档">
<Editor />
</GuidanceShell>
);
}
function Editor() {
const account = useGuidanceAccount(),
router = useRouter(),
dialog = useRef<HTMLDialogElement>(null);
const [doc, setDoc] = useState<Guidance>(blank),
[xml, setXml] = useState(""),
[mode, setMode] = useState<"form" | "xml">("form"),
[busy, setBusy] = useState(false),
[loading, setLoading] = useState(false),
[error, setError] = useState(""),
[preview, setPreview] = useState<Preview | null>(null),
[published, setPublished] = useState<{
id: string;
revision: number;
} | null>(null),
[dirty, setDirty] = useState(true);
const prefix = account.user ? "user-" + account.user.id + "-" : "",
editId = typeof router.query.id === "string" ? router.query.id : "";
useEffect(() => {
if (!router.isReady || !account.user) return;
let active = true;
setError("");
setPublished(null);
setPreview(null);
setMode("form");
setDirty(true);
if (!editId) {
setDoc({
...blank,
id:
"user-" +
account.user.id +
"-document-" +
Math.random().toString(16).slice(2, 8),
});
setLoading(false);
return;
}
if (!editId.startsWith("user-" + account.user.id + "-")) {
setError("只能编辑你自己发布的文档。");
setDoc(blank);
return;
}
setLoading(true);
fetch("/api/documents/" + encodeURIComponent(editId))
.then(responseBody)
.then((body) => {
if (active)
setDoc({ ...body.document, revision: body.document.revision + 1 });
})
.catch((e) => {
if (active) {
setError(e.message);
setDoc(blank);
}
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [account.user?.id, editId, router.isReady]);
function change<K extends keyof Guidance>(key: K, value: Guidance[K]) {
setDoc((current) => ({ ...current, [key]: value }));
setPreview(null);
setDirty(true);
setPublished(null);
}
async function request(action: "preview" | "publish" | "convert") {
setBusy(true);
setError("");
setPreview(null);
try {
const body = await responseBody(
await fetch(
"/api/documents" + (action === "publish" ? "" : "/preview"),
{
method: "POST",
headers: {
"Content-Type":
mode === "xml" ? "application/xml" : "application/json",
},
body: mode === "xml" ? xml : JSON.stringify(normalized()),
},
),
);
if (action === "convert") {
setDoc(body.document);
setMode("form");
} else if (action === "preview") {
setPreview(body);
dialog.current?.showModal();
} else {
setDoc({ ...body.document, revision: body.document.revision + 1 });
setXml(
guidanceXml({
...body.document,
revision: body.document.revision + 1,
}),
);
setPublished({
id: body.document.id,
revision: body.document.revision,
});
setDirty(false);
}
} catch (e) {
setError(e instanceof Error ? e.message : "请求失败,请稍后重试");
} finally {
setBusy(false);
}
}
function normalized() {
return {
...doc,
steps: doc.steps.filter((step) => step.trim()),
checks: doc.checks.filter((check) => check.trim()),
tags: doc.tags.filter((tag) => tag.trim()),
};
}
function selectXml() {
setXml(guidanceXml(normalized()));
setMode("xml");
setPreview(null);
}
const authorized = account.user?.verified_at;
return (
<>
<PageHeading
title="发布独立文档"
description="一篇文档,一项清晰的指导。按需关联,让 Agent 自由选择。"
eyebrow={editId ? "UPDATE DOCUMENT" : "NEW DOCUMENT"}
/>
{account.loading ? (
<div className={s.accountLoading}>正在读取账户…</div>
) : !authorized ? (
<section className={`${s.panel} ${s.publishGate}`}>
<EmptyState
title={account.user ? "验证邮箱后继续" : "登录后开始编写"}
description={
account.error ||
"公开阅读无需登录。发布和维护文档,需要一个已验证的邮箱账户。"
}
>
<Link className={s.primaryButton} href="/account?next=%2Fwrite">
<ShieldCheck size={15} />
{account.user ? "前往验证邮箱" : "登录 / 创建账户"}
</Link>
</EmptyState>
</section>
) : (
<>
{error && <Notice tone="error">{error}</Notice>}
{published && (
<Notice tone="success">
版本 v{published.revision} 已公开发布。
<div className={s.successActions}>
<Link
href={
"/documents/" +
published.id +
"?revision=" +
published.revision
}
>
查看已发布版本
<ArrowUpRight size={12} />
</Link>
<Link href="/documents?scope=mine">查看我的文档</Link>
</div>
</Notice>
)}
{loading ? (
<div className={s.accountLoading}>正在加载最新版本…</div>
) : (
doc.id && (
<fieldset className={s.formFieldset} disabled={busy}>
<div className={s.editorTabs} aria-label="编辑方式">
<button
type="button"
aria-pressed={mode === "form"}
onClick={() => {
if (mode === "xml") void request("convert");
}}
>
可视化编辑
</button>
<button
type="button"
aria-pressed={mode === "xml"}
onClick={() => {
if (mode === "form") selectXml();
}}
>
协议 XML
</button>
</div>
<div className={s.formGrid}>
<div className={s.formSections}>
{mode === "xml" ? (
<section className={`${s.panel} ${s.formPanel}`}>
<h2 className={s.formSectionTitle}>
<Braces size={17} />
协议源文档
</h2>
<p className={s.formDescription}>
可直接粘贴完整
XML。切回可视化编辑时,会先校验并解析当前内容;校验失败时保留输入。
</p>
<label className={s.formField}>
<span className={s.fieldLabel}>XML 输入</span>
<textarea
className={`${s.textarea} ${s.xmlInput}`}
spellCheck={false}
value={xml}
onChange={(e) => {
setXml(e.target.value);
setDirty(true);
setPreview(null);
setPublished(null);
}}
/>
</label>
</section>
) : (
<>
<section className={`${s.panel} ${s.formPanel}`}>
<h2 className={s.formSectionTitle}>
<FileText size={17} />
基本信息
</h2>
<p className={s.formDescription}>
帮助读者和 Agent 判断,这篇文档是否适合当前任务。
</p>
<div className={s.fieldColumns}>
<label className={s.formField}>
<span className={s.fieldLabel}>文档短名</span>
<input
className={s.input}
aria-label="文档短名"
maxLength={37}
pattern="[a-z0-9-]+"
value={doc.id.slice(prefix.length)}
disabled={!!editId || doc.revision > 1}
onChange={(e) =>
change("id", prefix + e.target.value)
}
/>
<small className={s.fieldHint}>
小写字母、数字和连字符。发布后不可修改。
</small>
</label>
<label className={s.formField}>
<span className={s.fieldLabel}>文档类型</span>
<select
className={s.select}
value={doc.kind}
onChange={(e) =>
change(
"kind",
e.target.value as Guidance["kind"],
)
}
>
{Object.entries(kindNames).map(
([id, label]) => (
<option value={id} key={id}>
{label}
</option>
),
)}
</select>
</label>
</div>
{(["title", "summary", "applies"] as const).map(
(key) => (
<label className={s.formField} key={key}>
<span className={s.fieldLabel}>
{
{
title: "标题",
summary: "一句话摘要",
applies: "适用条件",
}[key]
}
<span className={s.required}>*</span>
</span>
{key === "title" ? (
<input
className={s.input}
value={doc[key]}
placeholder="例如:审查一次代码改动"
onChange={(e) =>
change(key, e.target.value)
}
/>
) : (
<textarea
className={s.textarea}
rows={2}
value={doc[key]}
placeholder={
key === "summary"
? "这篇文档可以帮助完成什么?"
: "什么情况下应该阅读?哪些情况不适用?"
}
onChange={(e) =>
change(key, e.target.value)
}
/>
)}
</label>
),
)}
<label className={s.formField}>
<span className={s.fieldLabel}>标签</span>
<input
className={s.input}
value={doc.tags.join(", ")}
placeholder="代码审查, 开发协作"
onChange={(e) =>
change(
"tags",
e.target.value
.split(/[,,]/)
.map((tag) => tag.trim()),
)
}
/>
<small className={s.fieldHint}>
使用逗号分隔。
</small>
</label>
</section>
<section className={`${s.panel} ${s.formPanel}`}>
<h2 className={s.formSectionTitle}>
<ListChecks size={17} />
指导内容
</h2>
<p className={s.formDescription}>
正文应当完整、可独立理解。步骤和检查项可以留空。
</p>
<label className={s.formField}>
<span className={s.fieldLabel}>
正文<span className={s.required}>*</span>
</span>
<textarea
className={`${s.textarea} ${s.bodyInput}`}
value={doc.body}
placeholder="写下清晰、具体的指导…"
onChange={(e) => change("body", e.target.value)}
/>
</label>
{(["steps", "checks"] as const).map((key) => (
<label className={s.formField} key={key}>
<span className={s.fieldLabel}>
{key === "steps" ? "建议步骤" : "完成检查"}
</span>
<textarea
className={s.textarea}
aria-label={
key === "steps" ? "建议步骤" : "完成检查"
}
rows={3}
value={doc[key].join("\n")}
onChange={(e) =>
change(key, e.target.value.split("\n"))
}
/>
<small className={s.fieldHint}>
每行一项,空行会在提交时忽略。
</small>
</label>
))}
</section>
<section className={`${s.panel} ${s.formPanel}`}>
<h2 className={s.formSectionTitle}>
<Link2 size={17} />
条件链接
<span className={s.neutralBadge}>
{doc.links.length}
</span>
</h2>
<p className={s.formDescription}>
仅当条件适用时,才建议读取关联文档。请指定固定版本;无需链接也可以独立发布。
</p>
{!doc.links.length && (
<div className={s.linkEmpty}>
还没有关联文档。你可以先完成正文,再为需要的场景补充链接。
</div>
)}
{doc.links.map((link, index) => (
<div className={s.linkEditor} key={index}>
<div className={s.linkEditorHeader}>
关联文档 {index + 1}
<button
type="button"
className={s.quietButton}
aria-label={"移除关联文档 " + (index + 1)}
onClick={() =>
change(
"links",
doc.links.filter((_, i) => i !== index),
)
}
>
<Trash2 size={13} />
移除
</button>
</div>
<div className={s.fieldColumns}>
{(
[
"target",
"revision",
"relation",
"label",
"when",
] as const
).map((key) => (
<label className={s.formField} key={key}>
<span className={s.fieldLabel}>
{
{
target: "目标文档 ID",
revision: "固定版本",
relation: "关系类型",
label: "链接标题",
when: "什么情况下读取",
}[key]
}
</span>
{key === "relation" ? (
<select
className={s.select}
value={link.relation}
onChange={(e) =>
change(
"links",
doc.links.map((item, i) =>
i === index
? {
...item,
relation: e.target
.value as Guidance["kind"],
}
: item,
),
)
}
>
{Object.entries(kindNames).map(
([id, label]) => (
<option value={id} key={id}>
{label}
</option>
),
)}
</select>
) : (
<input
className={s.input}
type={
key === "revision" ? "number" : "text"
}
min={key === "revision" ? 1 : undefined}
value={link[key]}
onChange={(e) =>
change(
"links",
doc.links.map((item, i) =>
i === index
? {
...item,
[key]:
key === "revision"
? Number(e.target.value)
: e.target.value,
}
: item,
),
)
}
/>
)}
</label>
))}
</div>
</div>
))}
<button
type="button"
className={s.secondaryButton}
onClick={() =>
change("links", [
...doc.links,
{
target: "",
revision: 1,
relation: "context",
when: "",
label: "",
},
])
}
>
<Plus size={14} />
添加条件链接
</button>
</section>
</>
)}
</div>
<aside className={s.publishSidebar}>
<section className={s.sideCard}>
<h3>
<Globe2 size={15} />
发布设置
</h3>
<div className={s.publishMeta}>
公开文档 · 待发布版本 v{doc.revision}
</div>
<KindBadge kind={doc.kind} />
<ul className={s.publishChecklist}>
<li className={s.completed}>
<CheckCircle2 size={14} />
邮箱已验证
</li>
<li>
<CheckCircle2 size={14} />
发布后任何人均可读取
</li>
<li>
<CheckCircle2 size={14} />
每次发布创建不可变版本
</li>
</ul>
<p>内容暂存在当前页面,请在离开前发布或自行保存 XML。</p>
<div className={s.publishButtons}>
<button
type="button"
className={s.secondaryButton}
onClick={() => void request("preview")}
>
校验并预览
</button>
<button
type="button"
className={s.primaryButton}
disabled={!dirty}
onClick={() => void request("publish")}
>
{busy
? "正在处理…"
: doc.revision === 1
? "发布文档"
: "发布新版本"}
</button>
</div>
</section>
<section className={s.sideCard}>
<h3>独立使用,按需连接</h3>
<p>
关系类型和适用条件帮助 Agent
选择下一篇文档。链接不会继承账户权限,也不要求整组加载。
</p>
<Link className={s.textLink} href="/protocol">
阅读协议说明
<ArrowUpRight size={12} />
</Link>
</section>
</aside>
</div>
</fieldset>
)
)}
</>
)}
<dialog
className={`${s.modal} ${s.largeModal}`}
ref={dialog}
aria-labelledby="preview-title"
>
<div className={s.modalBody}>
<h2 id="preview-title">发布预览</h2>
<p>校验已通过,内容尚未发布。请确认正文和关联条件。</p>
</div>
{preview && (
<div className={s.previewBody}>
<KindBadge kind={preview.document.kind} />
<h2 className={s.previewTitle}>{preview.document.title}</h2>
<p className={s.formDescription}>{preview.document.summary}</p>
<div className={s.appliesCard}>
<p>{preview.document.applies}</p>
</div>
<div className={s.proseBody}>{preview.document.body}</div>
{preview.document.steps.length > 0 && (
<ol className={s.stepList}>
{preview.document.steps.map((step, i) => (
<li key={i}>{step}</li>
))}
</ol>
)}
{preview.document.checks.length > 0 && (
<ul className={s.checkList}>
{preview.document.checks.map((check, i) => (
<li key={i}>{check}</li>
))}
</ul>
)}
{preview.links.map((link, i) => (
<div className={s.relationCard} key={i}>
<div>
<strong>{link.label}</strong>
<p>当{link.when}</p>
<small>
{link.resolved ? "固定版本可用" : "目标缺失,读取时需跳过"}
</small>
</div>
</div>
))}
</div>
)}
<div className={s.modalActions}>
<button
type="button"
className={s.secondaryButton}
onClick={() => dialog.current?.close()}
>
返回编辑
</button>
</div>
</dialog>
</>
);
}