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
+40
View File
@@ -0,0 +1,40 @@
import Head from "next/head";
import Link from "next/link";
import { useEffect,useRef,useState } from "react";
import { useRouter } from "next/router";
import { Search,Image as ImageIcon,ArrowUpRight,AudioLines,Film,Layers,ArrowDown,Upload } from "lucide-react";
import { Shell } from "./Shell";
import { Heatmap } from "./Heatmap";
import { sections,mediaUrl,type FeedData,type Post } from "@/lib/model";
export function PostCard({post}:{post:Post}){
const image=post.assets.find(a=>a.kind==='image');const video=post.assets.find(a=>a.kind==='video');const cover=post.cover_asset_id||image?.id;
const label=sections.find(s=>s.kind===post.kind)?.name;const count=post.assets.filter(a=>a.kind!=='text').length;
const source=cover?mediaUrl(cover):video?.variants.includes('poster')?mediaUrl(video.id,'poster'):null;
return <Link className="post-card" href={`/p/${post.slug}`}><div className={`post-cover cover-${post.kind}`} style={image?.width&&image?.height?{aspectRatio:`${image.width}/${image.height}`,maxHeight:460}:undefined}>
{source?<img src={source} alt={post.title} loading="lazy"/>:post.kind==='audio'?<div className="waveform">{Array.from({length:36},(_,i)=><i key={i} style={{height:12+((i*31)%65)}}/>)}</div>:<div className="cover-symbol">{post.kind==='video'?<Film size={42}/>:<Layers size={42}/>}<span>{label}</span></div>}
{count>1&&<span className="cover-count"><Layers size={12}/>{count}</span>}{video&&<span className="cover-badge">{video.has_audio?'有声音':'无声音'}</span>}
</div><h3>{post.title}</h3><div className="post-meta"><span><i className={`type-dot ${post.kind}`}/>{label}</span><time>{new Date(post.created_at).toLocaleDateString('zh-CN',{month:'2-digit',day:'2-digit',timeZone:'Asia/Shanghai'})}</time></div>{post.tags.length>0&&<div className="card-tags">{post.tags.slice(0,2).map(t=><span key={t.id}>#{t.name}</span>)}</div>}</Link>;
}
function Masonry({posts}:{posts:Post[]}){
const element=useRef<HTMLDivElement>(null);const [width,setWidth]=useState(1100);
useEffect(()=>{if(!element.current)return;const observer=new ResizeObserver(entries=>setWidth(entries[0].contentRect.width));observer.observe(element.current);return ()=>observer.disconnect();},[]);
const count=width>1250?5:width>1000?4:width>720?3:2;
const columns:Post[][]=Array.from({length:count},()=>[]);const heights=Array(count).fill(0);const cardWidth=(width-22*(count-1))/count;
for(const post of posts){const image=post.assets.find(a=>a.kind==='image');const ratio=image?.width&&image.height?image.height/image.width:post.kind==='audio'?1:1.25;const index=heights.indexOf(Math.min(...heights));columns[index].push(post);heights[index]+=Math.min(cardWidth*ratio,460)+90+Math.ceil(post.title.length/15)*20;}
return <div ref={element} className="masonry" style={{gridTemplateColumns:`repeat(${count}, minmax(0,1fr))`}}>{columns.map((items,i)=><div className="masonry-column" key={i}>{items.map(p=><PostCard post={p} key={p.id}/>)}</div>)}</div>;
}
export function Feed({initial,section='',tagPath=''}:{initial:FeedData;section?:string;tagPath?:string}){
const router=useRouter();const [posts,setPosts]=useState(initial.posts);const [cursor,setCursor]=useState(initial.nextCursor);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const generation=useRef(0);
useEffect(()=>{generation.current++;setPosts(initial.posts);setCursor(initial.nextCursor);setError('');setBusy(false);},[initial,router.query.q]);
const current=sections.find(s=>s.path===section);const target=initial.tags.find(t=>t.path===tagPath);const children=initial.tags.filter(t=>target?t.parent_id===target.id:!t.parent_id);
async function load(){const gen=generation.current;setBusy(true);setError('');try{const q=new URLSearchParams({section,path:tagPath,cursor:cursor||'',q:String(router.query.q||'')});const res=await fetch('/api/feed?'+q);const d=await res.json();if(!res.ok)throw new Error(d.error);if(gen===generation.current){setPosts(old=>[...old,...d.posts.filter((p:Post)=>!old.some(a=>a.id===p.id))]);setCursor(d.nextCursor);}}catch{if(gen===generation.current)setError('加载没有完成,点击重试。');}finally{if(gen===generation.current)setBusy(false);}}
return <Shell><Head><title>{target?.name||current?.name||'灵感首页'} · PROMPT</title><meta name="description" content="自己的图文、视频与声音创作空间"/></Head>
{current&&<header className="page-header feed-heading"><div><h1>{target?.name||current.name}</h1><p>{current.hint}</p></div></header>}
{!section&&<Heatmap data={initial.contributions}/>}
{tagPath&&<div className="breadcrumbs"><Link href={`/${section}`}>全部{current?.name}</Link>{tagPath.split('/').map((_,i)=>{const path=tagPath.split('/').slice(0,i+1).join('/');return <span key={path}> / <Link href={`/${section}/${path}`}>{initial.tags.find(t=>t.path===path)?.name}</Link></span>;})}</div>}
<div className="feed-toolbar"><div className="feed-tabs">{!section?<><Link className="selected" href="/">全部</Link>{sections.map(s=><Link key={s.path} href={`/${s.path}`}>{s.name}</Link>)}</>:<><Link className={!tagPath?'selected':''} href={`/${section}`}>全部</Link>{children.map(t=><Link key={t.id} href={`/${section}/${t.path}`}>{t.name}</Link>)}</>}</div><span className="sort-label"><ArrowDown size={13}/>最近收录</span></div>
{initial.unavailable?<div className="empty-state"><Layers/><h2>素材库暂时没有连接上</h2><p>请稍后刷新,已保存的内容不会因此丢失。</p></div>:posts.length?<Masonry posts={posts}/>:<div className="empty-state"><div className="empty-art"><span/><ImageIcon size={42} strokeWidth={1.2}/><i><AudioLines size={18}/></i><b><Film size={19}/></b></div><span className="eyebrow">A LITTLE SPACE FOR SOMETHING GOOD</span><h2>{router.query.q?'还没有找到这份灵感':'这里还没有内容'}</h2><p>{router.query.q?'换一个词试试看。':'导入图片、视频或声音,开始整理你的素材。'}</p><Link className="primary-button" href={`/library/import${current&&['image','video','audio'].includes(current.kind)?'?kind='+current.kind:''}`}><Upload size={16}/>导入素材<ArrowUpRight size={16}/></Link><small>图文和动态作品通过代码加入,自由决定每一个像素。</small></div>}
{cursor&&<div className="load-more"><button disabled={busy} onClick={load}>{busy?'正在翻找…':error||'再看一些'}<ArrowDown size={14}/></button></div>}
<footer className="page-footer">PROMPT <span>·</span> PROBABLY RENDERING ONE MORE PIXEL TONIGHT</footer>
</Shell>;
}
+14
View File
@@ -0,0 +1,14 @@
import { useState,useRef,useEffect } from "react";
export function Heatmap({data}:{data:{day:string;total:number}[]}){
const [hover,setHover]=useState('');const values=new Map(data.map(d=>[d.day,d.total]));
const scroller=useRef<HTMLDivElement>(null);
useEffect(()=>{if(scroller.current)scroller.current.scrollLeft=scroller.current.scrollWidth;},[]);
const now=new Date();const today=new Date(now.toLocaleDateString('en-CA',{timeZone:'Asia/Shanghai'})+'T00:00:00Z');
const start=new Date(today);start.setUTCDate(start.getUTCDate()-364-start.getUTCDay());
const days=Array.from({length:371},(_,i)=>{const d=new Date(start);d.setUTCDate(d.getUTCDate()+i);return d;});
const total=data.reduce((s,d)=>s+d.total,0);
return <section className="activity-card" aria-label="创作贡献热力图"><div className="activity-top"><div><span className="eyebrow">CREATIVE RHYTHM</span><h2>创作记录<span>{total} 次贡献</span></h2></div><span className="activity-year">过去一年 <span>↗</span></span></div>
<div className="heatmap-scroll" ref={scroller}><div className="month-row">{Array.from({length:53},(_,week)=>{const d=days[week*7];const changed=week===0||d.getUTCMonth()!==days[(week-1)*7].getUTCMonth();return <span key={week}>{changed?`${d.getUTCMonth()+1}月`:''}</span>;})}</div><div className="heatmap-body"><div className="weekdays"><span>一</span><span>三</span><span>五</span></div><div className="heatmap-grid">{days.map(d=>{const key=d.toISOString().slice(0,10);const n=values.get(key)||0;const future=d>today;const label=`${key} · ${n} 次贡献`;return <button key={key} tabIndex={n>0?0:-1} disabled={future} aria-label={label} title={label} onFocus={()=>setHover(label)} onBlur={()=>setHover('')} onMouseEnter={()=>setHover(label)} onMouseLeave={()=>setHover('')} className={`heat-cell level-${n===0?0:n<3?1:n<6?2:n<10?3:4} ${future?'future':''}`}/>;})}</div></div></div>
<div className="activity-bottom"><span>{hover||'每日贡献汇总'}</span><div className="heat-legend">少{[0,1,2,3,4].map(n=><i key={n} className={`heat-cell level-${n}`}/>)}多</div></div>
</section>;
}
+20
View File
@@ -0,0 +1,20 @@
import Link from "next/link";
import { useRouter } from "next/router";
import { Grid2X2,Image,Film,AudioLines,BookOpen,Clapperboard,Sparkles,ArrowUpRight,Layers,Tags,Upload,Menu,X,Search } from "lucide-react";
import { useEffect,useState,type ReactNode } from "react";
const groups=[
{label:'',items:[{href:'/',label:'首页',icon:Grid2X2}]},
{label:'素材',items:[{href:'/images',label:'图片',icon:Image},{href:'/videos',label:'视频',icon:Film},{href:'/audio',label:'声音',icon:AudioLines}]},
{label:'作品',items:[{href:'/articles',label:'图文',icon:BookOpen},{href:'/motion',label:'动态',icon:Clapperboard}]},
{label:'工具',items:[{href:'/library/assets',label:'素材库',icon:Layers},{href:'/library/tags',label:'分类管理',icon:Tags},{href:'/tools/doodle',label:'线条工具',icon:Sparkles}]},
];
export function Shell({children}:{children:ReactNode}){
const router=useRouter();const [open,setOpen]=useState(false);const [query,setQuery]=useState(String(router.query.q||''));
useEffect(()=>setQuery(String(router.query.q||'')),[router.query.q]);
return <div className="app-shell"><button className="mobile-menu icon-button" aria-label="展开导航" onClick={()=>setOpen(!open)}>{open?<X size={22}/>:<Menu size={22}/>}</button>
<aside className={`sidebar ${open?'is-open':''}`}><Link href="/" className="brand" onClick={()=>setOpen(false)}><span className="brand-mark">P</span><strong>PROMPT</strong></Link>
<nav>{groups.map((g,i)=><div className="nav-group" key={i}>{g.label&&<p>{g.label}</p>}{g.items.map(item=>{const active=item.href==='/'?router.asPath.split('?')[0]==='/':router.asPath.split('?')[0].startsWith(item.href);return <Link key={item.href} href={item.href} title={item.label} className={`nav-item ${active?'active':''}`} onClick={()=>setOpen(false)}><item.icon size={24} strokeWidth={active?2.2:1.8}/><span>{item.label}</span></Link>;})}</div>)}</nav>
<div className="sidebar-bottom"><Link href="/library/import" className="import-link"><Upload size={22}/><span>导入素材</span><ArrowUpRight size={17}/></Link></div>
</aside><main className="main-content"><div className="global-topbar"><form className="global-search" role="search" onSubmit={e=>{e.preventDefault();const path=router.asPath.split('?')[0];const destination=/^\/(images|videos|audio|articles|motion)(\/|$)/.test(path)?path:'/';void router.push({pathname:destination,query:query?{q:query}:{}});}}><Search size={24}/><input aria-label="搜索素材包" placeholder="搜索素材、作品和灵感" value={query} onChange={e=>setQuery(e.target.value)}/>{query&&<button type="button" aria-label="清空搜索" onClick={()=>setQuery('')}><X size={20}/></button>}</form><span className="profile-mark" aria-label="PROMPT 个人空间">P</span></div>{children}</main>{open&&<button className="nav-scrim" aria-label="关闭导航" onClick={()=>setOpen(false)}/>}
</div>;
}