Build PROMPT media library with masonry UI and persistent PostgreSQL S3 storage
PROMPT CI and deployment / verify-and-deploy (push) Successful in 8m18s

This commit is contained in:
2026-10-22 22:18:11 +08:00
parent 68419e3852
commit 8b650fdf78
42 changed files with 1631 additions and 54 deletions
+11
View File
@@ -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}};}
};
+10
View File
@@ -0,0 +1,10 @@
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(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)}));
}catch(e){return apiError(res,e);}
}
+24
View File
@@ -0,0 +1,24 @@
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(!['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 asset_variants WHERE asset_id=$1 AND role=$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, max-age=3600');
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}};
+7
View File
@@ -0,0 +1,7 @@
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(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);}
}
+9
View File
@@ -0,0 +1,9 @@
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(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'});}
}
+15
View File
@@ -0,0 +1,15 @@
import type { NextApiRequest,NextApiResponse } from "next";
import { z } from "zod";
import { randomUUID } from "node:crypto";
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){
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().min(1).max(60),slug:z.string().regex(/^[a-z0-9][a-z0-9-]{0,59}$/),parentId:z.uuid().nullable().default(null)}).parse(req.body);
const id=randomUUID(); await db().query('INSERT INTO tags(id,name,slug,parent_id) VALUES($1,$2,$3,$4)',[id,data.name,data.slug,data.parentId]);return res.status(201).json({id});
}catch(e){return apiError(res,e);}
}
+59
View File
@@ -0,0 +1,59 @@
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 default async function handler(req:NextApiRequest,res:NextApiResponse){
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});
form.on('fileBegin',(_name,file)=>temporary.push(file.filepath));
const [fields,files]=await form.parse(req);
const kind=z.enum(['image','video','audio']).parse(fields.kind?.[0]);
const title=z.string().trim().min(1).max(200).parse(fields.title?.[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]||'[]'));
const items=Object.values(files).flat().filter(Boolean) as File[];
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'){
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=randomUUID();
await transaction(async client=>{
await client.query('INSERT INTO posts(id,slug,kind,title) VALUES($1,$2,$3,$4)',[postId,postId,kind,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']);
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(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]);}
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;return res.status(201).json({id:postId,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));}
}
+8
View File
@@ -0,0 +1,8 @@
import type { GetServerSideProps } from "next";
import { Feed } from "@/components/Feed";
import { feed } from "@/lib/library";
export default Feed;
export const getServerSideProps:GetServerSideProps=async({query})=>{
try{return {props:{initial:await feed({q:String(query.q||'').slice(0,200)})}};}
catch{return {props:{initial:{posts:[],tags:[],contributions:[],nextCursor:null,unavailable:true}}};}
};
+21
View File
@@ -0,0 +1,21 @@
import type { GetServerSideProps } from "next";
import Head from "next/head";
import Link from "next/link";
import { useState } from "react";
import { Layers,Copy,Upload } from "lucide-react";
import { Shell } from "@/components/Shell";
import { db } from "@/lib/db";
import { mediaUrl,type Asset } from "@/lib/model";
type Row=Asset&{uses:number};
export default function Assets({assets,next}:{assets:Row[];next:string|null}){
const [copied,setCopied]=useState('');
return <Shell><Head><title>原始素材 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">ONE ASSET, MANY POSSIBILITIES</span><h1>素材库</h1><p>查看全部原始文件和文字,复用已收录的素材。</p></div><Link className="secondary-button" href="/library/import"><Upload size={15}/>导入素材</Link></header>
{assets.length?<div className="asset-grid">{assets.map(a=><article className="asset-tile" key={a.id}><div className="asset-preview">{a.kind==='image'?<img src={mediaUrl(a.id)} alt={a.filename||''} loading="lazy"/>:a.kind==='audio'?<audio controls preload="none" src={mediaUrl(a.id)}/>:a.kind==='video'?<video controls preload="metadata" src={mediaUrl(a.id)}/>:<p>{a.body?.slice(0,300)}</p>}</div><div className="asset-tile-info"><h3>{a.filename||'文字片段'}</h3><span>{a.uses} 个素材包正在引用</span><button aria-label="复制素材 ID" onClick={async()=>{await navigator.clipboard.writeText(a.id);setCopied(a.id);}}><Copy size={14}/>{copied===a.id?'已复制':'复制 ID'}</button></div></article>)}</div>:<div className="empty-state"><Layers size={38}/><h2>素材架还是空的</h2><p>导入的图片、视频、声音,以及素材包中的文字都会保存在这里。</p></div>}
{next&&<Link className="secondary-button" href={'/library/assets?before='+encodeURIComponent(next)}>下一页素材</Link>}
</Shell>;
}
export const getServerSideProps:GetServerSideProps=async({query})=>{
const before=String(query.before||'');const valid=/^[0-9a-f-]{36}$/.test(before);
const result=await db().query(`SELECT a.*,(SELECT count(DISTINCT post_id)::integer FROM post_assets WHERE asset_id=a.id) AS uses,'[]'::json AS variants FROM assets a ${valid?'WHERE (a.created_at,a.id)<(SELECT created_at,id FROM assets WHERE id=$1)':''} ORDER BY a.created_at DESC,a.id DESC LIMIT 49`,valid?[before]:[]);
const rows=result.rows.slice(0,48).map(({created_at,...a})=>a);return {props:{assets:rows,next:result.rows.length>48?rows.at(-1).id:null}};
};
+25
View File
@@ -0,0 +1,25 @@
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 { 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('/p/'+result.slug);}catch(e){setError(e instanceof Error?e.message:'上传失败');}finally{setBusy(false);}}
return <Shell><Head><title>素材入库 · PROMPT</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>
{allTags.length>0&&<div className="form-field"><label>放进哪些分类 <small>可多选</small></label><div className="tag-picker">{allTags.map(t=><label key={t.id}><input type="checkbox" checked={selected.includes(t.id)} onChange={e=>setSelected(s=>e.target.checked?[...s,t.id]:s.filter(id=>id!==t.id))}/>{allTags.filter(a=>t.path.startsWith(a.path+'/')).map(a=>a.name+' / ')}{t.name}</label>)}</div></div>}
{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()}});
+14
View File
@@ -0,0 +1,14 @@
import type { GetServerSideProps } from "next";
import Head from "next/head";
import { useState,type FormEvent } from "react";
import { useRouter } from "next/router";
import { Hash,CornerDownRight } from "lucide-react";
import { Shell } from "@/components/Shell";
import { tags } from "@/lib/library";
import type { Tag } from "@/lib/model";
export default function TagsPage({allTags}:{allTags:Tag[]}){
const router=useRouter();const [error,setError]=useState('');const [busy,setBusy]=useState(false);
async function submit(e:FormEvent<HTMLFormElement>){e.preventDefault();const form=e.currentTarget;const data=new FormData(form);setBusy(true);setError('');try{const r=await fetch('/api/tags',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:data.get('name'),slug:data.get('slug'),parentId:data.get('parentId')||null})});if(!r.ok)throw new Error((await r.json()).error);form.reset();await router.replace(router.asPath);}catch(e){setError(e instanceof Error?e.message:'保存失败');}finally{setBusy(false);}}
return <Shell><Head><title>分类标签 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">A PLACE FOR EVERY IDEA</span><h1>分类管理</h1><p>按层级整理标签。同一个素材包可以同时归入多个分类。</p></div></header><div className="management-grid"><section className="surface"><h2>分类树 <small>{allTags.length} 个分类</small></h2>{allTags.length?allTags.map(t=><div className="taxonomy-row" key={t.id} style={{paddingLeft:18+t.path.split('/').length*18}}>{t.parent_id?<CornerDownRight size={16}/>:<Hash size={16}/>}<strong>{t.name}</strong><code>/{t.path}</code></div>):<div className="quiet-empty">还没有分类。先从一个大方向开始。</div>}</section><form className="surface compact-form" onSubmit={submit}><h2>新建分类</h2><label>分类名称<input required name="name" maxLength={60} placeholder="比如:手绘线条"/></label><label>网址标识<input required name="slug" pattern="[a-z0-9][a-z0-9-]*" maxLength={60} placeholder="hand-drawn"/><small>使用小写字母、数字和连字符。</small></label><label>上级分类<select name="parentId"><option value="">作为一级分类</option>{allTags.map(t=><option key={t.id} value={t.id}>{t.path.split('/').map((_,i)=>allTags.find(a=>a.path===t.path.split('/').slice(0,i+1).join('/'))?.name).join(' / ')}</option>)}</select></label>{error&&<p className="error-message" role="alert">{error}</p>}<button className="primary-button" disabled={busy}>{busy?'保存中…':'保存分类'}</button></form></div></Shell>;
}
export const getServerSideProps:GetServerSideProps=async()=>({props:{allTags:await tags()}});
+35
View File
@@ -0,0 +1,35 @@
import type { GetServerSideProps } from "next";
import Head from "next/head";
import Link from "next/link";
import { useEffect,useState } from "react";
import { useRouter } from "next/router";
import { ArrowLeft,ChevronLeft,ChevronRight,Volume2,VolumeX,Download,Copy,Layers } from "lucide-react";
import { Shell } from "@/components/Shell";
import { getPost } from "@/lib/library";
import { mediaUrl,sections,type Post } from "@/lib/model";
import { works } from "@/content/registry";
export default function PostDetail({post}:{post:Post}){
const [index,setIndex]=useState(0);const [copied,setCopied]=useState(false);const router=useRouter();
const media=post.assets.filter(a=>a.kind!=='text');const selected=media[index];const section=sections.find(s=>s.kind===post.kind)!;
useEffect(()=>{if(post.assets.some(a=>['pending','processing'].includes(a.processing_status))){const timer=setTimeout(()=>{void router.replace(router.asPath,undefined,{scroll:false});},3000);return ()=>clearTimeout(timer);}},[post,router]);
const Work=post.page_key?works[post.page_key]?.Component:undefined;
return <Shell><Head><title>{post.title} · PROMPT</title></Head><div className="detail-top"><Link href={`/${section.path}`}><ArrowLeft size={17}/>返回{section.name}</Link><span>{section.name}</span></div>
<div className={`detail-layout ${Work?'coded-detail':''}`}><section className="detail-media">
{Work?<Work/>:selected?<><div className={`media-stage stage-${selected.kind}`}>
{selected.kind==='image'&&<img src={mediaUrl(selected.id)} alt={selected.filename||post.title}/>}
{selected.kind==='video'&&<video key={selected.id} controls playsInline preload="metadata" poster={selected.variants.includes('poster')?mediaUrl(selected.id,'poster'):undefined} src={mediaUrl(selected.id,selected.variants.includes('silent_video')?'silent_video':undefined)}/>}
{selected.kind==='audio'&&<div className="audio-stage"><div className="vinyl"><span/></div><h3>{selected.filename}</h3><audio key={selected.id} controls preload="metadata" src={mediaUrl(selected.id)}/></div>}
{media.length>1&&<><button className="gallery-prev icon-button" disabled={index===0} aria-label="上一个素材" onClick={()=>setIndex(i=>i-1)}><ChevronLeft/></button><button className="gallery-next icon-button" disabled={index===media.length-1} aria-label="下一个素材" onClick={()=>setIndex(i=>i+1)}><ChevronRight/></button><span className="gallery-position">{index+1} / {media.length}</span></>}
</div>
{selected.kind==='video'&&<div className="video-companion"><div><span className="pill">{selected.has_audio?<><Volume2 size={14}/>原视频有声音</>:<><VolumeX size={14}/>原视频无声音</>}</span><small>{selected.processing_status==='ready'?'画面已分离,可独立预览与复用':selected.processing_status==='failed'?'音画分离未完成,原文件仍可使用':'正在后台拆分画面与声音…'}</small></div>{selected.variants.includes('audio_track')&&<div className="bound-audio"><span><Volume2 size={16}/>这段视频的声音</span><audio controls preload="metadata" src={mediaUrl(selected.id,'audio_track')}/><small>音轨随视频保存,不属于独立声音素材。</small></div>}</div>}
{media.length>1&&<div className="thumbnail-strip">{media.map((a,i)=><button key={a.id} className={i===index?'selected':''} onClick={()=>setIndex(i)} aria-label={`查看第 ${i+1} 个素材`}>{a.kind==='image'?<img src={mediaUrl(a.id)} alt=""/>:a.variants.includes('poster')?<img src={mediaUrl(a.id,'poster')} alt=""/>:<span>{a.kind==='audio'?'声音':'视频'} {i+1}</span>}</button>)}</div>}</>:<div className="empty-state"><Layers/><p>这个素材包还没有可展示的内容。</p></div>}
</section><aside className="detail-info"><span className="eyebrow">A PIECE OF YOUR COLLECTION</span><h1>{post.title}</h1><div className="detail-date">{new Date(post.created_at).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai'})}<span>· {media.length} 份素材</span></div>
<div className="description">{post.assets.filter(a=>a.kind==='text').map(a=><p key={a.id}>{a.body}</p>)}</div>
<div className="tag-list">{post.tags.map(t=><Link key={t.id} href={`/${section.path}/${t.path}`}># {t.name}</Link>)}</div>
{selected&&<div className="asset-facts"><h3>素材信息</h3><dl><dt>原文件</dt><dd>{selected.filename}</dd>{selected.width&&<><dt>尺寸</dt><dd>{selected.width} × {selected.height}</dd></>}{selected.duration&&<><dt>时长</dt><dd>{selected.duration.toFixed(1)} 秒</dd></>}<dt>复用方式</dt><dd>引用同一素材,无需再次上传</dd></dl><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(selected.id);setCopied(true);setTimeout(()=>setCopied(false),2000);}}><Copy size={14}/>{copied?'已复制素材 ID':'复制素材 ID'}</button><a className="text-link" href={mediaUrl(selected.id)} download><Download size={14}/>打开原文件</a></div>}
</aside></div>
</Shell>;
}
export const getServerSideProps:GetServerSideProps=async({params})=>{
const post=await getPost(String(params?.slug||''));return post?{props:{post}}:{notFound:true};
};
+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>线条灵感 · PROMPT</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>;
}