Unify Wiki and Studio and remove deployment scaffolding
This commit is contained in:
@@ -1,22 +1,18 @@
|
||||
# Replace all three placeholders before starting Docker Compose.
|
||||
POSTGRES_PASSWORD=replace-with-a-long-random-password
|
||||
S3_ACCESS_KEY=replace-with-a-unique-access-key
|
||||
S3_SECRET_KEY=replace-with-a-long-random-secret
|
||||
# Export to the web, storage bootstrap and worker processes.
|
||||
DATABASE_URL=postgresql://endoleap:replace-me@127.0.0.1:5432/endoleap
|
||||
S3_ENDPOINT=http://127.0.0.1:9000
|
||||
S3_ACCESS_KEY=replace-me
|
||||
S3_SECRET_KEY=replace-me
|
||||
S3_BUCKET=prompt
|
||||
WEB_BIND_ADDRESS=0.0.0.0
|
||||
WEB_PORT=18131
|
||||
PG_PORT=18132
|
||||
S3_PORT=18133
|
||||
PROMPT_IMAGE=prompt:local
|
||||
RELEASE_SHA=development
|
||||
|
||||
# Use HTTPS and secure cookies in production; HTTP acceptance requires explicit false.
|
||||
PORT=3000
|
||||
AUTH_CONFIG_FILE=/path/to/private/auth.json
|
||||
AUTH_COOKIE_SECURE=true
|
||||
ACCOUNT_PUBLIC_ORIGIN=http://8.211.154.134:18131
|
||||
# Enable only behind an ingress that overwrites x-forwarded-for.
|
||||
ACCOUNT_PUBLIC_ORIGIN=https://endoleap.example
|
||||
ACCOUNT_TRUST_PROXY=false
|
||||
SMTP_HOST=smtpdm.aliyun.com
|
||||
|
||||
# Email verification and recovery
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=465
|
||||
SMTP_USERNAME=noreply@notice.entroia.com
|
||||
SMTP_FROM=noreply@notice.entroia.com
|
||||
SMTP_USERNAME=
|
||||
SMTP_FROM=
|
||||
SMTP_PASSWORD=
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
FROM node:24-bookworm-slim AS base
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates chromium fonts-noto-cjk \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
FROM base AS dependencies
|
||||
WORKDIR /repo/apps/waterfall-wiki
|
||||
RUN corepack enable && corepack prepare pnpm@11.25.0 --activate
|
||||
COPY apps/waterfall-wiki/pnpm-lock.yaml ./
|
||||
COPY pnpm-workspace.yaml /repo/pnpm-workspace.yaml
|
||||
COPY packages/brand/ /repo/packages/brand/
|
||||
COPY apps/waterfall-wiki/package.json ./
|
||||
RUN pnpm --filter @prompt/waterfall-wiki install --frozen-lockfile --fetch-timeout=300000 --network-concurrency=8
|
||||
|
||||
FROM dependencies AS build
|
||||
# .dockerignore excludes docs and operational notes without extra legacy COPY snapshots.
|
||||
COPY apps/waterfall-wiki/ .
|
||||
RUN pnpm typecheck && pnpm test && pnpm build && pnpm test:smoke
|
||||
|
||||
FROM build AS integration
|
||||
USER node
|
||||
CMD ["npm", "run", "test:integration"]
|
||||
|
||||
FROM base AS runtime
|
||||
WORKDIR /app/apps/waterfall-wiki
|
||||
ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000 \
|
||||
FFMPEG_PATH=/usr/bin/ffmpeg FFPROBE_PATH=/usr/bin/ffprobe
|
||||
COPY --from=build --chown=node:node /repo/apps/waterfall-wiki/.next/standalone/ /app/
|
||||
COPY --from=build --chown=node:node /repo/apps/waterfall-wiki/dist/worker.cjs /repo/apps/waterfall-wiki/dist/bootstrap.cjs /repo/apps/waterfall-wiki/dist/publish-learning-series.cjs /repo/apps/waterfall-wiki/dist/auth-cli.cjs ./
|
||||
COPY --from=build --chown=node:node /repo/apps/waterfall-wiki/db/ ./db/
|
||||
COPY --chown=node:node apps/waterfall-wiki/scripts/container-health.mjs ./
|
||||
COPY --chown=node:node apps/waterfall-wiki/scripts/import-character-packs.mjs apps/waterfall-wiki/scripts/verify-character-pack.mjs ./scripts/
|
||||
COPY --chown=node:node apps/waterfall-wiki/seed/characters/ ./seed/characters/
|
||||
COPY --chown=node:node apps/waterfall-wiki/src/content/managed-media.json ./src/content/managed-media.json
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
CMD ["node", "server.js"]
|
||||
@@ -1,163 +0,0 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"name": "把秋天装进一页 · 银杏观察手记",
|
||||
"document": {
|
||||
"version": 1,
|
||||
"brief": {
|
||||
"topic": "银杏与秋日观察手记",
|
||||
"audience": "喜欢日常摄影与视觉手帐的小红书读者",
|
||||
"intent": "以封面、观察方法和行动结尾组成三页可发布图文",
|
||||
"designIntent": "奶油纸底、森林墨色、银杏金点缀;宋体大标题与克制的无衬线正文;所有页面保留相同页边距和节奏",
|
||||
"imageStrategy": "生成一幅原创银杏静物插画作为系列母图;每页复用素材,保留裁切配置,不把正文烘焙进图片"
|
||||
},
|
||||
"style": {
|
||||
"version": "autumn-journal/1",
|
||||
"palette": {
|
||||
"paper": "#F3EFE5",
|
||||
"ink": "#253C32",
|
||||
"muted": "#718074",
|
||||
"accent": "#C3A050"
|
||||
},
|
||||
"typography": {
|
||||
"title": {
|
||||
"fontFamily": "serif",
|
||||
"fontSize": 8.4,
|
||||
"fontWeight": 600,
|
||||
"lineHeight": 1.15,
|
||||
"letterSpacing": 0
|
||||
},
|
||||
"body": {
|
||||
"fontFamily": "sans",
|
||||
"fontSize": 3.1,
|
||||
"fontWeight": 400,
|
||||
"lineHeight": 1.65,
|
||||
"letterSpacing": 0
|
||||
},
|
||||
"caption": {
|
||||
"fontFamily": "sans",
|
||||
"fontSize": 1.7,
|
||||
"fontWeight": 500,
|
||||
"lineHeight": 1.2,
|
||||
"letterSpacing": 0
|
||||
}
|
||||
},
|
||||
"spacing": {
|
||||
"margin": 10,
|
||||
"gap": 4
|
||||
}
|
||||
},
|
||||
"sources": [],
|
||||
"pages": [
|
||||
{
|
||||
"key": "cover",
|
||||
"role": "cover",
|
||||
"layoutId": "standard-01",
|
||||
"intent": "用银杏静物与两行大标题建立主题",
|
||||
"bindings": {
|
||||
"T01": "title",
|
||||
"T02": "body",
|
||||
"T03": "caption"
|
||||
},
|
||||
"parameters": {
|
||||
"texts": {
|
||||
"T01": {
|
||||
"value": "把秋天\n装进一页"
|
||||
},
|
||||
"T02": {
|
||||
"value": "不必走很远。\n一片银杏,就是今天的风景。"
|
||||
},
|
||||
"T03": {
|
||||
"value": "SEASONAL NOTES / 01"
|
||||
}
|
||||
},
|
||||
"images": {
|
||||
"I01": {
|
||||
"fit": "cover",
|
||||
"cropX": 50,
|
||||
"cropY": 50,
|
||||
"zoom": 1
|
||||
}
|
||||
},
|
||||
"decorations": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "observe",
|
||||
"role": "body",
|
||||
"layoutId": "standard-01",
|
||||
"intent": "用三个观察动作提供可实践的方法",
|
||||
"bindings": {
|
||||
"T01": "title",
|
||||
"T02": "body",
|
||||
"T03": "caption"
|
||||
},
|
||||
"parameters": {
|
||||
"texts": {
|
||||
"T01": {
|
||||
"value": "先看见\n再记录"
|
||||
},
|
||||
"T02": {
|
||||
"value": "看叶脉,看光落下的方向。\n留住一片金黄,也留出一半空白。\n把感受写成短句,画面就有了呼吸。"
|
||||
},
|
||||
"T03": {
|
||||
"value": "FIELD NOTES / 02"
|
||||
}
|
||||
},
|
||||
"images": {
|
||||
"I01": {
|
||||
"fit": "cover",
|
||||
"cropX": 65,
|
||||
"cropY": 40,
|
||||
"zoom": 1.25
|
||||
}
|
||||
},
|
||||
"decorations": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "ending",
|
||||
"role": "ending",
|
||||
"layoutId": "standard-01",
|
||||
"intent": "以轻量行动和提问收尾",
|
||||
"bindings": {
|
||||
"T01": "title",
|
||||
"T02": "body",
|
||||
"T03": "caption"
|
||||
},
|
||||
"parameters": {
|
||||
"texts": {
|
||||
"T01": {
|
||||
"value": "留一点白\n给下一次",
|
||||
"align": "middle"
|
||||
},
|
||||
"T02": {
|
||||
"value": "今天,捡起一片叶子。\n用三个词记录它的颜色、纹理与心情。\n你的秋天,会从哪一页开始?",
|
||||
"align": "middle"
|
||||
},
|
||||
"T03": {
|
||||
"value": "YOUR TURN / 03"
|
||||
}
|
||||
},
|
||||
"images": {
|
||||
"I01": {
|
||||
"fit": "cover",
|
||||
"cropX": 65,
|
||||
"cropY": 50,
|
||||
"zoom": 1
|
||||
}
|
||||
},
|
||||
"decorations": {},
|
||||
"layers": {
|
||||
"I01": {
|
||||
"x": 40,
|
||||
"y": 55,
|
||||
"width": 40,
|
||||
"height": 40,
|
||||
"radius": 20
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,10 @@ const nextConfig: NextConfig = {
|
||||
]},
|
||||
async rewrites(){return [
|
||||
...Object.entries(managedMedia).filter(([path])=>path.startsWith("apps/waterfall-wiki/public/")).map(([path,asset])=>({source:"/"+path.slice("apps/waterfall-wiki/public/".length),destination:"/api/media/"+asset.id})),
|
||||
{source:'/graphic',destination:'http://prompt-studio:3000/studio/graphic'},
|
||||
{source:'/infinite_canvas',destination:'http://prompt-studio:3000/studio/infinite_canvas'},
|
||||
{source:"/studio/:path*",destination:"http://prompt-studio:3000/studio/:path*"},
|
||||
{source:"/studio/api/:path*",destination:"/api/studio-ui/:path*"},
|
||||
{source:"/studio/brand/:path*",destination:"/brand/:path*"},
|
||||
{source:"/studio/favicon.ico",destination:"/favicon.ico"},
|
||||
{source:"/studio/apple-touch-icon.png",destination:"/apple-touch-icon.png"},
|
||||
{source:"/index.md",destination:"/api/agent-index"},
|
||||
{source:"/skills/index.md",destination:"/api/guidance/skills"},
|
||||
{source:"/skills/:path+/index.md",destination:"/api/guidance/skills/:path+"},
|
||||
@@ -22,8 +23,6 @@ const nextConfig: NextConfig = {
|
||||
{source:"/agent/index.md",destination:"/api/agent-index"},
|
||||
{source:"/skills/:skill/:doc.md",destination:"/api/skill-docs/:skill/:doc"},
|
||||
]},
|
||||
output: "standalone", outputFileTracingRoot: resolve(process.cwd(), "../.."),
|
||||
outputFileTracingIncludes: {"/*":["./node_modules/playwright-core/**/*"]},
|
||||
poweredByHeader: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -7,15 +7,11 @@
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "pnpm brand:prepare && next dev",
|
||||
"build": "pnpm brand:prepare && next build && esbuild src/worker.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/worker.cjs && esbuild scripts/bootstrap.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/bootstrap.cjs && esbuild scripts/publish-learning-series.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/publish-learning-series.cjs && esbuild scripts/auth-cli.ts --bundle --platform=node --format=cjs --external:pg-native --outfile=dist/auth-cli.cjs && node scripts/prepare-standalone.mjs",
|
||||
"build": "pnpm brand:prepare && next build && esbuild src/worker.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/worker.cjs && esbuild scripts/bootstrap.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/bootstrap.cjs && esbuild scripts/auth-cli.ts --bundle --platform=node --format=cjs --external:pg-native --outfile=dist/auth-cli.cjs",
|
||||
"start": "next start",
|
||||
"typecheck": "next typegen && tsc --noEmit",
|
||||
"test": "tsx --test tests/api-documentation.test.ts tests/health.test.ts tests/model.test.ts tests/learning-series.test.ts tests/skill-docs.test.ts tests/wiki.test.ts tests/explore.test.ts tests/preview.test.ts tests/note-markdown.test.tsx tests/api-publication.test.ts tests/discovery.test.ts tests/auth.test.ts tests/account.test.ts tests/guidance.test.ts tests/guidance-publishing.test.ts",
|
||||
"test:smoke": "node scripts/smoke.mjs",
|
||||
"storage:prepare": "tsx scripts/bootstrap.ts",
|
||||
"content:publish-learning": "tsx scripts/publish-learning-series.ts",
|
||||
"worker": "tsx src/worker.ts",
|
||||
"test:integration": "tsx --test tests/integration.test.ts",
|
||||
"brand:prepare": "node ../../packages/brand/scripts/prepare-app.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
try {
|
||||
const port = process.env.PORT || '3000';
|
||||
const [health, ready] = await Promise.all([
|
||||
fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(5000) }),
|
||||
fetch(`http://127.0.0.1:${port}/api/ready`, { signal: AbortSignal.timeout(5000) }),
|
||||
]);
|
||||
const data = await health.json();
|
||||
if (!health.ok || !ready.ok || data.service !== 'prompt' || data.release !== (process.env.RELEASE_SHA || 'development')) process.exit(1);
|
||||
} catch { process.exit(1); }
|
||||
@@ -1,38 +0,0 @@
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {join,dirname} from 'node:path';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {requiredPackImages} from './verify-character-pack.mjs';
|
||||
const root=join(dirname(fileURLToPath(import.meta.url)),'..','seed','characters');
|
||||
const base=process.env.PROMPT_IMPORT_BASE_URL||'http://127.0.0.1:3000';
|
||||
const media=JSON.parse(await readFile(join(root,'..','..','src','content','managed-media.json'),'utf8'));
|
||||
const packFiles=pack=>Object.entries(media).filter(([name])=>name.startsWith(`apps/waterfall-wiki/seed/characters/${pack.directory}/`)).sort(([a],[b])=>a.localeCompare(b));
|
||||
const packs=JSON.parse(await readFile(join(root,'packs.json'),'utf8'));
|
||||
async function verify(pack){
|
||||
let cursor='',post;const seen=new Set();
|
||||
do{const response=await fetch(base+'/api/feed?'+new URLSearchParams({section:'images',...(cursor?{cursor}:{})}));if(!response.ok)throw Error('Cannot verify character feed: '+response.status);const page=await response.json();post=page.posts.find(p=>p.slug===pack.slug);cursor=page.nextCursor||'';if(cursor&&seen.has(cursor))throw Error('Character feed cursor did not advance');seen.add(cursor);}while(!post&&cursor);
|
||||
if(!post)throw Error('Character pack missing: '+pack.slug);
|
||||
const files=packFiles(pack);if(files.length!==pack.count)throw Error('Seed file count mismatch: '+pack.slug);
|
||||
const hashes=files.map(([,asset])=>asset.sha256);
|
||||
const originals=requiredPackImages(hashes,post.assets.filter(a=>a.kind==='image'));
|
||||
for(const image of originals){const media=await fetch(`${base}/api/media/${image.id}`,{method:'HEAD'});if(!media.ok||media.headers.get('content-type')!=='image/png')throw Error('Original PNG unavailable');}
|
||||
console.log(`Verified: /p/${pack.slug} (${originals.length} original PNGs preserved; editorial covers allowed)`);
|
||||
}
|
||||
for(const pack of packs){
|
||||
const existing=await fetch(`${base}/p/${pack.slug}`);
|
||||
if(existing.ok){console.log(`Already imported: /p/${pack.slug}`);await verify(pack);continue;}
|
||||
if(existing.status!==404)throw new Error(`Cannot check pack ${pack.slug}: ${existing.status}`);
|
||||
const files=packFiles(pack);
|
||||
if(files.length!==pack.count)throw new Error(`Expected ${pack.count} PNGs for ${pack.slug}, got ${files.length}`);
|
||||
const data=new FormData();data.set('title',pack.title);data.set('slug',pack.slug);data.set('description',pack.description);
|
||||
for(const [name,asset] of files){
|
||||
const response=await fetch(`${base}/api/media/${asset.id}`);if(!response.ok)throw Error('Cannot read migrated original: '+name);
|
||||
const bytes=Buffer.from(await response.arrayBuffer());if(bytes.length!==asset.bytes||createHash('sha256').update(bytes).digest('hex')!==asset.sha256)throw Error('Original checksum mismatch: '+name);
|
||||
data.append('files',new Blob([bytes],{type:'image/png'}),name.split('/').pop());
|
||||
}
|
||||
const response=await fetch(`${base}/api/skills/street-people`,{method:'POST',body:data});
|
||||
if(response.status!==201&&response.status!==409)throw new Error(`Import ${pack.slug}: ${response.status} ${await response.text()}`);
|
||||
if(response.status===409&&!(await fetch(`${base}/p/${pack.slug}`)).ok)throw new Error(`Conflicting import ${pack.slug}`);
|
||||
console.log(`Imported: /p/${pack.slug} (${files.length} transparent PNGs)`);
|
||||
await verify(pack);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import { cp,mkdir,access } from 'node:fs/promises';
|
||||
await mkdir('.next/standalone/apps/waterfall-wiki/.next',{recursive:true});
|
||||
await cp('.next/static','.next/standalone/apps/waterfall-wiki/.next/static',{recursive:true});
|
||||
try{await access('public');await cp('public','.next/standalone/apps/waterfall-wiki/public',{recursive:true});}catch(e){if(e.code!=='ENOENT')throw e;}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { db } from "../src/lib/db";
|
||||
import { publishLearningSeries } from "../src/lib/publish-learning-series";
|
||||
publishLearningSeries().then(result=>console.log(`Published learning series: ${result.published.join(", ")}; one shared cover: ${result.coverId}`))
|
||||
.catch(error=>{console.error("Learning series publication failed:",error instanceof Error?error.message:"Unknown error");process.exitCode=1;})
|
||||
.finally(()=>db().end());
|
||||
@@ -1,65 +0,0 @@
|
||||
import {writeFile,unlink} from 'node:fs/promises';
|
||||
import sharp from 'sharp';
|
||||
import { spawn } from "node:child_process";
|
||||
import assert from "node:assert/strict";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { once } from "node:events";
|
||||
|
||||
async function availablePort() {
|
||||
const server = createServer();
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const port = server.address().port;
|
||||
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
return String(port);
|
||||
}
|
||||
|
||||
const port = process.env.SMOKE_PORT || await availablePort();
|
||||
const release = "smoke-test";
|
||||
const previewFixture='.next/standalone/apps/waterfall-wiki/public/__smoke-preview.png';
|
||||
await writeFile(previewFixture,await sharp({create:{width:48,height:48,channels:3,background:'#eee'}}).png().toBuffer());
|
||||
const child = spawn(process.execPath, [".next/standalone/apps/waterfall-wiki/server.js"], {
|
||||
// This loopback-only child checks retained resources without production credentials.
|
||||
// Production keeps failing closed; the bypass requires both explicit test settings.
|
||||
env: { ...process.env, AUTH_CONFIG_FILE: "", AUTH_DISABLED_FOR_TESTS: "true", PORT: port, HOSTNAME: "127.0.0.1", RELEASE_SHA: release },
|
||||
stdio: "inherit",
|
||||
});
|
||||
try {
|
||||
let ready = false;
|
||||
for (let i = 0; i < 40; i++) {
|
||||
if (child.exitCode !== null) throw new Error(`Server exited: ${child.exitCode}`);
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/health`);
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(await response.json(), { status: "ok", service: "prompt", release });
|
||||
ready = true;
|
||||
break;
|
||||
} catch { await setTimeout(500); }
|
||||
}
|
||||
assert.ok(ready, "Standalone production server must be healthy");
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/health`, { method: "POST" });
|
||||
assert.equal(response.status, 405);
|
||||
const indexResponse=await fetch(`http://127.0.0.1:${port}/api/wiki-index`);
|
||||
assert.equal(indexResponse.status,200);
|
||||
const indexText=await indexResponse.text();
|
||||
const id=indexText.match(/\/explore\/([a-f0-9]{24})/)?.[1];assert.ok(id);
|
||||
const agent=await fetch(`http://127.0.0.1:${port}/explore/${id}?agent_mode=True`);
|
||||
assert.equal(agent.status,200);assert.match(agent.headers.get('content-type'),/text\/plain/);const agentText=await agent.text();assert.match(agentText,/^# /);assert.doesNotMatch(agentText,/^\s*(?:<!doctype html|<html)/i);
|
||||
const preview=await fetch(`http://127.0.0.1:${port}/api/preview?source=${encodeURIComponent('/__smoke-preview.png')}&width=480`);
|
||||
assert.equal(preview.status,200);assert.match(preview.headers.get('content-type'),/image\/webp/);assert.ok((await preview.arrayBuffer()).byteLength<=100000);
|
||||
const home=await fetch(`http://127.0.0.1:${port}/`).then(r=>r.text());
|
||||
for(const href of ['/graphic','/infinite_canvas','/account?next=/workspace'])assert.ok(home.includes(`href="${href}"`),href);
|
||||
for(const [legacy,canonical] of [['/studio/graphic','/graphic'],['/studio/infinite_canvas','/infinite_canvas']]){
|
||||
const redirect=await fetch(`http://127.0.0.1:${port}${legacy}`,{redirect:'manual'});
|
||||
assert.equal(redirect.status,308);assert.equal(redirect.headers.get('location'),canonical);
|
||||
}
|
||||
console.log("Production smoke test passed, including landing entry points and canonical redirects");
|
||||
} finally {
|
||||
await unlink(previewFixture);
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
const exited = once(child, "exit");
|
||||
child.kill("SIGTERM");
|
||||
await exited;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/** Extra editorial covers are allowed; every original seed image must remain attached. */
|
||||
export function requiredPackImages(hashes,images){
|
||||
const remaining=[...images],originals=[];
|
||||
for(const hash of hashes){const index=remaining.findIndex(image=>image.sha256===hash);if(index<0)throw Error('Original seed image missing from character pack');originals.push(...remaining.splice(index,1));}
|
||||
return originals;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -5,9 +5,11 @@ import "@/styles/globals.css";
|
||||
import "@/styles/skill-docs.css";
|
||||
import "@/styles/learning-series.css";
|
||||
import "@/styles/brand.css";
|
||||
import "@/studio/styles/globals.css";
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
const router = useRouter();
|
||||
useEffect(() => { const scope = /^\/(?:graphic|infinite_canvas|layouts|template-layout)(?:\/|$)/.test(router.pathname) ? 'canvas' : 'home'; document.documentElement.dataset.theme = `${scope}-${document.documentElement.dataset.mode === 'dark' ? 'dark' : 'light'}`; }, [router.pathname]);
|
||||
return <Component {...pageProps} />;
|
||||
useEffect(() => { const scope = /^\/(?:studio\/)?(?:graphic|infinite_canvas|layouts|template-layout)(?:\/|$)/.test(router.pathname) ? 'canvas' : 'home'; document.documentElement.dataset.theme = `${scope}-${document.documentElement.dataset.mode === 'dark' ? 'dark' : 'light'}`; }, [router.pathname]);
|
||||
const studio = /^\/(?:studio(?:\/|$)|graphic(?:\/|$)|infinite_canvas(?:\/|$))/.test(router.pathname);
|
||||
return studio ? <div className="studio-app"><Component {...pageProps} /></div> : <Component {...pageProps} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import {embedSvgMedia} from '../../../../studio/lib/layout-images';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {serveApiDocumentation} from '../../../../studio/lib/api-documentation';
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import {ideas,ideaMarkdown} from '../../../../studio/content/ideas';
|
||||
import {selections} from '../../../../studio/components/SourceCover';
|
||||
import {renderCover} from '../../../../studio/lib/render-cover';
|
||||
import {tutorialPost} from '../../../../studio/content/tool-links';
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(serveApiDocumentation(req,res,'/studio/api/export/{slug}'))return;
|
||||
if(!['GET','POST'].includes(req.method||'')){res.setHeader('Allow','GET, POST');return res.status(405).end();}
|
||||
const slug=String(req.query.slug||''),idea=ideas.find(i=>i.slug===slug);if(!idea)return res.status(404).end();
|
||||
if(req.method==='POST'||req.query.format==='svg'){
|
||||
if(req.query.format!==undefined&&!['svg','json'].includes(String(req.query.format)))return res.status(400).json({error:'渲染格式必须为 svg 或 json'});
|
||||
try{
|
||||
const raw=req.query.slide??'0';if(req.method==='GET'&&(typeof raw!=='string'||!/^\d+$/.test(raw)))throw Error('无效 slide');
|
||||
const input=req.method==='POST'?req.body:idea.tool?{layoutId:req.query.layoutId??selections[0].id}:{slide:Number(raw)};
|
||||
const result=renderCover(slug,input);res.setHeader('Cache-Control','no-store');
|
||||
res.setHeader('Content-Disposition',`attachment; filename="${slug}.${req.query.format==='json'?'json':'svg'}"`);
|
||||
if(req.query.format==='json')return res.json(result.data);
|
||||
res.setHeader('Content-Type','image/svg+xml; charset=utf-8');return res.send(await embedSvgMedia(req,renderToStaticMarkup(result.node)));
|
||||
}catch(error){return res.status(400).json({error:error instanceof Error?error.message:'无效参数'});}
|
||||
}
|
||||
if(req.query.format==='markdown'){res.setHeader('Content-Type','text/markdown; charset=utf-8');return res.send(ideaMarkdown(idea)+'\n\n使用教程:'+tutorialPost+(idea.tool?'\n\n```json\n'+JSON.stringify(selections,null,2)+'\n```':''));}
|
||||
res.setHeader('Content-Disposition',`attachment; filename="${idea.slug}.json"`);return res.json({version:idea.tool?3:idea.template?2:1,...idea,...(idea.tool?{layouts:selections}:{}),tutorialPost});
|
||||
}
|
||||
export const config={api:{bodyParser:{sizeLimit:'32kb'}}};
|
||||
@@ -0,0 +1,3 @@
|
||||
import {serveApiDocumentation} from '../../../studio/lib/api-documentation';
|
||||
import type {NextApiRequest,NextApiResponse} from "next";
|
||||
export default function handler(req:NextApiRequest,res:NextApiResponse){if(serveApiDocumentation(req,res,'/studio/api/health'))return;res.setHeader("Cache-Control","no-store");if(!["GET","HEAD"].includes(req.method||""))return res.status(405).end();return req.method==="HEAD"?res.status(200).end():res.status(200).json({status:"ok",service:"prompt-studio"});}
|
||||
@@ -0,0 +1,3 @@
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import {ideas} from '../../../studio/content/ideas';
|
||||
export default function handler(_:NextApiRequest,res:NextApiResponse){res.setHeader('Content-Type','text/markdown; charset=utf-8');res.send('# 创作站\n\n- [在线画布、引用与 Agent 任务](/api/canvases?agent_mode=True)\n- [27 套排版目录与 API](/studio/api/layouts?agent_mode=True)\n- [多页作品与统一视觉](/api/studio/series?agent_mode=True)\n- [按 ID 保存效果](/api/studio/designs?agent_mode=True)\n\n'+ideas.map(i=>`- [${i.title}](/studio/ideas/${i.slug}) · [正文](/studio/api/export/${i.slug}?format=markdown)`).join('\n'));}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {embedSvgMedia} from '../../../../studio/lib/layout-images';
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import {embedLayoutImages} from '../../../../studio/lib/layout-images';
|
||||
import {createElement} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import layouts from '../../../../studio/content/templates/layouts.json';
|
||||
import standardLayout from '../../../../studio/content/standard-layout.json';
|
||||
import {LayoutCanvas} from '../../../../studio/components/LayoutCanvas';
|
||||
import {parameters,LayoutParameterError} from '../../../../studio/lib/layout-parameters';
|
||||
const workspaceSchema={
|
||||
added:'可选数组,最多100项:{id:"user-唯一ID",kind:"text|image|decoration",role:"名称",box:[x,y,width,height],direction:"horizontal",text:"文字或null",reading:"custom",shape:"rectangle|ellipse(装饰可选)"}',
|
||||
layers:'按原生或新增元素ID索引:x/y -10000..10000,width/height 0.1..10000,rotation -360..360,opacity 0..1,radius 0..5000,z -1000..1000,hidden/locked 布尔值;坐标和字号均为模板单位',
|
||||
texts:'原有 value/color/scale/align,加 fontFamily sans|serif|mono,fontSize 0.1..1000,fontWeight 100..900,lineHeight 0.5..4,letterSpacing -20..100',
|
||||
images:'原有 assetId/color/fit,加 cropX/cropY 0..100(默认50),zoom 1..5',
|
||||
export:'新增工作区参数由原生 HTML/CSS 页面呈现。旧 SVG 导出仅支持旧文本、图片与装饰参数,不反映新增元素、图层几何及扩展字体或裁切设置。使用页面打印可保存原生效果。'
|
||||
};
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
res.setHeader('Cache-Control','no-store');
|
||||
if(String(req.query.agent_mode).toLowerCase()==='true'&&['GET','HEAD'].includes(req.method||'')){res.setHeader('Content-Type','text/plain; charset=utf-8');if(req.method==='HEAD')return res.status(200).end();return res.send(`# 扩展编辑参数\n${JSON.stringify(workspaceSchema,null,2)}\n\n# 排版参数与渲染 API\n\nGET /studio/api/layouts/{id} 返回模板尺寸、T/I/D 构件 ID、坐标、原始文字可辨识状态与默认参数。id 为 standard-01(标准图文)或 ref-01 .. ref-27(固定构图)。standard-01 仅返回原生模板参数,不提供兼容 SVG。\n页面 /studio/layouts/{id} 直接提供原生 HTML/CSS 默认排版,不加载原图。保存结果直接打开 /studio/template-layout?id={designId},服务端根据 ID 读取模板、图片和文字,无需选版或编辑器;缺失或不存在的 ID 返回404。\nGET 同地址 ?format=svg 是兼容的原图图层导出,与原生页面使用的 HTML/CSS 不同。POST JSON 参数返回 SVG,不自动保存。?format=json 返回规范化参数。\n参数整体形状:{texts:{T01:{value:"标题",color:"#26362f",scale:1,align:"start"}},images:{I01:{color:"#788880",assetId:"已上传图片UUID",fit:"cover"}},decorations:{D01:{color:"#53645b",hidden:false}},paper:"#f4f2eb"}。全部可省略;构件 ID 必须属于当前模板。文字 value 可为空(移除),最多500字/8行;scale 0.25–2,align start/middle/end;fit cover/contain。图片先通过 /api/upload assetOnly=true 上传。\n未替换构件保留原始低分辨率图层;替换文字为 SVG 文字,未辨识小字不会编造。图位使用原始形状蒙版。paper 修改原底色层,不覆盖原图已有设计色块。\n文字、图像、装饰分组一一对应源图,不接受任意 URL、SVG 或未知构件。最大请求64KB。\n保存:POST /api/studio/designs {layoutId,name,parameters},返回 design.id/url/revision。再次打开返回的 /studio/template-layout?id={id}(纯结果页面);/studio/designs/{id} 自动跳转;PATCH /api/studio/designs/{id} {name,parameters,revision} 更新。\n错误400参数不合法,404模板不存在,405方法不支持。\n目录:/studio/api/layouts?agent_mode=True\n`)}
|
||||
if(req.query.id==='standard-01'){
|
||||
if(!['GET','HEAD','POST'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD, POST');return res.status(405).end()}
|
||||
try{const p=parameters(standardLayout,req.method==='POST'?req.body:{});
|
||||
if(req.query.format!==undefined&&req.query.format!=='json')return res.status(400).json({error:'标准排版提供原生 HTML 页面,不提供 SVG 导出;format 仅支持 json'});
|
||||
if(req.method==='HEAD')return res.status(200).end();
|
||||
return res.json({...standardLayout,schemaVersion:1,family:'standard',parameters:p,workspaceSchema,url:'/studio/layouts/standard-01',saveApi:'/api/studio/designs'});
|
||||
}catch(e){return res.status(400).json({error:e instanceof Error?e.message:'参数不合法'})}
|
||||
}
|
||||
if(!['GET','HEAD','POST'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD, POST');return res.status(405).end()}const layout=layouts.find(l=>l.id===req.query.id);if(!layout)return res.status(404).json({error:'排版不存在'});
|
||||
try{if(req.query.format!==undefined&&!['svg','json'].includes(String(req.query.format)))throw new LayoutParameterError('format 为 svg 或 json');const params=parameters(layout,req.method==='POST'?req.body:{});if(req.method==='HEAD')return res.status(200).end();if(req.query.format==='json')return res.json({layoutId:layout.id,parameters:params});if(req.method==='POST'||req.query.format==='svg'){res.setHeader('Content-Type','image/svg+xml; charset=utf-8');return res.send(await embedSvgMedia(req,renderToStaticMarkup(createElement(LayoutCanvas,{layout,params,imageSources:await embedLayoutImages(req,params)}))))}return res.json({schemaVersion:1,family:'fixed',id:layout.id,name:layout.name,width:layout.width,height:layout.height,sourceSha256:layout.sourceSha256,tutorialUrl:layout.tutorialUrl,elements:layout.elements.map(({id,kind,role,box,direction,text,reading})=>({id,kind,role,box,direction,text,reading})),parameters:params,workspaceSchema,url:'/studio/layouts/'+layout.id})}catch(e){return res.status(400).json({error:e instanceof Error?e.message:'参数不合法'})}
|
||||
}
|
||||
export const config={api:{bodyParser:{sizeLimit:'64kb'}}};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import fixed from '../../../../studio/content/templates/layouts.json';
|
||||
import standard from '../../../../studio/content/standard-layout.json';
|
||||
export default function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(!['GET','HEAD'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD');return res.status(405).end()}
|
||||
const entries=[standard,...fixed].map(l=>({id:l.id,name:l.name,family:l.id==='standard-01'?'standard':'fixed',url:'/studio/layouts/'+l.id,api:'/studio/api/layouts/'+l.id}));
|
||||
res.setHeader('Cache-Control','no-store');if(req.method==='HEAD')return res.status(200).end();
|
||||
if(String(req.query.agent_mode).toLowerCase()==='true'){res.setHeader('Content-Type','text/plain; charset=utf-8');return res.send('# Studio 可视化排版 API 库\n\n'+entries.map(e=>`${e.family} / ${e.id} · ${e.name}\n页面:${e.url}\n参数:${e.api}?agent_mode=True`).join('\n\n')+'\n\n多页作品:/api/studio/series?agent_mode=True\n单页 CRUD:/api/studio/designs?agent_mode=True\n统一文档:/explore/8eb8c76500580f7a4b56ba3c')}
|
||||
return res.json({version:1,seriesDocumentVersion:1,seriesApi:'/api/studio/series',layouts:entries,saveApi:'/api/studio/designs',catalogUrl:'/studio',documentationUrl:'/explore/8eb8c76500580f7a4b56ba3c'});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { ThemeToggle } from "../../studio/components/ThemeToggle";
|
||||
import { Brand } from "../../studio/components/Brand";
|
||||
import Head from 'next/head';
|
||||
import {useEffect,useRef,useState,type PointerEvent} from 'react';
|
||||
import {MousePointer2,Type,Square,Circle,Plus,Minus,Undo2,Redo2,Download,Layers,ImagePlus,Trash2,Copy,Eye,EyeOff,Lock,Unlock,Scan,ChevronRight,ArrowUpRight,PenTool,X,Hand,Link2,BookOpen,PanelLeft,PanelRight} from 'lucide-react';
|
||||
import {newElementId} from '../../studio/lib/native-layout';
|
||||
import styles from '../../studio/styles/graphic.module.css';
|
||||
import {parseGraphicDocument,type GraphicItem as Item,type GraphicDocument as Doc} from '../../studio/lib/graphic-document';
|
||||
const blank:Doc={name:'未命名设计',background:'#ffffff',items:[]};
|
||||
const storage='studio.graphic.v1';
|
||||
export default function Graphic(){
|
||||
const [doc,setDoc]=useState<Doc>(blank),[selected,setSelected]=useState(''),[past,setPast]=useState<Doc[]>([]),[future,setFuture]=useState<Doc[]>([]),[zoom,setZoom]=useState(.65),[status,setStatus]=useState('本机草稿'),[tab,setTab]=useState('图层'),[user,setUser]=useState<{email:string}|null>(null),[auth,setAuth]=useState(false),[mode,setMode]=useState('login'),[message,setMessage]=useState(''),[busy,setBusy]=useState(false);
|
||||
const [tool,setTool]=useState('select'),[offset,setOffset]=useState({x:0,y:0}),[showLayers,setShowLayers]=useState(true),[showProps,setShowProps]=useState(true);
|
||||
const dialog=useRef<HTMLDivElement>(null);
|
||||
useEffect(()=>{if(!auth)return;const old=document.activeElement as HTMLElement;const box=dialog.current;box?.querySelector<HTMLElement>('button,input')?.focus();function key(e:KeyboardEvent){if(e.key==='Escape'){setAuth(false);return}if(e.key!=='Tab'||!box)return;const nodes=Array.from(box.querySelectorAll<HTMLElement>('button:not(:disabled),input,a[href]'));const first=nodes[0],last=nodes[nodes.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last?.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first?.focus()}}document.addEventListener('keydown',key);return()=>{document.removeEventListener('keydown',key);old?.focus()}},[auth]);
|
||||
const restore=useRef<HTMLInputElement>(null);
|
||||
const board=useRef<HTMLDivElement>(null),upload=useRef<HTMLInputElement>(null),viewport=useRef<HTMLDivElement>(null),ready=useRef(false),dirty=useRef(false);
|
||||
const item=doc.items.find(i=>i.id===selected);
|
||||
useEffect(()=>{try{const raw=localStorage.getItem(storage);if(raw){setDoc(parseGraphicDocument(raw));}}catch{setStatus('无法读取草稿,请导出备份')}ready.current=true;void refresh();},[]);
|
||||
useEffect(()=>{if(!ready.current)return;try{localStorage.setItem(storage,JSON.stringify(doc));setStatus('已保存到此浏览器');dirty.current=false;}catch{setStatus('本机空间不足,请导出备份');dirty.current=true;}},[doc]);
|
||||
useEffect(()=>{const warn=(e:BeforeUnloadEvent)=>{if(dirty.current){e.preventDefault();e.returnValue=''}};window.addEventListener('beforeunload',warn);return()=>window.removeEventListener('beforeunload',warn)},[]);
|
||||
async function refresh(){try{const r=await fetch('/api/account/session');if(r.ok)setUser((await r.json()).user);}catch{/* Guest editing remains available. */}}
|
||||
function change(next:Doc){setPast(p=>[...p.slice(-49),doc]);setFuture([]);setDoc(next);dirty.current=true;}
|
||||
function patch(p:Partial<Item>){if(item&&!item.locked)change({...doc,items:doc.items.map(i=>i.id===selected?{...i,...p}:i)})}
|
||||
function add(kind:Item['kind'],src?:string){if(doc.items.length>=500){setStatus('单页最多 500 个图层');return;}const id=newElementId();const next:Item={id,kind,name:kind==='text'?'文字':kind==='image'?'图片':kind==='rect'?'矩形':'椭圆',text:'让灵感,有形。',x:90+doc.items.length*12%260,y:100+doc.items.length*12%400,w:kind==='text'?480:260,h:kind==='text'?90:220,fill:kind==='text'?'#282832':'#b8b3ff',size:52,hidden:false,locked:false,src};change({...doc,items:[...doc.items,next]});setSelected(id);setTab('图层');}
|
||||
function undo(){if(!past.length)return;setFuture(f=>[doc,...f]);setDoc(past[past.length-1]);setPast(p=>p.slice(0,-1));}
|
||||
function redo(){if(!future.length)return;setPast(p=>[...p,doc]);setDoc(future[0]);setFuture(f=>f.slice(1));}
|
||||
function remove(){if(item&&!item.locked){change({...doc,items:doc.items.filter(i=>i.id!==selected)});setSelected('')}}
|
||||
function duplicate(){if(item&&doc.items.length<500){const id=newElementId();change({...doc,items:[...doc.items,{...item,id,x:item.x+24,y:item.y+24,name:item.name+' 副本',locked:false}]});setSelected(id)}}
|
||||
function fit(){setOffset({x:0,y:0});if(viewport.current)setZoom(Math.max(.15,Math.min(1,(viewport.current.clientWidth-100)/800,(viewport.current.clientHeight-100)/1000)))}
|
||||
useEffect(()=>{fit();},[]);
|
||||
useEffect(()=>{function key(e:KeyboardEvent){if((e.target as HTMLElement).closest('input,textarea,select,button'))return;if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='z'){e.preventDefault();e.shiftKey?redo():undo()}else if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='d'){e.preventDefault();duplicate()}else if(e.key==='Delete'||e.key==='Backspace'){e.preventDefault();remove()}else if(e.key==='Escape')setSelected('');else if(!e.ctrlKey&&!e.metaKey&&e.key.toLowerCase()==='v')setTool('select');else if(!e.ctrlKey&&!e.metaKey&&e.key.toLowerCase()==='h')setTool('hand');else if(item&&!item.locked&&e.key.startsWith('Arrow')){e.preventDefault();const step=e.shiftKey?10:1;patch({x:item.x+(e.key==='ArrowRight'?step:e.key==='ArrowLeft'?-step:0),y:item.y+(e.key==='ArrowDown'?step:e.key==='ArrowUp'?-step:0)})}}window.addEventListener('keydown',key);return()=>window.removeEventListener('keydown',key)});
|
||||
function drag(e:PointerEvent<HTMLDivElement>,i:Item){if(tool==='hand'){panBoard(e);return}e.stopPropagation();setSelected(i.id);if(i.locked||e.button!==0)return;e.preventDefault();e.currentTarget.setPointerCapture(e.pointerId);const x=e.clientX,y=e.clientY,start=doc;let next=start;const target=e.currentTarget;const move=(p:globalThis.PointerEvent)=>{next={...start,items:start.items.map(n=>n.id===i.id?{...n,x:Math.max(-4000,Math.min(4000,i.x+(p.clientX-x)/zoom)),y:Math.max(-4000,Math.min(4000,i.y+(p.clientY-y)/zoom))}:n)};setDoc(next)};const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end);if(next!==start){setPast(p=>[...p.slice(-49),start]);setFuture([])}};target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end);}
|
||||
function resize(e:PointerEvent<HTMLElement>){e.stopPropagation();if(!item||item.locked)return;e.preventDefault();const start=doc,x=e.clientX,y=e.clientY,target=e.currentTarget;target.setPointerCapture(e.pointerId);let next=start;const move=(p:globalThis.PointerEvent)=>{next={...start,items:start.items.map(i=>i.id===item.id?{...i,w:Math.max(1,Math.min(4000,item.w+(p.clientX-x)/zoom)),h:Math.max(1,Math.min(4000,item.h+(p.clientY-y)/zoom))}:i)};setDoc(next)};const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end);if(next!==start){setPast(p=>[...p.slice(-49),start]);setFuture([])}};target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end)}
|
||||
function panBoard(e:PointerEvent<HTMLElement>){if(tool!=='hand')return;e.preventDefault();const x=e.clientX,y=e.clientY,start=offset,target=e.currentTarget;target.setPointerCapture(e.pointerId);const move=(p:globalThis.PointerEvent)=>setOffset({x:start.x+p.clientX-x,y:start.y+p.clientY-y});const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end)};target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end)}
|
||||
function download(content:string,type:string,extension:string){const url=URL.createObjectURL(new Blob([content],{type}));const a=document.createElement('a');a.href=url;a.download=doc.name+'.'+extension;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
|
||||
function exportSVG(){const esc=(s:string)=>s.replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]!));const svg=doc.items.filter(i=>!i.hidden).map(i=>i.kind==='text'?`<text x="${i.x}" y="${i.y+i.size}" font-family="sans-serif" font-size="${i.size}" fill="${esc(i.fill)}">${i.text.split('\n').map((line,n)=>`<tspan x="${i.x}" dy="${n?i.size*1.3:0}">${esc(line)}</tspan>`).join('')}</text>`:i.kind==='image'?`<image x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" href="${esc(i.src||'')}" preserveAspectRatio="xMidYMid slice"/>`:i.kind==='ellipse'?`<ellipse cx="${i.x+i.w/2}" cy="${i.y+i.h/2}" rx="${i.w/2}" ry="${i.h/2}" fill="${esc(i.fill)}"/>`:`<rect x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" fill="${esc(i.fill)}"/>`).join('');download(`<svg xmlns="http://www.w3.org/2000/svg" width="800" height="1000" viewBox="0 0 800 1000"><rect width="800" height="1000" fill="${esc(doc.background)}"/>${svg}</svg>`,'image/svg+xml','svg');}
|
||||
async function account(e:React.FormEvent<HTMLFormElement>){e.preventDefault();setBusy(true);setMessage('');const data=new FormData(e.currentTarget);try{const r=await fetch('/api/account/'+mode,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:data.get('email'),password:data.get('password')})});const d=await r.json();setMessage(d.error||d.message||'登录成功');if(r.ok){await refresh();if(mode==='login')setAuth(false);}}catch{setMessage('账户服务暂时无法连接')}finally{setBusy(false)}}
|
||||
return <div className={styles.app} data-layers={showLayers} data-properties={showProps}><Head><title>{doc.name + " · 啡跃 Endoleap Graphic"}</title><meta name="description" content="在 Studio 中自由编排文字、图形与图片。"/></Head>
|
||||
<header className={styles.top}><a href="/workspace" className={styles.brand}><Brand compact/><span className={styles.badge}>GRAPHIC</span></a><button aria-label="切换图层面板" aria-pressed={showLayers} onClick={()=>setShowLayers(v=>!v)}><PanelLeft size={17}/></button><button aria-label="切换属性面板" aria-pressed={showProps} onClick={()=>setShowProps(v=>!v)}><PanelRight size={17}/></button><ChevronRight size={14}/><input aria-label="设计名称" value={doc.name} maxLength={100} onChange={e=>change({...doc,name:e.target.value})}/><span className={styles.saved} role="status">{status}</span><button title="撤销" aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={17}/></button><button title="重做" aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={17}/></button><ThemeToggle/><button onClick={()=>setAuth(true)} className={styles.account}>{user?user.email:'邮箱登录'}</button><button className={styles.primary} onClick={exportSVG}><Download size={15}/>导出 SVG</button></header>
|
||||
<div className={styles.body}><aside className={styles.left}><div className={styles.tabs}>{['图层','素材','Agent'].map(t=><button key={t} aria-pressed={tab===t} onClick={()=>setTab(t)}>{t}</button>)}</div><div className={styles.pageTitle}><span>页面 01</span><span>800 × 1000</span></div>{tab==='Agent'?<div className={styles.agentPanel}><Link2 size={24}/><h3>与你的 Agent 一起设计</h3><p>将接入文档交给 coding agent,使用已有的模板与创作 API。</p><a href="/studio/api" target="_blank" rel="noreferrer">查看接入文档 ↗</a><a href="/documents" target="_blank" rel="noreferrer"><BookOpen size={15}/>知识与教程 ↗</a><small>在 Agent 中打开文档,查看可用的创作接口与使用方式。</small></div>:tab==='图层'?<><div className={styles.layers}>{[...doc.items].reverse().map(i=><div className={styles.layer} data-selected={i.id===selected} key={i.id}><button onClick={()=>setSelected(i.id)}>{i.kind==='text'?<Type size={14}/>:<Square size={14}/>}<span>{i.name}</span></button><button aria-label={i.hidden?'显示图层':'隐藏图层'} onClick={()=>change({...doc,items:doc.items.map(n=>n.id===i.id?{...n,hidden:!n.hidden}:n)})}>{i.hidden?<EyeOff size={13}/>:<Eye size={13}/>}</button><button aria-label={i.locked?'解锁图层':'锁定图层'} onClick={()=>change({...doc,items:doc.items.map(n=>n.id===i.id?{...n,locked:!n.locked}:n)})}>{i.locked?<Lock size={13}/>:<Unlock size={13}/>}</button></div>)}{!doc.items.length&&<div className={styles.emptyLayers}><Layers size={23}/><p>好设计,从第一笔开始</p><small>从下方工具栏添加文字与图形</small></div>}</div><button className={styles.addLayer} onClick={()=>add('text')}><Plus size={15}/>添加图层</button></>:<div className={styles.assets}><h3>基础元素</h3><button onClick={()=>add('rect')}><Square/>矩形</button><button onClick={()=>add('ellipse')}><Circle/>椭圆</button><button onClick={()=>add('text')}><Type/>文字</button><button onClick={()=>upload.current?.click()}><ImagePlus/>上传图片</button><p>你的画布,由你定义。支持 PNG、JPEG、WebP。</p></div>}<div className={styles.leftFooter}><a href="/infinite_canvas">Infinite Canvas <ArrowUpRight size={14}/></a><small>⌘ Z 撤销 · 方向键微调 · Delete 删除</small></div></aside>
|
||||
<main ref={viewport} className={styles.viewport} onPointerDown={e=>{setSelected('');panBoard(e)}}><div className={styles.canvasLabel}>画板 01 <span>800 × 1000</span></div><div className={styles.boardWrap} style={{width:800*zoom,height:1000*zoom,transform:`translate(${offset.x}px,${offset.y}px)`}}><div ref={board} className={styles.board} style={{background:doc.background,transform:`scale(${zoom})`}}>{doc.items.filter(i=>!i.hidden).map(i=><div key={i.id} tabIndex={0} role="button" aria-label={i.name} aria-pressed={selected===i.id} onFocus={()=>setSelected(i.id)} onPointerDown={e=>drag(e,i)} className={styles.element} data-selected={selected===i.id} style={{left:i.x,top:i.y,width:i.w,height:i.h,borderRadius:i.kind==='ellipse'?'50%':0,background:i.kind==='rect'||i.kind==='ellipse'?i.fill:undefined,color:i.fill,fontSize:i.size,whiteSpace:'pre-wrap'}}>{i.kind==='text'?i.text:i.kind==='image'?<img src={i.src} alt={i.name} draggable={false}/>:null}{selected===i.id&&<><i className={styles.corner} onPointerDown={resize}/><span className={styles.measure}>{Math.round(i.w)} × {Math.round(i.h)}</span></>}</div>)}{!doc.items.length&&<div className={styles.blankHint}><PenTool size={34} strokeWidth={1}/><h1>留白,是创作的起点。</h1><p>添加文字、图形,或放入你的第一张图片。</p><button onPointerDown={e=>e.stopPropagation()} onClick={()=>add('text')}>开始设计 <ArrowUpRight size={16}/></button></div>}</div></div><div className={styles.tools} onPointerDown={e=>e.stopPropagation()}><button title="选择" aria-label="选择工具" aria-pressed={tool==='select'} onClick={()=>{setTool('select');setSelected('')}}><MousePointer2 size={20}/></button><button title="抓手工具" aria-label="抓手工具" aria-pressed={tool==='hand'} onClick={()=>setTool('hand')}><Hand size={19}/></button><button title="文字" aria-label="添加文字" onClick={()=>add('text')}><Type size={20}/></button><button title="矩形" aria-label="添加矩形" onClick={()=>add('rect')}><Square size={19}/></button><button title="椭圆" aria-label="添加椭圆" onClick={()=>add('ellipse')}><Circle size={19}/></button><button title="图片" aria-label="上传图片" onClick={()=>upload.current?.click()}><ImagePlus size={19}/></button><span/><button aria-label="缩小" onClick={()=>setZoom(z=>Math.max(.15,z-.1))}><Minus size={16}/></button><output>{Math.round(zoom*100)}%</output><button aria-label="放大" onClick={()=>setZoom(z=>Math.min(2,z+.1))}><Plus size={16}/></button><button aria-label="适应画布" onClick={fit}><Scan size={18}/></button></div></main>
|
||||
<aside className={styles.right}><div className={styles.inspectorTitle}>设计属性<span>Design</span></div>{item?<div className={styles.props}><label>图层名称<input maxLength={200} value={item.name} disabled={item.locked} onChange={e=>patch({name:e.target.value})}/></label><h3>布局</h3><div className={styles.fields}>{(['x','y','w','h'] as const).map(k=><label key={k}>{({x:'X',y:'Y',w:'宽',h:'高'})[k]}<input type="number" value={Math.round(item[k])} disabled={item.locked} onChange={e=>{const value=Number(e.target.value);if(Number.isFinite(value))patch({[k]:k==='w'||k==='h'?Math.max(1,Math.min(4000,value)):Math.max(-4000,Math.min(4000,value))})}}/></label>)}</div>{item.kind==='text'&&<><h3>文字</h3><textarea aria-label="文字内容" value={item.text} maxLength={4000} disabled={item.locked} onChange={e=>patch({text:e.target.value})}/><label>字号<input type="number" min={8} max={240} value={item.size} disabled={item.locked} onChange={e=>patch({size:Math.max(8,Math.min(240,Number(e.target.value)||8))})}/></label></>}<h3>填色</h3><label className={styles.color}><input type="color" value={item.fill} disabled={item.locked} onChange={e=>patch({fill:e.target.value})}/>{item.fill.toUpperCase()}</label><div className={styles.actions}><button onClick={duplicate}><Copy size={15}/>复制</button><button disabled={item.locked} onClick={remove}><Trash2 size={15}/>删除</button></div><button disabled={item.locked} onClick={()=>{const n=doc.items.findIndex(i=>i.id===item.id);if(n>0){const items=[...doc.items];[items[n-1],items[n]]=[items[n],items[n-1]];change({...doc,items})}}}>下移一层</button></div>:<div className={styles.props}><h3>画板</h3><p>自由画布 · 竖版</p><div className={styles.dimensions}>W <b>800</b> H <b>1000</b></div><h3>背景颜色</h3><label className={styles.color}><input type="color" value={doc.background} onChange={e=>change({...doc,background:e.target.value})}/>{doc.background.toUpperCase()}</label><div className={styles.note}><MousePointer2 size={20}/><p>选中一个图层,<br/>调整属于它的每个细节。</p></div></div>}<div className={styles.rightFooter}><button onClick={()=>download(JSON.stringify(doc,null,2),'application/json','json')}><Download size={15}/>备份设计 JSON</button><button onClick={()=>restore.current?.click()}>导入设计 JSON</button><p>草稿仅保存在此浏览器。<br/>邮箱登录共用全站账户。</p></div></aside></div>
|
||||
<input ref={restore} hidden type="file" accept="application/json,.json" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;try{if(f.size>5*1024*1024)throw Error('文件不得超过 5MB');const restored=parseGraphicDocument(await f.text());change(restored);setSelected('');}catch(error){setStatus(error instanceof Error?error.message:'导入失败')}}}/>
|
||||
<input ref={upload} hidden type="file" accept="image/png,image/jpeg,image/webp" onChange={e=>{const f=e.target.files?.[0];if(!f)return;if(f.size>3*1024*1024||!['image/png','image/jpeg','image/webp'].includes(f.type)){setStatus('请使用 3MB 以内的 PNG / JPEG / WebP');return}const reader=new FileReader();reader.onload=()=>add('image',String(reader.result));reader.readAsDataURL(f);e.target.value=''}}/>
|
||||
{auth&&<div className={styles.overlay}><div ref={dialog} className={styles.modal} role="dialog" aria-modal="true" aria-label="邮箱账户"><button className={styles.close} aria-label="关闭" onClick={()=>setAuth(false)}><X size={20}/></button><span className={styles.modalIcon}><Brand compact/></span><h2>{user?'你的 Studio 账户':'把灵感带进 Studio'}</h2>{user?<><p>{user.email}</p><button onClick={async()=>{try{const r=await fetch('/api/account/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});if(!r.ok)throw Error();setUser(null);setAuth(false)}catch{setMessage('退出失败,请重试')}}}>退出登录</button></>:<><p>使用知识站的同一个邮箱账户</p><div className={styles.tabs}>{[['login','登录'],['register','注册'],['resend','重发邮件']].map(([v,t])=><button key={v} aria-pressed={mode===v} onClick={()=>setMode(v)}>{t}</button>)}</div><form onSubmit={account}><label>邮箱<input autoFocus required type="email" name="email" autoComplete="email" maxLength={254}/></label><label>密码<input required type="password" name="password" minLength={12} maxLength={256} autoComplete={mode==='register'?'new-password':'current-password'}/></label><small>密码至少 12 字符;新账户需通过邮件验证。</small><button className={styles.primary} disabled={busy}>{busy?'处理中…':mode==='login'?'登录 Studio':mode==='register'?'创建账户':'重发验证邮件'}</button></form></>}<p role="status">{message}</p></div></div>}
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { ThemeToggle } from "../../studio/components/ThemeToggle";
|
||||
import { Brand } from "../../studio/components/Brand";
|
||||
import Head from 'next/head';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {ArrowLeft,Plus,MousePointer2,Hand,ImagePlus,Type,Workflow,Undo2,Redo2,Minus,Maximize,Download,Upload,Trash2,Link2,Sparkles,ChevronRight,Sun,Moon} from 'lucide-react';
|
||||
import s from '../../studio/styles/infinite-canvas.module.css';
|
||||
import CanvasNodeView from '../../studio/components/canvas/CanvasNodeView';
|
||||
import CanvasComposer from '../../studio/components/canvas/CanvasComposer';
|
||||
import CanvasAgentPanel,{type CanvasAgentHandle} from '../../studio/components/canvas/CanvasAgentPanel';
|
||||
import {parseCanvasDocument,deriveNode,connectNodes,removeCanvasNode,referencedNodes,agentTask,type CanvasNode as Card,type CanvasDocument as Doc} from '../../studio/lib/canvas-document';
|
||||
const example:Doc={version:1,cards:[{id:'brief',kind:'text',title:'01 / 创意简报',text:'把日常,拍成一场电影。\n\n一段关于城市清晨的视觉散文。低饱和色彩、自然光与细腻颗粒,让每一帧都有呼吸感。',x:70,y:140},{id:'reference',kind:'image',title:'02 / 视觉参考',text:'晨光 · 建筑 · 胶片质感\n上传你的参考图片',x:460,y:80},{id:'shot',kind:'prompt',title:'03 / 镜头构思',text:'清晨,阳光穿过窗边的植物,落在安静的房间里。缓慢推进镜头,35mm 胶片,温暖柔和的光线。',x:850,y:160}],links:[['brief','reference'],['reference','shot']]};
|
||||
const initial:Doc={version:1,cards:[],links:[]};
|
||||
const key='studio.infinite-canvas.v1';
|
||||
export default function InfiniteCanvas(){
|
||||
const [doc,setDoc]=useState<Doc>(initial),[selected,select]=useState('shot'),[zoom,setZoom]=useState(.8),[pan,setPan]=useState({x:0,y:0}),[tool,setTool]=useState('select'),[past,setPast]=useState<Doc[]>([]),[future,setFuture]=useState<Doc[]>([]),[status,setStatus]=useState('示例项目 · 尚未保存'),[ready,setReady]=useState(false),[email,setEmail]=useState(''),[link,setLink]=useState(''),[menu,setMenu]=useState<{x:number;y:number}|null>(null),[editing,setEditing]=useState(''),[refMenu,setRefMenu]=useState(''),[taskFeedback,setTaskFeedback]=useState(''),[composerTarget,setComposerTarget]=useState(''),[pickerRequest,setPickerRequest]=useState(0);
|
||||
const file=useRef<HTMLInputElement>(null),json=useRef<HTMLInputElement>(null),viewport=useRef<HTMLDivElement>(null),drag=useRef<{id:string;x:number;y:number;ox:number;oy:number;before:Doc;resize?:boolean}|null>(null);
|
||||
const pickerSequence=useRef(0),agent=useRef<CanvasAgentHandle>(null);
|
||||
const active=doc.cards.find(c=>c.id===selected);
|
||||
useEffect(()=>{try{const raw=localStorage.getItem(key);if(raw){const d=parseCanvasDocument(raw);setDoc(d);setStatus('已恢复本机草稿')}}catch{setStatus('草稿读取失败,可导入 JSON 恢复')}try{const v=JSON.parse(localStorage.getItem(key+'.view')||'null');if(v&&Number.isFinite(v.zoom)&&v.zoom>=.2&&v.zoom<=2&&Number.isFinite(v.x)&&Number.isFinite(v.y)){setZoom(v.zoom);setPan({x:v.x,y:v.y})}}catch{}setReady(true);fetch('/api/account/session').then(r=>r.ok?r.json():null).then(d=>setEmail(d?.user?.email||'')).catch(()=>{});},[]);
|
||||
useEffect(()=>{if(!ready)return;try{localStorage.setItem(key,JSON.stringify(doc));setStatus('已保存到此浏览器')}catch{setStatus('本机空间不足,请导出项目备份')}},[doc,ready]);
|
||||
useEffect(()=>{if(ready)try{localStorage.setItem(key+'.view',JSON.stringify({...pan,zoom}))}catch{}},[pan,zoom,ready]);
|
||||
useEffect(()=>{const el=viewport.current;if(!el)return;const block=(e:WheelEvent)=>{if(!(e.target as HTMLElement).closest('textarea,input,select'))e.preventDefault()};el.addEventListener('wheel',block,{passive:false});return()=>el.removeEventListener('wheel',block)},[]);
|
||||
useEffect(()=>{const keys=(e:KeyboardEvent)=>{if(e.key==='Escape'){setMenu(null);setRefMenu('');setEditing('');return}if((e.target as HTMLElement).closest('input,textarea,select,[contenteditable]'))return;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();if(e.shiftKey)redo();else undo()}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='d'){e.preventDefault();duplicate()}};window.addEventListener('keydown',keys);return()=>window.removeEventListener('keydown',keys)});
|
||||
|
||||
function scaleAt(next:number,cx?:number,cy?:number){const el=viewport.current;if(!el)return;const r=el.getBoundingClientRect(),x=cx===undefined?r.width/2:cx-r.left,y=cy===undefined?r.height/2:cy-r.top;const z=Math.max(.2,Math.min(2,next));setPan({x:x-(x-pan.x)*z/zoom,y:y-(y-pan.y)*z/zoom});setZoom(z)}
|
||||
function duplicate(){if(!active||doc.cards.length>=80)return;const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');commit({...doc,cards:[...doc.cards,{...active,id,title:active.title.slice(0,197)+' 副本',x:active.x+40,y:active.y+40}]});select(id)}
|
||||
function commit(next:Doc){setPast(p=>[...p.slice(-29),doc]);setFuture([]);setDoc(next)}
|
||||
function add(kind:Card['kind'],image?:string){if(doc.cards.length>=80){setStatus('最多 80 个节点');return}const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');const rect=viewport.current?.getBoundingClientRect();commit({...doc,cards:[...doc.cards,{id,kind,title:kind==='text'?'灵感笔记':kind==='image'?'图片节点':kind==='script'?'脚本生成器':'生成提示词',text:'',x:((menu?.x??(rect?.width||700)/2)-pan.x)/zoom-160,y:((menu?.y??(rect?.height||600)/2)-pan.y)/zoom-100,image}]});select(id)}
|
||||
function change(field:'title'|'text'|'instruction',value:string,id=selected){setDoc(d=>({...d,cards:d.cards.map(c=>c.id===id?{...c,[field]:value}:c)}))}
|
||||
function beginEdit(){setPast(p=>[...p.slice(-29),doc]);setFuture([])}
|
||||
function undo(){if(!past.length)return;setFuture(f=>[doc,...f]);setDoc(past[past.length-1]);setPast(p=>p.slice(0,-1))}
|
||||
function redo(){if(!future.length)return;setPast(p=>[...p,doc]);setDoc(future[0]);setFuture(f=>f.slice(1))}
|
||||
function fit(){const el=viewport.current;if(!el||!doc.cards.length)return;const minX=Math.min(...doc.cards.map(c=>c.x)),minY=Math.min(...doc.cards.map(c=>c.y));const w=Math.max(...doc.cards.map(c=>c.x+(c.width||320)))-minX,h=Math.max(...doc.cards.map(c=>c.y+(c.height||350)))-minY;const z=Math.max(.2,Math.min(1,(el.clientWidth-80)/w,(el.clientHeight-100)/h));setZoom(z);setPan({x:(el.clientWidth-w*z)/2-minX*z,y:(el.clientHeight-h*z)/2-minY*z})}
|
||||
function selectNode(id:string){if(id!==selected)setEditing('');select(id)}
|
||||
function editNode(id:string){setPickerRequest(0);setComposerTarget('');select(id);setEditing(id);setMenu(null);setRefMenu('');setTaskFeedback('');setTool('select')}
|
||||
function patchNode(id:string,patch:Partial<Card>){commit({...doc,cards:doc.cards.map(n=>n.id===id?{...n,...patch}:n)})}
|
||||
function derive(source:string,kind:Card['kind'],operation:Card['operation']='generate'){
|
||||
const parent=doc.cards.find(n=>n.id===source);if(!parent)return;
|
||||
const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');
|
||||
const title=operation==='upscale'?'图片高清':kind==='script'?'脚本生成器':kind==='image'?'图片节点':'文本节点';
|
||||
try{commit(deriveNode(doc,source,{id,kind,operation,title,text:'',x:parent.x+(parent.width||320)+150,y:parent.y,width:360,height:300}));editNode(id);setComposerTarget(id)}catch(e){setStatus(e instanceof Error?e.message:'无法创建节点')}
|
||||
}
|
||||
function connect(from:string,to:string){try{const next=connectNodes(doc,from,to);if(next!==doc)commit(next);setTaskFeedback('')}catch(e){setTaskFeedback(e instanceof Error?e.message:'无法引用节点')}}
|
||||
function exportTask(id:string){try{const task=agentTask(doc,id),url=URL.createObjectURL(new Blob([JSON.stringify(task,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=`canvas-task-${id}.json`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);setTaskFeedback('Agent 任务已导出')}catch(e){setTaskFeedback(e instanceof Error?e.message:'无法导出任务')}}
|
||||
function exportDoc(){const url=URL.createObjectURL(new Blob([JSON.stringify(doc,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='studio-canvas.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
|
||||
return <main className={s.app}><Head><title>无限画布 · 啡跃 Endoleap</title><meta name="description" content="在无限画布上组织灵感、参考素材与镜头提示词"/></Head>
|
||||
<header className={s.header}><a href="/workspace" className={s.back} aria-label="返回 Studio"><ArrowLeft size={18}/></a><a href="/workspace" className={s.brand}><Brand compact/></a><i/><span className={s.crumb}>工作空间 <ChevronRight size={13}/></span><strong>未命名的灵感宇宙</strong><span className={s.badge}>本机草稿</span><div className={s.spacer}/><CanvasAgentPanel ref={agent} document={doc} email={email} onLoad={next=>{setDoc(next);setPast([]);setFuture([]);setEditing('');select('')}} onFeedback={setTaskFeedback}/><ThemeToggle/><a href="/account">{email||'登录账户'}</a><button className={s.export} onClick={exportDoc}><Download size={15}/>导出项目</button></header>
|
||||
<div className={s.workspace}><nav className={s.rail} aria-label="画布工具"><button title="选择工具" aria-label="选择工具" aria-pressed={tool==='select'} onClick={()=>setTool('select')}><MousePointer2/></button><button title="移动画布" aria-label="移动画布" aria-pressed={tool==='hand'} onClick={()=>setTool('hand')}><Hand/></button><hr/><button title="添加笔记" aria-label="添加笔记" onClick={()=>add('text')}><Type/></button><button title="上传图片" aria-label="上传图片" onClick={()=>file.current?.click()}><ImagePlus/></button><button title="添加提示词" aria-label="添加提示词" onClick={()=>add('prompt')}><Sparkles/></button><button title="导入项目" aria-label="导入项目" onClick={()=>json.current?.click()}><Upload/></button><div className={s.spacer}/><span>∞</span></nav>
|
||||
<section className={s.canvasArea}>{!doc.cards.length&&<div className={s.startPanel}><span>YOUR NEXT IDEA STARTS HERE</span><h2>给想法,一个无限的空间。</h2><p>双击画布添加节点,或选择一个起点。</p><div><button onClick={()=>add('text')}><Type size={19}/>灵感笔记</button><button onClick={()=>file.current?.click()}><ImagePlus size={19}/>参考图片</button><button onClick={()=>add('prompt')}><Sparkles size={19}/>创作提示词</button></div><button onClick={()=>{commit(example);select('');setPan({x:0,y:0});setZoom(.7)}}>从示例开始 ↗</button><a href="/studio/api" target="_blank" rel="noreferrer">连接你的 coding agent · 接入文档 ↗</a></div>}<div className={s.canvasTitle}><span className={s.eyebrow}>YOUR IDEAS, CONNECTED</span><h1>无限画布<span> / Infinite canvas</span></h1><p>从一个灵感,连接所有可能。</p></div>
|
||||
<div className={s.viewport} style={{backgroundPosition:`${pan.x}px ${pan.y}px`,backgroundSize:`${24*zoom*Math.max(1,2**Math.ceil(Math.log2(1/zoom)))}px ${24*zoom*Math.max(1,2**Math.ceil(Math.log2(1/zoom)))}px`}} ref={viewport} onDoubleClick={e=>{if(e.target===e.currentTarget){setMenu(null);add('text')}}} onContextMenu={e=>{e.preventDefault();const id=(e.target as HTMLElement).closest('[data-node-id]')?.getAttribute('data-node-id');select(id||'');setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-330)})}} onWheel={e=>{const target=e.target as HTMLElement;if(drag.current)return;if(target.closest('textarea,input,select'))return;if(e.ctrlKey||e.metaKey){scaleAt(zoom*Math.exp(-e.deltaY*.002),e.clientX,e.clientY)}else setPan(p=>({x:p.x-e.deltaX,y:p.y-e.deltaY}))}} onPointerDown={e=>{setMenu(null);setRefMenu('');if(e.target===e.currentTarget){setEditing('');select('')};if(e.target===e.currentTarget||(tool==='hand'&&!(e.target as HTMLElement).closest('input,textarea,button,select'))||e.button===1){e.currentTarget.setPointerCapture(e.pointerId);drag.current={id:'pan',x:e.clientX,y:e.clientY,ox:pan.x,oy:pan.y,before:doc}}}} onPointerMove={e=>{const d=drag.current;if(!d)return;if(d.id==='pan')setPan({x:d.ox+e.clientX-d.x,y:d.oy+e.clientY-d.y});else {if(!d.resize&&Math.hypot(e.clientX-d.x,e.clientY-d.y)<4)return;e.currentTarget.setPointerCapture(e.pointerId);setDoc({...d.before,cards:d.before.cards.map(c=>c.id===d.id?(d.resize?{...c,width:Math.max(260,Math.min(1200,d.ox+(e.clientX-d.x)/zoom)),height:Math.max(300,Math.min(1200,d.oy+(e.clientY-d.y)/zoom))}:{...c,x:d.ox+(e.clientX-d.x)/zoom,y:d.oy+(e.clientY-d.y)/zoom}):c)})}}} onPointerUp={e=>{const d=drag.current;if(d?.id==='pan'&&tool==='select'&&Math.hypot(e.clientX-d.x,e.clientY-d.y)<4){select('');setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-230)})}if(d&&d.id!=='pan'&&doc!==d.before){setPast(p=>[...p.slice(-29),d.before]);setFuture([])}drag.current=null}} onPointerCancel={()=>{if(drag.current?.id!=='pan'&&drag.current)setDoc(drag.current.before);drag.current=null}}>
|
||||
<div className={s.world} style={{transform:`translate(${pan.x}px,${pan.y}px) scale(${zoom})`}}><svg className={s.wires} aria-hidden="true">{doc.links.map(([a,b])=>{const from=doc.cards.find(c=>c.id===a),to=doc.cards.find(c=>c.id===b);if(!from||!to)return null;return <path key={a+b} d={`M ${from.x+(from.width||320)} ${from.y+(from.height||350)/2} C ${from.x+(from.width||320)+70} ${from.y+(from.height||350)/2},${to.x-45} ${to.y+(to.height||350)/2},${to.x} ${to.y+(to.height||350)/2}`}/>})}</svg>
|
||||
{doc.cards.map(c=><CanvasNodeView key={c.id} node={c} selected={selected===c.id} editing={editing===c.id&&composerTarget!==c.id} hand={tool==='hand'} onSelect={()=>selectNode(c.id)} onChooseReference={()=>{editNode(c.id);setComposerTarget(c.id);setPickerRequest(++pickerSequence.current)}} onEdit={()=>editNode(c.id)} onDrag={e=>{setMenu(null);if(c.id!==editing)setEditing('');drag.current={id:c.id,x:e.clientX,y:e.clientY,ox:c.x,oy:c.y,before:doc}}} onResize={e=>{viewport.current?.setPointerCapture(e.pointerId);select(c.id);drag.current={id:c.id,x:e.clientX,y:e.clientY,ox:c.width||320,oy:c.height||350,before:doc,resize:true}}} onChange={value=>change('text',value,c.id)} onRename={value=>change('title',value,c.id)} onStyle={style=>patchNode(c.id,{style})} onReference={e=>{select(c.id);setRefMenu(c.id);setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-230)})}} onMenu={e=>{select(c.id);setRefMenu('');setMenu({x:Math.min(e.clientX,window.innerWidth-250),y:Math.min(e.clientY,window.innerHeight-330)})}} onUpload={()=>{select(c.id);file.current?.click()}} onUpscale={()=>derive(c.id,'image','upscale')} onExpand={()=>patchNode(c.id,{width:Math.min(1200,(c.width||320)*1.5),height:Math.min(1200,(c.height||350)*1.3)})} onBeginEdit={beginEdit}/>)}
|
||||
|
||||
</div></div><div className={s.canvasBottom}><span role="status">● {status}</span><div className={s.controls}><button aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={16}/></button><button aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={16}/></button><i/><button aria-label="缩小" onClick={()=>scaleAt(zoom-.1)}><Minus size={16}/></button><span>{Math.round(zoom*100)}%</span><button aria-label="放大" onClick={()=>scaleAt(zoom+.1)}><Plus size={16}/></button><button aria-label="适应画布" onClick={fit}><Maximize size={16}/></button></div></div></section>
|
||||
{menu&&<div className={s.contextMenu} role="dialog" aria-label="画布操作" style={{left:Math.max(8,menu.x),top:Math.max(8,menu.y)}}><div className={s.menuTitle}>{refMenu?'引用该节点生成':active?active.title:'添加到画布'}<button aria-label="关闭画布操作" onClick={()=>setMenu(null)}>×</button></div>{refMenu?<>{(['text','image','script'] as const).map(kind=><button key={kind} onClick={()=>derive(refMenu,kind,kind==='script'?'script':'generate')}>{kind==='text'?'文本':kind==='image'?'图片':'脚本'}</button>)}</>:active?<><button onClick={()=>{editNode(active.id);setComposerTarget(active.id)}}>创作要求</button><button onClick={duplicate}>复制节点</button><button onClick={()=>{commit(removeCanvasNode(doc,selected));select('');setEditing('');setMenu(null)}}>删除节点</button><label>连接到<select value={link} onChange={e=>setLink(e.target.value)}><option value="">选择目标节点</option>{doc.cards.filter(c=>c.id!==selected).map(c=><option key={c.id} value={c.id}>{c.title}</option>)}</select></label><button disabled={!link} onClick={()=>{connect(selected,link);setLink('')}}>连接节点</button>{doc.links.filter(l=>l.includes(selected)).map(([a,b])=><button key={a+b} onClick={()=>commit({...doc,links:doc.links.filter(l=>l[0]!==a||l[1]!==b)})}>断开:{doc.cards.find(c=>c.id===(a===selected?b:a))?.title}</button>)}</>:<><button onClick={()=>{add('text');setMenu(null)}}>添加笔记</button><button onClick={()=>{add('image');setMenu(null)}}>添加图片</button><button onClick={()=>{add('script');setMenu(null)}}>添加脚本</button></>}</div>}</div>
|
||||
{active&&editing===active.id&&(active.kind!=='text'||composerTarget===active.id)&&<CanvasComposer pickerRequest={pickerRequest} key={active.id} node={active} nodes={doc.cards} references={referencedNodes(doc,active.id)} onChange={value=>change('instruction',value,active.id)} onRename={value=>change('title',value,active.id)} onBeginEdit={beginEdit} onUpload={()=>file.current?.click()} onAddReference={id=>connect(id,active.id)} onRemoveReference={id=>commit({...doc,links:doc.links.filter(([from,to])=>from!==id||to!==active.id)})} onQueue={()=>void agent.current?.queue(active.id)} onExport={()=>exportTask(active.id)} onClose={()=>setEditing('')} feedback={taskFeedback}/>}
|
||||
<input hidden ref={file} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;if(!['image/png','image/jpeg','image/webp'].includes(f.type)||f.size>2000000){setStatus('请选择 2MB 以内的 PNG、JPEG 或 WebP');return}const reader=new FileReader();reader.onload=()=>{const image=String(reader.result);if(active?.kind==='image')commit({...doc,cards:doc.cards.map(c=>c.id===selected?{...c,image}:c)});else add('image',image)};reader.readAsDataURL(f)}}/>
|
||||
<input hidden ref={json} type="file" accept="application/json,.json" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;try{if(f.size>15000000)throw Error();const d=parseCanvasDocument(await f.text());commit(d);select(d.cards[0]?.id||'');setPan({x:0,y:0});setStatus('项目已导入')}catch{setStatus('无法导入:项目格式错误或文件过大')}}}/>
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type {GetServerSideProps} from 'next';
|
||||
import {readDesign} from '../../../studio/lib/design-server';
|
||||
import {designUrl} from '../../../studio/lib/native-layout';
|
||||
export default function DesignPage(){return null}
|
||||
export const getServerSideProps:GetServerSideProps=async({params,req,res})=>{
|
||||
res.setHeader('Cache-Control','private, no-store');
|
||||
const design=await readDesign(params?.id,req);
|
||||
if(!design)return {notFound:true};
|
||||
// The unified application has no basePath; keep the full historical URL.
|
||||
return {redirect:{destination:designUrl(design.layoutId,design.id),permanent:false}};
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type {GetStaticPaths,GetStaticProps} from 'next';
|
||||
import Head from 'next/head';
|
||||
import Link from 'next/link';
|
||||
import {LayoutSelection} from '../../../studio/components/LayoutSelection';
|
||||
import {tutorialPost} from '../../../studio/content/tool-links';
|
||||
import {TemplateTrial} from '../../../studio/components/TemplateTrial';
|
||||
import {ideas,type Idea} from '../../../studio/content/ideas';
|
||||
export default function IdeaPage({idea}:{idea:Idea}){if(idea.tool==='layout-selection')return <LayoutSelection/>;if(idea.template)return <TemplateTrial idea={idea}/>;return <main className="editor"><Head><title>{idea.title} · 创作站</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head><header><a href={tutorialPost}>← 啡跃使用教程</a><a href={'/studio/api/export/'+idea.slug}>导出内容包 ↓</a><a href={'/studio/api/export/'+idea.slug+'?format=markdown'}>Markdown ↓</a><button onClick={()=>window.print()}>打印 / PDF</button></header><h1>{idea.title}</h1><p>{idea.summary}</p><div className="slides">{idea.slides.map((s,i)=><article className="slide" key={i} style={{background:s.color}}><small>ENDOLEAP / {String(i+1).padStart(2,'0')}</small><h2>{s.heading}</h2><p>{s.body}</p><footer>记录灵感 · 自由表达</footer></article>)}</div></main>}
|
||||
export const getStaticPaths:GetStaticPaths=async()=>({paths:ideas.map(i=>({params:{slug:i.slug}})),fallback:false});
|
||||
export const getStaticProps:GetStaticProps=async({params})=>{const idea=ideas.find(i=>i.slug===params?.slug);return idea?{props:{idea}}:{notFound:true}};
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {GetServerSideProps} from 'next';
|
||||
import {NativeResult} from '../../../studio/components/NativeResult';
|
||||
import type {Layout} from '../../../studio/lib/layout-parameters';
|
||||
import fixedLayouts from '../../../studio/content/templates/layouts.json';
|
||||
import standardLayout from '../../../studio/content/standard-layout.json';
|
||||
const layouts=[...fixedLayouts,standardLayout];
|
||||
import {nativeLayout,designUrl} from '../../../studio/lib/native-layout';
|
||||
import {readDesign} from '../../../studio/lib/design-server';
|
||||
export default function LayoutPage({layout}:{layout:Layout}){return <NativeResult layout={layout} design={null}/>}
|
||||
export const getServerSideProps:GetServerSideProps<{layout:Layout}>=async({params,query,req,res})=>{
|
||||
res.setHeader('Cache-Control','private, no-store');
|
||||
const layout=layouts.find(l=>l.id===params?.layoutId);
|
||||
if(!layout)return {notFound:true};
|
||||
if(query.id!==undefined){
|
||||
const design=await readDesign(query.id,req);
|
||||
if(!design||design.layoutId!==layout.id)return {notFound:true};
|
||||
return {redirect:{destination:designUrl(design.layoutId,design.id).slice('/studio'.length),permanent:false}};
|
||||
}
|
||||
return {props:{layout:nativeLayout(layout)}};
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import type {GetServerSideProps} from 'next';
|
||||
import {NativeSeries} from '../../studio/components/NativeSeries';
|
||||
import {NativeResult} from '../../studio/components/NativeResult';
|
||||
import fixedLayouts from '../../studio/content/templates/layouts.json';
|
||||
import standardLayout from '../../studio/content/standard-layout.json';
|
||||
import {readDesign} from '../../studio/lib/design-server';
|
||||
import {nativeLayout,type Design} from '../../studio/lib/native-layout';
|
||||
import type {Layout} from '../../studio/lib/layout-parameters';
|
||||
|
||||
type Props={layout:Layout;design:Design;page:number|null;quality:boolean};
|
||||
export default function TemplateLayout(props:Props){return props.design.document?<NativeSeries design={props.design} page={props.page} quality={props.quality}/>:<NativeResult {...props}/>}
|
||||
export const getServerSideProps:GetServerSideProps<Props>=async({query,req,res})=>{
|
||||
res.setHeader('Cache-Control','private, no-store');
|
||||
const design=await readDesign(query.id,req);
|
||||
if(!design)return {notFound:true};
|
||||
const layout=[standardLayout,...fixedLayouts].find(l=>l.id===design.layoutId);
|
||||
if(!layout)return {notFound:true};
|
||||
const page=query.page===undefined?null:Number(query.page);
|
||||
if(page!==null&&(!Number.isInteger(page)||page<1||page>(design.document?.pages.length||1)))return {notFound:true};
|
||||
return {props:{layout:nativeLayout(layout),design,page,quality:query.export==='1'}};
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
/** The approved mark is copied from @endoleap/brand during the remote build. */
|
||||
export function Brand({ compact = false }: { compact?: boolean }) {
|
||||
return <span className="endoleap-brand"><img src="/studio/brand/logo-light.svg" className="endoleap-mark endoleap-mark-light" alt="" width={32} height={32}/><img src="/studio/brand/logo-dark.svg" className="endoleap-mark endoleap-mark-dark" alt="" width={32} height={32}/><span className="endoleap-wordmark">啡跃{!compact && <small>Endoleap</small>}</span></span>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {useId} from 'react';
|
||||
import type {Layout,Parameters} from '../lib/layout-parameters';
|
||||
export type LayerLayout=Omit<Layout,'elements'>&{source:string;background:string;tutorialUrl:string;sourceSha256:string;elements:(Layout['elements'][number]&{raster:string;shape?:string})[]};
|
||||
export function LayoutCanvas({layout,params,guides=false,imageSources={}}:{layout:LayerLayout;params:Parameters;guides?:boolean;imageSources?:Record<string,string>}){
|
||||
const uid=useId().replace(/[^a-z0-9]/gi,''),W=layout.width,H=layout.height,unchanged=!params.paper&&!Object.keys(params.texts).length&&!Object.keys(params.images).length&&!Object.keys(params.decorations).length;
|
||||
return <svg xmlns="http://www.w3.org/2000/svg" viewBox={`0 0 ${W} ${H}`} width={W*6} height={H*6} role="img" aria-label={layout.id+' '+layout.name} data-layout-id={layout.id} style={{width:'100%',height:'auto',display:'block'}}><title>{layout.id+' · '+layout.name}</title><desc>对应原图的文字、图位和装饰。未替换构件保留原始低分辨率图层;替换文字为 SVG 文字。</desc>{unchanged?<image href={layout.source} width={W} height={H}/>:<><rect width={W} height={H} fill={params.paper||'#f4f2eb'}/><image href={layout.background} width={W} height={H}/>{params.paper&&<><defs><mask id={uid+'paper'}><image href={layout.background} width={W} height={H}/></mask></defs><rect width={W} height={H} fill={params.paper} mask={'url(#'+uid+'paper)'}/></>}{['image','decoration','text'].flatMap(kind=>layout.elements.filter(s=>s.kind===kind).map(s=>{
|
||||
const [x,y,w,h]=s.box,id=uid+s.id,t=params.texts[s.id],im=params.images[s.id],d=params.decorations[s.id];
|
||||
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/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>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {referencePreview} from '../lib/layout-images-client';
|
||||
import {useState} from 'react';
|
||||
import Head from 'next/head';
|
||||
import {SourceCover,selections,type CoverValues} from './SourceCover';
|
||||
import {tutorialPost} from '../content/tool-links';
|
||||
export function LayoutSelection(){
|
||||
const [active,setActive]=useState(0),[values,setValues]=useState<CoverValues[]>(selections.map(l=>({fields:Object.fromEntries(Object.entries(l.fields).filter(([,v])=>v!==undefined)) as Record<string,string>,color:'#83918a',accent:'#c3cec5'}))),[guides,setGuides]=useState(false),[status,setStatus]=useState('');
|
||||
const layout=selections[active],current=values[active];
|
||||
function update(patch:Partial<CoverValues>){setValues(old=>old.map((v,i)=>i===active?{...v,...patch}:v));}
|
||||
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>三种排版 · 啡跃 Endoleap 工具</title></Head><header className="trial-nav"><a href={tutorialPost}>← 啡跃使用教程</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>;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { ThemeToggle } from "./ThemeToggle";
|
||||
import { Brand } from "./Brand";
|
||||
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,LayerValue,AddedSlot} from '../lib/layout-parameters';
|
||||
import {parameters} from '../lib/layout-parameters';
|
||||
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}){
|
||||
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>;
|
||||
}
|
||||
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[]>([]),[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]);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,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){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)}
|
||||
}
|
||||
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 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>
|
||||
{editing&&<header className="workbench-top"><a href="/explore/8eb8c76500580f7a4b56ba3c" aria-label="返回目录"><ArrowLeft size={18}/></a><a href="/workspace" className="studio-mark"><Brand compact/></a><ThemeToggle/><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} 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>
|
||||
</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}){
|
||||
return <main className="native-layout-page"><Head><title>{design?.name||layout.name} · Prompt</title></Head><NativeArtwork layout={layout} design={design}/></main>;
|
||||
}
|
||||
export function NativeArtwork({layout,design,quality=false}:{layout:Layout;design:Design|null;quality?:boolean}){
|
||||
const params:Parameters=design?.parameters||emptyParameters();
|
||||
const elements=[...layout.elements,...(params.added||[])];
|
||||
return <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}`,height:quality?Math.round(1080*layout.height/layout.width):undefined,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,"Noto Serif CJK SC","Songti SC",serif':t?.fontFamily==='mono'?'"Noto Sans Mono CJK SC",monospace':t?.fontFamily==='sans'?'Arial,"Noto Sans CJK SC","PingFang SC","Microsoft YaHei",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:quality?'2160':'960',...(quality?{profile:'export'}:{})})} srcSet={quality?undefined:[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>;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import Head from 'next/head';
|
||||
import fixed from '../content/templates/layouts.json';
|
||||
import standard from '../content/standard-layout.json';
|
||||
import {pageParameters} from '../lib/series';
|
||||
import type {Design} from '../lib/native-layout';
|
||||
import {NativeArtwork} from './NativeResult';
|
||||
export function NativeSeries({design,page,quality}:{design:Design;page:number|null;quality:boolean}){
|
||||
const doc=design.document!;
|
||||
return <main className={'native-layout-page native-series'+(quality?' native-export':'')} data-style-version={doc.style.version} data-revision={design.revision}>
|
||||
<Head><title>{design.name} · {doc.pages.length}页</title><meta name="description" content={doc.brief.intent}/></Head>
|
||||
{doc.pages.map((p,index)=>{if(page!==null&&page!==index+1)return null;const layout=[standard,...fixed].find(l=>l.id===p.layoutId)!;return <div className="series-page" key={p.key} data-page={index+1} data-page-key={p.key} data-page-role={p.role}><NativeArtwork layout={layout} quality={quality} design={{...design,name:design.name+' · '+(index+1),layoutId:p.layoutId,parameters:pageParameters(doc,p,layout)}}/>{!quality&&<p className="series-page-number">{String(index+1).padStart(2,'0')} / {doc.pages.length}</p>}</div>})}
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type {Idea,Slide} from '../content/ideas';
|
||||
type Template=NonNullable<Idea['template']>;
|
||||
export function Ref17Cover({template,slide,masthead=template.masthead,guides=false}:{template:Template;slide:Slide;masthead?:string[];guides?:boolean}){
|
||||
const scale=10,W=template.width*scale,H=template.height*scale;
|
||||
const slot=(id:string)=>{const s=template.slots.find(s=>s.id===id);if(!s)throw Error('Missing source slot '+id);return s.box.map(v=>v*scale)};
|
||||
const [mx,my,mw,mh]=slot('I01'),[cx,cy,cw,ch]=slot('I02'),[dx,dy,dw,dh]=slot('D02'),[bx,by,bw,bh]=slot('D03'),[lx,ly,lw,lh]=slot('D01');
|
||||
const [aX,aY,aW,aH]=slot('T01'),[bX,bY,bW,bH]=slot('T02'),[tX,tY,tW,tH]=slot('T03'),[sX,sY,sW,sH]=slot('T04');
|
||||
const first=masthead[0]||'STUDY',second=masthead[1]||'Skills',body=slide.body.split('\n').slice(0,3);
|
||||
const font1=Math.min(aH*1.2,aW/Math.max(1,first.length*.72)),font2=Math.min(bH,bW/Math.max(1,second.length*.59));
|
||||
const titleSize=Math.min(tH*.72,tW/Math.max(1,Array.from(slide.heading).length*1.06));
|
||||
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>
|
||||
<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>
|
||||
<g data-slot="D02" fill="none" stroke={template.ink} strokeWidth="2" opacity=".75"><rect x={dx+1} y={dy+9} width={dw-2} height={dh-18} rx={(dh-18)/2}/><path d={`M${dx+19} ${dy+dh/2}H${dx+dw-19}`}/></g>
|
||||
<g data-slot="D01"><path d={`M${lx} ${ly+lh/2}H${lx+lw}`} stroke={template.ink} strokeWidth="2"/></g>
|
||||
<g data-slot="D03"><rect x={bx} y={by} width={bw} height={bh} fill={accent}/></g>
|
||||
<g fill={template.ink} fontFamily="Georgia, 'Times New Roman', serif" fontWeight="400">
|
||||
<text data-slot="T01" x={aX} y={aY+aH*.9} fontSize={font1} letterSpacing={-font1*.035}>{first}</text>
|
||||
<text data-slot="T02" x={bX} y={bY+bH*.76} fontSize={font2} letterSpacing={-font2*.045}>{second}</text>
|
||||
</g>
|
||||
<text data-slot="T03" x={tX} y={tY+tH*.8} fill={template.ink} fontFamily="'PingFang SC', 'Microsoft YaHei', sans-serif" fontWeight="600" fontSize={titleSize} letterSpacing={-titleSize*.025}>{slide.heading}</text>
|
||||
<g data-slot="T04" fill={template.ink} fontFamily="Arial, 'PingFang SC', sans-serif">
|
||||
<text x={sX} y={sY+32} fontSize="22" letterSpacing="2">{slide.kicker||'TEMPLATE / XX'}</text>
|
||||
{body.map((line,i)=><text key={i} x={sX} y={sY+135+i*58} fontSize={bodySize}>{line}</text>)}
|
||||
<text x={sX} y={sY+sH-62} fontSize="19" letterSpacing="1">CONTENT</text><text x={sX} y={sY+sH-26} fontSize="19" letterSpacing="1">PLACEHOLDER</text>
|
||||
</g>
|
||||
{guides&&<g aria-hidden="true" fontFamily="Arial,sans-serif">{template.slots.map(s=>{const[x,y,w,h]=s.box.map(v=>v*scale),color=({text:'#2c64d8',image:'#d36b30',decoration:'#08875d'} as Record<string,string>)[s.kind]||'#666';return <g key={s.id}><rect x={x} y={y} width={w} height={h} fill={color} fillOpacity=".04" stroke={color} strokeWidth="2" strokeDasharray="8 5"/><rect x={x} y={y} width="66" height="29" fill={color}/><text x={x+6} y={y+22} fontSize="24" fill="white">{s.id}</text></g>})}</g>}
|
||||
</svg>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {useId} from 'react';
|
||||
import selections from '../content/templates/selection.json';
|
||||
export type SourceLayout=typeof selections[number];
|
||||
export type CoverValues={fields:Record<string,string>;color:string;accent:string};
|
||||
export {selections};
|
||||
export function SourceCover({layout,values,guides=false}:{layout:SourceLayout;values:CoverValues;guides?:boolean}){
|
||||
const uid=useId().replace(/:/g,''),W=layout.width*10,H=layout.height*10;
|
||||
return <svg xmlns="http://www.w3.org/2000/svg" viewBox={`0 0 ${W} ${H}`} width={W} height={H} role="img" aria-label={layout.id+' '+layout.name} data-layout-id={layout.id} style={{display:'block',width:'100%',height:'auto'}}>
|
||||
<title>{layout.name+' · 封面试版'}</title><desc>文字为可编辑占位,图位和装饰按原图构件重建为矢量,原始分层数据保留在模板 JSON 中。来源 {layout.tutorialUrl}</desc><rect width={W} height={H} fill="#f4f2eb"/>
|
||||
{['image','decoration','text'].flatMap(kind=>layout.slots.filter(s=>s.kind===kind).map(s=>{
|
||||
const [x,y,w,h]=s.box.map(n=>n*10);
|
||||
if(kind==='image')return <g data-slot={s.id} key={s.id}>{layout.id==='ref-07'?<ellipse cx={x+w/2} cy={y+h/2} rx={w/2} ry={h/2} fill={values.color}/>:<rect x={x} y={y} width={w} height={h} fill={s.id==='I01'?values.color:values.accent}/>}</g>;
|
||||
if(kind==='decoration'){
|
||||
if(layout.id==='ref-07')return <g data-slot={s.id} key={s.id} fill="none" stroke="#b8c2b8" strokeWidth="9"><defs><clipPath id={uid+s.id}><rect x={x} y={y} width={w} height={h}/></clipPath></defs><g clipPath={'url(#'+uid+s.id+')'}>{[550,595,640,685,730,775,820].map(r=><ellipse key={r} cx="640" cy="560" rx={r} ry={r*1.02}/>)}</g></g>;
|
||||
if(layout.id==='ref-26'&&s.id==='D04')return <path data-slot={s.id} key={s.id} d={`M${x} ${y+h} C${x+w*.28} ${y+h*.93} ${x+w*.43} ${y+h*.64} ${x+w*.30} ${y+h*.56} C${x+w*.16} ${y+h*.47} ${x+w*.19} ${y+h*.89} ${x+w*.38} ${y+h*.68} S${x+w*.69} ${y+h*.52} ${x+w*.65} ${y+h*.34} C${x+w*.59} ${y+h*.15} ${x+w*.52} ${y+h*.48} ${x+w*.75} ${y+h*.37} S${x+w*.90} ${y+h*.15} ${x+w} ${y}`} fill="none" stroke="#526459" strokeWidth="4"/>;
|
||||
return <path data-slot={s.id} key={s.id} d={`M${x} ${y+h/2}H${x+w}`} stroke="#526459" strokeWidth={layout.id==='ref-26'&&s.id==='D03'?4:2}/>;
|
||||
}
|
||||
const text=values.fields[s.id]||'',lines=text.split('\n').slice(0,4),length=(str:string)=>Array.from(str).reduce((sum,c)=>sum+(/[\u3400-\u9fff]/.test(c)?1:.6),0),size=Math.min(h/(lines.length*1.25),w/Math.max(1,...lines.map(length))*.94);
|
||||
if(s.direction==='vertical'){const letters=Array.from(text.replace(/\n/g,'')),font=Math.min(w*.88,h/Math.max(1,letters.length));return <g data-slot={s.id} key={s.id} fill="#26362f" fontFamily="'PingFang SC',sans-serif">{letters.map((c,i)=><text key={i} x={x+w/2} y={y+font*(i+.85)} textAnchor="middle" fontSize={font}>{c}</text>)}</g>}
|
||||
if(s.direction==='curved'){
|
||||
const letters=Array.from(text),font=Math.min(36,w/Math.max(1,letters.length*.9));
|
||||
return <g data-slot={s.id} key={s.id} fill="#26362f" fontFamily="Arial,sans-serif">{letters.map((letter,i)=>{const t=.08+.84*(i+.5)/letters.length,px=x+w*t,py=y+3.9*h*t*(1-t),angle=Math.atan(3.9*h*(1-2*t)/w)*180/Math.PI;return <text key={i} transform={`translate(${px} ${py}) rotate(${angle})`} fontSize={font} textAnchor="middle">{letter}</text>})}</g>;
|
||||
}
|
||||
|
||||
return <g data-slot={s.id} key={s.id} fill="#26362f" fontFamily={h>100?"Georgia,'PingFang SC',serif":"Arial,'PingFang SC',sans-serif"}>{lines.map((line,i)=><text key={i} x={x} y={y+size*(.88+i*1.25)} fontSize={size}>{line}</text>)}</g>;
|
||||
}))}
|
||||
{guides&&<g aria-hidden="true" fontFamily="Arial,sans-serif">{layout.slots.map(s=>{const[x,y,w,h]=s.box.map(n=>n*10),color=({text:'#2c64d8',image:'#d36b30',decoration:'#08875d'} as Record<string,string>)[s.kind];return <g key={s.id}><rect x={x} y={y} width={w} height={h} stroke={color} strokeWidth="2" fill="none"/><rect x={x} y={y} width="66" height="29" fill={color}/><text x={x+4} y={y+22} fontSize="24" fill="white">{s.id}</text></g>})}</g>}
|
||||
</svg>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {referencePreview} from '../lib/layout-images-client';
|
||||
import {useState} from 'react';
|
||||
import Head from 'next/head';
|
||||
import {tutorialPost} from '../content/tool-links';
|
||||
import {ideaMarkdown,type Idea,type Slide} from '../content/ideas';
|
||||
import {Ref17Cover} from './Ref17Cover';
|
||||
export function TemplateTrial({idea}:{idea:Idea}){
|
||||
const template=idea.template!;
|
||||
const [slides,setSlides]=useState<Slide[]>(idea.slides),[active,setActive]=useState(0),[masthead,setMasthead]=useState(template.masthead),[guides,setGuides]=useState(false),[notice,setNotice]=useState('');
|
||||
const selected=slides[active],current={...idea,slides,template:{...template,masthead}};
|
||||
const update=(patch:Partial<Slide>)=>setSlides(old=>old.map((slide,i)=>i===active?{...slide,...patch}:slide));
|
||||
const download=(text:string,type:string,name:string)=>{const url=URL.createObjectURL(new Blob([text],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),500)};
|
||||
async function exportSvg(){await document.fonts.ready;const svg=document.querySelector(`[data-proof="${selected.key}"] svg`);if(!svg)return;download(new XMLSerializer().serializeToString(svg),'image/svg+xml',`ref-17-${selected.key}.svg`);setNotice('已下载当前封面 SVG,可继续编辑文字与图形。')}
|
||||
const reset=()=>{setSlides(idea.slides);setMasthead(template.masthead);setGuides(false);setNotice('已恢复初始试版。')};
|
||||
return <main className="template-trial"><Head><title>{idea.title} · 啡跃 Endoleap</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head>
|
||||
<header className="trial-nav"><a href={tutorialPost}>← 啡跃使用教程</a><span>STUDIO / TEMPLATE PROOF</span><a href={template.tutorialUrl} target="_blank" rel="noreferrer">排版教程 ↗</a></header>
|
||||
<section className="trial-intro"><div><small>REF-17 · 同一母版 / 四张试版</small><h1>先试封面,再填内容。</h1><p>英文刊头、圆形叠标、左下主图与右侧窄栏保持同一套坐标。三组合集先用主题占位,暂不放入具体 Skills。</p></div><div className="trial-source"><b>01 母版</b><span>02 笔记复习</span><span>03 教学资料</span><span>04 英语学习</span></div></section>
|
||||
<div className="trial-workspace"><aside className="trial-controls"><h2>试一试</h2><label>当前封面<select value={active} onChange={e=>{setActive(Number(e.target.value));setNotice('')}}>{slides.map((s,i)=><option value={i} key={s.key}>{s.label}</option>)}</select></label>
|
||||
<fieldset><legend>共享英文刊头</legend><label>第一行<input value={masthead[0]} maxLength={8} onChange={e=>setMasthead([e.target.value.toUpperCase().replace(/[^A-Z ]/g,''),masthead[1]])}/></label><label>第二行<input value={masthead[1]} maxLength={8} onChange={e=>setMasthead([masthead[0],e.target.value.replace(/[^A-Za-z ]/g,'')])}/></label></fieldset>
|
||||
<label>本张标题 <small>建议 4–6 字</small><input maxLength={6} value={selected.heading} onChange={e=>update({heading:e.target.value})}/></label>
|
||||
<label>右侧简介 <small>最多三行</small><textarea rows={3} value={selected.body} onChange={e=>update({body:e.target.value.split('\n').slice(0,3).join('\n')})}/></label>
|
||||
<div className="trial-colors"><label>主图色块<input type="color" value={selected.color} onChange={e=>update({color:e.target.value})}/></label><label>圆形与贴条<input type="color" value={selected.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={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={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,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
export function ThemeToggle() {
|
||||
const [dark, setDark] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => { const sync = () => setDark(document.documentElement.dataset.mode === 'dark'); sync(); setReady(true); window.addEventListener('endoleap-theme', sync); return () => window.removeEventListener('endoleap-theme', sync); }, []);
|
||||
return <button type="button" data-theme-ready={ready} className="endoleap-theme-toggle" aria-label="切换明暗主题" title={dark ? '切换浅色模式' : '切换深色模式'} onClick={() => { const mode = document.documentElement.dataset.mode === 'dark' ? 'light' : 'dark'; const scope = document.documentElement.dataset.theme?.startsWith('canvas-') ? 'canvas' : 'home'; document.documentElement.dataset.mode = mode; document.documentElement.dataset.theme = `${scope}-${mode}`; try { localStorage.setItem('endoleap.theme', mode); } catch {} window.dispatchEvent(new Event('endoleap-theme')); }}>◐<span>{dark ? '浅色' : '深色'}</span></button>;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {forwardRef,useEffect,useImperativeHandle,useRef,useState} from 'react';
|
||||
import {parseCanvasDocument,type CanvasDocument} from '../../lib/canvas-document';
|
||||
import s from '../../styles/canvas-agent.module.css';
|
||||
type Task={id:string;targetId:string;status:'queued'|'running'|'succeeded'|'failed';error?:string};
|
||||
type State={id:string;name:string;revision:number;document:CanvasDocument;tasks:Task[]};
|
||||
type LinkState={expiresAt:string;lastSeenAt:string|null};
|
||||
export type CanvasAgentHandle={queue:(target:string)=>Promise<void>};
|
||||
type Props={document:CanvasDocument;email:string;onLoad:(document:CanvasDocument)=>void;onFeedback:(text:string)=>void};
|
||||
async function api(path:string,method='GET',body?:unknown){const r=await fetch('/api/canvases'+path,{method,headers:body?{'Content-Type':'application/json'}:undefined,...(body?{body:JSON.stringify(body)}:{})});const data=await r.json();if(!r.ok)throw Error(data.error||'在线画布暂时不可用');return data;}
|
||||
const names={queued:'等待 Agent',running:'Agent 正在处理',succeeded:'已完成',failed:'已结束'};
|
||||
export default forwardRef<CanvasAgentHandle,Props>(function CanvasAgentPanel(p,ref){
|
||||
const [open,setOpen]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState(''),[remote,setRemote]=useState<State|null>(null),[pending,setPending]=useState<State|null>(null),[connection,setConnection]=useState<LinkState|null>(null),[credential,setCredential]=useState(''),[items,setItems]=useState<{id:string;name:string}[]>([]);
|
||||
const live=useRef(p.document),synced=useRef(''),current=useRef<State|null>(null),locked=useRef(false),account=useRef(p.email),generation=useRef(0),credentialField=useRef<HTMLTextAreaElement>(null);
|
||||
live.current=p.document;account.current=p.email;
|
||||
function update(state:State){current.current=state;setRemote(state);}
|
||||
function apply(state:State){state={...state,document:parseCanvasDocument(state.document)};synced.current=JSON.stringify(state.document);update(state);setPending(null);p.onLoad(state.document);}
|
||||
async function run(action:()=>Promise<void>){if(locked.current)return;locked.current=true;setBusy(true);try{await action()}catch(e){const text=e instanceof Error?e.message:'操作失败';setMessage(text);p.onFeedback(text)}finally{locked.current=false;setBusy(false)}}
|
||||
useEffect(()=>{generation.current++;current.current=null;synced.current='';setRemote(null);setPending(null);setConnection(null);setCredential('');setItems([]);if(!p.email)return;const epoch=generation.current;void api('').then(data=>{if(epoch===generation.current)setItems(data.canvases)}).catch(()=>{});},[p.email]);
|
||||
useEffect(()=>{if(!remote||!p.email)return;const id=remote.id,epoch=generation.current;let cancelled=false;const poll=async()=>{try{const state:State=await api('/'+id);if(cancelled||epoch!==generation.current||current.current?.id!==id||locked.current)return;if(state.revision!==current.current.revision){if(JSON.stringify(live.current)===synced.current){apply(state);setMessage('已同步 Agent 的画布更新')}else{setPending(state);setMessage('在线画布有更新,请选择要保留的版本')}}else update(state);const link=await api('/'+id+'/link');if(!cancelled&&epoch===generation.current)setConnection(link.link)}catch(e){if(!cancelled)setMessage(e instanceof Error?e.message:'同步失败')}};void poll();const timer=setInterval(()=>void poll(),5000);return()=>{cancelled=true;clearInterval(timer)};},[remote?.id,p.email]);
|
||||
async function save():Promise<State>{if(!account.current)throw Error('请先登录邮箱账户');if(pending)throw Error('请先处理在线版本冲突');const doc=live.current,serialized=JSON.stringify(doc),old=current.current;const state:State=old?serialized===synced.current?old:await api('/'+old.id,'PUT',{revision:old.revision,document:doc}):await api('','POST',{document:doc,name:'灵感画布 '+new Date().toLocaleDateString()});if(account.current!==p.email)throw Error('账户已切换,请重新连接');synced.current=serialized;update(state);setMessage('已保存在线画布');return state;}
|
||||
useImperativeHandle(ref,()=>({queue:async target=>{setOpen(true);await run(async()=>{const state=await save();if(JSON.stringify(live.current)!==synced.current)throw Error('画布刚有修改,请重新派发任务');const task:Task=await api('/'+state.id+'/tasks','POST',{revision:state.revision,targetId:target});if(account.current!==p.email)return;update({...state,tasks:[task,...state.tasks]});setMessage('任务已创建,等待你的 coding agent 领取');p.onFeedback('任务已创建,等待 Agent')})}}));
|
||||
async function connect(){const state=await save(),link=await api('/'+state.id+'/link','POST',{});if(account.current!==p.email)return;setConnection({expiresAt:link.expiresAt,lastSeenAt:null});setCredential(JSON.stringify({canvasUrl:location.origin+'/api/canvases/'+state.id,authorization:'Bearer '+link.token,documentation:location.origin+link.documentation,expiresAt:link.expiresAt},null,2));setMessage('连接凭据已生成,有效期 1 小时');}
|
||||
async function copyCredential(){
|
||||
if(navigator.clipboard?.writeText){try{await navigator.clipboard.writeText(credential);setMessage('凭据已复制');return}catch{}}
|
||||
const field=credentialField.current;if(!field)return;field.focus();field.select();
|
||||
let copied=false;try{copied=document.execCommand('copy')}catch{}
|
||||
setMessage(copied?'凭据已复制':'已选中凭据,请按 Ctrl+C 或 ⌘C 复制');
|
||||
}
|
||||
const dirty=!!remote&&JSON.stringify(p.document)!==synced.current;
|
||||
return <div className={s.root}><button onClick={()=>setOpen(v=>!v)} aria-expanded={open}>Agent{remote?' · 在线画布':''}</button>{open&&<section className={s.panel} aria-label="Agent 连接"><header><strong>你的 coding agent</strong><button aria-label="关闭 Agent 连接" onClick={()=>setOpen(false)}>×</button></header>{!p.email?<a href="/account">登录后连接在线画布 ↗</a>:<>
|
||||
<div className={s.actions}><button disabled={busy||!!pending} onClick={()=>void run(async()=>{await save()})}>{remote?(dirty?'保存修改':'已同步'):'保存为在线画布'}</button><button disabled={busy||!!pending} onClick={()=>void run(connect)}>生成连接凭据</button>{connection&&<button disabled={busy} onClick={()=>void run(async()=>{await api('/'+current.current!.id+'/link','DELETE',{});setConnection(null);setCredential('');setMessage('Agent 访问已撤销')})}>撤销连接</button>}</div>
|
||||
{!remote&&<label>打开在线画布<select aria-label="打开在线画布" defaultValue="" disabled={busy} onChange={e=>{const id=e.target.value;if(id)void run(async()=>{const state:State=await api('/'+id);parseCanvasDocument(state.document);setPending(state);setMessage('加载在线画布将替换当前草稿,请先导出需要保留的内容')})}}><option value="">选择画布</option>{items.map(item=><option value={item.id} key={item.id}>{item.name} · {item.id.slice(0,8)}</option>)}</select></label>}
|
||||
{connection&&<small>{connection.lastSeenAt?'Agent 最近访问:'+new Date(connection.lastSeenAt).toLocaleTimeString():'等待 Agent 首次访问'} · 到期 {new Date(connection.expiresAt).toLocaleTimeString()}</small>}
|
||||
{credential&&<><textarea ref={credentialField} aria-label="Agent 连接凭据" readOnly value={credential}/><button onClick={()=>void copyCredential()}>复制给 coding agent</button></>}
|
||||
{pending&&<div className={s.conflict}><button disabled={busy} onClick={()=>{apply(pending);setMessage('已载入在线版本')}}>载入在线版本</button><button disabled={busy} onClick={()=>{setPending(null);current.current=null;setRemote(null);synced.current='';setConnection(null);setCredential('');setMessage('已保留本机草稿,可另存为新画布')}}>保留草稿并断开</button></div>}
|
||||
{!!remote?.tasks.length&&<ul aria-label="画布任务">{remote.tasks.slice(0,8).map(task=><li key={task.id}><span>{p.document.cards.find(n=>n.id===task.targetId)?.title||'已移除节点'} · {names[task.status]}</span>{task.error&&<small>{task.error}</small>}{['queued','running'].includes(task.status)&&<button disabled={busy} onClick={()=>void run(async()=>{await api('/'+remote.id+'/tasks/'+task.id,'PATCH',{status:'failed',error:'用户结束任务'});setMessage('任务已结束,可修改后重新派发')})}>结束任务</button>}</li>)}</ul>}
|
||||
</>}<p role="status">{message}</p><a href="/api/canvases?agent_mode=True" target="_blank" rel="noreferrer">接入文档 ↗</a></section>}</div>
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {ImagePlus,FileText,Plus,X,Maximize,Download,ArrowUp} from 'lucide-react';
|
||||
import type {CanvasNode} from '../../lib/canvas-document';
|
||||
import s from '../../styles/canvas-composer.module.css';
|
||||
type Props={pickerRequest:number;feedback:string;node:CanvasNode;nodes:CanvasNode[];references:CanvasNode[];onChange:(text:string)=>void;onRename:(title:string)=>void;onBeginEdit:()=>void;onUpload:()=>void;onAddReference:(id:string)=>void;onRemoveReference:(id:string)=>void;onQueue:()=>void;onExport:()=>void;onClose:()=>void};
|
||||
export default function CanvasComposer(p:Props){const [expanded,expand]=useState(false),[choosing,choose]=useState(false);useEffect(()=>{if(p.pickerRequest)choose(true)},[p.pickerRequest]);return <section className={s.composer} data-expanded={expanded} aria-label="节点编辑器"><header><span>{p.node.kind==='image'?<ImagePlus size={16}/>:<FileText size={16}/>} <input aria-label="节点名称" maxLength={200} value={p.node.title} onFocus={p.onBeginEdit} onChange={e=>p.onRename(e.target.value)}/></span><div>{p.node.kind==='image'&&<button onClick={p.onUpload}><Plus size={15}/>上传图片</button>}<button aria-expanded={choosing} onClick={()=>choose(v=>!v)}><Plus size={15}/>画布参考</button><button aria-label="展开编辑器" aria-pressed={expanded} onClick={()=>expand(v=>!v)}><Maximize size={16}/></button><button aria-label="关闭节点编辑器" onClick={p.onClose}><X size={17}/></button></div></header>
|
||||
{choosing&&<div className={s.picker} role="group" aria-label="选择引用节点">{p.nodes.filter(n=>n.id!==p.node.id&&!p.references.some(r=>r.id===n.id)).map(n=><button key={n.id} onClick={()=>{p.onAddReference(n.id);choose(false)}}>{n.kind==='image'?<ImagePlus size={15}/>:<FileText size={15}/>} {n.title}</button>)}{p.nodes.length<2&&<span>先在画布上添加一个参考节点</span>}</div>}
|
||||
{!!p.references.length&&<div className={s.references}>{p.references.map((n,i)=><div className={s.reference} key={n.id}>{n.image?<img src={n.image} alt={n.title}/>:<FileText size={24}/>}<span>{i+1}</span><small>{n.title}</small><button aria-label={`移除引用 ${n.title}`} onClick={()=>p.onRemoveReference(n.id)}><X size={12}/></button></div>)}</div>}
|
||||
<textarea aria-label="创作要求" maxLength={10000} value={p.node.instruction??p.node.text} onFocus={p.onBeginEdit} onChange={e=>p.onChange(e.target.value)} placeholder={p.node.kind==='script'?'描述剧情片段、故事或分镜要求…':'描述画面,或写下对参考图的修改要求…'}/><footer><span role="status">{p.feedback||<>{p.node.operation==='upscale'?'图片高清':p.node.kind==='script'?'分镜脚本':'创作任务'} · {p.references.length} 个引用</>}</span><div><button onClick={p.onExport}><Download size={15}/>导出任务</button><button onClick={p.onQueue}><ArrowUp size={15}/>交给 Agent</button></div></footer></section>}
|
||||
@@ -0,0 +1,16 @@
|
||||
import {useRef,type PointerEvent} from 'react';
|
||||
import {Type,ImagePlus,FileText,Plus,Bold,Italic,Maximize,MoreHorizontal} from 'lucide-react';
|
||||
import type {CanvasNode,TextStyle} from '../../lib/canvas-document';
|
||||
import s from '../../styles/canvas-node.module.css';
|
||||
type Props={node:CanvasNode;selected:boolean;editing:boolean;hand:boolean;onSelect:()=>void;onChooseReference:()=>void;onEdit:()=>void;onDrag:(e:PointerEvent<HTMLElement>)=>void;onResize:(e:PointerEvent<HTMLElement>)=>void;onChange:(text:string)=>void;onRename:(title:string)=>void;onStyle:(style:TextStyle)=>void;onReference:(e:PointerEvent<HTMLButtonElement>|React.MouseEvent<HTMLButtonElement>)=>void;onMenu:(e:React.MouseEvent<HTMLButtonElement>)=>void;onUpload:()=>void;onUpscale:()=>void;onExpand:()=>void;onBeginEdit:()=>void};
|
||||
export default function CanvasNodeView(p:Props){
|
||||
const {node:n}=p;const gesture=useRef<{selected:boolean;x:number;y:number;moved:boolean}|null>(null);
|
||||
const icon=n.kind==='image'?<ImagePlus size={15}/>:n.kind==='script'?<FileText size={15}/>:<Type size={15}/>;
|
||||
const style={fontWeight:n.style?.bold?700:400,fontStyle:n.style?.italic?'italic':'normal',fontSize:n.style?.size||15,color:n.style?.color};
|
||||
return <article data-node-id={n.id} data-editing={p.editing} data-selected={p.selected} className={s.node} style={{left:n.x,top:n.y,width:n.width||320,height:n.height||350}} onPointerDown={e=>{gesture.current=null;if(p.hand||(p.editing&&n.kind==='text')||e.button!==0||(e.target as HTMLElement).closest('button,input,select'))return;gesture.current={selected:p.selected,x:e.clientX,y:e.clientY,moved:false};e.stopPropagation();p.onSelect();p.onDrag(e)}} onPointerMove={e=>{const g=gesture.current;if(g&&Math.hypot(e.clientX-g.x,e.clientY-g.y)>=4)g.moved=true}} onClick={e=>{if((e.target as HTMLElement).closest('button,input,select'))return;const g=gesture.current;if(!p.hand&&!p.editing&&g?.selected&&!g.moved)p.onEdit();gesture.current=null}} onKeyDown={e=>{if(e.target!==e.currentTarget)return;if(e.key==='Enter'){e.preventDefault();p.onEdit()}}} tabIndex={0} aria-label={n.title}>
|
||||
<header className={s.title}>{icon}<input aria-label="节点名称" value={n.title} maxLength={200} onFocus={p.onBeginEdit} onChange={e=>p.onRename(e.target.value)} onPointerDown={e=>e.stopPropagation()}/>{p.selected&&<button aria-label={`${n.title} 操作`} onClick={e=>{e.stopPropagation();p.onMenu(e)}}><MoreHorizontal size={17}/></button>}</header>
|
||||
{p.editing&&n.kind==='text'&&<div className={s.format} onPointerDown={e=>e.stopPropagation()}><input aria-label="文字颜色" type="color" value={n.style?.color||'#dddddd'} onChange={e=>p.onStyle({...n.style,color:e.target.value})}/><select aria-label="文字样式" value={n.style?.size||15} onChange={e=>p.onStyle({...n.style,size:Number(e.target.value)})}><option value={15}>正文</option><option value={24}>小标题</option><option value={32}>标题</option></select><button aria-label="加粗" aria-pressed={!!n.style?.bold} onClick={()=>p.onStyle({...n.style,bold:!n.style?.bold})}><Bold size={17}/></button><button aria-label="斜体" aria-pressed={!!n.style?.italic} onClick={()=>p.onStyle({...n.style,italic:!n.style?.italic})}><Italic size={17}/></button><button aria-label="展开文本节点" onClick={p.onExpand}><Maximize size={17}/></button></div>}
|
||||
{n.kind==='image'?<div data-node-content className={s.image}>{n.image?<img src={n.image} alt={n.title} draggable={false}/>:<div className={s.empty}><ImagePlus size={48} strokeWidth={1}/><button onClick={e=>{e.stopPropagation();p.onUpload()}}>上传图片</button></div>}{p.selected&&n.image&&<button className={s.upscale} onClick={e=>{e.stopPropagation();p.onUpscale()}}>图片高清 ↗</button>}</div>:p.editing&&n.kind==='text'?<textarea data-node-content autoFocus aria-label={`${n.title} 内容`} style={style} value={n.text} maxLength={10000} placeholder="输入内容…" onFocus={p.onBeginEdit} onChange={e=>p.onChange(e.target.value)}/>:<div data-node-content className={s.content} style={style}>{n.text?<p>{n.text}</p>:<div className={s.empty}>{icon}<button onClick={e=>{e.stopPropagation();p.onEdit()}}>{n.kind==='text'?'自己编写内容':n.kind==='script'?'编写脚本':'填写创作要求'}</button></div>}</div>}
|
||||
{p.selected&&<><button className={`${s.reference} ${s.incoming}`} aria-label={`为 ${n.title} 添加参考`} onClick={e=>{e.stopPropagation();p.onChooseReference()}}><Plus size={18}/></button><button className={s.reference} aria-label={`引用 ${n.title} 生成`} onClick={e=>{e.stopPropagation();p.onReference(e)}}><Plus size={18}/></button><button className={s.resize} aria-label={`调整 ${n.title} 尺寸`} onPointerDown={e=>{e.stopPropagation();gesture.current=null;p.onResize(e)}} onClick={e=>e.stopPropagation()}>↘</button></>}
|
||||
</article>;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import ref17 from './templates/ref-17.json';
|
||||
export type Slide={heading:string;body:string;color:string;key?:string;label?:string;accent?:string;kicker?:string};
|
||||
export type Idea={slug:string;title:string;summary:string;slides:Slide[];tool?:string;template?:typeof ref17};
|
||||
// Studio owns creative pages. Wiki source tutorials are consumed as text/image data.
|
||||
export const ideas:Idea[]=[{slug:'layout-selection',tool:'layout-selection',title:'三种排版 · 模板选择工具',summary:'ref-01、ref-07、ref-26 三种不同构图的可编辑试版。',slides:[]},{
|
||||
slug:'learning-skills-template',title:'学习资料合集 · 封面模板试版',
|
||||
summary:'一张空白母版与三张主题占位封面,共用 ref-17 的同一套构件坐标;先试文案、色调和边界,暂不填具体 Skills。',template:ref17,
|
||||
slides:[
|
||||
{key:'master',label:'空白母版',heading:'合集标题',body:'副标题占位\n栏目一 · 栏目二\n正文稍后填入',color:'#84918c',accent:'#d8ddd4',kicker:'TEMPLATE / 00'},
|
||||
{key:'notes',label:'A · 笔记复习',heading:'笔记复习',body:'课程 · 笔记 · 复习\n副标题稍后确定\n正文暂不填入',color:'#7a8b7e',accent:'#d5ddcf',kicker:'COLLECTION / A'},
|
||||
{key:'teaching',label:'B · 教学资料',heading:'教学资料',body:'题目 · 试卷 · 课件\n副标题稍后确定\n正文暂不填入',color:'#7c8e9b',accent:'#d8e0e4',kicker:'COLLECTION / B'},
|
||||
{key:'english',label:'C · 英语学习',heading:'英语学习',body:'词汇 · 精读 · 表达\n副标题稍后确定\n正文暂不填入',color:'#9b817a',accent:'#e4d6ce',kicker:'COLLECTION / C'},
|
||||
],
|
||||
},{slug:'first-idea',title:'把一个想法,变成一组画面',summary:'从一句话出发,写成页面,再导出为图文或视频。',slides:[{heading:'先捕捉,再打磨',body:'把今天的灵感写下来。不用急着完整,先留下那个让你心动的瞬间。',color:'#ffe5df'},{heading:'让每一页只讲一件事',body:'一个标题,一段解释,一个值得被记住的画面。',color:'#e2e9e1'},{heading:'选择你的表达方式',body:'导出图文长页,或用 Python 将画面制作成视频。',color:'#eee5f5'}]}];
|
||||
export function ideaMarkdown(idea:Idea){
|
||||
return '# '+idea.title+'\n\n'+idea.summary+'\n\n'+(idea.template?'## 模板来源与约束\n\n教程:'+idea.template.tutorialUrl+'?agent_mode=True\n\n同一套模板:'+idea.template.id+';源画板 '+idea.template.width+'×'+idea.template.height+'。本阶段仅有占位封面,没有具体 Skills 内容。\n\n```json\n'+JSON.stringify(idea.template,null,2)+'\n```\n\n':'')+idea.slides.map(s=>'## '+(s.label||s.heading)+'\n\n'+s.heading+'\n\n'+s.body+'\n\n'+(idea.template?'主色:'+s.color+';叠圆:'+s.accent+'。\n':'')).join('\n\n');
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,116 @@
|
||||
{
|
||||
"id": "ref-17",
|
||||
"name": "英文刊头与圆形叠标及窄栏",
|
||||
"tutorialUrl": "http://8.211.154.134:18131/explore/7b1b2fc5b9690213bbbe07ac",
|
||||
"referenceUrl": "http://8.211.154.134:18131/api/media/447db777-d060-4987-b753-15422b0b4919",
|
||||
"sourceSha256": "121ab8a362c45eee86281ca5dfbbe33577cfcd255579a16c3542530484b9f1dc",
|
||||
"width": 113,
|
||||
"height": 174,
|
||||
"masthead": [
|
||||
"STUDY",
|
||||
"Skills"
|
||||
],
|
||||
"paper": "#f4f2eb",
|
||||
"ink": "#25342f",
|
||||
"slots": [
|
||||
{
|
||||
"id": "D01",
|
||||
"kind": "decoration",
|
||||
"role": "右栏底线",
|
||||
"box": [
|
||||
82,
|
||||
121,
|
||||
29,
|
||||
2
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "T01",
|
||||
"kind": "text",
|
||||
"role": "左上英文第一行",
|
||||
"box": [
|
||||
6,
|
||||
10,
|
||||
63,
|
||||
10
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "T02",
|
||||
"kind": "text",
|
||||
"role": "左上英文第二行",
|
||||
"box": [
|
||||
5,
|
||||
20,
|
||||
56,
|
||||
16
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "T03",
|
||||
"kind": "text",
|
||||
"role": "中部中文横题",
|
||||
"box": [
|
||||
51,
|
||||
50,
|
||||
60,
|
||||
16
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "T04",
|
||||
"kind": "text",
|
||||
"role": "右侧窄栏正文",
|
||||
"box": [
|
||||
82,
|
||||
67,
|
||||
29,
|
||||
54
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "I01",
|
||||
"kind": "image",
|
||||
"role": "左下主图",
|
||||
"box": [
|
||||
5,
|
||||
68,
|
||||
73,
|
||||
101
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "I02",
|
||||
"kind": "image",
|
||||
"role": "左中叠加圆形",
|
||||
"box": [
|
||||
5,
|
||||
53,
|
||||
22,
|
||||
22
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "D02",
|
||||
"kind": "decoration",
|
||||
"role": "刊头右侧双线",
|
||||
"box": [
|
||||
61,
|
||||
27,
|
||||
50,
|
||||
7
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "D03",
|
||||
"kind": "decoration",
|
||||
"role": "底部横向贴条",
|
||||
"box": [
|
||||
58,
|
||||
167,
|
||||
54,
|
||||
6
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
[{"id":"ref-01","name":"双矩形错位与左下说明","width":113,"height":171,"tutorialUrl":"http://8.211.154.134:18131/explore/eb937b42be92a9f6feee684f","referenceUrl":"http://8.211.154.134:18131/api/media/7d1eedda-bf64-4bf0-ae2b-a7a684282c20","sourceSha256":"121ab8a362c45eee86281ca5dfbbe33577cfcd255579a16c3542530484b9f1dc","slots":[{"id":"T01","kind":"text","role":"品牌字标","box":[8,20,36,15],"direction":"horizontal"},{"id":"T02","kind":"text","role":"左下说明","box":[7,121,44,34],"direction":"horizontal"},{"id":"I01","kind":"image","role":"上方主图","box":[24,14,77,71],"direction":"horizontal","raster":"/api/media/e815dd53-494f-5f08-8849-249fd63960ff"},{"id":"I02","kind":"image","role":"下方副图","box":[42,89,59,70],"direction":"horizontal","raster":"/api/media/388e3068-c739-5a0c-aa55-37f2997cfa35"},{"id":"D01","kind":"decoration","role":"顶部短线","box":[41,4,29,3],"direction":"horizontal","raster":"/api/media/edb874c0-c93a-5217-9c32-8888f5d20fa2"},{"id":"D02","kind":"decoration","role":"底部横线","box":[29,158,58,8],"direction":"horizontal","raster":"/api/media/9ee0db30-7579-52dc-bc03-f8b465a45bb5"}],"fields":{"T01":"STUDY","T02":"合集标题\n主题说明占位\n正文稍后填入"}},{"id":"ref-07","name":"同心圆图位与底部年份","width":112,"height":172,"tutorialUrl":"http://8.211.154.134:18131/explore/7d4cefdfada28bbe9e570af3","referenceUrl":"http://8.211.154.134:18131/api/media/da5eb520-196d-4cca-b056-95a40d20a281","sourceSha256":"121ab8a362c45eee86281ca5dfbbe33577cfcd255579a16c3542530484b9f1dc","slots":[{"id":"T01","kind":"text","role":"下沿环形文字","box":[17,75,90,34],"direction":"curved"},{"id":"T02","kind":"text","role":"年份","box":[2,129,27,12],"direction":"horizontal"},{"id":"T03","kind":"text","role":"年份下副标题","box":[3,140,58,5],"direction":"horizontal"},{"id":"T04","kind":"text","role":"底部说明","box":[1,146,109,16],"direction":"horizontal"},{"id":"T05","kind":"text","role":"右下品牌","box":[58,161,52,9],"direction":"horizontal"},{"id":"I01","kind":"image","role":"中央圆形主图","box":[18,9,92,94],"direction":"horizontal","raster":"/api/media/993144d9-462a-5277-b9bd-64739460b148"},{"id":"D01","kind":"decoration","role":"同心环线","box":[0,0,112,138],"direction":"horizontal","raster":"/api/media/fa472042-1b69-554f-bb0f-3957688b628d"}],"fields":{"T01":"STUDY / LEARN / CREATE","T02":"2026","T03":"COLLECTION / TEMPLATE","T04":"课程 · 笔记 · 复习\n主题说明占位,正文稍后填入","T05":"学习资料合集"}},{"id":"ref-26","name":"三行英文与曲线指引小图","width":114,"height":173,"tutorialUrl":"http://8.211.154.134:18131/explore/f356b77194288909ee4352b4","referenceUrl":"http://8.211.154.134:18131/api/media/43a6b1f3-317b-4464-a192-92ef023eedeb","sourceSha256":"121ab8a362c45eee86281ca5dfbbe33577cfcd255579a16c3542530484b9f1dc","slots":[{"id":"D01","kind":"decoration","role":"第二行下划线","box":[0,41,47,1],"direction":"horizontal","raster":"/api/media/2a23cc80-1ad1-53d8-86eb-30af228a66fa"},{"id":"D02","kind":"decoration","role":"第三行下划线","box":[0,58,67,2],"direction":"horizontal","raster":"/api/media/3ee85a46-19e4-5450-9d4f-37e65637f908"},{"id":"T01","kind":"text","role":"第一行英文","box":[0,0,81,18],"direction":"horizontal"},{"id":"T02","kind":"text","role":"第二行英文","box":[0,23,49,18],"direction":"horizontal"},{"id":"T03","kind":"text","role":"第三行英文","box":[0,41,68,19],"direction":"horizontal"},{"id":"T04","kind":"text","role":"右侧竖排标题","box":[98,68,12,46],"direction":"vertical"},{"id":"T05","kind":"text","role":"左下说明","box":[4,140,44,29],"direction":"horizontal"},{"id":"I01","kind":"image","role":"右下方形图片","box":[66,118,43,50],"direction":"horizontal","raster":"/api/media/89a6ac49-b1e9-5cab-b0d3-c1e7af8736b0"},{"id":"D03","kind":"decoration","role":"中间分隔线","box":[0,60,112,3],"direction":"horizontal","raster":"/api/media/0d8d17ed-cc40-56eb-bdc3-ad6cd7b9d301"},{"id":"D04","kind":"decoration","role":"中央自由曲线","box":[6,48,85,87],"direction":"horizontal","raster":"/api/media/8f128857-375d-5a40-b6c4-326bfe6fe1ef"},{"id":"D05","kind":"decoration","role":"自动识别细线","box":[91,59,19,1],"direction":"horizontal","raster":"/api/media/7c42438c-a394-5a21-a321-48ff2677e2ac"}],"fields":{"T01":"Study 01","T02":"Learn","T03":"Create","T04":"学习合集","T05":"主题说明占位\n正文稍后填入"}}]
|
||||
@@ -0,0 +1,2 @@
|
||||
// Stable Wiki post ID; the tutorial is published through /api/posts, never registered as a Wiki route.
|
||||
export const tutorialPost='/explore/8eb8c76500580f7a4b56ba3c';
|
||||
@@ -0,0 +1,24 @@
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
const docs:Record<string,string>={
|
||||
'/studio/api/export/{slug}': `# Studio 封面工具 API
|
||||
|
||||
方法:GET, POST
|
||||
路径参数:slug 为 learning-skills-template(同一母版四张试版)或 layout-selection(三种不同构图);first-idea 仅提供 GET 内容导出。
|
||||
GET 参数:省略 format 返回方案 JSON;format=markdown 返回说明;format=svg 返回初始封面。四张试版用 slide=0..3(默认 0),多模板工具用 layoutId=ref-01|ref-07|ref-26(默认 ref-01)。
|
||||
JSON:普通方案 version:1;四张试版 version:2;多模板 version:3,layouts 包含源教程、画板、构件坐标及分层蒙版。文字、图位、装饰一一对应,图片位为色块占位。
|
||||
POST:Content-Type: application/json。format=svg(默认)返回独立 SVG;format=json 返回渲染参数及模板信息。请求最大 32KB,无存储副作用。
|
||||
learning-skills-template 参数:slide(整数 0–3,默认 0)、heading(1–6 字)、body(最多 360 字、3 行)、color、accent(#RRGGBB)、masthead(2 项数组,每项 1–8 个英文字母/空格);省略参数沿用初始值。
|
||||
layout-selection 参数:layoutId(必填,ref-01/ref-07/ref-26)、fields(可选,以对应模板 T 构件 ID 为键;每项 1–120 字、最多 4 行)、color、accent(#RRGGBB)。省略文字沿用初始值;拒绝未知参数或构件 ID。
|
||||
示例:POST /studio/api/export/learning-skills-template?format=svg
|
||||
{"slide":1,"heading":"笔记复习","color":"#7a8b7e"}
|
||||
POST /studio/api/export/layout-selection?format=svg
|
||||
{"layoutId":"ref-01","fields":{"T01":"STUDY","T02":"笔记复习\\n主题说明占位"},"color":"#83918a"}
|
||||
错误:400 参数/格式错误;404 方案不存在;405 方法不支持;413 请求过大。SVG 不含编辑辅助边界,文字经过 XML 转义;装饰位分层图片是按源构件重建的矢量;原始低分辨率分层保留在模板 JSON 中供核对。`,
|
||||
'/studio/api/health': '# 创作站健康检查\n\n方法:GET, HEAD\n无业务参数。GET 返回 200 JSON:{"status":"ok","service":"prompt-studio"};HEAD 无正文。\n示例:GET /studio/api/health\n错误:405 方法不支持。',
|
||||
};
|
||||
export function serveApiDocumentation(req:NextApiRequest,res:NextApiResponse,path:string){
|
||||
if(!['GET','HEAD'].includes(req.method||'')||typeof req.query.agent_mode!=='string'||req.query.agent_mode.toLowerCase()!=='true')return false;
|
||||
if(!docs[path])return false;
|
||||
res.setHeader('Content-Type','text/plain; charset=utf-8');res.setHeader('Cache-Control','no-store');res.status(200);
|
||||
if(req.method==='HEAD')res.end();else res.send(docs[path]+'\n\n使用 GET 或 HEAD,在原地址加 ?agent_mode=True;已有参数时加 &agent_mode=True。值不区分大小写。动态路径可保留占位符读取说明。业务调用请移除 agent_mode。\nAPI 目录:/api?agent_mode=True\n');return true;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from '../../lib/canvas-document.ts';
|
||||
@@ -0,0 +1,24 @@
|
||||
import type {IncomingMessage} from 'node:http';
|
||||
import {series} from './series';
|
||||
import {parameters,uuid} from './layout-parameters';
|
||||
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. */
|
||||
export async function readDesign(id:unknown,req:IncomingMessage):Promise<Design|null>{
|
||||
if(!uuid(id))return null;
|
||||
const origin=process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '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');
|
||||
if((design as Design&{archived?:boolean}).archived)return null;
|
||||
return {...design,...(design.document?{document:series(design.document,layouts)}:{}),parameters:parameters(layout,design.parameters)};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type GraphicItem = {
|
||||
id:string;kind:'text'|'rect'|'ellipse'|'image';name:string;text:string;
|
||||
x:number;y:number;w:number;h:number;fill:string;size:number;hidden:boolean;locked:boolean;src?:string;
|
||||
};
|
||||
export type GraphicDocument = {name:string;background:string;items:GraphicItem[]};
|
||||
const color=(value:unknown)=>typeof value==='string'&&/^#[a-f0-9]{6}$/i.test(value);
|
||||
/** Accept only bounded editable documents; never execute or load external assets. */
|
||||
export function parseGraphicDocument(raw:string):GraphicDocument {
|
||||
if(raw.length>5*1024*1024)throw Error('设计文件不得超过 5MB');
|
||||
const d=JSON.parse(raw);
|
||||
if(!d||typeof d.name!=='string'||d.name.length>100||!color(d.background)||!Array.isArray(d.items)||d.items.length>500)throw Error('设计文件格式不正确');
|
||||
const ids=new Set<string>();
|
||||
for(const i of d.items){
|
||||
if(!i||typeof i.id!=='string'||i.id.length>100||ids.has(i.id)||!['text','rect','ellipse','image'].includes(i.kind)||typeof i.name!=='string'||i.name.length>200||typeof i.text!=='string'||i.text.length>4000||!color(i.fill)||typeof i.hidden!=='boolean'||typeof i.locked!=='boolean'||![i.x,i.y,i.w,i.h,i.size].every(Number.isFinite)||Math.abs(i.x)>4000||Math.abs(i.y)>4000||i.w<1||i.h<1||i.w>4000||i.h>4000||i.size<8||i.size>240)throw Error('设计图层格式不正确');
|
||||
if(i.kind==='image'&&(typeof i.src!=='string'||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(i.src)))throw Error('图片必须为嵌入式 PNG、JPEG 或 WebP');
|
||||
ids.add(i.id);
|
||||
}
|
||||
return {name:d.name,background:d.background,items:d.items.map((i:GraphicItem)=>({id:i.id,kind:i.kind,name:i.name,text:i.text,x:i.x,y:i.y,w:i.w,h:i.h,fill:i.fill,size:i.size,hidden:i.hidden,locked:i.locked,...(i.kind==='image'?{src:i.src}:{})}))};
|
||||
}
|
||||
@@ -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'});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {NextApiRequest} from 'next';
|
||||
import type {Parameters} from './layout-parameters';
|
||||
/** Only fetch bounded previews from the authenticated Wiki service, never caller URLs. */
|
||||
export async function embedLayoutImages(req:NextApiRequest,params:Parameters){
|
||||
const ids=[...new Set(Object.values(params.images).flatMap(v=>v.assetId?[v.assetId]:[]))],sources:Record<string,string>={};let total=0;
|
||||
const headers:Record<string,string>={};if(req.headers.authorization)headers.authorization=req.headers.authorization;if(req.headers.cookie)headers.cookie=req.headers.cookie;
|
||||
for(const id of ids){const url=(process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`)+'/api/preview?'+new URLSearchParams({source:'/api/media/'+id,width:'960'}),r=await fetch(url,{headers,signal:AbortSignal.timeout(15000),redirect:'error'});if(!r.ok||r.headers.get('content-type')?.split(';')[0]!=='image/webp')throw Error('图片预览不可访问,请检查图片 ID 与登录状态');const chunks:Buffer[]=[];const reader=r.body!.getReader();try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>16*1024*1024)throw Error('图片预览总计超限');chunks.push(Buffer.from(value))}}finally{await reader.cancel()}sources[id]='data:image/webp;base64,'+Buffer.concat(chunks).toString('base64');}
|
||||
return sources;
|
||||
}
|
||||
|
||||
/** Export a self-contained SVG without storing image bytes in template JSON. */
|
||||
export async function embedSvgMedia(req:NextApiRequest,svg:string){
|
||||
const paths=[...new Set(svg.match(/\/api\/media\/[0-9a-f-]{36}/g)||[])];
|
||||
const headers:Record<string,string>={};if(req.headers.authorization)headers.authorization=req.headers.authorization;if(req.headers.cookie)headers.cookie=req.headers.cookie;
|
||||
let total=0;
|
||||
for(const path of paths){
|
||||
const response=await fetch((process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`)+path,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});
|
||||
const mime=response.headers.get('content-type')?.split(';')[0];
|
||||
if(!response.ok||!mime||!['image/png','image/jpeg','image/webp'].includes(mime))throw Error('模板图片不可访问');
|
||||
const chunks:Uint8Array[]=[];const reader=response.body!.getReader();
|
||||
try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>16*1024*1024)throw Error('模板图片总计超限');chunks.push(value);}}finally{await reader.cancel();}
|
||||
svg=svg.replaceAll(path,'data:'+mime+';base64,'+Buffer.concat(chunks).toString('base64'));
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from '../../lib/layout-parameters.ts';
|
||||
@@ -0,0 +1,72 @@
|
||||
import type {CSSProperties} from 'react';
|
||||
import type {Layout,Parameters,Slot} from './layout-parameters';
|
||||
|
||||
export type Design={document?:import('./series').Series;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/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}))};
|
||||
}
|
||||
// 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 slot.box[2]<25?'FORM / '+layout.id.slice(-2):'FORM / SPACE / DESIGN';
|
||||
if(slot.direction==='vertical')return '设计灵感 · 日常观察';
|
||||
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}%`};
|
||||
}
|
||||
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*.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,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: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=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){
|
||||
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';
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {createElement} from 'react';
|
||||
import {ideas} from '../content/ideas';
|
||||
import {Ref17Cover} from '../components/Ref17Cover';
|
||||
import {SourceCover,selections} from '../components/SourceCover';
|
||||
const record=(v:unknown):v is Record<string,unknown>=>!!v&&typeof v==='object'&&!Array.isArray(v);
|
||||
function color(value:unknown,fallback:string){if(value===undefined)return fallback;if(typeof value!=='string'||!/^#[0-9a-f]{6}$/i.test(value))throw Error('颜色必须为 #RRGGBB');return value;}
|
||||
function text(value:unknown,fallback:string,max:number,lines=1){if(value===undefined)return fallback;if(typeof value!=='string'||!value.trim()||Array.from(value).length>max||value.split('\n').length>lines)throw Error('文字长度或行数超限');return value;}
|
||||
function keys(input:Record<string,unknown>,allowed:string[]){if(Object.keys(input).some(k=>!allowed.includes(k)))throw Error('包含不支持的参数');}
|
||||
export function renderCover(slug:string,input:unknown){
|
||||
if(!record(input))throw Error('需要 JSON 对象');
|
||||
if(slug==='layout-selection'){
|
||||
keys(input,['layoutId','fields','color','accent']);const layout=selections.find(l=>l.id===input.layoutId);if(!layout)throw Error('layoutId 必须为 ref-01、ref-07 或 ref-26');
|
||||
if(input.fields!==undefined&&!record(input.fields))throw Error('fields 必须为对象');const supplied=(input.fields||{}) as Record<string,unknown>,defaults=Object.fromEntries(Object.entries(layout.fields).filter(([,v])=>v!==undefined)) as Record<string,string>;
|
||||
keys(supplied,Object.keys(defaults));const fields=Object.fromEntries(Object.entries(defaults).map(([key,value])=>[key,text(supplied[key],value,120,4)]));
|
||||
const values={fields,color:color(input.color,'#83918a'),accent:color(input.accent,'#c3cec5')};return {node:createElement(SourceCover,{layout,values}),data:{version:3,tool:slug,layoutId:layout.id,template:layout,...values}};
|
||||
}
|
||||
const idea=ideas.find(i=>i.slug===slug);if(!idea?.template)throw Error('这个方案不支持封面渲染');keys(input,['slide','heading','body','color','accent','masthead']);
|
||||
const index=input.slide??0;if(typeof index!=='number'||!Number.isInteger(index)||!idea.slides[index])throw Error('slide 必须是 0–3 的整数');const initial=idea.slides[index];
|
||||
const slide={...initial,heading:text(input.heading,initial.heading,6),body:text(input.body,initial.body,360,3),color:color(input.color,initial.color),accent:color(input.accent,initial.accent!)};
|
||||
const masthead=input.masthead??idea.template.masthead;if(!Array.isArray(masthead)||masthead.length!==2||!masthead.every(v=>typeof v==='string'&&/^[A-Za-z ]{1,8}$/.test(v)&&v.trim()))throw Error('masthead 为两行、每行 1–8 个英文字母或空格');
|
||||
return {node:createElement(Ref17Cover,{template:idea.template,slide,masthead}),data:{version:2,tool:slug,template:{...idea.template,masthead},slide}};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from '../../lib/series.ts';
|
||||
@@ -0,0 +1,3 @@
|
||||
.root{position:static}.panel{position:absolute;left:0;top:calc(100% + 12px);width:min(390px,calc(100vw - 32px));max-height:75dvh;overflow:auto;padding:20px;border:1px solid var(--border);border-radius:16px;background:var(--surface);color:var(--foreground);box-shadow:0 15px 70px var(--shadow);z-index:12;display:grid;gap:14px;font-size:12px}.panel header,.actions,.conflict{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}.panel button{font-size:11px!important;padding:7px 10px!important;background:var(--surface)!important;color:inherit!important;border:1px solid var(--border)!important}.panel button:disabled{opacity:.45}.panel textarea{width:100%;height:150px;resize:vertical;background:var(--surface);color:var(--foreground);border:1px solid var(--input);border-radius:8px;padding:10px;font:10px/1.7 monospace}.panel p{margin:0;color:var(--muted-foreground);line-height:1.7}.panel small{color:var(--muted-foreground);font-size:10px}.panel label{display:grid;gap:8px}.panel select{width:100%;background:var(--surface);color:inherit;padding:8px;border-radius:6px}.panel ul{padding:0;margin:0;list-style:none;display:grid;gap:12px}.panel li{display:grid;gap:5px;border-top:1px solid var(--border);padding-top:10px}.panel li button{justify-self:start}.panel a{color:inherit!important;text-decoration:underline!important}
|
||||
|
||||
:global(header):has(> .root .panel){z-index:12}
|
||||
@@ -0,0 +1,4 @@
|
||||
.composer{position:fixed;z-index:6;left:50%;bottom:92px;transform:translateX(-50%);width:min(900px,calc(100vw - 40px));height:280px;border:1px solid var(--border);border-radius:22px;padding:20px 24px;background:var(--surface);color:var(--foreground);display:flex;flex-direction:column;box-shadow:0 15px 70px var(--shadow)}.composer[data-expanded=true]{height:min(65dvh,650px)}.composer header{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:12px}.composer header>span,.composer header>div{display:flex;align-items:center;gap:8px}.composer header button,.composer footer button{background:var(--surface);border-color:var(--border);font-size:11px;padding:7px 10px}.composer textarea{display:block;flex:1;min-height:50px;width:100%;resize:none;padding:17px 0;border:0;background:transparent;color:inherit;font:inherit;line-height:1.8;outline:none}.composer footer{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:10px;color:var(--muted-foreground)}.references{display:flex;gap:10px;padding-top:15px;flex-shrink:0;overflow:auto}.reference{width:70px;height:65px;border:1px solid var(--border);border-radius:8px;position:relative;display:grid;place-items:center;flex-shrink:0;overflow:hidden;background:var(--surface)}.reference img{width:100%;height:100%;object-fit:cover}.reference>span{position:absolute;top:3px;left:4px;background:var(--surface);color:var(--foreground);border-radius:50%;padding:1px 4px;font-size:9px}.reference small{position:absolute;bottom:0;width:100%;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;background:var(--surface);font-size:8px;padding:3px}.reference button{position:absolute;top:1px;right:1px;padding:2px!important;background:var(--surface)!important;border:0!important}.picker{position:absolute;bottom:calc(100% + 10px);left:0;background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:10px;max-height:200px;overflow:auto;display:grid;gap:5px;min-width:220px}.picker button{justify-content:flex-start;background:transparent;border:0}.picker>span{font-size:11px;padding:12px}@media(max-width:600px){.composer{width:calc(100vw - 20px);padding:15px;bottom:80px;height:260px;border-radius:16px}.composer header>span{max-width:95px;overflow:hidden;white-space:nowrap;font-size:10px}.composer header button{padding:5px;font-size:10px}.composer header{gap:4px}.composer header>div{gap:4px}}
|
||||
.composer header input{width:200px;max-width:25vw;min-width:0;border:0;background:transparent;color:inherit;font:inherit;outline:none}
|
||||
|
||||
.composer footer>div{display:flex;gap:8px;flex-shrink:0}@media(max-width:600px){.composer footer>div{gap:4px}.composer footer button{font-size:10px;padding:6px}.composer footer>span{min-width:0}}
|
||||
@@ -0,0 +1,3 @@
|
||||
.node{position:absolute;background:var(--surface);border:1px solid var(--border);border-radius:13px;color:var(--foreground);pointer-events:auto;touch-action:none;cursor:grab;outline:none}.node[data-selected=true]{border-color:var(--selection-border)}.node[data-editing=true]{border:2px solid var(--border);cursor:default}.title{position:absolute;top:-31px;left:0;right:0;display:flex;gap:7px;align-items:center;height:26px;color:var(--muted-foreground);font-size:12px;white-space:nowrap}.title>span{overflow:hidden;text-overflow:ellipsis}.title>button{margin-left:auto;padding:3px!important;background:transparent!important;border:0!important}.content,.image{height:100%;overflow:hidden;border-radius:12px}.content{padding:25px;white-space:pre-wrap;overflow:auto;scrollbar-width:thin}.content p{margin:0;line-height:1.7;pointer-events:none}.image{position:relative;display:grid;place-items:center}.image img{width:100%;height:100%;object-fit:contain;pointer-events:none;user-select:none;-webkit-user-drag:none}.empty{height:100%;width:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;color:var(--muted-foreground)}.empty button{background:transparent!important;border:0!important;color:var(--muted-foreground)!important;font-size:12px!important}.node>textarea{width:100%;height:100%;border:0;border-radius:12px;background:transparent;color:inherit;outline:none;resize:none;padding:25px;line-height:1.7;touch-action:auto}.format{position:absolute;bottom:calc(100% + 48px);left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:4px;background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:6px;white-space:nowrap;z-index:3}.format input{width:24px;height:24px;padding:0;border:0;background:transparent}.format select{max-width:100px;background:transparent;color:var(--foreground);border:0;padding:6px}.format button{padding:5px!important;border:0!important;background:transparent!important}.format button[aria-pressed=true]{background:var(--selection)!important}.reference{position:absolute!important;right:-38px;top:calc(50% - 14px);width:28px;height:28px;border-radius:50%!important;border:1px solid var(--border)!important;padding:2px!important;background:var(--surface)!important;color:var(--foreground)!important}.resize{position:absolute!important;right:3px;bottom:3px;padding:3px!important;border:0!important;background:transparent!important;color:var(--muted-foreground)!important;cursor:nwse-resize!important}.upscale{position:absolute;bottom:10px;left:10px;font-size:10px!important;background:var(--surface)!important}.node:focus-visible{outline:2px solid var(--ring);outline-offset:3px}
|
||||
.title>input{min-width:0;width:100%;border:0!important;background:transparent!important;padding:0!important;color:inherit;font:inherit;outline:none}.title>button{flex-shrink:0}
|
||||
.incoming{right:auto!important;left:-38px}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,51 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { db } from '../src/lib/db';
|
||||
import { hashPassword,newToken,tokenDigest } from '../src/lib/account-crypto';
|
||||
import { resetPassword,loginAccount,verifyAccount,currentAccount,logoutAccount,rateLimit } from '../src/lib/account';
|
||||
export async function verifyEmailAccounts(base: string) {
|
||||
const id=randomUUID(), email=id+'@example.com', password='a secure test password';
|
||||
const request=(token:string)=>new Request('https://wiki.example',{headers:{cookie:'wiki_account='+token}});
|
||||
try {
|
||||
await db().query('INSERT INTO account_users(id,email,password_hash) VALUES ($1,$2,$3)',[id,email,await hashPassword(password)]);
|
||||
assert.equal(await loginAccount(email,password),null,'unverified accounts cannot log in');
|
||||
const verification=newToken();await db().query("INSERT INTO account_tokens VALUES ($1,$2,'verify',now()+interval '1 minute')",[tokenDigest(verification),id]);
|
||||
const results=await Promise.all([verifyAccount(verification),verifyAccount(verification)]);assert.deepEqual(results.sort(),[false,true]);
|
||||
assert.equal(await loginAccount(email,'incorrect password'),null);
|
||||
const token=await loginAccount(email,password);assert.ok(token);
|
||||
assert.equal((await currentAccount(request(token))).id,id);
|
||||
await db().query("UPDATE account_tokens SET expires_at=now()-interval '1 second' WHERE digest=$1",[tokenDigest(token)]);
|
||||
assert.equal(await currentAccount(request(token)),null,'expired sessions rejected');
|
||||
const fresh=await loginAccount(email,password);assert.ok(fresh);await logoutAccount(request(fresh));assert.equal(await currentAccount(request(fresh)),null,'logout revokes token');
|
||||
const oldSession=await loginAccount(email,password);assert.ok(oldSession);
|
||||
const resets=[newToken(),newToken()],replacement='a new secure test password';
|
||||
for(const value of resets)await db().query("INSERT INTO account_tokens VALUES ($1,$2,'reset',now()+interval '30 minutes')",[tokenDigest(value),id]);
|
||||
const resetResults=await Promise.all(resets.map(value=>resetPassword(value,replacement)));
|
||||
assert.deepEqual(resetResults.sort(),[false,true],'Only one concurrent reset may succeed for one account');
|
||||
assert.equal(await currentAccount(request(oldSession)),null,'Reset revokes existing sessions');
|
||||
assert.equal(await loginAccount(email,password),null,'Original password is no longer accepted');
|
||||
assert.ok(await loginAccount(email,replacement));
|
||||
assert.equal(await resetPassword(resets[0],password),false,'Reset links are single-use, including sibling links');
|
||||
const expired=newToken();await db().query("INSERT INTO account_tokens VALUES ($1,$2,'reset',now()-interval '1 minute')",[tokenDigest(expired),id]);
|
||||
assert.equal(await resetPassword(expired,password),false);
|
||||
const wrongKind=newToken();await db().query("INSERT INTO account_tokens VALUES ($1,$2,'verify',now()+interval '30 minutes')",[tokenDigest(wrongKind),id]);
|
||||
assert.equal(await resetPassword(wrongKind,password),false,'Email verification cannot reset a password');
|
||||
assert.equal(await resetPassword(newToken(),'short'),false);
|
||||
const post=(action:string,body:object,origin=process.env.ACCOUNT_PUBLIC_ORIGIN||base)=>fetch(base+'/api/account/'+action,{method:'POST',headers:{'Content-Type':'application/json',Origin:origin},body:JSON.stringify(body)});
|
||||
assert.equal((await post('forgot',{email},'https://untrusted.invalid')).status,403,'Cross-origin recovery is rejected');
|
||||
const unknown=await post('forgot',{email:randomUUID()+'@example.com'});
|
||||
assert.equal(unknown.status,200,'Unknown email receives the same non-enumerating response without sending mail');
|
||||
assert.match((await unknown.json()).message,/若该邮箱/);
|
||||
const httpToken=newToken(),httpPassword='http replacement secure password';
|
||||
const priorHttpSession=await loginAccount(email,replacement);assert.ok(priorHttpSession);
|
||||
await db().query("INSERT INTO account_tokens VALUES ($1,$2,'reset',now()+interval '30 minutes')",[tokenDigest(httpToken),id]);
|
||||
const changed=await post('reset',{token:httpToken,password:httpPassword});
|
||||
assert.equal(changed.status,200);
|
||||
assert.match(changed.headers.get('set-cookie')||'',/Max-Age=0/);
|
||||
assert.equal(await currentAccount(request(priorHttpSession)),null);
|
||||
assert.ok(await loginAccount(email,httpPassword),'HTTP recovery changes the stored password');
|
||||
assert.equal((await post('reset',{token:httpToken,password:replacement})).status,400,'HTTP recovery rejects a consumed token');
|
||||
const key=randomUUID();assert.deepEqual(await Promise.all(Array.from({length:5},()=>rateLimit(key,3))).then(a=>a.sort()),[false,false,true,true,true]);
|
||||
await db().query('DELETE FROM account_limits WHERE key=$1',[tokenDigest(key)]);
|
||||
} finally {await db().query('DELETE FROM account_users WHERE id=$1',[id]);}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeEmail,validPassword,hashPassword,checkPassword,newToken,tokenDigest,accountCookie,trustedOrigin } from '../src/lib/account-crypto';
|
||||
test('canonical email and bounded passwords',()=>{assert.equal(normalizeEmail(' Test@Example.COM '),'test@example.com');assert.equal(normalizeEmail('a@b\r\nBcc:x@y.com'),null);assert.equal(validPassword('short'),false);assert.equal(validPassword('界'.repeat(100)),false);});
|
||||
test('salted passwords and constant size opaque token digests',async()=>{const a=await hashPassword('long enough password');const b=await hashPassword('long enough password');assert.notEqual(a,b);assert.equal(await checkPassword('long enough password',a),true);assert.equal(await checkPassword('wrong password',a),false);const t=newToken();assert.equal(t.length,64);assert.equal(tokenDigest(t).length,64);assert.notEqual(tokenDigest(t),t);});
|
||||
test('origin checks reject missing and cross-site origins',()=>{const r=(origin?:string,site?:string)=>new Request('https://wiki.example/api/account/login',{headers:{...(origin?{origin}:{}),...(site?{'sec-fetch-site':site}:{})}});assert.equal(trustedOrigin(r()),false);assert.equal(trustedOrigin(r('https://evil.example')),false);assert.equal(trustedOrigin(r('https://wiki.example','cross-site')),false);assert.equal(trustedOrigin(r('https://wiki.example')),true);});
|
||||
test('account cookie is distinct, HTTP-only and expires on logout',()=>{assert.match(accountCookie('abc'),/^wiki_account=abc;/);assert.match(accountCookie('abc'),/HttpOnly; SameSite=Lax/);assert.match(accountCookie('',true),/Max-Age=0/);});
|
||||
@@ -1,64 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import {apiDocuments,serveApiDocumentation} from '../src/lib/api-documentation';
|
||||
import index from '../src/pages/api/index';
|
||||
|
||||
function response(){
|
||||
const state={status:0,headers:{} as Record<string,string>,body:undefined as unknown};
|
||||
const res={setHeader(name:string,value:string){state.headers[name]=value;return res;},status(code:number){state.status=code;return res;},send(body:unknown){state.body=body;return res;},json(body:unknown){state.body=body;return res;},end(){return res;}};
|
||||
return {state,res:res as unknown as NextApiResponse};
|
||||
}
|
||||
const request=(method:string,agent_mode:unknown)=>({method,query:{agent_mode}} as unknown as NextApiRequest);
|
||||
|
||||
test('every business handler serves documentation before validating parameters or accessing dependencies',async()=>{
|
||||
const routes:Record<string,string>={
|
||||
'/api/canvases/{...path}':'canvases/[[...path]]','/api/explore-feed':'explore-feed','/api/feed':'feed','/api/notes/{id}':'notes/[id]',
|
||||
'/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',
|
||||
};
|
||||
for(const [path,route] of Object.entries(routes)){
|
||||
const {default:handler}=await import('../src/pages/api/'+route+'.ts');
|
||||
for(const method of ['GET','HEAD']){
|
||||
const {state,res}=response();
|
||||
await handler(request(method,'tRuE'),res);
|
||||
assert.equal(state.status,200,path);
|
||||
assert.equal(state.headers['Content-Type'],'text/plain; charset=utf-8',path);
|
||||
if(method==='HEAD')assert.equal(state.body,undefined);else {
|
||||
assert.ok(String(state.body).includes(path),path);
|
||||
assert.ok(String(state.body).includes('参数'),path);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(Object.keys(routes).sort(),Object.keys(apiDocuments).sort());
|
||||
});
|
||||
|
||||
test('normal calls and mutations do not enter documentation mode',()=>{
|
||||
for(const [method,value] of [['GET',undefined],['GET','false'],['GET',['True','false']],['POST','True'],['PUT','True'],['DELETE','True']]){
|
||||
const {state,res}=response();
|
||||
assert.equal(serveApiDocumentation(request(method as string,value),res,'/api/posts'),false);
|
||||
assert.equal(state.status,0);
|
||||
}
|
||||
});
|
||||
|
||||
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','/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()=>{
|
||||
const {default:handler}=await import('../src/pages/api/health');
|
||||
const {state,res}=response();handler(request('GET',undefined),res);
|
||||
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),/原生页面/);
|
||||
}
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {postInput} from '../src/lib/write';
|
||||
import {noteEditInput,withRevision} from '../src/lib/note-edits';
|
||||
import {publicPostId} from '../src/lib/model';
|
||||
import {entryText,type ExploreEntry} from '../src/lib/explore';
|
||||
test('generic API accepts stable public IDs while retaining UUID storage and rejecting invalid IDs',()=>{
|
||||
const publicId='0123456789abcdef01234567',stored=randomUUID();
|
||||
assert.equal(postInput.parse({kind:'article',title:'文本与图像',publicId}).publicId,publicId);
|
||||
for(const id of ['bad','ABCDEF0123456789abcdef01','1'.repeat(25)])assert.equal(postInput.safeParse({kind:'article',title:'x',publicId:id}).success,false);
|
||||
assert.equal(publicPostId({id:stored,public_id:publicId}),publicId);assert.equal(publicPostId({id:stored}),stored);
|
||||
});
|
||||
test('media/cover edits are optional and change optimistic revisions independently of the text',()=>{
|
||||
const a=randomUUID(),b=randomUUID();
|
||||
const entry:ExploreEntry={id:'0123456789abcdef01234567',title:'笔记',description:'说明',markdown:'# 笔记\n\n正文',namespace:'Main',categories:[],imageCount:1,media:[],color:'#fff',assets:[{id:a,kind:'image',role:'content'}],coverAssetId:a};
|
||||
const before=withRevision(entry).revision;
|
||||
assert.notEqual(withRevision({...entry,coverAssetId:b}).revision,before);
|
||||
assert.notEqual(withRevision({...entry,assets:[{id:b,kind:'image',role:'content'}]}).revision,before);
|
||||
const input={title:'笔记',description:'说明',markdown:'正文',tags:[],revision:before};
|
||||
assert.equal(noteEditInput.parse(input).assets,undefined);
|
||||
assert.equal(noteEditInput.parse({...input,assets:[{id:a}],coverAssetId:null}).assets?.[0].role,'content');
|
||||
});
|
||||
test('AI text preserves JSON, code and media links as ordinary modalities',()=>{
|
||||
const id=randomUUID(),markdown='# 文本说明\n\n```json\n{"type":"text","box":[1,2,3,4]}\n```\n\n```tsx\nexport default function Example(){return <div/>}\n```';
|
||||
const entry:ExploreEntry={id,title:'文本说明',description:'可访问',markdown,namespace:'Main',categories:[],imageCount:1,media:[{kind:'image',url:'/api/media/'+randomUUID(),title:'标注图'}],color:'#fff'};
|
||||
const text=entryText(entry);assert.ok(text.includes(markdown));assert.ok(text.includes(entry.media[0].url));assert.ok(text.includes('/explore/'+id));
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {base32,totp,matchingStep,newAuthConfig,signSession,validSession,sessionCookie,safeReturn,authConfig,isLoginRedirect} from '../src/lib/auth';
|
||||
import {proxy} from '../src/proxy';
|
||||
import {NextRequest} from 'next/server';
|
||||
import {mkdtempSync,writeFileSync,rmSync} from 'node:fs';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
test('TOTP matches RFC 6238 SHA-1 test vectors',()=>{
|
||||
const secret=base32(Buffer.from('12345678901234567890'));
|
||||
for(const [time,expected] of [[59,'94287082'],[1111111109,'07081804'],[1111111111,'14050471'],[1234567890,'89005924'],[2000000000,'69279037'],[20000000000,'65353130']] as const) assert.equal(totp(secret,Math.floor(time/30),8),expected);
|
||||
assert.equal(matchingStep(secret,totp(secret,100),3000000),100);
|
||||
assert.equal(matchingStep(secret,totp(secret,99),3000000),99);
|
||||
assert.equal(matchingStep(secret,totp(secret,98),3000000),null);
|
||||
assert.equal(matchingStep(secret,'123',3000000),null);
|
||||
});
|
||||
test('JWT rejects tampering, expiry, wrong keys and malformed values',()=>{
|
||||
const config=newAuthConfig(),token=signSession(config,1000);
|
||||
assert.equal(validSession(token,config,1000),true);
|
||||
assert.equal(validSession(token,config,1000+604800),false);
|
||||
assert.equal(validSession(token,config,900),false);
|
||||
assert.equal(validSession(token,newAuthConfig(),1000),false);
|
||||
assert.equal(validSession(token+'x',config,1000),false);
|
||||
assert.equal(validSession('eyJhbGciOiJub25lIn0.e30.',config,1000),false);
|
||||
assert.equal(validSession(undefined,config),false);
|
||||
});
|
||||
test('cookies are HTTP-only and secure by default; redirects stay local',()=>{
|
||||
assert.match(sessionCookie('test'),/HttpOnly; SameSite=Lax; Max-Age=604800; Secure$/);
|
||||
assert.match(sessionCookie('',true),/Max-Age=0/);
|
||||
for(const path of ['https://evil.test','//evil.test','/\\evil.test','/login?next=/','/\nLocation: bad']) assert.equal(safeReturn(path),'/');
|
||||
assert.equal(safeReturn('/explore/123?q=test'),'/explore/123?q=test');
|
||||
});
|
||||
test('proxy exposes creative entry pages while protecting APIs, data and Studio documents; fails closed',()=>{
|
||||
const temp=mkdtempSync(join(tmpdir(),'prompt-auth-')); const old=process.env.AUTH_CONFIG_FILE;
|
||||
try{
|
||||
const config=newAuthConfig(); process.env.AUTH_CONFIG_FILE=join(temp,'config.json'); writeFileSync(process.env.AUTH_CONFIG_FILE,JSON.stringify(config));
|
||||
for(const path of ['/library/import','/skills/example.png','/_next/data/build/library/import.json','/studio/layouts/ref-01']) assert.equal(proxy(new NextRequest('http://wiki.test'+path)).status,307,path);
|
||||
for(const path of ['/api/upload','/studio/api/export','/studio/api/layouts','/api/feed']) assert.equal(proxy(new NextRequest('http://wiki.test'+path)).status,401,path);
|
||||
for(const path of ['/','/_next/data/build/index.json','/llms.txt','/index.md','/agent','/agent/index.md','/api/agent-index','/api/guides','/write','/documents','/api/documents','/api/documents/preview','/guide/welcome','/protocol','/api/guides/welcome','/account','/api/account/session','/login','/brand-mark.svg','/_next/static/chunk.js','/api/health','/api/ready']) assert.equal(proxy(new NextRequest('http://wiki.test'+path)).status,200,path);
|
||||
const creativeEntries=['/favicon.ico','/apple-touch-icon.png','/brand/logo-light.svg','/brand/logo-dark.svg','/brand/icon-dark.svg','/studio/favicon.ico','/studio/apple-touch-icon.png','/studio/brand/logo-light.svg','/studio/brand/logo-dark.svg','/studio/brand/icon-dark.svg','/workspace','/graphic','/infinite_canvas','/studio','/studio/graphic','/studio/infinite_canvas','/studio/api','/studio/_next/static/chunk.js'];
|
||||
for(const path of creativeEntries){
|
||||
for(const method of ['GET','HEAD'])assert.equal(proxy(new NextRequest('http://wiki.test'+path,{method})).status,200,`${method} ${path}`);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test'+path,{method:'POST'})).status,401,`POST ${path} must not bypass authentication`);
|
||||
}
|
||||
const headers={cookie:'prompt_session='+signSession(config),host:'wiki.test'};
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/feed',{headers})).status,200);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/posts',{method:'POST',headers:{...headers,origin:'http://evil.test'}})).status,403);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/posts',{method:'POST',headers:{...headers,origin:'http://wiki.test'}})).status,200);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/posts',{method:'POST',headers:{cookie:'wiki_account='+ 'a'.repeat(64)}})).status,401);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/guide/welcome',{method:'POST'})).status,401);
|
||||
for(const path of ['/api/guides','/api/agent-index']) assert.equal(proxy(new NextRequest('http://wiki.test'+path,{method:'POST'})).status,401,path);
|
||||
writeFileSync(process.env.AUTH_CONFIG_FILE,'{}'); assert.throws(()=>authConfig()); assert.equal(proxy(new NextRequest('http://wiki.test/api/posts')).status,503);
|
||||
delete process.env.AUTH_CONFIG_FILE;
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/posts')).status,503,'Missing admin configuration fails closed');
|
||||
}finally{if(old===undefined)delete process.env.AUTH_CONFIG_FILE;else process.env.AUTH_CONFIG_FILE=old;rmSync(temp,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
test('login redirects recognize browser pages and Next.js data destinations',()=>{
|
||||
const base='http://wiki.test';
|
||||
for(const target of ['/login?next=%2F','http://wiki.test/login','/_next/data/build-123/login.json?next=%2F']) assert.equal(isLoginRedirect(target,base),true,target);
|
||||
for(const target of [null,'','https://evil.test/login','//evil.test/login','/api/login.json','/_next/data/build-123/index.json']) assert.equal(isLoginRedirect(target,base),false,String(target));
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* Recover once from an idempotent document GET's transient proxy failure.
|
||||
* This never retries hydration, theme assertions, or mutations, and shares one
|
||||
* 60-second budget across both attempts rather than extending the deadline.
|
||||
* @param {(timeout: number) => Promise<{ok(): boolean, status(): number} | null>} navigate
|
||||
* @param {string} url
|
||||
* @param {() => number} now
|
||||
*/
|
||||
export async function navigateBrandDocument(navigate, url, now = Date.now) {
|
||||
const deadline = now() + 60000;
|
||||
for (let attempt = 1; attempt <= 2; attempt++) {
|
||||
const remaining = deadline - now();
|
||||
if (remaining <= 0) throw new Error(`Document navigation budget exhausted: ${url}`);
|
||||
try {
|
||||
const response = await navigate(remaining);
|
||||
if (response?.ok()) return response;
|
||||
const status = response?.status();
|
||||
if (attempt === 1 && [500, 502, 503, 504].includes(status ?? 0)) {
|
||||
console.warn('Brand navigation proxy recovery', JSON.stringify({url, status, attempt}));
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Document navigation failed: ${url}, HTTP ${status ?? 'no response'}`);
|
||||
} catch (error) {
|
||||
if (attempt === 1 && /ECONNRESET|net::ERR_(?:CONNECTION_RESET|CONNECTION_CLOSED|EMPTY_RESPONSE|ABORTED)/.test(String(error))) {
|
||||
console.warn('Brand navigation connection recovery', JSON.stringify({url, error: String(error), attempt}));
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
throw new Error(`Document navigation failed: ${url}`);
|
||||
}
|
||||
|
||||
/** Load a document fully before relying on server-rendered text or leaving it.
|
||||
* Only document GETs may recover; application assertions remain outside retry.
|
||||
* @param {import('playwright-core').Page} page
|
||||
* @param {string} url
|
||||
* @param {boolean} reload
|
||||
*/
|
||||
export async function visitBrowserDocument(page, url, reload = false) {
|
||||
return navigateBrandDocument(async timeout => {
|
||||
const started = Date.now();
|
||||
const scripts = new Set(), failures = [];
|
||||
const requested = request => { if (request.resourceType() === 'script') scripts.add(request); };
|
||||
const failed = request => { if (scripts.has(request)) failures.push(request.failure()?.errorText || 'unknown script failure'); };
|
||||
page.on('request', requested);
|
||||
page.on('requestfailed', failed);
|
||||
try {
|
||||
const response = await (reload ? page.reload({waitUntil: 'domcontentloaded', timeout}) : page.goto(url, {waitUntil: 'domcontentloaded', timeout}));
|
||||
if (response?.ok()) {
|
||||
const remaining = timeout - (Date.now() - started);
|
||||
if (remaining <= 0) throw new Error('Document hydration budget exhausted: ' + url);
|
||||
try {
|
||||
// Responsive layouts may hide the toggle. Its mounted ready marker
|
||||
// proves hydration; each caller still checks the controls it needs.
|
||||
// A cancelled script may be a preload duplicate. Hydration is the
|
||||
// authority; recover only when cancellation actually blocks startup.
|
||||
await page.locator('button[data-theme-ready="true"]').first().waitFor({state: 'attached', timeout: failures.length ? Math.min(5000, remaining) : remaining});
|
||||
} catch (error) {
|
||||
if (failures.length) throw new Error('Document bootstrap script request failed: ' + failures.join('; '), {cause: error});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
} finally {
|
||||
page.off('request', requested);
|
||||
page.off('requestfailed', failed);
|
||||
}
|
||||
}, url);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {navigateBrandDocument, visitBrowserDocument} from './brand-navigation.mjs';
|
||||
const response = status => ({ok: () => status === 200, status: () => status});
|
||||
|
||||
test('successful documents are fetched once', async () => {
|
||||
let calls = 0;
|
||||
await navigateBrandDocument(async () => { calls++; return response(200); }, '/canvas');
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
test('one proxy failure can recover within the original deadline', async () => {
|
||||
const timeouts = []; let elapsed = 0;
|
||||
await navigateBrandDocument(async timeout => {
|
||||
timeouts.push(timeout); elapsed = 15000;
|
||||
return response(timeouts.length === 1 ? 500 : 200);
|
||||
}, '/canvas', () => elapsed);
|
||||
assert.deepEqual(timeouts, [60000, 45000]);
|
||||
});
|
||||
test('connection reset and interrupted bootstrap scripts can recover once', async () => {
|
||||
for(const failure of ['net::ERR_CONNECTION_RESET','Document bootstrap script request failed: net::ERR_ABORTED']){
|
||||
let calls = 0;
|
||||
await navigateBrandDocument(async () => {
|
||||
if (++calls === 1) throw new Error(failure);
|
||||
return response(200);
|
||||
}, '/canvas');
|
||||
assert.equal(calls, 2);
|
||||
}
|
||||
});
|
||||
test('persistent server failure is not hidden', async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(navigateBrandDocument(async () => { calls++; return response(502); }, '/canvas'), /HTTP 502/);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
test('missing routes, authentication failures and ordinary timeouts are not retried', async () => {
|
||||
for (const status of [401, 403, 404]) {
|
||||
let calls = 0;
|
||||
await assert.rejects(navigateBrandDocument(async () => { calls++; return response(status); }, '/canvas'), /HTTP/);
|
||||
assert.equal(calls, 1);
|
||||
}
|
||||
let calls = 0;
|
||||
await assert.rejects(navigateBrandDocument(async () => { calls++; throw new Error('Timeout 60000ms exceeded'); }, '/canvas'), /Timeout/);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
test('recovery cannot extend the total navigation budget', async () => {
|
||||
let calls = 0, elapsed = 0;
|
||||
await assert.rejects(navigateBrandDocument(async () => {
|
||||
calls++; elapsed = 60000; return response(503);
|
||||
}, '/canvas', () => elapsed), /budget exhausted/);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
function browserFixture(failBootstrap = false, failHydration = false, blockedOnce = false, readyVisible = true) {
|
||||
const listeners = new Map(), calls = [];
|
||||
const page = {
|
||||
on(event, fn) { if (!listeners.has(event)) listeners.set(event, new Set()); listeners.get(event).add(fn); },
|
||||
off(event, fn) { listeners.get(event)?.delete(fn); },
|
||||
async goto(url, options) {
|
||||
calls.push(options.waitUntil);
|
||||
const request = {resourceType: () => 'script', failure: () => ({errorText: 'net::ERR_ABORTED'})};
|
||||
for (const fn of listeners.get('request') || []) fn(request);
|
||||
if (failBootstrap && calls.length === 1) for (const fn of listeners.get('requestfailed') || []) fn(request);
|
||||
return response(200);
|
||||
},
|
||||
locator() { return {first: () => ({waitFor: async options => { calls.push('hydrated'); if (!readyVisible && options.state !== 'attached') throw Error('Ready marker is hidden by responsive CSS'); if (failHydration || (blockedOnce && calls.length === 2)) throw Error('Hydration timeout'); }})}; },
|
||||
};
|
||||
return {page, calls, listeners};
|
||||
}
|
||||
test('document visit completes deferred scripts before checking hydration and removes listeners', async () => {
|
||||
const {page, calls, listeners} = browserFixture();
|
||||
await visitBrowserDocument(page, '/account');
|
||||
assert.deepEqual(calls, ['domcontentloaded', 'hydrated']);
|
||||
assert.ok([...listeners.values()].every(set => set.size === 0));
|
||||
});
|
||||
test('interrupted bootstrap retries only document loading before hydration', async () => {
|
||||
const {page, calls} = browserFixture(true, false, true);
|
||||
await visitBrowserDocument(page, '/account');
|
||||
assert.deepEqual(calls, ['domcontentloaded', 'hydrated', 'domcontentloaded', 'hydrated']);
|
||||
});
|
||||
test('hydration failure is surfaced without retrying the application', async () => {
|
||||
const {page, calls} = browserFixture(false, true);
|
||||
await assert.rejects(visitBrowserDocument(page, '/account'), /Hydration timeout/);
|
||||
assert.deepEqual(calls, ['domcontentloaded', 'hydrated']);
|
||||
});
|
||||
|
||||
test('cancelled script does not reject an already hydrated document', async () => {
|
||||
const {page, calls} = browserFixture(true);
|
||||
await visitBrowserDocument(page, '/account');
|
||||
assert.deepEqual(calls, ['domcontentloaded', 'hydrated']);
|
||||
});
|
||||
|
||||
test('hydrated pages are ready even when responsive CSS hides the marker', async () => {
|
||||
const {page, calls} = browserFixture(false, false, false, false);
|
||||
await visitBrowserDocument(page, '/graphic');
|
||||
assert.deepEqual(calls, ['domcontentloaded', 'hydrated']);
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
/** CI-only checks against the disposable stack, never against personal documents. */
|
||||
import assert from 'node:assert/strict';
|
||||
import { chromium, type Request } from 'playwright-core';
|
||||
import { visitBrowserDocument } from './brand-navigation.mjs';
|
||||
export async function verifyBrandUI(base: string) {
|
||||
for (const prefix of process.env.VERIFY_CANVAS_UI === '1' ? ['', '/studio'] : ['']) {
|
||||
const icon = await fetch(`${base}${prefix}/favicon.ico`);
|
||||
assert.equal(icon.status, 200);
|
||||
const bytes = new Uint8Array(await icon.arrayBuffer());
|
||||
assert.deepEqual([...bytes.slice(0, 4)], [0, 0, 1, 0]);
|
||||
assert.equal(bytes[4], 7, 'favicon includes seven resolutions');
|
||||
for (const file of ['logo-light.svg', 'logo-dark.svg', 'icon-dark.svg']) {
|
||||
const image = await fetch(`${base}${prefix}/brand/${file}`);
|
||||
assert.equal(image.status, 200, prefix + '/' + file);
|
||||
assert.match(await image.text(), /<svg/);
|
||||
}
|
||||
}
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium', headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] });
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 960 } });
|
||||
page.setDefaultTimeout(60000);page.setDefaultNavigationTimeout(60000);
|
||||
const failures: string[] = [], scripts: {path:string;status?:number;ms:number;error?:string}[] = [];
|
||||
const scriptStarted = new WeakMap<Request,number>();
|
||||
page.on('request', request => { if(request.resourceType()==='script') scriptStarted.set(request,Date.now()); });
|
||||
page.on('response', response => { if(response.request().resourceType()==='script') { scripts.push({path:new URL(response.url()).pathname,status:response.status(),ms:Date.now()-(scriptStarted.get(response.request())??Date.now())}); if(scripts.length>24)scripts.shift(); } });
|
||||
page.on('pageerror', error => failures.push(error.message));
|
||||
page.on('requestfailed', request => { failures.push(new URL(request.url()).pathname + ': ' + request.failure()?.errorText); if(request.resourceType()==='script') scripts.push({path:new URL(request.url()).pathname,ms:Date.now()-(scriptStarted.get(request)??Date.now()),error:request.failure()?.errorText}); });
|
||||
const visit = async (path: string, theme: string) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
await visitBrowserDocument(page, base + path);
|
||||
await page.waitForFunction(expected => document.documentElement.dataset.theme === expected, theme);
|
||||
console.log('Brand UI route ready:', path, theme, Date.now() - started);
|
||||
} catch (error) {
|
||||
console.error('Brand UI navigation diagnostics', JSON.stringify({path, url:page.url(), elapsedMs:Date.now()-started, failures:failures.slice(-20), scripts:scripts.slice(-24), controls:await page.locator('[data-theme-ready]').evaluateAll(elements=>elements.map(el=>({ready:el.getAttribute('data-theme-ready'),display:getComputedStyle(el).display}))), body:(await page.locator('body').innerText({timeout:3000}).catch(()=>'unavailable')).slice(0,1200)}));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const background = (selector: string) => page.locator(selector).first().evaluate(el => getComputedStyle(el).backgroundColor);
|
||||
await visit('/', 'home-light');
|
||||
assert.equal(await background('body'), 'rgb(255, 246, 239)');
|
||||
assert.ok((await page.title()).includes('啡跃'));
|
||||
assert.ok((await page.locator('link[rel="icon"]').all()).length >= 2);
|
||||
assert.equal(await page.locator('.endoleap-mark-light').first().isVisible(), true);
|
||||
await page.getByRole('button', { name: '切换明暗主题', exact: true }).first().click();
|
||||
await page.waitForFunction(() => document.documentElement.dataset.theme === 'home-dark');
|
||||
assert.equal(await background('body'), 'rgb(28, 24, 22)');
|
||||
assert.equal(await page.locator('.endoleap-mark-dark').first().isVisible(), true);
|
||||
await visit('/account', 'home-dark');
|
||||
if (process.env.VERIFY_CANVAS_UI === '1') {
|
||||
await visit('/graphic', 'canvas-dark');
|
||||
assert.equal(await background('body'), 'rgb(20, 20, 20)');
|
||||
assert.equal(await page.locator('[class*="boardWrap"] > div').first().evaluate(el => getComputedStyle(el).backgroundColor), 'rgb(255, 255, 255)', 'artwork stays white in dark chrome');
|
||||
await page.getByRole('button', { name: '切换明暗主题', exact: true }).first().click();
|
||||
await page.waitForFunction(() => document.documentElement.dataset.theme === 'canvas-light');
|
||||
await visit('/infinite_canvas', 'canvas-light');
|
||||
assert.equal(await background('[class*="viewport"]'), 'rgb(250, 250, 250)');
|
||||
} else {
|
||||
await page.getByRole('button', { name: '切换明暗主题', exact: true }).first().click();
|
||||
}
|
||||
await visit('/', 'home-light');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert.equal(await page.locator('.endoleap-mark-light').first().isVisible(), true);
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'mobile home has no horizontal overflow');
|
||||
for (const width of [390, 320]) {
|
||||
await page.setViewportSize({ width, height: 844 });
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'Editorial home fits narrow screens');
|
||||
const entry = await page.getByRole('navigation', {name: '主导航'}).getByRole('link', {name: /进入工作台/}).boundingBox();
|
||||
assert.ok(entry && entry.x >= 0 && entry.x + entry.width <= width, 'Workspace entry is visible, not clipped');
|
||||
assert.equal(await page.getByRole('link', {name: /去知识空间逛逛/}).getAttribute('href'), '/documents');
|
||||
assert.equal(await page.getByRole('link', {name: '开始创作', exact: true}).getAttribute('href'), '/account?next=/workspace');
|
||||
}
|
||||
console.log('Endoleap logos, both favicon paths, persisted home/canvas themes and artwork color isolation passed.');
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {db} from '../src/lib/db';
|
||||
import {newToken,tokenDigest,ACCOUNT_COOKIE} from '../src/lib/account-crypto';
|
||||
import type {CanvasDocument} from '../src/lib/canvas-document';
|
||||
export async function verifyCanvasWorkspace(base:string){
|
||||
const identities=await Promise.all([0,1].map(async()=>{const id=randomUUID(),token=newToken();await db().query("INSERT INTO account_users(id,email,password_hash,verified_at) VALUES($1,$2,'test',now())",[id,id+'@example.com']);await db().query("INSERT INTO account_tokens(digest,user_id,kind,expires_at) VALUES($1,$2,'session',now()+interval '1 hour')",[tokenDigest(token),id]);return {[`cookie`]:ACCOUNT_COOKIE+'='+token}}));
|
||||
const origin=process.env.ACCOUNT_PUBLIC_ORIGIN||base;
|
||||
const call=(path:string,method='GET',body?:unknown,headers:Record<string,string>={})=>fetch(base+'/api/canvases'+path,{method,headers:{'Content-Type':'application/json',origin,...headers},...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
const doc={version:1,cards:[{id:'note',kind:'text',title:'简报',text:'自然光与城市清晨',x:0,y:0},{id:'script',kind:'script',title:'脚本',text:'',instruction:'写六个分镜',operation:'script',x:500,y:0}],links:[['note','script']]};
|
||||
assert.equal((await call('','POST',{document:doc})).status,401);
|
||||
const create=await call('','POST',{document:doc},identities[0]);assert.equal(create.status,201,await create.clone().text());const canvas=await create.json();assert.equal(canvas.revision,1);
|
||||
const root='/'+canvas.id;
|
||||
assert.equal((await call(root,'GET',undefined,identities[1])).status,404);
|
||||
assert.equal((await call(root,'PUT',{revision:1,document:doc},{...identities[0],origin:'https://evil.example'})).status,403);
|
||||
assert.equal((await call(root,'PUT',{revision:1,document:doc},{...identities[0],authorization:'Bearer invalid',origin:'https://evil.example'})).status,404,'A bearer request cannot fall back to an owner cookie');
|
||||
assert.equal((await call(root,'PUT',{revision:1,document:{...doc,links:[['note','script'],['script','note']]}},identities[0])).status,400,'Imported cyclic graphs are rejected');
|
||||
const linked=await call(root+'/link','POST',{},identities[0]);assert.equal(linked.status,201);const credentials=await linked.json();const agent={authorization:'Bearer '+credentials.token};
|
||||
assert.equal((await call('','GET',undefined,agent)).status,401);
|
||||
const other=await (await call('','POST',{document:doc},identities[0])).json();assert.equal((await call('/'+other.id,'GET',undefined,agent)).status,404,'A link cannot read another canvas');
|
||||
assert.equal((await call(root,'PUT',{revision:1,document:doc},identities[0])).status,200);
|
||||
assert.equal((await call(root,'PUT',{revision:1,document:doc},identities[0])).status,409);
|
||||
async function queue(rev:number){const r=await call(root+'/tasks','POST',{revision:rev,targetId:'script'},identities[0]);assert.equal(r.status,201,await r.clone().text());return (await r.json()).id as string}
|
||||
const concurrent=await Promise.all([0,1].map(()=>call('/'+other.id,'PUT',{revision:1,document:doc},identities[0])));
|
||||
assert.deepEqual(concurrent.map(r=>r.status).sort(),[200,409],'Concurrent saves cannot lose an update');
|
||||
const first=await queue(2);
|
||||
assert.equal((await call(root+'/tasks','POST',{revision:2,targetId:'script'},identities[0])).status,409,'Only one live task per target');
|
||||
const recipe=await (await call(root+'/tasks/'+first,'GET',undefined,agent)).json();assert.equal(recipe.request.references[0].text,doc.cards[0].text);assert.equal(recipe.request.instruction,'写六个分镜');
|
||||
assert.equal((await call(root+'/tasks/'+first,'GET',undefined,identities[1])).status,404);
|
||||
const result={status:'succeeded',result:{text:'第一镜:城市醒来。'}};
|
||||
assert.equal((await call(root+'/tasks/'+first,'PATCH',result,agent)).status,409,'Result cannot arrive before claim');
|
||||
assert.equal((await call(root+'/tasks/'+first,'PATCH',{status:'running'},agent)).status,200);
|
||||
assert.equal((await call(root,'PUT',{revision:2,document:{...doc,cards:doc.cards.map(n=>({...n,x:n.x+10}))}},identities[0])).status,200);
|
||||
assert.equal((await call(root+'/tasks/'+first,'PATCH',result,agent)).status,409,'Stale result must not overwrite newer user edits');
|
||||
assert.equal((await call(root+'/tasks/'+first,'PATCH',{status:'failed',error:'依据新版本重新派发'},identities[0])).status,200);
|
||||
const second=await queue(3);assert.equal((await call(root+'/tasks/'+second,'PATCH',{status:'running'},agent)).status,200);
|
||||
assert.equal((await call(root+'/tasks/'+second,'PATCH',{status:'succeeded',result:{text:{invalid:true}}},agent)).status,400,'Malformed results do not mutate the canvas');
|
||||
assert.equal((await call(root+'/tasks/'+second,'PATCH',{status:'succeeded',result:{image:'data:image/png;base64,AAAA'}},agent)).status,400,'A script node cannot accept an image result');
|
||||
assert.equal((await call(root+'/tasks/'+second,'PATCH',result,agent)).status,200);
|
||||
assert.equal((await call(root+'/tasks/'+second,'PATCH',result,agent)).status,200,'Identical completion is idempotent');
|
||||
assert.equal((await call(root+'/tasks/'+second,'PATCH',{status:'succeeded',result:{text:'覆盖'}},agent)).status,409);
|
||||
const final=await (await call(root,'GET',undefined,identities[0])).json();assert.equal(final.revision,4);assert.equal(final.document.cards.find((n:{id:string})=>n.id==='script').text,'第一镜:城市醒来。');assert.deepEqual(final.document.links,doc.links);
|
||||
const png='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=';
|
||||
const imageDocument:CanvasDocument={version:1,cards:[
|
||||
{id:'source',kind:'image',title:'参考图',text:'保留原图',image:png,x:0,y:0},
|
||||
{id:'generated',kind:'image',title:'图生图',text:'',instruction:'保留构图,改为雪夜',operation:'generate',x:500,y:0},
|
||||
{id:'upscaled',kind:'image',title:'图片高清',text:'',operation:'upscale',x:1000,y:0},
|
||||
],links:[['source','generated'],['generated','upscaled']]};
|
||||
const imageCreate=await call('','POST',{document:imageDocument},identities[0]);assert.equal(imageCreate.status,201);
|
||||
const imageCanvas=await imageCreate.json(),imageRoot='/'+imageCanvas.id;
|
||||
const imageLink=await call(imageRoot+'/link','POST',{},identities[0]);assert.equal(imageLink.status,201);
|
||||
const imageAgent={authorization:'Bearer '+(await imageLink.json()).token};
|
||||
for(const [index,targetId] of ['generated','upscaled'].entries()){
|
||||
const queued=await call(imageRoot+'/tasks','POST',{revision:index+1,targetId},identities[0]);assert.equal(queued.status,201,await queued.clone().text());
|
||||
const taskId=(await queued.json()).id,taskPath=imageRoot+'/tasks/'+taskId;
|
||||
const snapshotResponse=await call(taskPath,'GET',undefined,imageAgent);assert.equal(snapshotResponse.status,200);
|
||||
const snapshot=await snapshotResponse.json();assert.equal(snapshot.request.operation,index===0?'generate':'upscale');
|
||||
assert.equal(snapshot.request.references[0].id,index===0?'source':'generated');
|
||||
assert.equal(snapshot.request.references[0].image,png,'Image tasks carry the referenced image bytes');
|
||||
assert.deepEqual(snapshot.request.result.allowedFields,['image','text']);
|
||||
assert.equal((await call(taskPath,'PATCH',{status:'running'},imageAgent)).status,200);
|
||||
const completion={status:'succeeded',result:{image:png,text:index===0?'雪夜图片结果':'高清图片结果'}};
|
||||
const completed=await call(taskPath,'PATCH',completion,imageAgent);assert.equal(completed.status,200,await completed.clone().text());
|
||||
assert.equal((await call(taskPath,'PATCH',completion,imageAgent)).status,200,'Image completion retries are idempotent');
|
||||
const stateResponse=await call(imageRoot,'GET',undefined,identities[0]);assert.equal(stateResponse.status,200);
|
||||
const state=await stateResponse.json();assert.equal(state.revision,index+2);
|
||||
const cards=(state.document as CanvasDocument).cards;
|
||||
assert.equal(cards.find(n=>n.id===targetId)?.image,png);assert.equal(cards.find(n=>n.id===targetId)?.text,completion.result.text);
|
||||
assert.deepEqual(cards.find(n=>n.id==='source'),imageDocument.cards[0],'Generation preserves the reference node');
|
||||
assert.deepEqual(state.document.links,imageDocument.links,'Image results preserve the reference graph');
|
||||
if(index===0)assert.deepEqual(cards.find(n=>n.id==='upscaled'),imageDocument.cards[2],'Generation only updates its target');
|
||||
else assert.equal(cards.find(n=>n.id==='generated')?.text,'雪夜图片结果','Upscaling preserves the previous generated image');
|
||||
}
|
||||
assert.equal((await call(imageRoot+'/link','DELETE',{},identities[0])).status,200);
|
||||
assert.equal((await call(imageRoot,'GET',undefined,imageAgent)).status,404);
|
||||
assert.equal((await call(root+'/link','POST',{},agent)).status,403,'A delegated agent cannot mint links');
|
||||
assert.equal((await call(root+'/link','DELETE',{},identities[0])).status,200);
|
||||
assert.equal((await call(root,'GET',undefined,agent)).status,404,'Revocation takes effect on the next request');
|
||||
const rotated=await (await call(root+'/link','POST',{},identities[0])).json();
|
||||
const expired={authorization:'Bearer '+rotated.token};
|
||||
await db().query("UPDATE canvas_agent_links SET expires_at=now()-interval '1 second' WHERE canvas_id=$1",[canvas.id]);
|
||||
assert.equal((await call(root,'GET',undefined,expired)).status,404,'Expired capabilities are rejected');
|
||||
const rotations=await Promise.all([call(root+'/link','POST',{},identities[0]),call(root+'/link','POST',{},identities[0])]);
|
||||
assert.ok(rotations.every(r=>r.status===201));
|
||||
assert.equal((await db().query('SELECT count(*)::int AS count FROM canvas_agent_links WHERE canvas_id=$1',[canvas.id])).rows[0].count,1,'Concurrent rotation leaves one active capability');
|
||||
const docs=await call(root+'?agent_mode=True');assert.equal(docs.status,200);assert.match(await docs.text(),/Authorization/);
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { visitBrowserDocument } from "./brand-navigation.mjs";
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {chromium,type Request} from 'playwright-core';
|
||||
import {db} from '../src/lib/db';
|
||||
import {hashPassword,ACCOUNT_COOKIE} from '../src/lib/account-crypto';
|
||||
|
||||
export async function verifyCanvasAgentUI(base:string){
|
||||
assert.equal(process.env.PROMPT_INTEGRATION_TEST,'1');
|
||||
const owner=randomUUID(),email=owner+'@example.com',password='Canvas integration example1!';
|
||||
await db().query("INSERT INTO account_users(id,email,password_hash,verified_at) VALUES($1,$2,$3,now())",[owner,email,await hashPassword(password)]);
|
||||
const browser=await chromium.launch({executablePath:process.env.CHROMIUM_PATH||'/usr/bin/chromium',headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
const context=await browser.newContext({viewport:{width:1440,height:1000}}),errors:string[]=[];
|
||||
const page=await context.newPage(),canvasRequests:string[]=[],pending=new Set<Request>(),network:string[]=[];
|
||||
const started=Date.now(),navigation:{ms:number;event:string;path:string}[]=[];
|
||||
const mark=(event:string)=>{navigation.push({ms:Date.now()-started,event,path:new URL(page.url()).pathname});if(navigation.length>60)navigation.shift()};
|
||||
page.on('framenavigated',frame=>{if(frame===page.mainFrame())mark('framenavigated')});
|
||||
page.on('domcontentloaded',()=>mark('domcontentloaded'));page.on('load',()=>mark('load'));
|
||||
const requestName=(request:{method:()=>string;url:()=>string})=>request.method()+' '+new URL(request.url()).pathname;
|
||||
page.on('request',request=>pending.add(request));
|
||||
page.on('requestfinished',request=>pending.delete(request));
|
||||
page.on('requestfailed',request=>{pending.delete(request);network.push(requestName(request)+': '+request.failure()?.errorText)});
|
||||
page.on('response',response=>{const url=new URL(response.url());if(url.pathname.startsWith('/api/canvases'))canvasRequests.push(`${response.request().method()} ${url.pathname} ${response.status()}`)});
|
||||
try{
|
||||
page.setDefaultTimeout(60000);page.setDefaultNavigationTimeout(60000);page.on('pageerror',e=>errors.push(e.message));
|
||||
mark('open landing');await visitBrowserDocument(page,base+'/');
|
||||
await page.getByRole('heading',{name:/想法不该停在对话里/,level:1}).waitFor();
|
||||
const accountSession=page.waitForResponse(response=>new URL(response.url()).pathname==='/api/account/session'&&response.request().method()==='GET');
|
||||
const [,sessionResponse]=await Promise.all([page.getByRole('link',{name:'开始创作',exact:true}).click(),accountSession]);
|
||||
assert.equal(sessionResponse.status(),200);assert.equal((await sessionResponse.json()).user,null);
|
||||
await page.getByRole('heading',{name:'欢迎回来',exact:true,level:2}).waitFor();
|
||||
await page.locator('button[data-theme-ready="true"]').first().waitFor();
|
||||
mark('login form ready');
|
||||
await page.getByLabel('邮箱地址',{exact:true}).fill(email);
|
||||
await page.getByLabel('密码',{exact:true}).fill(password);
|
||||
mark('before login click');await page.locator('form').getByRole('button',{name:'登录',exact:true}).click();
|
||||
mark('after login click');
|
||||
await page.waitForURL(url=>url.pathname==='/workspace',{waitUntil:'commit'});
|
||||
mark('workspace URL accepted');
|
||||
await page.getByRole('heading',{name:'今天,让哪个想法成形?',exact:true}).waitFor();
|
||||
await page.locator('button[data-theme-ready="true"]').first().waitFor();
|
||||
mark('workspace rendered');
|
||||
const session=(await context.cookies()).find(c=>c.name===ACCOUNT_COOKIE);assert.ok(session?.httpOnly,'The actual login response establishes an HTTP-only account session');
|
||||
const ownerHeaders={cookie:ACCOUNT_COOKIE+'='+session.value};
|
||||
const canvasLink=page.getByRole('link',{name:'无限画布',exact:true});
|
||||
assert.equal(await canvasLink.getAttribute('href'),'/infinite_canvas');
|
||||
await visitBrowserDocument(page,base+'/infinite_canvas');
|
||||
await page.getByRole('link',{name:email,exact:true}).waitFor({state:'attached'});
|
||||
await page.getByRole('button',{name:'从示例开始 ↗',exact:true}).click();
|
||||
const shot=page.locator('[data-node-id="shot"] [data-node-content]');
|
||||
await shot.click();await shot.click();
|
||||
const composer=page.getByRole('region',{name:'节点编辑器',exact:true});
|
||||
await composer.getByRole('textbox',{name:'创作要求',exact:true}).fill('根据参考资料写六个分镜');
|
||||
await composer.getByRole('button',{name:'交给 Agent',exact:true}).click();
|
||||
const panel=page.getByRole('region',{name:'Agent 连接',exact:true});
|
||||
await panel.getByText('任务已创建,等待你的 coding agent 领取',{exact:true}).waitFor();
|
||||
const list=await fetch(base+'/api/canvases',{headers:ownerHeaders}).then(r=>r.json());assert.equal(list.canvases.length,1);
|
||||
const root='/api/canvases/'+list.canvases[0].id;
|
||||
const state=await fetch(base+root,{headers:ownerHeaders}).then(r=>r.json());assert.equal(state.tasks.length,1);assert.equal(state.tasks[0].status,'queued');
|
||||
await panel.getByRole('button',{name:'生成连接凭据',exact:true}).click();
|
||||
const credentials=panel.getByRole('textbox',{name:'Agent 连接凭据',exact:true});await credentials.waitFor();
|
||||
await panel.getByRole('button',{name:'复制给 coding agent',exact:true}).click();
|
||||
await panel.getByRole('status').filter({hasText:/凭据已复制|已选中凭据/}).waitFor();
|
||||
const first=JSON.parse(await credentials.inputValue());assert.equal(first.canvasUrl,base+root);
|
||||
const agentHeaders={'Content-Type':'application/json',authorization:first.authorization};
|
||||
const task=root+'/tasks/'+state.tasks[0].id;
|
||||
const recipe=await fetch(base+task,{headers:agentHeaders}).then(r=>r.json());assert.equal(recipe.request.instruction,'根据参考资料写六个分镜');assert.equal(recipe.request.references[0].id,'reference');
|
||||
const patch=async(body:unknown)=>fetch(base+task,{method:'PATCH',headers:agentHeaders,body:JSON.stringify(body)});
|
||||
assert.equal((await patch({status:'running'})).status,200);
|
||||
await panel.getByText(/Agent 正在处理/).waitFor();
|
||||
// This fixture verifies the external-client protocol and UI delivery, not model quality.
|
||||
let generated='第一镜:晨光穿过窗边的植物。';
|
||||
assert.equal((await patch({status:'succeeded',result:{text:generated}})).status,200);
|
||||
await page.locator('[data-node-id="shot"] [data-node-content]').getByText(generated,{exact:true}).waitFor();
|
||||
const updated=await fetch(base+root,{headers:ownerHeaders}).then(r=>r.json());
|
||||
assert.equal(updated.document.cards.find((n:{id:string})=>n.id==='shot').instruction,'根据参考资料写六个分镜');
|
||||
await panel.getByRole('button',{name:'关闭 Agent 连接',exact:true}).click();
|
||||
await shot.click();await shot.click();
|
||||
await composer.getByRole('textbox',{name:'创作要求',exact:true}).fill('再写一个新镜头');
|
||||
const queued=page.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname===root+'/tasks');
|
||||
await composer.getByRole('button',{name:'交给 Agent',exact:true}).click();
|
||||
const queuedResponse=await queued;assert.equal(queuedResponse.status(),201);const secondTask=await queuedResponse.json();
|
||||
await panel.getByRole('button',{name:'关闭 Agent 连接',exact:true}).click();
|
||||
const brief=page.locator('[data-node-id="brief"] [data-node-content]');await brief.click();await brief.click();
|
||||
const localText=page.getByRole('textbox',{name:'01 / 创意简报 内容',exact:true});await localText.fill('用户尚未同步的本机修改');
|
||||
const nextTask=root+'/tasks/'+secondTask.id;
|
||||
const nextPatch=(body:unknown)=>fetch(base+nextTask,{method:'PATCH',headers:agentHeaders,body:JSON.stringify(body)});
|
||||
assert.equal((await nextPatch({status:'running'})).status,200);
|
||||
generated='第二镜:城市在雨后醒来。';
|
||||
assert.equal((await nextPatch({status:'succeeded',result:{text:generated}})).status,200);
|
||||
await page.getByRole('button',{name:'Agent · 在线画布',exact:true}).click();
|
||||
await panel.getByRole('button',{name:'载入在线版本',exact:true}).waitFor();
|
||||
assert.equal(await localText.inputValue(),'用户尚未同步的本机修改','Polling must not replace unsaved local work');
|
||||
await panel.getByRole('button',{name:'载入在线版本',exact:true}).click();
|
||||
await page.locator('[data-node-id="shot"] [data-node-content]').getByText(generated,{exact:true}).waitFor();
|
||||
assert.equal(await page.locator('[data-node-id="brief"] [data-node-content]').textContent(),state.document.cards.find((n:{id:string})=>n.id==='brief').text);
|
||||
await panel.getByRole('button',{name:'生成连接凭据',exact:true}).click();
|
||||
await page.waitForFunction(old=>{const field=document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Agent 连接凭据"]');return !!field&&JSON.parse(field.value).authorization!==old},first.authorization);
|
||||
const second=JSON.parse(await credentials.inputValue());assert.equal((await fetch(base+root,{headers:agentHeaders})).status,404);
|
||||
await panel.getByRole('button',{name:'撤销连接',exact:true}).click();
|
||||
await panel.getByText('Agent 访问已撤销',{exact:true}).waitFor();
|
||||
assert.equal((await fetch(base+root,{headers:{authorization:second.authorization}})).status,404);
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
const bounds=await panel.boundingBox();assert.ok(bounds&&bounds.x>=0&&bounds.x+bounds.width<=390,'Agent panel stays within the mobile viewport');
|
||||
await visitBrowserDocument(page,page.url(),true);
|
||||
await page.getByRole('link',{name:email,exact:true,includeHidden:true}).waitFor({state:'attached'});
|
||||
await page.getByRole('button',{name:'Agent',exact:true}).click();
|
||||
const reopened=page.getByRole('region',{name:'Agent 连接',exact:true});
|
||||
await reopened.getByRole('combobox',{name:'打开在线画布',exact:true}).selectOption(list.canvases[0].id);
|
||||
await reopened.getByRole('button',{name:'载入在线版本',exact:true}).click();
|
||||
await page.locator('[data-node-id="shot"] [data-node-content]').getByText(generated,{exact:true}).waitFor();
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('Canvas navigation timeline',JSON.stringify(navigation));
|
||||
console.log('Canvas UI dispatched a real stored task, received an external-client fixture result, rotated/revoked access and restored its online document');
|
||||
}catch(error){
|
||||
const statuses=await page.getByRole('status').allTextContents().catch(()=>[]);
|
||||
const headings=await page.getByRole('heading').allTextContents().catch(()=>[]);
|
||||
const documentState=await page.evaluate(()=>({readyState:document.readyState,navigation:performance.getEntriesByType('navigation').map(entry=>{const timing=entry as PerformanceNavigationTiming;return {type:timing.type,domContentLoadedEventEnd:timing.domContentLoadedEventEnd,loadEventEnd:timing.loadEventEnd}})})).catch(()=>null);
|
||||
console.error('Canvas agent UI diagnostics',JSON.stringify({url:page.url(),browserConnected:browser.isConnected(),headings,statuses,documentState,navigation,pending:[...pending].map(requestName),network:network.slice(-20),canvasRequests:canvasRequests.slice(-20),errors}));
|
||||
throw error;
|
||||
}finally{await context.close();await browser.close()}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import {test} from 'node:test';import assert from 'node:assert/strict';import {requiredPackImages} from '../scripts/verify-character-pack.mjs';
|
||||
test('editorial covers do not invalidate preserved original packs',()=>{const originals=[{id:'a',sha256:'hash-a'},{id:'b',sha256:'hash-b'}];assert.deepEqual(requiredPackImages(['hash-a','hash-b'],[{id:'cover',sha256:'cover'},...originals]),originals)});
|
||||
test('extra images cannot disguise missing or replaced originals',()=>{assert.throws(()=>requiredPackImages(['a','b'],[{sha256:'a'},{sha256:'x'},{sha256:'y'}]));assert.throws(()=>requiredPackImages(['a','a'],[{sha256:'a'}]));assert.equal(requiredPackImages(['a','a'],[{sha256:'a'},{sha256:'a'}]).length,2)});
|
||||
@@ -1,31 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {backlinksFor,documentLinks,rankDocuments,discoveryPage,InvalidDiscoveryCursor,type SearchDocument} from '../src/lib/discovery';
|
||||
const doc=(id:string,patch:Partial<SearchDocument>={}):SearchDocument=>({id,title:'普通笔记 '+id,description:'',markdown:'',categories:[],namespace:'Main',createdAt:'2026-01-01',...patch});
|
||||
test('backlinks count distinct documents, resolve UUID aliases and ignore self/external/image/code links',()=>{
|
||||
const a=doc('a',{aliases:['aaaa-1111'],markdown:'[self](/explore/a)'}),b=doc('b',{markdown:'[inline](/explore/a) [again](http://8.211.154.134:18131/explore/aaaa-1111?agent_mode=True#x)\n\n[reference][target]\n\n[target]: /api/notes/a\n\n\n\n`[code](/explore/c)`\n\n```md\n[fenced](/explore/c)\n```\n[external](https://example.com/explore/c)'}),c=doc('c',{markdown:'[a](/explore/a)'});
|
||||
const refs=backlinksFor([a,b,c]);assert.deepEqual(refs.get('a')?.map(r=>r.id),['b','c']);assert.equal(refs.get('c')?.length,0);assert.equal(documentLinks(b.markdown).length,4);
|
||||
});
|
||||
test('search includes body, tags and descriptions; matches all terms, casefolds and ranks title above body',()=>{
|
||||
const documents=[doc('a',{markdown:'正文专属关键词 React 实践',categories:['课程']}),doc('b',{title:'REACT 实践',description:'正文专属关键词'}),doc('c',{description:'React 介绍'})];
|
||||
assert.deepEqual(rankDocuments(documents,'react 实践').map(r=>r.doc.id),['b','a']);
|
||||
assert.deepEqual(rankDocuments(documents,'课程 正文专属关键词').map(r=>r.doc.id),['a']);
|
||||
assert.deepEqual(rankDocuments(documents,'"react 实践"').map(r=>r.doc.id),['b','a']);assert.equal(rankDocuments(documents,'不存在').length,0);
|
||||
});
|
||||
test('default order favors inbound links and filters the entire corpus before paginating',()=>{
|
||||
const documents=Array.from({length:52},(_,i)=>doc(i.toString(16).padStart(3,'0'),{categories:i%2?['wanted']:[],markdown:i?'[target](/explore/000)':''}));
|
||||
const ranked=rankDocuments(documents);assert.equal(ranked[0].doc.id,'000');assert.equal(ranked[0].backlinkCount,51);
|
||||
const filtered=rankDocuments(documents,'','wanted'),first=discoveryPage(filtered,'','wanted'),second=discoveryPage(filtered,'','wanted',first.nextCursor!);
|
||||
assert.equal(first.total,26);assert.equal(first.rows.length,24);assert.equal(second.rows.length,2);assert.equal(second.nextCursor,null);assert.equal(new Set([...first.rows,...second.rows].map(r=>r.doc.id)).size,26);
|
||||
assert.throws(()=>discoveryPage(filtered,'different','wanted',first.nextCursor!),InvalidDiscoveryCursor);assert.throws(()=>discoveryPage(filtered,'','wanted','bad'),InvalidDiscoveryCursor);
|
||||
});
|
||||
|
||||
test('pasted full URLs count but disguised link labels and inline code do not',()=>{
|
||||
const source=doc('b',{markdown:'http://8.211.154.134:18131/explore/a。\n\n[http://8.211.154.134:18131/explore/c](https://example.com)\n\n`http://8.211.154.134:18131/explore/c`'});
|
||||
const refs=backlinksFor([doc('a'),source,doc('c')]);assert.equal(refs.get('a')?.length,1);assert.equal(refs.get('c')?.length,0);
|
||||
});
|
||||
|
||||
test('system categories filter independently of ordinary tags and are searchable',()=>{
|
||||
const ranked=rankDocuments([doc('a',{categories:['中国风'],systemTags:['文档入口','document-entry']}),doc('b',{categories:['中国风']})],'','document-entry');
|
||||
assert.deepEqual(ranked.map(r=>r.doc.id),['a']);assert.equal(rankDocuments([doc('a',{categories:['中国风'],systemTags:['文档入口']})],'中国风 文档入口').length,1);
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {staticEntries,getEntry,entryText} from '../src/lib/explore';
|
||||
import {pageId,previewUrl} from '../src/content/page-links';
|
||||
import {guidanceDocuments} from '../src/content/skills/guidance';
|
||||
import {getServerSideProps} from '../src/pages/explore/[id]';
|
||||
test('every public document has a distinct persisted ID and canonical entry',async()=>{assert.equal(new Set(staticEntries.map(e=>e.id)).size,staticEntries.length);for(const e of staticEntries){assert.match(e.id,/^[a-f0-9]{24}$/);assert.equal((await getEntry(e.id))?.title,e.title);}for(const doc of guidanceDocuments)assert.ok(pageId('guidance:'+doc.path));assert.equal(await getEntry('unknown'),null);});
|
||||
test('agent_mode on the canonical URL emits text with media links and no HTML',async()=>{const entry=staticEntries.find(e=>e.media.length)!;let body='';const headers:Record<string,string>={};const response={setHeader:(k:string,v:string)=>headers[k]=v,end:(value:string)=>{body=value}};await getServerSideProps({params:{id:entry.id},query:{agent_mode:'True'},res:response,req:{method:'GET'}} as never);assert.match(headers['Content-Type'],/text\/plain/);assert.ok(body.includes(entry.title));assert.ok(body.includes(entry.media[0].url));assert.ok(body.startsWith('# '+entry.title));assert.ok(!body.includes('!['));assert.equal(body,entryText((await getEntry(entry.id))!));});
|
||||
test('preview URLs always use bounded image endpoints',()=>{const url=new URL(previewUrl('/api/media/id?variant=poster',480),'http://test');assert.equal(url.pathname,'/api/preview');assert.equal(url.searchParams.get('source'),'/api/media/id?variant=poster');assert.equal(url.searchParams.get('width'),'480');});
|
||||
|
||||
test('independent notes expose their own description, tags and complete image counts',async()=>{
|
||||
for(const entry of staticEntries){assert.ok(entry.description.trim());assert.equal(entry.imageCount,entry.media.filter(m=>m.kind==='image').length);assert.equal(new Set(entry.media.map(m=>m.url)).size,entry.media.length);}
|
||||
const note=(await getEntry(pageId('guidance:shadow-puppet')))!;
|
||||
assert.equal(note.imageCount,2);assert.ok(note.categories.includes('照片入皮影'));assert.ok(entryText(note).includes('Description: '+note.description));
|
||||
const workflow=(await getEntry(pageId('guidance:shadow-puppet/workflow')))!;
|
||||
assert.notEqual(workflow.description,note.description);assert.notEqual(workflow.id,note.id);
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {db} from '../src/lib/db';
|
||||
export async function verifyFlatNoteMigration(){
|
||||
const client=await db().connect();const schema='migration_'+randomUUID().replaceAll('-','');
|
||||
try{
|
||||
await client.query(`CREATE SCHEMA ${schema}`);await client.query(`SET search_path TO ${schema}`);
|
||||
for(const name of ['001_library','002_page_snapshots','003_note_descriptions'])await client.query(await readFile(`db/${name}.sql`,'utf8'));
|
||||
const [video,picture,post,tag,duplicate,parent]=Array.from({length:6},()=>randomUUID());
|
||||
await client.query(`INSERT INTO assets(id,kind,storage_key,mime_type,byte_size) VALUES($1,'video','original','video/mp4',100),($2,'image','snapshot','image/png',50)`,[video,picture]);
|
||||
await client.query(`INSERT INTO posts(id,slug,kind,title,page_key) VALUES($1,'old-note','article','保留的笔记','old-code')`,[post]);
|
||||
await client.query(`INSERT INTO post_assets(post_id,asset_id,position) VALUES($1,$2,0)`,[post,video]);
|
||||
await client.query(`INSERT INTO page_snapshots(post_id,page_index,asset_id,revision) VALUES($1,1,$2,'old-revision')`,[post,picture]);
|
||||
await client.query(`INSERT INTO render_jobs(post_id,status,revision) VALUES($1,'pending','old-revision')`,[post]);
|
||||
await client.query(`INSERT INTO asset_variants(asset_id,role,storage_key,mime_type,byte_size) VALUES($1,'poster','old-poster','image/jpeg',20)`,[video]);
|
||||
await client.query(`INSERT INTO media_jobs(id,asset_id) VALUES($1,$2)`,[randomUUID(),video]);
|
||||
await client.query(`INSERT INTO tags(id,slug,name) VALUES($1,'parent','上级'),($2,'same','重复')`,[parent,tag]);
|
||||
await client.query(`INSERT INTO tags(id,parent_id,slug,name) VALUES($1,$2,'same','重复')`,[duplicate,parent]);
|
||||
await client.query(`INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2),($1,$3)`,[post,tag,duplicate]);
|
||||
await client.query(`INSERT INTO asset_tags(asset_id,tag_id) VALUES($1,$2)`,[video,duplicate]);
|
||||
await client.query(await readFile('db/004_flat_notes.sql','utf8'));
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM post_assets WHERE post_id=$1 AND asset_id=$2',[post,picture])).rows[0].n,1,'Previously generated image remains linked');
|
||||
const processed=(await client.query(`SELECT a.storage_key,pa.role FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.derivation='poster'`,[post])).rows;
|
||||
assert.deepEqual(processed,[{storage_key:'old-poster',role:'poster'}],'Processed file uses its existing object and a normal resource link');
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM post_tags WHERE post_id=$1',[post])).rows[0].n,1);
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM asset_tags WHERE asset_id=$1',[video])).rows[0].n,1,'Merging equal tags retains asset associations');
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM media_jobs')).rows[0].n,1,'Video processing queue survives');
|
||||
assert.equal((await client.query(`SELECT count(*)::integer n FROM information_schema.columns WHERE table_schema=$1 AND column_name IN ('parent_id','page_key')`,[schema])).rows[0].n,0);
|
||||
await client.query(await readFile('db/008_system_tags.sql','utf8'));
|
||||
assert.equal((await client.query("SELECT count(*)::integer n FROM tags WHERE kind='system'")).rows[0].n,2);
|
||||
assert.ok((await client.query("SELECT 1 FROM tags WHERE kind='normal'")).rowCount);
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM post_tags WHERE post_id=$1',[post])).rows[0].n,1,'System tag migration retains ordinary associations');
|
||||
await assert.rejects(client.query("INSERT INTO tags(id,slug,name,kind) VALUES($1,'invalid-system','Invalid system','system')",[randomUUID()]));
|
||||
}finally{
|
||||
await client.query('ROLLBACK');await client.query('SET search_path TO public');await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);client.release();
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import { visitBrowserDocument } from "./brand-navigation.mjs";
|
||||
import assert from 'node:assert/strict';
|
||||
import {verifyGuidanceWorkspaceUI} from './guidance-workspace-ui';
|
||||
import {chromium} from 'playwright-core';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {newToken,tokenDigest,ACCOUNT_COOKIE} from '../src/lib/account-crypto';
|
||||
import {guidanceXml,type Guidance} from '../src/content/guides/catalog';
|
||||
import {db} from '../src/lib/db';
|
||||
import {publishDocument,resolveDocument,withdrawDocument,discoverDocuments} from '../src/lib/guidance-store';
|
||||
export async function verifyGuidancePublishing(base:string){
|
||||
const owner=randomUUID(),other=randomUUID(),id='user-'+owner+'-document';
|
||||
for(const uid of [owner,other])await db().query("INSERT INTO account_users(id,email,password_hash,verified_at) VALUES($1,$2,'test',now())",[uid,uid+'@example.com']);
|
||||
const doc:Guidance={id,revision:1,kind:'context',title:'实际数据库文档',summary:'摘要',applies:'条件',body:'正文',steps:[],checks:[],links:[],tags:[]};
|
||||
await assert.rejects(()=>publishDocument(other,doc),/INVALID_ID/);
|
||||
await publishDocument(other,{...doc,id:'user-'+other+'-document'});
|
||||
await publishDocument(owner,doc);assert.equal((await resolveDocument(id,1))?.title,doc.title);
|
||||
await assert.rejects(()=>publishDocument(other,{...doc,revision:2}),/INVALID_ID/);
|
||||
const concurrent=await Promise.allSettled([publishDocument(owner,{...doc,revision:2,body:'新正文'}),publishDocument(owner,{...doc,revision:2})]);assert.equal(concurrent.filter(r=>r.status==='fulfilled').length,1);
|
||||
assert.equal((await resolveDocument(id,1))?.body,'正文');assert.equal(await resolveDocument(id,999),null);
|
||||
await assert.rejects(()=>db().query('UPDATE guidance_revisions SET content=$2 WHERE document_id=$1',[id,{}]),/immutable/);
|
||||
assert.equal(await withdrawDocument(other,id),false);assert.equal(await withdrawDocument(owner,id),true);assert.equal(await resolveDocument(id),null);assert.ok(await resolveDocument(id,1));assert.ok(!(await discoverDocuments()).some(d=>d.id===id));
|
||||
const token=newToken();await db().query("INSERT INTO account_tokens(digest,user_id,kind,expires_at) VALUES($1,$2,'session',now()+interval '1 hour')",[tokenDigest(token),owner]);
|
||||
const headers={'Content-Type':'application/json',origin:process.env.ACCOUNT_PUBLIC_ORIGIN||base,cookie:ACCOUNT_COOKIE+'='+token};
|
||||
const httpDoc={...doc,id:'user-'+owner+'-http',tags:['往返标签']};
|
||||
const request=(path:string,method:string,body?:unknown,extra:Record<string,string>={})=>fetch(base+'/api/documents'+path,{method,headers:{...headers,...extra},...(body?{body:typeof body==='string'?body:JSON.stringify(body)}:{})});
|
||||
assert.equal((await request('','POST',httpDoc,{cookie:''})).status,401);
|
||||
assert.equal((await request('','POST',httpDoc,{origin:'https://untrusted.example'})).status,403);
|
||||
const preview=await request('/preview','POST',httpDoc);assert.equal(preview.status,200,await preview.clone().text());assert.equal(await resolveDocument(httpDoc.id,1),null);
|
||||
const created=await request('','POST',guidanceXml(httpDoc),{'Content-Type':'application/xml'});assert.equal(created.status,201,await created.clone().text());
|
||||
assert.equal((await request('','POST',httpDoc)).status,409);
|
||||
assert.equal((await request('','POST',{...httpDoc,id:'user-'+other+'-http'})).status,400);
|
||||
const own=await fetch(base+'/api/documents?author='+owner).then(r=>r.json());assert.ok(own.documents.some((d:{id:string})=>d.id===httpDoc.id));assert.ok(own.documents.every((d:{author:string})=>d.author===owner));assert.equal((await fetch(base+'/api/documents?author=invalid')).status,400);
|
||||
const xml=await fetch(base+'/api/documents/'+httpDoc.id+'?revision=1&format=xml');assert.equal(xml.status,200);assert.match(await xml.text(),/<tag>往返标签<\/tag>/);
|
||||
const page=await fetch(base+'/documents/'+httpDoc.id+'?revision=1');assert.equal(page.status,200);assert.ok((await page.text()).includes('实际数据库文档'));
|
||||
const directory=await fetch(base+'/api/documents');assert.equal(directory.status,200);assert.ok((await directory.json()).documents.some((d:{id:string})=>d.id===httpDoc.id),'Published document must appear in the public API');
|
||||
// The document discovery list hydrates from the real API; the homepage is the product landing page.
|
||||
const browser=await chromium.launch({executablePath:process.env.CHROMIUM_PATH||'/usr/bin/chromium',headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
try{
|
||||
const page=await browser.newPage();page.setDefaultTimeout(60000);page.setDefaultNavigationTimeout(60000);
|
||||
const navigationDiagnostics:string[]=[],inflight=new Set<string>();
|
||||
const record=(value:string)=>{navigationDiagnostics.push(value.slice(0,1800));if(navigationDiagnostics.length>24)navigationDiagnostics.shift();};
|
||||
page.on('pageerror',error=>record('pageerror: '+error.message));
|
||||
page.on('console',message=>{if(message.type()==='error')record('console: '+message.text());});
|
||||
page.on('request',request=>inflight.add(request.url()));
|
||||
page.on('requestfinished',request=>inflight.delete(request.url()));
|
||||
page.on('requestfailed',request=>{inflight.delete(request.url());record('requestfailed: '+new URL(request.url()).pathname+' '+request.failure()?.errorText)});
|
||||
page.on('response',response=>{const path=new URL(response.url()).pathname;if(path.startsWith('/api/')||path.includes('/_next/data/'))void response.text().then(body=>record(`data ${response.status()} ${path}: ${body.slice(0,1400)}`)).catch(()=>{});else if(response.status()>=400||response.request().resourceType()==='script')record(`resource ${response.status()} ${path}`);});
|
||||
try{
|
||||
const link=`a[href="/documents/${httpDoc.id}?revision=1"]`;
|
||||
const navigation=await visitBrowserDocument(page,base+'/documents');record('directory HTTP '+navigation?.status());
|
||||
await page.locator(link).waitFor({state:'visible'});assert.equal(await page.locator(link).getByRole('heading').textContent(),httpDoc.title);
|
||||
// Published matches must not inherit the examples' empty state; submitted filters survive reload.
|
||||
const search=page.getByRole('textbox',{name:'搜索文档'});
|
||||
await search.fill(httpDoc.title);await search.press('Enter');
|
||||
await page.waitForURL(url=>url.searchParams.get('q')===httpDoc.title,{waitUntil:'commit'});
|
||||
await page.getByRole('status').filter({hasText:'找到 2 篇文档'}).waitFor();
|
||||
assert.equal(await page.getByText('没有匹配文档',{exact:false}).count(),0);
|
||||
await visitBrowserDocument(page,page.url(),true);
|
||||
await page.getByRole('status').filter({hasText:'找到 2 篇文档'}).waitFor();
|
||||
// The matching count can also describe the unfiltered list before router hydration.
|
||||
await page.waitForFunction(title=>document.querySelector<HTMLInputElement>('input[aria-label="搜索文档"]')?.value===title,httpDoc.title);
|
||||
assert.equal(await search.inputValue(),httpDoc.title);
|
||||
await page.getByRole('tab',{name:/事实依据/}).click();
|
||||
await page.waitForURL(url=>url.searchParams.get('kind')==='evidence',{waitUntil:'commit'});
|
||||
await page.getByRole('heading',{name:'没有匹配文档',exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'清除所有筛选'}).click();
|
||||
await page.waitForURL(url=>url.search==='',{waitUntil:'commit'});
|
||||
await page.locator(link).waitFor({state:'visible'});
|
||||
await page.waitForFunction(()=>document.querySelector<HTMLInputElement>('input[aria-label="搜索文档"]')?.value==='');
|
||||
assert.equal(await search.inputValue(),'');
|
||||
await page.getByRole('navigation',{name:'主导航',exact:true}).getByRole('link',{name:'社区文档',exact:true}).click();await page.locator(link).waitFor({state:'visible'});
|
||||
await page.locator(link).click();
|
||||
await page.waitForURL(url=>url.pathname==='/documents/'+httpDoc.id&&url.searchParams.get('revision')==='1',{waitUntil:'commit'});
|
||||
await page.getByRole('heading',{name:httpDoc.title,exact:true,level:1}).waitFor();
|
||||
assert.equal(await page.locator('h1').textContent(),httpDoc.title);
|
||||
await visitBrowserDocument(page,base+'/write');await page.getByRole('heading',{name:'发布独立文档',exact:true,level:1}).waitFor();assert.equal(await page.locator('h1').textContent(),'发布独立文档');
|
||||
}catch(error){console.error('Document navigation diagnostics',JSON.stringify({url:page.url(),headings:await page.locator('h1').allTextContents(),body:(await page.locator('body').innerText()).slice(0,2200),inflight:[...inflight].map(url=>new URL(url).pathname),events:navigationDiagnostics}));throw error;}
|
||||
await page.close();
|
||||
await verifyGuidanceWorkspaceUI(base,browser);
|
||||
console.log('Workspace desktop/mobile, filters, reading, account and publishing assertions passed in a fresh browser context');
|
||||
}finally{await browser.close();}
|
||||
assert.equal((await request('/'+httpDoc.id,'DELETE',undefined,{cookie:''})).status,401);
|
||||
assert.equal((await request('/'+httpDoc.id,'DELETE')).status,200);
|
||||
assert.equal((await fetch(base+'/api/documents/'+httpDoc.id)).status,404);
|
||||
assert.equal((await fetch(base+'/api/documents/'+httpDoc.id+'?revision=1')).status,200);
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {parseDocumentXml,documentInput} from '../src/lib/guidance-input';
|
||||
import {guidanceXml} from '../src/content/guides/catalog';
|
||||
const doc={id:'user-test',revision:1,kind:'guide' as const,title:'A & B',summary:'摘要',applies:'适用',body:'<正文>',steps:['一步'],checks:[],links:[],tags:[]};
|
||||
test('XML canonical round trip and strict rejection',()=>{const xml=guidanceXml(doc);assert.deepEqual(parseDocumentXml(xml),doc);for(const bad of [xml.replace('<title>','<title extra="1">'),xml.replace('</body>','</body><title>duplicate</title>'),xml.replace('urn:linked-guidance:0.1','urn:linked-guidance:0.2'),xml.replace('&','&unknown;'),xml.replace('<guidance','<!DOCTYPE guidance><guidance'),xml.replace('revision="1"','revision="1" revision="2"'),xml.replace('<body>','<body><script>')])assert.throws(()=>parseDocumentXml(bad));assert.throws(()=>documentInput.parse({...doc,admin:true}));assert.throws(()=>documentInput.parse({...doc,id:'review-changes'}));});
|
||||
|
||||
test('XML rejects forbidden Unicode, CDATA terminator and non-XML whitespace',()=>{const xml=guidanceXml(doc);for(const bad of [xml.replace('摘要','bad]]>value'),xml.replace('摘要','bad\u0000value'),xml.replace('摘要','bad\ud800value'),xml+'\u00a0',xml.replace(' id=', '\u00a0id=')])assert.throws(()=>parseDocumentXml(bad));assert.throws(()=>documentInput.parse({...doc,body:'\u000b正文'}));assert.equal(parseDocumentXml(xml.replace('摘要','😀摘要')).summary,'😀摘要');});
|
||||
|
||||
test('tags round trip and quoted attribute greater-than remains text',()=>{const value={...doc,tags:['标签'],links:[{target:'source-trust',revision:1,relation:'context' as const,when:'a > b',label:'来源'}]};const xml=guidanceXml(value);assert.deepEqual(parseDocumentXml(xml),value);assert.deepEqual(parseDocumentXml(xml.replace('a > b','a > b')),value);assert.throws(()=>parseDocumentXml(xml.replace('when="a > b"','when="a < b"')));});
|
||||
@@ -1,380 +0,0 @@
|
||||
/** UI fixtures run in a fresh context; real storage and authentication have separate coverage. */
|
||||
import assert from "node:assert/strict";
|
||||
import { visitBrowserDocument } from "./brand-navigation.mjs";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import type { Browser } from "playwright-core";
|
||||
import { documentInput, parseDocumentXml } from "../src/lib/guidance-input";
|
||||
import { guidanceXml, type Guidance } from "../src/content/guides/catalog";
|
||||
const owner = "11111111-1111-4111-8111-111111111111";
|
||||
const authored: Guidance = {
|
||||
id: "user-" + owner + "-review",
|
||||
revision: 1,
|
||||
kind: "guide",
|
||||
title: "准备一次清晰的代码审查",
|
||||
summary: "用明确的问题和证据,完成一次有用的代码审查。",
|
||||
applies: "提交合并请求前",
|
||||
body: "先理解改动目标,再核对实现与验证。",
|
||||
steps: [],
|
||||
checks: [],
|
||||
links: [],
|
||||
tags: [],
|
||||
};
|
||||
export async function verifyGuidanceWorkspaceUI(base: string, browser: Browser) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 1000 },
|
||||
});
|
||||
let signedIn = false,
|
||||
previewError = false,
|
||||
requestedAuthor: string | null = null,
|
||||
published: Guidance | null = null;
|
||||
const errors: string[] = [];
|
||||
let sessionReplies = 0;
|
||||
try {
|
||||
await context.route("**/api/account/session", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
json: {
|
||||
user: signedIn
|
||||
? {
|
||||
id: owner,
|
||||
email: "editor@example.com",
|
||||
verified_at: "2026-10-29T00:00:00Z",
|
||||
}
|
||||
: null,
|
||||
},
|
||||
});
|
||||
sessionReplies += 1;
|
||||
});
|
||||
await context.route(
|
||||
(url) => url.pathname === "/api/documents",
|
||||
async (route) => {
|
||||
if (route.request().method() === "GET") {
|
||||
requestedAuthor = new URL(route.request().url()).searchParams.get(
|
||||
"author",
|
||||
);
|
||||
return route.fulfill({
|
||||
json: { documents: [{ ...authored, author: owner }] },
|
||||
});
|
||||
}
|
||||
published = documentInput.parse(route.request().postDataJSON());
|
||||
return route.fulfill({ status: 201, json: { document: published } });
|
||||
},
|
||||
);
|
||||
await context.route("**/api/documents/preview", (route) => {
|
||||
if (previewError)
|
||||
return route.fulfill({
|
||||
status: 400,
|
||||
json: { error: "输入不符合协议", fields: ["applies"] },
|
||||
});
|
||||
let document: Guidance;
|
||||
try {
|
||||
document =
|
||||
route.request().headers()["content-type"] === "application/xml"
|
||||
? parseDocumentXml(route.request().postData() || "")
|
||||
: documentInput.parse(route.request().postDataJSON());
|
||||
} catch {
|
||||
return route.fulfill({
|
||||
status: 400,
|
||||
json: { error: "输入不符合协议" },
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
json: {
|
||||
document,
|
||||
xml: guidanceXml(document),
|
||||
links: document.links.map((link) => ({ ...link, resolved: true })),
|
||||
},
|
||||
});
|
||||
});
|
||||
await context.route("**/api/documents/" + authored.id, (route) =>
|
||||
route.fulfill({ json: { document: authored } }),
|
||||
);
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(60000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
page.on("crash", () => errors.push("Browser renderer crashed"));
|
||||
const pending = new Set<string>(), network: string[] = [];
|
||||
page.on("request", request => pending.add(request.url()));
|
||||
page.on("requestfinished", request => pending.delete(request.url()));
|
||||
page.on("requestfailed", request => {pending.delete(request.url());network.push(new URL(request.url()).pathname+": "+request.failure()?.errorText);});
|
||||
async function navigate(url: string, reload = false) {
|
||||
const previousSessionReplies = sessionReplies;
|
||||
try {
|
||||
const navigation = await visitBrowserDocument(page, url, reload);
|
||||
assert.ok(navigation?.ok(), "Navigation returns a successful document");
|
||||
if (new URL(url).pathname === "/account") {
|
||||
await page.getByRole("heading", { name: signedIn ? "你的账户" : "欢迎回来", exact: true }).waitFor();
|
||||
} else {
|
||||
await page.getByText(signedIn ? "editor@example.com" : "登录你的账户",{exact:true}).first().waitFor({state:"attached"});
|
||||
}
|
||||
await page.getByText("正在检查账户状态…", {exact: true}).waitFor({state: "hidden"});
|
||||
assert.ok(sessionReplies > previousSessionReplies, "The new document requests its account fixture and renders the resulting account state");
|
||||
} catch (error) {
|
||||
const probeStarted=Date.now();
|
||||
const server=await fetch(url,{signal:AbortSignal.timeout(3000)}).then(async response=>{await response.body?.cancel();return {status:response.status,elapsedMs:Date.now()-probeStarted}}).catch(error=>({error:error instanceof Error?error.name:"unknown",elapsedMs:Date.now()-probeStarted}));
|
||||
console.error("Workspace UI navigation diagnostics",JSON.stringify({url:page.url(),browserConnected:browser.isConnected(),server,pending:[...pending].map(value=>new URL(value).pathname),network:network.slice(-20),errors,body:(await page.locator("body").innerText().catch(()=>"unavailable")).slice(0,1600)}));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
await navigate(base + "/documents");
|
||||
await page
|
||||
.getByRole("heading", { name: authored.title, exact: true })
|
||||
.waitFor();
|
||||
assert.equal(await page.title(), "社区文档 · 啡跃");
|
||||
const search = page.getByRole("textbox", { name: "搜索文档" });
|
||||
await search.fill("不存在的文档");
|
||||
await search.press("Enter");
|
||||
await page
|
||||
.getByRole("heading", { name: "没有匹配文档", exact: true })
|
||||
.waitFor();
|
||||
await navigate(page.url(), true);
|
||||
await page.getByRole("heading",{name:"没有匹配文档",exact:true}).waitFor();
|
||||
await page.waitForFunction(() => document.querySelector<HTMLInputElement>('input[aria-label="搜索文档"]')?.value === "不存在的文档");
|
||||
assert.equal(await search.inputValue(), "不存在的文档");
|
||||
await page
|
||||
.getByRole("button", { name: "清除所有筛选", exact: true })
|
||||
.click();
|
||||
await page
|
||||
.getByRole("heading", { name: authored.title, exact: true })
|
||||
.waitFor();
|
||||
await page.getByRole("tab", { name: /事实依据/ }).focus();
|
||||
await page.keyboard.press("Home");
|
||||
await page.getByRole("tab", { name: /全部文档/ }).waitFor();
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR) {
|
||||
await mkdir(process.env.WORKSPACE_SCREENSHOT_DIR, { recursive: true });
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/directory.png",
|
||||
fullPage: true,
|
||||
});
|
||||
}
|
||||
await navigate(base + "/guide/review-changes?revision=1");
|
||||
await page.getByRole("tab", { name: "XML 源文档" }).click();
|
||||
assert.match(await page.locator("pre").innerText(), /linked-guidance/);
|
||||
await page.getByRole("tab", { name: /版本记录/ }).click();
|
||||
await page.getByText("当前阅读", { exact: true }).waitFor();
|
||||
await page.getByRole("tab", { name: "文档概览" }).click();
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR)
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/reader.png",
|
||||
fullPage: true,
|
||||
});
|
||||
await navigate(base + "/account");
|
||||
assert.equal(await page.getByRole("complementary").count(), 0, "Account page has no workspace sidebar");
|
||||
assert.equal(await page.getByRole("link", { name: "创建文档", exact: true }).count(), 0);
|
||||
await page.getByRole("link", { name: "返回首页", exact: true }).waitFor();
|
||||
const accountFits = async () => assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1 && document.documentElement.scrollHeight <= innerHeight + 1), "Account page fits the viewport on both axes");
|
||||
await accountFits();
|
||||
await context.route("**/api/account/login", route => route.fulfill({status: 401, json: {error: "测试登录失败,请重试"}}));
|
||||
await page.getByLabel("邮箱地址", {exact: true}).fill("fixture@example.com");
|
||||
await page.getByLabel("密码", {exact: true}).fill("fixture-password-long");
|
||||
await page.waitForFunction(() => document.getAnimations().every(animation => animation.playState !== "running"));
|
||||
const beforeMessage = await page.getByLabel("邮箱地址", {exact: true}).boundingBox();
|
||||
await page.locator("form").getByRole("button", {name: "登录", exact: true}).click();
|
||||
await page.getByRole("alert").getByText("测试登录失败,请重试").waitFor();
|
||||
const afterMessage = await page.getByLabel("邮箱地址", {exact: true}).boundingBox();
|
||||
assert.equal(afterMessage?.y, beforeMessage?.y, "Status messages must not move the form");
|
||||
await accountFits();
|
||||
await page.getByRole("button", {name: "关闭提示", exact: true}).click();
|
||||
await context.route("**/api/account/forgot", route => route.fulfill({json: {ok: true, message: "若账户符合条件,重设链接将发送到邮箱。"}}));
|
||||
await page.getByRole("button", {name: "忘记密码?", exact: true}).click();
|
||||
await page.getByRole("heading", {name: "找回你的账户", exact: true}).waitFor();
|
||||
await page.getByLabel("邮箱地址", {exact: true}).fill("fixture@example.com");
|
||||
await page.getByRole("button", {name: "发送重设链接", exact: true}).click();
|
||||
await page.getByRole("status").getByText("若账户符合条件,重设链接将发送到邮箱。").waitFor();
|
||||
await page.getByRole("button", {name: "返回登录", exact: true}).click();
|
||||
await page.getByRole("button", { name: "创建账户", exact: true }).click();
|
||||
await page.getByRole("heading", { name: "创建你的账户" }).waitFor();
|
||||
await page
|
||||
.getByLabel("密码", { exact: true })
|
||||
.fill("a-long-example-password");
|
||||
await page.getByRole("button", { name: "显示密码" }).click();
|
||||
assert.equal(
|
||||
await page.getByLabel("密码", { exact: true }).getAttribute("type"),
|
||||
"text",
|
||||
);
|
||||
await page.getByRole("button", { name: "隐藏密码" }).click();
|
||||
await page.getByLabel("密码", { exact: true }).fill("");
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR)
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/account.png",
|
||||
fullPage: true,
|
||||
});
|
||||
for (const viewport of [{width: 390, height: 844}, {width: 320, height: 568}]) {
|
||||
await page.setViewportSize(viewport);
|
||||
await accountFits();
|
||||
await page.getByLabel("邮箱地址", {exact: true}).waitFor({state: "visible"});
|
||||
}
|
||||
await page.setViewportSize({width: 1440, height: 1000});
|
||||
await context.route("**/api/account/reset", async route => {
|
||||
const body = route.request().postDataJSON();
|
||||
assert.equal(body.token, "f".repeat(64));
|
||||
assert.equal(body.password, "replacement-fixture-password");
|
||||
await route.fulfill({json: {ok: true}});
|
||||
});
|
||||
await visitBrowserDocument(page, base + "/account?reset=" + "f".repeat(64));
|
||||
await page.getByRole("heading", {name: "设置新密码", exact: true}).waitFor();
|
||||
assert.equal(new URL(page.url()).searchParams.has("reset"), false, "Recovery token is removed from the visible URL");
|
||||
await page.getByLabel("新密码", {exact: true}).fill("replacement-fixture-password");
|
||||
await page.getByLabel("确认新密码", {exact: true}).fill("replacement-fixture-password");
|
||||
await page.getByRole("button", {name: "保存新密码", exact: true}).click();
|
||||
await page.getByRole("heading", {name: "欢迎回来", exact: true}).waitFor();
|
||||
await accountFits();
|
||||
await navigate(base + "/write");
|
||||
await page.getByRole("heading", { name: "登录后开始编写" }).waitFor();
|
||||
signedIn = true;
|
||||
await navigate(page.url(), true);
|
||||
await page.getByLabel("文档短名", { exact: true }).fill("workspace-test");
|
||||
await page.getByLabel("标题", { exact: false }).fill("界面回归验证文档");
|
||||
await page
|
||||
.getByLabel("一句话摘要", { exact: false })
|
||||
.fill("可独立使用的指导");
|
||||
await page
|
||||
.getByLabel("适用条件", { exact: false })
|
||||
.fill("检查界面流程时");
|
||||
await page
|
||||
.getByLabel("正文", { exact: false })
|
||||
.fill("先判断适用条件,再阅读正文。");
|
||||
await page
|
||||
.getByLabel("建议步骤", { exact: true })
|
||||
.fill("第一步\n\n第二步");
|
||||
previewError = true;
|
||||
await page
|
||||
.getByRole("button", { name: "校验并预览", exact: true })
|
||||
.click();
|
||||
await page.getByRole("alert").filter({ hasText: "适用条件" }).waitFor();
|
||||
previewError = false;
|
||||
await page
|
||||
.getByRole("button", { name: "校验并预览", exact: true })
|
||||
.click();
|
||||
await page.getByRole("dialog").waitFor({ state: "visible" });
|
||||
await page.getByRole("button", { name: "返回编辑" }).click();
|
||||
assert.equal(
|
||||
await page.getByLabel("正文", { exact: false }).inputValue(),
|
||||
"先判断适用条件,再阅读正文。",
|
||||
);
|
||||
await page.getByRole("button", { name: "添加条件链接" }).click();
|
||||
await page.getByRole("button", { name: "移除关联文档 1" }).click();
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR) {
|
||||
await page.evaluate(() => window.scrollTo(0, 0));
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/editor.png",
|
||||
fullPage: true,
|
||||
});
|
||||
}
|
||||
await page.getByRole("button", { name: "发布文档", exact: true }).click();
|
||||
await page
|
||||
.getByRole("status")
|
||||
.filter({ hasText: "已公开发布" })
|
||||
.waitFor();
|
||||
assert.ok(published);
|
||||
assert.deepEqual((published as Guidance).steps, ["第一步", "第二步"]);
|
||||
assert.equal(
|
||||
(published as Guidance).id,
|
||||
"user-" + owner + "-workspace-test",
|
||||
);
|
||||
await navigate(base + "/documents?scope=mine");
|
||||
await page
|
||||
.getByRole("heading", { name: authored.title, exact: true })
|
||||
.waitFor();
|
||||
assert.equal(requestedAuthor, owner);
|
||||
await navigate(base + "/write?id=" + authored.id);
|
||||
await page.waitForFunction(title=>Array.from(document.querySelectorAll<HTMLInputElement>("input")).some(input=>input.value===title),authored.title);
|
||||
assert.equal(
|
||||
await page.getByLabel("文档短名", { exact: true }).isDisabled(),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
await page.getByLabel("标题", { exact: false }).inputValue(),
|
||||
authored.title,
|
||||
);
|
||||
await page.getByRole("button", { name: "协议 XML", exact: true }).click();
|
||||
const xmlInput = page.getByLabel("XML 输入");
|
||||
assert.match(await xmlInput.inputValue(), /revision="2"/);
|
||||
await xmlInput.fill(
|
||||
(await xmlInput.inputValue()).replace(
|
||||
authored.title,
|
||||
"通过 XML 更新的文档",
|
||||
),
|
||||
);
|
||||
await page
|
||||
.getByRole("button", { name: "可视化编辑", exact: true })
|
||||
.click();
|
||||
assert.equal(
|
||||
await page.getByLabel("标题", { exact: false }).inputValue(),
|
||||
"通过 XML 更新的文档",
|
||||
);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await navigate(base + "/documents");
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth,
|
||||
),
|
||||
true,
|
||||
);
|
||||
await page.getByRole("button", { name: "打开导航" }).click();
|
||||
await page
|
||||
.getByRole("dialog", { name: "工作区导航" })
|
||||
.waitFor({ state: "visible" });
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(
|
||||
await page.getByRole("dialog", { name: "工作区导航" }).isVisible(),
|
||||
false,
|
||||
);
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR)
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/mobile-directory.png",
|
||||
fullPage: true,
|
||||
});
|
||||
await navigate(base + "/guide/review-changes?revision=1");
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth,
|
||||
),
|
||||
true,
|
||||
);
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR)
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/mobile-reader.png",
|
||||
fullPage: true,
|
||||
});
|
||||
await navigate(base + "/account");
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth,
|
||||
),
|
||||
true,
|
||||
);
|
||||
await navigate(base + "/write");
|
||||
await page.getByLabel("文档短名", { exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "协议 XML", exact: true }).click();
|
||||
await page.getByLabel("XML 输入").waitFor();
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth,
|
||||
),
|
||||
true,
|
||||
);
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR)
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/mobile-editor.png",
|
||||
fullPage: true,
|
||||
});
|
||||
await navigate(base + "/protocol");
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth,
|
||||
),
|
||||
true,
|
||||
);
|
||||
if (process.env.WORKSPACE_SCREENSHOT_DIR)
|
||||
await page.screenshot({
|
||||
path: process.env.WORKSPACE_SCREENSHOT_DIR + "/mobile-protocol.png",
|
||||
fullPage: true,
|
||||
});
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import { chromium } from "playwright-core";
|
||||
import { verifyGuidanceWorkspaceUI } from "./guidance-workspace-ui";
|
||||
const base = process.env.WORKSPACE_TEST_URL;
|
||||
test("workspace filters, reading tabs, account states and editor work on desktop and mobile", {skip: !base}, async () => {
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_PATH || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
headless: true,
|
||||
args: ["--no-sandbox", "--disable-dev-shm-usage"],
|
||||
});
|
||||
try { await verifyGuidanceWorkspaceUI(base!, browser); }
|
||||
finally { await browser.close(); }
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {guides,findGuide,guidanceXml} from '../src/content/guides/catalog';
|
||||
test('every conditional link resolves to its exact revision',()=>{for(const g of guides){assert.ok(g.body&&g.applies&&g.summary);for(const l of g.links){assert.ok(findGuide(l.target,l.revision),`${g.id} -> ${l.target}`);assert.ok(l.when);}}});
|
||||
test('missing fixed revisions do not silently resolve latest',()=>{assert.equal(findGuide(guides[0].id,999),undefined);assert.equal(findGuide('missing'),undefined);});
|
||||
test('XML escapes text and attribute markup without introducing entities',()=>{const g={...guides[0],title:'<script> & "quoted"',links:[{...guides[0].links[0],when:'a" b< c&'}]};const xml=guidanceXml(g);assert.ok(xml.includes('<script> & "quoted"'));assert.ok(xml.includes('when="a" b< c&"'));assert.ok(!xml.includes('<script>'));assert.ok(!xml.includes('<!DOCTYPE'));});
|
||||
|
||||
import {linkedGuidanceIndex} from '../src/lib/guidance-discovery';
|
||||
test('agent entry discovers both corpora and fixes adoption scope',()=>{
|
||||
const entry=linkedGuidanceIndex();
|
||||
for(const path of ['/api/documents','/api/guides','/protocol'])assert.ok(entry.includes(path));
|
||||
for(const guide of guides)assert.ok(entry.includes(`/api/guides/${guide.id}?revision=${guide.revision}&format=xml`));
|
||||
assert.ok(entry.includes('(id, revision)'));
|
||||
assert.ok(entry.includes('8 篇、深度 3 层'));
|
||||
assert.ok(!entry.includes('/skills/index.md'));
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { healthResponse } from "../src/lib/health";
|
||||
|
||||
test("health identifies the deployed release", () => {
|
||||
assert.deepEqual(healthResponse("GET", "abc123"), {
|
||||
statusCode: 200,
|
||||
body: { status: "ok", service: "prompt", release: "abc123" },
|
||||
});
|
||||
});
|
||||
|
||||
test("HEAD is supported and mutations are rejected", () => {
|
||||
assert.equal(healthResponse("HEAD").statusCode, 200);
|
||||
assert.equal(healthResponse("POST").statusCode, 405);
|
||||
});
|
||||
@@ -1,311 +0,0 @@
|
||||
import {verifyBrandUI} from './brand-ui-integration';
|
||||
import {verifyCanvasWorkspace} from './canvas-integration';
|
||||
import {verifyCanvasAgentUI} from './canvas-ui-integration';
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {once} from 'node:events';
|
||||
import {createServer} from 'node:net';
|
||||
import {setTimeout} from 'node:timers/promises';
|
||||
import {mkdtemp,readFile,writeFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {putFile} from '../src/lib/storage';
|
||||
import managedMedia from '../src/content/managed-media.json';
|
||||
import sharp from 'sharp';
|
||||
import {db} from '../src/lib/db';
|
||||
import {probe,run} from '../src/lib/probe';
|
||||
import seriesExample from '../fixtures/autumn-journal.json';
|
||||
import {verifyGuidancePublishing} from './guidance-integration';
|
||||
import {verifyEmailAccounts} from './account-integration';
|
||||
import {verifyFlatNoteMigration} from './flat-note-migration';
|
||||
import {staticEntries} from '../src/lib/explore';
|
||||
import {publishLearningSeries} from '../src/lib/publish-learning-series';
|
||||
|
||||
// Browser acceptance gets its own deadline; it must not consume the existing business-flow budget.
|
||||
test('Endoleap icons, persisted themes and artwork isolation in the real browser', {timeout:300000,skip:!process.env.PROMPT_TEST_BASE_URL}, async()=>{
|
||||
assert.equal(process.env.PROMPT_INTEGRATION_TEST,'1');
|
||||
const base=process.env.PROMPT_TEST_BASE_URL;assert.ok(base);
|
||||
await verifyBrandUI(base);
|
||||
});
|
||||
|
||||
test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processing', {timeout:600000}, async()=>{
|
||||
assert.equal(process.env.PROMPT_INTEGRATION_TEST,'1','Run only against an explicitly isolated test database');
|
||||
const socket=createServer();socket.listen(0,'127.0.0.1');await once(socket,'listening');const address=socket.address();assert.ok(address&&typeof address!=='string');const port=address.port;await new Promise<void>(r=>socket.close(()=>r()));
|
||||
const external=process.env.PROMPT_TEST_BASE_URL;
|
||||
const base=external||`http://127.0.0.1:${port}`;
|
||||
const server=external?null:spawn(process.execPath,['.next/standalone/apps/waterfall-wiki/server.js'],{env:{...process.env,PORT:String(port),HOSTNAME:'127.0.0.1'},stdio:'inherit'});
|
||||
const worker=external?null:spawn(process.execPath,['dist/worker.cjs'],{env:process.env,stdio:'inherit'});const dir=await mkdtemp(join(tmpdir(),'prompt-test-'));
|
||||
const request=async(path:string,body?:unknown)=>{const res=await fetch(base+path,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:undefined);assert.ok(res.ok,`${path}: ${res.status} ${res.ok?'':await res.text()}`);return res.json();};
|
||||
try{
|
||||
let ready=false;for(let i=0;i<60;i++){try{if((await fetch(base+'/api/health')).ok){ready=true;break;}}catch{}await setTimeout(250);}assert.ok(ready);
|
||||
for(const route of ['/','/images','/videos','/audio','/articles','/motion','/library/import','/tools/doodle','/tools/skills','/tools/skills/street-people','/tools/skills/shadow-puppet'])assert.equal((await fetch(base+route)).status,200,route);
|
||||
if(!external)await verifyBrandUI(base);
|
||||
await verifyEmailAccounts(base);
|
||||
await verifyCanvasWorkspace(base);
|
||||
if(process.env.VERIFY_CANVAS_UI==='1')await verifyCanvasAgentUI(base);
|
||||
await verifyGuidancePublishing(base);
|
||||
await verifyFlatNoteMigration();
|
||||
const root=await request('/api/tags',{name:'线条',slug:'lines'});const child=await request('/api/tags',{name:'白色',slug:'white'});
|
||||
const sameTag=await request('/api/tags',{name:'#线条'});assert.equal(sameTag.id,root.id,'Hashtag creation reuses the globally unique tag');
|
||||
assert.equal((await db().query("SELECT count(*)::integer AS n FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='tags' AND column_name='parent_id'")).rows[0].n,0);
|
||||
const a=await sharp({create:{width:160,height:220,channels:3,background:'#b8c9af'}}).png().toBuffer();
|
||||
const upload=async(kind:string,files:{data:Uint8Array;name:string;mime:string}[])=>{const form=new FormData();form.set('kind',kind);form.set('title','测试收藏 '+kind);form.set('description','可以复用的独立文字');form.set('tags',JSON.stringify([child.id]));files.forEach(f=>form.append('files',new Blob([new Uint8Array(f.data)],{type:f.mime}),f.name));const res=await fetch(base+'/api/upload',{method:'POST',body:form});assert.equal(res.status,201,await res.clone().text());return res.json();};
|
||||
const first=await upload('image',[{data:a,name:'a.png',mime:'image/png'},{data:a,name:'b.png',mime:'image/png'}]);
|
||||
const reused=await request('/api/posts',{kind:'image',title:'同一张图的另一种用法',description:'同一素材的独立说明',assets:[{id:first.assets[0]}],tags:[root.id]});
|
||||
assert.equal((await db().query('SELECT count(*)::integer AS n FROM post_assets WHERE asset_id=$1',[first.assets[0]])).rows[0].n,2);
|
||||
const filtered=await request('/api/feed?section=images&path=lines');assert.equal(filtered.posts.length,1);assert.equal(filtered.posts.find((p:{id:string})=>p.id===reused.id).description,'同一素材的独立说明');assert.equal((await request('/api/feed?section=images&path=white')).posts.length,1);
|
||||
const empty=randomUUID();await db().query("INSERT INTO posts(id,slug,kind,title) VALUES($1,$2,'image','空对象')",[empty,empty]);assert.equal((await request('/api/feed')).posts.length,2);
|
||||
assert.equal((await request('/api/feed')).contributions.length,0,'Import does not invent contribution rules');
|
||||
await db().query("INSERT INTO contribution_events(id,kind,subject_type,amount) VALUES($1,'test.import','asset',2),($2,'test.edit','post',3)",[randomUUID(),randomUUID()]);assert.equal((await request('/api/feed')).contributions.reduce((n:number,c:{total:number})=>n+c.total,0),5);
|
||||
const img=await fetch(base+'/api/media/'+first.assets[0],{headers:{Range:'bytes=0-9'}});assert.equal(img.status,206);assert.equal((await img.arrayBuffer()).byteLength,10);
|
||||
const lightweight=await fetch(base+'/api/preview?source='+encodeURIComponent('/api/media/'+first.assets[0])+'&width=480');assert.equal(lightweight.status,200);assert.match(lightweight.headers.get('content-type')||'',/image\/webp/);assert.ok((await lightweight.arrayBuffer()).byteLength<=100000);
|
||||
const highQuality=await fetch(base+'/api/preview?source='+encodeURIComponent('/api/media/'+first.assets[0])+'&width=2160&profile=export');assert.equal(highQuality.status,200);assert.match(highQuality.headers.get('content-type')||'',/image\/webp/);const exportMeta=await sharp(Buffer.from(await highQuality.arrayBuffer())).metadata();assert.equal(exportMeta.width,160);assert.equal(exportMeta.height,220);
|
||||
assert.equal((await fetch(base+'/api/preview?source='+encodeURIComponent('/api/media/'+first.assets[0])+'&width=2160')).status,400);
|
||||
const textEntry=await fetch(base+'/explore/'+reused.id+'?agent_mode=True');assert.equal(textEntry.status,200);assert.match(textEntry.headers.get('content-type')||'',/text\/plain/);assert.ok((await textEntry.text()).includes(first.assets[0]));
|
||||
assert.equal((await fetch(base+'/images/lines/missing')).status,404);assert.equal((await fetch(base+'/p/'+reused.slug)).status,200);
|
||||
for(const sound of [true,false]){
|
||||
const path=join(dir,sound?'sound.mp4':'silent.mp4');const args=['-y','-v','error','-f','lavfi','-i','color=c=blue:s=160x120:r=10'];if(sound)args.push('-f','lavfi','-i','sine=frequency=440:sample_rate=44100');args.push('-t','0.5','-c:v','libx264','-pix_fmt','yuv420p');if(sound)args.push('-c:a','aac');args.push(path);await run('ffmpeg',args);
|
||||
const post=await upload('video',[{data:await readFile(path),name:'video.mp4',mime:'video/mp4'}]);let asset;
|
||||
for(let i=0;i<120;i++){asset=(await db().query('SELECT * FROM assets WHERE id=$1',[post.assets[0]])).rows[0];if(asset.processing_status==='ready'||asset.processing_status==='failed')break;await setTimeout(500);}
|
||||
assert.equal(asset.processing_status,'ready',asset.processing_error);assert.equal(asset.has_audio,sound);
|
||||
const variants:string[]=(await db().query('SELECT derivation AS role FROM assets WHERE source_asset_id=$1',[asset.id])).rows.map(r=>r.role);assert.ok(variants.includes('silent_video'));assert.ok(variants.includes('poster'));assert.equal(variants.includes('audio_track'),sound);
|
||||
const linked=(await request('/api/feed?section=videos')).posts.find((p:{id:string})=>p.id===post.id);assert.ok(linked.assets.some((a:{role:string})=>a.role==='poster'));
|
||||
const videoNote=await fetch(base+'/explore/'+post.id+'?agent_mode=True').then(r=>r.text());assert.ok(videoNote.includes('静音视频'));
|
||||
const reusedVideo=await request('/api/posts',{kind:'video',title:'复用已加工的视频',assets:[{id:asset.id}]});assert.ok((await db().query("SELECT 1 FROM post_assets WHERE post_id=$1 AND role='silent_video'",[reusedVideo.id])).rowCount);
|
||||
const clip:Response=await fetch(base+'/api/media/'+asset.id+'?variant=silent_video');assert.equal(clip.status,200);const derived=join(dir,'derived.mp4');await writeFile(derived,Buffer.from(await clip.arrayBuffer()));assert.equal((await probe(derived)).streams.some(s=>s.codec_type==='audio'),false);
|
||||
}
|
||||
assert.equal((await db().query("SELECT count(*)::integer AS n FROM assets WHERE kind='audio' AND derivation='audio_track'")).rows[0].n,1,'Video soundtracks are ordinary reusable assets');
|
||||
const audio=join(dir,'audio.wav');await run('ffmpeg',['-y','-v','error','-f','lavfi','-i','sine=frequency=220','-t','0.2',audio]);await upload('audio',[{data:await readFile(audio),name:'audio.wav',mime:'audio/wav'}]);assert.equal((await request('/api/feed?section=audio')).posts.length,1);
|
||||
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);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:{}});}
|
||||
// Exercise actual HTTP + PostgreSQL transactions, not a mocked persistence layer.
|
||||
const seriesBody=structuredClone(seriesExample);
|
||||
const group=await request('/api/studio/series',seriesBody);assert.equal(group.design.schemaVersion,2);assert.equal(group.design.document.pages.length,3);assert.ok(group.design.postId);
|
||||
const seriesId=group.design.id;
|
||||
const exportPlan=await request('/api/studio/series/'+seriesId+'/export');assert.equal(exportPlan.pages.length,3);assert.equal(exportPlan.pages[0].height,1440);
|
||||
const patchSeries={...seriesBody,revision:1,name:'Updated series'};
|
||||
const edits=await Promise.all([1,2].map(()=>fetch(base+'/api/studio/series/'+seriesId,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify(patchSeries)})));assert.deepEqual(edits.map(r=>r.status).sort(),[200,409]);
|
||||
const badSeries=structuredClone(seriesBody);const absentAsset=randomUUID();Object.assign(badSeries.document.pages[1].parameters.images.I01,{assetId:absentAsset});(badSeries.document.sources as unknown[]).push({assetId:absentAsset,author:'CI',license:'test',url:'generated',prompt:'fixture',tool:'test'});
|
||||
const countBefore=(await db().query('SELECT count(*) FROM studio_designs')).rows[0].count;
|
||||
assert.equal((await fetch(base+'/api/studio/series',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(badSeries)})).status,400);assert.equal((await db().query('SELECT count(*) FROM studio_designs')).rows[0].count,countBefore);
|
||||
assert.equal((await fetch(base+'/api/studio/designs/'+seriesId,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:'wrong API',revision:2,parameters:{}})})).status,409);
|
||||
assert.equal((await fetch(base+'/api/studio/series/'+seriesId,{method:'DELETE',headers:{'Content-Type':'application/json'},body:'{"revision":2}'})).status,200);
|
||||
assert.equal((await fetch(base+'/api/studio/series/'+seriesId+'/export')).status,404);
|
||||
assert.equal((await request('/api/studio/series/'+seriesId,{revision:3,archived:false})).design.revision,4);
|
||||
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'));
|
||||
// Isolated S3 uses synthetic fixtures, never credentials or production objects.
|
||||
const testCoverFile=join(dir,'learning-cover.png');
|
||||
const testCoverBytes=await sharp({create:{width:1080,height:1440,channels:3,background:'#e8eadc'}}).png().toBuffer();
|
||||
await writeFile(testCoverFile,testCoverBytes);
|
||||
const testCover={...managedMedia['apps/waterfall-wiki/public/learning-skills/cover.png'],id:randomUUID(),key:'integration/learning-cover.png',sha256:createHash('sha256').update(testCoverBytes).digest('hex'),bytes:testCoverBytes.length};
|
||||
await putFile(testCover.key,testCoverFile,'image/png');
|
||||
const publishTestSeries=()=>publishLearningSeries(testCover);
|
||||
const published=await publishTestSeries();await publishTestSeries();
|
||||
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);
|
||||
for(const slug of published.published){const response=await fetch(base+'/p/'+slug);assert.equal(response.status,200);assert.ok((await response.text()).includes('内容 ID'))}
|
||||
assert.equal((await request('/api/feed?section=articles&path=learning-skills')).posts.length,3);
|
||||
const coverResponse=await fetch(base+'/api/media/'+published.coverId);assert.equal(coverResponse.headers.get('content-type'),'image/png');
|
||||
const coverInfo=await sharp(Buffer.from(await coverResponse.arrayBuffer())).metadata();assert.equal(coverInfo.width,1080);assert.equal(coverInfo.height,1440);
|
||||
assert.equal((await request('/api/feed')).contributions.reduce((n:number,c:{total:number})=>n+c.total,0),5,'Editorial publication does not invent contribution events');
|
||||
for(const slug of published.published){
|
||||
assert.equal((await fetch(base+`/api/posts/${slug}/snapshots`)).status,404);
|
||||
assert.equal((await fetch(base+`/p/${slug}/pages/1`)).status,404);
|
||||
}
|
||||
const article=await request('/api/posts',{kind:'article',title:'无代码页面的笔记',text:'普通正文与 [引用](https://example.com)'});
|
||||
const articlePage=await fetch(base+'/explore/'+article.id).then(r=>r.text());assert.ok(articlePage.includes('note-inline-link'));
|
||||
const remaining=(await db().query("SELECT to_regclass('asset_variants') AS variants,to_regclass('page_snapshots') AS snapshots,to_regclass('render_jobs') AS renders")).rows[0];assert.deepEqual(remaining,{variants:null,snapshots:null,renders:null});
|
||||
// Both file-backed Wiki pages and media notes can be edited on their stable IDs.
|
||||
const note=staticEntries.find(e=>e.namespace==='Main'&&!e.media.length)!;
|
||||
const editable=await request('/api/notes/'+note.id);
|
||||
const newTag=await request('/api/tags',{name:'#在线编辑'});
|
||||
const updatedBody='## 新内容\n\n- 项目一\n - 子项目\n- [相关笔记](/explore/'+reused.id+')';
|
||||
const edit=async(id:string,payload:unknown)=>fetch(base+'/api/notes/'+id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
const payload={title:'已编辑的 Wiki 笔记',description:'修改后的预览描述',markdown:updatedBody,tags:[newTag.id],revision:editable.entry.revision};
|
||||
const saved=await edit(note.id,payload);assert.equal(saved.status,200,await saved.clone().text());
|
||||
assert.equal((await request('/api/notes/'+note.id)).entry.title,payload.title);
|
||||
assert.equal((await edit(note.id,{...payload,title:'旧窗口写入'})).status,409,'Stale editor must not overwrite a newer save');
|
||||
const updatedText=await fetch(base+'/explore/'+note.id+'?agent_mode=True').then(r=>r.text());assert.ok(updatedText.includes(updatedBody));assert.ok(updatedText.includes('在线编辑'));
|
||||
const updatedHtml=await fetch(base+'/explore/'+note.id).then(r=>r.text());assert.ok(updatedHtml.includes('<ul>'));assert.ok(updatedHtml.includes('<li>'));assert.ok(updatedHtml.includes('复制网页链接'));assert.ok(updatedHtml.includes('复制纯文本链接'));assert.ok(!updatedHtml.includes('原文件 ↗'));
|
||||
const editedPreview=(await request('/api/explore-feed?category='+encodeURIComponent('在线编辑'))).entries.find((e:{id:string})=>e.id===note.id);assert.equal(editedPreview.description,payload.description);
|
||||
assert.ok((await fetch(base+'/api/wiki-index').then(r=>r.text())).includes(payload.title));
|
||||
const storedPost=(await request('/api/notes/'+first.id)).entry;
|
||||
const oldCaption=(await db().query("SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.kind='text'",[first.id])).rows[0].id;
|
||||
const captionReuse=await request('/api/posts',{kind:'article',title:'共享文本的笔记',assets:[{id:oldCaption,role:'caption'}]});
|
||||
const savedPost=await edit(first.id,{title:'修改后的图片笔记',description:'图片仍保留',markdown:'新的正文',tags:[newTag.id],revision:storedPost.revision});assert.equal(savedPost.status,200,await savedPost.clone().text());
|
||||
const updatedPost=await request('/api/notes/'+first.id);assert.equal(updatedPost.entry.imageCount,2);assert.equal(updatedPost.entry.editableMarkdown,'新的正文');
|
||||
assert.equal((await request('/api/notes/'+captionReuse.id)).entry.editableMarkdown,'可以复用的独立文字','Editing one note must not mutate shared text');
|
||||
const authored=(await request('/api/feed?section=articles')).posts.find((p:{slug:string})=>p.slug===published.published[0]);const authoredState=await request('/api/notes/'+authored.id);
|
||||
assert.equal((await edit(authored.id,{title:'保留用户修改',description:'部署不能覆盖',markdown:'手动修改的正文',tags:[newTag.id],revision:authoredState.entry.revision})).status,200);
|
||||
await publishTestSeries();const retained=await request('/api/notes/'+authored.id);assert.equal(retained.entry.title,'保留用户修改');assert.equal(retained.entry.editableMarkdown,'手动修改的正文');
|
||||
assert.equal((await request('/api/notes/'+note.id)).entry.title,payload.title,'Static edits outlive content publication');
|
||||
assert.equal((await fetch(base+'/api/notes/missing')).status,404);
|
||||
assert.equal((await fetch(base+'/api/notes/'+note.id,{method:'DELETE'})).status,405);
|
||||
// API-only publication: upload independent assets, retain a stable public ID, then update cover.
|
||||
const postCountBefore=(await db().query('SELECT count(*)::integer AS n FROM posts')).rows[0].n;
|
||||
const assetsForm=new FormData();assetsForm.set('kind','image');assetsForm.set('assetOnly','true');
|
||||
assetsForm.append('files',new Blob([new Uint8Array(a)],{type:'image/png'}),'standalone-a.png');
|
||||
const secondImage=await sharp({create:{width:160,height:220,channels:3,background:'#d7c7b5'}}).png().toBuffer();
|
||||
assetsForm.append('files',new Blob([new Uint8Array(secondImage)],{type:'image/png'}),'standalone-b.png');
|
||||
const uploadedOnly=await fetch(base+'/api/upload',{method:'POST',body:assetsForm});assert.equal(uploadedOnly.status,201,await uploadedOnly.clone().text());
|
||||
const independent=await uploadedOnly.json();assert.equal(independent.assets.length,2);assert.deepEqual(independent.files.map((file:{filename:string})=>file.filename).sort(),['standalone-a.png','standalone-b.png']);assert.deepEqual(independent.files.map((file:{id:string})=>file.id),independent.assets,'file metadata matches the returned asset IDs');
|
||||
assert.equal((await db().query('SELECT count(*)::integer AS n FROM posts')).rows[0].n,postCountBefore,'assetOnly never creates a post');
|
||||
const publicId=note.id;
|
||||
const apiBody='## 纯文本资料\n\n```json\n{"type":"text","box":[1,2,3,4]}\n```\n\n```tsx\nexport default function Demo(){return <div/>}\n```';
|
||||
const publishedNote=await request('/api/posts',{kind:'article',title:'API 发布资料',slug:'api-public-'+randomUUID(),publicId,text:apiBody,assets:independent.assets.map((id:string)=>({id})),coverAssetId:independent.assets[0],tags:[child.id]});
|
||||
assert.equal(publishedNote.publicId,publicId);assert.ok(!(await fetch(base+'/api/wiki-index').then(r=>r.text())).includes('['+payload.title+']'),'Migrated code entries are not listed under stale titles');assert.equal(publishedNote.url,'/explore/'+publicId);
|
||||
const publicEntry=(await request('/api/notes/'+publicId)).entry;assert.equal(publicEntry.id,publicId);assert.equal(publicEntry.postSlug,publishedNote.slug);assert.equal(publicEntry.coverAssetId,independent.assets[0]);
|
||||
assert.equal((await request('/api/explore-feed')).entries.filter((e:{id:string})=>e.id===publicId).length,1,'API note replaces rather than duplicates its static predecessor');
|
||||
const publicText=await fetch(base+'/explore/'+publicId+'?agent_mode=True').then(r=>r.text());assert.ok(publicText.includes(apiBody));assert.ok(publicText.includes(independent.assets[0]));
|
||||
const coverPayload={title:publicEntry.title,description:publicEntry.description,markdown:publicEntry.editableMarkdown,tags:[child.id],revision:publicEntry.revision,coverAssetId:independent.assets[1]};
|
||||
const coverSaved=await edit(publicId,coverPayload);assert.equal(coverSaved.status,200,await coverSaved.clone().text());
|
||||
const afterCover=(await request('/api/notes/'+publicId)).entry;assert.equal(afterCover.coverAssetId,independent.assets[1]);assert.equal(afterCover.media[0].url,'/api/media/'+independent.assets[1]);assert.notEqual(afterCover.revision,publicEntry.revision);
|
||||
assert.equal((await edit(publicId,coverPayload)).status,409,'Stale cover edits cannot overwrite current media');
|
||||
const replaceMedia=await edit(publicId,{...coverPayload,revision:afterCover.revision,assets:[{id:independent.assets[1],role:'content'},{id:independent.assets[0],role:'caption'}]});assert.equal(replaceMedia.status,200,await replaceMedia.clone().text());
|
||||
const finalPublic=(await request('/api/notes/'+publicId)).entry;assert.equal(finalPublic.imageCount,1);assert.equal(finalPublic.assets.length,2);assert.equal(finalPublic.editableMarkdown,apiBody);
|
||||
const duplicatePublic=await fetch(base+'/api/posts',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({kind:'article',title:'不覆盖已有 ID',publicId,text:'x'})});assert.equal(duplicatePublic.status,409);
|
||||
assert.equal((await fetch(base+'/p/'+publishedNote.slug,{redirect:'manual'})).headers.get('location'),'/explore/'+publicId);
|
||||
for(const removed of ['/layout-reference/index.html','/layout-reference/ref-01/index.html','/layout-reference/index.json'])assert.equal((await fetch(base+removed)).status,404,removed);
|
||||
for(const doc of ['SKILL','style','upload','checks']){const r=await fetch(base+`/skills/street-people/${doc}.md`);assert.equal(r.status,200);assert.ok(r.headers.get('content-type')?.includes('text/markdown'));const text=await r.text();assert.ok(text.startsWith('# '));assert.ok(!text.includes('<html'));}
|
||||
for(const doc of ['SKILL','workflow','visual-grammar','prompt','delivery']){
|
||||
const path=`/skills/shadow-puppet/${doc}.md`;const response=await fetch(base+path);assert.equal(response.status,200,path);assert.ok(response.headers.get('content-type')?.includes('text/markdown'));assert.ok((await response.text()).startsWith('# '));
|
||||
const head=await fetch(base+path,{method:'HEAD'});assert.equal(head.status,200);assert.equal(await head.text(),'');
|
||||
if(doc!=='SKILL')assert.equal((await fetch(base+'/tools/skills/shadow-puppet/'+doc)).status,200);
|
||||
}
|
||||
for(const image of ['egret-example','dancer-example']){
|
||||
const asset=managedMedia[`apps/waterfall-wiki/public/skills/shadow-puppet/${image}.png` as keyof typeof managedMedia];
|
||||
const key='integration/legacy-'+asset.id+'.png';await putFile(key,testCoverFile,'image/png');
|
||||
await db().query("INSERT INTO assets(id,kind,filename,storage_key,mime_type,byte_size,sha256) VALUES($1,'image',$2,$3,'image/png',$4,$5)",[asset.id,image+'.png',key,testCoverBytes.length,testCover.sha256]);
|
||||
}
|
||||
for(const image of ['egret-example','dancer-example'])assert.equal((await fetch(base+`/skills/shadow-puppet/${image}.png`,{method:'HEAD'})).status,200);
|
||||
for(const path of ['/skills/missing/SKILL.md','/skills/shadow-puppet/missing.md','/tools/skills/shadow-puppet/missing'])assert.equal((await fetch(base+path)).status,404,path);
|
||||
assert.equal((await fetch(base+'/api/skill-docs/shadow-puppet/SKILL',{method:'POST'})).status,405);
|
||||
for(const path of ['/agent','/agent/index.md','/index.md']){
|
||||
const entry=await fetch(base+path);assert.equal(entry.status,200,path);assert.match(entry.headers.get('content-type')||'',/text\/markdown/);const text=await entry.text();assert.ok(text.includes('/api/documents'));assert.ok(text.includes('/api/guides'));assert.ok(!text.includes('/skills/index.md'));
|
||||
}
|
||||
const machineIndex=await fetch(base+'/api/guides');assert.equal(machineIndex.status,200);assert.equal((await machineIndex.json()).protocol,'linked-guidance/0.1');
|
||||
const home=await fetch(base+'/').then(r=>r.text());
|
||||
for(const href of ['/documents','/graphic','/infinite_canvas','/account?next=/workspace'])assert.ok(home.includes('href="'+href+'"'),`Landing page links to ${href}`);
|
||||
assert.ok(home.includes('让灵感,有形。'));
|
||||
for(const [oldPath,newPath] of [['/studio/graphic','/graphic'],['/studio/infinite_canvas','/infinite_canvas']]){
|
||||
const response=await fetch(base+oldPath,{redirect:'manual'});assert.equal(response.status,308);assert.equal(response.headers.get('location'),newPath);
|
||||
}
|
||||
// Legacy media and skill functionality stays covered by its own routes above and below.
|
||||
|
||||
const spec=await request('/api/skills/street-people');assert.equal(spec.generation.executor,'coding-agent');
|
||||
assert.equal((await fetch(base+'/api/skills/street-people?format=md')).headers.get('content-type'),'text/markdown; charset=utf-8');
|
||||
const skillUpload=async(bytes:Uint8Array,slug:string)=>{const f=new FormData();f.set('slug',slug);f.append('files',new Blob([new Uint8Array(bytes)],{type:'image/png'}),'person.png');return fetch(base+'/api/skills/street-people',{method:'POST',body:f});};
|
||||
const skillSlug='skill-'+randomUUID();
|
||||
assert.equal((await skillUpload(a,skillSlug)).status,400,'Opaque PNG rejected');
|
||||
const opaqueAlpha=await sharp({create:{width:64,height:64,channels:4,background:'#fff'}}).png().toBuffer();
|
||||
assert.equal((await skillUpload(opaqueAlpha,skillSlug)).status,400,'Unused alpha channel rejected');
|
||||
const transparent=await sharp({create:{width:64,height:64,channels:4,background:'#0000'}}).composite([{input:await sharp({create:{width:32,height:32,channels:4,background:'#faf4e5'}}).png().toBuffer(),left:16,top:16}]).png().toBuffer();
|
||||
const created=await skillUpload(transparent,skillSlug);assert.equal(created.status,201,await created.clone().text());const character=await created.json();assert.equal(character.slug,skillSlug);assert.equal(character.url,'/p/'+skillSlug);
|
||||
assert.equal((await skillUpload(transparent,skillSlug)).status,409,'Stable slug prevents duplicate posts');
|
||||
const stored=await fetch(base+'/api/media/'+character.assets[0]);assert.deepEqual(Buffer.from(await stored.arrayBuffer()),transparent,'PNG alpha and original bytes preserved in S3');
|
||||
assert.equal((await fetch(base+character.url)).status,200);
|
||||
// A real stored body-only match and backlinks must update through the public API.
|
||||
const targetNote=await request('/api/posts',{kind:'article',title:'引用目标',text:'仅在正文中的索引验证 OrchidLexicon',tags:[root.id]});
|
||||
const referring=await request('/api/posts',{kind:'article',title:'引用来源',text:`[目标](${targetNote.url}) [重复](${targetNote.url}?agent_mode=True)`,tags:[]});
|
||||
const targetEntry=(await request('/api/notes/'+targetNote.id)).entry;
|
||||
assert.equal(targetEntry.backlinkCount,1);assert.equal(targetEntry.backlinks[0].id,referring.id);
|
||||
const bodySearch=await request('/api/explore-feed?q=orchidlexicon');assert.equal(bodySearch.total,1);assert.equal(bodySearch.entries[0].id,targetNote.id);
|
||||
const mixedSearch=await request('/api/explore-feed?q='+encodeURIComponent('OrchidLexicon 线条'));assert.equal(mixedSearch.total,1);
|
||||
const removeReference=await request('/api/notes/'+referring.id);
|
||||
const editResponse=await fetch(base+'/api/notes/'+referring.id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({title:'引用来源',description:'更新后撤回引用',markdown:'引用已经移除',tags:[],revision:removeReference.entry.revision})});assert.equal(editResponse.status,200);
|
||||
assert.equal((await request('/api/notes/'+targetNote.id)).entry.backlinkCount,0);
|
||||
// System labels have a closed catalogue; ordinary # labels remain user-created.
|
||||
const allLabels=await request('/api/tags'),systems=allLabels.filter((t:{kind:string})=>t.kind==='system');assert.equal(systems.length,2);
|
||||
const entryLabel=systems.find((t:{system_key:string})=>t.system_key==='document-entry');assert.ok(entryLabel);
|
||||
for(const body of [{name:'非法系统项',kind:'system'},{name:'#文档入口'}]){
|
||||
const response=await fetch(base+'/api/tags',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal(response.status,400);
|
||||
}
|
||||
const plain=await request('/api/tags',{name:'#可随时添加'});assert.equal(plain.kind,'normal');
|
||||
const beforeTags=(await request('/api/notes/'+targetNote.id)).entry;
|
||||
const patchTags=(payload:unknown)=>fetch(base+'/api/notes/'+targetNote.id,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
const textLinksBefore=(await db().query("SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.kind='text' ORDER BY a.id",[targetNote.id])).rows;
|
||||
const assigned=await patchTags({tags:[plain.id,entryLabel.id],revision:beforeTags.revision});assert.equal(assigned.status,200,await assigned.clone().text());
|
||||
const afterTags=(await request('/api/notes/'+targetNote.id)).entry;assert.deepEqual(afterTags.categories,[plain.name]);assert.equal(afterTags.systemTags[0].system_key,'document-entry');assert.equal(afterTags.editableMarkdown,beforeTags.editableMarkdown);
|
||||
assert.deepEqual((await db().query("SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.kind='text' ORDER BY a.id",[targetNote.id])).rows,textLinksBefore,'Tag-only PATCH preserves the existing text assets');
|
||||
const systemFeed=await request('/api/explore-feed?category='+encodeURIComponent(entryLabel.name));assert.ok(systemFeed.entries.some((e:{id:string})=>e.id===targetNote.id));
|
||||
assert.equal((await patchTags({tags:[],revision:beforeTags.revision})).status,409);
|
||||
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();
|
||||
}
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { chapters, seriesCover } from "../src/content/learning-skills/data";
|
||||
|
||||
test("the authored series has three distinct chapters of ten sourced skills and one cover",()=>{
|
||||
assert.equal(chapters.length,3);assert.equal(new Set(chapters.map(c=>c.key)).size,3);
|
||||
assert.equal(new Set(chapters.map(c=>c.slug)).size,3);assert.equal(seriesCover,"/learning-skills/cover.png");
|
||||
for(const chapter of chapters){
|
||||
assert.equal(chapter.skills.length,10);assert.equal(new Set(chapter.skills.map(s=>s.source)).size,10);
|
||||
for(const skill of chapter.skills){
|
||||
const source=new URL(skill.source);assert.equal(source.protocol,"https:");assert.equal(source.hostname,"github.com");
|
||||
assert.ok(skill.title&&skill.input&&skill.output&&skill.prompt&&skill.note);
|
||||
assert.equal(skill.sample.length,3);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {decodeCursor,encodeCursor,validSection} from '../src/lib/model';
|
||||
test('timeline cursor preserves timestamp and ID, rejects malformed values',()=>{
|
||||
const date='2026-10-22T00:00:00.000Z',id=randomUUID();assert.deepEqual(decodeCursor(encodeCursor(date,id)),[date,id]);assert.throws(()=>decodeCursor('invalid'));assert.equal(decodeCursor(),null);
|
||||
});
|
||||
test('only the five content sections are recognized',()=>{assert.equal(validSection('videos')?.kind,'video');assert.equal(validSection('unknown'),undefined);});
|
||||
@@ -1,18 +0,0 @@
|
||||
import React from 'react';
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {NoteMarkdown} from '../src/components/NoteMarkdown';
|
||||
const render=(text:string)=>renderToStaticMarkup(<NoteMarkdown text={text}/>);
|
||||
test('Markdown renders nested bullets, numbered and task lists as semantic lists',()=>{
|
||||
const html=render('- 第一项\n - 子项目\n- 第二项\n\n3. 第三步\n4. 第四步\n\n- [x] 完成\n- [ ] 待办');
|
||||
assert.match(html,/<ul>/);assert.match(html,/<li>第一项\n<ul>/);assert.match(html,/<ol start="3">/);assert.match(html,/type="checkbox"/);assert.match(html,/checked/);assert.ok(!html.includes('- 第一项'));
|
||||
});
|
||||
test('Markdown keeps fenced code, tables, strong text and subtle links',()=>{
|
||||
const html=render('## 标题\n\n**重点** 和 [相关笔记](/explore/abc?agent_mode=True)\n\n| 名称 | 值 |\n| --- | --- |\n| 条目 | 1 |\n\n```ts\nconst items = [1, 2];\n```');
|
||||
assert.match(html,/<h2>标题/);assert.match(html,/<strong>重点/);assert.match(html,/<table>/);assert.match(html,/<pre><code class="language-ts">/);assert.match(html,/note-inline-link/);assert.match(html,/href="\/explore\/abc"/);
|
||||
});
|
||||
test('Untrusted Markdown cannot execute HTML or javascript links and images stay links',()=>{
|
||||
const html=render('<script>alert(1)</script>\n\n[unsafe](javascript:alert)\n\n');
|
||||
assert.ok(!html.includes('<script>'));assert.ok(!html.includes('href="javascript:'));assert.ok(!html.includes('<img'));assert.match(html,/href="\/api\/media\/example"/);
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import sharp from 'sharp';
|
||||
import {compressPreview,previewWidth,staticPreviewPath,cachedPreview} from '../src/lib/preview';
|
||||
test('preview input validation rejects traversal and arbitrary sizes',()=>{for(const value of [1,10000,'bad'])assert.equal(previewWidth(value),null);assert.equal(previewWidth(480),480);for(const source of ['https://example.com/x.png','/../secret.png','//remote/x.png','/x.svg','/x.png?foo=bar'])assert.throws(()=>staticPreviewPath(source,'/public'));assert.equal(staticPreviewPath('/images/a.png','/public'),'/public/images/a.png');});
|
||||
test('large PNG becomes a bounded WebP with no upscaling',async()=>{const original=await sharp({create:{width:2200,height:3000,channels:3,background:'#f0e2d2'}}).png().toBuffer();const preview=await compressPreview(original,480);const info=await sharp(preview).metadata();assert.equal(info.format,'webp');assert.equal(info.width,480);assert.ok(preview.length<=100000);});
|
||||
test('identical concurrent requests share one transform and reuse the disk result',async()=>{let loads=0;const input=await sharp({create:{width:40,height:40,channels:3,background:'#fff'}}).png().toBuffer();const identity='test-'+Date.now();const load=async()=>{loads++;return input};const [a,b]=await Promise.all([cachedPreview(identity,480,load),cachedPreview(identity,480,load)]);assert.deepEqual(a.bytes,b.bytes);assert.equal(loads,1);await cachedPreview(identity,480,load);assert.equal(loads,1);});
|
||||
test('export derivatives keep resolution and use an independent cache identity',async()=>{assert.equal(previewWidth(2160,'export'),2160);assert.equal(previewWidth(2160),null);assert.equal(previewWidth(480,'export'),null);const input=await sharp({create:{width:1800,height:1200,channels:3,background:'#eddfbd'}}).png().toBuffer();const identity='export-'+Date.now();const result=await cachedPreview(identity,2160,async()=>input,true);const meta=await sharp(result.bytes).metadata();assert.equal(meta.width,1800);assert.equal(meta.height,1200);const normal=await cachedPreview(identity,480,async()=>input);assert.notEqual(result.etag,normal.etag)});
|
||||
@@ -1,59 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {skillDocuments,skillResources,documentMarkdown,getSkill,skillDocumentMarkdown,skillCatalog} from '../src/content/skills/catalog';
|
||||
test('human and agent documents share a complete linked resource registry',()=>{
|
||||
for(const doc of skillDocuments){const md=documentMarkdown(doc.id)!;assert.ok(md.startsWith('# '+doc.title));for(const block of doc.blocks){if(block.text)assert.ok(md.includes(block.text));for(const id of block.refs||[])assert.ok(skillResources.some(r=>r.id===id))}assert.ok(!md.includes('/p/street-people-'));}
|
||||
assert.equal(documentMarkdown('missing'),null);assert.equal(new Set(skillResources.map(r=>r.id)).size,skillResources.length);
|
||||
for(const doc of skillDocuments)assert.ok(skillResources.some(r=>r.id===doc.id&&r.human&&r.href.endsWith('.md')));
|
||||
});
|
||||
|
||||
test('original collections retain their authored documents and API resources',()=>{
|
||||
for(const card of skillCatalog){
|
||||
const skill=getSkill(card.id)!;assert.ok(skill);assert.equal(skill.id,card.id);
|
||||
assert.equal(new Set(skill.resources.map(r=>r.id)).size,skill.resources.length);
|
||||
for(const doc of skill.documents){
|
||||
const md=skillDocumentMarkdown(card.id,doc.id)!;assert.ok(md.startsWith('# '+doc.title));
|
||||
assert.ok(skill.resources.some(r=>r.id===doc.id&&r.kind==='document'&&r.human));
|
||||
for(const block of doc.blocks){if(block.text)assert.ok(md.includes(block.text));for(const id of block.refs||[])assert.ok(skill.resources.some(r=>r.id===id),card.id+': '+id);}
|
||||
}
|
||||
}
|
||||
assert.equal(getSkill('__proto__'),undefined);assert.equal(skillDocumentMarkdown('missing','index'),null);assert.equal(skillDocumentMarkdown('shadow-puppet','missing'),null);
|
||||
const shadow=getSkill('shadow-puppet')!;
|
||||
assert.equal(shadow.resources.filter(r=>r.kind==='document').length,5);
|
||||
assert.equal(shadow.resources.filter(r=>r.kind==='image').length,2);
|
||||
assert.equal(shadow.resources.find(r=>r.id==='upload-api')?.href,'/api/upload');
|
||||
assert.equal(shadow.resources.find(r=>r.id==='media-api')?.template,true);
|
||||
});
|
||||
|
||||
test('every guidance page has a matching Markdown URL and all document links resolve globally',async()=>{
|
||||
const {guidanceDocuments,getGuidance,guidanceMarkdown,guidanceIndexMarkdown,humanDocumentUrl,markdownDocumentUrl,guidanceBacklinks}=await import('../src/content/skills/guidance');
|
||||
assert.equal(new Set(guidanceDocuments.map(d=>d.path)).size,guidanceDocuments.length);
|
||||
for(const doc of guidanceDocuments){
|
||||
for(const r of doc.resources)if(r.documentPath)assert.ok(getGuidance(r.documentPath),r.documentPath);
|
||||
const text=guidanceMarkdown(doc.path)!;
|
||||
assert.ok(text.startsWith('# '+doc.title));
|
||||
assert.equal(markdownDocumentUrl(doc.path),humanDocumentUrl(doc.path)+'?agent_mode=True');
|
||||
assert.ok(text.includes(humanDocumentUrl(doc.path)));
|
||||
for(const block of doc.blocks){
|
||||
if(block.text)assert.ok(text.includes(block.text));
|
||||
for(const id of block.refs||[]){const r=doc.resources.find(r=>r.id===id);assert.ok(r,doc.path+': '+id);if(r.documentPath){assert.ok(getGuidance(r.documentPath));assert.ok(text.includes(markdownDocumentUrl(r.documentPath)));}}
|
||||
}
|
||||
assert.ok(guidanceIndexMarkdown().includes(markdownDocumentUrl(doc.path)));
|
||||
}
|
||||
assert.ok(guidanceIndexMarkdown(true).includes('/skills/index.md'));
|
||||
assert.equal(getGuidance('__proto__'),undefined);assert.equal(guidanceMarkdown('missing'),null);
|
||||
const shared=guidanceBacklinks('image-delivery').map(d=>d.path);
|
||||
assert.ok(shared.includes('street-people/checks'));assert.ok(shared.includes('shadow-puppet/delivery'));
|
||||
assert.ok(guidanceMarkdown('image-delivery')!.includes(markdownDocumentUrl('street-people/checks')));
|
||||
assert.ok(guidanceMarkdown('image-delivery')!.includes(markdownDocumentUrl('shadow-puppet/delivery')));
|
||||
});
|
||||
|
||||
test('Markdown counterpart responses support GET and HEAD and reject writes or missing documents',async()=>{
|
||||
const {sendMarkdown}=await import('../src/lib/markdown-response');
|
||||
const {guidanceMarkdown}=await import('../src/content/skills/guidance');
|
||||
for(const [method,text,expected] of [['GET',guidanceMarkdown('shadow-puppet/prompt'),200],['HEAD',guidanceMarkdown('shadow-puppet/prompt'),200],['POST',guidanceMarkdown('shadow-puppet/prompt'),405],['GET',guidanceMarkdown('missing'),404]] as const){
|
||||
const result={code:0,body:null as string|null,headers:{} as Record<string,string>,setHeader(k:string,v:string){this.headers[k]=v;return this},status(code:number){this.code=code;return this},send(body:string){this.body=body;return this},end(){return this}};
|
||||
sendMarkdown({method} as import('next').NextApiRequest,result as unknown as import('next').NextApiResponse,text);
|
||||
assert.equal(result.code,expected);if(method==='GET'&&expected===200){assert.match(result.headers['Content-Type'],/text\/markdown/);assert.ok(result.body?.startsWith('# '));}else assert.equal(result.body,null);
|
||||
}
|
||||
});
|
||||
@@ -1,5 +0,0 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {wikiPages,findWikiPage,wikiMarkdown,wikiPath} from '../src/content/wiki';
|
||||
test('every wiki card resolves to the same AI-visible page',()=>{for(const page of wikiPages){const key=page.namespace+':'+page.slug;assert.equal(findWikiPage(key),page);assert.ok(wikiMarkdown(page).includes(page.body));assert.equal(decodeURIComponent(wikiPath(page)),'/wiki/'+key);}});
|
||||
test('category membership crosses namespaces and rejects unknown categories',()=>{const page=findWikiPage('Category:创作方法');assert.ok(page?.body.includes('Main:'));assert.ok(page?.body.includes('Template:'));assert.equal(findWikiPage('Category:missing'),undefined);assert.equal(findWikiPage('Unknown:welcome'),undefined);});
|
||||
@@ -1,7 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
@@ -14,8 +18,20 @@
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"baseUrl": ".",
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
},
|
||||
"allowImportingTsExtensions": true
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user