Compare commits

..

27 Commits

Author SHA1 Message Date
codex-bot b550c151bd Preserve the Studio agent documentation response handler
studio CI and deployment / verify-and-deploy (pull_request) Successful in 1m5s
waterfall-wiki CI and deployment / verify-and-deploy (pull_request) Successful in 17m44s
2026-10-28 21:17:04 +08:00
codex-bot eac2dd4cde Expect ID-only result links for both layout families
studio CI and deployment / verify-and-deploy (pull_request) Successful in 5m43s
waterfall-wiki CI and deployment / verify-and-deploy (pull_request) Failing after 1m39s
2026-10-28 21:07:53 +08:00
codex-bot df831a15ba Distinguish historical toolbox examples from current result flow
waterfall-wiki CI and deployment / verify-and-deploy (pull_request) Has been cancelled
studio CI and deployment / verify-and-deploy (pull_request) Has been cancelled
2026-10-28 21:05:04 +08:00
codex-bot de30ee4ec8 Render saved Studio results directly by ID without an editor
studio CI and deployment / verify-and-deploy (pull_request) Failing after 3m5s
waterfall-wiki CI and deployment / verify-and-deploy (pull_request) Has been cancelled
2026-10-28 21:02:21 +08:00
Zayden-Jung efffcdb1fe Merge pull request 'Fit serif headlines inside vertical slots' (#3) from codex/studio-render-api into main
studio CI and deployment / verify-and-deploy (push) Successful in 3m39s
Reviewed-on: #3
2026-10-28 11:16:27 +00:00
codex-bot 2e5fa40c19 Reserve serif glyph width inside vertical title slots
studio CI and deployment / verify-and-deploy (pull_request) Successful in 7m16s
2026-10-28 18:33:43 +08:00
Zayden-Jung c6037664e1 Merge pull request 'Align Studio previews, typography and production acceptance' (#2) from codex/studio-render-api into main
studio CI and deployment / verify-and-deploy (push) Failing after 3m17s
Reviewed-on: #2
2026-10-28 10:04:48 +00:00
codex-bot 06999cd8a6 Keep recurring acceptance cleanup scoped to each test run
studio CI and deployment / verify-and-deploy (pull_request) Successful in 3m25s
2026-10-28 17:37:46 +08:00
codex-bot ce1963f692 Improve fixed-layout copy contrast and correct SVG title hydration
studio CI and deployment / verify-and-deploy (pull_request) Successful in 7m29s
2026-10-28 17:27:28 +08:00
codex-bot 5beddf1d85 Run server acceptance through CI artifacts and clean task temporaries
studio CI and deployment / verify-and-deploy (pull_request) Successful in 8m10s
2026-10-28 16:25:29 +08:00
codex-bot aa1509df8a Match native catalogue previews and fit vertical title line boxes 2026-10-28 16:12:31 +08:00
codex-bot 4848ecc528 Wait for the actual category navigation landmark 2026-10-28 15:43:47 +08:00
codex-bot 833a345b85 Make production acceptance checks retain evidence and clean test records 2026-10-28 15:42:10 +08:00
codex-bot bfb646fcc9 Track production Studio acceptance scripts for Git delivery 2026-10-28 15:18:26 +08:00
Zayden-Jung 5c1c2bede6 Merge pull request 'Build Studio visual layout API library' (#1) from codex/studio-render-api into main
waterfall-wiki CI and deployment / verify-and-deploy (push) Successful in 5m6s
studio CI and deployment / verify-and-deploy (push) Successful in 5m20s
Reviewed-on: #1
2026-10-28 07:12:46 +00:00
codex-bot dd75e57b66 Size layout image derivatives to the mobile viewport
waterfall-wiki CI and deployment / verify-and-deploy (pull_request) Has been cancelled
studio CI and deployment / verify-and-deploy (pull_request) Has been cancelled
2026-10-28 15:07:41 +08:00
codex-bot dba9785379 Build Studio visual layout library with recoverable design CRUD
studio CI and deployment / verify-and-deploy (pull_request) Successful in 5m33s
waterfall-wiki CI and deployment / verify-and-deploy (pull_request) Successful in 16m52s
2026-10-28 14:45:37 +08:00
codex-bot ee4d818eed Add reproducible shadow cover layout and API publication tools 2026-10-27 21:58:35 +08:00
codex-bot e57f7b7518 Add reversible post archiving across Wiki discovery and feeds
waterfall-wiki CI and deployment / verify-and-deploy (push) Successful in 18m21s
2026-10-27 21:09:57 +08:00
codex-bot 3beb607cf6 Commit active native text before saving with keyboard shortcuts
studio CI and deployment / verify-and-deploy (push) Successful in 5m32s
2026-10-27 21:08:46 +08:00
codex-bot fef96a5819 Generate workspace element IDs on HTTP origins without randomUUID
studio CI and deployment / verify-and-deploy (push) Successful in 5m5s
2026-10-27 21:06:58 +08:00
codex-bot c5b80739db Isolate workspace panels from inherited page chrome spacing
studio CI and deployment / verify-and-deploy (push) Successful in 5m33s
2026-10-27 21:01:44 +08:00
codex-bot 9c8ab17efa Verify restored native workspace geometry and support curved type styling
studio CI and deployment / verify-and-deploy (push) Successful in 5m40s
2026-10-27 17:47:42 +08:00
codex-bot 9f496688d2 Make layer ordering swap adjacent elements and apply shape corner radius
studio CI and deployment / verify-and-deploy (push) Successful in 5m2s
2026-10-27 17:44:25 +08:00
codex-bot 8ccc77dd79 Include Wiki parameter validator in isolated Studio CI tests
studio CI and deployment / verify-and-deploy (push) Successful in 5m22s
2026-10-27 17:41:37 +08:00
codex-bot ad1f83d398 Modernize native layout editing workspace and shared design parameters
studio CI and deployment / verify-and-deploy (push) Failing after 2m22s
waterfall-wiki CI and deployment / verify-and-deploy (push) Successful in 17m53s
2026-10-27 17:37:26 +08:00
codex-bot 3069a797b4 Publish saved Studio pages as atomic Wiki posts and document agent editing 2026-10-27 17:37:22 +08:00
57 changed files with 1136 additions and 262 deletions
+21
View File
@@ -5,12 +5,18 @@ on:
paths:
- 'apps/studio/**'
- 'scripts/deploy-studio.sh'
- 'scripts/verify-studio-production.sh'
- 'scripts/verify-studio-library.mjs'
- 'scripts/verify-studio-visual.cjs'
- '.gitea/workflows/studio.yml'
- 'pnpm-workspace.yaml'
pull_request:
paths:
- 'apps/studio/**'
- 'scripts/deploy-studio.sh'
- 'scripts/verify-studio-production.sh'
- 'scripts/verify-studio-library.mjs'
- 'scripts/verify-studio-visual.cjs'
- '.gitea/workflows/studio.yml'
- 'pnpm-workspace.yaml'
workflow_dispatch:
@@ -28,3 +34,18 @@ jobs:
- name: Release studio
if: gitea.ref == 'refs/heads/main' && (gitea.event_name == 'push' || gitea.event_name == 'workflow_dispatch')
run: bash scripts/deploy-studio.sh "${{ gitea.sha }}"
- name: Verify the deployed Studio API and native pages
if: gitea.ref == 'refs/heads/main' && (gitea.event_name == 'push' || gitea.event_name == 'workflow_dispatch')
run: bash scripts/verify-studio-production.sh
- name: Save server acceptance evidence
id: acceptance_evidence
if: always()
uses: actions/upload-artifact@v3
with:
name: studio-production-acceptance
path: artifacts/studio-acceptance/
if-no-files-found: ignore
retention-days: 7
- name: Remove temporary acceptance output after upload
if: always() && steps.acceptance_evidence.outcome == 'success'
run: rm -rf artifacts/studio-acceptance
+2
View File
@@ -8,6 +8,8 @@ RUN pnpm fetch --frozen-lockfile --fetch-timeout=300000 --network-concurrency=8
COPY apps/studio/package.json ./
RUN pnpm install --offline --frozen-lockfile
COPY apps/studio/ .
# Compare the two public parameter validators inside the isolated CI build.
COPY apps/waterfall-wiki/src/lib/layout-parameters.ts /waterfall-wiki/src/lib/layout-parameters.ts
RUN pnpm typecheck && pnpm test && pnpm build && pnpm test:smoke
FROM node:24-bookworm-slim
WORKDIR /app
+10 -5
View File
@@ -1,17 +1,22 @@
/** CI-only isolated runtime checks, never a local preview workflow. */
import {spawn} from 'node:child_process';import {once} from 'node:events';import {createServer} from 'node:net';import {createServer as createHttpServer} from 'node:http';import assert from 'node:assert/strict';import {setTimeout} from 'node:timers/promises';
const designId='00000000-0000-4000-8000-000000000001',missingId='00000000-0000-4000-8000-000000000002';
const standardId='00000000-0000-4000-8000-000000000003';
let reads=0;
const wiki=createHttpServer((req,res)=>{reads++;assert.equal(req.headers.cookie,'session=smoke-test');res.setHeader('Content-Type','application/json');if(!req.url.endsWith(designId)){res.writeHead(404);return res.end('{}')}res.end(JSON.stringify({design:{id:designId,name:'已保存的实际页面',layoutId:'ref-01',revision:3,url:'/studio/designs/'+designId,parameters:{texts:{T01:{value:'确定的页面文字',color:'#123456'}},images:{I01:{color:'#abcdef'}},decorations:{D01:{hidden:true}},paper:'#eeeeee'}}}))});
const wiki=createHttpServer((req,res)=>{reads++;assert.equal(req.headers.cookie,'session=smoke-test');res.setHeader('Content-Type','application/json');const standard=req.url.endsWith(standardId);if(!standard&&!req.url.endsWith(designId)){res.writeHead(404);return res.end('{}')}res.end(JSON.stringify({design:{id:standard?standardId:designId,name:'已保存的实际页面',layoutId:standard?'standard-01':'ref-01',revision:3,url:'/studio/designs/'+designId,parameters:{added:[{id:'user-smoke',kind:'text',role:'Added text',box:[10,10,20,10],direction:'horizontal',text:'新增元素已恢复',reading:'custom'}],layers:{T01:{x:12,rotation:25,opacity:.7},'user-smoke':{z:12}},texts:{T01:{value:'确定的页面文字',color:'#123456'}},images:{I01:{color:'#abcdef'}},decorations:{D01:{hidden:true}},paper:'#eeeeee'}}}))});
wiki.listen(0,'127.0.0.1');await once(wiki,'listening');
const socket=createServer();socket.listen(0,'127.0.0.1');await once(socket,'listening');const port=socket.address().port;await new Promise(r=>socket.close(r));const child=spawn(process.execPath,['.next/standalone/server.js'],{env:{...process.env,PORT:String(port),HOSTNAME:'127.0.0.1',STUDIO_WIKI_ORIGIN:'http://127.0.0.1:'+wiki.address().port},stdio:'inherit'}),base='http://127.0.0.1:'+port;
try{let ready=false;for(let i=0;i<60;i++){try{if((await fetch(base+'/studio/api/health')).ok){ready=true;break}}catch{}await setTimeout(250)}assert.ok(ready);const catalog=await fetch(base+'/studio/api/layouts').then(r=>r.json());assert.equal(catalog.layouts.length,27);
for(const l of catalog.layouts){const page=await fetch(base+l.url);assert.equal(page.status,200,l.id);const html=await page.text();assert.ok(html.includes(l.name));assert.ok(html.includes('data-layout-id="'+l.id+'"'));assert.ok(!/<svg|<img|data:image|trial-controls/.test(html),'Default page must use native elements, not source imagery');const schema=await fetch(base+l.api).then(r=>r.json());assert.equal(schema.id,l.id);for(const s of schema.elements)assert.ok(html.includes('data-element="'+s.id+'"'));const original=await fetch(base+l.api+'?format=svg').then(r=>r.text());assert.ok(original.includes('data-layout-id="'+l.id+'"'));const text=schema.elements.find(e=>e.kind==='text');const result=await fetch(base+l.api,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({texts:{[text.id]:{value:'API render <test>'}}})});assert.equal(result.status,200);assert.ok((await result.text()).includes('&lt;'));}
try{let ready=false;for(let i=0;i<60;i++){try{if((await fetch(base+'/studio/api/health')).ok){ready=true;break}}catch{}await setTimeout(250)}assert.ok(ready);const library=await fetch(base+'/studio').then(r=>r.text());assert.ok(library.includes('standard-01'));assert.ok(library.includes('ref-27'));const catalog=await fetch(base+'/studio/api/layouts').then(r=>r.json());assert.equal(catalog.layouts.length,28);
for(const l of catalog.layouts){const page=await fetch(base+l.url);assert.equal(page.status,200,l.id);const html=await page.text();assert.ok(html.includes(l.name));assert.ok(html.includes('data-layout-id="'+l.id+'"'));assert.ok(!/<svg|<img|data:image|trial-controls|page-tools|workbench-top|contenteditable|编辑页面/.test(html),'Default page must use native elements, not source imagery');const schema=await fetch(base+l.api).then(r=>r.json());assert.equal(schema.id,l.id);for(const s of schema.elements)assert.ok(html.includes('data-element="'+s.id+'"'));if(l.family==='standard'){assert.equal((await fetch(base+l.api+'?format=svg')).status,400);continue;}const original=await fetch(base+l.api+'?format=svg').then(r=>r.text());assert.ok(original.includes('data-layout-id="'+l.id+'"'));const text=schema.elements.find(e=>e.kind==='text');const result=await fetch(base+l.api,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({texts:{[text.id]:{value:'API render <test>'}}})});assert.equal(result.status,200);assert.ok((await result.text()).includes('&lt;'));}
assert.equal(reads,0,'Default pages never load a saved design');
const headers={cookie:'session=smoke-test'};
const saved=await fetch(base+'/studio/layouts/ref-01?id='+designId,{headers});assert.equal(saved.status,200);const savedHtml=await saved.text();assert.ok(savedHtml.includes('确定的页面文字'));assert.ok(savedHtml.includes('data-design-id="'+designId+'"'));assert.ok(savedHtml.includes('#123456'));assert.ok(!savedHtml.includes('data-element="D01"'));assert.ok(!savedHtml.includes('data:image'));
for(const id of [designId,standardId]){
const saved=await fetch(base+'/studio/template-layout?id='+id,{headers});assert.equal(saved.status,200);const savedHtml=await saved.text();assert.ok(savedHtml.includes('确定的页面文字'));assert.ok(savedHtml.includes('新增元素已恢复'));assert.ok(savedHtml.includes('data-element="user-smoke"'));assert.ok(savedHtml.includes('rotate(25deg)'));assert.ok(savedHtml.includes('opacity:0.7'));assert.ok(savedHtml.includes('data-design-id="'+id+'"'));assert.ok(savedHtml.includes('#123456'));assert.ok(!savedHtml.includes('data-element="D01"'));assert.ok(!savedHtml.includes('data:image'));assert.ok(!/page-tools|workbench-top|contenteditable|编辑页面/.test(savedHtml));
}
for(const path of ['/studio/template-layout','/studio/template-layout?id=invalid','/studio/template-layout?id='+missingId,'/studio/template-layout?id='+designId+'&id='+standardId])assert.equal((await fetch(base+path,{headers})).status,404);
assert.equal((await fetch(base+'/studio/layouts/ref-02?id='+designId,{headers})).status,404);
assert.equal((await fetch(base+'/studio/layouts/ref-01?id='+missingId,{headers})).status,404);
const beforeInvalid=reads;assert.equal((await fetch(base+'/studio/layouts/ref-01?id=invalid',{headers})).status,404);assert.equal(reads,beforeInvalid);
const legacy=await fetch(base+'/studio/designs/'+designId,{headers,redirect:'manual'});assert.equal(legacy.status,307);assert.equal(legacy.headers.get('location'),'/studio/layouts/ref-01?id='+designId);
const legacy=await fetch(base+'/studio/designs/'+designId,{headers,redirect:'manual'});assert.equal(legacy.status,307);assert.equal(legacy.headers.get('location'),'/studio/template-layout?id='+designId);
const old=await fetch(base+'/studio/layouts/ref-01?id='+designId,{headers,redirect:'manual'});assert.equal(old.status,307);assert.equal(old.headers.get('location'),'/studio/template-layout?id='+designId);
assert.equal((await fetch(base+'/studio/layouts/ref-28')).status,404);assert.equal((await fetch(base+'/studio/api/layouts/ref-01',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({texts:{I01:{value:'bad'}}})})).status,400);console.log('All 27 native pages, server-loaded saved IDs, legacy redirects and render APIs passed');}finally{child.kill('SIGTERM');await once(child,'exit');await new Promise(r=>wiki.close(r))}
+1 -1
View File
@@ -8,7 +8,7 @@ export function LayoutCanvas({layout,params,guides=false,imageSources={}}:{layou
if(kind==='text'&&t){const lines=t.value.split('\n'),len=(v:string)=>Array.from(v).reduce((a,c)=>a+(/[\u3400-\u9fff]/.test(c)?1:.6),0),vertical=s.direction==='vertical',size=Math.min(vertical?w*.9:h/(lines.length*1.2),vertical?h/Math.max(1,Array.from(t.value).length):w/Math.max(1,...lines.map(len)))*(t.scale||1),align=t.align||'start';return <g key={s.id} data-slot={s.id} fill={t.color||'#26362f'} fontFamily="Arial,'Noto Sans CJK SC','PingFang SC',sans-serif"><defs><clipPath id={id+'clip'}><rect x={x} y={y} width={w} height={h}/></clipPath></defs><g clipPath={`url(#${id}clip)`}>{vertical?Array.from(t.value.replaceAll('\n','')).map((c,i)=><text key={i} x={x+w/2} y={y+size*(i+.85)} textAnchor="middle" fontSize={size}>{c}</text>):s.direction==='curved'?<><defs><path id={id+'path'} d={`M${x} ${y+h*.2} Q${x+w/2} ${y+h*1.7} ${x+w} ${y+h*.2}`}/></defs><text fontSize={size}><textPath href={'#'+id+'path'}>{t.value}</textPath></text></>:lines.map((l,i)=><text key={i} x={x+(align==='middle'?w/2:align==='end'?w:0)} y={y+size*(.88+i*1.2)} textAnchor={align} fontSize={size}>{l}</text>)}</g></g>}
if(kind==='decoration'&&d?.hidden)return null;
const fill=kind==='image'?im?.color:d?.color;
if(fill||im?.assetId)return <g key={s.id} data-slot={s.id}><defs><mask id={id} maskUnits="userSpaceOnUse" x={x} y={y} width={w} height={h} style={{maskType:'alpha'}}><image href={s.shape||s.raster} x={x} y={y} width={w} height={h}/></mask></defs><g mask={'url(#'+id+')'}>{fill&&<rect x={x} y={y} width={w} height={h} fill={fill}/>} {im?.assetId&&<image href={imageSources[im.assetId]||'/api/media/'+im.assetId} x={x} y={y} width={w} height={h} preserveAspectRatio={im.fit==='contain'?'xMidYMid meet':'xMidYMid slice'}/>}</g></g>;
if(fill||im?.assetId)return <g key={s.id} data-slot={s.id}><defs><mask id={id} maskUnits="userSpaceOnUse" x={x} y={y} width={w} height={h} style={{maskType:'alpha'}}><image href={s.shape||s.raster} x={x} y={y} width={w} height={h}/></mask></defs><g mask={'url(#'+id+')'}>{fill&&<rect x={x} y={y} width={w} height={h} fill={fill}/>} {im?.assetId&&<image href={imageSources[im.assetId]||'/api/preview?'+new URLSearchParams({source:'/api/media/'+im.assetId,width:'960'})} x={x} y={y} width={w} height={h} preserveAspectRatio={im.fit==='contain'?'xMidYMid meet':'xMidYMid slice'}/>}</g></g>;
return <image key={s.id} data-slot={s.id} href={s.raster} x={x} y={y} width={w} height={h}/>;
}))}</>}{guides&&layout.elements.map(s=>{const[x,y,w,h]=s.box,color=s.kind==='text'?'#2765da':s.kind==='image'?'#d86b27':'#08875d';return <g key={s.id} aria-hidden="true"><rect x={x} y={y} width={w} height={h} fill="none" stroke={color} strokeWidth=".35"/><text x={x} y={y+3} fontSize="3" fill={color}>{s.id}</text></g>})}</svg>;
}
@@ -1,3 +1,4 @@
import {referencePreview} from '../lib/layout-images-client';
import {useState} from 'react';
import Head from 'next/head';
import {SourceCover,selections,type CoverValues} from './SourceCover';
@@ -9,5 +10,5 @@ export function LayoutSelection(){
async function download(format:'svg'|'json'){
try{setStatus('正在生成…');const r=await fetch('/studio/api/export/layout-selection?format='+format,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({layoutId:layout.id,...current})});if(!r.ok)throw Error();const url=URL.createObjectURL(await r.blob()),a=document.createElement('a');a.href=url;a.download=layout.id+'.'+format;a.click();setTimeout(()=>URL.revokeObjectURL(url),500);setStatus('已导出当前模板。')}catch{setStatus('导出失败,请重试。')}
}
return <main className="template-trial"><Head><title>三种排版 · Studio 工具</title></Head><header className="trial-nav"><a href={tutorialPost}>← PROMPT 使用教程</a><span>STUDIO / LAYOUT SELECTION</span></header><section className="trial-intro"><div><small>REF-01 / REF-07 / REF-26</small><h1>三个构图,各有位置。</h1><p>切换真实原图对应的模板,分别试文字与配色。图位与装饰按教程构件重建为干净矢量;当前只放占位内容。</p></div></section><div className="trial-workspace"><aside className="trial-controls"><h2>选择与编辑</h2><label>排版<select value={active} onChange={e=>{setActive(Number(e.target.value));setStatus('')}}>{selections.map((l,i)=><option key={l.id} value={i}>{l.id} · {l.name}</option>)}</select></label>{layout.slots.filter(s=>s.kind==='text').map(s=><label key={s.id}>{s.id} · {s.role}<textarea rows={current.fields[s.id]?.includes('\n')?3:1} maxLength={120} value={current.fields[s.id]||''} onChange={e=>update({fields:{...current.fields,[s.id]:e.target.value}})}/></label>)}<div className="trial-colors"><label>主图色<input type="color" value={current.color} onChange={e=>update({color:e.target.value})}/></label><label>副图色<input type="color" value={current.accent} onChange={e=>update({accent:e.target.value})}/></label></div><label className="trial-switch"><input type="checkbox" checked={guides} onChange={e=>setGuides(e.target.checked)}/>显示构件边界</label><div className="trial-actions"><button className="trial-primary" onClick={()=>void download('svg')}>下载当前 SVG</button><button onClick={()=>void download('json')}>下载参数 JSON</button></div><p className="trial-help">每张模板单独保留本页修改,刷新恢复初始值。下载 SVG 为无边界线的正式图;原始低分辨率图层在 JSON 中保留作对照。</p><p role="status">{status}</p></aside><div><div className="selection-preview"><SourceCover layout={layout} values={current} guides={guides}/></div><div className="selection-thumbs">{selections.map((l,i)=><button key={l.id} aria-pressed={active===i} onClick={()=>setActive(i)}><SourceCover layout={l} values={values[i]}/><span>{l.id}</span></button>)}</div><details className="trial-reference"><summary>原图与构件坐标</summary><div className="trial-reference-body"><img src={layout.referenceUrl} alt={layout.name+'原图'}/><div><a href={layout.tutorialUrl}>阅读这张原图的教程 ↗</a><table><thead><tr><th>ID</th><th>构件</th><th>x,y,w,h</th></tr></thead><tbody>{layout.slots.map(s=><tr key={s.id}><td>{s.id}</td><td>{s.role}</td><td>{s.box.join(', ')}</td></tr>)}</tbody></table></div></div></details></div></div></main>;
return <main className="template-trial"><Head><title>三种排版 · Studio 工具</title></Head><header className="trial-nav"><a href={tutorialPost}>← PROMPT 使用教程</a><span>STUDIO / LAYOUT SELECTION</span></header><section className="trial-intro"><div><small>REF-01 / REF-07 / REF-26</small><h1>三个构图,各有位置。</h1><p>切换真实原图对应的模板,分别试文字与配色。图位与装饰按教程构件重建为干净矢量;当前只放占位内容。</p></div></section><div className="trial-workspace"><aside className="trial-controls"><h2>选择与编辑</h2><label>排版<select value={active} onChange={e=>{setActive(Number(e.target.value));setStatus('')}}>{selections.map((l,i)=><option key={l.id} value={i}>{l.id} · {l.name}</option>)}</select></label>{layout.slots.filter(s=>s.kind==='text').map(s=><label key={s.id}>{s.id} · {s.role}<textarea rows={current.fields[s.id]?.includes('\n')?3:1} maxLength={120} value={current.fields[s.id]||''} onChange={e=>update({fields:{...current.fields,[s.id]:e.target.value}})}/></label>)}<div className="trial-colors"><label>主图色<input type="color" value={current.color} onChange={e=>update({color:e.target.value})}/></label><label>副图色<input type="color" value={current.accent} onChange={e=>update({accent:e.target.value})}/></label></div><label className="trial-switch"><input type="checkbox" checked={guides} onChange={e=>setGuides(e.target.checked)}/>显示构件边界</label><div className="trial-actions"><button className="trial-primary" onClick={()=>void download('svg')}>下载当前 SVG</button><button onClick={()=>void download('json')}>下载参数 JSON</button></div><p className="trial-help">每张模板单独保留本页修改,刷新恢复初始值。下载 SVG 为无边界线的正式图;原始低分辨率图层在 JSON 中保留作对照。</p><p role="status">{status}</p></aside><div><div className="selection-preview"><SourceCover layout={layout} values={current} guides={guides}/></div><div className="selection-thumbs">{selections.map((l,i)=><button key={l.id} aria-pressed={active===i} onClick={()=>setActive(i)}><SourceCover layout={l} values={values[i]}/><span>{l.id}</span></button>)}</div><details className="trial-reference"><summary>原图与构件坐标</summary><div className="trial-reference-body"><img src={referencePreview(layout.referenceUrl)} alt={layout.name+'原图'}/><div><a href={layout.tutorialUrl}>阅读这张原图的教程 ↗</a><table><thead><tr><th>ID</th><th>构件</th><th>x,y,w,h</th></tr></thead><tbody>{layout.slots.map(s=><tr key={s.id}><td>{s.id}</td><td>{s.role}</td><td>{s.box.join(', ')}</td></tr>)}</tbody></table></div></div></details></div></div></main>;
}
+52 -35
View File
@@ -1,8 +1,10 @@
import {useEffect,useRef,useState,type CSSProperties,type KeyboardEvent} from 'react';
import {CurvedCopy} from './NativeCurvedCopy';
import {useEffect,useRef,useState,type CSSProperties,type KeyboardEvent,type PointerEvent} from 'react';
import {ArrowLeft,MousePointer2,Type,Square,Circle,ImagePlus,Layers,SlidersHorizontal,Undo2,Redo2,Copy,Trash2,Eye,EyeOff,Lock,Unlock,ChevronUp,ChevronDown,Minus,Plus,Scan,Save} from 'lucide-react';
import Head from 'next/head';
import type {Layout,Parameters,Slot} from '../lib/layout-parameters';
import type {Layout,Parameters,Slot,LayerValue,AddedSlot} from '../lib/layout-parameters';
import {parameters} from '../lib/layout-parameters';
import {decorationKind,defaultText,designUrl,emptyParameters,imageShape,paperColor,slotPosition,textColor,textSize,type Design} from '../lib/native-layout';
import {decorationKind,defaultText,designUrl,emptyParameters,imageShape,newElementId,paperColor,slotPosition,textColor,textSize,type Design} from '../lib/native-layout';
export type LayoutPageProps={layout:Layout;design:Design|null};
function TextElement({value,editable,onChange,onInvalid,onDirty,...props}:{value:string;editable:boolean;onChange:(text:string)=>void;onInvalid:()=>void;onDirty:()=>void;className:string;style:CSSProperties}){
@@ -10,25 +12,38 @@ function TextElement({value,editable,onChange,onInvalid,onDirty,...props}:{value
useEffect(()=>{if(ref.current&&document.activeElement!==ref.current)ref.current.textContent=value},[value]);
return <div {...props} ref={ref} contentEditable={editable?'plaintext-only':false} suppressContentEditableWarning spellCheck={false} role={editable?'textbox':undefined} aria-multiline={editable||undefined} onInput={onDirty} onBlur={e=>{const next=(e.currentTarget.innerText||'').replaceAll('\r','');if(Array.from(next).length>500||next.split('\n').length>8){e.currentTarget.textContent=value;onInvalid()}else if(next!==value)onChange(next)}}>{value}</div>;
}
function CurvedCopy({layout,slot,value,style}:{layout:Layout;slot:Slot;value:string;style:CSSProperties}){
const letters=Array.from(value),tall=slot.box[3]>slot.box[2];
return <div className="native-copy native-arc" aria-label={value} style={style}>{letters.map((letter,index)=>{const t=index/Math.max(1,letters.length-1),x=tall?90-75*Math.sin(Math.PI*t):4+92*t,y=tall?2+94*t:5+75*Math.sin(Math.PI*t),angle=tall?90+Math.cos(Math.PI*t)*18:Math.atan2(slot.box[3]*.75*Math.PI*Math.cos(Math.PI*t),slot.box[2]*.92)*180/Math.PI;return <span key={index} aria-hidden="true" style={{left:x+'%',top:y+'%',transform:`translate(-50%,-50%) rotate(${angle}deg)`}}>{letter===' '?'\u00a0':letter}</span>})}</div>;
}
export function LayoutWorkbench({layout,design:initialDesign}:LayoutPageProps){
const [params,setParams]=useState<Parameters>(initialDesign?.parameters||emptyParameters()),[design,setDesign]=useState(initialDesign),[editing,setEditing]=useState(false),[selected,setSelected]=useState<string|null>(null),[name,setName]=useState(initialDesign?.name||layout.name),[status,setStatus]=useState(''),[busy,setBusy]=useState(false),[dirty,setDirty]=useState(false),[history,setHistory]=useState<Parameters[]>([]);
const upload=useRef<HTMLInputElement>(null),slot=layout.elements.find(s=>s.id===selected);
const [params,setParams]=useState<Parameters>(initialDesign?.parameters||emptyParameters()),[design,setDesign]=useState(initialDesign),[editing,setEditing]=useState(false),[selected,setSelected]=useState<string|null>(null),[name,setName]=useState(initialDesign?.name||layout.name),[status,setStatus]=useState(''),[busy,setBusy]=useState(false),[dirty,setDirty]=useState(false),[history,setHistory]=useState<Parameters[]>([]),[future,setFuture]=useState<Parameters[]>([]),[zoom,setZoom]=useState(1),[panel,setPanel]=useState<'layers'|'properties'|null>(null),[textEditing,setTextEditing]=useState<string|null>(null),[conflict,setConflict]=useState(false);
const canvas=useRef<HTMLElement>(null),viewport=useRef<HTMLDivElement>(null);
const paramsRef=useRef(params);paramsRef.current=params;
const elements=[...layout.elements,...(params.added||[])];
const upload=useRef<HTMLInputElement>(null),slot=elements.find(s=>s.id===selected);
useEffect(()=>{const warn=(event:BeforeUnloadEvent)=>{if(dirty){event.preventDefault();event.returnValue=''}};window.addEventListener('beforeunload',warn);return()=>window.removeEventListener('beforeunload',warn)},[dirty]);
function patch(next:Parameters){try{const valid=parameters(layout,next);setHistory(old=>[...old.slice(-39),params]);setParams(valid);setDirty(true);setStatus('')}catch(e){setStatus(e instanceof Error?e.message:'修改失败')}}
function patch(next:Parameters){try{const valid=parameters(layout,next);setHistory(old=>[...old.slice(-39),params]);setFuture([]);paramsRef.current=valid;setParams(valid);setDirty(true);setStatus('')}catch(e){setStatus(e instanceof Error?e.message:'修改失败')}}
function updateText(s:Slot,changes:Partial<Parameters['texts'][string]>){patch({...params,texts:{...params.texts,[s.id]:{...params.texts[s.id],value:params.texts[s.id]?.value??defaultText(layout,s),...changes}}})}
function layer(s:Slot):LayerValue{return params.layers?.[s.id]||{}}
function updateLayer(s:Slot,changes:LayerValue){patch({...params,layers:{...params.layers,[s.id]:{...layer(s),...changes}}})}
function undo(){if(!history.length)return;setFuture(f=>[params,...f]);setParams(history[history.length-1]);setHistory(history.slice(0,-1));setDirty(true)}
function redo(){if(!future.length)return;setHistory(h=>[...h,params]);setParams(future[0]);setFuture(future.slice(1));setDirty(true)}
function fit(){if(!viewport.current)return;setZoom(Math.max(.1,Math.min(2,(viewport.current.clientWidth-96)/860,(viewport.current.clientHeight-96)/(860*layout.height/layout.width))))}
function add(kind:string,shape?:'rectangle'|'ellipse'){const id=newElementId();const added:AddedSlot={id,kind,role:kind==='text'?'新文字':kind==='image'?'新图片':shape==='ellipse'?'椭圆':'矩形',box:[layout.width*.15,layout.height*.15,layout.width*.3,layout.height*.16],direction:'horizontal',text:kind==='text'?'输入文字':null,reading:'custom',...(shape?{shape}:{})};patch({...params,added:[...(params.added||[]),added]});setSelected(id);setPanel('properties')}
function reorder(direction:number){if(!slot||layer(slot).locked)return;const ordered=['image','decoration','text'].flatMap(kind=>elements.filter(e=>e.kind===kind)).sort((a,b)=>(layer(a).z??(a.kind==='text'?3:a.kind==='image'?1:2))-(layer(b).z??(b.kind==='text'?3:b.kind==='image'?1:2)));const index=ordered.findIndex(e=>e.id===slot.id),target=index+direction;if(target<0||target>=ordered.length)return;[ordered[index],ordered[target]]=[ordered[target],ordered[index]];patch({...params,layers:{...params.layers,...Object.fromEntries(ordered.map((e,i)=>[e.id,{...layer(e),z:i+1}]))}})}
function remove(){if(!slot||layer(slot).locked)return;updateLayer(slot,{hidden:true});setSelected(null)}
function duplicate(){if(!slot||layer(slot).locked)return;const id=newElementId(),l=layer(slot),group=slot.kind==='text'?'texts':slot.kind==='image'?'images':'decorations';patch({...params,added:[...(params.added||[]),{...slot,id,direction:'horizontal',reading:'custom',role:slot.role+' 副本',text:slot.kind==='text'?params.texts[slot.id]?.value??defaultText(layout,slot):null}],layers:{...params.layers,[id]:{...l,x:(l.x??slot.box[0])+2,y:(l.y??slot.box[1])+2,locked:false}},[group]:{...params[group],[id]:params[group][slot.id]|| (slot.kind==='text'?{value:defaultText(layout,slot)}:{})}});setSelected(id)}
function pointer(e:PointerEvent,s:Slot,mode:'move'|'resize'|'rotate'='move'){if(!editing||busy||layer(s).locked||textEditing===s.id||e.button!==0)return;e.preventDefault();e.stopPropagation();setSelected(s.id);const start=params,l=layer(s),rect=canvas.current!.getBoundingClientRect(),x=e.clientX,y=e.clientY,bx=l.x??s.box[0],by=l.y??s.box[1],w=l.width??s.box[2],h=l.height??s.box[3];const cx=rect.left+(bx+w/2)/layout.width*rect.width,cy=rect.top+(by+h/2)/layout.height*rect.height;let next=start;const move=(event:globalThis.PointerEvent)=>{const dx=(event.clientX-x)/rect.width*layout.width,dy=(event.clientY-y)/rect.height*layout.height;let change:LayerValue=mode==='move'?{x:bx+dx,y:by+dy}:mode==='resize'?{width:Math.max(.1,w+dx),height:Math.max(.1,h+dy)}:{rotation:Math.max(-360,Math.min(360,(l.rotation||0)+(Math.atan2(event.clientY-cy,event.clientX-cx)-Math.atan2(y-cy,x-cx))*180/Math.PI))};next={...start,layers:{...start.layers,[s.id]:{...l,...change}}};setParams(next)};const end=()=>{window.removeEventListener('pointermove',move);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);if(next!==start){setHistory(old=>[...old.slice(-39),start]);setFuture([]);setDirty(true)}};window.addEventListener('pointermove',move);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end)}
useEffect(()=>{if(editing){fit()}},[editing]);
useEffect(()=>{function key(e:globalThis.KeyboardEvent){if(!editing||busy)return;const typing=(e.target as HTMLElement).closest('input,textarea,select,[contenteditable="plaintext-only"]');if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='s'){e.preventDefault();if(!busy)void save();return}if(typing)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(null);setTextEditing(null)}else if(slot&&!layer(slot).locked&&['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(e.key)){e.preventDefault();const step=e.shiftKey?10:1,l=layer(slot);updateLayer(slot,{x:(l.x??slot.box[0])+(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0),y:(l.y??slot.box[1])+(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0)})}}window.addEventListener('keydown',key);return()=>window.removeEventListener('keydown',key)});
function select(s:Slot){if(busy)return;setEditing(true);setSelected(s.id)}
function reset(s:Slot){const group=s.kind==='text'?'texts':s.kind==='image'?'images':'decorations',values={...params[group]};delete values[s.id];patch({...params,[group]:values})}
function keySelect(e:KeyboardEvent,s:Slot){if(e.key==='ContextMenu'||(e.shiftKey&&e.key==='F10')){e.preventDefault();select(s)}if(e.key==='Escape')setSelected(null)}
async function save(copy=false){
// Commit an active native text edit before keyboard-triggered saving.
if(document.activeElement instanceof HTMLElement)document.activeElement.blur();
setBusy(true);try{
const valid=parameters(layout,params),updating=design&&!copy;
const valid=parameters(layout,paramsRef.current),updating=design&&!copy;
const response=await fetch('/api/studio/designs'+(updating?'/'+design.id:''),{method:updating?'PATCH':'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(updating?{name,parameters:valid,revision:design.revision}:{name,layoutId:layout.id,parameters:valid})});
const data=await response.json();if(!response.ok)throw Error(data.error||'保存失败');
setDesign(data.design);setDirty(false);setEditing(false);setSelected(null);setStatus('已保存,当前网址可直接打开此页面');
const data=await response.json();if(!response.ok){if(response.status===409)setConflict(true);throw Error(data.error||'保存失败')};setConflict(false);
setDesign(data.design);setDirty(false);setStatus('已保存,当前网址可直接打开此页面');
window.history.replaceState(window.history.state,'',designUrl(layout.id,data.design.id));
}catch(e){setStatus(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}
}
@@ -36,36 +51,38 @@ export function LayoutWorkbench({layout,design:initialDesign}:LayoutPageProps){
if(!file||!slot||slot.kind!=='image')return;const target=slot.id;setBusy(true);setStatus('正在上传图片…');
try{const body=new FormData();body.append('assetOnly','true');body.append('kind','image');body.append('files',file);const response=await fetch('/api/upload',{method:'POST',body});const data=await response.json();if(!response.ok||!data.assets?.[0])throw Error(data.error||'上传失败');patch({...params,images:{...params.images,[target]:{...params.images[target],assetId:data.assets[0]}}});setStatus('图片已替换,保存后生效于此网址')}catch(e){setStatus(e instanceof Error?e.message:'上传失败')}finally{setBusy(false);if(upload.current)upload.current.value=''}
}
const l=slot?layer(slot):{},t=slot?params.texts[slot.id]:undefined,im=slot?params.images[slot.id]:undefined;
const selectedColor=slot?(slot.kind==='text'?params.texts[slot.id]?.color||textColor(layout.id,slot):slot.kind==='image'?params.images[slot.id]?.color||String(imageShape(layout,slot).backgroundColor):params.decorations[slot.id]?.color||'#83908a'):'';
return <main className={'native-layout-page'+(editing?' is-editing':'')}>
<Head><title>{name} · Prompt</title><meta name="description" content={layout.name+' · 可直接编辑的排版页面'}/></Head>
<article className={'native-layout '+layout.id} inert={busy} aria-label={layout.name} data-layout-id={layout.id} data-design-id={design?.id||undefined} style={{aspectRatio:`${layout.width}/${layout.height}`,backgroundColor:params.paper||paperColor(layout.id)}}>
{['image','decoration','text'].flatMap(kind=>layout.elements.filter(s=>s.kind===kind).map(s=>{
const t=params.texts[s.id],im=params.images[s.id],d=params.decorations[s.id],text=t?.value??defaultText(layout,s),hidden=kind==='decoration'&&d?.hidden;
const position=slotPosition(layout,s),common={onContextMenu:(e:React.MouseEvent)=>{e.preventDefault();select(s)},onKeyDown:(e:KeyboardEvent)=>keySelect(e,s),onClick:()=>{if(editing)setSelected(s.id)},onDoubleClick:()=>select(s),tabIndex:editing?0:undefined,'data-element':s.id,'aria-label':s.role};
{editing&&<header className="workbench-top"><a href="/explore/8eb8c76500580f7a4b56ba3c" aria-label="返回目录"><ArrowLeft size={18}/></a><span className="studio-mark">P<span>STUDIO</span></span><input aria-label="页面名称" value={name} maxLength={120} onChange={e=>{setName(e.target.value);setDirty(true)}}/><span className="save-indicator">{busy?'正在处理…':dirty?'有未保存的修改':design?'已保存':'尚未保存'}</span><button title="撤销 ⌘Z" disabled={!history.length||busy} onClick={undo}><Undo2 size={17}/></button><button title="重做 ⇧⌘Z" disabled={!future.length||busy} onClick={redo}><Redo2 size={17}/></button><button onClick={()=>{setEditing(false);setTextEditing(null);setSelected(null)}}>查看页面</button><button className="primary" disabled={busy||!name.trim()} onClick={()=>void save()}><Save size={15}/>保存</button></header>}
{editing&&<aside className={'workbench-layers '+(panel==='layers'?'mobile-open':'')} inert={busy}><div className="panel-heading"><Layers size={16}/><strong>图层与素材</strong><span>{elements.length}</span></div><div className="insert-tools"><button onClick={()=>add('text')}><Type/>文字</button><button onClick={()=>add('decoration','rectangle')}><Square/>矩形</button><button onClick={()=>add('decoration','ellipse')}><Circle/>椭圆</button><button onClick={()=>add('image')}><ImagePlus/>图片</button></div><div className="layers-caption">{layout.id.toUpperCase()} <span>从上到下排列</span></div><div className="layer-list">{[...elements].sort((a,b)=>(layer(b).z??(b.kind==='text'?3:b.kind==='image'?1:2))-(layer(a).z??(a.kind==='text'?3:a.kind==='image'?1:2))).map(s=><div key={s.id} className={'layer-row '+(selected===s.id?'active':'')+(layer(s).hidden?' muted':'')}><button className="layer-select" onClick={()=>{setSelected(s.id);setTextEditing(null)}}>{s.kind==='text'?<Type size={14}/>:s.kind==='image'?<ImagePlus size={14}/>:<Square size={14}/>}<span>{s.role}</span></button><button title="显示或隐藏图层" aria-label={s.role+'显示或隐藏'} onClick={()=>updateLayer(s,{hidden:!layer(s).hidden})}>{layer(s).hidden?<EyeOff size={13}/>:<Eye size={13}/>}</button><button title="锁定或解锁图层" aria-label={s.role+'锁定或解锁'} onClick={()=>updateLayer(s,{locked:!layer(s).locked})}>{layer(s).locked?<Lock size={13}/>:<Unlock size={13}/>}</button></div>)}</div><p className="workbench-tip">拖动移动 · 双击文字改写<br/>⌘/Ctrl D 复制 · 方向键微调<br/>Shift + 方向键移动 10 单位</p></aside>}
<div ref={viewport} className={editing?'workbench-viewport':'page-viewport'} onClick={e=>{if(e.target===e.currentTarget){setSelected(null);setTextEditing(null)}}}>
{editing&&<div className="canvas-caption">{layout.name}<span>{layout.width} × {layout.height}</span></div>}
<article ref={canvas} className={'native-layout '+layout.id} inert={busy} aria-label={layout.name} data-layout-id={layout.id} data-design-id={design?.id||undefined} style={{aspectRatio:`${layout.width}/${layout.height}`,backgroundColor:params.paper||paperColor(layout.id),...(editing?{width:860*zoom,minWidth:860*zoom,marginBottom:40}:{} )}}>
{['image','decoration','text'].flatMap(kind=>elements.filter(s=>s.kind===kind).map(s=>{
const t=params.texts[s.id],im=params.images[s.id],d=params.decorations[s.id],text=t?.value??defaultText(layout,s),hidden=layer(s).hidden||(kind==='decoration'&&d?.hidden),ls=layer(s);
const position={...slotPosition(layout,{...s,box:[ls.x??s.box[0],ls.y??s.box[1],ls.width??s.box[2],ls.height??s.box[3]]}),transform:`rotate(${ls.rotation||0}deg)`,opacity:ls.opacity??1,borderRadius:ls.radius===undefined?undefined:`${ls.radius/layout.width*100}cqw`,zIndex:ls.z??(kind==='text'?3:kind==='image'?1:2)},common={onContextMenu:(e:React.MouseEvent)=>{e.preventDefault();select(s)},onKeyDown:(e:KeyboardEvent)=>keySelect(e,s),onClick:()=>{if(editing)setSelected(s.id)},onPointerDown:(e:PointerEvent)=>pointer(e,s),onDoubleClick:()=>{select(s);if(!ls.locked&&kind==='text')setTextEditing(s.id)},tabIndex:editing?0:undefined,'data-element':s.id,'aria-label':s.role};
if(hidden)return null;
return <div key={s.id} {...common} className={`native-element native-${kind}${selected===s.id&&editing?' is-selected':''}`} style={position}>
{kind==='text'&&s.direction==='curved'?<CurvedCopy layout={layout} slot={s} value={text} style={{fontSize:`${textSize(layout,s,text)*(t?.scale||1)/layout.width*100}cqw`,color:t?.color||textColor(layout.id,s)}}/>:kind==='text'?<TextElement className={'native-copy direction-'+s.direction} editable={editing} onDirty={()=>setDirty(true)} value={text} onInvalid={()=>setStatus('文字最多 500 字、8 行')} onChange={value=>updateText(s,{value})} style={{fontSize:`${textSize(layout,s,text)*(t?.scale||1)/layout.width*100}cqw`,color:t?.color||textColor(layout.id,s),textAlign:t?.align==='middle'?'center':t?.align==='end'?'right':'left'}}/>:
kind==='image'?<div className="native-image-fill" style={{...imageShape(layout,s),...(im?.color?{backgroundColor:im.color}:{})}}>{im?.assetId&&<img src={'/api/media/'+im.assetId} alt={s.role} draggable={false} style={{objectFit:im.fit||'cover'}}/>}{editing&&!im?.assetId&&<span className="native-image-label">{s.role}</span>}</div>:
<div className={'native-decoration decoration-'+decorationKind(s)} style={{color:d?.color||'#83908a',backgroundColor:decorationKind(s)==='band'?d?.color||'#dce1d8':undefined}}>{decorationKind(s)==='lines'&&Array.from({length:s.box[3]>4?3:1},(_,i)=><i key={i}/>)}{decorationKind(s)==='vertical-lines'&&<><i/><i/><i/></>}</div>}
{kind==='text'&&s.direction==='curved'?<CurvedCopy layout={layout} slot={s} value={text} spacing={t?.letterSpacing} style={{fontFamily:t?.fontFamily==='serif'?'Georgia,serif':t?.fontFamily==='mono'?'monospace':t?.fontFamily==='sans'?'Arial,sans-serif':undefined,fontWeight:t?.fontWeight,fontSize:`${(t?.fontSize??textSize(layout,s,text)*(t?.scale||1))/layout.width*100}cqw`,color:t?.color||textColor(layout.id,s)}}/>:kind==='text'?<TextElement className={'native-copy direction-'+s.direction} editable={editing&&textEditing===s.id&&!ls.locked} onDirty={()=>setDirty(true)} value={text} onInvalid={()=>setStatus('文字最多 500 字、8 行')} onChange={value=>updateText(s,{value})} style={{fontSize:`${(t?.fontSize??textSize(layout,s,text)*(t?.scale||1))/layout.width*100}cqw`,color:t?.color||textColor(layout.id,s),fontFamily:t?.fontFamily=== 'serif'?'Georgia,serif':t?.fontFamily==='mono'?'monospace':t?.fontFamily==='sans'?'Arial,sans-serif':undefined,fontWeight:t?.fontWeight,lineHeight:t?.lineHeight,letterSpacing:t?.letterSpacing===undefined?undefined:`${t.letterSpacing/layout.width*100}cqw`,textAlign:t?.align==='middle'?'center':t?.align==='end'?'right':'left'}}/>:
kind==='image'?<div className="native-image-fill" style={{...imageShape(layout,s),...(im?.color?{backgroundColor:im.color}:{}),...(ls.radius!==undefined?{borderRadius:`${ls.radius/layout.width*100}cqw`}:{})}}>{im?.assetId&&<img src={'/api/preview?'+new URLSearchParams({source:'/api/media/'+im.assetId,width:'960'})} srcSet={[240,480,960,1280].map(width=>'/api/preview?'+new URLSearchParams({source:'/api/media/'+im.assetId!,width:String(width)})+' '+width+'w').join(',')} sizes={`(max-width: 860px) ${Math.min(100,(ls.width??s.box[2])/layout.width*100)}vw, ${Math.min(860,(ls.width??s.box[2])/layout.width*860)}px`} alt={s.role} draggable={false} style={{objectFit:im.fit||'cover',objectPosition:`${im.cropX??50}% ${im.cropY??50}%`,transform:`scale(${im.zoom??1})`}}/>}{editing&&!im?.assetId&&<span className="native-image-label">{s.role}</span>}</div>:
<div className={'native-decoration decoration-'+((s as AddedSlot).shape?'solid':decorationKind(s))} style={{borderRadius:ls.radius!==undefined?`${ls.radius/layout.width*100}cqw`:(s as AddedSlot).shape==='ellipse'?'50%':undefined,color:d?.color||'#83908a',backgroundColor:(s as AddedSlot).shape?d?.color||'#83908a':decorationKind(s)==='band'?d?.color||'#dce1d8':undefined}}>{decorationKind(s)==='lines'&&Array.from({length:s.box[3]>4?3:1},(_,i)=><i key={i}/>)}{decorationKind(s)==='vertical-lines'&&<><i/><i/><i/></>}</div>}
{editing&&selected===s.id&&!ls.locked&&<><button className="resize-handle" aria-label="拖动调整尺寸" onPointerDown={e=>pointer(e,s,'resize')}/><button className="rotate-handle" aria-label="拖动旋转" onPointerDown={e=>pointer(e,s,'rotate')}>↻</button></>}
</div>;
}))}
</article>
<nav className="page-tools" aria-label="页面操作">
<a href="/explore/8eb8c76500580f7a4b56ba3c" aria-label="返回排版目录">←</a>
<span className="page-layout-number">{layout.id.toUpperCase()}</span>
{editing?<><button onClick={()=>{setEditing(false);setSelected(null)}}>查看页面</button><button disabled={!history.length||busy} onClick={()=>{setParams(history[history.length-1]);setHistory(history.slice(0,-1));setDirty(true)}}>撤销</button><button className="page-save" disabled={busy} onClick={()=>void save()}>{busy?'处理中…':design?'保存修改':'保存页面'}</button></>:<button onClick={()=>setEditing(true)}>编辑页面</button>}
{dirty&&<span className="page-dirty" aria-label="尚未保存">●</span>}
</nav>
{editing&&<div className="page-edit-info" inert={busy}><p>点击文字直接改写;点击图形调整。也可以右键选择元素。</p><label>页面名称<input value={name} maxLength={120} onChange={e=>{setName(e.target.value);setDirty(true)}}/></label><div className="page-edit-options"><label>纸色<input type="color" aria-label="纸色" value={params.paper||paperColor(layout.id)} onChange={e=>patch({...params,paper:e.target.value})}/></label><label>选择元素<select aria-label="选择元素" value={selected||''} onChange={e=>setSelected(e.target.value||null)}><option value="">选择元素…</option>{layout.elements.map(s=><option value={s.id} key={s.id}>{s.role}</option>)}</select></label>{design&&<button disabled={busy} onClick={()=>void save(true)}>另存副本</button>}</div></div>}
{editing&&slot&&<div className="element-popover" inert={busy} role="dialog" aria-label={'编辑'+slot.role}>
<div className="element-popover-heading"><strong>{slot.role}</strong><button aria-label="关闭元素设置" onClick={()=>setSelected(null)}>×</button></div>
<label>颜色<input type="color" aria-label={slot.role+'颜色'} value={selectedColor} onChange={e=>{const color=e.target.value;if(slot.kind==='text')updateText(slot,{color});else if(slot.kind==='image')patch({...params,images:{...params.images,[slot.id]:{...params.images[slot.id],color}}});else patch({...params,decorations:{...params.decorations,[slot.id]:{...params.decorations[slot.id],color}}})}}/></label>
{slot.kind==='text'&&<><label>字号<input type="range" min="0.25" max="2" step="0.05" value={params.texts[slot.id]?.scale||1} onChange={e=>updateText(slot,{scale:Number(e.target.value)})}/></label><label>对齐<select value={params.texts[slot.id]?.align||'start'} onChange={e=>updateText(slot,{align:e.target.value as 'start'|'middle'|'end'})}><option value="start">左对齐</option><option value="middle">居中</option><option value="end">右对齐</option></select></label><label className="element-text-edit">文字<textarea rows={3} value={params.texts[slot.id]?.value??defaultText(layout,slot)} onChange={e=>updateText(slot,{value:e.target.value})}/></label></>}
{slot.kind==='image'&&<><button disabled={busy} onClick={()=>upload.current?.click()}>替换图片</button>{params.images[slot.id]?.assetId&&<><label>图片适应<select value={params.images[slot.id]?.fit||'cover'} onChange={e=>patch({...params,images:{...params.images,[slot.id]:{...params.images[slot.id],fit:e.target.value as 'cover'|'contain'}}})}><option value="cover">填满</option><option value="contain">完整显示</option></select></label><button onClick={()=>{const image={...params.images[slot.id]};delete image.assetId;patch({...params,images:{...params.images,[slot.id]:image}})}}>移除图片</button></>}</>}
{slot.kind==='decoration'&&<label>隐藏<input type="checkbox" checked={params.decorations[slot.id]?.hidden||false} onChange={e=>patch({...params,decorations:{...params.decorations,[slot.id]:{...params.decorations[slot.id],hidden:e.target.checked}}})}/></label>}
<button onClick={()=>reset(slot)}>恢复默认</button>
</div>}
</div>
{!editing&&<nav className="page-tools" aria-label="页面操作"><a href="/explore/8eb8c76500580f7a4b56ba3c">←</a><span className="page-layout-number">{layout.id.toUpperCase()}</span><button onClick={()=>setEditing(true)}>编辑页面</button>{dirty&&<span className="page-dirty">●</span>}</nav>}
{editing&&<aside className={'workbench-properties '+(panel==='properties'?'mobile-open':'')} inert={busy}><div className="panel-heading"><SlidersHorizontal size={16}/><strong>{slot?'元素属性':'页面设置'}</strong><span>{slot?.id||'Design'}</span></div>
{!slot?<><section><h3>页面</h3><label>纸张颜色<input type="color" value={params.paper||paperColor(layout.id)} onChange={e=>patch({...params,paper:e.target.value})}/></label><p className="property-hint">选择画布上的元素或左侧图层,调整它的设计属性。</p></section>{design&&<section><button onClick={()=>void save(true)}><Copy size={15}/>另存副本</button></section>}<section><h3>快捷操作</h3><p className="property-hint">⌘/Ctrl S 保存<br/>⌘/Ctrl Z 撤销<br/>Shift ⌘/Ctrl Z 重做<br/>Delete 隐藏所选图层<br/>Esc 取消选择</p></section></>:<><section><h3>{slot.role}<span>{slot.kind.toUpperCase()}</span></h3><div className="property-grid">{(['x','y','width','height','rotation','z'] as const).map((key,i)=><label key={key}>{['X','Y','宽','高','旋转 °','层级'][i]}<input aria-label={['X','Y','宽','高','旋转','层级'][i]} type="number" step="0.1" disabled={l.locked} value={Math.round((l[key]??(i<4?slot.box[i]:key==='z'?(slot.kind==='text'?3:slot.kind==='image'?1:2):0))*100)/100} onChange={e=>updateLayer(slot,{[key]:Number(e.target.value)})}/></label>)}</div><div className="property-actions"><button disabled={l.locked} onClick={()=>reorder(1)}><ChevronUp size={14}/>上移</button><button disabled={l.locked} onClick={()=>reorder(-1)}><ChevronDown size={14}/>下移</button></div></section>
<fieldset disabled={l.locked}><section><h3>外观</h3><label>颜色<input type="color" value={selectedColor} onChange={e=>{const color=e.target.value;if(slot.kind==='text')updateText(slot,{color});else if(slot.kind==='image')patch({...params,images:{...params.images,[slot.id]:{...im,color}}});else patch({...params,decorations:{...params.decorations,[slot.id]:{...params.decorations[slot.id],color}}})}}/></label><div className="property-grid"><label>不透明度 %<input type="number" min="0" max="100" value={(l.opacity??1)*100} onChange={e=>updateLayer(slot,{opacity:Number(e.target.value)/100})}/></label><label>圆角<input type="number" min="0" max="5000" value={l.radius??0} onChange={e=>updateLayer(slot,{radius:Number(e.target.value)})}/></label></div></section>
{slot.kind==='text'&&<section><h3>文字</h3><textarea aria-label="文字内容" rows={4} value={t?.value??defaultText(layout,slot)} onChange={e=>updateText(slot,{value:e.target.value})}/><label>字体<select value={t?.fontFamily||''} onChange={e=>updateText(slot,{fontFamily:e.target.value as 'sans'|'serif'|'mono'})}><option value="" disabled>模板默认</option><option value="sans">无衬线</option><option value="serif">衬线</option><option value="mono">等宽</option></select></label><div className="property-grid">{(['fontSize','fontWeight','lineHeight','letterSpacing'] as const).map((key,i)=><label key={key}>{['字号','字重','行距','字距'][i]}<input type="number" step={key==='lineHeight'?.1:key==='fontWeight'?100:.1} value={Math.round((t?.[key]??[textSize(layout,slot,t?.value??defaultText(layout,slot))*(t?.scale||1),500,1.15,0][i])*100)/100} onChange={e=>updateText(slot,{[key]:Number(e.target.value)})}/></label>)}</div><label>对齐<select value={t?.align||'start'} onChange={e=>updateText(slot,{align:e.target.value as 'start'|'middle'|'end'})}><option value="start">左对齐</option><option value="middle">居中</option><option value="end">右对齐</option></select></label></section>}
{slot.kind==='image'&&<section><h3>图片</h3><button onClick={()=>upload.current?.click()}><ImagePlus size={15}/>上传 / 替换图片</button><label>适应<select value={im?.fit||'cover'} onChange={e=>patch({...params,images:{...params.images,[slot.id]:{...im,fit:e.target.value as 'cover'|'contain'}}})}><option value="cover">裁切填满</option><option value="contain">完整显示</option></select></label>{(['cropX','cropY','zoom'] as const).map((key,i)=><label key={key}>{['水平裁切','垂直裁切','图片缩放'][i]}<input type="range" min={i===2?1:0} max={i===2?5:100} step={i===2?.05:1} value={im?.[key]??(i===2?1:50)} onChange={e=>patch({...params,images:{...params.images,[slot.id]:{...im,[key]:Number(e.target.value)}}})}/></label>)}</section>}</fieldset>
<section><div className="property-actions"><button disabled={l.locked} onClick={duplicate}><Copy size={14}/>复制</button><button disabled={l.locked} onClick={remove}><Trash2 size={14}/>删除</button></div><button disabled={l.locked} onClick={()=>reset(slot)}>恢复内容默认值</button></section></>}
</aside>}
{editing&&<nav className="workbench-bottom" aria-label="画布工具"><button className={panel==='layers'?'active':''} title="图层面板" onClick={()=>setPanel(panel==='layers'?null:'layers')}><Layers size={17}/></button><MousePointer2 size={18}/><span className="toolbar-divider"/><button aria-label="缩小" onClick={()=>setZoom(z=>Math.max(.1,z-.1))}><Minus size={16}/></button><span>{Math.round(zoom*100)}%</span><button aria-label="放大" onClick={()=>setZoom(z=>Math.min(3,z+.1))}><Plus size={16}/></button><button title="适合窗口" aria-label="适合窗口" onClick={fit}><Scan size={17}/></button><span className="toolbar-divider"/><button className={panel==='properties'?'active':''} title="属性面板" onClick={()=>setPanel(panel==='properties'?null:'properties')}><SlidersHorizontal size={17}/></button></nav>}
{conflict&&<div className="conflict-notice" role="alert"><strong>此页面已有更新</strong><p>本地修改已保留。可另存副本,或重新加载服务器版本。</p><button disabled={busy} onClick={()=>void save(true)}>另存副本</button><button onClick={()=>{if(window.confirm('重新加载将丢弃本地未保存修改,继续?')){setDirty(false);window.location.reload()}}}>重新加载</button></div>}
<input ref={upload} type="file" accept="image/png,image/jpeg,image/webp,image/gif,image/avif" hidden onChange={e=>void uploadImage(e.target.files?.[0])}/>
{status&&<p className="page-status" role="status">{status}</p>}
</main>;
@@ -0,0 +1,7 @@
import type {CSSProperties} from 'react';
import type {Layout,Slot} from '../lib/layout-parameters';
import {textSize} from '../lib/native-layout';
export function CurvedCopy({layout,slot,value,style,spacing=0}:{layout:Layout;slot:Slot;value:string;style:CSSProperties;spacing?:number}){
const letters=Array.from(value),tall=slot.box[3]>slot.box[2];
return <div className="native-copy native-arc" aria-label={value} style={style}>{letters.map((letter,index)=>{const t=.5+(index/Math.max(1,letters.length-1)-.5)*(1+spacing/Math.max(.1,textSize(layout,slot,value))),x=tall?90-75*Math.sin(Math.PI*t):4+92*t,y=tall?2+94*t:5+75*Math.sin(Math.PI*t),angle=tall?90+Math.cos(Math.PI*t)*18:Math.atan2(slot.box[3]*.75*Math.PI*Math.cos(Math.PI*t),slot.box[2]*.92)*180/Math.PI;return <span key={index} aria-hidden="true" style={{left:x+'%',top:y+'%',transform:`translate(-50%,-50%) rotate(${angle}deg)`}}>{letter===' '?'\u00a0':letter}</span>})}</div>;
}
@@ -0,0 +1,14 @@
import type {Layout} from '../lib/layout-parameters';
import {paperColor,textColor,defaultText,textSize,slotPosition,imageShape,decorationKind} from '../lib/native-layout';
import {CurvedCopy} from './NativeCurvedCopy';
/** The catalogue uses the same native type, contours and ornament as the rendered page. */
export function NativePreview({layout}:{layout:Layout}){
return <div className={'native-layout '+layout.id} style={{aspectRatio:`${layout.width}/${layout.height}`,backgroundColor:paperColor(layout.id)}} aria-label={layout.name} data-layout-id={layout.id}>
{['image','decoration','text'].flatMap(kind=>layout.elements.filter(s=>s.kind===kind).map(s=>{
const text=defaultText(layout,s),style={fontSize:textSize(layout,s,text)/layout.width*100+'cqw',color:textColor(layout.id,s)};
return <div key={s.id} data-element={s.id} className={'native-element native-'+kind} style={{...slotPosition(layout,s),zIndex:kind==='text'?3:kind==='image'?1:2}}>
{kind==='text'?(s.direction==='curved'?<CurvedCopy layout={layout} slot={s} value={text} style={style}/>:<div className={'native-copy direction-'+s.direction} style={style}>{text}</div>):kind==='image'?<div className="native-image-fill" style={imageShape(layout,s)}/>:<div className={'native-decoration decoration-'+decorationKind(s)} style={{color:'#83908a',backgroundColor:decorationKind(s)==='band'?'#dce1d8':undefined}}>{decorationKind(s)==='lines'&&Array.from({length:s.box[3]>4?3:1},(_,i)=><i key={i}/>)}{decorationKind(s)==='vertical-lines'&&<><i/><i/><i/></>}</div>}
</div>;
}))}
</div>;
}
@@ -0,0 +1,28 @@
import Head from 'next/head';
import type {CSSProperties} from 'react';
import type {AddedSlot,Layout,Parameters} from '../lib/layout-parameters';
import {CurvedCopy} from './NativeCurvedCopy';
import {decorationKind,defaultText,emptyParameters,imageShape,paperColor,slotPosition,textColor,textSize,type Design} from '../lib/native-layout';
/** A saved result contains artwork only: no editing state, controls or event handlers. */
export function NativeResult({layout,design}:{layout:Layout;design:Design|null}){
const params:Parameters=design?.parameters||emptyParameters();
const elements=[...layout.elements,...(params.added||[])];
return <main className="native-layout-page">
<Head><title>{design?.name||layout.name} · Prompt</title><meta name="description" content={layout.name+' · 排版结果'}/></Head>
<article className={'native-layout '+layout.id} aria-label={design?.name||layout.name} data-layout-id={layout.id} data-design-id={design?.id} style={{aspectRatio:`${layout.width}/${layout.height}`,backgroundColor:params.paper||paperColor(layout.id)}}>
{['image','decoration','text'].flatMap(kind=>elements.filter(s=>s.kind===kind).map(s=>{
const t=params.texts[s.id],im=params.images[s.id],d=params.decorations[s.id],ls=params.layers?.[s.id]||{};
if(ls.hidden||(kind==='decoration'&&d?.hidden))return null;
const text=t?.value??defaultText(layout,s);
const position:CSSProperties={...slotPosition(layout,{...s,box:[ls.x??s.box[0],ls.y??s.box[1],ls.width??s.box[2],ls.height??s.box[3]]}),transform:`rotate(${ls.rotation||0}deg)`,opacity:ls.opacity??1,borderRadius:ls.radius===undefined?undefined:`${ls.radius/layout.width*100}cqw`,zIndex:ls.z??(kind==='text'?3:kind==='image'?1:2)};
const textStyle:CSSProperties={fontSize:`${(t?.fontSize??textSize(layout,s,text)*(t?.scale||1))/layout.width*100}cqw`,color:t?.color||textColor(layout.id,s),fontFamily:t?.fontFamily==='serif'?'Georgia,serif':t?.fontFamily==='mono'?'monospace':t?.fontFamily==='sans'?'Arial,sans-serif':undefined,fontWeight:t?.fontWeight,lineHeight:t?.lineHeight,letterSpacing:t?.letterSpacing===undefined?undefined:`${t.letterSpacing/layout.width*100}cqw`,textAlign:t?.align==='middle'?'center':t?.align==='end'?'right':'left'};
return <div key={s.id} className={'native-element native-'+kind} data-element={s.id} aria-label={s.role} style={position}>
{kind==='text'?(s.direction==='curved'?<CurvedCopy layout={layout} slot={s} value={text} spacing={t?.letterSpacing} style={textStyle}/>:<div className={'native-copy direction-'+s.direction} style={textStyle}>{text}</div>):kind==='image'?<div className="native-image-fill" style={{...imageShape(layout,s),...(im?.color?{backgroundColor:im.color}:{}),...(ls.radius!==undefined?{borderRadius:`${ls.radius/layout.width*100}cqw`}:{})}}>
{im?.assetId&&<img src={'/api/preview?'+new URLSearchParams({source:'/api/media/'+im.assetId,width:'960'})} srcSet={[240,480,960,1280].map(width=>'/api/preview?'+new URLSearchParams({source:'/api/media/'+im.assetId!,width:String(width)})+' '+width+'w').join(',')} sizes={`(max-width: 860px) ${Math.min(100,(ls.width??s.box[2])/layout.width*100)}vw, ${Math.min(860,(ls.width??s.box[2])/layout.width*860)}px`} alt={s.role} style={{objectFit:im.fit||'cover',objectPosition:`${im.cropX??50}% ${im.cropY??50}%`,transform:`scale(${im.zoom??1})`}}/>}
</div>:<div className={'native-decoration decoration-'+((s as AddedSlot).shape?'solid':decorationKind(s))} style={{borderRadius:ls.radius!==undefined?`${ls.radius/layout.width*100}cqw`:(s as AddedSlot).shape==='ellipse'?'50%':undefined,color:d?.color||'#83908a',backgroundColor:(s as AddedSlot).shape?d?.color||'#83908a':decorationKind(s)==='band'?d?.color||'#dce1d8':undefined}}>{decorationKind(s)==='lines'&&Array.from({length:s.box[3]>4?3:1},(_,i)=><i key={i}/>)}{decorationKind(s)==='vertical-lines'&&<><i/><i/><i/></>}</div>}
</div>;
}))}
</article>
</main>;
}
+1 -1
View File
@@ -11,7 +11,7 @@ export function Ref17Cover({template,slide,masthead=template.masthead,guides=fal
const bodySize=Math.min(32,...body.map(s=>sW/Math.max(1,Array.from(s).reduce((n,c)=>n+(/[\u3400-\u9fff]/.test(c)?1:.5),0))));
const accent=slide.accent||'#d8ddd4';
return <svg xmlns="http://www.w3.org/2000/svg" viewBox={`0 0 ${W} ${H}`} width={W} height={H} role="img" aria-label={`${slide.label||slide.heading},ref-17 模板封面试版`} data-layout-id={template.id} style={{display:'block',width:'100%',height:'auto'}}>
<title>{slide.label||slide.heading} · 模板试版</title><desc>源自 ref-17 的九个固定构件。图片位使用色块,占位文案可替换,暂无具体工具内容。</desc>
<title>{(slide.label||slide.heading)+' · 模板试版'}</title><desc>源自 ref-17 的九个固定构件。图片位使用色块,占位文案可替换,暂无具体工具内容。</desc>
<rect width={W} height={H} fill={template.paper}/>
<g data-slot="I01"><rect x={mx} y={my} width={mw} height={mh} fill={slide.color}/></g>
<g data-slot="I02"><ellipse cx={cx+cw/2} cy={cy+ch/2} rx={cw/2} ry={ch/2} fill={accent}/></g>
+2 -1
View File
@@ -1,3 +1,4 @@
import {referencePreview} from '../lib/layout-images-client';
import {useState} from 'react';
import Head from 'next/head';
import {tutorialPost} from '../content/tool-links';
@@ -23,7 +24,7 @@ export function TemplateTrial({idea}:{idea:Idea}){
<div className="trial-actions"><button className="trial-primary" onClick={exportSvg}>下载当前 SVG</button><button onClick={()=>download(JSON.stringify({version:2,...current},null,2),'application/json',idea.slug+'.json')}>导出当前试版 JSON</button><button onClick={()=>download(ideaMarkdown(current),'text/markdown',idea.slug+'.md')}>导出说明 Markdown</button><button onClick={reset}>恢复初始试版</button></div>
<p className="trial-help">修改仅保留在当前页面,刷新会恢复;可下载 JSON 保存试版。主视觉仍是色块占位。</p><p role="status" className="trial-notice">{notice}</p>
</aside><div><div className="trial-grid">{slides.map((slide,i)=><figure className={'proof-card '+(i===active?'proof-active':'')} key={slide.key} data-proof={slide.key}><button className="proof-select" onClick={()=>setActive(i)} aria-label={'编辑'+slide.label} aria-pressed={i===active}><Ref17Cover template={template} slide={slide} masthead={masthead} guides={guides}/></button><figcaption><b>{slide.label}</b><span>共用 REF-17</span><a href={'/studio/api/export/'+idea.slug+'?format=svg&slide='+i}>初始 SVG ↗</a></figcaption></figure>)}</div>
<details className="trial-reference"><summary>查看原图与构件对应</summary><div className="trial-reference-body"><img src={template.referenceUrl} alt="ref-17 原始参考裁片"/><div><p>保留 {template.width}×{template.height} 的画板比例与九个构件位置;本试版重新绘制可编辑文字与色块,替换了文案和色调。</p><table><thead><tr><th>构件</th><th>用途</th><th>原图坐标</th></tr></thead><tbody>{template.slots.map(s=><tr key={s.id}><td>{s.id}</td><td>{s.role}</td><td>{s.box.join(', ')}</td></tr>)}</tbody></table><a href={template.tutorialUrl+'?agent_mode=True'}>读取教程纯文本 ↗</a></div></div></details>
<details className="trial-reference"><summary>查看原图与构件对应</summary><div className="trial-reference-body"><img src={referencePreview(template.referenceUrl)} alt="ref-17 原始参考裁片"/><div><p>保留 {template.width}×{template.height} 的画板比例与九个构件位置;本试版重新绘制可编辑文字与色块,替换了文案和色调。</p><table><thead><tr><th>构件</th><th>用途</th><th>原图坐标</th></tr></thead><tbody>{template.slots.map(s=><tr key={s.id}><td>{s.id}</td><td>{s.role}</td><td>{s.box.join(', ')}</td></tr>)}</tbody></table><a href={template.tutorialUrl+'?agent_mode=True'}>读取教程纯文本 ↗</a></div></div></details>
</div></div>
</main>;
}
@@ -0,0 +1,78 @@
{
"id": "standard-01",
"name": "标准排版 · 自由图文",
"width": 120,
"height": 160,
"elements": [
{
"id": "T01",
"kind": "text",
"role": "主标题",
"box": [
10,
16,
100,
28
],
"direction": "horizontal",
"text": "让每一页\n只讲一件事",
"reading": "standard"
},
{
"id": "T02",
"kind": "text",
"role": "正文",
"box": [
10,
112,
100,
27
],
"direction": "horizontal",
"text": "一个标题,一段解释,\n一个值得被记住的画面。",
"reading": "standard"
},
{
"id": "T03",
"kind": "text",
"role": "栏目",
"box": [
10,
7,
100,
4
],
"direction": "horizontal",
"text": "PROMPT STUDIO / 01",
"reading": "standard"
},
{
"id": "I01",
"kind": "image",
"role": "主题图片",
"box": [
10,
53,
100,
50
],
"direction": "horizontal",
"text": null,
"reading": "standard"
},
{
"id": "D01",
"kind": "decoration",
"role": "分隔线",
"box": [
10,
146,
100,
1
],
"direction": "horizontal",
"text": null,
"reading": "standard"
}
]
}
+1 -1
View File
@@ -1,2 +1,2 @@
// Stable Wiki post ID; the tutorial is published through /api/posts, never registered as a Wiki route.
export const tutorialPost='/explore/9ebd8f78d54b4b9db741b4e8';
export const tutorialPost='/explore/8eb8c76500580f7a4b56ba3c';
+4 -1
View File
@@ -1,6 +1,8 @@
import type {IncomingMessage} from 'node:http';
import {parameters,uuid} from './layout-parameters';
import layouts from '../content/templates/layouts.json';
import fixedLayouts from '../content/templates/layouts.json';
import standardLayout from '../content/standard-layout.json';
const layouts=[...fixedLayouts,standardLayout];
import type {Design} from './native-layout';
/** Only forward the session to our fixed private Wiki service, never a request Host. */
@@ -16,5 +18,6 @@ export async function readDesign(id:unknown,req:IncomingMessage):Promise<Design|
const {design}=await response.json() as {design:Design};
const layout=layouts.find(l=>l.id===design.layoutId);
if(!layout||design.id!==id)throw new Error('Invalid saved layout');
if((design as Design&{archived?:boolean}).archived)return null;
return {...design,parameters:parameters(layout,design.parameters)};
}
@@ -0,0 +1,6 @@
/** References in the retained toolbox are internal Wiki media, displayed as derivatives. */
export function referencePreview(source:string){
const path=new URL(source,'http://wiki.internal').pathname;
if(!/^\/api\/media\/[0-9a-f-]{36}$/.test(path))throw Error('Invalid reference media');
return '/api/preview?'+new URLSearchParams({source:path,width:'960'});
}
+14 -7
View File
@@ -1,23 +1,30 @@
export type Slot={id:string;kind:string;role:string;box:number[];direction:string;text:string|null;reading:string};
export type Layout={id:string;name:string;width:number;height:number;elements:Slot[]};
export type TextValue={value:string;color?:string;scale?:number;align?:'start'|'middle'|'end'};
export type ImageValue={assetId?:string;color?:string;fit?:'cover'|'contain'};
export type TextValue={value:string;color?:string;scale?:number;align?:'start'|'middle'|'end';fontFamily?:'sans'|'serif'|'mono';fontSize?:number;fontWeight?:number;lineHeight?:number;letterSpacing?:number};
export type ImageValue={assetId?:string;color?:string;fit?:'cover'|'contain';cropX?:number;cropY?:number;zoom?:number};
export type DecorationValue={color?:string;hidden?:boolean};
export type Parameters={texts:Record<string,TextValue>;images:Record<string,ImageValue>;decorations:Record<string,DecorationValue>;paper?:string};
export type LayerValue={x?:number;y?:number;width?:number;height?:number;rotation?:number;opacity?:number;radius?:number;z?:number;hidden?:boolean;locked?:boolean};
export type AddedSlot=Slot & {shape?:'rectangle'|'ellipse'};
export type Parameters={texts:Record<string,TextValue>;images:Record<string,ImageValue>;decorations:Record<string,DecorationValue>;paper?:string;layers?:Record<string,LayerValue>;added?:AddedSlot[]};
export class LayoutParameterError extends Error{}
export const uuid=(v:unknown):v is string=>typeof v==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);
function fail(message:string):never{throw new LayoutParameterError(message)}
function object(v:unknown):Record<string,unknown>{if(!v||typeof v!=='object'||Array.isArray(v))fail('参数必须为 JSON 对象');return v as Record<string,unknown>}
function keys(v:Record<string,unknown>,allowed:string[]){if(Object.keys(v).some(k=>!allowed.includes(k)))fail('未知参数或构件 ID')}
function number(v:unknown,min:number,max:number){if(typeof v!=='number'||!Number.isFinite(v)||v<min||v>max)fail(`数值范围 ${min}–${max}`);return v}
function color(v:unknown){if(typeof v!=='string'||!/^#[a-f0-9]{6}$/i.test(v))fail('颜色使用 #RRGGBB');return v}
export function parameters(layout:Layout,input:unknown):Parameters{
const raw=object(input);keys(raw,['texts','images','decorations','paper']);const result:Parameters={texts:{},images:{},decorations:{}};
const raw=object(input);keys(raw,['texts','images','decorations','paper','layers','added']);const result:Parameters={texts:{},images:{},decorations:{}};
const added:AddedSlot[]=[];
if(raw.added!==undefined){if(!Array.isArray(raw.added)||raw.added.length>100)fail('最多新增100个元素');for(const entry of raw.added){const v=object(entry);keys(v,['id','kind','role','box','direction','text','reading','shape']);if(typeof v.id!=='string'||!/^user-[a-zA-Z0-9-]{1,60}$/.test(v.id)||added.some(s=>s.id===v.id))fail('新增元素 ID 无效或重复');if(!['text','image','decoration'].includes(String(v.kind)))fail('新增元素类型无效');if(typeof v.role!=='string'||v.role.length>80)fail('图层名称最多80字');if(!Array.isArray(v.box)||v.box.length!==4)fail('box 为 x,y,width,height');const box=v.box.map((n,i)=>number(n,i<2?-10000:.1,10000));if(v.direction!=='horizontal'||v.reading!=='custom'||(v.text!==null&&(typeof v.text!=='string'||v.text.length>500)))fail('新增元素内容无效');if(v.shape!==undefined&&!['rectangle','ellipse'].includes(String(v.shape)))fail('无效形状');added.push({id:v.id,kind:String(v.kind),role:v.role,box,direction:'horizontal',text:v.text as string|null,reading:'custom',...(v.shape?{shape:v.shape as AddedSlot['shape']}:{})})}result.added=added}
const elements=[...layout.elements,...added];
if(raw.layers!==undefined){const entries=object(raw.layers);keys(entries,elements.map(e=>e.id));result.layers={};for(const [id,entry] of Object.entries(entries)){const v=object(entry);keys(v,['x','y','width','height','rotation','opacity','radius','z','hidden','locked']);const layer:Record<string,number|boolean>={};for(const [key,value] of Object.entries(v)){if(key==='hidden'||key==='locked'){if(typeof value!=='boolean')fail('图层开关必须为布尔值');layer[key]=value}else{const range:Record<string,number[]>={x:[-10000,10000],y:[-10000,10000],width:[.1,10000],height:[.1,10000],rotation:[-360,360],opacity:[0,1],radius:[0,5000],z:[-1000,1000]};layer[key]=number(value,range[key][0],range[key][1])}}result.layers[id]=layer}}
if(raw.paper!==undefined)result.paper=color(raw.paper);
for(const [group,kind] of [['texts','text'],['images','image'],['decorations','decoration']] as const){
const entries=object(raw[group]??{});keys(entries,layout.elements.filter(e=>e.kind===kind).map(e=>e.id));
const entries=object(raw[group]??{});keys(entries,elements.filter(e=>e.kind===kind).map(e=>e.id));
for(const [id,value] of Object.entries(entries)){const v=object(value);
if(group==='texts'){keys(v,['value','color','scale','align']);if(typeof v.value!=='string'||Array.from(v.value).length>500||v.value.split('\n').length>8)fail('文字最多 500 字 / 8 行');const t:TextValue={value:v.value};if(v.color!==undefined)t.color=color(v.color);if(v.scale!==undefined){if(typeof v.scale!=='number'||!Number.isFinite(v.scale)||v.scale<.25||v.scale>2)fail('scale 范围 0.25–2');t.scale=v.scale}if(v.align!==undefined){if(!['start','middle','end'].includes(String(v.align)))fail('无效 align');t.align=v.align as TextValue['align']}result.texts[id]=t;
}else if(group==='images'){keys(v,['assetId','color','fit']);const image:ImageValue={};if(v.assetId!==undefined){if(!uuid(v.assetId))fail('assetId 必须为已上传图片 UUID');image.assetId=v.assetId}if(v.color!==undefined)image.color=color(v.color);if(v.fit!==undefined){if(v.fit!=='cover'&&v.fit!=='contain')fail('fit 使用 cover 或 contain');image.fit=v.fit}result.images[id]=image;
if(group==='texts'){keys(v,['value','color','scale','align','fontFamily','fontSize','fontWeight','lineHeight','letterSpacing']);if(typeof v.value!=='string'||Array.from(v.value).length>500||v.value.split('\n').length>8)fail('文字最多 500 字 / 8 行');const t:TextValue={value:v.value};if(v.color!==undefined)t.color=color(v.color);if(v.scale!==undefined){if(typeof v.scale!=='number'||!Number.isFinite(v.scale)||v.scale<.25||v.scale>2)fail('scale 范围 0.25–2');t.scale=v.scale}if(v.align!==undefined){if(!['start','middle','end'].includes(String(v.align)))fail('无效 align');t.align=v.align as TextValue['align']}if(v.fontFamily!==undefined){if(!['sans','serif','mono'].includes(String(v.fontFamily)))fail('无效字体');t.fontFamily=v.fontFamily as TextValue['fontFamily']}for(const [key,min,max] of [['fontSize',.1,1000],['fontWeight',100,900],['lineHeight',.5,4],['letterSpacing',-20,100]] as const)if(v[key]!==undefined)t[key]=number(v[key],min,max);result.texts[id]=t;
}else if(group==='images'){keys(v,['assetId','color','fit','cropX','cropY','zoom']);const image:ImageValue={};if(v.assetId!==undefined){if(!uuid(v.assetId))fail('assetId 必须为已上传图片 UUID');image.assetId=v.assetId}if(v.color!==undefined)image.color=color(v.color);if(v.fit!==undefined){if(v.fit!=='cover'&&v.fit!=='contain')fail('fit 使用 cover 或 contain');image.fit=v.fit}for(const [key,min,max] of [['cropX',0,100],['cropY',0,100],['zoom',1,5]] as const)if(v[key]!==undefined)image[key]=number(v[key],min,max);result.images[id]=image;
}else{keys(v,['color','hidden']);const d:DecorationValue={};if(v.color!==undefined)d.color=color(v.color);if(v.hidden!==undefined){if(typeof v.hidden!=='boolean')fail('hidden 必须为布尔值');d.hidden=v.hidden}result.decorations[id]=d}
}
}
+30 -12
View File
@@ -2,22 +2,38 @@ import type {CSSProperties} from 'react';
import type {Layout,Parameters,Slot} from './layout-parameters';
export type Design={id:string;name:string;layoutId:string;parameters:Parameters;revision:number;url:string};
// getRandomValues is available on the deployment's HTTP origin; randomUUID is not.
export const newElementId=()=> 'user-'+Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)),n=>n.toString(16).padStart(8,'0')).join('');
export const emptyParameters=():Parameters=>({texts:{},images:{},decorations:{}});
export const designUrl=(layoutId:string,id:string)=>`/studio/layouts/${layoutId}?id=${id}`;
export const designUrl=(_layoutId:string,id:string)=>`/studio/template-layout?id=${id}`;
export function nativeLayout(layout:Layout):Layout {
return {id:layout.id,name:layout.name,width:layout.width,height:layout.height,elements:layout.elements.map(({id,kind,role,box,direction,text,reading})=>({id,kind,role,box,direction,text,reading}))};
}
export function paperColor(id:string){return ['ref-04','ref-22'].includes(id)?'#a8b0ae':'#f5f5ef'}
export function textColor(id:string,slot:Slot){return (id==='ref-04'&&['T01','T02'].includes(slot.id))||(id==='ref-22'&&slot.id==='T01')||(id==='ref-27'&&slot.id==='T01')||(id==='ref-10'&&slot.id==='T03')?'#f9faf5':'#28312e'}
// Each composition has its own paper and inks; layered artwork can add a middle tone.
const palettes=[
['#f3eee4','#293b42','#7c9a9e','#c4d5cb'],['#f5f2e9','#344335','#879782','#d7c39f'],['#efede7','#383d4a','#8996a6','#c5d0d7'],
['#5e7472','#f5f0e5','#354e4a','#d9ded0'],['#f5eddf','#5c3b32','#b47d68','#d9bba0'],['#eceee8','#263d43','#688a94','#b4c7c7'],
['#f3eddf','#4c4a36','#a1a185','#d8cba9'],['#edf0ef','#23424b','#73929a','#b6cbd2'],['#f5f1e9','#2f3e38','#7f9688','#d1d7ba'],
['#eeece4','#344b57','#526e80','#afc4c9'],['#f4eee8','#4e393b','#a58a90','#d8bdb3'],['#f1f0e9','#424b36','#8c997b','#d1c7aa'],
['#f3ebe5','#5b3e39','#b48e7e','#dec6ab'],['#eef0e7','#384c42','#789485','#c4d1b5'],['#e9edee','#2e4555','#839ba8','#c6d3d4'],
['#f4f0e7','#50483a','#ada18a','#d9d1c0'],['#eeeee5','#394d42','#7e9785','#c8d5bc'],['#f2ede6','#3e424e','#8a92a3','#d0c7c0'],
['#f5eede','#443d31','#a79b7a','#dbca9f'],['#eeefe8','#34463f','#809b89','#c5d3ba'],['#f0ebe5','#51413d','#a48b7f','#d5bfb3'],
['#64797d','#142a2e','#b5c7c7','#3d565b','#7c9497'],['#f0efe9','#2f414d','#8199a7','#c5d2d6'],['#f4eee5','#5a443b','#ae927b','#dfc8ac'],
['#ebeee8','#344b41','#829c8b','#c7d5bb'],['#edece8','#3c4354','#8b93aa','#c5cbd7'],['#f2ece2','#3b4e4b','#6f918c','#b8cdc3']
];
export function layoutPalette(id:string){return palettes[Number(id.slice(4))-1]||['#ffe5df','#303d43','#a9bec0','#f0bca6']}
export function paperColor(id:string){return layoutPalette(id)[0]}
export function textColor(id:string,slot:Slot){return (id==='ref-04'&&['T01','T02'].includes(slot.id))||(id==='ref-22'&&['T01','T03','T04'].includes(slot.id))||(id==='ref-27'&&slot.id==='T01')||(id==='ref-10'&&slot.id==='T03')?'#f9faf5':layoutPalette(id)[1]}
// The screenshot's illegible small print is replaced with editable editorial copy.
export function defaultText(layout:Layout,slot:Slot):string {
if(slot.text)return slot.text;
if(slot.direction==='curved')return 'BULUBLUE DESIGN · FORM AND SPACE · EDITORIAL DESIGN ·';
if(slot.role.includes('日期'))return '2025 / 03 / 25';
if(slot.role.includes('微字'))return slot.box[2]>60?'FORM / SPACE / DESIGN / 2026':'FORM / '+layout.id.slice(-2);
if(slot.role.includes('英文')||slot.role.includes('品牌')||slot.role.includes('标识'))return 'BULUBLUE DESIGN';
if(slot.role.includes('图注')||slot.role.includes('标签')||slot.box[3]<10)return 'FORM / SPACE / DESIGN';
if(slot.role.includes('图注')||slot.role.includes('标签')||slot.box[3]<10)return slot.box[2]<25?'FORM / '+layout.id.slice(-2):'FORM / SPACE / DESIGN';
if(slot.direction==='vertical')return '设计灵感 · 日常观察';
return '在留白之间,\n寻找新的秩序。\n让文字与形状相遇,\n记录日常的设计灵感。';
return slot.box[2]<25?'留白之间\n观察日常\n记录灵感':'让文字与形状相遇。\n在留白之间,寻找新的秩序。';
}
export function slotPosition(layout:Layout,slot:Slot):CSSProperties {
const [x,y,w,h]=slot.box;return {left:`${x/layout.width*100}%`,top:`${y/layout.height*100}%`,width:`${w/layout.width*100}%`,height:`${h/layout.height*100}%`};
@@ -25,21 +41,23 @@ export function slotPosition(layout:Layout,slot:Slot):CSSProperties {
export function textSize(layout:Layout,slot:Slot,text:string):number {
const [, ,w,h]=slot.box,lines=text.split('\n');
const length=(s:string)=>Array.from(s).reduce((n,c)=>n+(/[\u3400-\u9fff]/.test(c)?1:/[A-Z]/.test(c)?.8:.6),0);
if(slot.direction==='vertical')return Math.min(w*.9,h/Math.max(1,Array.from(text.replaceAll('\n','')).length)*.95);
if(slot.direction==='vertical')return Math.min(w*.75,h/Math.max(1,Array.from(text.replaceAll('\n','')).length)*.88);
if(slot.direction==='rotated')return Math.min(w*.85,h/Math.max(1,length(text)));
if(slot.direction==='curved')return Math.min(2.2,w/Math.max(1,length(text)));
return Math.min(h/(lines.length*1.15),w/Math.max(1,...lines.map(length)))*.92;
if(slot.direction==='curved')return Math.min(2.2,Math.max(w,h)*1.1/Math.max(1,length(text)));
const fitted=Math.min(h/(lines.length*1.15),w/Math.max(1,...lines.map(length)))*.92;
return /微字|脚注|图注|标签/.test(slot.role)?Math.min(fitted,2.2):fitted;
}
export function imageShape(layout:Layout,slot:Slot):CSSProperties {
const n=Number(layout.id.slice(4)),s:CSSProperties={backgroundColor:slot.id==='I01'?'#9ba6a3':'#788785'};
const n=Number(layout.id.slice(4)),s:CSSProperties={backgroundColor:layoutPalette(layout.id)[slot.id==='I01'?2:3],backgroundImage:'linear-gradient(145deg,#ffffff12,transparent 65%)'};
if([4,5,7,13,19,20].includes(n)||(n===17&&slot.id==='I02'))s.borderRadius='50%';
if(n===4)s.transform='rotate(-9deg)';
if(n===15&&slot.id==='I01')s.borderRadius='100% 0 0 0';
if(n===22)s.backgroundColor=layoutPalette(layout.id)[slot.id==='I02'?3:slot.id==='I03'?4:2];
if(n===22)s.clipPath=slot.id==='I01'?'polygon(0 0,100% 0,100% 48%,0 100%)':slot.id==='I02'?'polygon(0 30%,100% 0,100% 70%,0 100%)':'polygon(0 50%,100% 0,100% 100%,0 100%)';
if(n===27)s.clipPath=slot.id==='I01'?'polygon(0 0,100% 35%,100% 100%,0 68%)':'polygon(0 40%,100% 0,100% 100%,0 100%)';
if(n===10)s.backgroundColor='#596c67';
if(n===16)s.backgroundColor=slot.id==='I01'?'#b6bfba':'#7e8e87';
if(n===20&&slot.id==='I02')s.backgroundColor='#e3e6dc';
if(n===10)s.backgroundColor=layoutPalette(layout.id)[2];
if(n===16)s.backgroundColor=layoutPalette(layout.id)[slot.id==='I01'?3:2];
if(n===20&&slot.id==='I02')s.backgroundColor=layoutPalette(layout.id)[3];
return s;
}
export function decorationKind(slot:Slot){
+18 -2
View File
@@ -3,12 +3,28 @@ import {embedLayoutImages} from '../../../lib/layout-images';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import layouts from '../../../content/templates/layouts.json';
import standardLayout from '../../../content/standard-layout.json';
import {LayoutCanvas} from '../../../components/LayoutCanvas';
import {parameters,LayoutParameterError} from '../../../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(`# 排版参数与渲染 API\n\nGET /studio/api/layouts/{id} 返回模板尺寸、T/I/D 构件 ID、坐标、原始文字可辨识状态与默认参数。id 为 ref-01 .. ref-27。\n页面 /studio/layouts/{id} 直接提供原生 HTML/CSS 默认排版,不加载原图。带 ?id={designId} 在服务端加载已保存页面;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/layouts/{layoutId}?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(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(renderToStaticMarkup(createElement(LayoutCanvas,{layout,params,imageSources:await embedLayoutImages(req,params)})))}return res.json({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,url:'/studio/layouts/'+layout.id})}catch(e){return res.status(400).json({error:e instanceof Error?e.message:'参数不合法'})}
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(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'}}};
+9 -2
View File
@@ -1,3 +1,10 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import layouts from '../../../content/templates/layouts.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=layouts.map(l=>({id:l.id,name:l.name,url:'/studio/layouts/'+l.id,api:'/studio/api/layouts/'+l.id,tutorialUrl:l.tutorialUrl}));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('# 27 套排版 API\n\n'+entries.map(e=>`${e.id} · ${e.name}\n效果页:${e.url}\n参数和渲染:${e.api}?agent_mode=True`).join('\n\n')+'\n\n效果保存:/api/studio/designs?agent_mode=True\nRouter:/explore/8eb8c76500580f7a4b56ba3c')}return res.json({version:1,layouts:entries,saveApi:'/api/studio/designs'})}
import fixed from '../../../content/templates/layouts.json';
import standard from '../../../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\nCRUD:/api/studio/designs?agent_mode=True\n统一文档:/explore/8eb8c76500580f7a4b56ba3c')}
return res.json({version:1,layouts:entries,saveApi:'/api/studio/designs',catalogUrl:'/studio',documentationUrl:'/explore/8eb8c76500580f7a4b56ba3c'});
}
+6 -4
View File
@@ -1,4 +1,6 @@
import type {GetServerSideProps} from 'next';
export default function StudioEntry(){return null;}
// Studio tools are entered from their Wiki posts; there is no separate catalogue homepage.
export const getServerSideProps:GetServerSideProps=async()=>({redirect:{destination:'/',permanent:false,basePath:false}});
import Head from 'next/head';
import fixed from '../content/templates/layouts.json';
import standard from '../content/standard-layout.json';
import {nativeLayout} from '../lib/native-layout';
import {NativePreview as Preview} from '../components/NativePreview';
export default function StudioEntry(){return <main className="studio-library"><Head><title>Studio · 可视化排版 API 库</title></Head><nav className="library-nav"><a href="/">PROMPT / STUDIO</a><a href="/explore/8eb8c76500580f7a4b56ba3c">使用文档与工具箱</a><a href="/api/studio/designs?agent_mode=True">API 契约</a></nav><h1>用参数,编排画面。</h1><p className="library-intro">给 coding agent 文字、图片与创作意图。选择标准图文或固定构图,通过 HTTP 保存渲染描述,得到一个可持续更新的原生页面。</p><div className="library-heading"><h2>标准排版</h2><a href="/studio/api/layouts/standard-01">参数</a></div><div className="library-standard"><a href="/studio/layouts/standard-01"><Preview layout={standard}/></a><div><h2>一页,一件事。</h2><p>沿用 Studio 标题、正文与页脚的图文结构,增加可配置图片位。文字、颜色、图片和几何坐标共用一套参数,也可添加原生元素。</p><code>layoutId: standard-01</code><p><a href="/studio/layouts/standard-01">打开原生页面</a></p></div></div><div className="library-heading"><h2>固定排版 · 27 套</h2><a href="/explore/8eb8c76500580f7a4b56ba3c">使用文档</a></div><div className="library-grid">{fixed.map(l=><article className="library-item" key={l.id}><a href={'/studio/layouts/'+l.id}><Preview layout={nativeLayout(l)}/><h3>{l.name}</h3><p>{l.id.toUpperCase()}</p></a></article>)}</div></main>}
+10 -7
View File
@@ -1,17 +1,20 @@
import type {GetServerSideProps} from 'next';
import {LayoutWorkbench,type LayoutPageProps} from '../../components/LayoutWorkbench';
import layouts from '../../content/templates/layouts.json';
import {nativeLayout} from '../../lib/native-layout';
import {NativeResult} from '../../components/NativeResult';
import type {Layout} from '../../lib/layout-parameters';
import fixedLayouts from '../../content/templates/layouts.json';
import standardLayout from '../../content/standard-layout.json';
const layouts=[...fixedLayouts,standardLayout];
import {nativeLayout,designUrl} from '../../lib/native-layout';
import {readDesign} from '../../lib/design-server';
export default function LayoutPage(props:LayoutPageProps){return <LayoutWorkbench key={props.design?.id||props.layout.id} {...props}/>}
export const getServerSideProps:GetServerSideProps<LayoutPageProps>=async({params,query,req,res})=>{
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 {props:{layout:nativeLayout(layout),design}};
return {redirect:{destination:designUrl(design.layoutId,design.id).slice('/studio'.length),permanent:false}};
}
return {props:{layout:nativeLayout(layout),design:null}};
return {props:{layout:nativeLayout(layout)}};
};
+18
View File
@@ -0,0 +1,18 @@
import type {GetServerSideProps} from 'next';
import {NativeResult} from '../components/NativeResult';
import fixedLayouts from '../content/templates/layouts.json';
import standardLayout from '../content/standard-layout.json';
import {readDesign} from '../lib/design-server';
import {nativeLayout,type Design} from '../lib/native-layout';
import type {Layout} from '../lib/layout-parameters';
type Props={layout:Layout;design:Design};
export default function TemplateLayout(props:Props){return <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};
return {props:{layout:nativeLayout(layout),design}};
};
File diff suppressed because one or more lines are too long
@@ -3,3 +3,5 @@ import {parameters} from '../src/lib/layout-parameters.ts';
const layouts=JSON.parse(readFileSync(new URL('../src/content/templates/layouts.json',import.meta.url)));
test('27 layouts preserve unique typed source slots and complete shapes',()=>{assert.equal(layouts.length,27);for(const [i,l] of layouts.entries()){assert.equal(l.id,'ref-'+String(i+1).padStart(2,'0'));assert.equal(new Set(l.elements.map(s=>s.id)).size,l.elements.length);for(const s of l.elements){assert.match(s.id,/^[TID]\d{2}$/);assert.equal(s.kind,({T:'text',I:'image',D:'decoration'})[s.id[0]]);assert.ok(s.box[0]>=0&&s.box[1]>=0&&s.box[0]+s.box[2]<=l.width&&s.box[1]+s.box[3]<=l.height);assert.match(s.raster,/^data:image\/png;base64,/);if(s.kind==='image')assert.match(s.shape,/^data:image\/png;base64,/)}assert.deepEqual(parameters(l,{}),{texts:{},images:{},decorations:{}})}});
test('parameters reject mismatched slots, unsafe URLs and excessive text',()=>{const l=layouts[0];for(const input of [{texts:{I01:{value:'bad'}}},{images:{I01:{url:'https://evil.test'}}},{texts:{T01:{value:'x',scale:3}}},{texts:{T01:{value:'x'.repeat(501)}}},{paper:'url(x)'},{decorations:{D01:{hidden:'true'}}},null,[]])assert.throws(()=>parameters(l,input));const p=parameters(l,{texts:{T01:{value:'<script>not markup</script>',scale:1.2,align:'middle'}},images:{I01:{color:'#abcdef',fit:'contain'}},decorations:{D01:{hidden:true}}});assert.equal(p.texts.T01.value,'<script>not markup</script>');assert.equal(p.decorations.D01.hidden,true)});
test('workspace parameters round-trip identically through Studio and Wiki validation',async()=>{const {parameters:wiki}=await import('../../waterfall-wiki/src/lib/layout-parameters.ts');for(const l of layouts){const added={id:'user-example',kind:'text',role:'Added text',box:[3,4,20,12],direction:'horizontal',text:'Hello',reading:'custom'};const input={added:[added],layers:{T01:{x:2,y:4,width:15,height:10,rotation:25,opacity:.7,radius:2,z:10,hidden:false,locked:true},'user-example':{x:8,z:20}},texts:{T01:{value:'Updated',fontFamily:'serif',fontSize:4,fontWeight:700,lineHeight:1.6,letterSpacing:.2},'user-example':{value:'Hello'}},images:{I01:{fit:'cover',cropX:15,cropY:85,zoom:2}}};assert.deepEqual(parameters(l,input),wiki(l,input));assert.deepEqual(parameters(l,parameters(l,input)),parameters(l,input))}});
test('workspace validation rejects unbounded, mismatched and executable properties',()=>{const l=layouts[0];for(const input of [{layers:{unknown:{x:2}}},{layers:{T01:{rotation:Infinity}}},{layers:{T01:{width:0}}},{layers:{T01:{opacity:2}}},{layers:{T01:{locked:'yes'}}},{texts:{T01:{value:'x',fontFamily:'url(evil)'}}},{images:{I01:{cropX:101}}},{images:{I01:{zoom:0}}},{added:[{id:'T01'}]},{added:Array(101).fill({})},{layers:{T01:{onClick:'evil'}}}])assert.throws(()=>parameters(l,input))});
+5 -2
View File
@@ -1,7 +1,7 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {nativeLayout,defaultText,textSize,imageShape,designUrl} from '../src/lib/native-layout.ts';
import {nativeLayout,defaultText,textSize,imageShape,designUrl,newElementId} from '../src/lib/native-layout.ts';
const layouts=JSON.parse(readFileSync(new URL('../src/content/templates/layouts.json',import.meta.url)));
test('all 27 native pages are independent of source images and supply actual text',()=>{
for(const original of layouts){const layout=nativeLayout(original),serialized=JSON.stringify(layout);assert.ok(!serialized.includes('data:image'));assert.ok(!serialized.includes('raster'));assert.ok(!serialized.includes('source'));assert.ok(serialized.length<7000);
@@ -12,5 +12,8 @@ test('geometric templates retain their distinct silhouettes without bitmap masks
assert.equal(imageShape(layouts[4],layouts[4].elements.find(s=>s.id==='I03')).borderRadius,'50%');
assert.ok(imageShape(layouts[21],layouts[21].elements.find(s=>s.id==='I02')).clipPath.startsWith('polygon('));
assert.notEqual(imageShape(layouts[21],layouts[21].elements.find(s=>s.id==='I02')).clipPath,imageShape(layouts[26],layouts[26].elements.find(s=>s.id==='I02')).clipPath);
assert.equal(designUrl('ref-01','abc'),'/studio/layouts/ref-01?id=abc');
assert.equal(designUrl('ref-01','abc'),'/studio/template-layout?id=abc');
assert.equal(designUrl('standard-01','abc'),'/studio/template-layout?id=abc');
});
test('element IDs work on HTTP origins without secure-context randomUUID',()=>{const saved=Object.getOwnPropertyDescriptor(globalThis,'crypto');let calls=0;Object.defineProperty(globalThis,'crypto',{configurable:true,value:{getRandomValues(array){for(let i=0;i<array.length;i++)array[i]=++calls;return array}}});try{const first=newElementId(),second=newElementId();assert.match(first,/^user-[a-f0-9]{32}$/);assert.notEqual(first,second)}finally{Object.defineProperty(globalThis,'crypto',saved)}});
@@ -0,0 +1,12 @@
BEGIN;
ALTER TABLE studio_designs ADD COLUMN IF NOT EXISTS post_id uuid REFERENCES posts(id) ON DELETE RESTRICT;
CREATE UNIQUE INDEX IF NOT EXISTS studio_designs_post ON studio_designs(post_id) WHERE post_id IS NOT NULL;
-- Adopt explicitly published entries, including the user's page repaired before deployment.
UPDATE studio_designs d SET post_id=p.id
FROM posts p
WHERE d.post_id IS NULL AND p.slug='studio-design-'||d.id::text
AND EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id
WHERE pa.post_id=p.id AND a.kind='text'
AND strpos(a.body,'/studio/layouts/'||d.layout_id||'?id='||d.id::text)>0);
INSERT INTO schema_migrations(version) VALUES('010_studio_design_posts') ON CONFLICT DO NOTHING;
COMMIT;
@@ -0,0 +1,6 @@
BEGIN;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS archived boolean NOT NULL DEFAULT false;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS archived_at timestamptz;
CREATE INDEX IF NOT EXISTS posts_active_timeline ON posts(created_at DESC,id DESC) WHERE NOT archived;
INSERT INTO schema_migrations(version) VALUES('011_post_archiving') ON CONFLICT DO NOTHING;
COMMIT;
@@ -0,0 +1,7 @@
BEGIN;
ALTER TABLE studio_designs DROP CONSTRAINT studio_designs_layout_id_check;
ALTER TABLE studio_designs ADD CONSTRAINT studio_designs_layout_id_check CHECK (layout_id='standard-01' OR layout_id ~ '^ref-(0[1-9]|1[0-9]|2[0-7])$');
ALTER TABLE studio_designs ADD COLUMN archived boolean NOT NULL DEFAULT false;
ALTER TABLE studio_designs ADD COLUMN archived_at timestamptz;
INSERT INTO schema_migrations(version) VALUES('012_studio_library');
COMMIT;
@@ -2,7 +2,7 @@ import Head from 'next/head';
import Link from 'next/link';
import {useEffect,useRef,useState} from 'react';
import {useRouter} from 'next/router';
import {X,ChevronLeft,ChevronRight,Link as LinkIcon,FileText,Pencil} from 'lucide-react';
import {X,ChevronLeft,ChevronRight,Link as LinkIcon,FileText,Pencil,Archive,ArchiveRestore} from 'lucide-react';
import type {ExploreEntry} from '@/lib/explore';
import {previewUrl,exploreUrl} from '@/content/page-links';
import {Shell} from './Shell';
@@ -11,7 +11,7 @@ import {NoteMarkdown} from './NoteMarkdown';
import {QuickTags} from './QuickTags';
import {NoteEditor} from './NoteEditor';
export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;background:ExploreEntry[]}){
const [entry,setEntry]=useState(initial),[index,setIndex]=useState(0),[copied,setCopied]=useState(''),[editing,setEditing]=useState(false),[copyError,setCopyError]=useState('');
const [entry,setEntry]=useState(initial),[index,setIndex]=useState(0),[copied,setCopied]=useState(''),[editing,setEditing]=useState(false),[copyError,setCopyError]=useState(''),[archiveBusy,setArchiveBusy]=useState(false);
const router=useRouter();const closeRef=useRef<HTMLButtonElement>(null),detailRef=useRef<HTMLDivElement>(null);const media=entry.media[index];
useEffect(()=>{setEntry(initial);setIndex(0);setCopied('');setEditing(false)},[initial]);
const close=()=>{if(editing){setEditing(false);return;}void router.push('/')};
@@ -32,6 +32,9 @@ export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;bac
setCopied(mode);setCopyError('');
}catch{setCopied('');setCopyError('复制失败,请重试。')}
}
async function archive(){
setArchiveBusy(true);setCopyError('');try{const r=await fetch('/api/posts/'+entry.id+'/archive',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({archived:!entry.archived})});const d=await r.json();if(!r.ok)throw Error(d.error||'操作失败');const state=await fetch('/api/notes/'+entry.id).then(r=>r.json());setEntry(state.entry);void router.replace(router.asPath,undefined,{scroll:false})}catch(e){setCopyError(e instanceof Error?e.message:'操作失败')}finally{setArchiveBusy(false)}
}
return <Shell><Head><title>{entry.title} · PROMPT</title><link rel="canonical" href={exploreUrl(entry.id)}/><link rel="alternate" type="text/plain" href={exploreUrl(entry.id)+'?agent_mode=True'}/></Head>
<div aria-hidden="true" inert><ExploreFeed key={entry.revision} initial={background.map(e=>e.id===entry.id?entry:e)}/></div>
<div className="note-overlay" onClick={()=>{if(!editing)close()}}><div className="note-dialog" ref={detailRef} role="dialog" aria-modal="true" aria-labelledby="note-title" onClick={e=>e.stopPropagation()}>
@@ -40,7 +43,7 @@ export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;bac
{media?.kind==='image'?<img key={media.url} src={previewUrl(media.url,1280)} alt={media.title} decoding="async"/>:media?.kind==='video'?<video controls playsInline preload="metadata" src={media.url} poster={media.poster?previewUrl(media.poster,960):undefined}/>:media?.kind==='audio'?<div className="note-audio"><span>♫</span><audio controls preload="metadata" src={media.url}/></div>:<div className="note-title-cover" style={{background:entry.color}}><small>{entry.namespace}</small><strong>{entry.title}</strong><span>灵感笔记</span></div>}
{entry.media.length>1&&<><button className="note-prev" aria-label="上一张" disabled={index===0} onClick={()=>setIndex(n=>n-1)}><ChevronLeft/></button><button className="note-next" aria-label="下一张" disabled={index===entry.media.length-1} onClick={()=>setIndex(n=>n+1)}><ChevronRight/></button><div className="note-dots">{entry.media.map((_,i)=><button key={i} className={i===index?'selected':''} aria-label={'查看第 '+(i+1)+' 张'} aria-pressed={i===index} onClick={()=>setIndex(i)}/>)}</div><span className="note-count">{index+1} / {entry.media.length}</span></>}
</section><section className="note-info"><div className="note-content">
{editing?<NoteEditor key={entry.id} entry={entry} onCancel={()=>setEditing(false)} onSaved={updated=>{setEntry(updated);setEditing(false);setCopied('')}}/>:<><h1 id="note-title">{entry.title}</h1><p className="note-description">{entry.description}</p><div className="note-tags">{entry.systemTags?.map(t=><Link className="system-tag-pill" key={t.id} href={"/categories?category="+encodeURIComponent(t.name)}>{t.name}</Link>)}{entry.categories.map(c=><Link key={c} href={'/categories?category='+encodeURIComponent(c)}>#{c} </Link>)}<QuickTags entry={entry} onSaved={setEntry}/></div><NoteMarkdown text={entry.markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'')}/><section id="backlinks" className="note-backlinks"><h2>被 {entry.backlinkCount??0} 篇笔记引用</h2>{entry.backlinks?.length?<ul>{entry.backlinks.map(ref=><li key={ref.id}><Link href={exploreUrl(ref.id)}>{ref.title}</Link></li>)}</ul>:<p>还没有笔记引用本文。</p>}</section><div className="note-id">内容 ID · {entry.id}</div></>}
</div>{!editing&&<footer><button onClick={()=>void copy('web')}><LinkIcon size={18}/>{copied==='web'?'网页链接已复制':'复制网页链接'}</button><button onClick={()=>void copy('agent')}><FileText size={18}/>{copied==='agent'?'纯文本链接已复制':'复制纯文本链接'}</button><button onClick={()=>setEditing(true)}><Pencil size={17}/>编辑</button>{copyError&&<span role="status">{copyError}</span>}</footer>}</section>
{editing?<NoteEditor key={entry.id} entry={entry} onCancel={()=>setEditing(false)} onSaved={updated=>{setEntry(updated);setEditing(false);setCopied('')}}/>:<><h1 id="note-title">{entry.title}</h1>{entry.archived&&<p className="note-archive-status" role="status">已归档 · 已从列表和搜索中隐藏,内容仍保留。</p>}<p className="note-description">{entry.description}</p><div className="note-tags">{entry.systemTags?.map(t=><Link className="system-tag-pill" key={t.id} href={"/categories?category="+encodeURIComponent(t.name)}>{t.name}</Link>)}{entry.categories.map(c=><Link key={c} href={'/categories?category='+encodeURIComponent(c)}>#{c} </Link>)}<QuickTags entry={entry} onSaved={setEntry}/></div><NoteMarkdown text={entry.markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'')}/><section id="backlinks" className="note-backlinks"><h2>被 {entry.backlinkCount??0} 篇笔记引用</h2>{entry.backlinks?.length?<ul>{entry.backlinks.map(ref=><li key={ref.id}><Link href={exploreUrl(ref.id)}>{ref.title}</Link></li>)}</ul>:<p>还没有笔记引用本文。</p>}</section><div className="note-id">内容 ID · {entry.id}</div></>}
</div>{!editing&&<footer><button onClick={()=>void copy('web')}><LinkIcon size={18}/>{copied==='web'?'网页链接已复制':'复制网页链接'}</button><button onClick={()=>void copy('agent')}><FileText size={18}/>{copied==='agent'?'纯文本链接已复制':'复制纯文本链接'}</button><button onClick={()=>setEditing(true)}><Pencil size={17}/>编辑</button>{entry.postSlug&&<button disabled={archiveBusy} onClick={()=>void archive()}>{entry.archived?<ArchiveRestore size={17}/>:<Archive size={17}/>}{archiveBusy?'处理中…':entry.archived?'恢复':'归档'}</button>}{copyError&&<span role="status">{copyError}</span>}</footer>}</section>
</div></div></Shell>;
}
@@ -0,0 +1,78 @@
{
"id": "standard-01",
"name": "标准排版 · 自由图文",
"width": 120,
"height": 160,
"elements": [
{
"id": "T01",
"kind": "text",
"role": "主标题",
"box": [
10,
16,
100,
28
],
"direction": "horizontal",
"text": "让每一页\n只讲一件事",
"reading": "standard"
},
{
"id": "T02",
"kind": "text",
"role": "正文",
"box": [
10,
112,
100,
27
],
"direction": "horizontal",
"text": "一个标题,一段解释,\n一个值得被记住的画面。",
"reading": "standard"
},
{
"id": "T03",
"kind": "text",
"role": "栏目",
"box": [
10,
7,
100,
4
],
"direction": "horizontal",
"text": "PROMPT STUDIO / 01",
"reading": "standard"
},
{
"id": "I01",
"kind": "image",
"role": "主题图片",
"box": [
10,
53,
100,
50
],
"direction": "horizontal",
"text": null,
"reading": "standard"
},
{
"id": "D01",
"kind": "decoration",
"role": "分隔线",
"box": [
10,
146,
100,
1
],
"direction": "horizontal",
"text": null,
"reading": "standard"
}
]
}
@@ -2,6 +2,13 @@ import type {NextApiRequest,NextApiResponse} from 'next';
// Read documentation before business validation or storage access. Mutations never enter this branch.
export const apiDocuments:Record<string,readonly string[]>={
"/api/posts/{id}/archive": [
"归档或恢复笔记", "POST",
"路径参数 id 为存储 UUID 或24位 publicId。JSON 参数:{archived:true} 归档,{archived:false} 恢复。重复调用幂等,不删除 post、正文、媒体、标签或页面记录。",
"200 {post:{id,publicId,title,archived,archivedAt,url}}。归档内容不出现在首页、分类、搜索和普通素材流,仍可通过原地址读取并恢复。GET /api/feed?archived=true 列举归档内容;默认只列出未归档内容。",
"POST /api/posts/{id}/archive\n{\"archived\":true}",
"400 参数不合法;404 笔记不存在;405 方法不支持。"
],
"/api/explore-feed": [
"统一内容流",
"GET",
@@ -13,7 +20,7 @@ export const apiDocuments:Record<string,readonly string[]>={
"/api/feed": [
"素材列表",
"GET",
"查询参数:section(images / videos / audio / articles / motion,可选);path(可选,标签 path);q(可选,最多 200 字符);cursor(可选,上一页 nextCursor)。",
"查询参数:archived(字符串 true / false,默认 false;true 只列出归档);section(images / videos / audio / articles / motion,可选);path(可选,标签 path);q(可选,最多 200 字符);cursor(可选,上一页 nextCursor)。",
"JSON:posts、tags、contributions、nextCursor;每页最多 24 个 post。",
"GET /api/feed?section=images",
"400:未知 section、标签或无效游标。"
+7 -6
View File
@@ -7,11 +7,11 @@ import {wikiPages,wikiMarkdown} from '@/content/wiki';
import {skillCatalog} from '@/content/skills/catalog';
import {publicPostId} from './model';
import {pageId,exploreUrl,guidanceUrl} from '@/content/page-links';
import {getPostById,discoveryDocuments,postsByPublicIds} from './library';
import {getPostById,discoveryDocuments,postsByPublicIds,publishedPublicIds} from './library';
import {backlinksFor,rankDocuments,discoveryPage,type SearchDocument,type Backlink} from './discovery';
import {applyStaticEdit,staticEdits,withRevision} from './note-edits';
export type ExploreMedia={kind:'image'|'video'|'audio';url:string;title:string;poster?:string};
export type ExploreEntry={id:string;title:string;description:string;imageCount:number;namespace:string;categories:string[];systemTags?:Tag[];markdown:string;media:ExploreMedia[];color:string;postSlug?:string;editableMarkdown?:string;revision?:string;assets?:{id:string;kind:string;role:string}[];coverAssetId?:string|null;backlinkCount?:number;backlinks?:Backlink[];searchExcerpt?:string};
export type ExploreEntry={archived?:boolean;id:string;title:string;description:string;imageCount:number;namespace:string;categories:string[];systemTags?:Tag[];markdown:string;media:ExploreMedia[];color:string;postSlug?:string;editableMarkdown?:string;revision?:string;assets?:{id:string;kind:string;role:string}[];coverAssetId?:string|null;backlinkCount?:number;backlinks?:Backlink[];searchExcerpt?:string};
export const staticEntries:ExploreEntry[]=[...guidanceDocuments.map(doc=>{const card=skillCatalog.find(c=>doc.path===c.id);return {id:pageId('guidance:'+doc.path),title:doc.title,description:noteDescriptions[doc.path]||doc.blocks.find(b=>b.type==='paragraph')?.text||doc.title,imageCount:new Set([...(card?[card.image]:[]),...doc.resources.filter(r=>r.kind==='image').map(r=>r.href)]).size,namespace:'Main',categories:[doc.collection,...(doc.collection==='照片入皮影'?['中国风']:doc.collection==='街头小人'?['贴纸']:[])],systemTags:card?[systemTags[0]]:[],markdown:guidanceMarkdown(doc.path)!,media:Array.from(new Map([...(card?[{kind:'image' as const,url:card.image,title:card.alt}]:[]),...doc.resources.filter(r=>r.kind==='image').map(r=>({kind:'image' as const,url:r.href,title:r.title}))].map(m=>[m.url,m])).values()),color:'#eee5dc'};}),...wikiPages.map(page=>({id:pageId('wiki:'+page.namespace+':'+page.slug),title:page.title,description:page.summary,imageCount:0,namespace:page.namespace,categories:page.categories,markdown:wikiMarkdown(page),media:[],color:page.color}))];
// Canonicalize document references, including absolute links; pictures remain explicit links.
export function canonicalMarkdown(text:string){return text.replace(/\]\((?:http:\/\/8\.211\.154\.134:18131)?\/skills\/([^ )]+)\)/g,(whole,path:string)=>{const clean=path.replace(/\/index\.md$/,'').replace(/\.md$/,'');return pageId('guidance:'+clean)?']('+guidanceUrl(clean)+'?agent_mode=True)':whole;});}
@@ -23,11 +23,12 @@ async function readEntry(id:string,client?:PoolClient):Promise<ExploreEntry|null
const media:ExploreMedia[]=orderedAssets.filter(a=>a.kind!=='text'&&a.role==='content').map(a=>({kind:a.kind as ExploreMedia['kind'],url:'/api/media/'+a.id,title:a.filename||post.title,...(a.kind==='video'&&a.variants.includes('poster')?{poster:'/api/media/'+post.assets.find(p=>p.source_asset_id===a.id&&p.derivation==='poster')?.id}:{})}));
const editableMarkdown=post.assets.filter(a=>a.kind==='text').map(a=>a.body||'').join('\n\n');
const body=editableMarkdown+'\n\n'+post.assets.filter(a=>a.derivation).map(a=>'['+({poster:'视频封面',audio_track:'独立音轨',silent_video:'静音视频'}[a.derivation||'']||a.derivation)+'](/api/media/'+a.id+')').join(' · ');
return withRevision({id:publicPostId(post),assets:post.assets.filter(a=>a.kind!=='text').map(a=>({id:a.id,kind:a.kind,role:a.role})),coverAssetId:post.cover_asset_id,title:post.title,editableMarkdown,description:post.description||body.slice(0,180)||post.title,imageCount:media.filter(m=>m.kind==='image').length,namespace:['image','video','audio'].includes(post.kind)?'File':'Main',categories:ordinaryTags(post.tags).map(t=>t.name),systemTags:selectedSystemTags(post.tags),markdown:'# '+post.title+'\n\n'+body,media,color:'#eee5dc',postSlug:post.slug});
return withRevision({archived:post.archived||false,id:publicPostId(post),assets:post.assets.filter(a=>a.kind!=='text').map(a=>({id:a.id,kind:a.kind,role:a.role})),coverAssetId:post.cover_asset_id,title:post.title,editableMarkdown,description:post.description||body.slice(0,180)||post.title,imageCount:media.filter(m=>m.kind==='image').length,namespace:['image','video','audio'].includes(post.kind)?'File':'Main',categories:ordinaryTags(post.tags).map(t=>t.name),systemTags:selectedSystemTags(post.tags),markdown:'# '+post.title+'\n\n'+body,media,color:'#eee5dc',postSlug:post.slug});
}
export async function discoveryCorpus(client?:PoolClient){
const [stored,edits]=await Promise.all([process.env.DATABASE_URL||client?discoveryDocuments(client):Promise.resolve([]),staticEdits(client)]);
const published=new Set(stored.map(p=>p.public_id));
const [stored,edits,publishedIds]=await Promise.all([process.env.DATABASE_URL||client?discoveryDocuments(client):Promise.resolve([]),staticEdits(client),process.env.DATABASE_URL||client?publishedPublicIds(client):Promise.resolve([])]);
// Archived database notes must still suppress their file-backed predecessors.
const published=new Set(publishedIds);
const pages=staticEntries.filter(e=>!published.has(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));
const documents:SearchDocument[]=[...pages.map(e=>({id:e.id,title:e.title,description:e.description,markdown:canonicalMarkdown(e.markdown),categories:e.categories,systemTags:e.systemTags?.flatMap(t=>[t.name,t.system_key||'']),namespace:e.namespace,createdAt:''})),...stored.map(p=>({id:p.public_id||p.id,aliases:[p.id],title:p.title,description:p.description,markdown:canonicalMarkdown(p.markdown),categories:p.categories,systemTags:(p.system_tags||[]).flatMap((t:Tag)=>[t.name,t.system_key||'']),namespace:['image','video','audio'].includes(p.kind)?'File':'Main',createdAt:new Date(p.created_at).toISOString()}))];
return {documents,pages};
@@ -49,4 +50,4 @@ export async function exploreFeed(q='',category='',cursor?:string){
});return {entries,nextCursor:page.nextCursor,total:page.total,sort:q?'relevance,backlinks,newest':'backlinks,newest'};
}
function excerpt(markdown:string,q:string){const clean=markdown.replace(/[`#*_[\]<>]/g,'').replace(/\s+/g,' '),term=q.trim().replace(/^"|"$/g,'').split(/\s+/)[0]||'',at=clean.toLocaleLowerCase().indexOf(term.toLocaleLowerCase());return (at>50?'…':'')+clean.slice(Math.max(0,at-50),Math.max(0,at-50)+180);}
export function entryText(entry:ExploreEntry){return `${entry.markdown}\n\nDescription: ${entry.description}\nBacklinks: ${entry.backlinkCount??0}\n${(entry.backlinks||[]).map(b=>'引用来源:['+b.title+']('+exploreUrl(b.id)+')').join('\n')}\nSystem tags: ${(entry.systemTags||[]).map(t=>t.name).join(', ')}\nNamespace: ${entry.namespace}\nCategories: ${entry.categories.join(', ')}\n\n`+entry.media.map(m=>`- ${m.kind}: [${m.title}](${m.url})`).join('\n')+'\n\n[网页]('+exploreUrl(entry.id)+')\n';}
export function entryText(entry:ExploreEntry){return `${entry.markdown}\n\nArchived: ${entry.archived?'true':'false'}\nDescription: ${entry.description}\nBacklinks: ${entry.backlinkCount??0}\n${(entry.backlinks||[]).map(b=>'引用来源:['+b.title+']('+exploreUrl(b.id)+')').join('\n')}\nSystem tags: ${(entry.systemTags||[]).map(t=>t.name).join(', ')}\nNamespace: ${entry.namespace}\nCategories: ${entry.categories.join(', ')}\n\n`+entry.media.map(m=>`- ${m.kind}: [${m.title}](${m.url})`).join('\n')+'\n\n[网页]('+exploreUrl(entry.id)+')\n';}
@@ -1,23 +1,30 @@
export type Slot={id:string;kind:string;role:string;box:number[];direction:string;text:string|null;reading:string};
export type Layout={id:string;name:string;width:number;height:number;elements:Slot[]};
export type TextValue={value:string;color?:string;scale?:number;align?:'start'|'middle'|'end'};
export type ImageValue={assetId?:string;color?:string;fit?:'cover'|'contain'};
export type TextValue={value:string;color?:string;scale?:number;align?:'start'|'middle'|'end';fontFamily?:'sans'|'serif'|'mono';fontSize?:number;fontWeight?:number;lineHeight?:number;letterSpacing?:number};
export type ImageValue={assetId?:string;color?:string;fit?:'cover'|'contain';cropX?:number;cropY?:number;zoom?:number};
export type DecorationValue={color?:string;hidden?:boolean};
export type Parameters={texts:Record<string,TextValue>;images:Record<string,ImageValue>;decorations:Record<string,DecorationValue>;paper?:string};
export type LayerValue={x?:number;y?:number;width?:number;height?:number;rotation?:number;opacity?:number;radius?:number;z?:number;hidden?:boolean;locked?:boolean};
export type AddedSlot=Slot & {shape?:'rectangle'|'ellipse'};
export type Parameters={texts:Record<string,TextValue>;images:Record<string,ImageValue>;decorations:Record<string,DecorationValue>;paper?:string;layers?:Record<string,LayerValue>;added?:AddedSlot[]};
export class LayoutParameterError extends Error{}
export const uuid=(v:unknown):v is string=>typeof v==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);
function fail(message:string):never{throw new LayoutParameterError(message)}
function object(v:unknown):Record<string,unknown>{if(!v||typeof v!=='object'||Array.isArray(v))fail('参数必须为 JSON 对象');return v as Record<string,unknown>}
function keys(v:Record<string,unknown>,allowed:string[]){if(Object.keys(v).some(k=>!allowed.includes(k)))fail('未知参数或构件 ID')}
function number(v:unknown,min:number,max:number){if(typeof v!=='number'||!Number.isFinite(v)||v<min||v>max)fail(`数值范围 ${min}–${max}`);return v}
function color(v:unknown){if(typeof v!=='string'||!/^#[a-f0-9]{6}$/i.test(v))fail('颜色使用 #RRGGBB');return v}
export function parameters(layout:Layout,input:unknown):Parameters{
const raw=object(input);keys(raw,['texts','images','decorations','paper']);const result:Parameters={texts:{},images:{},decorations:{}};
const raw=object(input);keys(raw,['texts','images','decorations','paper','layers','added']);const result:Parameters={texts:{},images:{},decorations:{}};
const added:AddedSlot[]=[];
if(raw.added!==undefined){if(!Array.isArray(raw.added)||raw.added.length>100)fail('最多新增100个元素');for(const entry of raw.added){const v=object(entry);keys(v,['id','kind','role','box','direction','text','reading','shape']);if(typeof v.id!=='string'||!/^user-[a-zA-Z0-9-]{1,60}$/.test(v.id)||added.some(s=>s.id===v.id))fail('新增元素 ID 无效或重复');if(!['text','image','decoration'].includes(String(v.kind)))fail('新增元素类型无效');if(typeof v.role!=='string'||v.role.length>80)fail('图层名称最多80字');if(!Array.isArray(v.box)||v.box.length!==4)fail('box 为 x,y,width,height');const box=v.box.map((n,i)=>number(n,i<2?-10000:.1,10000));if(v.direction!=='horizontal'||v.reading!=='custom'||(v.text!==null&&(typeof v.text!=='string'||v.text.length>500)))fail('新增元素内容无效');if(v.shape!==undefined&&!['rectangle','ellipse'].includes(String(v.shape)))fail('无效形状');added.push({id:v.id,kind:String(v.kind),role:v.role,box,direction:'horizontal',text:v.text as string|null,reading:'custom',...(v.shape?{shape:v.shape as AddedSlot['shape']}:{})})}result.added=added}
const elements=[...layout.elements,...added];
if(raw.layers!==undefined){const entries=object(raw.layers);keys(entries,elements.map(e=>e.id));result.layers={};for(const [id,entry] of Object.entries(entries)){const v=object(entry);keys(v,['x','y','width','height','rotation','opacity','radius','z','hidden','locked']);const layer:Record<string,number|boolean>={};for(const [key,value] of Object.entries(v)){if(key==='hidden'||key==='locked'){if(typeof value!=='boolean')fail('图层开关必须为布尔值');layer[key]=value}else{const range:Record<string,number[]>={x:[-10000,10000],y:[-10000,10000],width:[.1,10000],height:[.1,10000],rotation:[-360,360],opacity:[0,1],radius:[0,5000],z:[-1000,1000]};layer[key]=number(value,range[key][0],range[key][1])}}result.layers[id]=layer}}
if(raw.paper!==undefined)result.paper=color(raw.paper);
for(const [group,kind] of [['texts','text'],['images','image'],['decorations','decoration']] as const){
const entries=object(raw[group]??{});keys(entries,layout.elements.filter(e=>e.kind===kind).map(e=>e.id));
const entries=object(raw[group]??{});keys(entries,elements.filter(e=>e.kind===kind).map(e=>e.id));
for(const [id,value] of Object.entries(entries)){const v=object(value);
if(group==='texts'){keys(v,['value','color','scale','align']);if(typeof v.value!=='string'||Array.from(v.value).length>500||v.value.split('\n').length>8)fail('文字最多 500 字 / 8 行');const t:TextValue={value:v.value};if(v.color!==undefined)t.color=color(v.color);if(v.scale!==undefined){if(typeof v.scale!=='number'||!Number.isFinite(v.scale)||v.scale<.25||v.scale>2)fail('scale 范围 0.25–2');t.scale=v.scale}if(v.align!==undefined){if(!['start','middle','end'].includes(String(v.align)))fail('无效 align');t.align=v.align as TextValue['align']}result.texts[id]=t;
}else if(group==='images'){keys(v,['assetId','color','fit']);const image:ImageValue={};if(v.assetId!==undefined){if(!uuid(v.assetId))fail('assetId 必须为已上传图片 UUID');image.assetId=v.assetId}if(v.color!==undefined)image.color=color(v.color);if(v.fit!==undefined){if(v.fit!=='cover'&&v.fit!=='contain')fail('fit 使用 cover 或 contain');image.fit=v.fit}result.images[id]=image;
if(group==='texts'){keys(v,['value','color','scale','align','fontFamily','fontSize','fontWeight','lineHeight','letterSpacing']);if(typeof v.value!=='string'||Array.from(v.value).length>500||v.value.split('\n').length>8)fail('文字最多 500 字 / 8 行');const t:TextValue={value:v.value};if(v.color!==undefined)t.color=color(v.color);if(v.scale!==undefined){if(typeof v.scale!=='number'||!Number.isFinite(v.scale)||v.scale<.25||v.scale>2)fail('scale 范围 0.25–2');t.scale=v.scale}if(v.align!==undefined){if(!['start','middle','end'].includes(String(v.align)))fail('无效 align');t.align=v.align as TextValue['align']}if(v.fontFamily!==undefined){if(!['sans','serif','mono'].includes(String(v.fontFamily)))fail('无效字体');t.fontFamily=v.fontFamily as TextValue['fontFamily']}for(const [key,min,max] of [['fontSize',.1,1000],['fontWeight',100,900],['lineHeight',.5,4],['letterSpacing',-20,100]] as const)if(v[key]!==undefined)t[key]=number(v[key],min,max);result.texts[id]=t;
}else if(group==='images'){keys(v,['assetId','color','fit','cropX','cropY','zoom']);const image:ImageValue={};if(v.assetId!==undefined){if(!uuid(v.assetId))fail('assetId 必须为已上传图片 UUID');image.assetId=v.assetId}if(v.color!==undefined)image.color=color(v.color);if(v.fit!==undefined){if(v.fit!=='cover'&&v.fit!=='contain')fail('fit 使用 cover 或 contain');image.fit=v.fit}for(const [key,min,max] of [['cropX',0,100],['cropY',0,100],['zoom',1,5]] as const)if(v[key]!==undefined)image[key]=number(v[key],min,max);result.images[id]=image;
}else{keys(v,['color','hidden']);const d:DecorationValue={};if(v.color!==undefined)d.color=color(v.color);if(v.hidden!==undefined){if(typeof v.hidden!=='boolean')fail('hidden 必须为布尔值');d.hidden=v.hidden}result.decorations[id]=d}
}
}
+4 -4
View File
@@ -17,11 +17,11 @@ export async function getPostById(id:string,client?:PoolClient):Promise<Post|nul
const result=await (client||db()).query(`${expand} WHERE ${/^[0-9a-f]{24}$/.test(id)?'p.public_id':'p.id'}=$1`,[id]);
return serialize(result.rows,await tags(client))[0]||null;
}
export async function feed(options: {kind?: PostKind; path?: string; cursor?: string; q?: string} = {}): Promise<FeedData> {
export async function feed(options: {kind?: PostKind; path?: string; cursor?: string; q?: string;archived?:boolean} = {}): Promise<FeedData> {
const allTags=await tags(); const target=options.path ? allTags.find(t=>t.path===options.path) : undefined;
if(options.path&&!target) throw new Error("Tag not found");
const cursor=decodeCursor(options.cursor); const values: unknown[]=[];
const where=[`EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`];
const where=[`p.archived=${options.archived===true?'true':'false'}`,`EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`];
if(options.kind){values.push(options.kind);where.push(`p.kind=$${values.length}`);}
if(target){values.push([target.id]);where.push(`EXISTS(SELECT 1 FROM post_tags WHERE post_id=p.id AND tag_id=ANY($${values.length}::uuid[]))`);}
if(options.q){values.push(`%${options.q.replace(/[\\%_]/g,"\\$&")}%`);where.push(`p.title ILIKE $${values.length}`);}
@@ -32,7 +32,7 @@ export async function feed(options: {kind?: PostKind; path?: string; cursor?: st
return {posts,tags:allTags,contributions,nextCursor:hasMore&&last?encodeCursor(last.created_at,last.id):null};
}
export async function publishedPublicIds():Promise<string[]>{return (await db().query("SELECT public_id FROM posts WHERE public_id IS NOT NULL")).rows.map(p=>p.public_id);}
export async function publishedPublicIds(client?:PoolClient):Promise<string[]>{return (await (client||db()).query("SELECT public_id FROM posts WHERE public_id IS NOT NULL")).rows.map(p=>p.public_id);}
/** Lightweight text corpus: no image bodies or media files are loaded. */
export async function discoveryDocuments(client?:PoolClient){
@@ -40,7 +40,7 @@ export async function discoveryDocuments(client?:PoolClient){
COALESCE((SELECT string_agg(a.body,E'\n\n' ORDER BY pa.position) FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND a.kind='text'),'') AS markdown,
COALESCE((SELECT jsonb_agg(t.name) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id AND t.kind='normal'),'[]') AS categories,
COALESCE((SELECT jsonb_agg(t) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id AND t.kind='system'),'[]') AS system_tags
FROM posts p WHERE EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`)).rows;
FROM posts p WHERE NOT p.archived AND EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`)).rows;
}
export async function postsByPublicIds(ids:string[],client?:PoolClient):Promise<Post[]>{
if(!ids.length)return [];const rows=(await (client||db()).query(`${expand} WHERE COALESCE(p.public_id,p.id::text)=ANY($1::text[])`,[ids])).rows;
+1 -1
View File
@@ -8,7 +8,7 @@ export const sections = [
export type PostKind = typeof sections[number]["kind"];
export type Asset = { id: string; kind: "image" | "video" | "audio" | "text"; filename: string | null; body: string | null; width: number | null; height: number | null; duration: number | null; has_audio: boolean | null; processing_status: string; variants: string[]; role: string; source_asset_id: string | null; derivation: string | null };
export type Tag = { id: string; name: string; slug: string; path: string;kind?:'normal'|'system';system_key?:string|null };
export type Post = { description: string; id: string; public_id?: string | null; slug: string; kind: PostKind; title: string; created_at: string; updated_at: string; cover_asset_id: string | null; assets: Asset[]; tags: Tag[] };
export type Post = { archived?:boolean;archived_at?:string|null; description: string; id: string; public_id?: string | null; slug: string; kind: PostKind; title: string; created_at: string; updated_at: string; cover_asset_id: string | null; assets: Asset[]; tags: Tag[] };
export type FeedData = { posts: Post[]; tags: Tag[]; contributions: { day: string; total: number }[]; nextCursor: string | null; unavailable?: boolean };
export function validSection(path: string) { return sections.find(s => s.path === path); }
export const mediaUrl = (id: string, variant?: string) => `/api/media/${id}${variant ? `?variant=${variant}` : ""}`;
+1 -1
View File
@@ -8,7 +8,7 @@ import {postInput} from './write';
export function withoutTitle(markdown:string){return markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'');}
export function withRevision(entry:ExploreEntry):ExploreEntry{
const editableMarkdown=entry.editableMarkdown??withoutTitle(entry.markdown);
const revision=createHash('sha256').update(JSON.stringify([entry.title,entry.description,editableMarkdown,[...entry.categories].sort(),(entry.systemTags||[]).map(t=>t.id).sort(),entry.coverAssetId??null,entry.assets?.map(a=>[a.id,a.role])??[]])).digest('hex');
const revision=createHash('sha256').update(JSON.stringify([entry.archived||false,entry.title,entry.description,editableMarkdown,[...entry.categories].sort(),(entry.systemTags||[]).map(t=>t.id).sort(),entry.coverAssetId??null,entry.assets?.map(a=>[a.id,a.role])??[]])).digest('hex');
return {...entry,editableMarkdown,revision};
}
export async function staticEdits(client?:PoolClient){if(!process.env.DATABASE_URL)return [];return (await (client||db()).query(`SELECT e.*,COALESCE((SELECT jsonb_agg(t.name ORDER BY t.name) FROM note_edit_tags et JOIN tags t ON t.id=et.tag_id WHERE et.page_id=e.page_id AND t.kind='normal'),'[]') AS categories,COALESCE((SELECT jsonb_agg(t ORDER BY t.name) FROM note_edit_tags et JOIN tags t ON t.id=et.tag_id WHERE et.page_id=e.page_id AND t.kind='system'),'[]') AS "systemTags" FROM note_edits e`)).rows;}
@@ -0,0 +1,11 @@
import {z} from 'zod';
import {db} from './db';
export const archiveInput=z.object({archived:z.boolean()}).strict();
export const postIdentifier=z.string().regex(/^(?:[a-f0-9]{24}|[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12})$/);
export async function setPostArchived(id:string,archived:boolean){
const result=await db().query(`UPDATE posts SET archived=$2,
archived_at=CASE WHEN $2 THEN COALESCE(archived_at,now()) ELSE NULL END,
updated_at=CASE WHEN archived IS DISTINCT FROM $2 THEN now() ELSE updated_at END
WHERE id::text=$1 OR public_id=$1 RETURNING id,public_id,title,archived,archived_at`,[id,archived]);
const post=result.rows[0];return post?{id:post.id,publicId:post.public_id,title:post.title,archived:post.archived,archivedAt:post.archived_at,url:'/explore/'+(post.public_id||post.id)}:null;
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,25 @@
import {randomUUID} from 'node:crypto';
import type {PoolClient} from 'pg';
import type {Parameters} from './layout-parameters';
export type DesignRow={id:string;layout_id:string;name:string;parameters:Parameters;revision:number;post_id:string|null;archived?:boolean;created_at:Date;updated_at:Date};
export const studioPageUrl=(design:Pick<DesignRow,'id'|'layout_id'>)=>`/studio/template-layout?id=${design.id}`;
function postDescription(design:DesignRow){return `已保存的 ${design.layout_id} 排版结果,打开链接即显示图片与文字。`}
/** Caller holds the design row lock. All writes share the design's transaction. */
export async function ensureDesignPost(client:PoolClient,design:DesignRow):Promise<DesignRow>{
if(design.post_id){
// A manually edited Wiki note keeps its own title, body, tags and cover.
await client.query('UPDATE posts SET title=$2,description=$3,updated_at=now() WHERE id=$1 AND edited_at IS NULL',[design.post_id,design.name,postDescription(design)]);
return design;
}
const postId=randomUUID(),textId=randomUUID(),imageIds=[...new Set(Object.values(design.parameters.images||{}).flatMap(image=>image.assetId?[image.assetId]:[]))];
const images=imageIds.length?(await client.query("SELECT id FROM assets WHERE id=ANY($1::uuid[]) AND kind='image'",[imageIds])).rows.map(row=>row.id as string):[];
const body=`[打开排版结果](${studioPageUrl(design)})\n\n排版:${design.layout_id}\n\n页面 ID:\`${design.id}\`\n\n此笔记关联 API 保存的模板、图片与文字;直接打开链接即可看到结果,无需选择排版或进入编辑器。`;
await client.query("INSERT INTO posts(id,slug,kind,title,description,cover_asset_id) VALUES($1,$2,'article',$3,$4,$5)",[postId,'studio-design-'+design.id,design.name,postDescription(design),images[0]||null]);
await client.query("INSERT INTO assets(id,kind,body) VALUES($1,'text',$2)",[textId,body]);
await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,0,'caption')",[postId,textId]);
for(const [index,imageId] of images.entries())await client.query("INSERT INTO post_assets(post_id,asset_id,position,role) VALUES($1,$2,$3,'content')",[postId,imageId,index+1]);
await client.query("INSERT INTO post_tags(post_id,tag_id) SELECT $1,id FROM tags WHERE name='高级感排版' AND kind='normal' ON CONFLICT DO NOTHING",[postId]);
await client.query('UPDATE studio_designs SET post_id=$2 WHERE id=$1',[design.id,postId]);
return {...design,post_id:postId};
}
+49 -6
View File
@@ -1,10 +1,53 @@
import {randomUUID} from 'node:crypto';
import {z} from 'zod';
import {db} from './db';
import type {PoolClient} from 'pg';
import {db,transaction} from './db';
import {parameters,LayoutParameterError} from './layout-parameters';
import layouts from '../content/studio-layouts.json';
export const designInput=z.object({layoutId:z.string(),name:z.string().trim().min(1).max(120),parameters:z.unknown()}).strict();
import fixedLayouts from '../content/studio-layouts.json';
import standardLayout from '../content/standard-layout.json';
const layouts=[...fixedLayouts,standardLayout];
import {ensureDesignPost,studioPageUrl,type DesignRow} from './studio-design-posts';
export const designInput=z.object({schemaVersion:z.literal(1).optional(),layoutId:z.string(),name:z.string().trim().min(1).max(120),parameters:z.unknown()}).strict();
export const updateDesignInput=designInput.omit({layoutId:true}).extend({revision:z.number().int().positive()}).strict();
export function designOutput(r:Record<string,unknown>){return {id:r.id,layoutId:r.layout_id,name:r.name,parameters:r.parameters,revision:r.revision,createdAt:r.created_at,updatedAt:r.updated_at,url:'/studio/designs/'+r.id,renderUrl:'/studio/api/layouts/'+r.layout_id};}
export async function validateDesign(layoutId:string,raw:unknown){const layout=layouts.find(l=>l.id===layoutId);if(!layout)throw new LayoutParameterError('排版不存在');const p=parameters(layout,raw),images=[...new Set(Object.values(p.images).flatMap(i=>i.assetId?[i.assetId]:[]))];if(images.length){const found=await db().query("SELECT id FROM assets WHERE kind='image' AND id=ANY($1::uuid[])",[images]);if(found.rowCount!==images.length)throw new LayoutParameterError('引用的图片素材不存在')}return p;}
export async function createDesign(input:z.infer<typeof designInput>){const p=await validateDesign(input.layoutId,input.parameters);const r=await db().query('INSERT INTO studio_designs(id,layout_id,name,parameters) VALUES($1,$2,$3,$4) RETURNING *',[randomUUID(),input.layoutId,input.name,JSON.stringify(p)]);return designOutput(r.rows[0]);}
export class DesignConflict extends Error{}
export function designOutput(r:Record<string,unknown>){return {id:r.id,layoutId:r.layout_id,name:r.name,parameters:r.parameters,revision:r.revision,schemaVersion:1,family:r.layout_id==='standard-01'?'standard':'fixed',archived:r.archived||false,archivedAt:r.archived_at||null,createdAt:r.created_at,updatedAt:r.updated_at,url:studioPageUrl(r as DesignRow),schemaUrl:'/studio/api/layouts/'+r.layout_id,postId:r.post_id||null,postUrl:r.post_id?'/explore/'+r.post_id:null,renderUrl:studioPageUrl(r as DesignRow),legacySvgUrl:r.layout_id==='standard-01'?null:'/studio/api/layouts/'+r.layout_id+'?format=svg'};}
export async function validateDesign(layoutId:string,raw:unknown,client?:PoolClient){const layout=layouts.find(l=>l.id===layoutId);if(!layout)throw new LayoutParameterError('排版不存在');const p=parameters(layout,raw),images=[...new Set(Object.values(p.images).flatMap(i=>i.assetId?[i.assetId]:[]))];if(images.length){const found=await (client||db()).query("SELECT id FROM assets WHERE kind='image' AND id=ANY($1::uuid[])",[images]);if(found.rowCount!==images.length)throw new LayoutParameterError('引用的图片素材不存在')}return p;}
export async function createDesign(input:z.infer<typeof designInput>){
const p=await validateDesign(input.layoutId,input.parameters);
return transaction(async client=>{
const result=await client.query('INSERT INTO studio_designs(id,layout_id,name,parameters) VALUES($1,$2,$3,$4) RETURNING *',[randomUUID(),input.layoutId,input.name,JSON.stringify(p)]);
return designOutput(await ensureDesignPost(client,result.rows[0]));
});
}
export async function updateDesign(id:string,input:z.infer<typeof updateDesignInput>){
return transaction(async client=>{
const old=(await client.query('SELECT * FROM studio_designs WHERE id=$1 FOR UPDATE',[id])).rows[0] as DesignRow|undefined;
if(!old)return null;
if(old.archived)throw new DesignConflict('页面已归档,请先恢复');
if(old.revision!==input.revision)throw new DesignConflict('效果已被修改,请重新读取后再保存');
const p=await validateDesign(old.layout_id,input.parameters,client);
const result=await client.query('UPDATE studio_designs SET name=$2,parameters=$3,revision=revision+1,updated_at=now() WHERE id=$1 RETURNING *',[id,input.name,JSON.stringify(p)]);
return designOutput(await ensureDesignPost(client,result.rows[0]));
});
}
/** Explicit, repeatable repair for pre-existing designs; never changes their revision. */
export async function publishDesignPost(id:string){
return transaction(async client=>{
const row=(await client.query('SELECT * FROM studio_designs WHERE id=$1 FOR UPDATE',[id])).rows[0] as DesignRow|undefined;
if(!row)return null;
const created=!row.post_id;
return {design:designOutput(await ensureDesignPost(client,row)),created};
});
}
export const archiveDesignInput=z.object({revision:z.number().int().positive(),archived:z.boolean().optional()}).strict();
export async function archiveDesign(id:string,revision:number,archived:boolean){
return transaction(async client=>{
const old=(await client.query('SELECT * FROM studio_designs WHERE id=$1 FOR UPDATE',[id])).rows[0];
if(!old)return null;
if(old.revision!==revision)throw new DesignConflict('修订冲突,请重新读取');
const result=await client.query(`UPDATE studio_designs SET archived=$2,archived_at=CASE WHEN $2 THEN COALESCE(archived_at,now()) ELSE NULL END,revision=revision+1,updated_at=now() WHERE id=$1 RETURNING *`,[id,archived]);
if(old.post_id)await client.query('UPDATE posts SET archived=$2,archived_at=CASE WHEN $2 THEN COALESCE(archived_at,now()) ELSE NULL END,updated_at=now() WHERE id=$1',[old.post_id,archived]);
return designOutput(result.rows[0]);
});
}
+2 -1
View File
@@ -1,3 +1,4 @@
import {z} from 'zod';
import {serveApiDocumentation} from '@/lib/api-documentation';
import type { NextApiRequest,NextApiResponse } from "next";
import { feed } from "@/lib/library";
@@ -7,6 +8,6 @@ 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)}));
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);}
}
+3 -2
View File
@@ -4,10 +4,11 @@ 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',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/designs',title:'保存与列举 Studio 效果',methods:'GET, POST',documentation:'/api/studio/designs?agent_mode=True'},
{path:'/api/studio/designs/{id}',title:'读取与更新效果 ID',methods:'GET, PATCH',documentation:'/api/studio/designs/{id}?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';
@@ -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'}}};
@@ -2,13 +2,19 @@ import type {NextApiRequest,NextApiResponse} from 'next';
import {z} from 'zod';
import {db} from '@/lib/db';
import {sameOrigin,apiError} from '@/lib/api';
import {designOutput,updateDesignInput,validateDesign} from '@/lib/studio-designs';
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'].includes(req.method||'')){res.setHeader('Allow','GET, PATCH');return res.status(405).end()}const id=z.uuid().parse(req.query.id),old=(await db().query('SELECT * FROM studio_designs WHERE id=$1',[id])).rows[0];if(!old)return res.status(404).json({error:'效果不存在'});
if(req.method==='GET')return res.json({design:designOutput(old)});sameOrigin(req);const input=updateDesignInput.parse(req.body),p=await validateDesign(old.layout_id,input.parameters),r=await db().query('UPDATE studio_designs SET name=$2,parameters=$3,revision=revision+1,updated_at=now() WHERE id=$1 AND revision=$4 RETURNING *',[id,input.name,JSON.stringify(p),input.revision]);if(!r.rowCount)return res.status(409).json({error:'效果已被修改,请重新读取后再保存'});return res.json({design:designOutput(r.rows[0])});
}catch(e){if(e instanceof LayoutParameterError)return res.status(400).json({error:e.message});return apiError(res,e)}
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)}
}
@@ -8,7 +8,7 @@ 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(/^ref-(0[1-9]|1[0-9]|2[0-7])$/).optional(),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 ($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]);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})}
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)}
}
@@ -64,3 +64,5 @@
@media(min-width:761px){.tag-popover{position:fixed;left:50%;right:auto;top:50%;width:min(380px,calc(100vw - 32px));transform:translate(-50%,-50%);z-index:1100}}
.discovery-card-meta .backlink-count svg{width:16px;height:16px}.discovery-card .discovery-image-count svg{width:15px;height:15px}
.note-archive-status{background:#fff1db;color:#795d31;padding:10px 12px;border-radius:8px;font-size:13px;line-height:1.6}.note-info>footer{flex-wrap:wrap}
@@ -14,7 +14,7 @@ const request=(method:string,agent_mode:unknown)=>({method,query:{agent_mode}} a
test('every business handler serves documentation before validating parameters or accessing dependencies',async()=>{
const routes:Record<string,string>={
'/api/explore-feed':'explore-feed','/api/feed':'feed','/api/notes/{id}':'notes/[id]',
'/api/posts':'posts/index','/api/tags':'tags','/api/upload':'upload',
'/api/posts/{id}/archive':'posts/[id]/archive','/api/posts':'posts/index','/api/tags':'tags','/api/upload':'upload',
'/api/media/{id}':'media/[id]','/api/preview':'preview',
'/api/skills/street-people':'skills/street-people','/api/health':'health','/api/ready':'ready',
};
@@ -44,7 +44,7 @@ test('normal calls and mutations do not enter documentation mode',()=>{
test('index exposes every business endpoint and its text URL',()=>{
const {state,res}=response();index(request('GET','True'),res);
for(const path of [...Object.keys(apiDocuments),'/studio/api/export/{slug}','/studio/api/health'])assert.ok(String(state.body).includes(path+'?agent_mode=True'));
for(const path of [...Object.keys(apiDocuments),'/studio/api/export/{slug}','/studio/api/health','/api/studio/designs','/api/studio/designs/{id}','/api/studio/designs/{id}/post'])assert.ok(String(state.body).includes(path+'?agent_mode=True'));
});
test('health keeps its regular JSON response',async()=>{
@@ -53,3 +53,12 @@ test('health keeps its regular JSON response',async()=>{
assert.equal(state.status,200);assert.equal((state.body as {status:string}).status,'ok');
});
test('Studio docs describe native editing and atomic Wiki publication without accessing storage',async()=>{
for(const route of ['studio/designs/index','studio/designs/[id]','studio/designs/[id]/post']){
const {default:handler}=await import('../src/pages/api/'+route+'.ts');
const {state,res}=response();await handler(request('GET','True'),res);
assert.equal(state.status,200);assert.match(String(state.body),/postUrl/);assert.match(String(state.body),/整体替换/);assert.match(String(state.body),/同一数据库事务/);assert.match(String(state.body),/原生页面/);
}
});
+61 -2
View File
@@ -59,17 +59,60 @@ test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processi
for(const removed of ['/library/assets','/library/tags'])assert.equal((await fetch(base+removed)).status,404);
assert.equal((await db().query("SELECT 1 FROM schema_migrations WHERE version='009_studio_designs'")).rowCount,1,'Studio migration must be recorded for repeat deployments');
// Studio owns no second database: designs use this same isolated PostgreSQL.
for(let i=1;i<=27;i++){const layoutId='ref-'+String(i).padStart(2,'0'),saved=await request('/api/studio/designs',{layoutId,name:'布局 '+i,parameters:{}});assert.equal(saved.design.layoutId,layoutId);assert.equal(saved.design.revision,1);const read=await request('/api/studio/designs/'+saved.design.id);assert.deepEqual(read.design.parameters,{texts:{},images:{},decorations:{}});}
for(let i=1;i<=27;i++){const layoutId='ref-'+String(i).padStart(2,'0'),saved=await request('/api/studio/designs',{layoutId,name:'布局 '+i,parameters:{}});assert.equal(saved.design.layoutId,layoutId);assert.equal(saved.design.revision,1);assert.ok(saved.design.postId);assert.equal(saved.design.postUrl,'/explore/'+saved.design.postId);assert.equal(saved.design.url,'/studio/template-layout?id='+saved.design.id);const wiki=await request('/api/notes/'+saved.design.postId);assert.ok(wiki.entry.editableMarkdown.includes(saved.design.url));const read=await request('/api/studio/designs/'+saved.design.id);assert.deepEqual(read.design.parameters,{texts:{},images:{},decorations:{}});}
const design=await request('/api/studio/designs',{layoutId:'ref-01',name:'可修改效果',parameters:{texts:{T01:{value:'新的标题'}},images:{I01:{assetId:first.assets[0],fit:'contain'}}}});
const designEdit={name:'更新效果',parameters:{texts:{T01:{value:'修改后'}}},revision:design.design.revision};
const patches=await Promise.all([1,2].map(()=>fetch(base+'/api/studio/designs/'+design.design.id,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify(designEdit)})));assert.deepEqual(patches.map(r=>r.status).sort(),[200,409]);
const designRead=await request('/api/studio/designs/'+design.design.id);assert.equal(designRead.design.revision,2);assert.equal(designRead.design.parameters.texts.T01.value,'修改后');
assert.equal(designRead.design.postId,design.design.postId,'Updating a page reuses its Wiki post');
const linkedWiki=await request('/api/notes/'+design.design.postId);assert.equal(linkedWiki.entry.title,'更新效果');
assert.equal(linkedWiki.entry.coverAssetId,first.assets[0],'An uploaded page image supplies the initial cover');
const repeated=await Promise.all([1,2].map(()=>request('/api/studio/designs/'+design.design.id+'/post',{})));
assert.ok(repeated.every(r=>r.created===false&&r.design.postId===design.design.postId&&r.design.revision===2));
const manualBody=linkedWiki.entry.editableMarkdown+'\n\n我的补充说明';
assert.equal((await fetch(base+'/api/notes/'+design.design.postId,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({title:'我的页面笔记',description:'独立的笔记说明',markdown:manualBody,tags:[],revision:linkedWiki.entry.revision})})).status,200);
const nextDesign=await fetch(base+'/api/studio/designs/'+design.design.id,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({...designEdit,name:'再改页面名称',revision:2})});assert.equal(nextDesign.status,200);
const retainedWiki=await request('/api/notes/'+design.design.postId);assert.equal(retainedWiki.entry.title,'我的页面笔记');assert.equal(retainedWiki.entry.editableMarkdown,manualBody);
const legacyId=randomUUID();await db().query("INSERT INTO studio_designs(id,layout_id,name,parameters) VALUES($1,'ref-01','旧保存页面',$2)",[legacyId,JSON.stringify({texts:{},images:{},decorations:{}})]);
const repaired=await Promise.all([1,2].map(()=>fetch(base+'/api/studio/designs/'+legacyId+'/post',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'})));
assert.deepEqual(repaired.map(r=>r.status).sort(),[200,201]);const repairs=await Promise.all(repaired.map(r=>r.json()));assert.equal(repairs[0].design.postId,repairs[1].design.postId);assert.equal(repairs[0].design.revision,1);
assert.equal((await db().query("SELECT count(*)::integer AS n FROM posts WHERE slug=$1",['studio-design-'+legacyId])).rows[0].n,1);
assert.equal((await fetch(base+'/api/studio/designs/'+randomUUID()+'/post',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'})).status,404);
// Both families share content validation and revision-guarded, recoverable CRUD.
for(const layoutId of ['standard-01','ref-07']){
const created=(await request('/api/studio/designs',{schemaVersion:1,layoutId,name:'CRUD '+layoutId,parameters:{texts:{T01:{value:'API 标题'}},images:{I01:{assetId:first.assets[0],fit:'cover',cropX:25,zoom:1.5}},added:[{id:'user-caption',kind:'text',role:'补充',box:[1,2,30,10],direction:'horizontal',text:'自定义',reading:'custom'}]}})).design;
assert.equal(created.family,layoutId==='standard-01'?'standard':'fixed');assert.equal(created.schemaVersion,1);
const call=(method:string,body:unknown)=>fetch(base+'/api/studio/designs/'+created.id,{method,headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
assert.equal((await call('PATCH',{name:'新标题',parameters:created.parameters,revision:1})).status,200);
assert.equal((await call('DELETE',{revision:1})).status,409);
const deleted=await call('DELETE',{revision:2});assert.equal(deleted.status,200);assert.equal((await deleted.json()).design.archived,true);
const read=(await request('/api/studio/designs/'+created.id)).design;assert.equal(read.revision,3);assert.deepEqual(read.parameters,created.parameters);
assert.equal((await request('/api/notes/'+created.postId)).entry.archived,true);
assert.ok(!(await request('/api/studio/designs?layoutId='+layoutId)).designs.some((d:{id:string})=>d.id===created.id));
assert.ok((await request('/api/studio/designs?archived=true&layoutId='+layoutId)).designs.some((d:{id:string})=>d.id===created.id));
assert.equal((await call('PATCH',{name:'禁止修改归档',parameters:{},revision:3})).status,409);
assert.equal((await call('POST',{revision:3,archived:false})).status,200);
assert.equal((await request('/api/notes/'+created.postId)).entry.archived,false);
assert.equal((await request('/api/studio/designs/'+created.id)).design.revision,4);
}
assert.equal((await fetch(base+'/api/studio/designs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({schemaVersion:2,layoutId:'standard-01',name:'未来版本',parameters:{}})})).status,400);
// A post failure must roll back the design and text assets as one unit.
const beforeFailure=(await db().query('SELECT (SELECT count(*) FROM studio_designs)::integer AS designs,(SELECT count(*) FROM posts)::integer AS posts,(SELECT count(*) FROM assets)::integer AS assets')).rows[0];
await db().query(`CREATE FUNCTION reject_studio_post_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.title='atomic-studio-post-test' THEN RAISE EXCEPTION 'test publication failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_studio_post_test BEFORE INSERT ON posts FOR EACH ROW EXECUTE FUNCTION reject_studio_post_test()`);
try{assert.equal((await fetch(base+'/api/studio/designs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({layoutId:'ref-01',name:'atomic-studio-post-test',parameters:{}})})).status,500)}finally{await db().query('DROP TRIGGER reject_studio_post_test ON posts; DROP FUNCTION reject_studio_post_test()')}
assert.deepEqual((await db().query('SELECT (SELECT count(*) FROM studio_designs)::integer AS designs,(SELECT count(*) FROM posts)::integer AS posts,(SELECT count(*) FROM assets)::integer AS assets')).rows[0],beforeFailure);
// The migration adopts an existing manual post instead of publishing a duplicate.
const adoptedId=randomUUID(),adoptedUrl='/studio/layouts/ref-01?id='+adoptedId,adoptedPost=await request('/api/posts',{kind:'article',title:'已补录的保存页',slug:'studio-design-'+adoptedId,text:'[打开页面]('+adoptedUrl+')'});
await db().query("INSERT INTO studio_designs(id,layout_id,name,parameters) VALUES($1,'ref-01','已补录的保存页',$2)",[adoptedId,JSON.stringify({texts:{},images:{},decorations:{}})]);
await db().query(await readFile(new URL('../db/010_studio_design_posts.sql',import.meta.url),'utf8'));
const adopted=await request('/api/studio/designs/'+adoptedId);assert.equal(adopted.design.postId,adoptedPost.id);assert.equal((await request('/api/studio/designs/'+adoptedId+'/post',{})).created,false);
const designPage=await request('/api/studio/designs?layoutId=ref-01&limit=1');assert.equal(designPage.designs.length,1);assert.ok(designPage.nextCursor);assert.equal((await request('/api/studio/designs?layoutId=ref-01&limit=1&before='+designPage.nextCursor)).designs.length,1);
for(const body of [{layoutId:'ref-28',name:'bad',parameters:{}},{layoutId:'ref-01',name:'bad',parameters:{texts:{I01:{value:'wrong kind'}}}},{layoutId:'ref-01',name:'bad',parameters:{images:{I01:{assetId:randomUUID()}}}}])assert.equal((await fetch(base+'/api/studio/designs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})).status,400);
assert.equal((await fetch(base+'/api/studio/designs/'+randomUUID())).status,404);
assert.ok((await fetch(base+'/api/studio/designs?agent_mode=True').then(r=>r.text())).includes('revision'));
const published=await publishLearningSeries();await publishLearningSeries();
const articles=(await request('/api/feed?section=articles')).posts;
const articles=(await request('/api/feed?section=articles&path=learning-skills')).posts;
assert.equal(articles.length,3,'Repeated publication must not duplicate posts');
assert.equal(new Set(articles.map((p:{cover_asset_id:string})=>p.cover_asset_id)).size,1,'Three posts share one independent image asset');
assert.equal((await db().query('SELECT count(*)::integer AS n FROM post_assets WHERE asset_id=$1',[published.coverId])).rows[0].n,3);
@@ -187,6 +230,22 @@ test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processi
assert.equal((await patchTags({tags:[],revision:afterTags.revision})).status,200);
const cleared=(await request('/api/notes/'+targetNote.id)).entry;assert.equal(cleared.categories.length,0);assert.equal(cleared.systemTags.length,0);
const categoriesHtml=await fetch(base+'/categories').then(r=>r.text());const tabs=categoriesHtml.match(/aria-label="系统标签分类"[\s\S]*?<\/nav>/)?.[0]||'';assert.ok(tabs.includes('文档入口'));assert.ok(tabs.includes('参考图'));assert.ok(!tabs.includes(plain.name));
// Archive is a reversible visibility change, including code-backed public IDs.
const archiveTarget=(await request('/api/notes/'+publishedNote.publicId)).entry;
const archive=(value:boolean)=>fetch(base+'/api/posts/'+publishedNote.publicId+'/archive',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({archived:value})});
const archivedResponse=await archive(true);assert.equal(archivedResponse.status,200);const archived=(await archivedResponse.json()).post;assert.equal(archived.archived,true);assert.ok(archived.archivedAt);
assert.equal((await (await archive(true)).json()).post.archivedAt,archived.archivedAt,'Repeated archive preserves the archive timestamp');
const archivedEntry=(await request('/api/notes/'+publishedNote.publicId)).entry;assert.equal(archivedEntry.archived,true);assert.equal(archivedEntry.editableMarkdown,archiveTarget.editableMarkdown);assert.deepEqual(archivedEntry.assets,archiveTarget.assets);assert.notEqual(archivedEntry.revision,archiveTarget.revision);
assert.ok(!(await request('/api/explore-feed?q='+encodeURIComponent(archiveTarget.title))).entries.some((e:{id:string})=>e.id===publishedNote.publicId),'Archived database note must not reappear from its static predecessor');
assert.ok(!(await request('/api/feed?q='+encodeURIComponent(archiveTarget.title))).posts.some((p:{id:string})=>p.id===publishedNote.id));
assert.ok((await request('/api/feed?archived=true&q='+encodeURIComponent(archiveTarget.title))).posts.some((p:{id:string})=>p.id===publishedNote.id));
assert.ok(!(await fetch(base+'/api/wiki-index').then(r=>r.text())).includes('['+archiveTarget.title+']'));
assert.equal((await fetch(base+'/explore/'+publishedNote.publicId)).status,200,'Direct archived links remain readable for recovery');
const restored=await archive(false);assert.equal(restored.status,200);assert.equal((await restored.json()).post.archived,false);
assert.ok((await request('/api/explore-feed?q='+encodeURIComponent(archiveTarget.title))).entries.some((e:{id:string})=>e.id===publishedNote.publicId));
assert.equal((await fetch(base+'/api/feed?archived=invalid')).status,400);
assert.equal((await fetch(base+'/api/posts/'+randomUUID()+'/archive',{method:'POST',headers:{'Content-Type':'application/json'},body:'{"archived":true}'})).status,404);
}finally{
for(const child of [worker,server])if(child&&child.exitCode===null&&child.signalCode===null){const stopped=once(child,'exit');child.kill('SIGTERM');await stopped;}
await rm(dir,{recursive:true,force:true});await db().end();
+11
View File
@@ -0,0 +1,11 @@
# Studio 固定构图视觉审查
2026-10-28:先搜索互联网设计 skills,再检查源文件。采用 [Anthropic frontend-design 原始 SKILL.md](https://github.com/anthropics/claude-code/blob/main/plugins/frontend-design/skills/frontend-design/SKILL.md) 中与本任务适用的字体层级、基于内容选择配色、保留构图个性及逐版审视方法;不采用其自由重构产品布局的方向,因为本任务要求保留27套构图及现有工具箱。只阅读说明,没有安装依赖或执行第三方代码。
搜索结果中的第三方技能聚合页只用于发现,不作为实现依据。另检查了 Impeccable 候选源路径,但该路径返回404,未读取到可信内容,因此不采用,也不声称安装或使用了该技能。
实现把每套构图的纸色、文字、主图位、副图位组织成独立四色色谱。蓝灰用于横向英文刊头,暖赭用于出血椭圆与斜题,苔绿用于竖题与同心圆;没有把构图改为统一卡片。竖向中文使用宋体栈,英文大刊头保留衬线,模块式构图加强字重与字距,小字替换成适合槽位的简短可编辑内容。原始画板、元素ID、裁切轮廓与主要坐标保持不变。
可视化目录用原生文字和几何展示构图,页面本身继续由现有 LayoutWorkbench 原生渲染。颜色、字体和几何显式参数优先于模板默认值;模板默认外观会跟随版本美化,要求固定外观的调用者应传入显式参数。
验收应在部署完成后仅访问指定服务器,检查27套页面、移动宽度、保存ID恢复、字体/几何扩展、图片网络请求,以及旧工具功能。原生页面不能以旧SVG导出代替视觉验收。
+156 -127
View File
@@ -1,131 +1,160 @@
# 27 套排版 · Studio 参数 API 与保存教程
# Studio 排版 API · 标准图文与 27 套固定构图
把这篇 post 交给 agent,即可选排版、预览、调整参数并保存可再次打开的效果。每套 ref-01…ref-27 都有独立页面,与原图的 T(文字)、I(图位)、D(装饰)构件对应。
把本篇与图片生成文档一起交给 coding agent。agent 自行选择图片、配色、字体、构图与参数,通过 HTTP 保存渲染描述,得到可持续更新的原生 HTML/CSS 页面。数据库只保存模板关联、文字、素材引用和渲染参数,不保存截图或任意 HTML。
## 先看效果,再通过 API 调整
[可选:查看模板示例](/studio) · [读取实时 API 契约](/api/studio/designs?agent_mode=True) · [照片入皮影](/explore/3c98946754c33309d73d5284) · [街头小人](/explore/4ce3283fd98bb03a8fb39a19)
## agent 的交付流程
1. 按下文读取模板 API,选择 layoutId,并获取该模板实际的 T/I/D 元素 ID。
2. 上传图片取得 assetId,把图片、文字和参数提交给创建 API。
3. 从创建响应读取 `design.id` 与 `design.url`,把完整结果链接交给用户,例如 `http://8.211.154.134:18131/studio/template-layout?id=实际返回的UUID`。
4. 用户直接打开该链接看结果;修改内容继续调用 PATCH,同一 ID 与结果链接保持不变。
不要编造 ID,也不要把模板预览链接当作最终结果。API 保存成功并返回真实 UUID 才算完成。以下文档足以通过 HTTP 完成流程,无需使用编辑器。
## 两类排版,同一内容模型
- **标准排版**:`standard-01`,120×160 单位。沿用原 Studio 图文页的标题、正文、栏目结构,增加主题图片与分隔线。T01 主标题、T02 正文、T03 栏目、I01 图片、D01 分隔线。所有内容和位置可设置,也能增加原生元素。
- **固定排版**:`ref-01` 至 `ref-27`,保留各自画板、出血、圆形、斜切、竖题和字体构图。先读取模板,按实际 T/I/D ID 填入内容。不能假定各模板拥有相同元素。
两类都使用 `/api/studio/designs` 的真实 CRUD。创建额外指定 layoutId;更新从 URL 确定 ID,模板关联不能修改。更换模板应创建新记录,避免把旧元素 ID 错套到新模板。调用方无需打开 `/studio` 或操作编辑器。模板由 agent 经 API 选择,图片和文字由 API 保存,用户只打开结果链接。现有独立工具箱功能保持可用。
## 1. 由 agent 通过 API 发现模板
以下 curl 使用指定服务器。`PROMPT_TOKEN` 由用户通过现有登录方式提供,只保存在进程环境,不放 URL 或日志。也可使用已登录浏览器的同源 Cookie;浏览器写请求需要同源 Origin。未登录 API 返回 401。
```sh
BASE=http://8.211.154.134:18131
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" "$BASE/studio/api/layouts"
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" "$BASE/studio/api/layouts/standard-01"
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" "$BASE/studio/api/layouts/ref-17"
```
目录返回 `version, layouts, saveApi, catalogUrl, documentationUrl`。每项包含 `id,name,family,url,api`,family 为 standard/fixed。模板返回尺寸、元素 ID/类型/role/box/direction/text、默认 parameters、workspaceSchema 与页面 URL。`?agent_mode=True` 返回纯文本文档,业务请求移除此参数。
## 2. 生成图片,上传一次,显示压缩衍生图
先让 coding agent 按生成图片文档产出文件;Studio 不暗中调用生成模型。图片可以来自用户素材或生成结果。上传走现有素材 API:
```sh
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" \
-F kind=image -F assetOnly=true -F files=@hero.png "$BASE/api/upload"
```
返回 `assets` UUID 数组及对应 `files` 元数据。取 `assets[0]` 作为 assetId。上传不单独发帖;设计创建时才自动关联 Wiki post。不要把 Base64、任意远程 URL、HTML 或 SVG 塞入参数。
原素材保留在素材库,**页面展示只请求压缩 WebP**。以 assetId 引用素材,不必自行再上传缩略图:
```sh
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" \
"$BASE/api/preview?source=%2Fapi%2Fmedia%2FASSET_UUID&width=960" -o hero-preview.webp
```
width 只允许 240/480/960/1280;小图预算 100KB,大图预算 220KB,复杂图片会降低尺寸/质量。原生页面按槽位显示宽度和像素密度选择 srcset 衍生图,保留 fit/cropX/cropY/zoom。目录使用原生文字与 CSS 色块,不加载参考原图;旧工具箱参考图也使用压缩预览。`/api/media/{id}` 是素材原件读取接口,不应用作展示图片的 src。
## 3. 创建:POST /api/studio/designs
创建和更新共用内容字段 `name,parameters`;`schemaVersion` 可省略,当前仅支持 1。创建额外传 `layoutId`,不传 revision 或 id。
```sh
curl -fsS -X POST "$BASE/api/studio/designs" \
-H "Authorization: Bearer $PROMPT_TOKEN" -H 'Content-Type: application/json' \
-d '{"schemaVersion":1,"layoutId":"standard-01","name":"观察日常","parameters":{"paper":"#edf0ef","texts":{"T01":{"value":"观察日常\n记录灵感","fontFamily":"serif","color":"#23424b"},"T02":{"value":"让每一页只讲一件事。","lineHeight":1.4}},"images":{"I01":{"color":"#73929a","fit":"cover","cropX":50,"cropY":45,"zoom":1}},"decorations":{"D01":{"color":"#73929a"}}}}'
```
有图片时在 I01 加 `assetId:"上传返回的UUID"`。固定排版只需改为所选 `layoutId`,并按 schema 选择元素 ID。例如 ref-01 支持 `texts.T01`、`texts.T02` 与 `images.I01`。
201 返回 `{design}`。design 包含:
| 字段 | 含义 |
| --- | --- |
| id / layoutId / family | 持久化 UUID、不可变模板 ID、standard 或 fixed |
| schemaVersion / revision | 参数契约版本(1)、记录修订号(从1递增) |
| name / parameters | 名称与规范化内容;省略的分组返回空对象 |
| url / renderUrl | 同一个原生 HTML/CSS 页面 URL |
| schemaUrl | 当前模板参数地址 |
| postId / postUrl | 自动创建并在后续更新中复用的 Wiki post |
| archived / archivedAt | 可恢复归档状态与时间 |
| createdAt / updatedAt | 创建与最后修改时间 |
| legacySvgUrl | 固定排版的旧 SVG 导出地址,标准排版为 null |
创建设计与 Wiki post 在同一数据库事务内完成,失败整体回滚。更新同一设计复用同一 post;手工编辑过的 Wiki 正文、标题、标签、封面不会被参数更新覆盖。
## 4. 读取与打开
```sh
ID=创建返回的UUID
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" "$BASE/api/studio/designs/$ID"
curl -fsS -H "Authorization: Bearer $PROMPT_TOKEN" "$BASE/api/studio/designs?layoutId=standard-01&limit=20"
```
读取返回 `{design}`,没有副作用。列表默认只列未归档记录;`archived=true` 只列归档记录;limit 为1–50,默认20;`nextCursor` 作为下一页 before。layoutId 可省略。
直接打开创建响应中的 `design.url`:`/studio/template-layout?id={UUID}`。这个 UUID 对应数据库里 API 保存的模板、图片与文字,服务端按记录渲染最终 HTML/CSS。链接中无需携带 layoutId,无需打开 `/studio` 选择模板,也没有编辑按钮、双击编辑或右键编辑。`standard-01` 与 `ref-17` 是模板 ID,不是保存记录的 UUID。
`/studio/designs/{UUID}` 与旧 `/studio/layouts/{layoutId}?id={UUID}` 兼容跳转到同一个结果页。缺失、非法、不存在或已归档的 ID 返回404,不会显示空模板或编辑器;旧链接模板与记录不匹配也返回404。归档设计仍能经 API 读取以恢复。
## 5. 更新:PATCH /api/studio/designs/{id}
先 GET,保留所有未改字段,再整体替换 parameters;不是深度合并。以下假设刚读到 revision=1:
```sh
curl -fsS -X PATCH "$BASE/api/studio/designs/$ID" \
-H "Authorization: Bearer $PROMPT_TOKEN" -H 'Content-Type: application/json' \
-d '{"name":"观察日常 · 修订","revision":1,"parameters":{"texts":{"T01":{"value":"新的标题"}},"images":{},"decorations":{}}}'
```
200 返回新 design,revision 增加。过期 revision 返回409,重新 GET 并合并后再提交;不要盲目重试。不接受 layoutId、id、url、postId 等返回字段;不能直接把整个 design 作为 body。另存副本使用 POST 创建新 UUID。
## 6. 删除与恢复
DELETE 采用可恢复归档,不物理删除参数、素材或 Wiki post。和更新一样必须提供最新 revision;自动同步关联 post 的归档状态。
```sh
curl -fsS -X DELETE "$BASE/api/studio/designs/$ID" \
-H "Authorization: Bearer $PROMPT_TOKEN" -H 'Content-Type: application/json' -d '{"revision":2}'
# 删除后读取新 revision,再恢复。此例删除后为3:
curl -fsS -X POST "$BASE/api/studio/designs/$ID" \
-H "Authorization: Bearer $PROMPT_TOKEN" -H 'Content-Type: application/json' -d '{"revision":3,"archived":false}'
```
两者200返回 `{design}`,revision 递增。归档记录 PATCH 返回409,先恢复。重复写入仍需最新 revision;409不会修改数据。独立归档 Wiki post 只影响笔记发现状态,不等于删除设计。旧设计缺 Wiki 入口可调用 `POST /api/studio/designs/{id}/post`,body `{}`,首次201、已有200;不改变 revision。
## 参数清单(两类共用)
parameters 顶层允许 texts/images/decorations/paper/layers/added;全部可省略,不能添加未知字段。最大请求64KB。颜色都为 `#RRGGBB`。坐标与字号使用模板单位,不是 CSS 像素。
| 分组 | 字段与约束 |
| --- | --- |
| texts.{文字ID} | value 必填,可空,最多500字/8行;color;scale 0.25–2;align start/middle/end;fontFamily sans/serif/mono;fontSize 0.1–1000;fontWeight 100–900;lineHeight 0.5–4;letterSpacing -20–100 |
| images.{图片ID} | assetId(已存在的图片 UUID);color;fit cover/contain;cropX/cropY 0–100(默认50);zoom 1–5(默认1) |
| decorations.{装饰ID} | color;hidden 布尔值 |
| paper | 纸张颜色 |
| 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 布尔值 |
| added | 最多100项:id 为 user- 加1–60位字母/数字/连字符,唯一;kind text/image/decoration;role 最多80字;box 为 [x,y,width,height];direction 必须 horizontal;text 为文字或null;reading 必须 custom;装饰可带 shape rectangle/ellipse |
新增元素先在 added 声明,然后在 texts/images/decorations/layers 用该 ID 配置。locked 控制工作区交互,不禁止 agent 更新。数据是封闭结构,无脚本执行。未来扩展新增契约版本;v1 不接受未知字段/版本。现有省略 schemaVersion 的请求继续按v1处理,旧记录无需重建,布局 ID 和页面 UUID 保持不变。默认视觉可随模板美化变化;要求固定外观时显式设置配色、字体和图层参数。
错误:400 参数/版本/构件类型/图片 ID 不合法;401 未登录;404 模板或设计不存在;409 修订冲突或已归档;405 方法不支持;413 请求超限;500 服务失败。压缩预览失败可能返回503与 Retry-After。
## 现有工具箱与兼容导出
工具功能保留:[ref-17 同一母版四张试版](/studio/ideas/learning-skills-template)、[ref-01/07/26 三种构图试版](/studio/ideas/layout-selection)、[最初图文页](/studio/ideas/first-idea)。旧封面工具文档已合并到本篇,旧文档 URL 保留为归档说明,避免重复顶级入口。
旧无状态 API:`/studio/api/export/learning-skills-template` 和 `/studio/api/export/layout-selection` 支持 GET/POST,不保存设计。前者参数 slide=0..3、heading(1–6字)、body(最多360字/3行)、color/accent、masthead(2项);后者 layoutId=ref-01/ref-07/ref-26、fields(对应T ID,1–120字/4行)、color/accent。GET 默认返回方案 JSON;GET format=svg 导出初始图;POST format=svg(默认)导出 SVG,format=json 返回参数,最大32KB。first-idea 仅支持 GET 方案/Markdown。
```sh
curl -fsS -X POST "$BASE/studio/api/export/learning-skills-template?format=svg" \
-H "Authorization: Bearer $PROMPT_TOKEN" -H 'Content-Type: application/json' \
-d '{"slide":1,"heading":"笔记复习","color":"#7a8b7e"}' -o cover.svg
curl -fsS -X POST "$BASE/studio/api/export/layout-selection?format=svg" \
-H "Authorization: Bearer $PROMPT_TOKEN" -H 'Content-Type: application/json' \
-d '{"layoutId":"ref-01","fields":{"T01":"STUDY"},"color":"#83918a"}' -o selection.svg
```
固定排版 `/studio/api/layouts/ref-01` 的 GET format=svg、POST 仍提供旧分层 SVG;POST format=json 只验证和返回规范化参数。**旧 SVG 不反映 added、layers、扩展字体和裁切参数**,不能用来证明原生效果。standard-01 不支持 SVG。原生页面应直接打开返回 URL,或用浏览器打印。代码可扩展渲染能力,但每次是否使用、选择哪些参数均由 coding agent 决定。
## 固定排版索引
{{LAYOUTS}}
以上页面都可以修改文字、图位颜色或图片、装饰颜色和显隐、纸色,也能输入完整参数 JSON。打开“显示 T/I/D 构件边界”核对位置;“原图与构件对应表”可查看原图及坐标。页面下方可找到已保存的此排版效果。
## Agent 调用顺序
1. 读取 [全部 27 套排版目录与接口](/studio/api/layouts?agent_mode=True),选择 ID。
2. GET `/studio/api/layouts/ref-01` 获取当前模板的真实构件 ID、坐标、方向与可辨识文字。也可以先读 [渲染接口说明](/studio/api/layouts/ref-01?agent_mode=True)。不要把其他模板的 T/I/D ID 混用。
3. POST 同地址传入参数,得到 SVG。渲染不会自动保存;迭代参数直到效果合适。
4. POST `/api/studio/designs` 保存新效果,返回 `design.id`、`design.url` 与 `design.revision`。通过 `design.url` 可直接看效果。
5. GET `/api/studio/designs/{id}` 读取上次参数;PATCH 同地址携带 revision 更新同一 ID。要保留两个不同版本,使用 POST 保存两个新 ID。
所有 API 与 Wiki 共用现有登录 Cookie 或 Bearer JWT。浏览器修改请求必须同源。Studio 本身不配置数据库连接,保存由 Wiki 写入同一个 PostgreSQL。
## 参数示例:ref-01
```json
{
"texts": {
"T01": {"value": "STUDY", "color": "#26362f", "scale": 1, "align": "start"},
"T02": {"value": "知识合集\n从记录到创作"}
},
"images": {
"I01": {"color": "#7f9188"},
"I02": {"color": "#b7c4bb"}
},
"decorations": {"D01": {"color": "#53645b", "hidden": false}},
"paper": "#f4f2eb"
}
```
文字最多 500 字、8 行,scale 范围 0.25–2,align 为 start/middle/end。文字 value 为空则移除这一组;删除其参数键则恢复原图字形。图片可以只改色,也可先通过 `/api/upload` 的 `assetOnly=true` 上传,再传入 `assetId` UUID 与 `fit: cover/contain`;不接受任意图片网址。装饰支持颜色与 hidden。参数在画板内裁切,未知字段、错误构件 ID、非法颜色和超限输入返回 400。请求最大 64KB。
原始参考来自低分辨率拼图。默认效果保留原图;未替换的构件继续使用原始分层,图位使用原始形状蒙版。可替换文字生成 SVG 文字;无法辨识的小字标为 unreadable,保留原图层而不编造文字。纸色作用于原有底层,不替代图位色块。页面预览通过同站媒体读取图片;API 导出时会使用当前登录读取 Wiki 有尺寸上限的 WebP 预览,并内嵌到 SVG,使下载结果不依赖外部图片链接。原始大图仍保留在 Wiki,导出使用最长 960 像素的预览。
## HTML / JavaScript:渲染与保存
```html
<div id="preview"></div>
<script type="module">
const layoutId = 'ref-01';
const parameters = {texts:{T01:{value:'STUDY'}},images:{I01:{color:'#7f9188'}}};
const response = await fetch(`/studio/api/layouts/${layoutId}`, {
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(parameters)
});
if (!response.ok) throw new Error(await response.text());
const previewUrl = URL.createObjectURL(await response.blob());
const image = new Image(); image.src = previewUrl;
document.querySelector('#preview').replaceChildren(image);
// 预览完成后可 URL.revokeObjectURL(previewUrl)。
const saved = await fetch('/api/studio/designs', {
method:'POST', headers:{'Content-Type':'application/json'},
body:JSON.stringify({layoutId,name:'知识合集第一版',parameters})
});
if (!saved.ok) throw new Error(await saved.text());
const {design} = await saved.json();
console.log(design.id, design.url, design.revision);
</script>
```
## React:参数变化重新预览
```tsx
import {useEffect,useState} from 'react';
export function Preview(){
const [title,setTitle]=useState('STUDY'),[src,setSrc]=useState(''),[error,setError]=useState('');
useEffect(()=>{
const controller=new AbortController();let url='';
fetch('/studio/api/layouts/ref-01',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({texts:{T01:{value:title}}}),signal:controller.signal})
.then(async r=>{if(!r.ok)throw Error(await r.text());return r.blob()})
.then(blob=>{if(!controller.signal.aborted){url=URL.createObjectURL(blob);setSrc(url);setError('')}})
.catch(e=>{if(!controller.signal.aborted)setError(e.message)});
return()=>{controller.abort();if(url)URL.revokeObjectURL(url)};
},[title]);
return <><input value={title} onChange={e=>setTitle(e.target.value)}/>{error&&<p>{error}</p>}{src&&<img src={src} alt="当前排版效果"/>}</>;
}
```
## Next.js:客户端编辑组件
```tsx
// app/layout-playground/page.tsx
'use client';
import {useState} from 'react';
export default function Playground(){
const [title,setTitle]=useState('STUDY'),[link,setLink]=useState(''),[status,setStatus]=useState('');
async function save(){
const response=await fetch('/api/studio/designs',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({layoutId:'ref-01',name:title||'排版效果',parameters:{texts:{T01:{value:title}}}})});
const data=await response.json();if(!response.ok){setStatus(data.error);return}setLink(data.design.url);setStatus('已保存');
}
return <><input value={title} onChange={e=>setTitle(e.target.value)}/><button onClick={save}>保存新效果</button><p>{status}</p>{link&&<a href={link}>打开效果</a>}</>;
}
```
这些前端示例应放在已登录的 PROMPT 同站环境。服务端 agent 使用既有 Bearer JWT,只在进程内读取凭据,勿把令牌写入 post、源码、日志或 URL。接口错误不可当作渲染结果处理。
## 按 ID 读取、修改、保留分支
```js
const headers = {'Content-Type':'application/json'};
const read = await fetch(`/api/studio/designs/${id}`);
if (!read.ok) throw Error(await read.text());
const {design} = await read.json();
const parameters = {...design.parameters,texts:{...design.parameters.texts,T01:{value:'第二版'}}};
const update = await fetch(`/api/studio/designs/${id}`, {
method:'PATCH',headers,
body:JSON.stringify({name:'知识合集第二版',parameters,revision:design.revision})
});
if (update.status===409) throw Error('有人已经修改,请重新读取后合并');
if (!update.ok) throw Error(await update.text());
// 想保留旧版时,改用 POST /api/studio/designs,传 {layoutId:design.layoutId,name,parameters}。
```
PATCH 的 parameters 整体替换,因此先 GET 并合并未修改的构件;layoutId 不可改变。错误:400 参数不合法、401 未登录、404 不存在、409 修订冲突、413 超限。[效果保存接口说明](/api/studio/designs?agent_mode=True)。列表可用 `layoutId` 筛选、`limit=1..50`;返回 nextCursor 后用 `before=<nextCursor>` 继续。
## 验收标准
- 27 个 ID 都有独立效果页、参数说明与渲染 API,来源链接与 T/I/D 构件一一对应。
- 默认效果展示原图;替换一组文字、一个图位或装饰后,只改变指定构件。
- API 渲染与界面使用相同模板、验证和渲染器;导出的 SVG 不包含辅助边界。
- 保存返回独立 UUID,刷新或再次访问效果 URL 能恢复参数;更新后 revision 增加,过期修订返回 409。
- 图片 assetId 必须是 Wiki 中已上传的图片;不接受未知构件或外站 URL。
- Wiki 与 Studio 共用现有登录和数据库,Studio 无独立持久化或数据库凭据。
+38
View File
@@ -0,0 +1,38 @@
/** Precise layout authorized by the user; all photographic/puppet/paper content comes from original photos or imagegen. */
import {createRequire} from 'node:module';
import {writeFile} from 'node:fs/promises';
import {resolve,join} from 'node:path';
const require=createRequire(new URL('../apps/waterfall-wiki/package.json',import.meta.url)),sharp=require('sharp');
const root=resolve(process.argv[2]||'../output/shadow-puppet-covers'),W=1536,H=2048,HALF=1024;
const specs=[
{key:'lotus',draft:'lotus-shadow-puppet.png',seam:724},
{key:'pavilion',draft:'pavilion-shadow-puppet.png',seam:727},
{key:'crane',draft:'crane-draft.png',seam:648,cutoutHeight:880},
{key:'lion',draft:'lion-draft.png',seam:724,cutoutHeight:880,generatedPhoto:true},
{key:'peach',draft:'peach-draft.png',seam:645,cutoutHeight:900}
];
const checks=[];
for(const spec of specs){
const path=join(root,spec.draft),meta=await sharp(path).metadata();let lower;
if(spec.cutoutHeight){
const cutout=join(root,spec.key+'-cutout.png'),alpha=await sharp(cutout).stats();
if(!alpha.channels[3]||alpha.channels[3].min!==0)throw Error('Cutout lacks real transparent background: '+spec.key);
const resizedSubject=await sharp(cutout).trim({background:'#00000000',threshold:1}).resize({width:1050,height:spec.cutoutHeight,fit:'inside'}).png().toBuffer();
const sized=await sharp(resizedSubject).metadata();
// Control rods continue beyond the frame rather than terminating on the paper.
const subject=await sharp(resizedSubject).extract({left:0,top:0,width:sized.width,height:sized.height-36}).png().toBuffer();
const subjectInfo=await sharp(subject).metadata();
const paper=await sharp(join(root,'paper-stage.png')).resize(W,HALF,{fit:'cover'}).png().toBuffer();
lower=await sharp(paper).composite([{input:subject,left:Math.round((W-subjectInfo.width)/2),top:HALF-subjectInfo.height}]).png().toBuffer();
}else{
lower=await sharp(path).extract({left:0,top:spec.seam,width:meta.width,height:meta.height-spec.seam}).resize(W,HALF,{fit:'cover'}).png().toBuffer();
}
const upper=spec.generatedPhoto?await sharp(path).extract({left:0,top:0,width:meta.width,height:spec.seam}).resize(W,HALF,{fit:'cover'}).png().toBuffer():await sharp(join(root,'sources',spec.key+'.jpg')).resize(W,HALF,{fit:'cover',position:'centre'}).png().toBuffer();
const output=join(root,spec.key+'-cover.png');
const composed=await sharp({create:{width:W,height:H,channels:3,background:'#f3d39c'}}).composite([{input:upper,left:0,top:0},{input:lower,left:0,top:HALF}]).png().toBuffer();
await sharp(composed).flatten({background:'#f3d39c'}).removeAlpha().png().toFile(output);
const final=await sharp(output).metadata();if(final.width*4!==final.height*3||final.height%2||final.hasAlpha)throw Error('Invalid cover geometry: '+spec.key);
checks.push({key:spec.key,path:output,width:final.width,height:final.height,photographRows:[0,HALF-1],puppetRows:[HALF,H-1],sourcePanelSeam:spec.seam,sourcePhoto:spec.generatedPhoto?'imagegen photographic outpaint of original':'original photograph',cutout:!!spec.cutoutHeight});
}
await writeFile(join(root,'layout-checks.json'),JSON.stringify(checks,null,2));
console.log(JSON.stringify({covers:checks.length,width:W,height:H,seam:HALF,checks:'exact 3:4, equal halves, opaque'}));
+46
View File
@@ -0,0 +1,46 @@
/** Run with the production auth CLI after staging reviewed covers and manifest. Never stores auth tokens. */
import {readFile,writeFile} from 'node:fs/promises';
import {join,resolve} from 'node:path';
import {createHash} from 'node:crypto';
const root=resolve(process.env.SHADOW_COVERS_DIR||'/tmp/shadow-covers');
const base=process.env.AUTH_CHECK_BASE_URL||'http://127.0.0.1:3000';
const manifest=JSON.parse(await readFile(join(root,'manifest.json'),'utf8'));
const backup=JSON.parse(await readFile(join(root,'notes-before.json'),'utf8'));
let state;try{state=JSON.parse(await readFile(join(root,'publication.json'),'utf8'))}catch{state={covers:{},archived:[],beforeArchive:[]}}
const persist=()=>writeFile(join(root,'publication.json'),JSON.stringify(state,null,2));
async function api(path,body,method=body?'POST':'GET'){const r=await fetch(base+path,{method,...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const data=await r.json();if(!r.ok)throw Error(path+' '+r.status+' '+JSON.stringify(data));return data}
async function upload(key,file){if(state.covers[key]?.assetId)return state.covers[key].assetId;const bytes=await readFile(join(root,file)),form=new FormData();form.set('kind','image');form.set('assetOnly','true');form.set('files',new Blob([bytes],{type:'image/png'}),file);const r=await fetch(base+'/api/upload',{method:'POST',body:form});const data=await r.json();if(!r.ok)throw Error('Upload '+r.status+JSON.stringify(data));state.covers[key]={assetId:data.assets[0],sha256:createHash('sha256').update(bytes).digest('hex')};await persist();return data.assets[0]}
for(const item of manifest){
const assetId=await upload(item.key,item.outputFile),{entry:e,tags}=await api('/api/notes/'+item.postId);
const marker='<!-- shadow-cover-2026-10-27:'+item.key+' -->';
if(e.coverAssetId!==assetId){
const ids=[...(e.systemTags||[]).map(t=>t.id),...e.categories.map(name=>{const t=tags.find(t=>t.kind==='normal'&&t.name===name);if(!t)throw Error('Missing tag '+name);return t.id})];
const attribution=`\n\n${marker}\n## 本篇封面:照片入皮影\n\n摄影/馆藏来源:[原始照片](${item.source});作者:${item.author}。\n\n封面图许可:[${item.license}](${item.licenseUrl})(仅适用于本封面及其改编,不改变正文原有许可)。照片经裁切,皮影由 AI 根据原照生成;上下分区经代码精确排版为 1:1。${item.key==='lion'?'上半部亦使用 AI 对原照扩图。':''}\n`;
const markdown=e.editableMarkdown.includes(marker)?e.editableMarkdown:e.editableMarkdown+attribution;
const assets=(e.assets||[]).map(({id,role})=>({id,role}));
if(!e.postSlug){
// Retain the original skill's two style examples, already stored by its companion notes.
assets.push({id:'102a1975-5343-4da9-91aa-c6914db50d5e',role:'content'},{id:'0a7a631d-0a4a-4a66-bae9-71d824469c50',role:'content'});
}
if(!assets.some(a=>a.id===assetId))assets.push({id:assetId,role:'content'});
const input={title:e.title,description:e.description,tags:[...new Set(ids)],assets,coverAssetId:assetId};
if(e.postSlug)await api('/api/notes/'+e.id,{...input,markdown,revision:e.revision},'PUT');
else await api('/api/posts',{...input,kind:'article',publicId:e.id,slug:'guide-shadow-puppet',text:markdown});
}
const after=(await api('/api/notes/'+e.id)).entry;if(after.coverAssetId!==assetId)throw Error('Cover mismatch');
const media=await fetch(base+'/api/media/'+assetId);if(!media.ok||createHash('sha256').update(Buffer.from(await media.arrayBuffer())).digest('hex')!==state.covers[item.key].sha256)throw Error('Media checksum mismatch');
state.covers[item.key].postId=e.id;state.covers[item.key].verified=true;await persist();console.log(JSON.stringify({cover:item.key,postId:e.id,verified:true}));
}
if(backup.oldRefs.length!==27)throw Error('Expected exact 27-entry archive allowlist');
for(const item of backup.oldRefs){
const e=(await api('/api/notes/'+item.id)).entry;
if(e.title!==item.title||!/^ref-(0[1-9]|1[0-9]|2[0-7]) · /.test(e.title)||!e.postSlug)throw Error('Archive allowlist mismatch '+item.id);
if(!state.beforeArchive.some(n=>n.id===e.id)){state.beforeArchive.push(e);await persist()}
await api('/api/posts/'+item.id+'/archive',{archived:true});
const after=(await api('/api/notes/'+item.id)).entry;
if(!after.archived||after.editableMarkdown!==e.editableMarkdown||JSON.stringify(after.assets)!==JSON.stringify(e.assets))throw Error('Archive preservation failed');
if(!state.archived.includes(e.id))state.archived.push(e.id);await persist();
}
for(const category of ['照片入皮影','高级感排版']){let cursor=null,entries=[];do{const d=await api('/api/explore-feed?category='+encodeURIComponent(category)+(cursor?'&cursor='+encodeURIComponent(cursor):''));entries.push(...d.entries);cursor=d.nextCursor}while(cursor);if(category==='照片入皮影'&&!manifest.every(m=>entries.some(e=>e.id===m.postId)))throw Error('Missing cover post');if(entries.some(e=>state.archived.includes(e.id)))throw Error('Archived article still discoverable');state[category]=entries.map(e=>({id:e.id,title:e.title}));}
const saved=(await api('/api/notes/38a7a8ea-6b3b-46fd-902f-431d2f351cf4')).entry;if(saved.archived)throw Error('User design incorrectly archived');
state.completedAt=new Date().toISOString();await persist();console.log(JSON.stringify({covers:manifest.length,archived:state.archived.length,userDesignPreserved:true}));
+39
View File
@@ -0,0 +1,39 @@
/** Execute via production auth-cli run; token stays in memory. Uses only the designated origin. */
import {readFile,writeFile,mkdir} from 'node:fs/promises';
const base=process.env.AUTH_CHECK_BASE_URL||'http://8.211.154.134:18131';
if(base!=='http://8.211.154.134:18131')throw Error('Use the designated acceptance origin');
const dir=process.env.STUDIO_LIBRARY_DIR||'/tmp/studio-library';
await mkdir(dir,{recursive:true});
async function api(path,body,method=body?'POST':'GET'){
const response=await fetch(base+path,{method,...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});
if(!response.ok)throw Error(path+' status '+response.status);
return response.json();
}
const canonical='8eb8c76500580f7a4b56ba3c',legacy='9ebd8f78d54b4b9db741b4e8';
const {entry:current,tags}=await api('/api/notes/'+canonical),{entry:old}=await api('/api/notes/'+legacy);
// Snapshot only non-secret editorial state. Retain the first backup across repeat publication.
for(const [id,entry] of [[canonical,current],[legacy,old]]){try{await readFile(dir+'/'+id+'-before.json')}catch{await writeFile(dir+'/'+id+'-before.json',JSON.stringify(entry),{mode:0o600})}}
const catalogue=await api('/studio/api/layouts');
let markdown=(await readFile(new URL('../content/studio-tools/layouts-api.md',import.meta.url),'utf8')).replace('{{LAYOUTS}}',catalogue.layouts.filter(l=>l.family==='fixed').map(l=>`- [${l.id} · ${l.name}](${l.url}) · [参数](${l.api})`).join('\n'));
const appendixMarker='## 兼容工具原说明与代码示例';
const historicalNotice='> 以下保留历史工具示例,不代表当前 API 保存与打开流程。历史文字中关于首页、编辑器和旧结果地址的描述已过时:当前由 API 创建 ID,直接打开 `/studio/template-layout?id={UUID}`,无需选版或编辑器。当前契约以上文为准。';
if(current.editableMarkdown.includes(appendixMarker)){
const appendix=current.editableMarkdown.slice(current.editableMarkdown.indexOf(appendixMarker));
markdown+='\n\n'+(appendix.includes(historicalNotice)?appendix:appendix.replace(appendixMarker,appendixMarker+'\n\n'+historicalNotice));
}else{
if(old.archived)throw Error('Original toolbox appendix is missing; refusing to replace it with the archived redirect');
const legacyOriginal=JSON.parse(await readFile(dir+'/'+legacy+'-before.json','utf8')).editableMarkdown;
markdown+='\n\n'+appendixMarker+'\n\n'+historicalNotice+'\n\n以下保留原工具的说明与 HTML/React/Next.js 调用示例;它们是无状态兼容接口,持久化页面请使用上文 CRUD。\n\n'+legacyOriginal;
}
const tagIds=entry=>[...new Set([...(entry.systemTags||[]).map(t=>t.id),...entry.categories.map(name=>tags.find(t=>t.name===name)?.id).filter(Boolean)])];
const body=(entry,text,title=entry.title)=>({title,description:entry.description,markdown:text,tags:tagIds(entry),assets:entry.assets,coverAssetId:entry.coverAssetId,revision:entry.revision});
await api('/api/notes/'+canonical,{...body(current,markdown,'Studio 排版 API · 标准图文与27套固定构图'),description:'coding agent 经 HTTP 选择标准图文或27套固定构图,上传压缩展示素材,创建、读取、更新、归档与恢复稳定 ID 原生页面;含兼容工具箱。'},'PUT');
const redirectText=`# Studio 文档已合并\n\n[前往 Studio 排版 API 统一入口](/explore/${canonical})\n\n[可视化 API 库](/studio) · [原 ref-17 工具](/studio/ideas/learning-skills-template) · [原三种构图工具](/studio/ideas/layout-selection)\n\n完整原说明与代码示例已保留在统一入口的兼容工具章节。此记录仅可恢复归档,未删除工具、素材或设计。`;
await api('/api/notes/'+legacy,body(old,redirectText),'PUT');
await api('/api/posts/'+legacy+'/archive',{archived:true});
const entries=await api('/api/explore-feed?category='+encodeURIComponent('文档入口'));
const expected=['3c98946754c33309d73d5284','4ce3283fd98bb03a8fb39a19',canonical].sort();
if(entries.total!==3||entries.nextCursor||JSON.stringify(entries.entries.map(e=>e.id).sort())!==JSON.stringify(expected))throw Error('Document-entry category does not contain exactly the intended three posts');
const after=(await api('/api/notes/'+legacy)).entry;
if(!after.archived||!after.editableMarkdown.includes(canonical))throw Error('Legacy compatibility link missing');
console.log(JSON.stringify({canonical:base+'/explore/'+canonical,legacyArchived:true,documentEntryCount:entries.total}));
+54
View File
@@ -0,0 +1,54 @@
import assert from 'node:assert/strict';
import {writeFile} from 'node:fs/promises';
const base='http://8.211.154.134:18131';
async function api(path,body,method=body?'POST':'GET',status=200){const r=await fetch(base+path,{method,...(body?{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});assert.equal(r.status,status,path);return r.json()}
if(process.argv.includes('--finalize')){
const {results}=JSON.parse(await (await import('node:fs/promises')).readFile('/tmp/studio-library/verification.json','utf8'));
const canonical='8eb8c76500580f7a4b56ba3c',legacy='9ebd8f78d54b4b9db741b4e8';
let documentFailure;let category;
try{
const entry=(await api('/api/notes/'+canonical)).entry;
for(const needle of ['standard-01','DELETE','revision','cropX','兼容工具原说明'])assert.ok(entry.editableMarkdown.includes(needle),needle);
for(const id of [canonical,legacy])assert.equal((await fetch(base+'/explore/'+id)).status,200);
const old=(await api('/api/notes/'+legacy)).entry;assert.ok(old.archived&&old.editableMarkdown.includes(canonical));
category=await api('/api/explore-feed?category='+encodeURIComponent('文档入口'));
assert.equal(category.total,3);assert.equal(category.nextCursor,null);
assert.deepEqual(category.entries.map(e=>e.id).sort(),['3c98946754c33309d73d5284','4ce3283fd98bb03a8fb39a19',canonical].sort());
}catch(error){documentFailure=error}
for(const item of results){const d=(await api('/api/studio/designs/'+item.id)).design;assert.ok(d.name.startsWith('API 验收'));assert.equal(d.postId,item.postId);if(!d.archived)await api('/api/studio/designs/'+d.id,{revision:d.revision},'DELETE');assert.equal((await api('/api/studio/designs/'+d.id)).design.archived,true)}
const final={canonical:base+'/explore/'+canonical,documentEntries:category?.total??null,legacyCompatible:!documentFailure,testRecordsArchived:results.length};
await writeFile('/tmp/studio-library/final-verification.json',JSON.stringify(final,null,2));console.log(JSON.stringify(final));if(documentFailure)throw documentFailure;
}else{
for(const path of ['/studio/template-layout','/studio/template-layout?id=invalid'])assert.equal((await fetch(base+path)).status,404);
const catalog=await api('/studio/api/layouts');assert.equal(catalog.layouts.length,28);
const note=(await api('/api/notes/8eb8c76500580f7a4b56ba3c')).entry;
const asset=note.coverAssetId||note.assets.find(a=>a.kind==='image').id;
const preview=await fetch(base+'/api/preview?'+new URLSearchParams({source:'/api/media/'+asset,width:'960'}));assert.equal(preview.status,200);assert.equal(preview.headers.get('content-type'),'image/webp');const bytes=(await preview.arrayBuffer()).byteLength;assert.ok(bytes<=220000);
const results=[];
for(const layoutId of ['standard-01','ref-17']){
const schema=await api('/studio/api/layouts/'+layoutId);assert.ok(schema.elements.some(s=>s.id==='T01'));
const p={texts:{T01:{value:'API 验收 · 原生页面',fontFamily:'serif',fontWeight:600}},images:{I01:{assetId:asset,fit:'cover',cropX:35,cropY:65,zoom:1.2}},added:[{id:'user-api-check',kind:'text',role:'扩展正文',box:[10,120,60,9],direction:'horizontal',text:'通过 HTTP 保存并恢复',reading:'custom'}],layers:{'user-api-check':{z:20,rotation:2}}};
let d=(await api('/api/studio/designs',{schemaVersion:1,layoutId,name:'API 验收 '+layoutId,parameters:p},'POST',201)).design;
const id=d.id,postId=d.postId;
assert.equal(d.url,'/studio/template-layout?id='+id);assert.equal(d.renderUrl,d.url);
results.push({layoutId,id,url:d.url,revision:d.revision,postId,parameters:p});
await writeFile('/tmp/studio-library/verification.json',JSON.stringify({results,preview:{asset,bytes,type:'image/webp'},pages:0},null,2));
assert.deepEqual((await api('/api/studio/designs/'+id)).design.parameters,d.parameters);
const html=await fetch(base+d.url).then(r=>r.text());assert.ok(html.includes('API 验收'));assert.ok(html.includes('user-api-check'));assert.ok(html.includes('/api/preview?'));assert.ok(!html.includes('src="/api/media/'));assert.ok(!/page-tools|workbench-top|contenteditable|编辑页面/.test(html));
d=(await api('/api/studio/designs/'+id,{name:'API 验收修订 '+layoutId,parameters:p,revision:d.revision},'PATCH')).design;
assert.equal(d.postId,postId);assert.equal(d.revision,2);
await api('/api/studio/designs/'+id,{name:'过期写入',parameters:{},revision:1},'PATCH',409);
d=(await api('/api/studio/designs/'+id,{revision:2},'DELETE')).design;assert.equal(d.archived,true);
assert.equal((await fetch(base+d.url)).status,404);assert.equal((await api('/api/notes/'+postId)).entry.archived,true);
assert.deepEqual((await api('/api/studio/designs/'+id)).design.parameters,d.parameters);
assert.ok((await api('/api/studio/designs?archived=true&layoutId='+layoutId)).designs.some(v=>v.id===id));
d=(await api('/api/studio/designs/'+id,{revision:3,archived:false},'POST')).design;assert.equal(d.revision,4);assert.equal(d.archived,false);assert.equal((await fetch(base+d.url)).status,200);
Object.assign(results[results.length-1],{url:d.url,revision:d.revision});
// Restore tested URL for visual inspection, then archive only these clearly named test records later.
}
for(const l of catalog.layouts){const r=await fetch(base+l.url);assert.equal(r.status,200,l.id);const html=await r.text();assert.ok(html.includes('data-layout-id="'+l.id+'"'));assert.ok(!/<img|data:image/.test(html));}
for(const slug of ['learning-skills-template','layout-selection']){assert.equal((await fetch(base+'/studio/ideas/'+slug)).status,200);const r=await fetch(base+'/studio/api/export/'+slug+'?format=svg');assert.equal(r.status,200);assert.match(r.headers.get('content-type'),/svg/);}
await writeFile('/tmp/studio-library/verification.json',JSON.stringify({results,preview:{asset,bytes,type:'image/webp'},pages:28},null,2));
console.log(JSON.stringify({crudFamilies:2,pages:28,conflicts:2,archiveRestore:2,compressedPreviewBytes:bytes,retainedToolbox:2,results:results.map(({parameters,...r})=>r)}));
}
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Run on ces-control after deployment; never starts a preview web server.
set -Eeuo pipefail
REPO_ROOT=$(git rev-parse --show-toplevel)
RESULT_DIR="$REPO_ROOT/artifacts/studio-acceptance"
MODE=${1:-verify}
[[ "$MODE" == verify || "$MODE" == --diagnose ]] || exit 2
WIKI_IMAGE=$(docker inspect --format '{{.Config.Image}}' prompt-waterfall-wiki-1)
[[ "$WIKI_IMAGE" =~ ^waterfall-wiki:[0-9a-f]{40}$ ]] || { echo 'Unexpected Wiki image'; exit 1; }
TEST_IMAGE="waterfall-wiki-tests:${WIKI_IMAGE#waterfall-wiki:}"
docker image inspect "$TEST_IMAGE" >/dev/null
mkdir -p "$RESULT_DIR"
chown 1000:1000 "$RESULT_DIR"
run_api(){
local result_root=$1 script=$2; shift 2
docker run --rm --volumes-from prompt-waterfall-wiki-1:ro \
--mount "type=bind,src=$REPO_ROOT,dst=/delivery,readonly" \
--mount "type=bind,src=$result_root,dst=/tmp/studio-library" \
-e AUTH_CONFIG_FILE=/auth/config.json -e AUTH_CHECK_BASE_URL=http://8.211.154.134:18131 \
--entrypoint node "$TEST_IMAGE" dist/auth-cli.cjs run "/delivery/scripts/$script" "$@"
}
# Result files are uploaded by the workflow and removed after successful upload.
printf '{"temporaryOutputManagedByCI":true}\n' > "$RESULT_DIR/cleanup.json"
# Always archive only the UUIDs created by this run, including when visual checks fail.
finish(){
local status=$?
trap - EXIT
if [[ -f "$RESULT_DIR/verification.json" ]]; then
if ! run_api "$RESULT_DIR" verify-studio-library.mjs --finalize; then status=1; fi
fi
exit "$status"
}
trap finish EXIT
run_api "$RESULT_DIR" verify-studio-library.mjs
docker run --rm --volumes-from prompt-waterfall-wiki-1:ro \
--mount "type=bind,src=$REPO_ROOT,dst=/delivery,readonly" \
--mount "type=bind,src=$RESULT_DIR,dst=/tmp/studio-library" \
-e AUTH_CONFIG_FILE=/auth/config.json -e NODE_PATH=/app/node_modules \
--entrypoint node "$TEST_IMAGE" /delivery/scripts/verify-studio-visual.cjs "$MODE"
+45
View File
@@ -0,0 +1,45 @@
const {readFile,mkdir,writeFile}=require('node:fs/promises');
const {createHmac,randomBytes}=require('node:crypto');
const {chromium}=require('playwright-core');
const assert=require('node:assert/strict');
(async()=>{
const base='http://8.211.154.134:18131',origin=new URL(base).origin,dir='/tmp/studio-library/visual';await mkdir(dir,{recursive:true});
const config=JSON.parse(await readFile(process.env.AUTH_CONFIG_FILE,'utf8'));
const now=Math.floor(Date.now()/1000),part=o=>Buffer.from(JSON.stringify(o)).toString('base64url');
const content=part({alg:'HS256',typ:'JWT'})+'.'+part({iss:'prompt',aud:'prompt-web',sub:'shared',iat:now,exp:now+1200,jti:randomBytes(16).toString('hex')});
const token=content+'.'+createHmac('sha256',Buffer.from(config.jwtKey,'hex')).update(content).digest('base64url');
const browser=await chromium.launch({executablePath:'/usr/bin/chromium',headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});
const context=await browser.newContext({viewport:{width:1100,height:1000},deviceScaleFactor:1});
await context.route('**/*',async route=>{const u=new URL(route.request().url());if(u.origin===origin)return route.continue({headers:{...route.request().headers(),Authorization:'Bearer '+token}});if(['data:','blob:'].includes(u.protocol))return route.continue();return route.abort()});
const page=await context.newPage(),errors=[],images=[];
page.on('pageerror',error=>errors.push({url:page.url(),message:error.message}));
page.on('response',async response=>{if(response.request().resourceType()==='image'){const url=new URL(response.url());images.push({path:url.pathname+url.search,status:response.status(),type:response.headers()['content-type'],bytes:(await response.body().catch(()=>Buffer.alloc(0))).length})}});
const metrics=process.argv.includes('--after-layouts')?JSON.parse(await readFile(dir+'/metrics.json','utf8')).metrics:[];
for(let i=1;i<=27&&!process.argv.includes('--after-layouts');i++){
const id='ref-'+String(i).padStart(2,'0');await page.goto(base+'/studio/layouts/'+id,{waitUntil:'networkidle'});await page.locator('article.native-layout').screenshot({path:dir+'/'+id+'.png',style:'.page-tools{visibility:hidden}'});
const m=await page.locator('article.native-layout').evaluate(el=>{
const overflow=[...el.querySelectorAll('.native-copy')].filter(e=>e.scrollHeight>e.clientHeight+2||e.scrollWidth>e.clientWidth+2);
return {id:el.dataset.layoutId,elements:el.querySelectorAll('[data-element]').length,width:el.clientWidth,height:el.clientHeight,overflow:overflow.map(e=>e.closest('[data-element]').dataset.element),overflowDetails:overflow.map(e=>{const style=getComputedStyle(e);return {id:e.closest('[data-element]').dataset.element,text:e.textContent,clientWidth:e.clientWidth,scrollWidth:e.scrollWidth,clientHeight:e.clientHeight,scrollHeight:e.scrollHeight,fontSize:style.fontSize,lineHeight:style.lineHeight,letterSpacing:style.letterSpacing,fontFamily:style.fontFamily,fontWeight:style.fontWeight,writingMode:style.writingMode}})};
});metrics.push(m);await writeFile(dir+'/metrics.json',JSON.stringify({metrics,images,errors},null,2));
}
if(!process.argv.includes('--after-layouts')&&!process.argv.includes('--diagnose'))assert.deepEqual(metrics.filter(m=>m.overflow.length),[],'Default copy must fit every native slot');
await page.goto(base+'/studio',{waitUntil:'networkidle'});assert.equal(await page.locator('.library-item').count(),27);await page.screenshot({path:dir+'/catalog-desktop.png',fullPage:true});
const verify=JSON.parse(await readFile('/tmp/studio-library/verification.json','utf8'));
for(const d of verify.results){await page.goto(base+d.url,{waitUntil:'networkidle'});assert.equal(await page.locator('img').count(),1);const current=await page.locator('img').evaluate(img=>({src:img.currentSrc,complete:img.complete,width:img.naturalWidth}));assert.ok(current.complete&&current.width>0);assert.equal(new URL(current.src).pathname,'/api/preview');await page.locator('article.native-layout').screenshot({path:dir+'/'+d.layoutId+'-saved.png',style:'.page-tools{visibility:hidden}'});
assert.equal(new URL(page.url()).pathname,'/studio/template-layout');
assert.equal(await page.locator('button,input,textarea,select,[contenteditable],.page-tools,.workbench-top').count(),0);
await page.locator('.native-copy').first().dblclick();await page.locator('.native-copy').first().dispatchEvent('contextmenu');
assert.equal(await page.locator('button,input,textarea,select,[contenteditable],.workbench-top').count(),0);
const plain=await browser.newContext({viewport:{width:1100,height:1000},javaScriptEnabled:false});
await plain.route('**/*',async route=>{const u=new URL(route.request().url());if(u.origin===origin)return route.continue({headers:{...route.request().headers(),Authorization:'Bearer '+token}});return route.abort()});
const direct=await plain.newPage();await direct.goto(base+d.url,{waitUntil:'networkidle'});assert.equal(await direct.locator('article[data-design-id="'+d.id+'"]').count(),1);assert.ok((await direct.locator('article').innerText()).includes('API 验收'));await plain.close();
}
for(const slug of ['learning-skills-template','layout-selection']){await page.goto(base+'/studio/ideas/'+slug,{waitUntil:'networkidle'});await page.screenshot({path:dir+'/tool-'+slug+'.png',fullPage:true})}
await page.setViewportSize({width:390,height:844});await page.goto(base+'/studio',{waitUntil:'networkidle'});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.screenshot({path:dir+'/catalog-mobile.png',fullPage:true});
await page.goto(base+verify.results[0].url,{waitUntil:'networkidle'});await page.screenshot({path:dir+'/standard-mobile.png',fullPage:true});
await page.goto(base+'/categories?category='+encodeURIComponent('文档入口'),{waitUntil:'domcontentloaded',timeout:60000});await page.getByRole('navigation',{name:'系统标签分类',exact:true}).waitFor({state:'visible'});assert.equal(await page.locator('.discovery-card').count(),3);await page.waitForFunction(()=>Array.from(document.querySelectorAll('.discovery-card img')).every(img=>img.complete&&img.naturalWidth>0),null,{timeout:60000});await page.screenshot({path:dir+'/document-entries.png',fullPage:true});
await writeFile(dir+'/metrics.json',JSON.stringify({metrics,images,errors},null,2));
assert.equal(images.filter(r=>new URL(r.path,base).pathname.startsWith('/api/media/')).length,0,'Display must never fetch originals');if(!process.argv.includes('--diagnose'))assert.equal(errors.length,0,JSON.stringify(errors));for(const image of images){if(new URL(image.path,base).pathname==='/brand-mark.svg'){assert.equal(image.status,200);assert.match(image.type,/image\/svg\+xml/);continue;}assert.equal(new URL(image.path,base).pathname,'/api/preview');assert.equal(image.status,200);assert.equal(image.type,'image/webp');assert.ok(image.bytes>0&&image.bytes<=220000)}
await writeFile(dir+'/metrics.json',JSON.stringify({metrics,images,errors},null,2));await browser.close();
console.log(JSON.stringify({diagnostic:process.argv.includes('--diagnose'),pages:27,errors:errors.length,displayImages:images.length,originalImageRequests:0,overflow:metrics.filter(m=>m.overflow.length)}));
})().catch(e=>{console.error(e.message);process.exit(1)});