Replace layout workbenches with native editable pages and server-loaded designs
studio CI and deployment / verify-and-deploy (push) Failing after 2m55s

This commit is contained in:
2026-10-27 16:46:27 +08:00
parent e6a10ff855
commit 3ffe457be4
10 changed files with 237 additions and 35 deletions
+70 -21
View File
@@ -1,23 +1,72 @@
import {useEffect,useState} from 'react';
import {useEffect,useRef,useState,type CSSProperties,type KeyboardEvent} from 'react';
import Head from 'next/head';
import {LayoutCanvas,type LayerLayout} from './LayoutCanvas';
import {parameters,type Parameters} from '../lib/layout-parameters';
import layouts from '../content/templates/layouts.json';
type Design={id:string;name:string;layoutId:string;parameters:Parameters;revision:number;url:string};
export function LayoutWorkbench({layoutId,designId}:{layoutId?:string;designId?:string}){
const [active,setActive]=useState(layoutId||''),[params,setParams]=useState<Parameters>({texts:{},images:{},decorations:{}}),[design,setDesign]=useState<Design|null>(null),[name,setName]=useState('新排版效果'),[status,setStatus]=useState(''),[guides,setGuides]=useState(false),[busy,setBusy]=useState(false),[raw,setRaw]=useState(''),[recent,setRecent]=useState<Design[]>([]);
const layout=layouts.find(l=>l.id===active) as LayerLayout|undefined;
useEffect(()=>{if(!designId)return;let live=true;fetch('/api/studio/designs/'+designId).then(async r=>{const d=await r.json();if(!r.ok)throw Error(d.error);if(live){setDesign(d.design);setActive(d.design.layoutId);setParams(d.design.parameters);setName(d.design.name)}}).catch(e=>{if(live)setStatus(e.message)});return()=>{live=false}},[designId]);
useEffect(()=>{if(!active)return;let live=true;fetch('/api/studio/designs?layoutId='+active).then(async r=>{if(r.ok&&live)setRecent((await r.json()).designs)}).catch(()=>{});return()=>{live=false}},[active,design]);
function patch(p:Partial<Parameters>){setParams(old=>({...old,...p}));setStatus('有未保存的修改')}
async function save(update=false){if(!layout)return;setBusy(true);try{const body=update&&design?{name,parameters:params,revision:design.revision}:{name,layoutId:layout.id,parameters:params},r=await fetch('/api/studio/designs'+(update&&design?'/'+design.id:''),{method:update?'PATCH':'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}),d=await r.json();if(!r.ok)throw Error(d.error);setDesign(d.design);setStatus('已保存效果 · '+d.design.id);window.history.replaceState(null,'',d.design.url)}catch(e){setStatus(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}}
async function download(){if(!layout)return;setBusy(true);try{const r=await fetch('/studio/api/layouts/'+layout.id,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(params)});if(!r.ok)throw Error('渲染失败');const url=URL.createObjectURL(await r.blob()),a=document.createElement('a');a.href=url;a.download=(design?.id||layout.id)+'.svg';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}catch(e){setStatus(e instanceof Error?e.message:'导出失败')}finally{setBusy(false)}}
if(!layout)return <main className="template-trial"><h1>读取排版效果</h1><p role="status">{status||'读取中…'}</p><a href="/explore/8eb8c76500580f7a4b56ba3c">返回使用教程</a></main>;
return <main className="template-trial"><Head><title>{layout.id} · {name} · Studio</title></Head><header className="trial-nav"><a href="/explore/8eb8c76500580f7a4b56ba3c">← PROMPT · 27 套排版教程</a><a href={'/studio/api/layouts/'+layout.id+'?agent_mode=True'}>API 说明</a></header><section className="trial-intro"><div><small>STUDIO / {layout.id.toUpperCase()}</small><h1>{layout.name}</h1><p>每个构件对应原图。修改文字、图位和装饰,保存为独立 ID,可交给 agent 通过 API 继续调整。</p></div></section><div className="trial-workspace"><aside className="trial-controls"><label>排版<select value={active} onChange={e=>{window.location.href='/studio/layouts/'+e.target.value}}>{layouts.map(l=><option key={l.id} value={l.id}>{l.id} · {l.name}</option>)}</select></label><label>效果名称<input value={name} maxLength={120} onChange={e=>setName(e.target.value)}/></label>
<details open><summary>文字 T · {layout.elements.filter(s=>s.kind==='text').length} 组</summary>{layout.elements.filter(s=>s.kind==='text').map(s=><label key={s.id}>{s.id} · {s.role}<small>{params.texts[s.id]?'替换文字':s.reading==='unreadable'?'原图小字无法辨认;未替换时保留原图层':'未替换时保留原图字形'}</small><textarea rows={2} maxLength={500} placeholder={s.text||'输入替换文字;留空可移除此文字'} value={params.texts[s.id]?.value??''} onChange={e=>patch({texts:{...params.texts,[s.id]:{...params.texts[s.id],value:e.target.value}}})}/><button onClick={()=>{const texts={...params.texts};delete texts[s.id];patch({texts})}}>恢复原图文字</button></label>)}</details>
<details><summary>图位 I · {layout.elements.filter(s=>s.kind==='image').length} 组</summary>{layout.elements.filter(s=>s.kind==='image').map(s=><div key={s.id}><label>{s.id} · {s.role}<input type="color" value={params.images[s.id]?.color||'#83918a'} onChange={e=>patch({images:{...params.images,[s.id]:{...params.images[s.id],color:e.target.value}}})}/></label><label>已上传图片的 asset ID<input placeholder="UUID(可留空)" value={params.images[s.id]?.assetId||''} onChange={e=>{const image={...params.images[s.id]};if(e.target.value)image.assetId=e.target.value;else delete image.assetId;patch({images:{...params.images,[s.id]:image}})}}/></label><button onClick={()=>{const images={...params.images};delete images[s.id];patch({images})}}>恢复原图图位</button></div>)}</details>
<details><summary>装饰 D · {layout.elements.filter(s=>s.kind==='decoration').length} 组</summary>{layout.elements.filter(s=>s.kind==='decoration').map(s=><div key={s.id}><label>{s.id} · {s.role}<input type="color" value={params.decorations[s.id]?.color||'#53645b'} onChange={e=>patch({decorations:{...params.decorations,[s.id]:{...params.decorations[s.id],color:e.target.value}}})}/></label><label><input type="checkbox" checked={params.decorations[s.id]?.hidden||false} onChange={e=>patch({decorations:{...params.decorations,[s.id]:{...params.decorations[s.id],hidden:e.target.checked}}})}/>隐藏此装饰</label><button onClick={()=>{const decorations={...params.decorations};delete decorations[s.id];patch({decorations})}}>恢复原装饰</button></div>)}</details>
<label>纸色<input type="color" value={params.paper||'#f4f2eb'} onChange={e=>patch({paper:e.target.value})}/></label><label className="trial-switch"><input type="checkbox" checked={guides} onChange={e=>setGuides(e.target.checked)}/>显示 T/I/D 构件边界</label><details onToggle={e=>{if(e.currentTarget.open)setRaw(JSON.stringify(params,null,2))}}><summary>完整参数 JSON</summary><textarea aria-label="完整参数 JSON" rows={12} value={raw} onChange={e=>setRaw(e.target.value)}/><button onClick={()=>{try{setParams(parameters(layout,JSON.parse(raw)));setStatus('参数已应用,尚未保存')}catch(e){setStatus(e instanceof Error?e.message:'JSON 错误')}}}>应用参数</button></details>
<div className="trial-actions"><button disabled={busy} className="trial-primary" onClick={()=>void save()}>保存新效果</button>{design&&<button disabled={busy} onClick={()=>void save(true)}>更新当前 ID</button>}<button disabled={busy} onClick={()=>void download()}>下载当前 SVG</button></div><p role="status">{status}</p>{design&&<p><a href={design.url}>打开已保存效果</a> · 修订 {design.revision}</p>}<p className="trial-help">原图来自低分辨率截图,未替换部分保留其像素质量。渲染不会自动保存;保存新效果生成新 ID,更新当前 ID 会检测修订冲突。</p><details><summary>已保存的此排版效果</summary>{recent.length?recent.map(d=><p key={d.id}><a href={d.url}>{d.name}</a> · r{d.revision}</p>):<p>还没有保存的效果</p>}</details></aside>
<div><div className="selection-preview"><LayoutCanvas layout={layout} params={params} guides={guides}/></div><details className="trial-reference"><summary>原图与构件对应表</summary><div className="trial-reference-body"><img src={layout.source} alt={layout.name+'原图'}/><div><a href={layout.tutorialUrl}>原图分层文档 ↗</a><table><thead><tr><th>ID</th><th>构件</th><th>坐标</th></tr></thead><tbody>{layout.elements.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>;
import type {Layout,Parameters,Slot} 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';
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}){
const ref=useRef<HTMLDivElement>(null);
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);
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 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 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){
setBusy(true);try{
const valid=parameters(layout,params),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('已保存,当前网址可直接打开此页面');
window.history.replaceState(window.history.state,'',designUrl(layout.id,data.design.id));
}catch(e){setStatus(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}
}
async function uploadImage(file:File|undefined){
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 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};
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>}
</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>}
<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>;
}
+20
View File
@@ -0,0 +1,20 @@
import type {IncomingMessage} from 'node:http';
import {parameters,uuid} from './layout-parameters';
import layouts from '../content/templates/layouts.json';
import type {Design} from './native-layout';
/** Only forward the session to our fixed private Wiki service, never a request Host. */
export async function readDesign(id:unknown,req:IncomingMessage):Promise<Design|null>{
if(!uuid(id))return null;
const origin=process.env.STUDIO_WIKI_ORIGIN||'http://waterfall-wiki:3000';
const headers:Record<string,string>={};
if(req.headers.cookie)headers.cookie=req.headers.cookie;
if(req.headers.authorization)headers.authorization=req.headers.authorization;
const response=await fetch(`${origin}/api/studio/designs/${id}`,{headers,redirect:'error',cache:'no-store',signal:AbortSignal.timeout(8000)});
if(response.status===404||response.status===400)return null;
if(!response.ok)throw new Error('Saved layout service unavailable');
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');
return {...design,parameters:parameters(layout,design.parameters)};
}
+54
View File
@@ -0,0 +1,54 @@
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};
export const emptyParameters=():Parameters=>({texts:{},images:{},decorations:{}});
export const designUrl=(layoutId:string,id:string)=>`/studio/layouts/${layoutId}?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'}
// 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('英文')||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.direction==='vertical')return '设计灵感 · 日常观察';
return '在留白之间,\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}%`};
}
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:.56),0);
if(slot.direction==='vertical')return Math.min(w*.9,h/Math.max(1,Array.from(text.replaceAll('\n','')).length)*.95);
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;
}
export function imageShape(layout:Layout,slot:Slot):CSSProperties {
const n=Number(layout.id.slice(4)),s:CSSProperties={backgroundColor:slot.id==='I01'?'#9ba6a3':'#788785'};
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.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';
return s;
}
export function decorationKind(slot:Slot){
if(slot.role.includes('同心'))return 'rings';
if(slot.role.includes('圆节点'))return 'node';
if(slot.role.includes('椭圆'))return 'oval';
if(slot.role.includes('曲线'))return 'curve';
if(slot.role.includes('贴条')||slot.role.includes('浅带'))return 'band';
if(slot.role.includes('斜'))return 'diagonal';
if(slot.box[3]>slot.box[2]*2)return 'vertical-lines';
return 'lines';
}
+1 -1
View File
@@ -7,7 +7,7 @@ import {LayoutCanvas} from '../../../components/LayoutCanvas';
import {parameters,LayoutParameterError} from '../../../lib/layout-parameters';
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。\nGET 同地址 ?format=svg 返回原图对应效果。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/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(`# 排版参数与渲染 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(!['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:'参数不合法'})}
}
+10 -3
View File
@@ -1,3 +1,10 @@
import {useRouter} from 'next/router';
import {LayoutWorkbench} from '../../components/LayoutWorkbench';
export default function DesignPage(){const router=useRouter();return typeof router.query.id==='string'?<LayoutWorkbench designId={router.query.id}/>:null}
import type {GetServerSideProps} from 'next';
import {readDesign} from '../../lib/design-server';
import {designUrl} from '../../lib/native-layout';
export default function DesignPage(){return null}
export const getServerSideProps:GetServerSideProps=async({params,req,res})=>{
res.setHeader('Cache-Control','private, no-store');
const design=await readDesign(params?.id,req);
if(!design)return {notFound:true};
return {redirect:{destination:designUrl(design.layoutId,design.id),permanent:false}};
};
-6
View File
@@ -1,6 +0,0 @@
import type {GetStaticPaths,GetStaticProps} from 'next';
import {LayoutWorkbench} from '../../components/LayoutWorkbench';
import layouts from '../../content/templates/layouts.json';
export default function LayoutPage({id}:{id:string}){return <LayoutWorkbench layoutId={id}/>}
export const getStaticPaths:GetStaticPaths=async()=>({paths:layouts.map(l=>({params:{id:l.id}})),fallback:false});
export const getStaticProps:GetStaticProps=async({params})=>layouts.some(l=>l.id===params?.id)?{props:{id:params?.id}}:{notFound:true};
@@ -0,0 +1,17 @@
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 {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})=>{
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 {props:{layout:nativeLayout(layout),design:null}};
};
+34
View File
@@ -28,3 +28,37 @@
.selection-preview{max-width:540px;margin:auto;box-shadow:0 3px 15px #28362f14}.selection-thumbs{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin-top:30px}.selection-thumbs button{padding:0;border-radius:0;border:1px solid #d8dcd5;background:#fff}.selection-thumbs button[aria-pressed=true]{outline:2px solid #617d65;outline-offset:4px}.selection-thumbs span{display:block;font-size:12px;padding:10px}
.trial-controls details{border-top:1px solid #dedfd8;padding:12px 0}.trial-controls summary{cursor:pointer;margin-bottom:12px}.trial-controls label small{display:block;font-weight:400;line-height:1.6;color:#687268}.trial-controls textarea{width:100%;box-sizing:border-box}.trial-controls>label input:not([type=checkbox]):not([type=color]){width:100%;box-sizing:border-box}.trial-actions button:disabled{opacity:.5;cursor:wait}
/* These are the pages themselves: live type and CSS geometry, no reference raster. */
.native-layout-page{min-height:100vh;background:#f5f5ef;padding-bottom:90px;color:#28312e}
.native-layout{position:relative;isolation:isolate;container-type:inline-size;width:min(100%,860px);margin:0 auto;overflow:hidden;font-family:Arial,"PingFang SC","Microsoft YaHei",sans-serif}
.native-element{position:absolute;outline-offset:3px;min-width:0;min-height:0}
.native-image{z-index:1}.native-decoration{z-index:2}.native-text{z-index:3}
.native-image-fill{width:100%;height:100%;overflow:hidden;display:grid;place-items:center}
.native-image-fill img{width:100%;height:100%;display:block;grid-area:1/1}
.native-image-label{font-size:12px;line-height:1.4;color:#fff;background:#26312e99;padding:5px 8px;max-width:95%;text-align:center}
.native-copy{width:100%;height:100%;line-height:1.15;font-weight:500;white-space:pre-wrap;overflow-wrap:anywhere;overflow:hidden;outline:none;letter-spacing:-.035em}
.native-copy.direction-vertical{writing-mode:vertical-rl;text-orientation:upright;letter-spacing:0}
.native-copy.direction-rotated{writing-mode:vertical-rl;text-orientation:mixed;transform:rotate(180deg);font-family:Georgia,serif}
.native-copy.direction-angled{transform:rotate(-15deg);transform-origin:center;overflow:visible;font-weight:700}
.native-copy.direction-curved{writing-mode:vertical-rl;transform:rotate(13deg);letter-spacing:.13em}
.native-text:first-of-type .native-copy{font-weight:700}
.ref-01 .native-text[data-element=T01] .native-copy,.ref-08 .native-text[data-element=T01] .native-copy,.ref-10 .native-text[data-element=T01] .native-copy,.ref-15 .native-text[data-element=T01] .native-copy,.ref-15 .native-text[data-element=T02] .native-copy,.ref-17 .native-text[data-element=T01] .native-copy,.ref-17 .native-text[data-element=T02] .native-copy,.ref-18 .native-text[data-element=T02] .native-copy,.ref-18 .native-text[data-element=T03] .native-copy{font-family:Georgia,"Times New Roman",serif;font-weight:700}
.ref-08 .native-copy{text-align:justify;letter-spacing:.07em}.ref-19 .native-text[data-element=T01],.ref-19 .native-text[data-element=T02],.ref-19 .native-text[data-element=T03],.ref-19 .native-text[data-element=T04]{font-weight:800}
.native-decoration{width:100%;height:100%}.decoration-lines{display:flex;flex-direction:column;justify-content:space-between;padding:2% 0}.decoration-lines i{display:block;border-top:max(1px,.18cqw) solid currentColor;width:100%}.decoration-lines i:nth-child(2){width:76%}.decoration-lines i:nth-child(3){width:88%}
.decoration-vertical-lines{display:flex;justify-content:space-between}.decoration-vertical-lines i{height:100%;border-left:max(1px,.15cqw) solid currentColor}
.decoration-node{border-radius:50%;background:currentColor}.decoration-oval{border:.25cqw solid currentColor;border-radius:50%}
.decoration-rings{border:.4cqw solid currentColor;border-radius:50%;box-shadow:0 0 0 1.5cqw #f5f5ef,0 0 0 1.8cqw currentColor,0 0 0 3.2cqw #f5f5ef,0 0 0 3.5cqw currentColor,0 0 0 5cqw #f5f5ef,0 0 0 5.3cqw currentColor;transform:scale(.92)}
.decoration-curve{border:.3cqw solid currentColor;border-left:0;border-radius:0 75% 50% 0;transform:rotate(15deg)}
.decoration-diagonal{border-left:.3cqw solid currentColor;transform:rotate(12deg)}.decoration-band{transform:rotate(-15deg)}
.is-editing .native-element{cursor:pointer}.is-editing .native-element:hover{outline:1px dashed #ff2442}.is-editing .native-element.is-selected{outline:2px solid #ff2442}.is-editing .native-copy[contenteditable=plaintext-only]{cursor:text}.native-element:focus-visible{outline:2px solid #ff2442}
.page-tools{position:fixed;z-index:30;bottom:18px;left:50%;transform:translateX(-50%);display:flex;gap:5px;align-items:center;width:max-content;max-width:calc(100% - 24px);padding:6px;border:1px solid #e1e3dc;background:#fffffff2;box-shadow:0 5px 30px #25312b14;border-radius:32px;backdrop-filter:blur(12px);font-size:13px;white-space:nowrap}
.page-tools a{padding:10px}.page-tools button{background:transparent;color:#28312e;padding:10px 14px;font:inherit}.page-tools .page-save{background:#283e32;color:#fff}.page-tools button:disabled{opacity:.4;cursor:default}.page-layout-number{font-size:10px;letter-spacing:.08em;color:#7e8881;padding:0 5px}.page-dirty{color:#ff2442;padding-right:8px}
.page-edit-info{position:relative;max-width:860px;margin:20px auto 0;padding:18px 20px;background:#fff;border-top:1px solid #e1e3dc;font-size:13px}.page-edit-info p{margin:0 0 16px;color:#657168}.page-edit-info label{display:flex;gap:10px;align-items:center}.page-edit-info input:not([type=color]){flex:1;min-width:0}.page-edit-options{display:flex;flex-wrap:wrap;gap:16px;margin-top:14px;align-items:center}
.page-edit-info input,.page-edit-info select,.element-popover input:not([type=checkbox]),.element-popover select,.element-popover textarea{border:1px solid #dbe0d8;border-radius:5px;background:#fff;color:#28312e;padding:7px;font:inherit;max-width:100%}.page-edit-info input[type=color],.element-popover input[type=color]{width:40px;height:32px;padding:2px}.page-edit-info button,.element-popover button{font:inherit;background:#f2f4ee;border-radius:5px;padding:9px 12px;color:#28312e}
.element-popover{position:fixed;right:18px;bottom:86px;z-index:40;width:290px;max-width:calc(100vw - 24px);max-height:60dvh;overflow:auto;border:1px solid #dbe0d8;border-radius:14px;padding:16px;background:#fffffff7;box-shadow:0 10px 40px #25312b24;font-size:13px;backdrop-filter:blur(14px)}
.element-popover-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.element-popover-heading button{padding:3px 8px;background:transparent;font-size:22px}.element-popover label{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:12px 0}.element-popover input[type=range]{width:150px}.element-popover .element-text-edit{display:block}.element-text-edit textarea{display:block;width:100%;margin-top:8px;resize:vertical}.element-popover>button{margin:5px 8px 0 0}.page-status{position:fixed;z-index:45;bottom:80px;left:50%;transform:translateX(-50%);max-width:calc(100% - 32px);margin:0;padding:10px 16px;background:#283e32;color:#fff;border-radius:8px;font-size:13px;box-shadow:0 4px 20px #0002}
@media(max-width:600px){.page-layout-number{display:none}.page-tools{bottom:12px}.page-tools button{padding:10px}.element-popover{right:12px;bottom:76px;width:260px}.page-edit-info{margin-top:0}.page-edit-options{gap:10px}}
@media print{.native-layout-page{padding:0;background:none}.native-layout{width:100%;margin:0;print-color-adjust:exact}.page-tools,.page-edit-info,.element-popover,.page-status{display:none!important}.native-element{outline:none!important}}
.native-copy.native-arc{position:relative;overflow:visible;white-space:pre;writing-mode:horizontal-tb;letter-spacing:0}.native-arc span{position:absolute;display:block}