Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: add native poster notes and unified AI editing

tianma-if0da78f6ce8a4
diff --git a/README.ja.md b/README.ja.md
index 08cc837f..5e7ff54b 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -180,7 +180,7 @@ curl -fsSL https://edgeever.org/install.sh | bash
### Telegram コミュニティ
-EdgeEver の使い方、AI Agent の実例、費用対効果の高い / 無料の AI 資源、自動化の流れを話す場です。
+EdgeEver コミュニティへようこそ。Vibe Coding や AI を探求する仲間が集まり、最先端の AI 生産性と個人ナレッジベースのベストプラクティスを共有しています。
👉 [EdgeEver の Telegram グループに参加](https://t.me/+wwUx1BYLrIdiZjY1)
@@ -287,6 +287,7 @@ EdgeEver は無料のオープンソースプロジェクトです。クロス
- ノート製品の設計は、[Evernote](https://evernote.com/) や [Notion](https://www.notion.com/) など成熟したノートツールの公開されている製品体験も参考にしています。関連機能は EdgeEver が独自に設計し、実装しています。
- マインドマップと視覚的な図のノートは、[XMind](https://xmind.com/) と [ProcessOn](https://www.processon.com/) の公開されている製品体験を参考にしています。関連機能は EdgeEver が独自に設計し、実装しています。
+- EdgeEver のポスターデザイン機能は、向阳乔木(joeseesun)の [Qiaomu Design](https://github.com/joeseesun/qiaomu-cover-design) を参考にし、MIT ライセンスに基づいてテンプレートと文字組みエンジンを改変して利用しています。
## 商標とブランド
diff --git a/README.md b/README.md
index f72014ea..b3cf4a43 100644
--- a/README.md
+++ b/README.md
@@ -181,7 +181,7 @@ The instance administrator can create, disable, or reset member accounts in **Pr
### Telegram Community
-Welcome to the EdgeEver community. Join us to discuss the EdgeEver experience, real-world AI Agent applications, cost-effective or free AI resources, and automation workflows.
+Welcome to the EdgeEver community, bringing together developers and creators exploring vibe coding and AI. Join us to discuss cutting-edge AI productivity and best practices for personal knowledge bases.
👉 [Join the EdgeEver Telegram group](https://t.me/+wwUx1BYLrIdiZjY1)
@@ -288,6 +288,7 @@ EdgeEver is a free and open-source project. Sustaining cross-platform client dev
- EdgeEver's note-taking product design was also informed by the publicly available product experiences of mature note-taking tools such as [Evernote](https://evernote.com/) and [Notion](https://www.notion.com/). The related features were independently designed and implemented by EdgeEver.
- The product design of mind-map and visual-diagram notes was informed by the publicly available product experiences of [XMind](https://xmind.com/) and [ProcessOn](https://www.processon.com/). These features were independently designed and implemented by EdgeEver.
+- EdgeEver's poster design workspace draws inspiration from [Qiaomu Design](https://github.com/joeseesun/qiaomu-cover-design) by 向阳乔木 (joeseesun), and adapts its templates and typography engine under the MIT license.
## Trademark and Brand Use
diff --git a/README.pl-PL.md b/README.pl-PL.md
index 41416134..9c084dc3 100644
--- a/README.pl-PL.md
+++ b/README.pl-PL.md
@@ -177,7 +177,7 @@ Jedna instancja obsługuje wiele kont. Administrator może tworzyć i wyłącza
### Społeczność na Telegramie
-Zapraszamy do rozmów o korzystaniu z EdgeEver, agentach AI, niedrogich lub darmowych usługach AI i automatyzacji.
+Zapraszamy do społeczności EdgeEver, skupiającej twórców i pasjonatów vibe codingu oraz AI. Rozmawiajmy o nowoczesnej produktywności opartej na AI i sprawdzonych praktykach budowania osobistej bazy wiedzy.
👉 [Dołącz do grupy na Telegramie](https://t.me/+wwUx1BYLrIdiZjY1)
@@ -284,6 +284,7 @@ EdgeEver jest darmowym projektem o otwartym kodzie. Rozwijanie aplikacji na ró
- Przy projektowaniu EdgeEver wzorowano się na publicznie dostępnych rozwiązaniach dojrzałych aplikacji do notatek, takich jak [Evernote](https://evernote.com/) i [Notion](https://www.notion.com/). Powiązane funkcje zostały zaprojektowane i zaimplementowane niezależnie przez EdgeEver.
- Inspiracją dla notatek z mapami myśli i diagramami były publicznie dostępne funkcje [XMind](https://xmind.com/) i [ProcessOn](https://www.processon.com/). Funkcje te zostały zaprojektowane i zaimplementowane niezależnie przez EdgeEver.
+- Narzędzie do projektowania plakatów w EdgeEver czerpie inspirację z [Qiaomu Design](https://github.com/joeseesun/qiaomu-cover-design) autorstwa 向阳乔木 (joeseesun) i wykorzystuje dostosowane szablony oraz silnik typograficzny udostępnione na licencji MIT.
## Znak towarowy i użycie marki
diff --git a/README.zh-CN.md b/README.zh-CN.md
index b3329c9f..8e3d3651 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -181,7 +181,7 @@ curl -fsSL https://edgeever.org/install.sh | bash
<h3 id="wechat-group">微信交流群</h3>
-欢迎加入 EdgeEver AI 交流群,这里聚集了大量 Vibe Coding 与 AI 玩家。一起交流 EdgeEver 体验、AI Agent 实战落地、高性价比/免费 AI 资源及自动化工作流。
+欢迎加入 EdgeEver AI 交流群,这里聚集了大量 Vibe Coding 与 AI 玩家。一起交流前沿 AI 生产力与个人知识库的最佳实践。
> 扫描下方二维码或添加微信 `m1245207870`(备注“EdgeEver 进群”),群主将手动邀请入群。
@@ -291,6 +291,7 @@ EdgeEver 是免费开源项目。保持跨平台客户端(macOS、Windows、Li
- EdgeEver 的笔记产品设计也参考了 [Evernote(印象笔记)](https://evernote.com/)、[Notion](https://www.notion.com/) 等成熟笔记工具的公开产品体验。相关功能由 EdgeEver 独立设计与实现。
- 思维导图与可视化图表笔记的产品设计参考了 [XMind](https://xmind.com/) 和 [ProcessOn](https://www.processon.com/) 等图表工具的公开产品体验。相关功能由 EdgeEver 独立设计与实现。
+- EdgeEver 的海报设计工作台借鉴了向阳乔木(joeseesun)的 [Qiaomu Design](https://github.com/joeseesun/qiaomu-cover-design),并基于其 MIT 开源许可改编了模板与字体排版引擎。
## 商标与品牌使用
diff --git a/README.zh-TW.md b/README.zh-TW.md
index 5be83f34..0827de39 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -179,7 +179,7 @@ curl -fsSL https://edgeever.org/install.sh | bash
<h3 id="wechat-group">微信交流群</h3>
-歡迎加入 EdgeEver AI 交流群,這裡聚集了大量 Vibe Coding 與 AI 玩家。一起交流 EdgeEver 體驗、AI Agent 實戰落地、高性價比/免費 AI 資源及自動化工作流程。
+歡迎加入 EdgeEver AI 交流群,這裡聚集了大量 Vibe Coding 與 AI 玩家。一起交流前沿 AI 生產力與個人知識庫的最佳實踐。
> 掃描下方 QR Code 或加入微信 `m1245207870`(備註「EdgeEver 進群」),群主將手動邀請入群。
@@ -289,6 +289,7 @@ EdgeEver 是免費開源專案。保持跨平台用戶端(macOS、Windows、Li
- EdgeEver 的筆記產品設計也參考了 [Evernote(印象筆記)](https://evernote.com/)、[Notion](https://www.notion.com/) 等成熟筆記工具的公開產品體驗。相關功能由 EdgeEver 獨立設計與實作。
- 心智圖與視覺化圖表筆記的產品設計參考了 [XMind](https://xmind.com/) 和 [ProcessOn](https://www.processon.com/) 等圖表工具的公開產品體驗。相關功能由 EdgeEver 獨立設計與實作。
+- EdgeEver 的海報設計工作台借鑑了向阳乔木(joeseesun)的 [Qiaomu Design](https://github.com/joeseesun/qiaomu-cover-design),並基於其 MIT 開源授權改編了範本與字型排版引擎。
## 商標與品牌使用
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.ts
index 901df5bd..dd747732 100644
--- a/apps/api/src/companion-agent-tools.ts
+++ b/apps/api/src/companion-agent-tools.ts
@@ -124,6 +124,8 @@ const TOOL_HINTS: Record<string, string> = {
add_table_record: " Add one requested record to a structured table. First call get_table_records, then use its field IDs and latest revision. Do not invent factual records to fill a new table.",
create_diagram_memo: " Create an editable visual diagram note. kind=mind-map for 思维导图/mind map, flowchart for 流程图, architecture for 架构图. Never use this for 信息图/infographic; call create_infographic_memo. Omit edge ids; EdgeEver generates them. For mind maps, give a root and children with parentId; omit node type. If the user did not name a notebook, omit notebookId. The diagram is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Build nodes from the open note body in Focus DATA when the user refers to this note.",
create_infographic_memo: " Create an AntV infographic note (信息图). A share, proportion, or 占比 uses template chart-pie-donut-plain-text and numeric data.values, not a mind map. If the user did not supply the figures, say in data.desc that they are illustrative and are not an official disclosure. If the user did not name a notebook, omit notebookId. The infographic is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it.",
+ get_poster: " Read the existing poster canvas and elements before editing. Do not use raw Markdown for posters.",
+ update_poster: " Edit poster text, colors, typography and positions after get_poster. Preserve unmentioned and locked elements. Pass the revision you read.",
get_diagram: " Read an existing editable diagram as a semantic graph. Call this before update_diagram. Do not use get_memo when you only need the diagram structure.",
update_diagram: " Edit an existing diagram after get_diagram. Pass expectedRevision from get_diagram. Use add_node, update_node, remove_node, add_edge, update_edge, or remove_edge. Do not create a new diagram unless the user asked for a new note.",
use_note_template: " Create a new memo from a template. If the user did not name a notebook, omit notebookId. The note is saved in the inbox (等待分类). Do not ask which notebook.",
@@ -258,6 +260,7 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
if (!args.input.allowNotes || !args.context) return {};
const session = args.session ?? emptyCompanionAgentSession();
const inspected = new Map(Object.entries(session.inspected));
+ const posterReads = new Map<string, number>();
const persistSession = () => {
session.inspected = Object.fromEntries(inspected);
};
@@ -356,15 +359,15 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
}
parameters_.expectedRevision = memo.revision;
}
- if (autoApply && parameters_.dryRun !== true && (definition.name === "update_memo" || definition.name === "update_diagram" || definition.name === "restore_memo_revision")) {
+ if (autoApply && parameters_.dryRun !== true && (definition.name === "update_memo" || definition.name === "update_diagram" || definition.name === "update_poster" || definition.name === "restore_memo_revision")) {
const memo = await getMemoDetail(args.db, args.scope.workspaceId, String(parameters_.memoId));
- if (!memo || inspected.get(memo.id) !== memo.revision) {
+ if (!memo || inspected.get(memo.id) !== memo.revision || (definition.name === "update_poster" && posterReads.get(memo.id) !== memo.revision)) {
throw new AppError("companion_action_unread",
definition.name === "update_diagram"
? "Call get_diagram on this note before changing it."
: "Read the complete source notes before changing their content.", 400);
}
- if (definition.name === "update_diagram") parameters_.expectedRevision = memo.revision;
+ if (definition.name === "update_diagram" || definition.name === "update_poster") parameters_.expectedRevision = memo.revision;
}
if (autoApply && parameters_.dryRun !== true && definition.name === "merge_memos") {
const memoIds = Array.isArray(parameters_.memoIds) ? parameters_.memoIds.map(String) : [];
@@ -375,7 +378,7 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
}
}
}
- if ((definition.name === "get_memo" || definition.name === "get_diagram") && inspected.has(String(parameters_.memoId))) {
+ if ((definition.name === "get_memo" || definition.name === "get_diagram" || (definition.name === "get_poster" && posterReads.get(String(parameters_.memoId)) === inspected.get(String(parameters_.memoId)))) && inspected.has(String(parameters_.memoId))) {
// The original full result remains in this run's model messages. Only
// reuse it after authorization/context/cursor checks, never across runs.
return done({ id: parameters_.memoId, revision: inspected.get(String(parameters_.memoId)), alreadyRead: true,
@@ -447,7 +450,7 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
changes: updated.changes,
});
}
- if (definition.name === "update_memo") {
+ if (definition.name === "update_memo" || definition.name === "update_poster") {
const updated = (result as { memo: MemoDetail }).memo;
const receipt = await done({ applied: true, id: updated.id, title: updated.title,
notebookId: updated.notebookId, revision: updated.revision });
@@ -463,15 +466,16 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
return done({ applied: true, ...(typeof result === "object" && result ? result as object : { result }) });
}
if (current !== await companionWorkspaceCursor(args.db, args.scope.workspaceId)) return done({ error: "Notes changed during this read. Start a fresh request." });
- if (definition.name === "get_diagram") {
- const payload = result as { memo: { id: string; title: string | null; revision: number }; diagram: { kind?: string; nodes?: unknown[] } };
+ if (definition.name === "get_diagram" || definition.name === "get_poster") {
+ const payload = result as { memo: { id: string; title: string | null; revision: number; notebookId?: string }; diagram: { kind?: string; nodes?: unknown[] } };
inspected.set(payload.memo.id, payload.memo.revision);
+ if (definition.name === "get_poster") posterReads.set(payload.memo.id, payload.memo.revision);
const known = args.sources.find(source => source.id === payload.memo.id);
remember({
id: payload.memo.id,
title: payload.memo.title,
revision: payload.memo.revision,
- notebookId: known?.notebookId || "",
+ notebookId: known?.notebookId || payload.memo.notebookId || "",
});
return done(payload);
}
diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.ts
index 1c188d31..e8f86cd7 100644
--- a/apps/api/src/companion-prepare.ts
+++ b/apps/api/src/companion-prepare.ts
@@ -49,6 +49,7 @@ When the user refers to this note, 这篇, 当前, or the open note, use the Ope
When the user asks for a mind map, 思维导图, flowchart, 流程图, architecture diagram, or 架构图 of the open note, build it from that body (or get_memo/get_diagram first). To create a new diagram note, call create_diagram_memo. Do not use create_memo, Markdown outlines, or Mermaid. Preserve an explicitly requested type exactly: 思维导图/mind map means kind=mind-map, 流程图/flowchart means kind=flowchart, and 架构图/architecture diagram means kind=architecture. For mind maps, supply a root node and children with parentId; omit node type. If the user did not name a notebook, omit notebookId so it is saved in the inbox notebook (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Reply with the new note link.
When the user asks for an infographic, 信息图, 資訊圖, or インフォグラフィック, call create_infographic_memo. Do not use create_diagram_memo, create_memo, Markdown, or Mermaid for that request. A share, proportion, or 占比 is a pie infographic: template chart-pie-donut-plain-text and numeric data.values, not a mind map. If the user did not supply the figures, say in data.desc that they are illustrative and are not an official disclosure. If the user did not name a notebook, omit notebookId. Reply with the new note link.
When the user asks for a 多维表格, 多維表格, or structured table, call create_table_memo with explicit fields. Do not use create_memo or a Markdown table. If no records were supplied or requested, leave it empty. If records were requested, call get_table_records for the new table's field IDs and revision before add_table_record. Omit notebookId when no notebook was named. Reply with the new note link.
+To change a poster/海报, call get_poster then update_poster. Edit only requested text, colors, typography or positions; preserve other elements and locked elements. Never replace poster content with update_memo.
To change an existing diagram, call get_diagram then update_diagram. Do not create a second diagram unless the user asked for a new note. Do not use update_memo or Mermaid for diagrams.
A structured table cannot be replaced with update_memo. Use get_table_records to read its structure and records. Do not rewrite its Markdown.
You can list, create, update, use, and delete note templates, and list, create, update, and delete AI instructions. use_note_template creates a memo immediately. You cannot empty the trash, share notes, or upload files. Do not claim those tools exist.
diff --git a/apps/api/src/companion-tool-actions.test.mjs b/apps/api/src/companion-tool-actions.test.mjs
index 0fb7e64a..c0b4d8bd 100644
--- a/apps/api/src/companion-tool-actions.test.mjs
+++ b/apps/api/src/companion-tool-actions.test.mjs
@@ -5,7 +5,7 @@ import { Hono } from "hono";
import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";
import { registerCompanionRoutes } from "./companion-routes.ts";
import { beginCompanionTurn, checkpointCompanionTurn, clearCompanionHistory, saveCompanionMemory } from "./companion-service.ts";
-import { createDefaultTableDocument, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeTableDocument } from "@edgeever/shared";
+import { createPosterDocument, serializePosterDocument, parsePosterDocument, createDefaultTableDocument, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeTableDocument } from "@edgeever/shared";
import { createMemoRecord, getMemoDetail, normalizeSearchTimeBound, updateMemoRecord } from "./memo-service.ts";
import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companion-tool-actions.ts";
import { getCompanionAction, applyCompanionAction, dismissCompanionAction } from "./companion-actions.ts";
@@ -49,7 +49,7 @@ async function setup() {
describe("shared companion MCP adapter", () => {
test("reuses the exact reviewed MCP definitions, with no administration or upload tools", () => {
- expect(COMPANION_MCP_TOOLS).toHaveLength(47);
+ expect(COMPANION_MCP_TOOLS).toHaveLength(49);
for (const definition of COMPANION_MCP_TOOLS) expect(MCP_TOOLS.includes(definition)).toBe(true);
for (const name of ["upload_memo_image", "upload_memo_attachment", "empty_trash", "share_memo"]) {
expect(() => validateCompanionTool(name, {})).toThrow();
@@ -115,13 +115,26 @@ describe("shared companion MCP adapter", () => {
test("read and dry-run tools reuse MCP without writing or requiring a proposal", async () => {
const f = await setup();
const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });
- expect(Object.keys(tools)).toHaveLength(49);
+ expect(Object.keys(tools)).toHaveLength(51);
expect(await tools.get_memo.execute({ memoId: f.notes[0].id })).toMatchObject({ content: "One original content" });
expect(await tools.trash_memos.execute({ memoIds: [f.notes[0].id], dryRun: true })).toMatchObject({ dryRun: true });
expect(await getMemoDetail(f.db, scope.workspaceId, f.notes[0].id)).not.toBeNull();
expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);
expect(createCompanionTools({ ...f, scope, input: { ...f.input, allowNotes: false } })).toEqual({});
});
+ test("poster changes use the shared agent execution path with read and revision guards", async () => {
+ const f = await setup();
+ const created = await createMemoRecord(f.db, scope.workspaceId, { notebookId: "ideas", title: "Poster", contentMarkdown: serializePosterDocument(createPosterDocument("Hello")), tags: [] }, actor, "owner");
+ const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });
+ await expect(tools.update_poster.execute({ memoId: created.id, expectedRevision: created.revision, background: "#16A06E" })).rejects.toMatchObject({ code: "companion_action_unread" });
+ await tools.get_memo.execute({ memoId: created.id });
+ const read = await tools.get_poster.execute({ memoId: created.id });
+ expect(read.poster.elements.length).toBeGreaterThan(0);
+ const updated = await tools.update_poster.execute({ memoId: created.id, expectedRevision: read.memo.revision, background: "#16A06E" });
+ expect(updated).toMatchObject({ applied: true, id: created.id });
+ expect(parsePosterDocument((await getMemoDetail(f.db, scope.workspaceId, created.id)).contentMarkdown).background).toBe("#16A06E");
+ expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);
+ });
test("read-only note access keeps MCP reads and omits write tools", async () => {
const f = await setup();
const tools = createCompanionTools({
@@ -134,6 +147,8 @@ describe("shared companion MCP adapter", () => {
expect(tools.create_diagram_memo).toBeUndefined();
expect(tools.update_diagram).toBeUndefined();
expect(tools.get_diagram).toBeTruthy();
+ expect(tools.get_poster).toBeTruthy();
+ expect(tools.update_poster).toBeUndefined();
expect(tools.update_memo).toBeUndefined();
expect(tools.merge_memos).toBeUndefined();
expect(tools.list_note_templates).toBeTruthy();
diff --git a/apps/api/src/companion-tool-actions.ts b/apps/api/src/companion-tool-actions.ts
index 862223a5..96222669 100644
--- a/apps/api/src/companion-tool-actions.ts
+++ b/apps/api/src/companion-tool-actions.ts
@@ -27,7 +27,7 @@ export async function proposeCompanionToolAction(db: DatabaseAdapter, scope: Com
for (const id of new Set([...ids, ...evidenceIds])) {
const memo = await getMemoDetail(db, scope.workspaceId, id, toolName === "restore_memos");
if (!memo) throw stale();
- if ((toolName === "update_memo" || toolName === "merge_memos") && inspected.get(id) !== memo.revision) {
+ if ((toolName === "update_memo" || toolName === "update_poster" || toolName === "merge_memos") && inspected.get(id) !== memo.revision) {
throw new AppError("companion_action_unread", "Read the complete source notes before changing their content or merging them.", 400);
}
notes.push({ id, title: memo.title ?? "", revision: memo.revision, notebookId: memo.notebookId,
diff --git a/apps/api/src/companion-tool-catalog.ts b/apps/api/src/companion-tool-catalog.ts
index 194fe1d4..ef46246a 100644
--- a/apps/api/src/companion-tool-catalog.ts
+++ b/apps/api/src/companion-tool-catalog.ts
@@ -6,7 +6,7 @@ import { AppError } from "./app-error";
// capabilities must be reviewed rather than silently acquiring user authority.
const allowed = new Set([
"get_current_user", "search_memos", "list_memos", "get_memo", "create_memo", "create_table_memo", "get_table_records", "add_table_record", "create_diagram_memo", "create_infographic_memo", "get_diagram",
- "update_diagram",
+ "update_diagram", "get_poster", "update_poster",
"import_memos", "update_memo",
"trash_memos", "restore_memos", "move_memos", "add_tags_to_memos", "remove_tags_from_memos",
"rename_tag", "delete_tag", "merge_memos", "list_memo_resources", "list_resources",
diff --git a/apps/api/src/companion-tool-receipts.ts b/apps/api/src/companion-tool-receipts.ts
index 25aab91e..37fd5aad 100644
--- a/apps/api/src/companion-tool-receipts.ts
+++ b/apps/api/src/companion-tool-receipts.ts
@@ -33,13 +33,13 @@ export function describeCompanionTool(
const memos = Array.isArray(record?.memos) ? record.memos : [];
return memos.slice(0, 5).map(item => effect("listed", asMemo(item)));
}
- if (name === "get_memo" || name === "get_diagram" || name === "get_table_records") {
+ if (name === "get_memo" || name === "get_diagram" || name === "get_poster" || name === "get_table_records") {
return [effect("read", memo ?? { id: String(args.memoId ?? record?.memoId ?? record?.id ?? "") })];
}
if (name === "create_memo" || name === "create_table_memo" || name === "create_diagram_memo" || name === "create_infographic_memo" || name === "use_note_template") {
return [effect("created", memo)];
}
- if (name === "update_memo" || name === "update_diagram" || name === "restore_memo_revision") {
+ if (name === "update_memo" || name === "update_diagram" || name === "update_poster" || name === "restore_memo_revision") {
const id = memo?.id ?? String(args.memoId ?? "");
const before = prior(id);
return [effect("updated", memo ?? { id, title: before?.title }, { previousRevision: before?.revision })];
diff --git a/apps/api/src/database-write-optimizations.test.mjs b/apps/api/src/database-write-optimizations.test.mjs
index 8607a559..8293f240 100644
--- a/apps/api/src/database-write-optimizations.test.mjs
+++ b/apps/api/src/database-write-optimizations.test.mjs
@@ -1,7 +1,7 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { globSync, readFileSync } from "node:fs";
-import { addTableField, createDefaultTableDocument, serializeTableDocument, updateTableCell } from "@edgeever/shared";
+import { createPosterDocument, serializePosterDocument, parsePosterDocument, markdownToDoc, addTableField, createDefaultTableDocument, serializeTableDocument, updateTableCell } from "@edgeever/shared";
import {
acquireMaintenanceLease,
createMemoEditSession,
@@ -211,6 +211,21 @@ describe("database write optimizations", () => {
sqlite.close();
});
+ test("protects new poster source from legacy contentJson edits and stale revisions", async () => {
+ const { database, sqlite } = createDatabase();
+ const memo = getSeedMemo(sqlite), actor = { actorType: "user", actorId: "user_owner" };
+ const first = await updateMemoRecord(database, memo.workspace_id, memo.id, { contentMarkdown: serializePosterDocument(createPosterDocument("Poster")) }, actor, "owner");
+ expect(parsePosterDocument(first.memo.contentMarkdown)).not.toBeNull();
+ const legacy = await updateMemoRecord(database, memo.workspace_id, memo.id, { contentJson: markdownToDoc("legacy editor changed preview") }, actor, "owner");
+ expect(legacy.error).toBe("poster_update_required");
+ const next = await updateMemoRecord(database, memo.workspace_id, memo.id, { expectedRevision: first.memo.revision, expectedContentHash: first.memo.contentHash, contentMarkdown: serializePosterDocument(createPosterDocument("New design")) }, actor, "owner");
+ expect(parsePosterDocument(next.memo.contentMarkdown).elements[1].text).toBe("New design");
+ const stale = await updateMemoRecord(database, memo.workspace_id, memo.id, { expectedRevision: first.memo.revision, expectedContentHash: first.memo.contentHash, contentMarkdown: first.memo.contentMarkdown }, actor, "owner");
+ expect(stale.error).toBeTruthy();
+ expect(parsePosterDocument(sqlite.query("SELECT content_markdown FROM memo_contents WHERE memo_id = ?").get(memo.id).content_markdown).elements[1].text).toBe("New design");
+ sqlite.close();
+ });
+
test("allows only one live maintenance lease owner", async () => {
const { database, sqlite } = createDatabase();
const first = await acquireMaintenanceLease(database, "demo-reset-test", 60_000);
diff --git a/apps/api/src/mcp-management-tools.test.mjs b/apps/api/src/mcp-management-tools.test.mjs
index 201c8276..03b41edc 100644
--- a/apps/api/src/mcp-management-tools.test.mjs
+++ b/apps/api/src/mcp-management-tools.test.mjs
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
import { globSync, readFileSync } from "node:fs";
import { Database } from "bun:sqlite";
import { callMcpTool } from "./index.ts";
-import { addTableField, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeTableDocument, createDefaultTableDocument } from "@edgeever/shared";
+import { createPosterDocument, serializePosterDocument, parsePosterDocument, addTableField, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeTableDocument, createDefaultTableDocument } from "@edgeever/shared";
class SqliteD1PreparedStatement {
constructor(db, sql, bindings = []) {
@@ -72,6 +72,26 @@ const createFixture = (scopes = ["read:memos", "write:memos"]) => {
};
describe("MCP template and AI instruction management", () => {
+ test("poster tools preserve untouched elements, previews, scopes and revision guards", async () => {
+ const { sqlite, auth, context } = createFixture();
+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES (?, ?, ?)").run("nb_posters", "ws_mcp", "Posters");
+ const poster = { ...createPosterDocument("Original"), previewResourceId: "old_preview" };
+ const created = await callMcpTool(context, auth, "create_memo", { notebookId: "nb_posters", title: "Poster", contentMarkdown: serializePosterDocument(poster) });
+ const read = await callMcpTool(context, auth, "get_poster", { memoId: created.memo.id });
+ const heading = read.poster.elements.find(element => element.type === "text");
+ const input = { memoId: created.memo.id, expectedRevision: read.memo.revision, edits: [{ id: heading.id, patch: { text: "Updated", fill: "#16A06E" } }] };
+ const preview = await callMcpTool(context, auth, "update_poster", { ...input, dryRun: true });
+ expect(preview.poster.elements.find(element => element.id === heading.id).text).toBe("Updated");
+ expect((await callMcpTool(context, auth, "get_poster", { memoId: created.memo.id })).poster.previewResourceId).toBe("old_preview");
+ await expect(callMcpTool(context, { ...auth, scopes: ["read:memos"] }, "update_poster", input)).rejects.toThrow();
+ await expect(callMcpTool(context, { ...auth, workspaceId: "ws_other" }, "get_poster", { memoId: created.memo.id })).rejects.toThrow();
+ const result = await callMcpTool(context, auth, "update_poster", input);
+ expect(result.poster.previewResourceId).toBeUndefined();
+ expect(result.poster.elements.filter(element => element.id !== heading.id)).toEqual(read.poster.elements.filter(element => element.id !== heading.id));
+ expect(parsePosterDocument(result.memo.contentMarkdown).elements.find(element => element.id === heading.id).text).toBe("Updated");
+ await expect(callMcpTool(context, auth, "update_poster", input)).rejects.toThrow();
+ await expect(callMcpTool(context, auth, "update_poster", { ...input, expectedRevision: result.memo.revision, edits: [{ id: "missing", patch: { text: "Bad" } }] })).rejects.toThrow();
+ });
test.each([
["mind-map", [
{ id: "root", label: "Root" },
diff --git a/apps/api/src/mcp-poster-tools.test.mjs b/apps/api/src/mcp-poster-tools.test.mjs
new file mode 100644
index 00000000..f3de0d7d
--- /dev/null
+++ b/apps/api/src/mcp-poster-tools.test.mjs
@@ -0,0 +1,26 @@
+import { expect, test } from "bun:test";
+import { createPosterDocument } from "@edgeever/shared";
+import { applyPosterEdits } from "./mcp-poster-tools";
+
+test("poster edits reject locked elements, duplicate IDs, unknown patch keys and invalid geometry", () => {
+ const poster = createPosterDocument("Hello");
+ const element = poster.elements.find(element => element.type === "text");
+ const input = patch => ({ memoId: "memo", expectedRevision: 1, edits: [{ id: element.id, patch }] });
+ expect(() => applyPosterEdits(input({ text: "Bad" }), { ...poster, elements: poster.elements.map(item => item.id === element.id ? { ...item, locked: true } : item) })).toThrow();
+ expect(() => applyPosterEdits({ ...input({ text: "Bad" }), edits: [input({ text: "One" }).edits[0], input({ text: "Two" }).edits[0]] }, poster)).toThrow();
+ expect(() => applyPosterEdits(input({ resourceId: "other" }), poster)).toThrow();
+ expect(() => applyPosterEdits(input({ width: -1 }), poster)).toThrow();
+ expect(() => applyPosterEdits({ memoId: "memo", expectedRevision: 1 }, poster)).toThrow();
+});
+
+test("poster edits update canonical copy, support background changes and retain a preview on no-op", () => {
+ const poster = { ...createPosterDocument("Hello"), previewResourceId: "preview" };
+ const title = poster.elements.find(element => element.type === "text");
+ const changed = applyPosterEdits({ memoId: "memo", expectedRevision: 1, background: "#16A06E", edits: [{ id: title.id, patch: { text: "New heading" } }] }, poster);
+ expect(changed.document.background).toBe("#16A06E");
+ expect(changed.document.elements.find(element => element.id === title.id).sourceText).toBe("New heading");
+ expect(changed.document.previewResourceId).toBeUndefined();
+ const unchanged = applyPosterEdits({ memoId: "memo", expectedRevision: 1, background: poster.background }, poster);
+ expect(unchanged.changed).toBe(false);
+ expect(unchanged.document.previewResourceId).toBe("preview");
+});
diff --git a/apps/api/src/mcp-poster-tools.ts b/apps/api/src/mcp-poster-tools.ts
new file mode 100644
index 00000000..742ca534
--- /dev/null
+++ b/apps/api/src/mcp-poster-tools.ts
@@ -0,0 +1,66 @@
+import { z } from "zod";
+import { PosterDocumentSchema, PosterGradientSchema, type PosterDocument } from "@edgeever/shared";
+import { AppError } from "./app-error";
+
+const patch = z.object({
+ text: z.string().max(8000).optional(),
+ fill: z.string().regex(/^#[0-9a-f]{6}$/i).optional(),
+ fontSize: z.number().finite().min(4).max(8192).optional(),
+ fontWeight: z.enum(["normal", "bold"]).optional(),
+ textAlign: z.enum(["left", "center", "right"]).optional(),
+ x: z.number().finite().min(-8192).max(8192).optional(),
+ y: z.number().finite().min(-8192).max(8192).optional(),
+ width: z.number().finite().min(1).max(8192).optional(),
+ height: z.number().finite().min(1).max(8192).optional(),
+ rotation: z.number().finite().min(-360).max(360).optional(),
+ opacity: z.number().finite().min(0).max(1).optional(),
+}).strict().refine(value => Object.keys(value).length > 0);
+const request = z.object({
+ memoId: z.string().min(1),
+ expectedRevision: z.number().int().nonnegative(),
+ dryRun: z.boolean().optional(),
+ background: z.string().regex(/^#[0-9a-f]{6}$/i).optional(),
+ backgroundGradient: PosterGradientSchema.nullable().optional(),
+ edits: z.array(z.object({ id: z.string().min(1), patch }).strict()).max(100).optional(),
+}).strict().refine(value => Boolean(value.edits?.length || value.background || value.backgroundGradient !== undefined));
+
+export function applyPosterEdits(input: unknown, current: PosterDocument) {
+ const parsed = request.safeParse(input);
+ if (!parsed.success) throw new AppError("invalid_params", "Invalid poster edits", 400);
+ const args = parsed.data;
+ const edits = args.edits ?? [];
+ if (new Set(edits.map(edit => edit.id)).size !== edits.length) throw new AppError("invalid_params", "Duplicate poster element IDs", 400);
+ for (const edit of edits) {
+ const element = current.elements.find(element => element.id === edit.id);
+ if (!element || element.locked) throw new AppError("invalid_params", "Poster element is missing or locked", 400);
+ if (element.type !== "text" && ["text", "fontSize", "fontWeight", "textAlign"].some(key => key in edit.patch)) {
+ throw new AppError("invalid_params", "Typography edits require a text element", 400);
+ }
+ if (element.type === "image" && edit.patch.fill !== undefined) throw new AppError("invalid_params", "Image elements do not have a fill", 400);
+ }
+ const next = PosterDocumentSchema.safeParse({
+ ...current,
+ ...(args.background !== undefined ? { background: args.background } : {}),
+ ...(args.backgroundGradient !== undefined ? { backgroundGradient: args.backgroundGradient ?? undefined } : {}),
+ elements: current.elements.map(element => {
+ const edit = edits.find(edit => edit.id === element.id);
+ if (!edit) return element;
+ return { ...element, ...edit.patch, ...(edit.patch.text !== undefined ? { sourceText: edit.patch.text } : {}) };
+ }),
+ });
+ if (!next.success) throw new AppError("invalid_params", "Poster edits exceed document limits", 400);
+ const document = next.data;
+ if (edits.some(edit => edit.patch.text !== undefined)) {
+ document.copy = {
+ title: current.copy?.title ?? "", subtitle: current.copy?.subtitle ?? "", badge: current.copy?.badge ?? "",
+ };
+ for (const role of ["title", "subtitle", "badge"] as const) {
+ if (!edits.some(edit => edit.patch.text !== undefined && current.elements.some(element => element.id === edit.id && element.role === role))) continue;
+ document.copy[role] = [...new Set(document.elements.filter(element => element.type === "text" && element.role === role)
+ .map(element => element.type === "text" ? element.sourceText ?? element.text : ""))].join("\n");
+ }
+ }
+ const changed = JSON.stringify(document) !== JSON.stringify(PosterDocumentSchema.parse(current));
+ if (changed) document.previewResourceId = undefined;
+ return { document, changed };
+}
diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.ts
index ea242c23..1c98cf0d 100644
--- a/apps/api/src/mcp-tool-service.ts
+++ b/apps/api/src/mcp-tool-service.ts
@@ -1,3 +1,5 @@
+import { applyPosterEdits } from "./mcp-poster-tools";
+import { hasPosterDocumentMarker, parsePosterDocument, serializePosterDocument } from "@edgeever/shared";
import {
AiPromptTemplateCreateSchema,
AiPromptTemplateUpdateSchema,
@@ -508,6 +510,30 @@ export const callMcpTool = async (
diagram: diagramSemanticGraph(document),
};
}
+ case "get_poster": {
+ assertScope(auth, "read:memos");
+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, getRequiredString(args.memoId, "memoId"));
+ if (!memo) throw new AppError("not_found", "Memo not found", 404);
+ const poster = parsePosterDocument(memo.contentMarkdown);
+ if (!poster) throw new AppError("not_poster", "Memo is not an editable poster", 400);
+ return { memo: { id: memo.id, title: memo.title, notebookId: memo.notebookId, revision: memo.revision }, poster };
+ }
+ case "update_poster": {
+ assertScope(auth, "write:memos");
+ const memoId = getRequiredString(args.memoId, "memoId");
+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);
+ if (!memo) throw new AppError("not_found", "Memo not found", 404);
+ if (memo.revision !== args.expectedRevision) throw new AppError("revision_conflict", "Poster changed. Read it again before editing.", 409);
+ const current = parsePosterDocument(memo.contentMarkdown);
+ if (!current) throw new AppError("not_poster", "Memo is not an editable poster", 400);
+ const mutation = applyPosterEdits(args, current);
+ if (args.dryRun === true || !mutation.changed) return { dryRun: args.dryRun === true, memo, poster: mutation.document, changed: mutation.changed };
+ const result = await updateMemoRecord(c.env.storage.db, auth.workspaceId, memoId, {
+ expectedRevision: args.expectedRevision, contentMarkdown: serializePosterDocument(mutation.document),
+ }, getAuditActor(c), getActorLabel(c));
+ if (result.error !== undefined) throw new AppError(result.error, result.message, result.status ?? 400);
+ return { memo: result.memo, poster: mutation.document, changed: true };
+ }
case "get_diagram": {
assertScope(auth, "read:memos");
const memoId = getRequiredString(args.memoId, "memoId");
@@ -585,6 +611,9 @@ export const callMcpTool = async (
400,
);
}
+ if (existing && hasPosterDocumentMarker(existing.contentMarkdown)) {
+ throw new AppError("poster_update_required", "Poster content cannot be replaced through update_memo. Use get_poster then update_poster.", 400);
+ }
if (existing && hasInfographicDocumentMarker(existing.contentMarkdown)) {
throw new AppError(
"infographic_update_required",
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
index d0c6d1ce..59e64397 100644
--- a/apps/api/src/mcp-tools.ts
+++ b/apps/api/src/mcp-tools.ts
@@ -363,6 +363,37 @@ const MCP_TOOL_DEFINITIONS = [
},
},
},
+ {
+ name: "get_poster",
+ description: "Read an editable poster's canvas, element IDs, text, colors and geometry. Read before update_poster; never decode or replace poster Markdown.",
+ inputSchema: { type: "object", required: ["memoId"], additionalProperties: false, properties: { memoId: { type: "string", minLength: 1 } } },
+ },
+ {
+ name: "update_poster",
+ description: "Edit an existing poster's text, colors, typography and element positions. Preserve unmentioned elements and locked elements. Read get_poster first and pass its expectedRevision. Use dryRun to preview. After changes the editor regenerates the preview image.",
+ inputSchema: {
+ type: "object", required: ["memoId", "expectedRevision"], additionalProperties: false,
+ properties: {
+ memoId: { type: "string", minLength: 1 }, expectedRevision: { type: "integer", minimum: 0 }, dryRun: { type: "boolean" },
+ background: { type: "string", pattern: "^#[0-9a-fA-F]{6}$" },
+ backgroundGradient: { type: ["object", "null"], additionalProperties: false, required: ["kind", "from", "to"], properties: {
+ kind: { type: "string", enum: ["linear", "radial"] }, from: { type: "string", pattern: "^#[0-9a-fA-F]{6}$" }, to: { type: "string", pattern: "^#[0-9a-fA-F]{6}$" }, angle: { type: "number", minimum: -360, maximum: 360 },
+ } },
+ edits: { type: "array", maxItems: 100, items: {
+ type: "object", required: ["id", "patch"], additionalProperties: false,
+ properties: { id: { type: "string", minLength: 1 }, patch: {
+ type: "object", additionalProperties: false, properties: {
+ text: { type: "string", maxLength: 8000 }, fill: { type: "string", pattern: "^#[0-9a-fA-F]{6}$" },
+ fontSize: { type: "number", minimum: 4, maximum: 8192 }, fontWeight: { type: "string", enum: ["normal", "bold"] }, textAlign: { type: "string", enum: ["left", "center", "right"] },
+ x: { type: "number", minimum: -8192, maximum: 8192 }, y: { type: "number", minimum: -8192, maximum: 8192 },
+ width: { type: "number", minimum: 1, maximum: 8192 }, height: { type: "number", minimum: 1, maximum: 8192 },
+ rotation: { type: "number", minimum: -360, maximum: 360 }, opacity: { type: "number", minimum: 0, maximum: 1 },
+ },
+ } },
+ } },
+ },
+ },
+ },
{
name: "get_diagram",
description:
@@ -979,6 +1010,7 @@ const READ_ONLY_MCP_TOOLS = new Set([
"get_memo",
"get_table_records",
"get_diagram",
+ "get_poster",
"list_memo_resources",
"list_resources",
"list_memo_revisions",
diff --git a/apps/api/src/memo-list-service.ts b/apps/api/src/memo-list-service.ts
index 761c2ad4..f468d36d 100644
--- a/apps/api/src/memo-list-service.ts
+++ b/apps/api/src/memo-list-service.ts
@@ -5,6 +5,7 @@ import {
markdownToDoc,
getDiagramSummary,
getInfographicSummary,
+ getPosterSummary,
getTableSummary,
type MemoSummary,
} from "@edgeever/shared";
@@ -73,6 +74,7 @@ export const mapMemoSummary = (row: MemoSummaryRow): MemoSummary => ({
createExcerpt(docToText(markdownToDoc(row.content_markdown ?? ""))),
...getDiagramSummary(row.content_markdown),
...getInfographicSummary(row.content_markdown),
+ ...getPosterSummary(row.content_markdown),
...getTableSummary(row.content_markdown),
tags: parseJsonArray(row.tags_json),
isPinned: Boolean(row.is_pinned),
diff --git a/apps/api/src/memo-service.ts b/apps/api/src/memo-service.ts
index 2eea49d5..371c362b 100644
--- a/apps/api/src/memo-service.ts
+++ b/apps/api/src/memo-service.ts
@@ -1,3 +1,4 @@
+import { hasPosterDocumentMarker, parsePosterDocument } from "@edgeever/shared";
import {
createExcerpt,
DEFAULT_MEMO_TITLE,
@@ -1346,6 +1347,12 @@ export const updateMemoRecord = async (
const tags = input.tags === undefined ? parseJsonArray(current.tags_json) : normalizeTags(input.tags);
const excerpt = createExcerpt(contentText);
const notebookId = input.notebookId ?? current.notebook_id;
+ if (hasPosterDocumentMarker(current.content_markdown) && !parsePosterDocument(contentMarkdown)) {
+ return { error: "poster_update_required", message: "Poster source must be edited on a supported client.", status: 409 };
+ }
+ if (hasPosterDocumentMarker(contentMarkdown) && !parsePosterDocument(contentMarkdown)) {
+ return { error: "invalid_poster", message: "Invalid poster source.", status: 400 };
+ }
const currentTable = parseTableDocument(current.content_markdown);
const nextTable = parseTableDocument(contentMarkdown);
if (currentTable && !nextTable) {
diff --git a/apps/ios/EdgeEver/Editor/TipTapContentSource.swift b/apps/ios/EdgeEver/Editor/TipTapContentSource.swift
index b3f3685c..2cc07168 100644
--- a/apps/ios/EdgeEver/Editor/TipTapContentSource.swift
+++ b/apps/ios/EdgeEver/Editor/TipTapContentSource.swift
@@ -32,6 +32,10 @@ enum TipTapContentSource: Sendable {
let stripped = stripStructuredTableMarker(markdown)
return Decision(useJSON: false, payload: stripped, fingerprint: "table:\(stripped)")
}
+ if markdown.contains("<!-- edgeever-poster-v1:") {
+ let stripped = markdown.replacingOccurrences(of: #"<!--\s*edgeever-poster-v1:[\s\S]*?-->"#, with: "", options: .regularExpression).trimmingCharacters(in: .whitespacesAndNewlines)
+ return Decision(useJSON: false, payload: stripped, fingerprint: "poster:\(stripped)")
+ }
if markdown.contains("<!-- edgeever-infographic-v1:") {
let stripped = stripInfographicMarker(markdown)
return Decision(useJSON: false, payload: stripped, fingerprint: "infographic:\(stripped)")
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift
index 0246b6b0..d8ade530 100644
--- a/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift
@@ -959,7 +959,9 @@ struct MemoDetailView: View {
: isVisualDiagram(memo)
? env.preferences.t("图表标题", en: "Diagram title", pl: "Tytuł diagramu")
: env.preferences.t("编辑笔记标题", en: "Edit note title", pl: "Edytuj tytuł notatki"))
- .accessibilityHint(isInfographic(memo)
+ .accessibilityHint(memo.contentMarkdown.contains("<!-- edgeever-poster-v1:")
+ ? env.preferences.t("海报请在 Web 或桌面端编辑", en: "Edit posters on Web or desktop", pl: "Plakaty edytuj w wersji webowej lub desktopowej")
+ : isInfographic(memo)
? env.preferences.t("信息图请在 Web 或桌面端编辑", en: "Edit infographics on Web or desktop", pl: "Infografiki edytuj w wersji webowej lub desktopowej")
: isStructuredTable(memo)
? env.preferences.t("多维表格请在 Web 或桌面端编辑", en: "Edit databases on Web or desktop", pl: "Bazy danych edytuj w wersji webowej lub desktopowej")
@@ -995,7 +997,7 @@ struct MemoDetailView: View {
}
private func blocksRichTextEdit(_ memo: MemoDetail) -> Bool {
- isVisualDiagram(memo) || isStructuredTable(memo) || isInfographic(memo)
+ isVisualDiagram(memo) || isStructuredTable(memo) || isInfographic(memo) || memo.contentMarkdown.contains("<!-- edgeever-poster-v1:")
}
private func refreshSyncStatus() {
diff --git a/apps/ios/Tests/EdgeEverTests/TipTapContentSourceTests.swift b/apps/ios/Tests/EdgeEverTests/TipTapContentSourceTests.swift
index aef21b50..fbc8c68c 100644
--- a/apps/ios/Tests/EdgeEverTests/TipTapContentSourceTests.swift
+++ b/apps/ios/Tests/EdgeEverTests/TipTapContentSourceTests.swift
@@ -37,6 +37,14 @@ final class TipTapContentSourceTests: XCTestCase {
XCTAssertTrue(decision.payload.contains("infographic list-row-simple-horizontal-arrow"))
}
+ func testPosterViewerKeepsPreviewAndStripsSource() {
+ let markdown = "![Poster](/api/v1/resources/res_preview/blob)\n\n<!-- edgeever-poster-v1:abc -->"
+ let decision = TipTapContentSource.resolve(mode: .viewer, documentJSON: "{}", markdown: markdown)
+ XCTAssertFalse(decision.useJSON)
+ XCTAssertTrue(decision.payload.contains("res_preview/blob"))
+ XCTAssertFalse(decision.payload.contains("edgeever-poster-v1"))
+ }
+
func testEditorMarkdownRemainsAuthoritativeForRichStructures() {
let markdown = """
1. first
diff --git a/apps/mobile/src/lib/mobile-diagram.test.ts b/apps/mobile/src/lib/mobile-diagram.test.ts
index b530f734..171be1fa 100644
--- a/apps/mobile/src/lib/mobile-diagram.test.ts
+++ b/apps/mobile/src/lib/mobile-diagram.test.ts
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import { describe, expect, test } from "bun:test";
-import { createDefaultDiagramDocument, createDefaultTableDocument, diagramFallbackMarkdown, serializeDiagramDocument, serializeInfographicDocument, serializeTableDocument, tableFallbackMarkdown } from "@edgeever/shared";
-import { getMobileVisualDiagramKind, hasMobileInfographic, hasMobileStructuredTable, hasMobileVisualDiagram, resolveMobileMemoViewerContent } from "./mobile-diagram";
+import { createPosterDocument, serializePosterDocument, createDefaultDiagramDocument, createDefaultTableDocument, diagramFallbackMarkdown, serializeDiagramDocument, serializeInfographicDocument, serializeTableDocument, tableFallbackMarkdown } from "@edgeever/shared";
+import { hasMobilePoster, getMobileVisualDiagramKind, hasMobileInfographic, hasMobileStructuredTable, hasMobileVisualDiagram, resolveMobileMemoViewerContent } from "./mobile-diagram";
const hasMermaidCodeBlock = (doc: { content?: Array<{ type?: string; attrs?: { language?: string } }> }) =>
Boolean(doc.content?.some((node) => node.type === "codeBlock" && node.attrs?.language === "mermaid"));
@@ -47,6 +47,15 @@ describe("mobile visual diagram viewer", () => {
expect(JSON.stringify(resolveMobileMemoViewerContent(null, broken))).not.toContain("edgeever-table-v1");
});
+ test("shows a poster preview and keeps editable source out of the native reader", () => {
+ const markdown = serializePosterDocument({ ...createPosterDocument("Poster"), previewResourceId: "res_preview" });
+ expect(hasMobilePoster(markdown)).toBe(true);
+ const doc = resolveMobileMemoViewerContent(null, markdown);
+ expect(JSON.stringify(doc)).toContain("res_preview/blob");
+ expect(JSON.stringify(doc)).not.toContain("edgeever-poster-v1");
+ expect(hasMobilePoster("text\n<!-- edgeever-poster-v1:broken -->")).toBe(true);
+ });
+
test("shows infographic syntax without exposing its marker to the native viewer", () => {
const markdown = serializeInfographicDocument({ schemaVersion: 1, syntax: "infographic list-row-simple-horizontal-arrow\ndata\n title Test" });
expect(hasMobileInfographic(markdown)).toBe(true);
diff --git a/apps/mobile/src/lib/mobile-diagram.ts b/apps/mobile/src/lib/mobile-diagram.ts
index 4bb877a4..9e0e0efd 100644
--- a/apps/mobile/src/lib/mobile-diagram.ts
+++ b/apps/mobile/src/lib/mobile-diagram.ts
@@ -1,6 +1,8 @@
import {
hasDiagramDocumentMarker,
hasInfographicDocumentMarker,
+ hasPosterDocumentMarker,
+ stripPosterDocumentMarker,
hasTableDocumentMarker,
markdownToDoc,
parseDiagramDocument,
@@ -27,11 +29,14 @@ export const hasMobileStructuredTable = (contentMarkdown: string) =>
export const hasMobileInfographic = (contentMarkdown: string) =>
hasInfographicDocumentMarker(contentMarkdown);
+export const hasMobilePoster = (contentMarkdown: string) => hasPosterDocumentMarker(contentMarkdown);
+
/** Viewer TipTap payload for a visual-diagram envelope. Valid IR is drawn by read-only X6, so this returns an empty doc instead of a hidden Mermaid projection. Invalid envelopes keep the stripped Mermaid fence as degraded content. */
export const resolveMobileMemoViewerContent = (
contentJson: TiptapDoc | null | undefined,
contentMarkdown: string,
) => {
+ if (hasPosterDocumentMarker(contentMarkdown)) return markdownToDoc(stripPosterDocumentMarker(contentMarkdown));
if (parseDiagramDocument(contentMarkdown)) {
return { type: "doc", content: [{ type: "paragraph" }] } satisfies TiptapDoc;
}
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index fef9c33a..8b5f25d8 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -21,7 +21,7 @@ import { MobileAiAssistantModal } from "../components/MobileAiAssistantModal";
import { MobileResourceActions } from "../components/MobileResourceActions";
import { SAFE_DOM_WEBVIEW_PROPS } from "../lib/mobile-dom";
import { getNextMobileNoteSearchIndex } from "../lib/mobile-note-search";
-import { hasMobileInfographic, hasMobileStructuredTable, hasMobileVisualDiagram, resolveMobileMemoViewerContent } from "../lib/mobile-diagram";
+import { hasMobilePoster, hasMobileInfographic, hasMobileStructuredTable, hasMobileVisualDiagram, resolveMobileMemoViewerContent } from "../lib/mobile-diagram";
import { safeDomCall } from "../lib/safe-dom-call";
import {
getMobileImageTarget,
@@ -555,7 +555,7 @@ export const MemoDetailModal = ({
() => (memo ? hasMobileStructuredTable(memo.contentMarkdown) : false),
[memo]
);
- const locksRichTextEdit = isVisualDiagram || isStructuredTable || Boolean(memo && hasMobileInfographic(memo.contentMarkdown));
+ const locksRichTextEdit = isVisualDiagram || isStructuredTable || Boolean(memo && (hasMobileInfographic(memo.contentMarkdown) || hasMobilePoster(memo.contentMarkdown)));
const visualDiagramJson = useMemo(() => {
const diagram = memo ? parseDiagramDocument(memo.contentMarkdown) : null;
return diagram ? JSON.stringify(diagram) : undefined;
diff --git a/apps/web/package.json b/apps/web/package.json
index cdb0ca01..f2afcf01 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -28,6 +28,7 @@
"ai": "7.0.58",
"beautiful-mermaid": "^1.1.3",
"docx-preview": "0.4.1",
+ "fabric": "7.4.0",
"highlight.js": "^11.11.1",
"html-to-image": "^1.11.13",
"lowlight": "^3.3.0",
diff --git a/apps/web/public/poster-fonts/anton.woff2 b/apps/web/public/poster-fonts/anton.woff2
new file mode 100644
index 00000000..2d79727e
Binary files /dev/null and b/apps/web/public/poster-fonts/anton.woff2 differ
diff --git a/apps/web/public/poster-fonts/bebas.woff2 b/apps/web/public/poster-fonts/bebas.woff2
new file mode 100644
index 00000000..ede33a9b
Binary files /dev/null and b/apps/web/public/poster-fonts/bebas.woff2 differ
diff --git a/apps/web/public/poster-fonts/dmserif.woff2 b/apps/web/public/poster-fonts/dmserif.woff2
new file mode 100644
index 00000000..7d6d23cb
Binary files /dev/null and b/apps/web/public/poster-fonts/dmserif.woff2 differ
diff --git a/apps/web/public/poster-fonts/douyin.ttf b/apps/web/public/poster-fonts/douyin.ttf
new file mode 100644
index 00000000..eb8555c6
Binary files /dev/null and b/apps/web/public/poster-fonts/douyin.ttf differ
diff --git a/apps/web/public/poster-fonts/glow.woff2 b/apps/web/public/poster-fonts/glow.woff2
new file mode 100644
index 00000000..5e83e289
Binary files /dev/null and b/apps/web/public/poster-fonts/glow.woff2 differ
diff --git a/apps/web/public/poster-fonts/huangyou.woff2 b/apps/web/public/poster-fonts/huangyou.woff2
new file mode 100644
index 00000000..fbba0fbe
Binary files /dev/null and b/apps/web/public/poster-fonts/huangyou.woff2 differ
diff --git a/apps/web/public/poster-fonts/inter.woff2 b/apps/web/public/poster-fonts/inter.woff2
new file mode 100644
index 00000000..f92bdd38
Binary files /dev/null and b/apps/web/public/poster-fonts/inter.woff2 differ
diff --git a/apps/web/public/poster-fonts/jetbrains.woff2 b/apps/web/public/poster-fonts/jetbrains.woff2
new file mode 100644
index 00000000..b7a7ef5d
Binary files /dev/null and b/apps/web/public/poster-fonts/jetbrains.woff2 differ
diff --git a/apps/web/public/poster-fonts/jiangcheng.woff2 b/apps/web/public/poster-fonts/jiangcheng.woff2
new file mode 100644
index 00000000..2ab52100
Binary files /dev/null and b/apps/web/public/poster-fonts/jiangcheng.woff2 differ
diff --git a/apps/web/public/poster-fonts/kuaile.woff2 b/apps/web/public/poster-fonts/kuaile.woff2
new file mode 100644
index 00000000..5e1c65e0
Binary files /dev/null and b/apps/web/public/poster-fonts/kuaile.woff2 differ
diff --git a/apps/web/public/poster-fonts/licenses/anton.txt b/apps/web/public/poster-fonts/licenses/anton.txt
new file mode 100644
index 00000000..979f0b64
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/anton.txt
@@ -0,0 +1,33 @@
+Anton (Anton)
+Source: https://fonts.google.com/specimen/Anton
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2020 The Anton Project Authors (https://github.com/googlefonts/AntonFont.git)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/bebas.txt b/apps/web/public/poster-fonts/licenses/bebas.txt
new file mode 100644
index 00000000..95b2a7e5
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/bebas.txt
@@ -0,0 +1,33 @@
+Bebas Neue (Bebas Neue)
+Source: https://fonts.google.com/specimen/Bebas+Neue
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2019 The Bebas Neue Project Authors (https://github.com/dharmatype/Bebas-Neue)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/dmserif.txt b/apps/web/public/poster-fonts/licenses/dmserif.txt
new file mode 100644
index 00000000..896a8104
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/dmserif.txt
@@ -0,0 +1,33 @@
+DM Serif Display (DM Serif Display)
+Source: https://fonts.google.com/specimen/DM+Serif+Display
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2014 - 2017 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. Copyright 2019 Google LLC.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/douyin.txt b/apps/web/public/poster-fonts/licenses/douyin.txt
new file mode 100644
index 00000000..dd45a686
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/douyin.txt
@@ -0,0 +1,34 @@
+抖音美好体 (Douyin Sans)
+Source: https://github.com/bytedance/fonts
+This copy: unmodified original
+
+Copyright (c) , 2023 Beijing Zitiao Network Technology Co. Ltd.
+with Reserved Font Names "Douyin", "抖音", "抖音美好".
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/glow.txt b/apps/web/public/poster-fonts/licenses/glow.txt
new file mode 100644
index 00000000..8d9113bd
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/glow.txt
@@ -0,0 +1,33 @@
+未来荧黑 (Glow Sans SC Heavy)
+Source: https://github.com/welai/glow-sans
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Glow Sans (c) 2021 Project Welai
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/huangyou.txt b/apps/web/public/poster-fonts/licenses/huangyou.txt
new file mode 100644
index 00000000..5e138d4a
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/huangyou.txt
@@ -0,0 +1,33 @@
+站酷庆科黄油体 (ZCOOL QingKe HuangYou)
+Source: https://fonts.google.com/specimen/ZCOOL+QingKe+HuangYou
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2018 The ZCOOL QingKe HuangYou Project Authors (https://www.github.com/googlefonts/zcool-qingke-huangyou)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/inter.txt b/apps/web/public/poster-fonts/licenses/inter.txt
new file mode 100644
index 00000000..d47c7b2a
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/inter.txt
@@ -0,0 +1,33 @@
+Inter (Inter)
+Source: https://fonts.google.com/specimen/Inter
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/jetbrains.txt b/apps/web/public/poster-fonts/licenses/jetbrains.txt
new file mode 100644
index 00000000..d9affa6d
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/jetbrains.txt
@@ -0,0 +1,33 @@
+JetBrains Mono (JetBrains Mono)
+Source: https://fonts.google.com/specimen/JetBrains+Mono
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/jiangcheng.txt b/apps/web/public/poster-fonts/licenses/jiangcheng.txt
new file mode 100644
index 00000000..532d05f8
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/jiangcheng.txt
@@ -0,0 +1,33 @@
+江城圆体 (JiangCheng YuanTi)
+Source: https://www.npmjs.com/package/@fontpkg/jiang-cheng-yuan-ti
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+JiangCheng YuanTi
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/kuaile.txt b/apps/web/public/poster-fonts/licenses/kuaile.txt
new file mode 100644
index 00000000..3bb9bfc5
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/kuaile.txt
@@ -0,0 +1,33 @@
+站酷快乐体 (ZCOOL KuaiLe)
+Source: https://fonts.google.com/specimen/ZCOOL+KuaiLe
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2018 The ZCOOL KuaiLe Project Authors (https://github.com/googlefonts/zcool-kuaile)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/mashan.txt b/apps/web/public/poster-fonts/licenses/mashan.txt
new file mode 100644
index 00000000..7853fccf
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/mashan.txt
@@ -0,0 +1,33 @@
+马善政楷书 (Ma Shan Zheng)
+Source: https://fonts.google.com/specimen/Ma+Shan+Zheng
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2018 The MaShanZheng Project Authors (https://github.com/googlefonts/mashanzheng)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/notosans-heavy.txt b/apps/web/public/poster-fonts/licenses/notosans-heavy.txt
new file mode 100644
index 00000000..e39cb8f7
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/notosans-heavy.txt
@@ -0,0 +1,33 @@
+思源黑体 Heavy (Noto Sans SC Black)
+Source: https://fonts.google.com/noto/specimen/Noto+Sans+SC
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+(c) 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/notosans.txt b/apps/web/public/poster-fonts/licenses/notosans.txt
new file mode 100644
index 00000000..3bf91bbb
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/notosans.txt
@@ -0,0 +1,33 @@
+思源黑体 (Noto Sans SC)
+Source: https://fonts.google.com/noto/specimen/Noto+Sans+SC
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+(c) 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/notoserif-heavy.txt b/apps/web/public/poster-fonts/licenses/notoserif-heavy.txt
new file mode 100644
index 00000000..70bc0a39
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/notoserif-heavy.txt
@@ -0,0 +1,33 @@
+思源宋体 Heavy (Noto Serif SC Black)
+Source: https://fonts.google.com/noto/specimen/Noto+Serif+SC
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+(c) 2017-2024 Adobe (http://www.adobe.com/).
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/notoserif.txt b/apps/web/public/poster-fonts/licenses/notoserif.txt
new file mode 100644
index 00000000..921d5cc0
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/notoserif.txt
@@ -0,0 +1,33 @@
+思源宋体 (Noto Serif SC)
+Source: https://fonts.google.com/noto/specimen/Noto+Serif+SC
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+(c) 2017-2024 Adobe (http://www.adobe.com/).
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/smiley.txt b/apps/web/public/poster-fonts/licenses/smiley.txt
new file mode 100644
index 00000000..3519e256
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/smiley.txt
@@ -0,0 +1,33 @@
+得意黑 (Smiley Sans)
+Source: https://github.com/atelier-anchor/smiley-sans
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright © 2022–2024 atelierAnchor. All rights reserved.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/spacegrotesk.txt b/apps/web/public/poster-fonts/licenses/spacegrotesk.txt
new file mode 100644
index 00000000..30821da7
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/spacegrotesk.txt
@@ -0,0 +1,33 @@
+Space Grotesk (Space Grotesk)
+Source: https://fonts.google.com/specimen/Space+Grotesk
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2020 The Space Grotesk Project Authors (https://github.com/floriankarsten/space-grotesk)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/wenkai.txt b/apps/web/public/poster-fonts/licenses/wenkai.txt
new file mode 100644
index 00000000..ff332015
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/wenkai.txt
@@ -0,0 +1,34 @@
+霞鹜文楷 (LXGW WenKai)
+Source: https://github.com/lxgw/LxgwWenKai
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2021-2025 LXGW (https://github.com/lxgw/LxgwWenKai)
+Copyright 2020 The Klee Project Authors (https://github.com/fontworks-fonts/Klee)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/licenses/zhuque.txt b/apps/web/public/poster-fonts/licenses/zhuque.txt
new file mode 100644
index 00000000..7b2c0539
--- /dev/null
+++ b/apps/web/public/poster-fonts/licenses/zhuque.txt
@@ -0,0 +1,33 @@
+朱雀仿宋 (Zhuque Fangsong)
+Source: https://github.com/TrionesType/zhuque
+This copy: subset and converted to WOFF2 by Qiaomu Cover Design
+
+Copyright 2023 JadeFoci
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at: https://openfontlicense.org
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
+The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
+"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
+"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
+"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
+"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
+- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
+- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
+- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
+- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
+- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/web/public/poster-fonts/mashan.woff2 b/apps/web/public/poster-fonts/mashan.woff2
new file mode 100644
index 00000000..eea17c61
Binary files /dev/null and b/apps/web/public/poster-fonts/mashan.woff2 differ
diff --git a/apps/web/public/poster-fonts/notosans-heavy.woff2 b/apps/web/public/poster-fonts/notosans-heavy.woff2
new file mode 100644
index 00000000..31aba365
Binary files /dev/null and b/apps/web/public/poster-fonts/notosans-heavy.woff2 differ
diff --git a/apps/web/public/poster-fonts/notosans.woff2 b/apps/web/public/poster-fonts/notosans.woff2
new file mode 100644
index 00000000..0ade561d
Binary files /dev/null and b/apps/web/public/poster-fonts/notosans.woff2 differ
diff --git a/apps/web/public/poster-fonts/notoserif-heavy.woff2 b/apps/web/public/poster-fonts/notoserif-heavy.woff2
new file mode 100644
index 00000000..02884bcd
Binary files /dev/null and b/apps/web/public/poster-fonts/notoserif-heavy.woff2 differ
diff --git a/apps/web/public/poster-fonts/notoserif.woff2 b/apps/web/public/poster-fonts/notoserif.woff2
new file mode 100644
index 00000000..71bd02db
Binary files /dev/null and b/apps/web/public/poster-fonts/notoserif.woff2 differ
diff --git a/apps/web/public/poster-fonts/smiley.woff2 b/apps/web/public/poster-fonts/smiley.woff2
new file mode 100644
index 00000000..536cf6f0
Binary files /dev/null and b/apps/web/public/poster-fonts/smiley.woff2 differ
diff --git a/apps/web/public/poster-fonts/spacegrotesk.woff2 b/apps/web/public/poster-fonts/spacegrotesk.woff2
new file mode 100644
index 00000000..fbacab1e
Binary files /dev/null and b/apps/web/public/poster-fonts/spacegrotesk.woff2 differ
diff --git a/apps/web/public/poster-fonts/wenkai.woff2 b/apps/web/public/poster-fonts/wenkai.woff2
new file mode 100644
index 00000000..59231f42
Binary files /dev/null and b/apps/web/public/poster-fonts/wenkai.woff2 differ
diff --git a/apps/web/public/poster-fonts/zhuque.woff2 b/apps/web/public/poster-fonts/zhuque.woff2
new file mode 100644
index 00000000..34a1e586
Binary files /dev/null and b/apps/web/public/poster-fonts/zhuque.woff2 differ
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index af948bfe..202bcd42 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -316,6 +316,7 @@ import {
} from "./editor/editor-pane-helpers";
type EditorPaneProps = {
+ onCreatePoster?: (memo: MemoDetail, text: string) => Promise<void>;
memo: MemoDetail | null;
repository: EdgeEverRepository;
desktopFocusMode: boolean;
@@ -416,6 +417,7 @@ const RichEditorPane = ({
onRestored,
onMobileDefaultEditConsumed,
onSaveAsTemplate,
+ onCreatePoster,
searchFocusToken,
replaceFocusToken,
aiAssistantOpenToken,
@@ -4112,6 +4114,11 @@ const RichEditorPane = ({
onSearch={() => openNoteSearch()}
textNoteMenuItems={(
<>
+ {onCreatePoster && !effectiveReadOnly && <DropdownMenuItem disabled={!memo || saveMutation.isPending} onSelect={() => {
+ const selection = editor?.state.selection;
+ const text = selection && !selection.empty ? editor?.state.doc.textBetween(selection.from, selection.to, "\n") ?? "" : editor?.getText() ?? memo?.contentText ?? "";
+ void (async () => { if (!memo) return; if (hasUnsavedChangesRef.current) await saveMutation.mutateAsync(); await onCreatePoster(memoRef.current ?? memo, text); })().catch((error) => setSaveState("error"));
+ }}>{t("poster.createFromNote")}</DropdownMenuItem>}
{!isMobileViewport && !useMobilePlainTextEditor && !useMarkdownSourceEditor && (
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
diff --git a/apps/web/src/components/MemoCard.tsx b/apps/web/src/components/MemoCard.tsx
index 866bc337..4e55c138 100644
--- a/apps/web/src/components/MemoCard.tsx
+++ b/apps/web/src/components/MemoCard.tsx
@@ -1,6 +1,6 @@
import { useRef, useState, useEffect, type DragEvent, type MouseEvent, type PointerEvent as ReactPointerEvent, type KeyboardEvent as ReactKeyboardEvent } from "react";
import { useTranslation } from "react-i18next";
-import { Component, GitFork, PieChart, Table2, Workflow, Star, Check, MoreHorizontal, RotateCcw, Trash2 } from "lucide-react";
+import { FileText, Component, GitFork, PieChart, Table2, Workflow, Star, Check, MoreHorizontal, RotateCcw, Trash2 } from "lucide-react";
import { getMemoListTimestamp, type MemoSummary } from "@edgeever/shared";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
@@ -414,6 +414,8 @@ export const MemoCard = ({
<div className="line-clamp-2 text-xs leading-relaxed text-slate-600">{memo.diagramPreview.labels.join(" · ")}</div>
) : null}
</div>
+ ) : memo.poster ? (
+ <div className="flex items-center gap-1.5 text-xs text-slate-500"><FileText className="h-3.5 w-3.5" aria-hidden="true" /><span>{t("poster.name")}</span></div>
) : memo.infographic ? (
<div className="flex items-center text-xs text-slate-500">
<PieChart className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
diff --git a/apps/web/src/components/MemoEditorHeaderActions.tsx b/apps/web/src/components/MemoEditorHeaderActions.tsx
index ce3750ec..c26a4605 100644
--- a/apps/web/src/components/MemoEditorHeaderActions.tsx
+++ b/apps/web/src/components/MemoEditorHeaderActions.tsx
@@ -10,6 +10,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { IconTooltip } from "@/components/editor/EditorPaneChrome";
import { cn } from "@/lib/utils";
export const MemoEditorHeaderActions = ({
@@ -43,17 +44,16 @@ export const MemoEditorHeaderActions = ({
/>
<ExecutionCenterButton className="h-8 w-8" onClick={onOpenExecutionCenter} />
<DropdownMenu>
- <DropdownMenuTrigger asChild>
+ <IconTooltip label={t("editor.more")}><DropdownMenuTrigger asChild>
<Button
className={moreButtonClassName}
size="icon"
variant="ghost"
- title={t("editor.more")}
aria-label={t("editor.moreAria")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
- </DropdownMenuTrigger>
+ </DropdownMenuTrigger></IconTooltip>
<DropdownMenuContent
align="end"
className={cn("border border-slate-200 bg-card py-1 shadow-md", moreMenuClassName)}
diff --git a/apps/web/src/components/MemoListPane.tsx b/apps/web/src/components/MemoListPane.tsx
index ccaa8fa3..e9ba87fe 100644
--- a/apps/web/src/components/MemoListPane.tsx
+++ b/apps/web/src/components/MemoListPane.tsx
@@ -673,7 +673,7 @@ export const MemoListPane = ({
const handleCopyContextMemoToWeChat = async () => {
const memo = memoContextMenu?.memo;
- if (!memo || memo.diagramKind || memo.structuredTable || memo.infographic || wechatCopyPendingRef.current) return;
+ if (!memo || memo.diagramKind || memo.structuredTable || memo.infographic || memo.poster || wechatCopyPendingRef.current) return;
setMemoContextMenu(null);
wechatCopyPendingRef.current = true;
if (wechatCopyNoticeTimerRef.current !== null) {
@@ -1674,7 +1674,7 @@ export const MemoListPane = ({
<Share2 className="h-4 w-4 text-slate-500" />
{t(isLocalMemoId(memoContextMenu.memo.id) ? "sharing.afterSync" : "sharing.action")}
</DropdownMenuItem>
- {!memoContextMenu.memo.diagramKind && !memoContextMenu.memo.structuredTable && !memoContextMenu.memo.infographic && (
+ {!memoContextMenu.memo.diagramKind && !memoContextMenu.memo.structuredTable && !memoContextMenu.memo.infographic && !memoContextMenu.memo.poster && (
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
onClick={() => void handleCopyContextMemoToWeChat()}
diff --git a/apps/web/src/components/NotebookPane.tsx b/apps/web/src/components/NotebookPane.tsx
index c7c6a78f..ce0a2f28 100644
--- a/apps/web/src/components/NotebookPane.tsx
+++ b/apps/web/src/components/NotebookPane.tsx
@@ -346,6 +346,11 @@ const CreateMemoTypeItems = ({ onCreateMemo }: { onCreateMemo: (kind?: NoteCreat
<span className="min-w-0 flex-1 truncate">{t("infographic.name")}</span>
<span className={BETA_BADGE_CLASSNAME}>Beta</span>
</DropdownMenuItem>
+ <DropdownMenuItem className="gap-2 text-xs leading-5" onSelect={() => onCreateMemo("poster")}>
+ <FileText className="h-4 w-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">{t("poster.name")}</span>
+ <span className={BETA_BADGE_CLASSNAME}>Beta</span>
+ </DropdownMenuItem>
<DropdownMenuItem className="gap-2 text-xs leading-5" onSelect={() => onCreateMemo("table")}>
<Table2 className="h-4 w-4 shrink-0" />
<span className="min-w-0 flex-1 truncate">{t("structuredTable.name")}</span>
diff --git a/apps/web/src/components/PosterEditorPane.tsx b/apps/web/src/components/PosterEditorPane.tsx
new file mode 100644
index 00000000..0c6ac060
--- /dev/null
+++ b/apps/web/src/components/PosterEditorPane.tsx
@@ -0,0 +1,2133 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ ArrowLeft,
+ ChevronDown,
+ Copy,
+ Download,
+ Grid3X3,
+ Hand,
+ ImagePlus,
+ LoaderCircle,
+ Maximize2,
+ MousePointer2,
+ PanelLeftClose,
+ PanelRightClose,
+ Pencil,
+ RectangleHorizontal,
+ Redo2,
+ Save,
+ ScanLine,
+ Shapes,
+ Sparkles,
+ Type,
+ Undo2,
+} from "lucide-react";
+import { PencilBrush, Textbox, type FabricObject } from "fabric";
+import {
+ parsePosterDocument,
+ posterFallbackMarkdown,
+ PosterDocumentSchema,
+ createPosterDocument,
+ resizePosterDocument,
+ type MemoDetail,
+ type MemoEditSession,
+ type Notebook,
+ type PosterDocument,
+ type PosterElement,
+} from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuTrigger,
+} from "@/components/ui/context-menu";
+import { api } from "@/lib/api";
+import type { EdgeEverRepository } from "@/lib/repository";
+import {
+ Canvas,
+ ActiveSelection,
+ makePosterGradient,
+ posterObject,
+ posterElementFromObject,
+ renderPosterBlob,
+} from "@/lib/poster-canvas";
+import {
+ buildPosterDesign,
+ PLATFORMS,
+ posterCopy,
+ posterPrimitiveFromObject,
+ platformFor,
+} from "@/lib/poster-design/templates";
+import { savePosterMemo } from "@/lib/poster-save";
+import { copyImageBlobToClipboard } from "@/lib/clipboard";
+import { compressImageForUpload } from "@/lib/image-compression";
+import {
+ createLocalEditSession,
+ requiresLocalEditSession,
+} from "./editor/editor-pane-helpers";
+import { downloadBlob } from "@/lib/infographic-image-export";
+import { PosterTool } from "./poster/PosterControls";
+import { PosterTemplatePanel } from "./poster/PosterTemplatePanel";
+import { PosterInspector, type PosterAlign } from "./poster/PosterInspector";
+import { PosterCanvasSettings } from "./poster/PosterCanvasSettings";
+import { PosterLayers } from "./poster/PosterLayers";
+import { PosterAssetsPanel } from "./poster/PosterAssetsPanel";
+import { z } from "zod";
+import { MemoEditorHeaderActions } from "./MemoEditorHeaderActions";
+import { MemoEditorMetadataRow } from "./MemoEditorMetadataRow";
+import { MemoEditorFocusModeButton, MemoEditorTopRowLeading } from "./MemoEditorTopRowLeading";
+import { MEMO_EDITOR_TOP_ROW_CLASS_NAME, MEMO_EDITOR_METADATA_ROW_CLASS_NAME } from "./MemoEditorChromeDensity";
+import { MemoTitleInput } from "./MemoTitleInput";
+import { IconTooltip } from "./editor/EditorPaneChrome";
+import { AiSidebar, readAiSidebarOpen, writeAiSidebarOpen } from "./ai-sidebar/AiSidebar";
+import { AiSidebarErrorBoundary } from "./ai-sidebar/AiSidebarErrorBoundary";
+import { getNotebookMoveOptions } from "@/lib/app-helpers";
+import { parseTagsText } from "@/lib/utils";
+
+const artwork = (document: PosterDocument) =>
+ JSON.stringify({ ...document, previewResourceId: undefined });
+const snapshot = (title: string, document: PosterDocument) =>
+ JSON.stringify([title, artwork(document)]);
+type Props = {
+ memo: MemoDetail;
+ repository: EdgeEverRepository;
+ readOnly: boolean;
+ companionAvailable?: boolean;
+ beforeCompanionApply?: () => Promise<void>;
+ onCompanionNotesChanged?: () => Promise<void>;
+ onSaved: (memo: MemoDetail) => Promise<void>;
+ onBackToList: () => void;
+ onOpenCompanionNote?: (id: string, notebookId: string) => void;
+ notebooks?: Notebook[];
+ desktopFocusMode?: boolean;
+ onOpenExecutionCenter?: () => void;
+ onToggleDesktopFocusMode?: () => void;
+ aiAssistantOpenToken?: number;
+ shortcutSettings?: unknown;
+};
+export default function PosterEditorPane({
+ memo,
+ repository,
+ readOnly,
+ onSaved,
+ onBackToList,
+ onOpenCompanionNote,
+ notebooks = [], desktopFocusMode = false, onToggleDesktopFocusMode,
+ onOpenExecutionCenter, aiAssistantOpenToken,
+ companionAvailable = false, beforeCompanionApply, onCompanionNotesChanged,
+}: Props) {
+ const { t, i18n } = useTranslation();
+ const zh = i18n.language.startsWith("zh");
+ const initial = useMemo(
+ () => parsePosterDocument(memo.contentMarkdown),
+ [memo.contentMarkdown],
+ );
+ const [document, setDocument] = useState<PosterDocument>(
+ initial ?? createPosterDocument(),
+ );
+ const [aiAssistantOpen, setAiAssistantOpen] = useState(readAiSidebarOpen);
+ const setAiSidebarOpen = useCallback((open: boolean) => {
+ setAiAssistantOpen(open);
+ writeAiSidebarOpen(open);
+ }, []);
+ const handledAiToken = useRef(aiAssistantOpenToken);
+ useEffect(() => {
+ if (handledAiToken.current === aiAssistantOpenToken) return;
+ handledAiToken.current = aiAssistantOpenToken;
+ if (!readOnly) setAiSidebarOpen(true);
+ }, [aiAssistantOpenToken, readOnly, setAiSidebarOpen]);
+ const notebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
+ const [mobileNotebookPickerOpen, setMobileNotebookPickerOpen] = useState(false);
+ const [notebookUpdatePending, setNotebookUpdatePending] = useState(false);
+ const [tagsText, setTagsText] = useState(memo.tags.join(", "));
+ const [savedTags, setSavedTags] = useState(memo.tags.join(", "));
+ const [title, setTitle] = useState(memo.title ?? "");
+ const [saved, setSaved] = useState(
+ initial?.previewResourceId ? snapshot(memo.title ?? "", document) : "",
+ );
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const [busy, setBusy] = useState(false),
+ [canvasReady, setCanvasReady] = useState(false),
+ [canvasRevision, setCanvasRevision] = useState(0),
+ [saving, setSaving] = useState(false),
+ [ready, setReady] = useState(false);
+ const [error, setError] = useState<string | null>(
+ initial ? null : t("poster.invalid"),
+ );
+ const [leftTab, setLeftTab] = useState<"templates" | "assets">(
+ "templates",
+ ),
+ [rightTab, setRightTab] = useState<"properties" | "layers" | "canvas">(
+ "canvas",
+ );
+ const [leftOpen, setLeftOpen] = useState(() => window.innerWidth >= 760),
+ [rightOpen, setRightOpen] = useState(() => window.innerWidth >= 1100);
+ const [tool, setTool] = useState<"select" | "hand" | "draw">("select"),
+ [spaceHeld, setSpaceHeld] = useState(false);
+ const [brushColor, setBrushColor] = useState("#16a06e"),
+ [brushWidth, setBrushWidth] = useState(8);
+ const [zoom, setZoom] = useState(0.4),
+ [fitZoom, setFitZoom] = useState(0.4),
+ [autoFit, setAutoFit] = useState(true);
+ const [grid, setGrid] = useState(false),
+ [safeArea, setSafeArea] = useState(false),
+ [snap, setSnap] = useState(true),
+ [guides, setGuides] = useState<{ x?: number; y?: number }>({});
+ const [exportOpen, setExportOpen] = useState(false),
+ [exportFormat, setExportFormat] = useState<"png" | "jpeg" | "webp">("png"),
+ [exportScale, setExportScale] = useState(1),
+ [exportQuality, setExportQuality] = useState(0.92);
+ const [toast, setToast] = useState("");
+ const [recovery, setRecovery] = useState<{
+ title: string;
+ document: PosterDocument;
+ baseHash: string;
+ tagsText?: string;
+ } | null>(null);
+ const [, setHistoryVersion] = useState(0);
+ const workbenchHost = useRef<HTMLDivElement>(null);
+ const canvasHost = useRef<HTMLDivElement>(null),
+ viewport = useRef<HTMLDivElement>(null);
+ const fileInput = useRef<HTMLInputElement>(null),
+ canvas = useRef<Canvas | null>(null);
+ const objectsRef = useRef<FabricObject[]>([]);
+ const selectionSync = useRef(false);
+ const session = useRef<MemoEditSession | null>(null),
+ currentMemo = useRef(memo);
+ const current = useRef({ title, document, tagsText });
+ current.current = { title, document, tagsText };
+ const selected = useRef(selectedIds);
+ selected.current = selectedIds;
+ const options = useRef({ zoom, snap, readOnly, busy, tool, spaceHeld });
+ options.current = { zoom, snap, readOnly, busy, tool, spaceHeld };
+ const loadedArt = useRef(artwork(document));
+ const undo = useRef<PosterDocument[]>([]),
+ redo = useRef<PosterDocument[]>([]);
+ const saveLock = useRef<Promise<boolean> | null>(null),
+ saveRef = useRef<() => Promise<boolean>>(async () => false);
+ const onSavedRef = useRef(onSaved);
+ onSavedRef.current = onSaved;
+ const actions = useRef<{ commit: typeof commit; add: typeof add }>(
+ {} as never,
+ );
+ const panStart = useRef<{
+ x: number;
+ y: number;
+ left: number;
+ top: number;
+ } | null>(null);
+ const draftKey = `edgeever:poster-draft:${memo.id}`;
+ const dirty = snapshot(title, document) !== saved || tagsText !== savedTags;
+ const editable = !readOnly && Boolean(initial) && ready && !busy;
+ const selectedElements = document.elements.filter((element) =>
+ selectedIds.includes(element.id),
+ );
+ const active =
+ selectedElements.length === 1 ? selectedElements[0] : undefined;
+ const platform = platformFor(
+ document.width,
+ document.height,
+ document.platformId,
+ );
+ const readResource = useMemo(() => {
+ const cache = new Map<string, Promise<Blob>>();
+ return (id: string) => {
+ if (!cache.has(id))
+ cache.set(
+ id,
+ repository.readResource(id).catch((error) => {
+ cache.delete(id);
+ throw error;
+ }),
+ );
+ return cache.get(id)!;
+ };
+ }, [repository]);
+
+ const commit = (next: PosterDocument, redraw = true) => {
+ const validated = PosterDocumentSchema.safeParse(next);
+ if (!validated.success) {
+ setError(t("poster.invalid"));
+ if (!redraw) setCanvasRevision((version) => version + 1);
+ return;
+ }
+ if (artwork(next) === artwork(current.current.document)) return;
+ undo.current = [...undo.current.slice(-49), current.current.document];
+ redo.current = [];
+ current.current.document = validated.data;
+ setDocument(validated.data);
+ if (redraw) setCanvasRevision((version) => version + 1);
+ setHistoryVersion((version) => version + 1);
+ setError(null);
+ };
+ const patchIds = (
+ ids: string[],
+ patch: Partial<PosterElement>,
+ allowLocked = false,
+ ) => {
+ const value = current.current.document;
+ const next = {
+ ...value,
+ elements: value.elements.map((element) =>
+ ids.includes(element.id) && (!element.locked || allowLocked)
+ ? ({
+ ...element,
+ ...patch,
+ ...("text" in patch && patch.text !== undefined
+ ? { sourceText: patch.text }
+ : {}),
+ } as PosterElement)
+ : element,
+ ),
+ };
+ if ("text" in patch) {
+ const copy = { ...posterCopy(value) };
+ for (const role of ["title", "subtitle", "badge"] as const)
+ if (
+ value.elements.some(
+ (element) =>
+ ids.includes(element.id) &&
+ element.role === role &&
+ (!element.locked || allowLocked),
+ )
+ )
+ copy[role] = next.elements
+ .filter(
+ (element) => element.type === "text" && element.role === role,
+ )
+ .map((element) =>
+ element.type === "text"
+ ? (element.sourceText ?? element.text)
+ : "",
+ )
+ .join("\n");
+ next.copy = copy;
+ }
+ commit(next);
+ };
+ const updateElement = (patch: Partial<PosterElement>) =>
+ patchIds(selected.current, patch, "locked" in patch || "name" in patch);
+ const travel = (back: boolean) => {
+ const from = back ? undo.current : redo.current,
+ to = back ? redo.current : undo.current;
+ const next = from.pop();
+ if (!next) return;
+ to.push(current.current.document);
+ current.current.document = next;
+ setDocument(next);
+ setCanvasRevision((version) => version + 1);
+ setHistoryVersion((version) => version + 1);
+ };
+ const syncSelection = (ids: string[]) => {
+ setSelectedIds(ids);
+ selected.current = ids;
+ const instance = canvas.current;
+ if (!instance) return;
+ selectionSync.current = true;
+ instance.discardActiveObject();
+ const objects = objectsRef.current.filter((_, index) =>
+ ids.includes(current.current.document.elements[index]?.id),
+ );
+ if (objects.length === 1) instance.setActiveObject(objects[0]);
+ else if (objects.length > 1)
+ instance.setActiveObject(
+ new ActiveSelection(objects, { canvas: instance }),
+ );
+ instance.requestRenderAll();
+ setSelectedIds(ids);
+ selected.current = ids;
+ selectionSync.current = false;
+ };
+ const selectLayer = (id: string, append: boolean) => {
+ const element = current.current.document.elements.find(
+ (entry) => entry.id === id,
+ );
+ const ids =
+ element?.groupId && !append
+ ? current.current.document.elements
+ .filter((entry) => entry.groupId === element.groupId)
+ .map((entry) => entry.id)
+ : [id];
+ syncSelection(
+ append
+ ? selected.current.includes(id)
+ ? selected.current.filter((entry) => entry !== id)
+ : [...selected.current, id]
+ : ids,
+ );
+ };
+ const removeSelected = () => {
+ const value = current.current.document;
+ commit({
+ ...value,
+ elements: value.elements.filter(
+ (element) => !selected.current.includes(element.id) || element.locked,
+ ),
+ });
+ syncSelection([]);
+ };
+ const duplicate = () => {
+ const value = current.current.document,
+ groupIds = new Map<string, string>();
+ const copies = value.elements
+ .filter(
+ (element) => selected.current.includes(element.id) && !element.locked,
+ )
+ .map((element) => {
+ if (element.groupId && !groupIds.has(element.groupId))
+ groupIds.set(element.groupId, crypto.randomUUID());
+ return {
+ ...element,
+ id: crypto.randomUUID(),
+ x: element.x + 24,
+ y: element.y + 24,
+ groupId: element.groupId ? groupIds.get(element.groupId) : undefined,
+ };
+ });
+ commit({ ...value, elements: [...value.elements, ...copies] });
+ selected.current = copies.map((element) => element.id);
+ setSelectedIds(selected.current);
+ };
+ const add = (element: PosterElement) => {
+ commit({
+ ...current.current.document,
+ elements: [...current.current.document.elements, element],
+ });
+ selected.current = [element.id];
+ setSelectedIds([element.id]);
+ setRightTab("properties");
+ setRightOpen(true);
+ setTool("select");
+ };
+ const addText = (style: "heading" | "subtitle" | "body" | "badge") => {
+ const value = current.current.document,
+ size =
+ style === "heading"
+ ? Math.min(value.width * 0.13, value.height * 0.18)
+ : style === "subtitle"
+ ? 48
+ : 32;
+ add({
+ id: crypto.randomUUID(),
+ name: t(`poster.design.textStyles.${style}`),
+ type: "text",
+ text: t(`poster.design.textStyles.${style}`),
+ x: value.width * 0.12,
+ y: value.height * 0.35,
+ width: value.width * 0.76,
+ height: size * 1.5,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ fill: style === "badge" ? "#ffffff" : "#07130b",
+ fontSize: Math.round(size),
+ fontFamily: zh
+ ? style === "heading"
+ ? "思源黑体 Heavy"
+ : "思源黑体"
+ : "Inter",
+ fontWeight: "normal",
+ textAlign: "left",
+ ...(style === "badge"
+ ? {
+ badge: {
+ background: "#16a06e",
+ padX: 0.6,
+ padY: 0.35,
+ radius: 0.5,
+ },
+ }
+ : {}),
+ });
+ };
+ const addShape = (shape: string) => {
+ const value = current.current.document,
+ width = value.width * 0.3,
+ height = value.height * 0.15;
+ const base = {
+ id: crypto.randomUUID(),
+ name: t(`poster.design.shapes.${shape}`),
+ x: value.width * 0.35,
+ y: value.height * 0.4,
+ width,
+ height,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ fill: "#16a06e",
+ };
+ if (["rect", "pill", "ellipse"].includes(shape))
+ add({
+ ...base,
+ type: shape === "ellipse" ? "ellipse" : "rect",
+ radius: shape === "pill" ? height / 2 : 0,
+ });
+ else {
+ const paths: Record<string, string> = {
+ line: "M 0 0 L 200 0",
+ arrow: "M 0 120 L 150 0 M 85 0 L 150 0 L 150 65",
+ star: "M 100 0 L 124 70 L 200 72 L 140 118 L 160 192 L 100 148 L 40 192 L 60 118 L 0 72 L 76 70 Z",
+ sparkle:
+ "M 100 0 Q 100 100 200 100 Q 100 100 100 200 Q 100 100 0 100 Q 100 100 100 0 Z",
+ };
+ add({
+ ...base,
+ type: "path",
+ path: paths[shape] ?? paths.star,
+ height: shape === "line" ? 1 : width,
+ ...(shape === "line" || shape === "arrow"
+ ? { fill: "rgba(0,0,0,0)", stroke: "#16a06e", strokeWidth: 8 }
+ : {}),
+ });
+ }
+ };
+ const align = (direction: PosterAlign) => {
+ const value = current.current.document,
+ chosen = value.elements.filter(
+ (element) => selected.current.includes(element.id) && !element.locked,
+ );
+ if (!chosen.length) return;
+ const bounds =
+ chosen.length === 1
+ ? { left: 0, right: value.width, top: 0, bottom: value.height }
+ : {
+ left: Math.min(...chosen.map((element) => element.x)),
+ right: Math.max(
+ ...chosen.map((element) => element.x + element.width),
+ ),
+ top: Math.min(...chosen.map((element) => element.y)),
+ bottom: Math.max(
+ ...chosen.map((element) => element.y + element.height),
+ ),
+ };
+ commit({
+ ...value,
+ elements: value.elements.map((element) =>
+ !chosen.includes(element)
+ ? element
+ : {
+ ...element,
+ ...(direction === "left"
+ ? { x: bounds.left }
+ : direction === "right"
+ ? { x: bounds.right - element.width }
+ : direction === "center"
+ ? { x: (bounds.left + bounds.right - element.width) / 2 }
+ : direction === "top"
+ ? { y: bounds.top }
+ : direction === "bottom"
+ ? { y: bounds.bottom - element.height }
+ : {
+ y:
+ (bounds.top + bounds.bottom - element.height) / 2,
+ }),
+ },
+ ),
+ });
+ };
+ const group = (ungroup: boolean) => {
+ patchIds(selected.current, {
+ groupId: ungroup ? undefined : crypto.randomUUID(),
+ });
+ };
+ const moveLayer = (front: boolean, oneStep = false) => {
+ const value = current.current.document,
+ selectedElements = value.elements.filter(
+ (element) => selected.current.includes(element.id) && !element.locked,
+ ),
+ rest = value.elements.filter(
+ (element) => !selectedElements.includes(element),
+ );
+ if (!selectedElements.length) return;
+ if (oneStep && selectedElements.length === 1) {
+ const index = value.elements.indexOf(selectedElements[0]);
+ rest.splice(
+ Math.max(0, Math.min(rest.length, index + (front ? 1 : -1))),
+ 0,
+ selectedElements[0],
+ );
+ } else if (front) rest.push(...selectedElements);
+ else rest.unshift(...selectedElements);
+ commit({ ...value, elements: rest });
+ };
+ actions.current = { commit, add };
+ useEffect(() => {
+ if (!initial || readOnly) return;
+ let cancelled = false;
+ if (requiresLocalEditSession(memo)) {
+ session.current = createLocalEditSession(memo);
+ setReady(true);
+ } else
+ void api
+ .createMemoEditSession(memo.id)
+ .then(({ editSession }) => {
+ if (!cancelled) {
+ session.current = editSession;
+ setReady(true);
+ }
+ })
+ .catch(() => {
+ if (!cancelled) setError(t("poster.error"));
+ });
+ try {
+ const raw = localStorage.getItem(draftKey);
+ if (raw) {
+ const stored = JSON.parse(raw);
+ const document = PosterDocumentSchema.parse(stored.document);
+ if (
+ typeof stored.title === "string" &&
+ typeof stored.baseHash === "string" &&
+ (snapshot(stored.title, document) !==
+ snapshot(memo.title ?? "", initial) ||
+ (typeof stored.tagsText === "string" && stored.tagsText !== memo.tags.join(", ")))
+ )
+ setRecovery({ ...stored, document });
+ }
+ } catch {
+ setError(t("poster.recoveryError"));
+ }
+ return () => {
+ cancelled = true;
+ };
+ }, [memo.id, readOnly]);
+
+ useEffect(() => {
+ if (memo.contentHash === currentMemo.current.contentHash) return;
+ if (dirty || saveLock.current) {
+ setError(t("poster.remoteChanged"));
+ return;
+ }
+ const next = parsePosterDocument(memo.contentMarkdown);
+ if (!next) {
+ setError(t("poster.invalid"));
+ return;
+ }
+ if (
+ snapshot(memo.title ?? "", next) ===
+ snapshot(current.current.title, current.current.document)
+ ) {
+ currentMemo.current = memo;
+ setTagsText(memo.tags.join(", "));
+ setSavedTags(memo.tags.join(", "));
+ setSaved(snapshot(memo.title ?? "", next));
+ return;
+ }
+ currentMemo.current = memo;
+ setTagsText(memo.tags.join(", "));
+ setSavedTags(memo.tags.join(", "));
+ loadedArt.current = next.previewResourceId ? artwork(next) : "";
+ setDocument(next);
+ setCanvasRevision((version) => version + 1);
+ setTitle(memo.title ?? "");
+ setSaved(next.previewResourceId ? snapshot(memo.title ?? "", next) : "");
+ undo.current = [];
+ redo.current = [];
+ setHistoryVersion((version) => version + 1);
+ }, [memo.contentHash]);
+
+ useEffect(() => {
+ const host = workbenchHost.current;
+ if (!host) return;
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry.contentRect.width < 760) setLeftOpen(false);
+ if (entry.contentRect.width < 1000) setRightOpen(false);
+ });
+ observer.observe(host);
+ return () => observer.disconnect();
+ }, []);
+ useEffect(() => {
+ if (!canvasHost.current) return;
+ // Fabric owns this subtree. React must not manage a canvas that Fabric wraps and moves.
+ const node = window.document.createElement("canvas");
+ node.setAttribute("aria-label", t("poster.canvas"));
+ canvasHost.current.appendChild(node);
+ const instance = new Canvas(node, {
+ preserveObjectStacking: true,
+ selection: true,
+ selectionKey: ["shiftKey", "ctrlKey", "metaKey"],
+ });
+ canvas.current = instance;
+ const pick = () => {
+ if (selectionSync.current) return;
+ const ids = instance
+ .getActiveObjects()
+ .map(
+ (object) =>
+ current.current.document.elements[
+ objectsRef.current.indexOf(object)
+ ]?.id,
+ )
+ .filter((id): id is string => Boolean(id));
+ if (ids.length === 1) {
+ const groupId = current.current.document.elements.find(
+ (element) => element.id === ids[0],
+ )?.groupId;
+ if (groupId) {
+ syncSelection(
+ current.current.document.elements
+ .filter(
+ (element) => element.groupId === groupId && !element.locked,
+ )
+ .map((element) => element.id),
+ );
+ setRightTab("properties");
+ return;
+ }
+ }
+ selected.current = ids;
+ setSelectedIds(ids);
+ if (ids.length) setRightTab("properties");
+ };
+ instance.on("selection:created", pick);
+ instance.on("selection:updated", pick);
+ instance.on("selection:cleared", pick);
+ const changed = () => {
+ if (options.current.readOnly) return;
+ const value = current.current.document;
+ const elements = value.elements.map((element, index) =>
+ objectsRef.current[index]
+ ? posterElementFromObject(element, objectsRef.current[index])
+ : element,
+ );
+ const copy = { ...posterCopy(value) };
+ for (const role of ["title", "subtitle", "badge"] as const)
+ if (
+ elements.some(
+ (element, index) =>
+ element.type === "text" &&
+ element.role === role &&
+ value.elements[index]?.type === "text" &&
+ element.text !==
+ (
+ value.elements[index] as Extract<
+ PosterElement,
+ { type: "text" }
+ >
+ ).text,
+ )
+ )
+ copy[role] = elements
+ .filter(
+ (element) => element.type === "text" && element.role === role,
+ )
+ .map((element) =>
+ element.type === "text"
+ ? (element.sourceText ?? element.text)
+ : "",
+ )
+ .join("\n");
+ actions.current.commit({ ...value, elements, copy }, false);
+ };
+ instance.on("object:modified", changed);
+ instance.on("text:editing:exited", changed);
+ instance.on("object:moving", ({ target }) => {
+ if (!target || !options.current.snap || target instanceof ActiveSelection)
+ return;
+ const value = current.current.document,
+ threshold = 6 / options.current.zoom;
+ const bounds = target.getBoundingRect(),
+ axes = {
+ x: [0, value.width / 2, value.width],
+ y: [0, value.height / 2, value.height],
+ };
+ for (const object of objectsRef.current)
+ if (object !== target && object.visible) {
+ const other = object.getBoundingRect();
+ axes.x.push(
+ other.left,
+ other.left + other.width / 2,
+ other.left + other.width,
+ );
+ axes.y.push(
+ other.top,
+ other.top + other.height / 2,
+ other.top + other.height,
+ );
+ }
+ const found: { x?: number; y?: number } = {};
+ for (const axis of ["x", "y"] as const) {
+ const start = axis === "x" ? bounds.left : bounds.top,
+ size = axis === "x" ? bounds.width : bounds.height;
+ let best = threshold,
+ delta = 0;
+ for (const anchor of [start, start + size / 2, start + size])
+ for (const guide of axes[axis])
+ if (Math.abs(guide - anchor) < best) {
+ best = Math.abs(guide - anchor);
+ found[axis] = guide;
+ delta = guide - anchor;
+ }
+ if (found[axis] !== undefined)
+ target.set(
+ axis === "x" ? "left" : "top",
+ (axis === "x" ? target.left : target.top) + delta,
+ );
+ }
+ setGuides(found);
+ });
+ instance.on("mouse:up", () => setGuides({}));
+ instance.on("path:created", ({ path }) => {
+ const element = posterPrimitiveFromObject(path, 0);
+ if (!element) return;
+ actions.current.add({
+ ...element,
+ id: crypto.randomUUID(),
+ name: t("poster.design.drawing"),
+ });
+ setTool("draw");
+ syncSelection([]);
+ });
+ return () => {
+ canvas.current = null;
+ const wrapper = instance.wrapperEl;
+ void instance.dispose().then(() => {
+ node.remove();
+ wrapper.remove();
+ });
+ };
+ }, []);
+ useEffect(() => {
+ const instance = canvas.current;
+ if (!instance) return;
+ let cancelled = false;
+ setCanvasReady(false);
+ const value = current.current.document,
+ ids = [...selected.current];
+ void Promise.all(
+ value.elements.map((element) => posterObject(element, readResource)),
+ )
+ .then((objects) => {
+ if (cancelled) return;
+ instance.discardActiveObject();
+ instance.clear();
+ instance.backgroundColor = value.backgroundGradient
+ ? makePosterGradient(
+ value.backgroundGradient,
+ value.width,
+ value.height,
+ )
+ : value.background;
+ objectsRef.current = objects;
+ for (let index = 0; index < objects.length; index++) {
+ const element = value.elements[index],
+ object = objects[index];
+ object.set({
+ selectable:
+ !readOnly && !element.locked && element.visible !== false,
+ evented: !readOnly && !element.locked && element.visible !== false,
+ hasControls: !readOnly && !element.locked,
+ lockMovementX: Boolean(element.locked),
+ lockMovementY: Boolean(element.locked),
+ });
+ if (object instanceof Textbox)
+ object.editable = !readOnly && !element.locked;
+ instance.add(object);
+ }
+ syncSelection(
+ ids.filter((id) =>
+ value.elements.some(
+ (element) => element.id === id && !element.locked,
+ ),
+ ),
+ );
+ instance.requestRenderAll();
+ setCanvasReady(true);
+ })
+ .catch((caught) => {
+ if (!cancelled)
+ setError(
+ caught instanceof Error ? caught.message : t("poster.error"),
+ );
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [canvasRevision, readOnly, readResource]);
+ useEffect(() => {
+ const instance = canvas.current;
+ if (!instance) return;
+ instance.setDimensions({
+ width: document.width * zoom,
+ height: document.height * zoom,
+ });
+ instance.setViewportTransform([zoom, 0, 0, zoom, 0, 0]);
+ instance.requestRenderAll();
+ }, [zoom, document.width, document.height, canvasReady]);
+ useEffect(() => {
+ const host = viewport.current;
+ if (!host) return;
+ const fit = () => {
+ const next = Math.max(
+ 0.1,
+ Math.min(
+ 1,
+ (host.clientWidth - 112) / document.width,
+ (host.clientHeight - 112) / document.height,
+ ),
+ );
+ setFitZoom(next);
+ if (autoFit) setZoom(next);
+ };
+ const observer = new ResizeObserver(fit);
+ observer.observe(host);
+ fit();
+ return () => observer.disconnect();
+ }, [document.width, document.height, autoFit, leftOpen, rightOpen]);
+ useEffect(() => {
+ const instance = canvas.current;
+ if (!instance) return;
+ const hand = tool === "hand" || spaceHeld;
+ instance.isDrawingMode = tool === "draw" && !readOnly && !busy;
+ instance.selection = !hand && tool === "select" && !readOnly && !busy;
+ instance.skipTargetFind = hand || readOnly || busy;
+ instance.defaultCursor = hand ? "grab" : "default";
+ instance.hoverCursor = hand ? "grab" : "move";
+ if (instance.isDrawingMode) {
+ const brush = new PencilBrush(instance);
+ brush.color = brushColor;
+ brush.width = brushWidth;
+ instance.freeDrawingBrush = brush;
+ }
+ }, [tool, spaceHeld, readOnly, busy, brushColor, brushWidth, canvasReady]);
+ useEffect(() => {
+ const host = viewport.current;
+ if (!host) return;
+ const wheel = (event: WheelEvent) => {
+ if (!event.ctrlKey && !event.metaKey) return;
+ event.preventDefault();
+ setAutoFit(false);
+ setZoom((value) =>
+ Math.max(0.1, Math.min(2, value * Math.exp(-event.deltaY * 0.002))),
+ );
+ };
+ host.addEventListener("wheel", wheel, { passive: false });
+ return () => host.removeEventListener("wheel", wheel);
+ }, []);
+
+ saveRef.current = () => {
+ if (saveLock.current) return saveLock.current;
+ const editing = canvas.current?.getActiveObject();
+ if (
+ editing &&
+ "exitEditing" in editing &&
+ typeof editing.exitEditing === "function"
+ )
+ editing.exitEditing();
+ const data = { ...current.current };
+ if (snapshot(data.title, data.document) === saved && data.tagsText === savedTags)
+ return Promise.resolve(true);
+ if (!session.current || !canvasReady || readOnly || !initial)
+ return Promise.resolve(false);
+ const operation = (async () => {
+ setSaving(true);
+ setError(null);
+ try {
+ const captured = snapshot(data.title, data.document);
+ const preview =
+ artwork(data.document) !== loadedArt.current ||
+ !data.document.previewResourceId
+ ? await renderPosterBlob(data.document, readResource, "png", true)
+ : undefined;
+ const result = await savePosterMemo(
+ repository,
+ currentMemo.current,
+ data.document,
+ data.title,
+ session.current!.id,
+ preview,
+ parseTagsText(data.tagsText),
+ );
+ currentMemo.current = result.memo;
+ loadedArt.current = artwork(data.document);
+ setSaved(captured);
+ setSavedTags(data.tagsText);
+ setDocument((latest) => ({
+ ...latest,
+ previewResourceId: result.document.previewResourceId,
+ }));
+ try {
+ if (
+ snapshot(current.current.title, current.current.document) ===
+ captured && current.current.tagsText === data.tagsText
+ )
+ localStorage.removeItem(draftKey);
+ } catch {
+ /* Saved data remains in the repository. */
+ }
+ await onSavedRef.current(result.memo);
+ return true;
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : t("poster.error"));
+ return false;
+ } finally {
+ setSaving(false);
+ saveLock.current = null;
+ }
+ })();
+ saveLock.current = operation;
+ return operation;
+ };
+ useEffect(() => {
+ if (!dirty || readOnly || !initial) return;
+ try {
+ localStorage.setItem(
+ draftKey,
+ JSON.stringify({
+ title,
+ document,
+ tagsText,
+ baseHash: currentMemo.current.contentHash,
+ }),
+ );
+ } catch {
+ setError(t("poster.recoveryError"));
+ }
+ if (!ready || !canvasReady || saving || busy || recovery || error) return;
+ const timer = window.setTimeout(() => void saveRef.current(), 2000);
+ return () => window.clearTimeout(timer);
+ }, [
+ title,
+ document,
+ tagsText,
+ dirty,
+ ready,
+ canvasReady,
+ saving,
+ busy,
+ recovery,
+ error,
+ ]);
+ useEffect(() => {
+ if (!dirty) return;
+ const handler = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ };
+ window.addEventListener("beforeunload", handler);
+ return () => window.removeEventListener("beforeunload", handler);
+ }, [dirty]);
+
+ const run = async (action: () => Promise<void>) => {
+ if (busy) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await action();
+ } catch (caught) {
+ setError(
+ caught instanceof z.ZodError || caught instanceof SyntaxError
+ ? t("poster.aiInvalid")
+ : caught instanceof Error
+ ? caught.message
+ : t("poster.error"),
+ );
+ } finally {
+ setBusy(false);
+ }
+ };
+ const exportImage = (format: "png" | "jpeg" | "webp") =>
+ run(async () => {
+ const editing = canvas.current?.getActiveObject();
+ if (
+ editing &&
+ "exitEditing" in editing &&
+ typeof editing.exitEditing === "function"
+ )
+ editing.exitEditing();
+ const blob = await renderPosterBlob(
+ current.current.document,
+ readResource,
+ format,
+ false,
+ exportScale,
+ exportQuality,
+ );
+ downloadBlob(
+ blob,
+ `${title.trim().replace(/[\\/:*?"<>|]/g, "_") || "poster"}.${format === "jpeg" ? "jpg" : format}`,
+ );
+ });
+ const insertInSource = () =>
+ run(async () => {
+ const sourceId = document.sourceMemoId;
+ if (!sourceId) return;
+ if (!navigator.onLine) throw new Error(t("poster.offline"));
+ if (!(await saveRef.current())) return;
+ const { memo: source } = await repository.getMemo(sourceId);
+ if (
+ source.isDeleted ||
+ /<!--\s*edgeever-(?:poster|diagram|table|infographic)-v1:/.test(
+ source.contentMarkdown,
+ )
+ )
+ throw new Error(t("poster.sourceUnavailable"));
+ const blob = await renderPosterBlob(
+ current.current.document,
+ readResource,
+ );
+ const { resource } = await repository.uploadMemoResource(
+ source.id,
+ new File([blob], "poster.png", { type: "image/png" }),
+ );
+ let inserted = false;
+ try {
+ const sourceSession = requiresLocalEditSession(source)
+ ? createLocalEditSession(source)
+ : (await api.createMemoEditSession(source.id)).editSession;
+ const markdown = `${source.contentMarkdown}\n\n![${title.replace(/[\[\]\\\n]/g, " ")}](${resource.url})`;
+ const result = await repository.updateMemo(source, {
+ expectedRevision: source.revision,
+ expectedContentHash: source.contentHash,
+ editSessionId: sourceSession.id,
+ contentMarkdown: markdown,
+ contentJson: {
+ ...source.contentJson,
+ content: [
+ ...(source.contentJson.content ?? []),
+ { type: "image", attrs: { src: resource.url, alt: title } },
+ ],
+ },
+ title: source.title ?? "",
+ tags: source.tags,
+ });
+ inserted = true;
+ await onSavedRef.current(result.memo);
+ onOpenCompanionNote?.(source.id, source.notebookId);
+ } finally {
+ if (!inserted) {
+ const latest = await repository.getMemo(source.id).catch(() => null);
+ if (
+ latest &&
+ !JSON.stringify(latest.memo.contentJson).includes(resource.id) &&
+ !latest.memo.contentMarkdown.includes(resource.id)
+ )
+ await repository.deleteResource(resource.id).catch(() => undefined);
+ }
+ }
+ });
+ const designAt = async (
+ id: string,
+ width = current.current.document.width,
+ height = current.current.document.height,
+ platformId = current.current.document.platformId,
+ ) => {
+ const editing = canvas.current?.getActiveObject();
+ if (editing instanceof Textbox && editing.isEditing) editing.exitEditing();
+ const value = current.current.document;
+ const built = await buildPosterDesign({
+ id,
+ ...posterCopy(value),
+ width,
+ height,
+ zh,
+ });
+ const extras = value.elements.filter(
+ (element) =>
+ !element.id.startsWith("design_") &&
+ !["heading", "subtitle", "accent"].includes(element.id),
+ );
+ const scaled = resizePosterDocument(
+ { ...value, elements: extras },
+ width,
+ height,
+ ).elements;
+ return {
+ ...built,
+ sourceMemoId: value.sourceMemoId,
+ platformId,
+ elements: [...built.elements, ...scaled],
+ };
+ };
+ const applyTemplate = (id: string) =>
+ run(async () => {
+ const next = await designAt(id);
+ syncSelection([]);
+ commit(next);
+ setAutoFit(true);
+ });
+ const resize = (width: number, height: number, platformId?: string) =>
+ run(async () => {
+ const value = current.current.document;
+ const next = value.templateId
+ ? await designAt(value.templateId, width, height, platformId)
+ : { ...resizePosterDocument(value, width, height), platformId };
+ syncSelection([]);
+ commit(next);
+ setExportScale((scale) =>
+ Math.min(scale, Math.floor(8192 / Math.max(width, height))),
+ );
+ setAutoFit(true);
+ });
+ const changePlatform = (id: string) => {
+ const platform = PLATFORMS.find((entry) => entry.id === id);
+ if (platform) void resize(platform.width, platform.height, id);
+ };
+ const upload = (file: File) =>
+ run(async () => {
+ if (
+ file.size > 10 * 1024 * 1024 ||
+ !["image/png", "image/jpeg", "image/webp"].includes(file.type)
+ )
+ throw new Error(t("poster.imageLimit"));
+ if (!navigator.onLine) throw new Error(t("poster.offline"));
+ if (current.current.document.elements.length >= 500)
+ throw new Error(t("poster.invalid"));
+ const bitmap = await createImageBitmap(file);
+ const width = bitmap.width,
+ height = bitmap.height;
+ bitmap.close();
+ if (width * height > 36_000_000) throw new Error(t("poster.imageLimit"));
+ const compressed = await compressImageForUpload(file);
+ const { resource } = await repository.uploadMemoResource(
+ memo.id,
+ compressed.file,
+ );
+ const value = current.current.document,
+ factor = Math.min(
+ (value.width * 0.7) / width,
+ (value.height * 0.5) / height,
+ 1,
+ );
+ add({
+ id: crypto.randomUUID(),
+ name: file.name.slice(0, 120),
+ type: "image",
+ resourceId: resource.id,
+ x: (value.width - width * factor) / 2,
+ y: (value.height - height * factor) / 2,
+ width: width * factor,
+ height: height * factor,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ });
+ });
+ const imageFit = (cover: boolean) =>
+ run(async () => {
+ if (active?.type !== "image") return;
+ const bitmap = await createImageBitmap(
+ await readResource(active.resourceId),
+ ),
+ ratio = bitmap.width / bitmap.height;
+ bitmap.close();
+ const value = current.current.document;
+ if (cover) {
+ const frame = value.width / value.height,
+ width = frame < ratio ? frame / ratio : 1,
+ height = frame > ratio ? ratio / frame : 1;
+ commit({
+ ...value,
+ elements: [
+ {
+ ...active,
+ x: 0,
+ y: 0,
+ width: value.width,
+ height: value.height,
+ rotation: 0,
+ crop: { x: (1 - width) / 2, y: (1 - height) / 2, width, height },
+ },
+ ...value.elements.filter((element) => element.id !== active.id),
+ ],
+ });
+ } else {
+ const width = Math.min(value.width * 0.8, value.height * 0.8 * ratio),
+ height = width / ratio;
+ updateElement({
+ x: (value.width - width) / 2,
+ y: (value.height - height) / 2,
+ width,
+ height,
+ crop: undefined,
+ rotation: 0,
+ });
+ }
+ });
+ const copyImage = () =>
+ run(async () => {
+ const blob = await renderPosterBlob(
+ current.current.document,
+ readResource,
+ );
+ if (!(await copyImageBlobToClipboard(blob)))
+ throw new Error(t("poster.design.copyFailed"));
+ setToast(t("poster.design.copied"));
+ });
+ useEffect(() => {
+ if (!toast) return;
+ const timer = window.setTimeout(() => setToast(""), 3000);
+ return () => window.clearTimeout(timer);
+ }, [toast]);
+ useEffect(() => {
+ const key = (event: KeyboardEvent) => {
+ const input =
+ event.target instanceof HTMLElement &&
+ (event.target.closest("input,textarea,select,[contenteditable=true]") ||
+ (canvas.current?.getActiveObject() instanceof Textbox &&
+ (canvas.current.getActiveObject() as Textbox).isEditing));
+ const command = event.metaKey || event.ctrlKey;
+ if (command && event.key.toLowerCase() === "s") {
+ event.preventDefault();
+ void saveRef.current();
+ return;
+ }
+ if (input || !editable) return;
+ if (event.code === "Space") {
+ event.preventDefault();
+ setSpaceHeld(true);
+ return;
+ }
+ if (command && event.key.toLowerCase() === "z") {
+ event.preventDefault();
+ travel(!event.shiftKey);
+ } else if (command && event.key.toLowerCase() === "d") {
+ event.preventDefault();
+ duplicate();
+ } else if (command && event.key.toLowerCase() === "g") {
+ event.preventDefault();
+ group(event.shiftKey);
+ } else if (command && event.key.toLowerCase() === "a") {
+ event.preventDefault();
+ syncSelection(
+ current.current.document.elements
+ .filter((element) => !element.locked && element.visible !== false)
+ .map((element) => element.id),
+ );
+ } else if (event.key === "Delete" || event.key === "Backspace") {
+ event.preventDefault();
+ removeSelected();
+ } else if (event.key === "Escape") {
+ syncSelection([]);
+ setTool("select");
+ } else if (
+ ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(
+ event.key,
+ ) &&
+ selected.current.length
+ ) {
+ event.preventDefault();
+ const step = event.shiftKey ? 10 : 1,
+ value = current.current.document;
+ commit({
+ ...value,
+ elements: value.elements.map((element) =>
+ !selected.current.includes(element.id) || element.locked
+ ? element
+ : {
+ ...element,
+ x:
+ element.x +
+ (event.key === "ArrowLeft"
+ ? -step
+ : event.key === "ArrowRight"
+ ? step
+ : 0),
+ y:
+ element.y +
+ (event.key === "ArrowUp"
+ ? -step
+ : event.key === "ArrowDown"
+ ? step
+ : 0),
+ },
+ ),
+ });
+ }
+ };
+ const up = (event: KeyboardEvent) => {
+ if (event.code === "Space") setSpaceHeld(false);
+ };
+ const blur = () => setSpaceHeld(false);
+ window.addEventListener("keydown", key);
+ window.addEventListener("keyup", up);
+ window.addEventListener("blur", blur);
+ return () => {
+ window.removeEventListener("keydown", key);
+ window.removeEventListener("keyup", up);
+ window.removeEventListener("blur", blur);
+ };
+ }, [editable]);
+ const toolButton = (
+ label: string,
+ icon: React.ReactNode,
+ onClick: () => void,
+ disabled = false,
+ active = false,
+ text = false,
+ ) => (
+ <PosterTool
+ label={label}
+ onClick={onClick}
+ disabled={disabled}
+ active={active}
+ text={text}
+ >
+ {icon}
+ </PosterTool>
+ );
+ const safeMargin =
+ Math.min(document.width, document.height) * (platform?.margin ?? 0.06);
+ return (
+ <div className="relative flex h-full min-h-0 min-w-0 bg-card" data-poster-workbench>
+ <div ref={workbenchHost} className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col">
+ <header className="shrink-0 border-b border-slate-200 bg-card">
+ <div className={MEMO_EDITOR_TOP_ROW_CLASS_NAME}>
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2 px-4 sm:flex-nowrap">
+ <MemoEditorTopRowLeading
+ mobileBackButton={<IconTooltip label={t("poster.back")}><Button className="lg:hidden" variant="ghost" size="icon" aria-label={t("poster.back")} onClick={() => { void (async () => { if (!dirty || await saveRef.current()) onBackToList(); })(); }}><ArrowLeft className="h-4 w-4" /></Button></IconTooltip>}
+ titleInput={<MemoTitleInput value={title} onValueChange={setTitle} readOnly={!editable} placeholder={t("poster.name")} ariaLabel={t("poster.title")} />}
+ />
+ <MemoEditorMetadataRow rowClassName={MEMO_EDITOR_METADATA_ROW_CLASS_NAME} contentMarkdown={memo.contentMarkdown} disabled={!editable}
+ mobileNotebookPickerOpen={mobileNotebookPickerOpen} notebookOptions={notebookOptions} notebookUpdatePending={notebookUpdatePending || saving}
+ repository={repository} selectedNotebookId={currentMemo.current.notebookId} tagsText={tagsText} title={title}
+ onMobileNotebookPickerOpenChange={setMobileNotebookPickerOpen} onTagsChange={setTagsText}
+ onNotebookChange={(notebookId) => {
+ if (!editable || notebookUpdatePending || notebookId === currentMemo.current.notebookId) return;
+ setNotebookUpdatePending(true);
+ void (async () => {
+ if (!(await saveRef.current())) return;
+ await repository.moveMemos({ memoIds: [memo.id], notebookId });
+ const result = await repository.getMemo(memo.id);
+ currentMemo.current = result.memo;
+ await onSaved(result.memo);
+ })().catch((caught) => setError(caught instanceof Error ? caught.message : t("poster.error"))).finally(() => { setNotebookUpdatePending(false); setMobileNotebookPickerOpen(false); });
+ }} />
+ </div>
+ <div className="flex shrink-0 items-center gap-1 pr-2">
+ <span role="status" className="hidden text-xs text-slate-500 sm:inline-flex">{t(readOnly ? "poster.readOnly" : saving ? "poster.saving" : dirty ? "poster.unsaved" : "poster.saved")}</span>
+ {onToggleDesktopFocusMode && <MemoEditorFocusModeButton desktopFocusMode={desktopFocusMode} onToggleDesktopFocusMode={onToggleDesktopFocusMode} />}
+ {onOpenExecutionCenter && <MemoEditorHeaderActions onOpenExecutionCenter={onOpenExecutionCenter} moreMenuItems={<DropdownMenuItem disabled={!canvasReady || busy || !initial} onClick={() => setExportOpen(true)}>{t("poster.design.export")}</DropdownMenuItem>} />}
+ </div>
+ </div>
+ <div className="flex min-h-9 items-center justify-end gap-2 overflow-x-auto px-4 py-0.5">
+ {!initial && (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() =>
+ downloadBlob(
+ new Blob([memo.contentMarkdown], { type: "text/markdown" }),
+ "poster-source.md",
+ )
+ }
+ >
+ {t("poster.design.downloadSource")}
+ </Button>
+ )}
+ {toast && (
+ <span role="status" className="text-xs text-emerald-600">
+ {toast}
+ </span>
+ )}
+ {toolButton(
+ t("poster.save"),
+ saving ? (
+ <LoaderCircle className="h-4 w-4 animate-spin" />
+ ) : (
+ <Save className="h-4 w-4" />
+ ),
+ () => {
+ void saveRef.current();
+ },
+ !editable || saving,
+ )}
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!canvasReady || busy || !initial}
+ onClick={() => void copyImage()}
+ >
+ <Copy className="h-3.5 w-3.5" />
+ {t("poster.design.copyImage")}
+ </Button>
+ <Button
+ size="sm"
+ disabled={!canvasReady || busy || !initial}
+ onClick={() => setExportOpen(true)}
+ >
+ <Download className="h-3.5 w-3.5" />
+ {t("poster.design.export")}
+ </Button>
+ </div>
+ </header>
+ {error && (
+ <div
+ role="alert"
+ className="flex items-center gap-2 border-b bg-amber-50 px-4 py-2 text-xs text-amber-900"
+ >
+ <span className="flex-1">{error}</span>
+ {toolButton(
+ t("poster.retry"),
+ <Redo2 className="h-3.5 w-3.5" />,
+ () => {
+ setError(null);
+ setCanvasRevision((value) => value + 1);
+ },
+ )}
+ </div>
+ )}
+ {recovery && (
+ <div className="flex items-center gap-3 border-b bg-amber-50 px-4 py-2 text-xs">
+ <span className="flex-1">{t("poster.recover")}</span>
+ <Button
+ size="sm"
+ onClick={() => {
+ if (recovery.baseHash !== currentMemo.current.contentHash) {
+ setError(t("poster.remoteChanged"));
+ return;
+ }
+ commit(recovery.document);
+ setTitle(recovery.title);
+ if (typeof recovery.tagsText === "string") setTagsText(recovery.tagsText);
+ setRecovery(null);
+ }}
+ >
+ {t("poster.restore")}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ downloadBlob(
+ new Blob([JSON.stringify(recovery)], {
+ type: "application/json",
+ }),
+ "poster-draft.json",
+ );
+ }}
+ >
+ {t("poster.downloadDraft")}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ setRecovery(null);
+ }}
+ >
+ {t("poster.later")}
+ </Button>
+ </div>
+ )}
+ <div className="flex h-12 shrink-0 items-center gap-1 overflow-x-auto border-b px-3">
+ {toolButton(
+ t("poster.design.templates"),
+ <PanelLeftClose className="h-4 w-4" />,
+ () => setLeftOpen(!leftOpen),
+ false,
+ leftOpen,
+ )}
+ <div className="mx-1 h-5 border-l" />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="min-w-32 justify-between text-xs"
+ >
+ {platform
+ ? zh
+ ? platform.zh
+ : platform.en
+ : `${document.width} × ${document.height}`}
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {PLATFORMS.map((entry) => (
+ <DropdownMenuItem
+ key={entry.id}
+ disabled={!editable}
+ onSelect={() => changePlatform(entry.id)}
+ >
+ {zh ? entry.zh : entry.en}
+ <span className="ml-auto pl-4 text-[10px] text-slate-400">
+ {entry.width}×{entry.height}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ setRightTab("canvas");
+ setRightOpen(true);
+ }}
+ >
+ {t("poster.design.customSize")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <div className="mx-1 h-5 border-l" />
+ {toolButton(
+ t("poster.text"),
+ <Type className="h-4 w-4" />,
+ () => addText("heading"),
+ !editable,
+ false,
+ true,
+ )}
+ {toolButton(
+ t("poster.design.shape"),
+ <Shapes className="h-4 w-4" />,
+ () => {
+ setLeftTab("assets");
+ setLeftOpen(true);
+ },
+ !editable,
+ false,
+ true,
+ )}
+ {toolButton(
+ t("poster.image"),
+ <ImagePlus className="h-4 w-4" />,
+ () => fileInput.current?.click(),
+ !editable,
+ false,
+ true,
+ )}
+ <div className="mx-1 h-5 border-l" />
+ {toolButton(
+ t("poster.design.select"),
+ <MousePointer2 className="h-4 w-4" />,
+ () => setTool("select"),
+ !editable,
+ tool === "select",
+ )}
+ {toolButton(
+ t("poster.design.pan"),
+ <Hand className="h-4 w-4" />,
+ () => setTool("hand"),
+ false,
+ tool === "hand",
+ )}
+ {toolButton(
+ t("poster.design.draw"),
+ <Pencil className="h-4 w-4" />,
+ () => setTool("draw"),
+ !editable,
+ tool === "draw",
+ )}
+ {tool === "draw" && (
+ <>
+ <input
+ type="color"
+ aria-label={t("poster.color")}
+ value={brushColor}
+ onChange={(event) => setBrushColor(event.target.value)}
+ className="h-6 w-7"
+ />
+ <input
+ type="range"
+ aria-label={t("poster.design.strokeWidth")}
+ min="1"
+ max="80"
+ value={brushWidth}
+ onChange={(event) => setBrushWidth(Number(event.target.value))}
+ className="w-20"
+ />
+ </>
+ )}
+ <div className="mx-1 h-5 border-l" />
+ {toolButton(
+ t("poster.undo"),
+ <Undo2 className="h-4 w-4" />,
+ () => travel(true),
+ !editable || !undo.current.length,
+ )}
+ {toolButton(
+ t("poster.redo"),
+ <Redo2 className="h-4 w-4" />,
+ () => travel(false),
+ !editable || !redo.current.length,
+ )}
+ <div className="flex-1" />
+ {toolButton(
+ t("poster.design.grid"),
+ <Grid3X3 className="h-4 w-4" />,
+ () => setGrid(!grid),
+ false,
+ grid,
+ )}
+ {toolButton(
+ t("poster.design.snap"),
+ <ScanLine className="h-4 w-4" />,
+ () => setSnap(!snap),
+ false,
+ snap,
+ )}
+ {toolButton(
+ t("poster.design.safeArea"),
+ <RectangleHorizontal className="h-4 w-4" />,
+ () => setSafeArea(!safeArea),
+ false,
+ safeArea,
+ )}
+ {toolButton(
+ t("poster.properties"),
+ <PanelRightClose className="h-4 w-4" />,
+ () => setRightOpen(!rightOpen),
+ false,
+ rightOpen,
+ )}
+ </div>
+ <input
+ ref={fileInput}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ className="hidden"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (file && editable) void upload(file);
+ }}
+ />
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ {leftOpen && (
+ <aside className="flex w-[252px] shrink-0 flex-col border-r bg-card">
+ <div className="grid h-11 shrink-0 grid-cols-2 border-b px-2 text-xs">
+ {(["templates", "assets"] as const).map((tab) => (
+ <button
+ key={tab}
+ className={`border-b-2 ${leftTab === tab ? "border-emerald-600 font-semibold text-emerald-700" : "border-transparent text-slate-500"}`}
+ onClick={() => setLeftTab(tab)}
+ >
+ {t(`poster.design.${tab}`)}
+ </button>
+ ))}
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {leftTab === "templates" ? (
+ <PosterTemplatePanel
+ width={document.width}
+ height={document.height}
+ platformId={platform?.id}
+ templateId={document.templateId}
+ zh={zh}
+ disabled={!editable}
+ onApply={(id) => void applyTemplate(id)}
+ />
+ ) : (
+ <PosterAssetsPanel
+ repository={repository}
+ disabled={!editable}
+ onUpload={() => fileInput.current?.click()}
+ onResource={(resource) => {
+ void readResource(resource.id)
+ .then((blob) =>
+ upload(
+ new File([blob], resource.filename ?? "image.png", {
+ type: resource.mimeType ?? blob.type,
+ }),
+ ),
+ )
+ .catch((error) => setError(String(error)));
+ }}
+ onText={addText}
+ onShape={addShape}
+ />
+ )}
+ </div>
+ </aside>
+ )}
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <div
+ ref={viewport}
+ className="relative min-h-0 min-w-0 flex-1 overflow-auto bg-[#eef0f3]"
+ data-poster-canvas
+ style={{
+ backgroundImage:
+ "radial-gradient(#c7cdd5 1px, transparent 1px)",
+ backgroundSize: "16px 16px",
+ }}
+ onDragOver={(event) => {
+ if (editable) event.preventDefault();
+ }}
+ onDrop={(event) => {
+ event.preventDefault();
+ const file = event.dataTransfer.files[0];
+ if (file && editable) void upload(file);
+ }}
+ onPaste={(event) => {
+ const file = [...event.clipboardData.files].find((file) =>
+ file.type.startsWith("image/"),
+ );
+ if (file && editable) {
+ event.preventDefault();
+ void upload(file);
+ }
+ }}
+ onPointerDownCapture={(event) => {
+ if (
+ (tool === "hand" || spaceHeld || event.button === 1) &&
+ viewport.current
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ panStart.current = {
+ x: event.clientX,
+ y: event.clientY,
+ left: viewport.current.scrollLeft,
+ top: viewport.current.scrollTop,
+ };
+ viewport.current.setPointerCapture(event.pointerId);
+ }
+ }}
+ onPointerMove={(event) => {
+ if (panStart.current && viewport.current) {
+ viewport.current.scrollLeft =
+ panStart.current.left - event.clientX + panStart.current.x;
+ viewport.current.scrollTop =
+ panStart.current.top - event.clientY + panStart.current.y;
+ }
+ }}
+ onPointerUp={() => {
+ panStart.current = null;
+ }}
+ onPointerCancel={() => {
+ panStart.current = null;
+ }}
+ >
+ <div
+ className="flex min-h-full min-w-full items-center justify-center p-14"
+ style={{
+ width: document.width * zoom + 112,
+ height: document.height * zoom + 112,
+ }}
+ >
+ <div
+ className="relative shrink-0 shadow-[0_8px_32px_rgba(15,23,42,0.14)]"
+ style={{
+ width: document.width * zoom,
+ height: document.height * zoom,
+ }}
+ >
+ <div ref={canvasHost} />
+ {grid && (
+ <div
+ className="pointer-events-none absolute inset-0"
+ style={{
+ backgroundImage:
+ "linear-gradient(to right,#16a06e22 1px,transparent 1px),linear-gradient(to bottom,#16a06e22 1px,transparent 1px)",
+ backgroundSize: `${(document.width * zoom) / 12}px ${(document.width * zoom) / 12}px`,
+ }}
+ />
+ )}
+ {safeArea && (
+ <div
+ className="pointer-events-none absolute border border-dashed border-rose-500/70"
+ style={{
+ left: safeMargin * zoom,
+ top: safeMargin * zoom,
+ right: safeMargin * zoom,
+ bottom: safeMargin * zoom,
+ }}
+ />
+ )}
+ {safeArea &&
+ platform?.avoid.map((zone, index) => (
+ <div
+ key={index}
+ className="pointer-events-none absolute border border-dashed border-rose-500/60 bg-rose-500/10 text-[9px] text-rose-600"
+ style={{
+ left: zone.x * document.width * zoom,
+ top: zone.y * document.height * zoom,
+ width: zone.w * document.width * zoom,
+ height: zone.h * document.height * zoom,
+ }}
+ >
+ {zh ? zone.zh : zone.en}
+ </div>
+ ))}
+ {guides.x !== undefined && (
+ <div
+ className="pointer-events-none absolute inset-y-0 border-l border-fuchsia-500"
+ style={{ left: guides.x * zoom }}
+ />
+ )}
+ {guides.y !== undefined && (
+ <div
+ className="pointer-events-none absolute inset-x-0 border-t border-fuchsia-500"
+ style={{ top: guides.y * zoom }}
+ />
+ )}
+ </div>
+ </div>
+ {!canvasReady && (
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
+ <LoaderCircle className="h-7 w-7 animate-spin text-emerald-600" />
+ </div>
+ )}
+ </div>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem
+ disabled={!editable || !selectedIds.length}
+ onSelect={duplicate}
+ >
+ {t("poster.design.duplicate")}
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!editable || selectedIds.length < 2}
+ onSelect={() => group(false)}
+ >
+ {t("poster.design.group")}
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!editable || !selectedIds.length}
+ onSelect={() => group(true)}
+ >
+ {t("poster.design.ungroup")}
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ disabled={!editable || !selectedIds.length}
+ onSelect={() => moveLayer(true)}
+ >
+ {t("poster.front")}
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!editable || !selectedIds.length}
+ onSelect={() => moveLayer(false)}
+ >
+ {t("poster.backLayer")}
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ disabled={!editable || !selectedIds.length}
+ onSelect={removeSelected}
+ >
+ {t("poster.delete")}
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ {rightOpen && (
+ <aside className="flex w-[280px] shrink-0 flex-col border-l bg-card">
+ <div className="grid h-11 shrink-0 grid-cols-2 border-b px-2 text-xs">
+ {(["properties", "layers", "canvas"] as const).map((tab) => (
+ <button
+ key={tab}
+ className={`border-b-2 ${rightTab === tab ? "border-emerald-600 font-semibold text-emerald-700" : "border-transparent text-slate-500"}`}
+ onClick={() => setRightTab(tab)}
+ >
+ {tab === "canvas"
+ ? t("poster.design.canvasTab")
+ : t(`poster.${tab}`)}
+ </button>
+ ))}
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {rightTab === "properties" ? (
+ <PosterInspector
+ elements={selectedElements}
+ disabled={!editable}
+ zh={zh}
+ onPatch={updateElement}
+ onAlign={align}
+ onDuplicate={duplicate}
+ onDelete={removeSelected}
+ onImageFit={(cover) => void imageFit(cover)}
+ />
+ ) : rightTab === "layers" ? (
+ <PosterLayers
+ elements={document.elements}
+ selected={selectedIds}
+ disabled={!editable}
+ onSelect={selectLayer}
+ onChange={(id, patch) => patchIds([id], patch, true)}
+ onGroup={group}
+ onMove={moveLayer}
+ />
+ ) : (
+ <PosterCanvasSettings
+ document={document}
+ disabled={!editable}
+ zh={zh}
+ onChange={commit}
+ onResize={(width, height) => void resize(width, height)}
+ onPlatform={changePlatform}
+ />
+ )}
+ </div>
+ </aside>
+ )}
+ </div>
+ <footer className="flex h-11 shrink-0 items-center gap-2 border-t px-4 text-[11px] text-slate-500">
+ <span>
+ {document.width} × {document.height} px
+ </span>
+ <span className="hidden truncate md:inline">
+ ·{" "}
+ {t(
+ selectedIds.length
+ ? "poster.design.selectionCount"
+ : "poster.design.canvasHint",
+ { count: selectedIds.length },
+ )}
+ </span>
+ {document.sourceMemoId && (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={!editable || saving}
+ onClick={() => void insertInSource()}
+ >
+ {t("poster.insertSource")}
+ </Button>
+ )}
+ <div className="flex-1" />
+ <button
+ className="h-7 w-7 rounded hover:bg-slate-100"
+ aria-label={t("poster.design.zoomOut")}
+ onClick={() => {
+ setAutoFit(false);
+ setZoom(Math.max(0.1, zoom / 1.2));
+ }}
+ >
+ −
+ </button>
+ <select
+ aria-label={t("poster.design.zoom")}
+ className="h-7 rounded border bg-card px-1 text-xs"
+ value={zoom.toFixed(3)}
+ onChange={(event) => {
+ setAutoFit(false);
+ setZoom(Number(event.target.value));
+ }}
+ >
+ <option value={zoom.toFixed(3)}>{Math.round(zoom * 100)}%</option>
+ {[0.25, 0.5, 0.75, 1, 1.5, 2]
+ .filter((value) => value.toFixed(3) !== zoom.toFixed(3))
+ .map((value) => (
+ <option key={value} value={value.toFixed(3)}>
+ {value * 100}%
+ </option>
+ ))}
+ </select>
+ <button
+ className="h-7 w-7 rounded hover:bg-slate-100"
+ aria-label={t("poster.design.zoomIn")}
+ onClick={() => {
+ setAutoFit(false);
+ setZoom(Math.min(2, zoom * 1.2));
+ }}
+ >
+ +
+ </button>
+ {toolButton(
+ t("poster.design.fit"),
+ <Maximize2 className="h-3.5 w-3.5" />,
+ () => {
+ setAutoFit(true);
+ setZoom(fitZoom);
+ },
+ false,
+ false,
+ true,
+ )}
+ </footer>
+ <Dialog open={exportOpen} onOpenChange={setExportOpen}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t("poster.design.export")}</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="grid grid-cols-3 gap-2">
+ {(["png", "jpeg", "webp"] as const).map((format) => (
+ <Button
+ key={format}
+ variant={exportFormat === format ? "solid" : "outline"}
+ onClick={() => setExportFormat(format)}
+ >
+ {format.toUpperCase()}
+ </Button>
+ ))}
+ </div>
+ <label className="flex items-center justify-between text-sm">
+ {t("poster.design.exportScale")}
+ <select
+ className="rounded border p-2"
+ value={exportScale}
+ onChange={(event) => setExportScale(Number(event.target.value))}
+ >
+ {[1, 2, 3]
+ .filter(
+ (scale) =>
+ Math.max(document.width, document.height) * scale <= 8192,
+ )
+ .map((scale) => (
+ <option key={scale} value={scale}>
+ {scale}×
+ </option>
+ ))}
+ </select>
+ </label>
+ {exportFormat !== "png" && (
+ <label className="flex items-center justify-between text-sm">
+ {t("poster.design.exportQuality")}
+ <input
+ type="range"
+ min=".5"
+ max="1"
+ step=".01"
+ value={exportQuality}
+ onChange={(event) =>
+ setExportQuality(Number(event.target.value))
+ }
+ />
+ <span>{Math.round(exportQuality * 100)}%</span>
+ </label>
+ )}
+ <p className="rounded-lg bg-slate-50 p-3 text-xs text-slate-500">
+ {Math.round(document.width * exportScale)} ×{" "}
+ {Math.round(document.height * exportScale)} px
+ </p>
+ <Button
+ className="w-full"
+ disabled={busy}
+ onClick={() => void exportImage(exportFormat)}
+ >
+ {busy ? (
+ <LoaderCircle className="h-4 w-4 animate-spin" />
+ ) : (
+ <Download className="h-4 w-4" />
+ )}
+ {t("poster.design.download")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ {!readOnly && !aiAssistantOpen && <IconTooltip side="left" label={t("aiAssistant.open")}>
+ <Button variant="outline" size="icon" data-ai-assistant-launcher="" aria-label={t("aiAssistant.open")}
+ className="absolute bottom-[calc(1.25rem+env(safe-area-inset-bottom))] right-5 z-30 size-11 rounded-full border-slate-200 bg-card text-slate-950 shadow-[0_8px_24px_rgba(15,23,42,0.14)]"
+ onClick={() => setAiSidebarOpen(true)}><Sparkles className="size-5" strokeWidth={1.75} /></Button>
+ </IconTooltip>}
+ </div>
+ <AiSidebarErrorBoundary open={aiAssistantOpen} onOpenChange={setAiSidebarOpen}>
+ <AiSidebar open={aiAssistantOpen} onOpenChange={setAiSidebarOpen} companionAvailable={companionAvailable}
+ contentMarkdown={`${posterFallbackMarkdown(document)}\n\nEditable poster canvas: ${document.width} × ${document.height}. Use get_poster and update_poster to edit elements; do not replace the note Markdown.`}
+ selectionMarkdown={selectedIds.length ? `Selected poster element IDs: ${selectedIds.join(", ")}. Preserve elements outside this selection unless the user explicitly asks to change the whole poster.` : undefined}
+ memoId={memo.id} notebookId={memo.notebookId} noteTitle={title}
+ notebookTitle={notebookOptions.find((item) => item.id === memo.notebookId)?.name}
+ beforeCompanionApply={async () => { if (!(await saveRef.current())) throw new Error("save failed"); await beforeCompanionApply?.(); }}
+ onCompanionNotesChanged={onCompanionNotesChanged} onOpenCompanionNote={onOpenCompanionNote} />
+ </AiSidebarErrorBoundary>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/TableEditorPane.tsx b/apps/web/src/components/TableEditorPane.tsx
index 4c359fe7..ef9ccc50 100644
--- a/apps/web/src/components/TableEditorPane.tsx
+++ b/apps/web/src/components/TableEditorPane.tsx
@@ -526,11 +526,27 @@ export const TableEditorPane = ({
const pendingUploadIdsRef = useRef(new Set<string>());
const savedSnapshotRef = useRef(parsed ? snapshotOf(memo.title ?? "", parsed) : "");
const saveRef = useRef<() => void>(() => undefined);
- if (memo.revision >= memoRef.current.revision) memoRef.current = memo;
titleRef.current = title;
documentRef.current = document;
editingRef.current = editing;
+ useEffect(() => {
+ // Keep the displayed table and its save base in sync after AI/server edits.
+ // An active local edit must retain its original revision for conflict checks.
+ if (!parsed || dirty || saving || editing || memo.revision < memoRef.current.revision) return;
+ const nextTitle = memo.title ?? "";
+ const nextSnapshot = snapshotOf(nextTitle, parsed);
+ memoRef.current = memo;
+ if (nextSnapshot === savedSnapshotRef.current) return;
+ setTitle(nextTitle);
+ titleRef.current = nextTitle;
+ setDocument(parsed);
+ documentRef.current = parsed;
+ savedSnapshotRef.current = nextSnapshot;
+ setSaveError(null);
+ setSaveFailed(false);
+ }, [dirty, editing, memo, parsed, saving]);
+
useEffect(() => {
editSessionRef.current = null;
setEditSessionReady(false);
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index fcf0f284..69988cba 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -47,7 +47,7 @@ import {
} from "@/lib/mobile-editor";
import { cn } from "@/lib/utils";
import { isBrowserOffline, isBrowserOnline } from "@/lib/network-status";
-import { createDefaultDiagramDocument, createDefaultInfographicDocument, createDefaultTableDocument, diagramFallbackMarkdown, getNotebookScopeIds, hasTableDocumentMarker, infographicFallbackMarkdown, markdownToDoc, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeDiagramDocument, serializeInfographicDocument, serializeTableDocument, tableFallbackMarkdown, type NoteCreateKind, type Notebook, type AuthUser, type MemoSummary, type MemoDetail, type MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";
+import { createDefaultDiagramDocument, createDefaultInfographicDocument, hasPosterDocumentMarker, posterFallbackMarkdown, serializePosterDocument, createDefaultTableDocument, diagramFallbackMarkdown, getNotebookScopeIds, hasTableDocumentMarker, infographicFallbackMarkdown, markdownToDoc, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeDiagramDocument, serializeInfographicDocument, serializeTableDocument, tableFallbackMarkdown, type NoteCreateKind, type Notebook, type AuthUser, type MemoSummary, type MemoDetail, type MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";
import { toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";
import type {
Pane,
@@ -143,6 +143,7 @@ import { findMatchingMemoResource } from "@/lib/staged-resource-repair";
const EditorPane = lazy(() => import("./EditorPane").then((module) => ({ default: module.EditorPane })));
const DiagramEditorPane = lazy(() => import("./DiagramEditorPane"));
const TableEditorPane = lazy(() => import("./TableEditorPane"));
+const PosterEditorPane = lazy(() => import("./PosterEditorPane"));
const InfographicEditorPane = lazy(() => import("./InfographicEditorPane"));
const AssetsPane = lazy(() => import("./AssetsPane").then((module) => ({ default: module.AssetsPane })));
const SettingsPane = lazy(() => import("./SettingsPane").then((module) => ({ default: module.SettingsPane })));
@@ -1231,7 +1232,7 @@ export const WorkspaceApp = ({
const revealCreatedMemo = (memo: MemoDetail) => {
const targetNotebookId = memo.notebookId;
- const isStructuredNote = Boolean(parseDiagramDocument(memo.contentMarkdown) || parseTableDocument(memo.contentMarkdown) || parseInfographicDocument(memo.contentMarkdown));
+ const isStructuredNote = Boolean(parseDiagramDocument(memo.contentMarkdown) || parseTableDocument(memo.contentMarkdown) || parseInfographicDocument(memo.contentMarkdown) || hasPosterDocumentMarker(memo.contentMarkdown));
setMemoView("notebook");
setSearch("");
@@ -1457,6 +1458,7 @@ export const WorkspaceApp = ({
const selectedMemo = memoQuery.data?.memo ?? cachedSelectedMemo;
const selectedDiagram = parseDiagramDocument(selectedMemo?.contentMarkdown);
const selectedTableNote = hasTableDocumentMarker(selectedMemo?.contentMarkdown);
+ const selectedPosterNote = hasPosterDocumentMarker(selectedMemo?.contentMarkdown);
const selectedInfographicNote = Boolean(parseInfographicDocument(selectedMemo?.contentMarkdown));
const desktopNotebookSidebarCollapsed = Boolean(isDesktop && notebookSidebarCollapsed);
const desktopFocusModeActive = Boolean(
@@ -1861,6 +1863,18 @@ export const WorkspaceApp = ({
setTemplatesOpen(false);
setMobileBottomNavActive("home");
creatingMemoSelectionRef.current = true;
+ if (kind === "poster") {
+ void import("@/lib/poster-design/templates").then(async ({ buildPosterDesign }) => {
+ const poster = await buildPosterDesign({ id: "folio", title: t("poster.defaultHeading"), subtitle: t("poster.defaultSubtitle"), width: 1080, height: 1440, zh: i18n.language.startsWith("zh") });
+ createMemoMutation.mutate({ notebookId: targetNotebookId, title: t("poster.name"), contentJson: markdownToDoc(posterFallbackMarkdown(poster)), contentMarkdown: serializePosterDocument(poster), tags: [] });
+ }).catch(() => {
+ createMemoInFlightRef.current = false;
+ clearPendingCreatedMemo();
+ setCreatedMemoEditId(null);
+ setAppNoticeDialog({ title: t("poster.name"), description: t("poster.error") });
+ });
+ return;
+ }
if (kind === "infographic") {
const infographic = createDefaultInfographicDocument();
createMemoMutation.mutate({
@@ -3226,7 +3240,7 @@ export const WorkspaceApp = ({
const openTextNote = selectedMemo?.id === memoId
&& !selectedDiagram
&& !selectedTableNote
- && !selectedInfographicNote;
+ && !selectedInfographicNote && !selectedPosterNote;
if (openTextNote) {
memoDocumentActionIdRef.current += 1;
setMemoDocumentActionRequest({
@@ -3394,6 +3408,43 @@ export const WorkspaceApp = ({
}}
onOpenCompanionNote={handleOpenPluginNote}
/>
+ ) : selectedMemo && selectedPosterNote ? (
+ <PosterEditorPane
+ key={selectedMemo.id}
+ memo={selectedMemo}
+ notebooks={notebooks}
+ repository={repository}
+ readOnly={memoView === "trash" || selectedMemo.isDeleted}
+ desktopFocusMode={desktopFocusModeActive}
+ onBackToList={() => {
+ clearPendingCreatedMemo();
+ setSelectedMemoId(null);
+ setActivePane("memos");
+ }}
+ onOpenExecutionCenter={handleOpenExecutionCenter}
+ onToggleDesktopFocusMode={toggleDesktopFocusMode}
+ aiAssistantOpenToken={noteAiAssistantOpenToken}
+ shortcutSettings={shortcutSettings}
+ companionAvailable={authRequired && Boolean(user) && !demoMode}
+ beforeCompanionApply={async () => {
+ const { assertCompanionChangesSynced } = await import("@/lib/companion-actions");
+ await assertCompanionChangesSynced(localDataScope);
+ }}
+ onCompanionNotesChanged={async () => {
+ const result = await refreshWorkspaceFromServer("manual");
+ if ("skipped" in result && result.skipped) throw new Error("Workspace refresh was skipped.");
+ }}
+ onOpenCompanionNote={handleOpenPluginNote}
+ onSaved={async (memo) => {
+ await putLocalMemo(localDataScope, memo);
+ cacheMemoDetail(queryClient, memo, memoView);
+ updateMemoSummaryInLists(queryClient, memoToSummary(memo));
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["memos"], refetchType: "inactive" }),
+ queryClient.invalidateQueries({ queryKey: ["notebooks"], refetchType: "inactive" }),
+ ]);
+ }}
+ />
) : selectedMemo && selectedInfographicNote ? (
<InfographicEditorPane
key={selectedMemo.id}
@@ -3456,6 +3507,11 @@ export const WorkspaceApp = ({
/>
) : (
<EditorPane
+ onCreatePoster={async (source, text) => {
+ const { buildPosterDesign } = await import("@/lib/poster-design/templates");
+ const poster = { ...await buildPosterDesign({ id: "folio", title: (source.title ?? t("poster.defaultHeading")).slice(0, 160), subtitle: text.slice(0, 240), width: 1080, height: 1440, zh: i18n.language.startsWith("zh") }), sourceMemoId: source.id };
+ await createMemoMutation.mutateAsync({ notebookId: source.notebookId, title: `${source.title || t("poster.name")} · ${t("poster.name")}`, contentJson: markdownToDoc(posterFallbackMarkdown(poster)), contentMarkdown: serializePosterDocument(poster), tags: source.tags });
+ }}
demoMode={demoMode}
onOpenExecutionCenter={handleOpenExecutionCenter}
memo={selectedMemo}
diff --git a/apps/web/src/components/WorkspaceMobileChrome.tsx b/apps/web/src/components/WorkspaceMobileChrome.tsx
index 75f10b96..502f33b1 100644
--- a/apps/web/src/components/WorkspaceMobileChrome.tsx
+++ b/apps/web/src/components/WorkspaceMobileChrome.tsx
@@ -116,7 +116,12 @@ export const MobileBottomNav = ({
<span className="min-w-0 flex-1 truncate">{t("infographic.name")}</span>
<span className={BETA_BADGE_CLASSNAME}>Beta</span>
</DropdownMenuItem>
- <DropdownMenuItem className="gap-2 text-xs leading-5" onSelect={() => onCreateMemo("table")}>
+ <DropdownMenuItem className="gap-2 text-xs leading-5" onSelect={() => onCreateMemo("poster")}>
+ <FileText className="h-4 w-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">{t("poster.name")}</span>
+ <span className={BETA_BADGE_CLASSNAME}>Beta</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem className="gap-2 text-xs leading-5" onSelect={() => onCreateMemo("table")}>
<Table2 className="h-4 w-4 shrink-0" />
<span className="min-w-0 flex-1 truncate">{t("structuredTable.name")}</span>
<span className={BETA_BADGE_CLASSNAME}>Beta</span>
diff --git a/apps/web/src/components/ai-sidebar/AiSidebar.tsx b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
index 9668c2b2..29e1e397 100644
--- a/apps/web/src/components/ai-sidebar/AiSidebar.tsx
+++ b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
@@ -1004,6 +1004,9 @@ function AiSidebarSession({
active.current = null;
locked.current = false;
setBusy(false);
+ // Local agents write through MCP, outside the renderer's query cache.
+ // Also refresh failed runs, which may have completed some writes.
+ void onCompanionNotesChanged?.().catch(() => undefined);
}
}
};
diff --git a/apps/web/src/components/poster/PosterAssetsPanel.tsx b/apps/web/src/components/poster/PosterAssetsPanel.tsx
new file mode 100644
index 00000000..410905df
--- /dev/null
+++ b/apps/web/src/components/poster/PosterAssetsPanel.tsx
@@ -0,0 +1,239 @@
+import { useEffect, useRef, useState } from "react";
+import {
+ ArrowUpRight,
+ Circle,
+ ImagePlus,
+ LoaderCircle,
+ RectangleHorizontal,
+ Search,
+ Sparkles,
+ Star,
+ Type,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import type { EdgeEverRepository } from "@/lib/repository";
+import type { ResourceListItem } from "@edgeever/shared";
+import { PosterSection } from "./PosterControls";
+function ResourceThumbnail({
+ resource,
+ repository,
+}: {
+ resource: ResourceListItem;
+ repository: EdgeEverRepository;
+}) {
+ const host = useRef<HTMLDivElement>(null),
+ [visible, setVisible] = useState(false),
+ [url, setUrl] = useState<string>();
+ useEffect(() => {
+ const observer = new IntersectionObserver(([entry]) => {
+ if (entry?.isIntersecting) {
+ setVisible(true);
+ observer.disconnect();
+ }
+ });
+ if (host.current) observer.observe(host.current);
+ return () => observer.disconnect();
+ }, []);
+ useEffect(() => {
+ if (!visible) return;
+ let cancelled = false,
+ url: string | undefined;
+ void repository
+ .readResource(resource.id)
+ .then((blob) => {
+ url = URL.createObjectURL(blob);
+ if (cancelled) URL.revokeObjectURL(url);
+ else setUrl(url);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ if (url) URL.revokeObjectURL(url);
+ };
+ }, [visible, resource.id, repository]);
+ return (
+ <div
+ ref={host}
+ className="flex aspect-square items-center justify-center overflow-hidden rounded-md bg-slate-100"
+ >
+ {url ? (
+ <img
+ src={url}
+ alt={resource.filename ?? "Image"}
+ className="h-full w-full object-cover"
+ />
+ ) : (
+ <ImagePlus className="h-5 w-5 text-slate-300" />
+ )}
+ </div>
+ );
+}
+export function PosterAssetsPanel({
+ repository,
+ disabled,
+ onUpload,
+ onResource,
+ onShape,
+ onText,
+}: {
+ repository: EdgeEverRepository;
+ disabled: boolean;
+ onUpload: () => void;
+ onResource: (resource: ResourceListItem) => void;
+ onShape: (shape: string) => void;
+ onText: (style: "heading" | "subtitle" | "body" | "badge") => void;
+}) {
+ const { t } = useTranslation(),
+ [resources, setResources] = useState<ResourceListItem[]>([]),
+ [search, setSearch] = useState(""),
+ [loading, setLoading] = useState(true),
+ [failed, setFailed] = useState(false),
+ [retry, setRetry] = useState(0);
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ setFailed(false);
+ void repository
+ .listResources()
+ .then(({ resources }) => {
+ if (!cancelled)
+ setResources(
+ resources.filter(
+ (resource) =>
+ ["image/png", "image/jpeg", "image/webp"].includes(
+ resource.mimeType ?? "",
+ ) && !(resource.filename ?? "").startsWith("poster-preview"),
+ ),
+ );
+ })
+ .catch(() => {
+ if (!cancelled) setFailed(true);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [repository, retry]);
+ const shapes = [
+ { id: "rect", Icon: RectangleHorizontal },
+ { id: "ellipse", Icon: Circle },
+ { id: "pill", Icon: RectangleHorizontal },
+ { id: "line", Icon: RectangleHorizontal },
+ { id: "arrow", Icon: ArrowUpRight },
+ { id: "star", Icon: Star },
+ { id: "sparkle", Icon: Sparkles },
+ ];
+ return (
+ <div className="space-y-4 p-3">
+ <PosterSection title={t("poster.text")}>
+ <div className="space-y-2">
+ {(["heading", "subtitle", "body", "badge"] as const).map(
+ (style, index) => (
+ <button
+ key={style}
+ disabled={disabled}
+ onClick={() => onText(style)}
+ className="flex w-full items-center gap-2 rounded-lg border border-slate-200 bg-card p-3 text-left hover:border-emerald-400"
+ >
+ <Type className="h-4 w-4 text-slate-400" />
+ <span
+ className={
+ index === 0
+ ? "text-xl font-bold"
+ : index === 1
+ ? "text-base font-medium"
+ : "text-xs"
+ }
+ >
+ {t(`poster.design.textStyles.${style}`)}
+ </span>
+ </button>
+ ),
+ )}
+ </div>
+ </PosterSection>
+ <PosterSection title={t("poster.design.shape")}>
+ <div className="grid grid-cols-4 gap-2">
+ {shapes.map(({ id, Icon }) => (
+ <button
+ key={id}
+ disabled={disabled}
+ aria-label={t(`poster.design.shapes.${id}`)}
+ onClick={() => onShape(id)}
+ className="flex aspect-square items-center justify-center rounded-lg border border-slate-200 bg-card hover:border-emerald-400"
+ >
+ <Icon className="h-6 w-6 stroke-[1.5]" />
+ </button>
+ ))}
+ </div>
+ </PosterSection>
+ <PosterSection title={t("poster.design.images")}>
+ <Button
+ size="sm"
+ className="w-full"
+ disabled={disabled}
+ onClick={onUpload}
+ >
+ <ImagePlus className="h-4 w-4" />
+ {t("poster.design.uploadImage")}
+ </Button>
+ <div className="relative">
+ <Search className="absolute left-2 top-2.5 h-3.5 w-3.5 text-slate-400" />
+ <Input
+ aria-label={t("poster.design.searchImages")}
+ placeholder={t("poster.design.searchImages")}
+ className="h-8 pl-7 text-xs"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ />
+ </div>
+ {loading ? (
+ <div className="flex justify-center py-8">
+ <LoaderCircle className="h-5 w-5 animate-spin text-slate-400" />
+ </div>
+ ) : failed ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="w-full"
+ onClick={() => setRetry(retry + 1)}
+ >
+ {t("poster.retry")}
+ </Button>
+ ) : (
+ <div className="grid grid-cols-2 gap-2">
+ {resources
+ .filter((resource) =>
+ (resource.filename ?? "")
+ .toLowerCase()
+ .includes(search.toLowerCase()),
+ )
+ .map((resource) => (
+ <button
+ key={resource.id}
+ disabled={disabled}
+ className="space-y-1 text-left"
+ onClick={() => onResource(resource)}
+ >
+ <ResourceThumbnail
+ resource={resource}
+ repository={repository}
+ />
+ <p className="truncate text-[10px] text-slate-500">
+ {resource.filename}
+ </p>
+ </button>
+ ))}
+ </div>
+ )}
+ <p className="text-[10px] leading-relaxed text-slate-400">
+ {t("poster.design.imageLibraryHint")}
+ </p>
+ </PosterSection>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/poster/PosterCanvasSettings.tsx b/apps/web/src/components/poster/PosterCanvasSettings.tsx
new file mode 100644
index 00000000..e725069f
--- /dev/null
+++ b/apps/web/src/components/poster/PosterCanvasSettings.tsx
@@ -0,0 +1,169 @@
+import { useTranslation } from "react-i18next";
+import type { PosterDocument } from "@edgeever/shared";
+import { PLATFORMS } from "@/lib/poster-design/templates";
+import { PosterColor, PosterNumber, PosterSection } from "./PosterControls";
+export function PosterCanvasSettings({
+ document,
+ disabled,
+ zh,
+ onChange,
+ onResize,
+ onPlatform,
+}: {
+ document: PosterDocument;
+ disabled: boolean;
+ zh: boolean;
+ onChange: (document: PosterDocument) => void;
+ onResize: (width: number, height: number) => void;
+ onPlatform: (id: string) => void;
+}) {
+ const { t } = useTranslation();
+ const gradient = document.backgroundGradient;
+ return (
+ <div className="space-y-4 p-4">
+ <PosterSection title={t("poster.design.platform")}>
+ <div className="grid grid-cols-2 gap-2">
+ {PLATFORMS.map((platform) => (
+ <button
+ key={platform.id}
+ disabled={disabled}
+ className={`rounded-lg border p-2 text-left transition ${platform.width === document.width && platform.height === document.height && (!document.platformId || document.platformId === platform.id) ? "border-emerald-500 bg-emerald-50/60" : "border-slate-200 hover:border-emerald-300"}`}
+ onClick={() => onPlatform(platform.id)}
+ >
+ <div className="truncate text-[11px] font-medium">
+ {zh ? platform.zh : platform.en}
+ </div>
+ <div className="mt-1 text-[10px] tabular-nums text-slate-400">
+ {platform.width} × {platform.height}
+ </div>
+ </button>
+ ))}
+ </div>
+ </PosterSection>
+ <PosterSection title={t("poster.design.customSize")}>
+ <div className="grid grid-cols-2 gap-2">
+ <PosterNumber
+ label={t("poster.design.width")}
+ min={320}
+ max={4096}
+ value={document.width}
+ disabled={disabled}
+ onChange={(width) => onResize(Math.round(width), document.height)}
+ />
+ <PosterNumber
+ label={t("poster.design.height")}
+ min={320}
+ max={4096}
+ value={document.height}
+ disabled={disabled}
+ onChange={(height) => onResize(document.width, Math.round(height))}
+ />
+ </div>
+ </PosterSection>
+ <PosterSection title={t("poster.background")}>
+ <div className="grid grid-cols-2 rounded-md bg-slate-100/70 p-1 text-xs">
+ {[false, true].map((value) => (
+ <button
+ key={String(value)}
+ disabled={disabled}
+ aria-pressed={Boolean(gradient) === value}
+ className={`rounded px-2 py-1.5 ${Boolean(gradient) === value ? "bg-card shadow-sm" : "text-slate-500"}`}
+ onClick={() =>
+ onChange({
+ ...document,
+ backgroundGradient: value
+ ? {
+ kind: "linear",
+ from: document.background,
+ to: "#baf264",
+ angle: 120,
+ }
+ : undefined,
+ })
+ }
+ >
+ {t(value ? "poster.design.gradient" : "poster.design.solid")}
+ </button>
+ ))}
+ </div>
+ <PosterColor
+ label={t(
+ gradient ? "poster.design.gradientFrom" : "poster.background",
+ )}
+ value={gradient?.from ?? document.background}
+ disabled={disabled}
+ swatches
+ onChange={(color) =>
+ onChange({
+ ...document,
+ background: color,
+ backgroundGradient: gradient
+ ? { ...gradient, from: color }
+ : undefined,
+ })
+ }
+ />
+ {gradient && (
+ <>
+ <PosterColor
+ label={t("poster.design.gradientTo")}
+ value={gradient.to}
+ disabled={disabled}
+ onChange={(to) =>
+ onChange({
+ ...document,
+ backgroundGradient: { ...gradient, to },
+ })
+ }
+ />
+ <PosterNumber
+ label={t("poster.design.rotation")}
+ value={gradient.angle}
+ min={-360}
+ max={360}
+ disabled={disabled}
+ onChange={(angle) =>
+ onChange({
+ ...document,
+ backgroundGradient: { ...gradient, angle },
+ })
+ }
+ />
+ <div className="grid grid-cols-3 gap-2">
+ {[
+ ["#f4efe4", "#ffdbbc"],
+ ["#dbeafe", "#ddd6fe"],
+ ["#07130b", "#16a06e"],
+ ["#fce7f3", "#fb7185"],
+ ["#dcfce7", "#baf264"],
+ ["#111827", "#4f46e5"],
+ ].map(([from, to]) => (
+ <button
+ key={from}
+ disabled={disabled}
+ className="h-8 rounded-md border border-black/5"
+ aria-label={`${from} ${to}`}
+ style={{
+ background: `linear-gradient(120deg,${from},${to})`,
+ }}
+ onClick={() =>
+ onChange({
+ ...document,
+ background: from,
+ backgroundGradient: {
+ kind: "linear",
+ from,
+ to,
+ angle: 120,
+ },
+ })
+ }
+ />
+ ))}
+ </div>
+ </>
+ )}
+ </PosterSection>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/poster/PosterControls.tsx b/apps/web/src/components/poster/PosterControls.tsx
new file mode 100644
index 00000000..19d25b24
--- /dev/null
+++ b/apps/web/src/components/poster/PosterControls.tsx
@@ -0,0 +1,197 @@
+import { useEffect, useState, type ReactNode } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+export function PosterTool({
+ label,
+ children,
+ onClick,
+ disabled = false,
+ active = false,
+ text = false,
+}: {
+ label: string;
+ children: ReactNode;
+ onClick: () => void;
+ disabled?: boolean;
+ active?: boolean;
+ text?: boolean;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size={text ? "sm" : "icon"}
+ variant={active ? "soft" : "ghost"}
+ disabled={disabled}
+ aria-label={label}
+ aria-pressed={active}
+ onClick={onClick}
+ className={
+ active ? "text-emerald-700 bg-emerald-50 border-emerald-200" : ""
+ }
+ >
+ {children}
+ {text && <span>{label}</span>}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ );
+}
+export function PosterSection({
+ title,
+ children,
+}: {
+ title: string;
+ children: ReactNode;
+}) {
+ return (
+ <section className="space-y-3 border-b border-slate-200/60 pb-4 last:border-0">
+ <h3 className="text-xs font-semibold tracking-wide text-slate-500">
+ {title}
+ </h3>
+ {children}
+ </section>
+ );
+}
+export function PosterNumber({
+ label,
+ value,
+ onChange,
+ min = -8192,
+ max = 8192,
+ step = 1,
+ disabled = false,
+}: {
+ label: string;
+ value: number;
+ onChange: (value: number) => void;
+ min?: number;
+ max?: number;
+ step?: number;
+ disabled?: boolean;
+}) {
+ const [draft, setDraft] = useState(String(Number(value.toFixed(2))));
+ useEffect(() => {
+ setDraft(String(Number(value.toFixed(2))));
+ }, [value]);
+ const apply = () => {
+ const number = Number(draft);
+ if (
+ draft.trim() &&
+ Number.isFinite(number) &&
+ number >= min &&
+ number <= max
+ )
+ onChange(number);
+ else setDraft(String(Number(value.toFixed(2))));
+ };
+ return (
+ <label className="space-y-1 text-[11px] text-slate-500">
+ <span>{label}</span>
+ <Input
+ aria-label={label}
+ type="number"
+ min={min}
+ max={max}
+ step={step}
+ disabled={disabled}
+ className="h-8 px-2 text-xs"
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={apply}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ apply();
+ event.currentTarget.blur();
+ }
+ }}
+ />
+ </label>
+ );
+}
+export const POSTER_SWATCHES = [
+ "#07130b",
+ "#ffffff",
+ "#f4efe4",
+ "#16a06e",
+ "#baf264",
+ "#ffe04b",
+ "#ff6b45",
+ "#e63946",
+ "#2563eb",
+ "#7c3aed",
+ "#fb7185",
+ "#14b8a6",
+];
+export function PosterColor({
+ label,
+ value,
+ onChange,
+ disabled = false,
+ swatches = false,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+ swatches?: boolean;
+}) {
+ const hex = /^#[a-f0-9]{6}$/i.test(value) ? value : "#000000";
+ const [draft, setDraft] = useState(hex);
+ useEffect(() => setDraft(hex), [hex]);
+ const apply = () => {
+ if (/^#[a-f0-9]{6}$/i.test(draft)) onChange(draft);
+ else setDraft(hex);
+ };
+ return (
+ <div className="space-y-2">
+ <label className="flex items-center gap-2 text-xs">
+ <span className="flex-1 text-slate-500">{label}</span>
+ <input
+ type="color"
+ aria-label={label}
+ value={hex}
+ disabled={disabled}
+ onChange={(event) => onChange(event.target.value)}
+ className="h-7 w-8 cursor-pointer rounded border-0 bg-transparent p-0"
+ />
+ <Input
+ aria-label={`${label} HEX`}
+ className="h-7 w-24 px-2 font-mono text-xs"
+ value={draft}
+ disabled={disabled}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={apply}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ apply();
+ event.currentTarget.blur();
+ }
+ }}
+ />
+ </label>
+ {swatches && (
+ <div className="grid grid-cols-6 gap-1.5">
+ {POSTER_SWATCHES.map((color) => (
+ <button
+ key={color}
+ disabled={disabled}
+ aria-label={`${label} ${color}`}
+ aria-pressed={hex.toLowerCase() === color}
+ onClick={() => onChange(color)}
+ className={`h-6 rounded border border-black/10 ${hex.toLowerCase() === color ? "ring-2 ring-emerald-500 ring-offset-2" : ""}`}
+ style={{ background: color }}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/poster/PosterInspector.tsx b/apps/web/src/components/poster/PosterInspector.tsx
new file mode 100644
index 00000000..8df0be12
--- /dev/null
+++ b/apps/web/src/components/poster/PosterInspector.tsx
@@ -0,0 +1,508 @@
+import {
+ AlignCenter,
+ AlignHorizontalDistributeCenter,
+ AlignLeft,
+ AlignRight,
+ AlignVerticalDistributeCenter,
+ ArrowDownToLine,
+ ArrowLeftToLine,
+ ArrowRightToLine,
+ ArrowUpToLine,
+ Bold,
+ Copy,
+ FlipHorizontal,
+ FlipVertical,
+ Image,
+ Italic,
+ Lock,
+ Trash2,
+ Underline,
+ Unlock,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { Button } from "@/components/ui/button";
+import type { PosterElement } from "@edgeever/shared";
+import { POSTER_FONTS } from "@/lib/poster-design/fonts";
+import {
+ PosterColor,
+ PosterNumber,
+ PosterSection,
+ PosterTool,
+} from "./PosterControls";
+export type PosterAlign =
+ "left" | "center" | "right" | "top" | "middle" | "bottom";
+export function PosterInspector({
+ elements,
+ disabled,
+ onPatch,
+ onAlign,
+ onDuplicate,
+ onDelete,
+ onImageFit,
+ zh,
+}: {
+ elements: PosterElement[];
+ disabled: boolean;
+ onPatch: (patch: Partial<PosterElement>) => void;
+ onAlign: (align: PosterAlign) => void;
+ onDuplicate: () => void;
+ onDelete: () => void;
+ onImageFit: (cover: boolean) => void;
+ zh: boolean;
+}) {
+ const { t } = useTranslation();
+ const active = elements.length === 1 ? elements[0] : undefined;
+ const locked = elements.some((element) => element.locked),
+ editable = !disabled && !locked;
+ const alignments = [
+ "left",
+ "center",
+ "right",
+ "top",
+ "middle",
+ "bottom",
+ ] as const;
+ const icons = [
+ ArrowLeftToLine,
+ AlignHorizontalDistributeCenter,
+ ArrowRightToLine,
+ ArrowUpToLine,
+ AlignVerticalDistributeCenter,
+ ArrowDownToLine,
+ ];
+ if (!elements.length)
+ return (
+ <div className="flex flex-col items-center gap-3 px-5 py-12 text-center text-slate-400">
+ <Image className="h-9 w-9 stroke-1" />
+ <p className="text-xs leading-relaxed">
+ {t("poster.design.selectHint")}
+ </p>
+ </div>
+ );
+ return (
+ <div className="space-y-4 p-4">
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-semibold">
+ {elements.length > 1
+ ? t("poster.design.selectionCount", { count: elements.length })
+ : active?.type === "text"
+ ? t("poster.text")
+ : active?.type === "image"
+ ? t("poster.image")
+ : t("poster.design.shape")}
+ </h2>
+ <div className="flex gap-0.5">
+ <PosterTool
+ label={t("poster.design.duplicate")}
+ disabled={!editable}
+ onClick={onDuplicate}
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </PosterTool>
+ <PosterTool
+ label={t("poster.delete")}
+ disabled={!editable}
+ onClick={onDelete}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </PosterTool>
+ </div>
+ </div>
+ {active && (
+ <Input
+ aria-label={t("poster.layerName")}
+ className="h-8 text-xs"
+ value={active.name}
+ disabled={disabled}
+ onChange={(event) =>
+ onPatch({ name: event.target.value.slice(0, 120) })
+ }
+ />
+ )}
+ <PosterSection title={t("poster.design.position")}>
+ <div className="grid grid-cols-6 gap-0.5">
+ {alignments.map((align, index) => {
+ const Icon = icons[index];
+ return (
+ <PosterTool
+ key={align}
+ label={t(`poster.design.align.${align}`)}
+ disabled={!editable}
+ onClick={() => onAlign(align)}
+ >
+ <Icon className="h-4 w-4" />
+ </PosterTool>
+ );
+ })}
+ </div>
+ {active && (
+ <div className="grid grid-cols-2 gap-2">
+ <PosterNumber
+ label="X"
+ value={active.x}
+ disabled={!editable}
+ onChange={(x) => onPatch({ x })}
+ />
+ <PosterNumber
+ label="Y"
+ value={active.y}
+ disabled={!editable}
+ onChange={(y) => onPatch({ y })}
+ />
+ <PosterNumber
+ label={t("poster.design.width")}
+ value={active.width}
+ min={1}
+ disabled={!editable}
+ onChange={(width) => onPatch({ width })}
+ />
+ <PosterNumber
+ label={t("poster.design.height")}
+ value={active.height}
+ min={1}
+ disabled={!editable}
+ onChange={(height) => onPatch({ height })}
+ />
+ <PosterNumber
+ label={t("poster.design.rotation")}
+ value={active.rotation}
+ min={-360}
+ max={360}
+ disabled={!editable}
+ onChange={(rotation) => onPatch({ rotation })}
+ />
+ <PosterNumber
+ label={t("poster.design.opacity")}
+ value={active.opacity * 100}
+ min={0}
+ max={100}
+ disabled={!editable}
+ onChange={(opacity) => onPatch({ opacity: opacity / 100 })}
+ />
+ </div>
+ )}
+ </PosterSection>
+ {active?.type === "text" && (
+ <>
+ <PosterSection title={t("poster.design.typography")}>
+ <Textarea
+ aria-label={t("poster.text")}
+ value={active.text}
+ disabled={!editable}
+ maxLength={8000}
+ className="min-h-20 resize-y text-xs"
+ onChange={(event) =>
+ onPatch({
+ text: event.target.value,
+ sourceText: event.target.value,
+ })
+ }
+ />
+ <select
+ aria-label={t("poster.fontFamily")}
+ className="h-9 w-full rounded-md border border-slate-200 bg-card px-2 text-xs"
+ value={active.fontFamily}
+ disabled={!editable}
+ onChange={(event) => onPatch({ fontFamily: event.target.value })}
+ >
+ <option value="sans-serif">{t("poster.sans")}</option>
+ <option value="serif">{t("poster.serif")}</option>
+ <option value="monospace">{t("poster.mono")}</option>
+ {POSTER_FONTS.map((font) => (
+ <option key={font.family} value={font.family}>
+ {zh ? font.zh : font.en}
+ </option>
+ ))}
+ </select>
+ <div className="flex items-end gap-2">
+ <div className="min-w-0 flex-1">
+ <PosterNumber
+ label={t("poster.fontSize")}
+ value={active.fontSize}
+ min={4}
+ max={1024}
+ disabled={!editable}
+ onChange={(fontSize) => onPatch({ fontSize })}
+ />
+ </div>
+ <div className="flex pb-0.5">
+ <PosterTool
+ label={t("poster.bold")}
+ active={active.fontWeight === "bold"}
+ disabled={!editable}
+ onClick={() =>
+ onPatch({
+ fontWeight:
+ active.fontWeight === "bold" ? "normal" : "bold",
+ })
+ }
+ >
+ <Bold className="h-4 w-4" />
+ </PosterTool>
+ <PosterTool
+ label={t("poster.design.italic")}
+ active={active.fontStyle === "italic"}
+ disabled={!editable}
+ onClick={() =>
+ onPatch({
+ fontStyle:
+ active.fontStyle === "italic" ? "normal" : "italic",
+ })
+ }
+ >
+ <Italic className="h-4 w-4" />
+ </PosterTool>
+ <PosterTool
+ label={t("poster.design.underline")}
+ active={active.underline}
+ disabled={!editable}
+ onClick={() => onPatch({ underline: !active.underline })}
+ >
+ <Underline className="h-4 w-4" />
+ </PosterTool>
+ </div>
+ </div>
+ <div className="flex gap-1">
+ {(["left", "center", "right"] as const).map((align, index) => {
+ const Icon = [AlignLeft, AlignCenter, AlignRight][index];
+ return (
+ <PosterTool
+ key={align}
+ label={t(`poster.design.textAlign.${align}`)}
+ active={active.textAlign === align}
+ disabled={!editable}
+ onClick={() => onPatch({ textAlign: align })}
+ >
+ <Icon className="h-4 w-4" />
+ </PosterTool>
+ );
+ })}
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <PosterNumber
+ label={t("poster.design.lineHeight")}
+ value={active.lineHeight ?? 1.25}
+ min={0.5}
+ max={3}
+ step={0.05}
+ disabled={!editable}
+ onChange={(lineHeight) => onPatch({ lineHeight })}
+ />
+ <PosterNumber
+ label={t("poster.design.tracking")}
+ value={active.charSpacing ?? 0}
+ min={-300}
+ max={1000}
+ disabled={!editable}
+ onChange={(charSpacing) => onPatch({ charSpacing })}
+ />
+ </div>
+ <PosterColor
+ label={t("poster.color")}
+ value={active.fill}
+ disabled={!editable}
+ onChange={(fill) => onPatch({ fill, gradient: undefined })}
+ swatches
+ />
+ </PosterSection>
+ {active.badge && (
+ <PosterSection title={t("poster.design.badgeBackground")}>
+ <PosterColor
+ label={t("poster.background")}
+ value={active.badge.background}
+ disabled={!editable}
+ onChange={(background) =>
+ onPatch({ badge: { ...active.badge!, background } })
+ }
+ />
+ </PosterSection>
+ )}
+ </>
+ )}
+ {active && active.type !== "text" && active.type !== "image" && (
+ <PosterSection title={t("poster.design.fill")}>
+ <PosterColor
+ label={t("poster.color")}
+ value={active.fill}
+ disabled={!editable}
+ onChange={(fill) => onPatch({ fill, gradient: undefined })}
+ swatches
+ />
+ {active.type === "rect" && (
+ <PosterNumber
+ label={t("poster.design.radius")}
+ value={active.radius ?? 0}
+ min={0}
+ max={Math.min(active.width, active.height) / 2}
+ disabled={!editable}
+ onChange={(radius) => onPatch({ radius })}
+ />
+ )}
+ </PosterSection>
+ )}
+ {active?.type === "image" && (
+ <PosterSection title={t("poster.design.imageAdjust")}>
+ <div className="grid grid-cols-2 gap-2">
+ <Button
+ size="sm"
+ disabled={!editable}
+ onClick={() => onImageFit(false)}
+ >
+ {t("poster.design.fitImage")}
+ </Button>
+ <Button
+ size="sm"
+ disabled={!editable}
+ onClick={() => onImageFit(true)}
+ >
+ {t("poster.design.coverImage")}
+ </Button>
+ </div>
+ <div className="flex gap-1">
+ <PosterTool
+ label={t("poster.design.flipHorizontal")}
+ disabled={!editable}
+ onClick={() => onPatch({ flipX: !active.flipX })}
+ >
+ <FlipHorizontal className="h-4 w-4" />
+ </PosterTool>
+ <PosterTool
+ label={t("poster.design.flipVertical")}
+ disabled={!editable}
+ onClick={() => onPatch({ flipY: !active.flipY })}
+ >
+ <FlipVertical className="h-4 w-4" />
+ </PosterTool>
+ </div>
+ {active.crop && (
+ <div className="grid grid-cols-2 gap-2">
+ <PosterNumber
+ label={t("poster.design.cropX")}
+ min={0}
+ max={Math.max(0, 100 * (1 - active.crop.width))}
+ value={active.crop.x * 100}
+ onChange={(x) =>
+ onPatch({ crop: { ...active.crop!, x: x / 100 } })
+ }
+ disabled={!editable}
+ />
+ <PosterNumber
+ label={t("poster.design.cropY")}
+ min={0}
+ max={Math.max(0, 100 * (1 - active.crop.height))}
+ value={active.crop.y * 100}
+ onChange={(y) =>
+ onPatch({ crop: { ...active.crop!, y: y / 100 } })
+ }
+ disabled={!editable}
+ />
+ </div>
+ )}
+ </PosterSection>
+ )}
+ {active && active.type !== "image" && (
+ <>
+ <PosterSection title={t("poster.design.outline")}>
+ <div className="grid grid-cols-2 gap-2">
+ <PosterNumber
+ label={t("poster.design.strokeWidth")}
+ value={active.strokeWidth ?? 0}
+ min={0}
+ max={100}
+ disabled={!editable}
+ onChange={(strokeWidth) =>
+ onPatch({ strokeWidth, stroke: active.stroke ?? "#07130b" })
+ }
+ />
+ <PosterColor
+ label={t("poster.color")}
+ value={active.stroke ?? "#07130b"}
+ disabled={!editable}
+ onChange={(stroke) =>
+ onPatch({ stroke, strokeWidth: active.strokeWidth || 2 })
+ }
+ />
+ </div>
+ </PosterSection>
+ <PosterSection title={t("poster.design.shadow")}>
+ <label className="flex items-center justify-between text-xs">
+ <span>{t("poster.design.enableShadow")}</span>
+ <input
+ type="checkbox"
+ checked={Boolean(active.shadow)}
+ disabled={!editable}
+ onChange={(event) =>
+ onPatch({
+ shadow: event.target.checked
+ ? { color: "#000000", blur: 12, offsetX: 4, offsetY: 6 }
+ : undefined,
+ })
+ }
+ />
+ </label>
+ {active.shadow && (
+ <div className="space-y-2">
+ <PosterColor
+ label={t("poster.color")}
+ value={active.shadow.color}
+ disabled={!editable}
+ onChange={(color) =>
+ onPatch({ shadow: { ...active.shadow!, color } })
+ }
+ />
+ <div className="grid grid-cols-3 gap-2">
+ <PosterNumber
+ label={t("poster.design.blur")}
+ value={active.shadow.blur}
+ min={0}
+ max={300}
+ disabled={!editable}
+ onChange={(blur) =>
+ onPatch({ shadow: { ...active.shadow!, blur } })
+ }
+ />
+ <PosterNumber
+ label="X"
+ value={active.shadow.offsetX}
+ min={-300}
+ max={300}
+ disabled={!editable}
+ onChange={(offsetX) =>
+ onPatch({ shadow: { ...active.shadow!, offsetX } })
+ }
+ />
+ <PosterNumber
+ label="Y"
+ value={active.shadow.offsetY}
+ min={-300}
+ max={300}
+ disabled={!editable}
+ onChange={(offsetY) =>
+ onPatch({ shadow: { ...active.shadow!, offsetY } })
+ }
+ />
+ </div>
+ </div>
+ )}
+ </PosterSection>
+ </>
+ )}
+ <Button
+ className="w-full"
+ size="sm"
+ variant="ghost"
+ disabled={disabled}
+ onClick={() => onPatch({ locked: !locked })}
+ >
+ {locked ? (
+ <Unlock className="h-3.5 w-3.5" />
+ ) : (
+ <Lock className="h-3.5 w-3.5" />
+ )}
+ {t(locked ? "poster.unlock" : "poster.lock")}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/poster/PosterLayers.tsx b/apps/web/src/components/poster/PosterLayers.tsx
new file mode 100644
index 00000000..7848c6b1
--- /dev/null
+++ b/apps/web/src/components/poster/PosterLayers.tsx
@@ -0,0 +1,149 @@
+import {
+ ArrowDown,
+ ArrowUp,
+ Eye,
+ EyeOff,
+ Group,
+ Image,
+ Lock,
+ Shapes,
+ Type,
+ Ungroup,
+ Unlock,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import type { PosterElement } from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+import { PosterTool } from "./PosterControls";
+export function PosterLayers({
+ elements,
+ selected,
+ disabled,
+ onSelect,
+ onChange,
+ onGroup,
+ onMove,
+}: {
+ elements: PosterElement[];
+ selected: string[];
+ disabled: boolean;
+ onSelect: (id: string, append: boolean) => void;
+ onChange: (id: string, patch: Partial<PosterElement>) => void;
+ onGroup: (ungroup: boolean) => void;
+ onMove: (front: boolean, oneStep: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const active = elements.filter((element) => selected.includes(element.id));
+ return (
+ <div className="space-y-3 p-3">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-slate-400">
+ {t("poster.design.layerCount", { count: elements.length })}
+ </span>
+ <div className="flex">
+ <PosterTool
+ label={t("poster.front")}
+ disabled={disabled || !active.length}
+ onClick={() => onMove(true, true)}
+ >
+ <ArrowUp className="h-3.5 w-3.5" />
+ </PosterTool>
+ <PosterTool
+ label={t("poster.backLayer")}
+ disabled={disabled || !active.length}
+ onClick={() => onMove(false, true)}
+ >
+ <ArrowDown className="h-3.5 w-3.5" />
+ </PosterTool>
+ </div>
+ </div>
+ {[...elements].reverse().map((element) => {
+ const Icon =
+ element.type === "text"
+ ? Type
+ : element.type === "image"
+ ? Image
+ : Shapes;
+ const picked = selected.includes(element.id);
+ return (
+ <div
+ key={element.id}
+ className={`group flex items-center gap-1 rounded-md border px-1 py-1 ${picked ? "border-emerald-300 bg-emerald-50/70" : "border-transparent hover:bg-slate-50/70"}`}
+ >
+ <button
+ className="flex min-w-0 flex-1 items-center gap-2 p-1.5 text-left"
+ aria-pressed={picked}
+ onClick={(event) =>
+ onSelect(
+ element.id,
+ event.shiftKey || event.metaKey || event.ctrlKey,
+ )
+ }
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0 text-slate-400" />
+ <span
+ className={`min-w-0 flex-1 truncate text-xs ${element.visible === false ? "text-slate-400 line-through" : ""}`}
+ >
+ {element.type === "text"
+ ? element.text || t("poster.text")
+ : element.name === "decor" || element.name === "accent"
+ ? t("poster.accent")
+ : element.name}
+ </span>
+ {element.groupId && <Group className="h-3 w-3 text-slate-400" />}
+ </button>
+ <PosterTool
+ label={t(
+ element.visible === false
+ ? "poster.design.show"
+ : "poster.design.hide",
+ )}
+ disabled={disabled}
+ onClick={() =>
+ onChange(element.id, { visible: element.visible === false })
+ }
+ >
+ {element.visible === false ? (
+ <EyeOff className="h-3 w-3" />
+ ) : (
+ <Eye className="h-3 w-3 opacity-40 group-hover:opacity-100" />
+ )}
+ </PosterTool>
+ <PosterTool
+ label={t(element.locked ? "poster.unlock" : "poster.lock")}
+ disabled={disabled}
+ onClick={() => onChange(element.id, { locked: !element.locked })}
+ >
+ {element.locked ? (
+ <Lock className="h-3 w-3" />
+ ) : (
+ <Unlock className="h-3 w-3 opacity-40 group-hover:opacity-100" />
+ )}
+ </PosterTool>
+ </div>
+ );
+ })}
+ <div className="grid grid-cols-2 gap-2 border-t border-slate-200/60 pt-3">
+ <Button
+ size="sm"
+ disabled={disabled || active.length < 2}
+ onClick={() => onGroup(false)}
+ >
+ <Group className="h-3.5 w-3.5" />
+ {t("poster.design.group")}
+ </Button>
+ <Button
+ size="sm"
+ disabled={disabled || !active.some((element) => element.groupId)}
+ onClick={() => onGroup(true)}
+ >
+ <Ungroup className="h-3.5 w-3.5" />
+ {t("poster.design.ungroup")}
+ </Button>
+ </div>
+ <p className="text-[10px] leading-relaxed text-slate-400">
+ {t("poster.design.multiSelectHint")}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/poster/PosterTemplatePanel.tsx b/apps/web/src/components/poster/PosterTemplatePanel.tsx
new file mode 100644
index 00000000..fba7afb4
--- /dev/null
+++ b/apps/web/src/components/poster/PosterTemplatePanel.tsx
@@ -0,0 +1,181 @@
+import { memo, useEffect, useRef, useState } from "react";
+import { Search } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/components/ui/input";
+import {
+ buildPosterDesign,
+ DESIGN_TEMPLATES,
+ templatesFor,
+} from "@/lib/poster-design/templates";
+import { renderPosterThumbnail } from "@/lib/poster-canvas";
+
+type Template = (typeof DESIGN_TEMPLATES)[number];
+const Preview = memo(function Preview({
+ template,
+ width,
+ height,
+ zh,
+ selected,
+ onSelect,
+ disabled,
+}: {
+ template: Template;
+ width: number;
+ height: number;
+ zh: boolean;
+ selected: boolean;
+ onSelect: () => void;
+ disabled: boolean;
+}) {
+ const host = useRef<HTMLButtonElement>(null);
+ const [visible, setVisible] = useState(false),
+ [url, setUrl] = useState<string>();
+ useEffect(() => {
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry?.isIntersecting) {
+ setVisible(true);
+ observer.disconnect();
+ }
+ },
+ { rootMargin: "120px" },
+ );
+ if (host.current) observer.observe(host.current);
+ return () => observer.disconnect();
+ }, []);
+ useEffect(() => {
+ if (!visible) return;
+ let cancelled = false,
+ preview: string | undefined;
+ void buildPosterDesign({
+ id: template.id,
+ title: zh ? "把想法\n变成作品" : "MAKE IDEAS\nWORTH SHARING",
+ subtitle: zh ? "一个好想法,值得被看见。" : "Ideas deserve to be seen.",
+ badge: zh ? "创作笔记" : "CREATIVE NOTES",
+ width,
+ height,
+ zh,
+ })
+ .then(renderPosterThumbnail)
+ .then((next) => {
+ preview = next;
+ if (cancelled) URL.revokeObjectURL(next);
+ else setUrl(next);
+ })
+ .catch(() => {
+ if (!cancelled) setUrl(undefined);
+ });
+ return () => {
+ cancelled = true;
+ if (preview) URL.revokeObjectURL(preview);
+ };
+ }, [visible, width, height, zh, template.id]);
+ return (
+ <button
+ ref={host}
+ disabled={disabled}
+ data-poster-template={template.id}
+ aria-label={zh ? template.zh : template.en}
+ aria-pressed={selected}
+ onClick={onSelect}
+ className={`group overflow-hidden rounded-lg border p-1.5 text-left transition disabled:opacity-50 ${selected ? "border-emerald-500 bg-emerald-50/50 ring-1 ring-emerald-500" : "border-slate-200/80 bg-card hover:border-emerald-400"}`}
+ >
+ <div className="relative flex aspect-[3/4] items-center justify-center overflow-hidden rounded bg-slate-100">
+ {url ? (
+ <img
+ src={url}
+ alt={zh ? template.zh : template.en}
+ loading="lazy"
+ className="h-full w-full object-contain"
+ />
+ ) : (
+ <span className="text-[10px] text-slate-400">
+ {zh ? "载入版式…" : "Loading layout…"}
+ </span>
+ )}
+ </div>
+ <div className="mt-2 truncate px-1 text-[11px] font-medium">
+ {zh ? template.zh : template.en}
+ </div>
+ </button>
+ );
+});
+export function PosterTemplatePanel({
+ width,
+ height,
+ platformId,
+ templateId,
+ zh,
+ disabled,
+ onApply,
+}: {
+ width: number;
+ height: number;
+ platformId?: string;
+ templateId?: string;
+ zh: boolean;
+ disabled: boolean;
+ onApply: (id: string) => void;
+}) {
+ const { t } = useTranslation();
+ const [search, setSearch] = useState(""),
+ [recommended, setRecommended] = useState(true);
+ const templates = (
+ recommended ? templatesFor(platformId) : DESIGN_TEMPLATES
+ ).filter((template) =>
+ `${template.zh} ${template.en} ${template.zhUse} ${template.enUse}`
+ .toLowerCase()
+ .includes(search.toLowerCase()),
+ );
+ return (
+ <div className="space-y-4 p-3">
+ <div className="sticky -top-0.5 z-10 space-y-2 bg-card py-1">
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs font-semibold">
+ {t("poster.templates")}{" "}
+ <span className="font-normal text-slate-400">
+ {templates.length}
+ </span>
+ </h3>
+ <button
+ className="text-[11px] text-emerald-600"
+ onClick={() => setRecommended(!recommended)}
+ >
+ {t(
+ recommended
+ ? "poster.design.allTemplates"
+ : "poster.design.recommended",
+ )}
+ </button>
+ </div>
+ <div className="relative">
+ <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-slate-400" />
+ <Input
+ className="h-8 pl-8 text-xs"
+ value={search}
+ aria-label={t("poster.design.searchTemplates")}
+ placeholder={t("poster.design.searchTemplates")}
+ onChange={(event) => setSearch(event.target.value)}
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ {templates.map((template) => (
+ <Preview
+ key={template.id}
+ template={template}
+ width={width}
+ height={height}
+ zh={zh}
+ selected={template.id === templateId}
+ onSelect={() => onApply(template.id)}
+ disabled={disabled}
+ />
+ ))}
+ </div>
+ <p className="text-[10px] leading-relaxed text-slate-400">
+ {t("poster.design.templateCredit")}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/lib/local-mirror.ts b/apps/web/src/lib/local-mirror.ts
index 6bff331c..20261fa7 100644
--- a/apps/web/src/lib/local-mirror.ts
+++ b/apps/web/src/lib/local-mirror.ts
@@ -8,6 +8,7 @@ import {
mergeMemoDocs,
getDiagramSummary,
getInfographicSummary,
+ getPosterSummary,
getTableSummary,
getNotebookDescendantIds,
resolveMemoContentDoc,
@@ -80,6 +81,7 @@ const toSummary = (memo: MemoDetail): MemoSummary => ({
excerpt: memo.excerpt,
...getDiagramSummary(memo.contentMarkdown),
...getInfographicSummary(memo.contentMarkdown),
+ ...getPosterSummary(memo.contentMarkdown),
...getTableSummary(memo.contentMarkdown),
tags: memo.tags,
isPinned: memo.isPinned,
diff --git a/apps/web/src/lib/poster-canvas.ts b/apps/web/src/lib/poster-canvas.ts
new file mode 100644
index 00000000..8d547773
--- /dev/null
+++ b/apps/web/src/lib/poster-canvas.ts
@@ -0,0 +1,370 @@
+import {
+ ActiveSelection,
+ Canvas,
+ StaticCanvas,
+ Textbox,
+ Rect,
+ Ellipse,
+ FabricImage,
+ Gradient,
+ Path,
+ Shadow,
+ Point,
+ util,
+ type FabricObject,
+} from "fabric";
+import {
+ PosterDocumentSchema,
+ type PosterDocument,
+ type PosterElement,
+ type PosterPaintGradient,
+} from "@edgeever/shared";
+import { BadgeBox } from "./poster-design/vendor/qiaomu/badge";
+import { loadPosterFont } from "./poster-design/fonts";
+
+export function makePosterGradient(
+ value: PosterPaintGradient,
+ width: number,
+ height: number,
+) {
+ const angle = ((value.angle - 90) * Math.PI) / 180,
+ dx = Math.cos(angle),
+ dy = Math.sin(angle);
+ const half = (Math.abs(width * dx) + Math.abs(height * dy)) / 2;
+ const c = value.coords;
+ const coords = c
+ ? {
+ x1: c.x1 * width,
+ y1: c.y1 * height,
+ x2: c.x2 * width,
+ y2: c.y2 * height,
+ ...(value.kind === "radial"
+ ? {
+ r1: (c.r1 ?? 0) * Math.max(width, height),
+ r2: (c.r2 ?? 1) * Math.max(width, height),
+ }
+ : {}),
+ }
+ : value.kind === "radial"
+ ? {
+ x1: width / 2,
+ y1: height / 2,
+ x2: width / 2,
+ y2: height / 2,
+ r1: 0,
+ r2: Math.max(width, height) / 2,
+ }
+ : {
+ x1: width / 2 - dx * half,
+ y1: height / 2 - dy * half,
+ x2: width / 2 + dx * half,
+ y2: height / 2 + dy * half,
+ };
+ const colorStops = value.stops ?? [
+ { offset: 0, color: value.from },
+ { offset: 1, color: value.to },
+ ];
+ return value.kind === "radial"
+ ? new Gradient<"radial">({
+ type: "radial",
+ gradientUnits: "pixels",
+ coords: {
+ ...coords,
+ r1: "r1" in coords ? (coords.r1 ?? 0) : 0,
+ r2:
+ "r2" in coords
+ ? (coords.r2 ?? Math.max(width, height))
+ : Math.max(width, height),
+ },
+ colorStops,
+ })
+ : new Gradient<"linear">({
+ type: "linear",
+ gradientUnits: "pixels",
+ coords,
+ colorStops,
+ });
+}
+export const posterObject = async (
+ element: PosterElement,
+ readResource: (id: string) => Promise<Blob>,
+): Promise<FabricObject> => {
+ const options = {
+ left: element.x,
+ top: element.y,
+ angle: element.rotation,
+ opacity: element.opacity,
+ strokeWidth: element.strokeWidth ?? 0,
+ stroke: element.stroke,
+ strokeUniform: true,
+ paintFirst: "stroke" as const,
+ originX: "left" as const,
+ originY: "top" as const,
+ flipX: element.flipX ?? false,
+ flipY: element.flipY ?? false,
+ visible: element.visible ?? true,
+ shadow: element.shadow ? new Shadow(element.shadow) : undefined,
+ selectable: !element.locked,
+ evented: !element.locked,
+ borderColor: "#16a06e",
+ cornerColor: "#16a06e",
+ cornerStrokeColor: "#ffffff",
+ cornerSize: 9,
+ cornerStyle: "circle" as const,
+ transparentCorners: false,
+ };
+ const fill = element.gradient
+ ? makePosterGradient(element.gradient, element.width, element.height)
+ : "fill" in element
+ ? element.fill
+ : undefined;
+ if (element.type === "text") {
+ await loadPosterFont(element.fontFamily);
+ const textOptions = {
+ ...options,
+ width: element.width,
+ fontSize: element.fontSize,
+ fontFamily: element.fontFamily,
+ fontWeight: element.fontWeight,
+ fontStyle: element.fontStyle ?? "normal",
+ underline: element.underline ?? false,
+ lineHeight: element.lineHeight ?? 1.25,
+ charSpacing: element.charSpacing ?? 0,
+ textAlign: element.textAlign,
+ fill,
+ splitByGrapheme: true,
+ };
+ if (element.badge) {
+ const badge = new BadgeBox(element.text, {
+ ...textOptions,
+ badgeBg: element.badge.background,
+ padX: element.badge.padX,
+ padY: element.badge.padY,
+ radius: element.badge.radius,
+ });
+ badge.editable = true;
+ return badge;
+ }
+ return new Textbox(element.text, textOptions);
+ }
+ if (element.type === "rect")
+ return new Rect({
+ ...options,
+ width: element.width,
+ height: element.height,
+ fill,
+ rx: element.radius ?? 0,
+ ry: element.radius ?? 0,
+ });
+ if (element.type === "ellipse")
+ return new Ellipse({
+ ...options,
+ rx: element.width / 2,
+ ry: element.height / 2,
+ fill,
+ });
+ if (element.type === "path") {
+ const path = new Path(element.path, { ...options, fill });
+ path.set({
+ scaleX: element.width / Math.max(1, path.width),
+ scaleY: element.height / Math.max(1, path.height),
+ });
+ return path;
+ }
+ if (element.type !== "image") throw new Error("Unsupported poster element");
+ const blob = await readResource(element.resourceId);
+ const url = URL.createObjectURL(blob);
+ try {
+ const image = await FabricImage.fromURL(url);
+ const crop = element.crop ?? { x: 0, y: 0, width: 1, height: 1 };
+ const width = image.width * crop.width,
+ height = image.height * crop.height;
+ image.set({
+ ...options,
+ cropX: image.width * crop.x,
+ cropY: image.height * crop.y,
+ width,
+ height,
+ scaleX: element.width / width,
+ scaleY: element.height / height,
+ });
+ return image;
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+};
+export const posterElementFromObject = (
+ element: PosterElement,
+ object: FabricObject,
+): PosterElement => {
+ const matrix = object.calcTransformMatrix();
+ const transform = util.qrDecompose(matrix);
+ const radians = (transform.angle * Math.PI) / 180;
+ const offsetX =
+ -(object.width * Math.abs(transform.scaleX) + object.strokeWidth) / 2;
+ const offsetY =
+ -(object.height * Math.abs(transform.scaleY) + object.strokeWidth) / 2;
+ const point = {
+ x: matrix[4] + offsetX * Math.cos(radians) - offsetY * Math.sin(radians),
+ y: matrix[5] + offsetX * Math.sin(radians) + offsetY * Math.cos(radians),
+ };
+ return {
+ ...element,
+ x: point.x,
+ y: point.y,
+ rotation: transform.angle % 360,
+ width: Math.max(1, Math.abs(object.width * transform.scaleX)),
+ height: Math.max(1, Math.abs(object.height * transform.scaleY)),
+ flipX: false,
+ flipY: transform.scaleY < 0,
+ ...(element.type === "text" && object instanceof Textbox
+ ? {
+ text: object.text,
+ sourceText:
+ object.text === element.text ? element.sourceText : object.text,
+ fontSize: object.fontSize * Math.abs(transform.scaleY),
+ }
+ : {}),
+ };
+};
+export const renderPosterBlob = async (
+ document: PosterDocument,
+ readResource: (id: string) => Promise<Blob>,
+ format: "png" | "jpeg" | "webp" = "png",
+ preview = false,
+ scale = 1,
+ quality = 0.92,
+) => {
+ PosterDocumentSchema.parse(document);
+ const canvas = new StaticCanvas(undefined, {
+ width: document.width,
+ height: document.height,
+ backgroundColor: document.backgroundGradient
+ ? makePosterGradient(
+ document.backgroundGradient,
+ document.width,
+ document.height,
+ )
+ : document.background,
+ enableRetinaScaling: false,
+ });
+ try {
+ canvas.add(
+ ...(await Promise.all(
+ document.elements.map((element) => posterObject(element, readResource)),
+ )),
+ );
+ canvas.renderAll();
+ const output = canvas.toCanvasElement(
+ preview
+ ? Math.min(1, 480 / document.width)
+ : Math.min(scale, 8192 / Math.max(document.width, document.height)),
+ );
+ return await new Promise<Blob>((resolve, reject) =>
+ output.toBlob(
+ (blob) =>
+ blob ? resolve(blob) : reject(new Error("Image export failed")),
+ `image/${format}`,
+ quality,
+ ),
+ );
+ } finally {
+ await canvas.dispose();
+ }
+};
+export const renderPosterThumbnail = async (
+ document: PosterDocument,
+): Promise<string> => {
+ const blob = await renderPosterBlob(
+ document,
+ async () => {
+ throw new Error("Template thumbnails cannot access resources");
+ },
+ "png",
+ true,
+ );
+ return URL.createObjectURL(blob);
+};
+export { Canvas, ActiveSelection };
+
+/** AI colours must be checked against the actual card underneath, not just the outer canvas background. */
+export async function ensurePosterContrast(
+ document: PosterDocument,
+ readResource: (id: string) => Promise<Blob>,
+): Promise<PosterDocument> {
+ const { contrast } = await import("./poster-design/vendor/qiaomu/quality");
+ const background = new StaticCanvas(undefined, {
+ width: document.width,
+ height: document.height,
+ enableRetinaScaling: false,
+ backgroundColor: document.backgroundGradient
+ ? makePosterGradient(
+ document.backgroundGradient,
+ document.width,
+ document.height,
+ )
+ : document.background,
+ });
+ try {
+ const objects = await Promise.all(
+ document.elements.map((element) => posterObject(element, readResource)),
+ );
+ const elements: PosterElement[] = [];
+ for (let i = 0; i < objects.length; i++) {
+ const element = document.elements[i],
+ object = objects[i];
+ if (
+ element.type === "text" &&
+ ["title", "subtitle", "badge"].includes(element.role ?? "") &&
+ !element.gradient &&
+ element.visible !== false
+ ) {
+ background.renderAll();
+ const colors: string[] = [];
+ if (element.badge) colors.push(element.badge.background);
+ else {
+ const bounds = object.getBoundingRect();
+ for (const fraction of [0.25, 0.5, 0.75]) {
+ const x = Math.max(
+ 0,
+ Math.min(
+ document.width - 1,
+ Math.round(bounds.left + bounds.width * fraction),
+ ),
+ ),
+ y = Math.max(
+ 0,
+ Math.min(
+ document.height - 1,
+ Math.round(bounds.top + bounds.height / 2),
+ ),
+ );
+ const pixel = background.getContext().getImageData(x, y, 1, 1).data;
+ colors.push(
+ `#${[pixel[0], pixel[1], pixel[2]].map((value) => value.toString(16).padStart(2, "0")).join("")}`,
+ );
+ }
+ }
+ const average = (fill: string) =>
+ colors.reduce(
+ (sum, color) => sum + (contrast(fill, color) ?? 21),
+ 0,
+ ) / colors.length;
+ const best =
+ average("#111111") >= average("#ffffff") ? "#111111" : "#ffffff";
+ const outlined =
+ element.stroke &&
+ (element.strokeWidth ?? 0) >= 2 &&
+ average(element.stroke) >= 3;
+ if (average(element.fill) < 3 && !outlined) {
+ elements.push({ ...element, fill: best });
+ object.set("fill", best);
+ } else elements.push(element);
+ } else elements.push(element);
+ background.add(object);
+ }
+ return { ...document, elements };
+ } finally {
+ await background.dispose();
+ }
+}
diff --git a/apps/web/src/lib/poster-design/fonts.ts b/apps/web/src/lib/poster-design/fonts.ts
new file mode 100644
index 00000000..9fd7efe4
--- /dev/null
+++ b/apps/web/src/lib/poster-design/fonts.ts
@@ -0,0 +1,132 @@
+export const POSTER_FONTS = [
+ {
+ family: "思源宋体",
+ file: "notoserif",
+ zh: "思源宋体 · 正文",
+ en: "Source Han Serif",
+ },
+ { family: "Anton", file: "anton", zh: "Anton · 冲击", en: "Anton" },
+ {
+ family: "抖音美好体",
+ file: "douyin",
+ zh: "抖音美好体",
+ en: "Douyin Display",
+ },
+ {
+ family: "马善政楷书",
+ file: "mashan",
+ zh: "马善政楷书",
+ en: "Ma Shan Zheng",
+ },
+ {
+ family: "江城圆体",
+ file: "jiangcheng",
+ zh: "江城圆体",
+ en: "Jiangcheng Rounded",
+ },
+ {
+ family: "站酷庆科黄油体",
+ file: "huangyou",
+ zh: "站酷庆科黄油体",
+ en: "ZCOOL QingKe HuangYou",
+ },
+ { family: "未来荧黑", file: "glow", zh: "未来荧黑", en: "Glow Sans" },
+ { family: "朱雀仿宋", file: "zhuque", zh: "朱雀仿宋", en: "Zhuque FangSong" },
+ {
+ family: "站酷快乐体",
+ file: "kuaile",
+ zh: "站酷快乐体",
+ en: "ZCOOL KuaiLe",
+ },
+
+ {
+ family: "思源黑体",
+ file: "notosans",
+ zh: "思源黑体 · 正文",
+ en: "Source Han Sans",
+ },
+ {
+ family: "思源黑体 Heavy",
+ file: "notosans-heavy",
+ zh: "思源黑体 · 特重",
+ en: "Source Han Sans Heavy",
+ },
+ {
+ family: "思源宋体 Heavy",
+ file: "notoserif-heavy",
+ zh: "思源宋体 · 特重",
+ en: "Source Han Serif Heavy",
+ },
+ { family: "得意黑", file: "smiley", zh: "得意黑 · 标题", en: "Smiley Sans" },
+ {
+ family: "霞鹜文楷",
+ file: "wenkai",
+ zh: "霞鹜文楷 · 手写",
+ en: "LXGW WenKai",
+ },
+ { family: "Inter", file: "inter", zh: "Inter · 无衬线", en: "Inter" },
+ {
+ family: "DM Serif Display",
+ file: "dmserif",
+ zh: "DM Serif · 衬线",
+ en: "DM Serif Display",
+ },
+ { family: "Bebas Neue", file: "bebas", zh: "Bebas · 窄体", en: "Bebas Neue" },
+ {
+ family: "Space Grotesk",
+ file: "spacegrotesk",
+ zh: "Space Grotesk · 科技",
+ en: "Space Grotesk",
+ },
+ {
+ family: "JetBrains Mono",
+ file: "jetbrains",
+ zh: "JetBrains · 等宽",
+ en: "JetBrains Mono",
+ },
+] as const;
+const loads = new Map<string, Promise<void>>();
+export function loadPosterFont(family: string) {
+ const font = POSTER_FONTS.find((entry) => entry.family === family);
+ if (!font) return Promise.resolve();
+ if (!loads.has(family)) {
+ const face = new FontFace(
+ family,
+ `url("/poster-fonts/${font.file}.${font.file === "douyin" ? "ttf" : "woff2"}")`,
+ );
+ const promise = face
+ .load()
+ .then((loaded) => {
+ window.document.fonts.add(loaded);
+ })
+ .catch((error) => {
+ loads.delete(family);
+ throw error;
+ });
+ loads.set(family, promise);
+ }
+ return loads.get(family)!;
+}
+export const loadDesignFonts = (zh: boolean) =>
+ Promise.all(
+ (zh
+ ? [
+ "思源黑体",
+ "思源黑体 Heavy",
+ "思源宋体",
+ "思源宋体 Heavy",
+ "得意黑",
+ "霞鹜文楷",
+ "抖音美好体",
+ "马善政楷书",
+ "江城圆体",
+ "站酷庆科黄油体",
+ "未来荧黑",
+ "朱雀仿宋",
+ "站酷快乐体",
+ "DM Serif Display",
+ "Anton",
+ ]
+ : ["Inter", "DM Serif Display", "Bebas Neue", "Space Grotesk"]
+ ).map(loadPosterFont),
+ );
diff --git a/apps/web/src/lib/poster-design/templates.ts b/apps/web/src/lib/poster-design/templates.ts
new file mode 100644
index 00000000..89bd1e84
--- /dev/null
+++ b/apps/web/src/lib/poster-design/templates.ts
@@ -0,0 +1,257 @@
+import {
+ Circle,
+ Color,
+ Ellipse,
+ FabricObject,
+ Gradient,
+ Line,
+ Path,
+ Pattern,
+ Polygon,
+ Rect,
+ Textbox,
+ Triangle,
+} from "fabric";
+import {
+ PosterDocumentSchema,
+ type PosterDocument,
+ type PosterElement,
+ type PosterPaintGradient,
+} from "@edgeever/shared";
+import { TEMPLATES, sourceOf, templatesFor } from "./vendor/qiaomu/templates";
+import { BadgeBox } from "./vendor/qiaomu/badge";
+import { resolvePair, usePairing } from "./vendor/qiaomu/typeset";
+import { POSTER_FONTS, loadDesignFonts } from "./fonts";
+export { PLATFORMS, platformFor } from "./vendor/qiaomu/platforms";
+export const DESIGN_TEMPLATES = TEMPLATES;
+export { templatesFor };
+const hex = (color: string | undefined) =>
+ `#${new Color(color || "#000000").toHex()}`;
+const paint = (object: FabricObject) =>
+ typeof object.fill === "string" && object.fill
+ ? object.fill
+ : object.fill instanceof Gradient
+ ? hex(object.fill.colorStops[0]?.color)
+ : "rgba(0,0,0,0)";
+export function gradientFromFabric(
+ value: Gradient<"linear" | "radial">,
+ width: number,
+ height: number,
+): PosterPaintGradient {
+ const c = value.coords as {
+ x1: number;
+ y1: number;
+ x2: number;
+ y2: number;
+ r1?: number;
+ r2?: number;
+ };
+ return {
+ kind: value.type,
+ from: hex(value.colorStops[0]?.color),
+ to: hex(value.colorStops.at(-1)?.color),
+ angle: 90,
+ stops: value.colorStops.map((stop) => ({
+ offset: stop.offset,
+ color: stop.color,
+ opacity: (stop as typeof stop & { opacity?: number }).opacity,
+ })),
+ coords: {
+ x1: c.x1 / width,
+ y1: c.y1 / height,
+ x2: c.x2 / width,
+ y2: c.y2 / height,
+ ...(value.type === "radial"
+ ? {
+ r1: (c.r1 ?? 0) / Math.max(width, height),
+ r2: (c.r2 ?? 0) / Math.max(width, height),
+ }
+ : {}),
+ },
+ };
+}
+export function posterPrimitiveFromObject(
+ object: FabricObject,
+ index: number,
+): PosterElement | null {
+ if (object.fill instanceof Pattern) return null; // Film grain is a generated raster tile, not editable vector source.
+ const roleValue = (object as FabricObject & { qcRole?: string }).qcRole;
+ const role =
+ roleValue === "title" || roleValue === "subtitle" || roleValue === "badge"
+ ? roleValue
+ : "decor";
+ const pos = object.getPointByOrigin("left", "top");
+ const options = {
+ id: `design_${index}`,
+ name: role,
+ role,
+ x: pos.x,
+ y: pos.y,
+ width: Math.max(1, object.width * Math.abs(object.scaleX)),
+ height: Math.max(1, object.height * Math.abs(object.scaleY)),
+ rotation: object.angle % 360,
+ opacity: object.opacity,
+ locked: false,
+ ...(object.stroke && typeof object.stroke === "string"
+ ? { stroke: object.stroke, strokeWidth: object.strokeWidth }
+ : {}),
+ ...(object.shadow
+ ? {
+ shadow: {
+ color: object.shadow.color,
+ blur: object.shadow.blur,
+ offsetX: object.shadow.offsetX,
+ offsetY: object.shadow.offsetY,
+ },
+ }
+ : {}),
+ ...(object.fill instanceof Gradient
+ ? {
+ gradient: gradientFromFabric(
+ object.fill,
+ Math.max(1, object.width),
+ Math.max(1, object.height),
+ ),
+ }
+ : {}),
+ } satisfies Partial<PosterElement>;
+ if (object instanceof Textbox)
+ return {
+ ...options,
+ type: "text",
+ text: object.text,
+ sourceText: sourceOf(object),
+ fill: paint(object),
+ fontSize: object.fontSize * Math.abs(object.scaleY),
+ fontFamily: object.fontFamily,
+ fontWeight: ["bold", "700", "800", "900"].includes(
+ String(object.fontWeight),
+ )
+ ? "bold"
+ : "normal",
+ fontStyle: object.fontStyle === "italic" ? "italic" : "normal",
+ textAlign:
+ object.textAlign === "center" || object.textAlign === "right"
+ ? object.textAlign
+ : "left",
+ lineHeight: object.lineHeight,
+ charSpacing: object.charSpacing,
+ ...(object instanceof BadgeBox
+ ? {
+ badge: {
+ background: hex(object.badgeBg),
+ padX: object.padX,
+ padY: object.padY,
+ radius: object.radius,
+ },
+ }
+ : {}),
+ };
+ if (object instanceof Rect)
+ return {
+ ...options,
+ type: "rect",
+ fill: paint(object),
+ radius: object.rx * Math.abs(object.scaleX),
+ };
+ if (object instanceof Circle || object instanceof Ellipse)
+ return { ...options, type: "ellipse", fill: paint(object) };
+ let path: string | undefined;
+ if (object instanceof Path)
+ path = object.path.map((command) => command.join(" ")).join(" ");
+ if (object instanceof Line)
+ path = `M ${object.x1} ${object.y1} L ${object.x2} ${object.y2}`;
+ if (object instanceof Polygon)
+ path =
+ object.points
+ .map((point, i) => `${i ? "L" : "M"} ${point.x} ${point.y}`)
+ .join(" ") + " Z";
+ if (object instanceof Triangle)
+ path = `M ${object.width / 2} 0 L ${object.width} ${object.height} L 0 ${object.height} Z`;
+ if (!path) throw new Error(`Unsupported design primitive: ${object.type}`);
+ return { ...options, type: "path", path, fill: paint(object) };
+}
+export function posterCopy(document: PosterDocument) {
+ if (document.copy) return document.copy;
+ const text = document.elements.filter((element) => element.type === "text");
+ const title =
+ text.find(
+ (element) => element.role === "title" || element.id === "heading",
+ ) ?? text[0];
+ const subtitle =
+ text.find(
+ (element) => element.role === "subtitle" || element.id === "subtitle",
+ ) ?? text[1];
+ const badge = text.find((element) => element.role === "badge");
+ return {
+ title: title?.sourceText ?? title?.text ?? "",
+ subtitle: subtitle?.sourceText ?? subtitle?.text ?? "",
+ badge: badge?.sourceText ?? badge?.text ?? "",
+ };
+}
+export async function buildPosterDesign(input: {
+ id: string;
+ title: string;
+ subtitle: string;
+ badge?: string;
+ points?: string[];
+ width: number;
+ height: number;
+ zh: boolean;
+ palette?: { bg?: string; ink?: string; accent?: string };
+}): Promise<PosterDocument> {
+ await loadDesignFonts(input.zh);
+ const template =
+ TEMPLATES.find((entry) => entry.id === input.id) ?? TEMPLATES[0]!;
+ usePairing(
+ input.zh
+ ? resolvePair(template.id, (family) =>
+ POSTER_FONTS.some((font) => font.family === family),
+ )
+ : {
+ title:
+ template.id === "newspaper" || template.id === "folio"
+ ? "DM Serif Display"
+ : "Inter",
+ body: "Inter",
+ titleBold: true,
+ missing: [],
+ },
+ );
+ try {
+ const built = template.build({ ...input });
+ const elements = built.objects
+ .map(posterPrimitiveFromObject)
+ .filter((value): value is PosterElement => Boolean(value));
+ const background =
+ built.background.kind === "solid"
+ ? built.background.color
+ : built.background.from;
+ const result = {
+ copy: {
+ title: input.title,
+ subtitle: input.subtitle,
+ badge: input.badge ?? "",
+ },
+ schemaVersion: 1,
+ width: input.width,
+ height: input.height,
+ templateId: template.id,
+ background: hex(background),
+ ...(built.background.kind === "linear"
+ ? {
+ backgroundGradient: {
+ kind: "linear",
+ from: hex(built.background.from),
+ to: hex(built.background.to),
+ angle: built.background.angle,
+ },
+ }
+ : {}),
+ elements,
+ };
+ return PosterDocumentSchema.parse(result);
+ } finally {
+ usePairing(undefined);
+ }
+}
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/LICENSE b/apps/web/src/lib/poster-design/vendor/qiaomu/LICENSE
new file mode 100644
index 00000000..b1168c79
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025-2026 向阳乔木 (joeseesun)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/README.md b/apps/web/src/lib/poster-design/vendor/qiaomu/README.md
new file mode 100644
index 00000000..485dda7f
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/README.md
@@ -0,0 +1,6 @@
+Qiaomu Design 0.2.4 template and typesetting primitives.
+
+Source: https://github.com/joeseesun/qiaomu-cover-design/tree/0.2.4
+
+Copyright (c) 2025–2026 向阳乔木 (joeseesun), MIT. See LICENSE.
+The files are pure design primitives; Obsidian runtime, credentials and storage are not included.
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/badge.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/badge.ts
new file mode 100644
index 00000000..8a402f80
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/badge.ts
@@ -0,0 +1,45 @@
+/**
+ * A text label with a filled pill behind it, drawn by hand so the words sit exactly in the middle.
+ * Fabric's own text background fills the whole line box, and the extra leading ends up on one side, so CJK labels look
+ * dropped. Here the pill is sized from the measured glyph height of a reference character and the baseline is placed so
+ * its cap height is centred, with equal padding left and right. Serialises as an ordinary object and reloads by type.
+ */
+import { classRegistry, getEnv, Textbox, TextboxProps } from 'fabric';
+
+export interface BadgeProps { badgeBg: string; padX: number; padY: number; radius: number }
+let ctx2d: CanvasRenderingContext2D | null | undefined;
+function measureCtx(): CanvasRenderingContext2D | null {
+ if (ctx2d === undefined) { try { ctx2d = getEnv().document?.createElement('canvas').getContext('2d') ?? null; } catch { ctx2d = null; } }
+ return ctx2d;
+}
+interface Metrics { width: number; ascent: number; descent: number }
+/** Width of the text and the ink extent of a reference glyph pair (cap/CJK height), in px. */
+export function measureLabel(text: string, size: number, weight: string, family: string): Metrics {
+ const c = measureCtx(); if (!c) return { width: [...text].length * size * 0.8, ascent: size * 0.8, descent: size * 0.04 };
+ c.font = `${weight} ${size}px ${family}`; const width = c.measureText(text).width; const ref = c.measureText('H国');
+ return { width, ascent: ref.actualBoundingBoxAscent || size * 0.8, descent: Math.max(0, ref.actualBoundingBoxDescent || size * 0.04) };
+}
+
+export class BadgeBox extends Textbox {
+ static type = 'BadgeBox';
+ static customProperties = ['badgeBg', 'padX', 'padY', 'radius'];
+ declare badgeBg: string; declare padX: number; declare padY: number; declare radius: number;
+ constructor(text: string, options?: Partial<TextboxProps> & Partial<BadgeProps>) { super(text, { badgeBg: '#111111', padX: 0.6, padY: 0.34, radius: 0.5, editable: false, lineHeight: 1, ...options } as Partial<TextboxProps>); }
+ private metrics(): Metrics { return measureLabel(this.text.trim(), this.fontSize, String(this.fontWeight), this.fontFamily); }
+ /** Size comes from the measured label, not from Fabric's line layout. */
+ initDimensions(): void {
+ const m = this.metrics(); const px = this.padX * this.fontSize, py = this.padY * this.fontSize;
+ this.width = m.width + px * 2; this.height = m.ascent + m.descent + py * 2;
+ this.textLines = [this.text]; this._textLines = [[...this.text]]; this.dirty = true;
+ }
+ /** The pill is the visible extent. Fabric's own line cache is never filled here, so its version would throw. */
+ getLineWidth(): number { return this.width; }
+ _render(c: CanvasRenderingContext2D): void {
+ const w = this.width, h = this.height; const m = this.metrics(); const r = Math.min(h / 2, this.radius * h);
+ c.save(); c.fillStyle = this.badgeBg; c.beginPath();
+ c.moveTo(-w / 2 + r, -h / 2); c.arcTo(w / 2, -h / 2, w / 2, h / 2, r); c.arcTo(w / 2, h / 2, -w / 2, h / 2, r); c.arcTo(-w / 2, h / 2, -w / 2, -h / 2, r); c.arcTo(-w / 2, -h / 2, w / 2, -h / 2, r); c.closePath(); c.fill();
+ c.fillStyle = typeof this.fill === 'string' ? this.fill : '#ffffff'; c.font = `${this.fontWeight} ${this.fontSize}px ${this.fontFamily}`; c.textAlign = 'center'; c.textBaseline = 'alphabetic';
+ c.fillText(this.text.trim(), 0, (m.ascent - m.descent) / 2); c.restore();
+ }
+}
+classRegistry.setClass(BadgeBox, 'BadgeBox');
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/gaoding.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/gaoding.ts
new file mode 100644
index 00000000..582ad1f3
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/gaoding.ts
@@ -0,0 +1,193 @@
+/**
+ * Layouts drawn from the formats that dominate the Gaoding (稿定设计) recommended feed for Xiaohongshu and WeChat, kept to the
+ * ones that live on type and flat shapes alone (no stock photo, no illustration), redrawn to the design rules: one focal
+ * headline, flat colour, no outlined type, no starbursts. Helpers come from templates.ts and are only used inside build().
+ */
+import { Circle, FabricObject, Line, Path, Polygon, Rect, Shadow } from 'fabric';
+import { grain } from './kit';
+import { badge, dot, FABRIC_LINE, fitTitle, hasCjk, keep, lineW, metrics, meta, pill, rect, solid, sub, Template, textbox, textHeight, wrapLines, palette } from './templates';
+
+const XHS = ['xhs', 'xhs-square', 'portrait', 'square']; const VIDEO = ['youtube', 'bilibili', 'bilibili-43', 'bilibili-hd', 'wide']; const BANNER = ['wechat', 'x'];
+/** Items for a checklist row: the points, or a subtitle written as a list. */
+const items = (points: string[] | undefined, subtitle: string, max: number): string[] => {
+ const xs = (points?.length ? points : subtitle.split(/[\n,,、;;||]/)).map(s => s.trim()).filter(Boolean);
+ return xs.length >= 2 ? xs.slice(0, max) : [];
+};
+/** Tags a shape as part of the layout's signature, so the clean-up that runs when a subject picture arrives keeps it. */
+const mark = <T extends FabricObject>(o: T, kind: 'mark' | 'mark-title' = 'mark'): T => Object.assign(o, { qcKind: kind });
+/** A hand-drawn arrow: one curved stroke and an open head, round caps. From (x0,y0) bending to (x1,y1). */
+function arrow(x0: number, y0: number, x1: number, y1: number, bend: number, color: string, weight: number): Path {
+ const mx = (x0 + x1) / 2 + bend, my = (y0 + y1) / 2 - bend * 0.4;
+ const ang = Math.atan2(y1 - my, x1 - mx); const head = weight * 3.4;
+ const a = (k: number): string => `${(x1 - Math.cos(ang + k) * head).toFixed(1)} ${(y1 - Math.sin(ang + k) * head).toFixed(1)}`;
+ return mark(new Path(`M${x0} ${y0} Q${mx} ${my} ${x1} ${y1} M${a(0.55)} L${x1} ${y1} L${a(-0.55)}`, { fill: '', stroke: color, strokeWidth: weight, strokeLineCap: 'round', strokeLineJoin: 'round', objectCaching: false }));
+}
+/** A dry-brush block: a rectangle with ragged, slightly wavy long edges, for a highlighter stroke made by a brush. */
+function brushBlock(x: number, y: number, w: number, h: number, color: string, seed = 3): Path {
+ const n = 9; let s = seed * 7919 + 17; const rnd = (): number => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
+ let d = `M${x} ${y + h * 0.12}`;
+ for (let k = 1; k <= n; k++) d += ` L${(x + (w * k) / n).toFixed(1)} ${(y + h * (0.04 + rnd() * 0.16)).toFixed(1)}`;
+ d += ` L${(x + w + h * 0.12).toFixed(1)} ${(y + h * 0.55).toFixed(1)}`;
+ for (let k = n; k >= 0; k--) d += ` L${(x + (w * k) / n).toFixed(1)} ${(y + h * (0.84 + rnd() * 0.14)).toFixed(1)}`;
+ return mark(new Path(`${d} Z`, { fill: color, stroke: '', angle: -1.2 }), 'mark-title');
+}
+
+export const GAODING: Template[] = [
+ {
+ id: 'regeng', zh: '热梗卡', en: 'Daily drop', fit: [...XHS, 'wechat'], zhUse: '黑色话题条(#标签#)+ 三层错位描边卡片里的粗黑大字 + 左下“No.期号”;每日热梗、资讯速递、系列笔记,小红书辨识度很高', enUse: 'A black hashtag bar, a heavy headline in a stack of three offset outlined cards and an issue number; daily drops, news and series notes',
+ build(i) {
+ const p = palette(i, { bg: '#f2f2ef', bg2: '#f2f2ef', ink: '#111111', sub: '#4b4b4b', accent: '#e8432b', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.25; const bar = Math.max(56, 88 * u); const sw = Math.max(4, 6 * u); const off = Math.max(8, 14 * u);
+ const tag = (i.badge?.trim() || (i.zh ? '每日新鲜事' : 'daily')).replace(/^#|#$/g, '');
+ const bx = m, by = bar + m * 0.9; const bw = side ? w * 0.6 - m : w - m * 2 - off * 2; const bh = side ? h - by - m - off * 2 : h * 0.5;
+ const pad = Math.max(m * 0.6, 34 * u); const tw = bw - pad * 2;
+ const size = fitTitle(i.title, tw, bh - pad * 2, 200 * u, 36, 1.08); const th = textHeight(i.title, tw, size, 1.08);
+ const card = (k: number): Rect => rect(bx + off * k, by + off * k, bw, bh, k ? p.bg : '#ffffff', { stroke: p.ink, strokeWidth: sw });
+ const no = `No.${String(Number(/\d+/.exec(i.badge ?? '')?.[0] ?? 1)).padStart(3, '0')}`; const ns = Math.max(40, Math.min(110 * u, h * 0.07));
+ const nx = side ? bx + bw + off * 2 + m : bx; const ny = side ? by : by + bh + off * 2 + m * 0.8; const nw = side ? w - nx - m : w - m * 2;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.05, 151),
+ rect(0, 0, w, bar, p.ink),
+ textbox(`#${tag}#`, m, (bar - bar * 0.42 * 1.13) / 2, w * 0.6, { qcRole: 'badge', fontSize: bar * 0.42, fill: '#ffffff', fontWeight: 'bold', lineHeight: 1 }),
+ // The record switch lives in the bar: a white track with the red "live" light on.
+ rect(w - m - bar * 0.95, bar * 0.3, bar * 0.95, bar * 0.4, 'rgba(0,0,0,0)', { rx: bar * 0.2, ry: bar * 0.2, stroke: '#ffffff', strokeWidth: Math.max(2, 3 * u) }),
+ dot(w - m - bar * 0.25, bar * 0.5, bar * 0.13, p.accent),
+ card(2), card(1), card(0),
+ textbox(i.title, bx + pad, by + (bh - th) / 2, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08 }),
+ textbox(no, nx, ny, nw, { fontSize: ns, fill: p.ink, fontFamily: 'Anton', lineHeight: 1, charSpacing: 20 }),
+ rect(nx, ny + ns * 1.22, Math.max(40, ns * 0.9), Math.max(4, 6 * u), p.accent),
+ ...sub(i, nx, ny + ns * 1.22 + 24 * u, nw, Math.max(24, size * 0.3), p.sub, { fontWeight: 'bold' }),
+ ) };
+ },
+ },
+ {
+ id: 'interview', zh: '黑黄箭头', en: 'Black & yellow', fit: [...XHS, ...VIDEO, 'vertical'], zhUse: '黑底 + 黄色超粗标题 + 一条手绘大箭头指向标题 + 白框英文标签 + 角落笑脸;面试、考试、干货清单,强对比又不土', enUse: 'Black, a heavy yellow headline, one big hand-drawn arrow pointing at it, a boxed label and a corner smiley; interviews, exams and checklists',
+ build(i) {
+ const p = palette(i, { bg: '#0f0f0f', bg2: '#0f0f0f', ink: '#ffe14a', sub: '#ffffff', accent: '#ffe14a', accentInk: '#0f0f0f' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.25; const x0 = m * 1.1; const tw = side ? w * 0.62 - x0 : w - x0 * 2;
+ const label = (i.badge?.trim() || 'INTERVIEW').toUpperCase(); const ls = Math.max(30, Math.min(side ? h * 0.1 : w * 0.085, (tw * 0.9) / Math.max(4, [...label].length * (hasCjk(label) ? 1 : 0.62))));
+ const lh = ls * 1.5; const ly = m * 0.9; const lw = Math.min(tw, lineW(label, ls, 'bold', 0) + ls * 1.2);
+ const size = fitTitle(i.title, tw, h * (side ? 0.5 : 0.36), 230 * u, 40, 1.04); const th = textHeight(i.title, tw, size, 1.04);
+ const subS = Math.max(24, size * 0.28); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subS, 1.25) + 28 * u : 0;
+ const ty = side ? Math.max(ly + lh + m * 0.6, (h - th - subH) / 2) : Math.max(ly + lh + h * 0.16, h * 0.42 - th / 2);
+ const aw = Math.max(10, 24 * u);
+ const arrowTo = { x: side ? x0 + tw + m * 0.2 : x0 + tw * 0.62, y: ty - (side ? -th * 0.2 : m * 0.25) };
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.07, 157),
+ rect(x0, ly, lw, lh, 'rgba(0,0,0,0)', { stroke: '#ffffff', strokeWidth: Math.max(3, 5 * u) }),
+ textbox(label, x0, ly + (lh - ls * 1.13) / 2, lw, { qcRole: 'badge', fontSize: ls, fill: '#ffffff', fontWeight: 'bold', textAlign: 'center', lineHeight: 1 }),
+ arrow(side ? w - m * 1.2 : w - m * 1.1, side ? h * 0.18 : ly + lh * 0.6, arrowTo.x, arrowTo.y, side ? -w * 0.06 : -w * 0.12, p.accent, aw),
+ textbox(i.title, x0, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.04 }),
+ ...sub(i, x0, ty + th + 28 * u, tw, subS, p.sub, { fontWeight: 'bold' }),
+ textbox(':)', w - m - 120 * u, h - m - 70 * u, 120 * u, { fontSize: Math.max(40, 64 * u), fill: '#ffffff', fontWeight: 'bold', textAlign: 'right', lineHeight: 1 }),
+ ) };
+ },
+ },
+ {
+ id: 'brush', zh: '笔刷收藏', en: 'Brush highlight', fit: [...XHS, 'wechat', ...VIDEO], zhUse: '白底粗黑标题 + 最后一行压一道绿色笔刷 + 歪贴的“建议收藏!”标签 + 底部 ✓ 清单(points);副业、避坑、干货,最像小红书爆款笔记', enUse: 'Heavy black type on white, a green brush stroke under the last line, a tilted “save this” tag and a check row from the points; tips and side hustles',
+ build(i) {
+ const p = palette(i, { bg: '#ffffff', bg2: '#ffffff', ink: '#111111', sub: '#4b4b4b', accent: '#3ddc84', accentInk: '#111111' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.1; const tw = (w - x0 * 2) * (wide ? 0.82 : 1); const lh = 1.12;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.5 : 0.48), 240 * u, 40, lh); const lines = wrapLines(i.title, tw, size, 'bold', -18); const step = size * lh * FABRIC_LINE; const th = lines.length * step;
+ const checks = items(i.points, i.subtitle, 3); const cs = Math.max(24, size * 0.28);
+ // The check row wraps instead of running off the page; its height is known before the block is centred.
+ const cw = (t: string): number => cs * 2.2 + lineW(t, cs, 'bold', 0); const flow: { t: string; x: number; y: number }[] = []; { let fx = 0, fy = 0; for (const t of checks) { if (fx && fx + cw(t) > tw) { fx = 0; fy += cs * 1.7; } flow.push({ t, x: fx, y: fy }); fx += cw(t); } }
+ const rowH = checks.length ? (flow[flow.length - 1]!.y + cs * 1.4) : 0;
+ const subS = Math.max(24, size * 0.28); const subH = !checks.length && i.subtitle.trim() ? textHeight(i.subtitle, tw, subS, 1.25) + 30 * u : 0;
+ const tagS = Math.max(22, size * 0.24); const tagH = tagS * 1.3 * 1.7 + 40 * u;
+ const ty = (h - tagH - th - subH - rowH - (rowH ? 40 * u : 0)) / 2 + tagH; const last = lines[lines.length - 1] ?? '';
+ const ray = (k: number): Line => { const a = (-150 - k * 28) * Math.PI / 180; const cx = x0 + tagS * 0.2, cy = ty - tagH * 0.55; const r0 = tagS * 0.9, r1 = tagS * 1.6; return mark(new Line([cx + Math.cos(a) * r0, cy + Math.sin(a) * r0, cx + Math.cos(a) * r1, cy + Math.sin(a) * r1], { stroke: p.ink, strokeWidth: Math.max(3, 5 * u), strokeLineCap: 'round' }), 'mark-title'); };
+ const rowY = ty + th + 40 * u;
+ const row = flow.flatMap(({ t, x, y }) => { const cx = x0 + x, cy = rowY + y; return [dot(cx + cs * 0.5, cy + cs * 0.62, cs * 0.5, p.accent), textbox('✓', cx + cs * 0.1, cy + cs * 0.06, cs * 0.8, { fontSize: cs * 0.9, fill: p.ink, fontWeight: 'bold', textAlign: 'center', lineHeight: 1 }), textbox(t, cx + cs * 1.3, cy, lineW(t, cs, 'bold', 0) + cs, { fontSize: cs, fill: p.ink, fontWeight: 'bold', lineHeight: 1.1 })]; });
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.04, 163),
+ brushBlock(x0 - size * 0.1, ty + (lines.length - 1) * step + size * 0.22, Math.min(w - x0, lineW(last, size) + size * 0.25), size * 0.95, p.accent, lines.length),
+ ray(0), ray(1), ray(2),
+ pill(i.badge?.trim() || (i.zh ? '建议收藏!' : 'Save this!'), x0 + tagS * 0.4, ty - tagH, p.accent, p.accentInk, tagS * 1.3, { qcRole: 'badge', angle: -8, radius: 0.3 }),
+ textbox(i.title, x0, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: lh, charSpacing: -18 }),
+ ...(checks.length ? row : sub(i, x0, ty + th + 30 * u, tw, subS, p.sub, { fontWeight: 'bold' })),
+ ) };
+ },
+ },
+ {
+ id: 'calendar', zh: '日历页', en: 'Calendar page', fit: [...XHS, 'wechat', ...VIDEO], zhUse: '纯蓝底 + 一张带装订环的白色日历页 + 页里的粗黑大字;每日一句、打卡、待办、节日,干净有仪式感', enUse: 'Flat blue with a white calendar page and binding rings, a heavy headline on the page; daily lines, check-ins and to-dos',
+ build(i) {
+ const p = palette(i, { bg: '#2f6bff', bg2: '#2f6bff', ink: '#111111', sub: '#555555', accent: '#2f6bff', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const cw = wide ? w * 0.7 : w - m * 2.2; const ch = wide ? h - m * 2.4 : h * 0.66; const cx = (w - cw) / 2; const cy = (h - ch) / 2 + m * 0.3;
+ const r = Math.max(10, 16 * u); const pad = Math.max(m * 0.8, 44 * u); const tw = cw - pad * 2; const holes = Math.max(6, Math.round(cw / (r * 5)));
+ const size = fitTitle(i.title, tw, ch * 0.5, 220 * u, 36, 1.08); const th = textHeight(i.title, tw, size, 1.08);
+ const subS = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subS, 1.25) + 30 * u : 0; const head = r * 4;
+ const ty = cy + head + (ch - head - th - subH) / 2;
+ const rings = Array.from({ length: holes }, (_, k) => { const x = cx + (cw / holes) * (k + 0.5); return [mark(dot(x, cy + r * 1.6, r * 0.55, p.bg)), mark(new Rect({ left: x - r * 0.28, top: cy - r * 1.1, width: r * 0.56, height: r * 2.8, rx: r * 0.28, ry: r * 0.28, fill: '#1b1b1b', originX: 'left', originY: 'top' }))]; }).flat();
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.06, 167),
+ rect(cx + 14 * u, cy + 18 * u, cw, ch, '#dfe6ff', { rx: 18 * u, ry: 18 * u }),
+ rect(cx, cy, cw, ch, '#ffffff', { rx: 18 * u, ry: 18 * u, shadow: new Shadow({ color: 'rgba(0,20,90,0.25)', blur: 40 * u, offsetX: 0, offsetY: 16 * u }) }),
+ ...rings,
+ meta((i.badge?.trim() || (i.zh ? '今日' : 'TODAY')).toUpperCase(), cx + pad, cy + head * 0.75, tw * 0.6, Math.max(16, 22 * u), p.accent, { qcRole: 'badge' }),
+ textbox(i.title, cx + pad, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08, textAlign: 'center' }),
+ ...sub(i, cx + pad, ty + th + 30 * u, tw, subS, p.sub, { textAlign: 'center' }),
+ ) };
+ },
+ },
+ {
+ id: 'frame', zh: '框线大字', en: 'Framed type', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '纯色底 + 一圈细内框 + 撑满框的超大标题 + 一角出血的太阳圆;招聘、开学、通知、活动,最简单也最醒目', enUse: 'Flat colour, a thin inset frame, a headline that fills it and a sun disc bleeding off a corner; hiring, launches and notices',
+ build(i) {
+ const p = palette(i, { bg: '#22b573', bg2: '#22b573', ink: '#0f2a1d', sub: '#0f2a1d', accent: '#f4e04d', accentInk: '#0f2a1d' });
+ const { u, m, w, h, wide } = metrics(i); const f = m * 0.55; const pad = m * 0.9; const tw = w - (f + pad) * 2;
+ // The subtitle rides right under the headline: the foot of the frame is left to the sun and to platform UI (9:16 captions).
+ const subS = Math.max(24, 32 * u); const sw = tw * 0.8; const subH = i.subtitle.trim() ? textHeight(i.subtitle, sw, subS, 1.25) + 30 * u : 0; const bs = Math.max(22, 34 * u); const bH = i.badge?.trim() ? bs * 1.3 * 1.8 + 16 * u : 0;
+ // On a banner (wider than 2.2:1) the copy hangs from the top: the lower left is where X puts the avatar.
+ const banner = w / h > 2.2; const room = h - (f + pad) * 2 - bH; const size = fitTitle(i.title, tw, (room - subH) * (banner ? 0.62 : wide ? 0.86 : 0.58), 420 * u, 44, 1.02); const th = textHeight(i.title, tw, size, 1.02);
+ const ty = f + pad + bH + (banner ? 0 : wide ? (room - subH - th) / 2 : room * 0.04); const R = Math.min(w, h) * 0.34;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ new Circle({ left: w - R * 1.45, top: h - R * 1.25, radius: R, fill: p.accent, opacity: 0.85, originX: 'left', originY: 'top' }),
+ grain(w, h, 0.08, 173),
+ // qcRole marks the border as the page's structure, so platform avoidance moves the words inside it and leaves it whole.
+ rect(f, f, w - f * 2, h - f * 2, 'rgba(0,0,0,0)', { stroke: p.ink, strokeWidth: Math.max(2, 3 * u), qcRole: 'frame' }),
+ ...badge(i.badge, f + pad, f + pad * 0.7, { ...p, accent: p.ink, accentInk: p.bg }, bs),
+ textbox(i.title, f + pad, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.02 }),
+ ...sub(i, f + pad, ty + th + 30 * u, sw, subS, p.sub, { fontWeight: 'bold' }),
+ ) };
+ },
+ },
+ {
+ id: 'kicker', zh: '粗细引题', en: 'Kicker headline', fit: [...XHS, 'wechat', ...VIDEO], zhUse: '浅灰底:副标题当细字引题写在上面,标题粗黑放大 + 双线胶囊标签 + 底部“右滑查看 ››››”;经验、问答、职场,信息感强', enUse: 'Light grey: the subtitle as a thin kicker above a heavy headline, a double-ring pill tag and a “swipe” cue; experience posts, Q&A, work',
+ build(i) {
+ const p = palette(i, { bg: '#ececea', bg2: '#ececea', ink: '#111111', sub: '#2b2b2b', accent: '#111111', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.1; const tw = (w - x0 * 2) * (wide ? 0.72 : 1);
+ const size = fitTitle(i.title, tw, h * (wide ? 0.42 : 0.32), 200 * u, 40, 1.08); const th = textHeight(i.title, tw, size, 1.08);
+ const ks = Math.max(26, size * 0.46); const kick = i.subtitle.trim(); const kh = kick ? textHeight(kick, tw, ks, 1.2) + size * 0.18 : 0;
+ const label = i.badge?.trim() ?? ''; const tagS = Math.max(20, size * 0.2); const gap = 8 * u;
+ const rw = label ? lineW(label, tagS, 'bold', 0) + tagS * 1.6 : 0; const rh = tagS * 2; const tagH = label ? rh + gap * 2 + 36 * u : 0; const foot = Math.max(22, 30 * u);
+ const top = (h - tagH - kh - th) / 2 + tagH; const R = Math.min(w, h) * 0.42; const ry = top - tagH;
+ const ring = (k: number): Rect => rect(x0 + gap * (1 - k), ry + gap * (1 - k), rw + gap * 2 * k, rh + gap * 2 * k, 'rgba(0,0,0,0)', { rx: (rh + gap * 2 * k) / 2, ry: (rh + gap * 2 * k) / 2, stroke: p.ink, strokeWidth: Math.max(1.5, (k ? 2.5 : 2) * u) });
+ const tag = label ? textbox(label, x0 + gap, ry + gap + (rh - tagS * 1.13) / 2, rw, { qcRole: 'badge', fontSize: tagS, fill: p.ink, fontWeight: 'bold', textAlign: 'center', lineHeight: 1 }) : undefined;
+ const rings = label ? [ring(1), ring(0)] : [];
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ new Circle({ left: w - R * 1.25, top: h - R * 1.5, radius: R, fill: 'rgba(0,0,0,0)', stroke: 'rgba(0,0,0,0.06)', strokeWidth: R * 0.32, originX: 'left', originY: 'top' }),
+ grain(w, h, 0.06, 179), ...rings, tag,
+ ...(kick ? [textbox(kick, x0, top, tw, { qcRole: 'subtitle', fontSize: ks, fill: p.sub, lineHeight: 1.2 })] : []),
+ textbox(i.title, x0, top + kh, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08 }),
+ textbox(i.zh ? '右滑查看 ››››' : 'Swipe ››››', x0, h - m - foot * 1.4, w * 0.5, { fontSize: foot, fill: p.ink, fontWeight: 'bold', lineHeight: 1 }),
+ ) };
+ },
+ },
+ {
+ id: 'corner', zh: '斜角色块', en: 'Corner wedge', fit: [...XHS, ...VIDEO, 'wechat'], zhUse: '白底 + 右下一大块斜切薄荷色 + 左上粗黑大字 + 黑色胶囊副标题 + 一条弯箭头;计划、清单、自律、学习,清爽有节奏', enUse: 'White with a big mint wedge from the lower right, a heavy headline top left, a black pill subtitle and a curved arrow; plans, lists and study',
+ build(i) {
+ const p = palette(i, { bg: '#ffffff', bg2: '#ffffff', ink: '#111111', sub: '#ffffff', accent: '#7ee0c3', accentInk: '#111111' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.1; const tw = (w - x0 * 2) * (wide ? 0.6 : 0.86);
+ const size = fitTitle(i.title, tw, h * (wide ? 0.5 : 0.34), 220 * u, 40, 1.08); const th = textHeight(i.title, tw, size, 1.08); const ty = m * 1.2 + (i.badge?.trim() ? Math.max(16, 20 * u) * 2.2 : 0);
+ const subS = Math.max(22, size * 0.24);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ new Polygon([{ x: w, y: h * (wide ? 0.05 : 0.3) }, { x: w, y: h }, { x: w * (wide ? 0.45 : 0.08), y: h }], { fill: p.accent, originX: 'left', originY: 'top' }),
+ grain(w, h, 0.05, 181),
+ i.badge?.trim() ? meta(i.badge.trim().toUpperCase(), x0, m * 1.1, w * 0.6, Math.max(16, 20 * u), p.ink, { qcRole: 'badge' }) : undefined,
+ textbox(i.title, x0, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08 }),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, x0, ty + th + 30 * u, p.ink, p.sub, subS, { qcRole: 'subtitle', radius: 0.5 })] : []),
+ arrow(w * (wide ? 0.72 : 0.62), h - m * 1.6, w - m * 1.2, h - m * (wide ? 3.2 : 4.2), -w * 0.04, p.ink, Math.max(6, 12 * u)),
+ ) };
+ },
+ },
+];
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/kit.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/kit.ts
new file mode 100644
index 00000000..c8527f3a
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/kit.ts
@@ -0,0 +1,128 @@
+/**
+ * Texture and craft primitives for templates: grain, paper, tape, stickers, tickers, soft light, seals. They are plain
+ * Fabric objects built synchronously, so a template stays a pure function, every piece stays editable, and a thumbnail
+ * renders exactly like the real cover. Nothing here loads files or touches the network.
+ */
+import { Circle, FabricObject, getEnv, Gradient, Line, Path, Pattern, Polygon, Rect, Shadow, Textbox } from 'fabric';
+import { BadgeBox } from './badge';
+
+type Role = FabricObject & { qcRole?: string };
+const tag = <T extends FabricObject>(o: T, role: string): T => { (o as Role).qcRole = role; return o; };
+
+/** A tile of film grain as a repeating pattern over the whole artboard. Undefined where no canvas exists (unit tests). */
+export function grain(w: number, h: number, opacity = 0.08, seed = 7): Rect | undefined {
+ try {
+ const doc = getEnv().document; if (!doc) return undefined;
+ const cv = doc.createElement('canvas'); cv.width = cv.height = 128; const ctx = cv.getContext('2d'); if (!ctx) return undefined;
+ const img = ctx.createImageData(128, 128); let x = seed * 9301 + 49297;
+ for (let i = 0; i < img.data.length; i += 4) { x = (x * 9301 + 49297) % 233280; const v = (x / 233280) * 255; img.data[i] = img.data[i + 1] = img.data[i + 2] = v; img.data[i + 3] = 255; }
+ ctx.putImageData(img, 0, 0);
+ return tag(new Rect({ left: 0, top: 0, width: w, height: h, originX: 'left', originY: 'top', fill: new Pattern({ source: cv, repeat: 'repeat' }), opacity, selectable: true, globalCompositeOperation: 'overlay' }), 'grain');
+ } catch { return undefined; }
+}
+
+/** A sheet of paper: slightly rotated, with a soft contact shadow. */
+export function paper(left: number, top: number, w: number, h: number, fill: string, angle = 0, u = 1, extra: Record<string, unknown> = {}): Rect {
+ return tag(new Rect({ left, top, width: w, height: h, fill, angle, originX: 'left', originY: 'top', shadow: new Shadow({ color: 'rgba(40,25,10,0.28)', blur: 22 * u, offsetX: 0, offsetY: 8 * u }), ...extra }), 'paper');
+}
+/** Translucent masking tape. */
+export function tape(left: number, top: number, w: number, h: number, angle: number, fill = 'rgba(255,224,120,0.78)'): Rect { return tag(new Rect({ left, top, width: w, height: h, fill, angle, originX: 'left', originY: 'top', opacity: 0.92 }), 'tape'); }
+
+/** An organic blob (one path, scaled and rotated). */
+export function blob(cx: number, cy: number, size: number, fill: string, opacity = 1, angle = 0): Path {
+ const p = new Path('M155 38c24 22 38 56 24 86s-52 56-88 50-62-38-60-72 22-58 56-70 44-14 68 6z', { fill, opacity, originX: 'center', originY: 'center', left: cx, top: cy, angle });
+ const k = size / 200; p.set({ scaleX: k, scaleY: k }); return p;
+}
+export function sparkle(cx: number, cy: number, size: number, fill: string, angle = 0): Path {
+ const p = new Path('M60 4C64 40 80 56 116 60 80 64 64 80 60 116 56 80 40 64 4 60 40 56 56 40 60 4z', { fill, originX: 'center', originY: 'center', left: cx, top: cy, angle }); const k = size / 120; p.set({ scaleX: k, scaleY: k }); return p;
+}
+/** A starburst: the classic price-tag shape. */
+export function burst(cx: number, cy: number, r: number, fill: string, points = 14, angle = 0): Polygon {
+ const pts: { x: number; y: number }[] = [];
+ for (let i = 0; i < points * 2; i++) { const rr = i % 2 ? r * 0.66 : r; const a = (i / (points * 2)) * Math.PI * 2; pts.push({ x: Math.cos(a) * rr, y: Math.sin(a) * rr }); }
+ return new Polygon(pts, { fill, originX: 'center', originY: 'center', left: cx, top: cy, angle });
+}
+/** Soft light: a radial gradient that fades to nothing, so there is never a visible edge. */
+export function glow(cx: number, cy: number, r: number, color: string, opacity = 0.6): Circle {
+ return tag(new Circle({ left: cx - r, top: cy - r, radius: r, originX: 'left', originY: 'top', opacity, fill: new Gradient({ type: 'radial', coords: { x1: r, y1: r, r1: 0, x2: r, y2: r, r2: r }, colorStops: [{ offset: 0, color }, { offset: 0.55, color: `${color}55` }, { offset: 1, color: `${color}00` }] }) }), 'glow');
+}
+/** A fine rule. */
+export function rule(x: number, y: number, len: number, color: string, weight = 2, vertical = false, opacity = 1): Line {
+ return new Line(vertical ? [0, 0, 0, len] : [0, 0, len, 0], { left: x, top: y, stroke: color, strokeWidth: weight, opacity, originX: 'left', originY: 'top', strokeLineCap: 'butt' });
+}
+/** Faded giant lettering behind the content: outline only, or a quiet fill. */
+export function ghost(text: string, left: number, top: number, size: number, color: string, opacity = 0.12, outline = false): Textbox {
+ return tag(new Textbox(text, { left, top, width: Math.max(size * text.length * 0.8, size), originX: 'left', originY: 'top', fontSize: size, fontWeight: 'bold', lineHeight: 0.9, fill: outline ? 'rgba(0,0,0,0)' : color, stroke: outline ? color : undefined, strokeWidth: outline ? Math.max(2, size * 0.012) : 0, opacity, selectable: true, splitByGrapheme: false }), 'ghost');
+}
+/** A repeating strip of words on a band, rotated: the "now playing" ticker. */
+export function ticker(w: number, y: number, h: number, word: string, size: number, fg: string, bg: string, angle = 0): FabricObject[] {
+ const unit = `${word} ✦ `; const reps = Math.ceil((w * 1.6) / Math.max(size * unit.length * 0.62, 1)) + 1;
+ const band = new Rect({ left: -w * 0.1, top: y, width: w * 1.2, height: h, fill: bg, originX: 'left', originY: 'top', angle });
+ const text = new Textbox(unit.repeat(reps), { left: -w * 0.08, top: y + (h - size * 1.2) / 2, width: w * 3, fontSize: size, fontWeight: 'bold', fill: fg, originX: 'left', originY: 'top', splitByGrapheme: false, angle, lineHeight: 1.2 });
+ const rad = (angle * Math.PI) / 180; const off = { x: -(h - size * 1.2) / 2 * Math.sin(rad), y: ((h - size * 1.2) / 2) * (Math.cos(rad) - 1) }; text.set({ left: (text.left ?? 0) + off.x, top: (text.top ?? 0) + off.y });
+ return [tag(band, 'ticker'), tag(text, 'ticker')];
+}
+/** A round sticker with a word on it. Longer words get smaller, so four characters still sit inside the disc. */
+export function stickerDot(cx: number, cy: number, r: number, fill: string, label: string, ink: string, angle = 0, ring?: string): FabricObject[] {
+ const dot = new Circle({ left: cx, top: cy, radius: r, fill, stroke: ring, strokeWidth: ring ? r * 0.08 : 0, originX: 'center', originY: 'center', angle, shadow: new Shadow({ color: 'rgba(0,0,0,0.22)', blur: r * 0.3, offsetX: 0, offsetY: r * 0.1 }) });
+ const t = new BadgeBox(label, { fontSize: r * Math.min(0.62, 1.5 / Math.max(1, [...label].length * (/[\u3400-\u9fff]/.test(label) ? 1 : 0.6))), fontWeight: 'bold', fill: ink, badgeBg: 'rgba(0,0,0,0)', padX: 0.2, padY: 0.2, originX: 'center', originY: 'center', left: cx, top: cy, angle, qcRole: 'badge' } as ConstructorParameters<typeof BadgeBox>[1]);
+ return [dot, t];
+}
+/** A red seal chop: a rounded square with one character reversed out. */
+export function seal(left: number, top: number, size: number, char: string, color = '#c0392b'): FabricObject[] {
+ const sq = new Rect({ left, top, width: size, height: size, rx: size * 0.1, ry: size * 0.1, fill: color, originX: 'left', originY: 'top', angle: -3, opacity: 0.92 });
+ const t = new BadgeBox(char.slice(0, 2), { fontSize: size * 0.56, fontWeight: 'bold', fill: '#f6efe0', badgeBg: 'rgba(0,0,0,0)', padX: 0.1, padY: 0.1, originX: 'center', originY: 'center', left: left + size / 2, top: top + size / 2, angle: -3, fontFamily: 'serif' } as ConstructorParameters<typeof BadgeBox>[1]);
+ return [sq, t];
+}
+
+/* ---------- print-poster system: the small marks that make a layout read as designed ---------- */
+/** Corner crop marks inside the artboard (two short strokes per corner). */
+export function cropMarks(w: number, h: number, inset: number, len: number, color: string, weight = 2): FabricObject[] {
+ const L = (x: number, y: number, dx: number, dy: number): Line => new Line([0, 0, dx * len, dy * len], { left: Math.min(x, x + dx * len), top: Math.min(y, y + dy * len), stroke: color, strokeWidth: weight, originX: 'left', originY: 'top' });
+ const out: FabricObject[] = [];
+ for (const [cx, cy, sx, sy] of [[inset, inset, 1, 1], [w - inset, inset, -1, 1], [inset, h - inset, 1, -1], [w - inset, h - inset, -1, -1]] as const) { out.push(L(cx, cy, sx, 0)); out.push(L(cx, cy, 0, sy)); }
+ return out;
+}
+/** A registration target: ring with a crosshair. */
+export function regMark(cx: number, cy: number, r: number, color: string, weight = 2): FabricObject[] {
+ return [
+ new Circle({ left: cx, top: cy, radius: r, fill: 'rgba(0,0,0,0)', stroke: color, strokeWidth: weight, originX: 'center', originY: 'center' }),
+ new Line([0, 0, r * 2.8, 0], { left: cx - r * 1.4, top: cy, stroke: color, strokeWidth: weight, originX: 'left', originY: 'top' }),
+ new Line([0, 0, 0, r * 2.8], { left: cx, top: cy - r * 1.4, stroke: color, strokeWidth: weight, originX: 'left', originY: 'top' }),
+ ];
+}
+/** Text that runs along an edge, rotated a quarter turn (up reads bottom-to-top). The box spans x..x+size and y..y+len. */
+export function sideText(text: string, x: number, y: number, len: number, size: number, color: string, dir: 'up' | 'down' = 'up', opacity = 1): Textbox {
+ const t = new Textbox(text, { left: dir === 'up' ? x : x + size, top: dir === 'up' ? y + len : y, width: len, fontSize: size, fill: color, originX: 'left', originY: 'top', angle: dir === 'up' ? -90 : 90, textAlign: 'center', charSpacing: 320, fontWeight: 'bold', splitByGrapheme: false, lineHeight: 1, opacity });
+ return t;
+}
+/** A small block of tracked-out caption lines, like the credits in a poster's corner. */
+export function metaBlock(lines: string[], left: number, top: number, width: number, size: number, color: string, align: 'left' | 'right' = 'left'): Textbox {
+ return new Textbox(lines.join('\n'), { left, top, width, fontSize: size, fill: color, originX: 'left', originY: 'top', fontWeight: 'bold', charSpacing: 160, lineHeight: 1.55, textAlign: align, splitByGrapheme: false });
+}
+/** A barcode-like strip of bars. */
+export function barcode(left: number, top: number, w: number, h: number, color: string, seed = 5): FabricObject[] {
+ const out: FabricObject[] = []; let x = left; let s = seed * 7919 + 13;
+ while (x < left + w) { s = (s * 9301 + 49297) % 233280; const bw = 2 + Math.floor((s / 233280) * 7); if ((s >> 3) % 3) out.push(new Rect({ left: x, top, width: bw, height: h, fill: color, originX: 'left', originY: 'top' })); x += bw + 2 + ((s >> 5) % 4); }
+ return out;
+}
+
+/* ---------- comic / thumbnail devices ---------- */
+/** Alternating rays fanning out from a point, as one path (a sunburst or manga speed lines). */
+export function rays(cx: number, cy: number, reach: number, n: number, fill: string, opacity = 0.1, rot = 0): Path {
+ let d = ''; for (let i = 0; i < n; i++) { const a0 = rot + (i / n) * Math.PI * 2, a1 = rot + ((i + 0.5) / n) * Math.PI * 2; d += `M${cx} ${cy}L${(cx + Math.cos(a0) * reach).toFixed(1)} ${(cy + Math.sin(a0) * reach).toFixed(1)}L${(cx + Math.cos(a1) * reach).toFixed(1)} ${(cy + Math.sin(a1) * reach).toFixed(1)}Z`; }
+ return tag(new Path(d, { fill, opacity, selectable: true }), 'rays');
+}
+/** A rounded-top window (arch), the shape behind a portrait in editorial layouts. */
+export function arch(left: number, top: number, w: number, h: number, fill: string, stroke?: string, strokeWidth = 0): Path {
+ const r = w / 2; return new Path(`M0 ${h}L0 ${r}A${r} ${r} 0 0 1 ${w} ${r}L${w} ${h}Z`, { left, top, fill, stroke, strokeWidth, originX: 'left', originY: 'top' });
+}
+/** A grid of dots, optionally fading toward one corner (halftone). */
+export function dotGrid(left: number, top: number, cols: number, rows: number, gap: number, r: number, fill: string, opacity = 0.2, fade = true): Circle[] {
+ const out: Circle[] = []; for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) { const k = fade ? 1 - (x / cols + y / rows) / 2.2 : 1; if (k > 0.12) out.push(new Circle({ left: left + x * gap, top: top + y * gap, radius: Math.max(1, r * k), fill, opacity, originX: 'center', originY: 'center' })); }
+ return out;
+}
+/** A comic caption box: white card, thick ink border and a hard shadow. */
+export function captionBox(left: number, top: number, w: number, h: number, u: number, fill = '#ffffff', ink = '#111111', angle = 0): Rect {
+ return new Rect({ left, top, width: w, height: h, fill, stroke: ink, strokeWidth: Math.max(4, 7 * u), angle, originX: 'left', originY: 'top', shadow: new Shadow({ color: ink, blur: 0, offsetX: 9 * u, offsetY: 9 * u }) });
+}
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/model.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/model.ts
new file mode 100644
index 00000000..b9aa2169
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/model.ts
@@ -0,0 +1,112 @@
+export type Background = { kind: 'solid'; color: string } | { kind: 'linear'; from: string; to: string; angle: number };
+export type ExportFormat = 'png' | 'jpeg' | 'webp';
+export type Destination = 'folder' | 'note' | 'system';
+export interface ExportPrefs {
+ format: ExportFormat; scale: number; quality: number; destination: Destination;
+ folder: string; systemDir: string; filename: string; insert: boolean; cover: boolean; copy: boolean; fitLimit: boolean;
+}
+export const EXPORT_DEFAULTS: ExportPrefs = {
+ format: 'jpeg', scale: 1, quality: 0.92, destination: 'folder', folder: '', systemDir: '', filename: '{name}-{platform}', insert: false, cover: false, copy: false, fitLimit: true,
+};
+export interface Design {
+ format: 'qiaomu-cover-design'; schema: 1; width: number; height: number; source?: string;
+ /** Platform preset id. Informational: width/height remain the source of truth. */
+ platform?: string; bg?: Background; export?: Partial<ExportPrefs>;
+ /** Id of the template this cover was laid out from. Lets a platform switch re-lay it out instead of just scaling it. */
+ template?: string;
+ /** The palette the cover's layers follow (bg, bg2, ink, sub, accent, accentInk), so a later colour change knows what to replace. */
+ palette?: { bg: string; bg2: string; ink: string; sub: string; accent: string; accentInk: string };
+ canvas: Record<string, unknown>;
+}
+export const MAX_SIDE = 4096;
+export const MIN_SIDE = 200;
+export function validSize(width: number, height: number): boolean {
+ return Number.isInteger(width) && Number.isInteger(height) && width >= MIN_SIDE && height >= MIN_SIDE && width <= MAX_SIDE && height <= MAX_SIDE;
+}
+const COLOR = /^#[\da-f]{6}$/i;
+export function validBackground(value: unknown): value is Background {
+ if (!value || typeof value !== 'object') return false;
+ const b = value as Record<string, unknown>;
+ if (b.kind === 'solid') return typeof b.color === 'string' && COLOR.test(b.color);
+ return b.kind === 'linear' && typeof b.from === 'string' && COLOR.test(b.from) && typeof b.to === 'string' && COLOR.test(b.to) && typeof b.angle === 'number' && Number.isFinite(b.angle);
+}
+/** File name from a template such as `{name}-{platform}-{date}`; never yields path separators. */
+export function renderFilename(template: string, vars: Record<string, string>): string {
+ const out = (template || '{name}').replace(/\{(\w+)\}/g, (_, key: string) => vars[key] ?? '');
+ return safeName(out.replace(/\s+/g, ' ').trim()).replace(/ +/g, '-');
+}
+export function folderPath(value: string): string {
+ const path = value.trim().replace(/\\/g,'/').replace(/\/+$/,'');
+ if (!path || path.startsWith('/') || /^[a-z]:/i.test(path) || path.split('/').some(p => !p || p === '..' || p === '.') || /[\x00-\x1f]/.test(path)) throw new Error('invalid-folder');
+ return path;
+}
+export function safeName(value: string): string {
+ return value.replace(/[\\/:*?"<>|\x00-\x1f]/g,' ').trim().replace(/^\.+|\.+$/g,'').trim().slice(0,100) || 'Cover';
+}
+function checkCanvas(value: unknown, depth = 0): void {
+ if (depth > 40) throw new Error('invalid-design');
+ if (!value || typeof value !== 'object') return;
+ for (const [key, item] of Object.entries(value)) {
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') throw new Error('invalid-design');
+ // Persisted image objects must be self-contained raster images. Never request remote URLs.
+ if (key === 'src' && (typeof item !== 'string' || !/^data:image\/(png|jpeg|webp);base64,[a-z0-9+/=\s]+$/i.test(item))) throw new Error('invalid-design');
+ checkCanvas(item, depth + 1);
+ }
+}
+export function parseDesign(raw: string): Design {
+ if (raw.length > 40_000_000) throw new Error('invalid-design');
+ const d = JSON.parse(raw) as Design;
+ if (!d || d.format !== 'qiaomu-cover-design' || d.schema !== 1 || !validSize(d.width,d.height) || !d.canvas || !Array.isArray(d.canvas.objects) || d.canvas.objects.length > 500 || (d.source !== undefined && typeof d.source !== 'string') || (d.platform !== undefined && typeof d.platform !== 'string') || (d.template !== undefined && typeof d.template !== 'string') || (d.bg !== undefined && !validBackground(d.bg)) || (d.export !== undefined && (typeof d.export !== 'object' || d.export === null))) throw new Error('invalid-design');
+ checkCanvas(d.canvas);
+ if (d.palette !== undefined && (typeof d.palette !== 'object' || d.palette === null || !['bg', 'bg2', 'ink', 'sub', 'accent', 'accentInk'].every(k => /^#[\da-f]{6}$/i.test(String((d.palette as Record<string, unknown>)[k]))))) delete d.palette;
+ return d;
+}
+/**
+ * Undo snapshots would otherwise hold one full copy of every embedded image per step.
+ * Images are replaced by a shared reference so 40 steps cost one copy.
+ */
+export class SnapshotCodec {
+ private images: string[] = []; private index = new Map<string, number>();
+ encode(design: Design): string {
+ return JSON.stringify(design, (key, value: unknown) => {
+ if (key !== 'src' || typeof value !== 'string' || !value.startsWith('data:image/')) return value;
+ let id = this.index.get(value);
+ if (id === undefined) { id = this.images.length; this.images.push(value); this.index.set(value, id); }
+ return `@img:${id}`;
+ });
+ }
+ decode(snapshot: string): Design {
+ return JSON.parse(snapshot, (key, value: unknown) => {
+ if (key === 'src' && typeof value === 'string' && value.startsWith('@img:')) {
+ const image = this.images[Number(value.slice(5))];
+ if (image === undefined) throw new Error('invalid-design');
+ return image;
+ }
+ return value;
+ }) as Design;
+ }
+}
+export class History {
+ private entries: string[] = []; private index = -1;
+ reset(value: string): void { this.entries = [value]; this.index = 0; }
+ /** Font metrics can normalize a restored snapshot without creating a new edit or losing redo. */
+ replaceCurrent(value: string): void { if (this.index >= 0) this.entries[this.index] = value; }
+ push(value: string): void {
+ if (value === this.entries[this.index]) return;
+ this.entries = this.entries.slice(0,this.index + 1); this.entries.push(value);
+ if (this.entries.length > 40) this.entries.shift();
+ this.index = this.entries.length - 1;
+ }
+ canStep(direction: -1|1): boolean { const i = this.index + direction; return i >= 0 && i < this.entries.length; }
+ step(direction: -1|1): string|undefined {
+ const index = this.index + direction;
+ if (index < 0 || index >= this.entries.length) return;
+ this.index = index; return this.entries[index];
+ }
+}
+export class SerialWriter {
+ private tail: Promise<void> = Promise.resolve();
+ run(task: () => Promise<void>): Promise<void> {
+ const result = this.tail.then(task); this.tail = result.catch(() => {}); return result;
+ }
+}
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/platforms.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/platforms.ts
new file mode 100644
index 00000000..01e723bb
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/platforms.ts
@@ -0,0 +1,55 @@
+/** Platform presets: sizes, feed overlays that cover parts of a cover, and file-size limits. */
+export interface Zone { x: number; y: number; w: number; h: number; zh: string; en: string }
+export interface Platform {
+ id: string; zh: string; en: string; icon: string; group: 'social' | 'video' | 'general';
+ width: number; height: number; zhHint: string; enHint: string;
+ /** Inner text-safe margin as a fraction of the shorter side. */
+ margin: number;
+ /** Areas the platform usually draws over the cover (timestamps, counters, buttons). */
+ avoid: Zone[];
+ /** Upload limit in bytes when the platform has a documented one. */
+ maxBytes?: number;
+}
+
+export const PLATFORMS: Platform[] = [
+ { id: 'xhs', zh: '小红书 · 3:4', en: 'Xiaohongshu · 3:4', icon: 'book-heart', group: 'social', width: 1080, height: 1440, margin: 0.06, avoid: [],
+ zhHint: '图文笔记封面,3:4 竖版最常用', enHint: 'Note cover, 3:4 portrait is the standard' },
+ { id: 'xhs-square', zh: '小红书 · 1:1', en: 'Xiaohongshu · 1:1', icon: 'square', group: 'social', width: 1080, height: 1080, margin: 0.07, avoid: [],
+ zhHint: '方形封面,信息流中更紧凑', enHint: 'Square cover, more compact in the feed' },
+ { id: 'youtube', zh: 'YouTube 缩略图', en: 'YouTube thumbnail', icon: 'play', group: 'video', width: 1280, height: 720, margin: 0.04, maxBytes: 2 * 1024 * 1024,
+ avoid: [{ x: 0.82, y: 0.86, w: 0.18, h: 0.14, zh: '时长标签', en: 'Duration' }],
+ zhHint: '1280×720,文件不超过 2MB,右下角会被时长遮挡', enHint: '1280×720, under 2MB; the duration badge covers the bottom-right corner' },
+ { id: 'bilibili', zh: 'B 站封面 · 16:10', en: 'Bilibili cover · 16:10', icon: 'tv', group: 'video', width: 1146, height: 717, margin: 0.04,
+ avoid: [{ x: 0, y: 0.84, w: 1, h: 0.16, zh: '播放数据条', en: 'Stats bar' }],
+ zhHint: '1146×717,信息流底部会叠加播放与弹幕数据', enHint: '1146×717; the feed overlays play counts along the bottom' },
+ { id: 'bilibili-43', zh: 'B 站投稿 · 4:3', en: 'Bilibili upload · 4:3', icon: 'tv', group: 'video', width: 1200, height: 900, margin: 0.05,
+ avoid: [{ x: 0, y: 0, w: 1, h: 0.08, zh: '信息流裁切', en: 'Cropped in feed' }, { x: 0, y: 0.78, w: 1, h: 0.22, zh: '裁切 + 播放数据条', en: 'Crop + stats bar' }],
+ zhHint: '1200×900 投稿封面;信息流里按 16:10 裁切,文字放在中间 80% 内', enHint: '1200×900 upload cover; the feed crops it to 16:10, keep type in the middle band' },
+ { id: 'bilibili-hd', zh: 'B 站 · 16:9 高清', en: 'Bilibili · 16:9 HD', icon: 'tv', group: 'video', width: 1920, height: 1080, margin: 0.04,
+ avoid: [{ x: 0, y: 0.86, w: 1, h: 0.14, zh: '播放数据条', en: 'Stats bar' }],
+ zhHint: '1920×1080,横版高清封面', enHint: '1920×1080 widescreen cover' },
+ { id: 'vertical', zh: '抖音 / 视频号 · 9:16', en: 'Douyin / Shorts · 9:16', icon: 'smartphone', group: 'video', width: 1080, height: 1920, margin: 0.06,
+ avoid: [{ x: 0, y: 0.78, w: 0.8, h: 0.22, zh: '标题与账号', en: 'Caption' }, { x: 0.84, y: 0.5, w: 0.16, h: 0.4, zh: '互动按钮', en: 'Buttons' }],
+ zhHint: '竖屏短视频封面,底部和右侧会被界面遮挡', enHint: 'Vertical video; captions and buttons cover the bottom and right' },
+ { id: 'wechat', zh: '公众号头图 · 2.35:1', en: 'WeChat banner · 2.35:1', icon: 'message-circle', group: 'social', width: 1410, height: 600, margin: 0.05, avoid: [],
+ zhHint: '文章头图,列表中会被裁为 1:1 小图,主体放中间', enHint: 'Article banner; the feed crops a square from the centre' },
+ { id: 'x', zh: 'X 封面 · 5:2', en: 'X header · 5:2', icon: 'at-sign', group: 'social', width: 1500, height: 600, margin: 0.05, avoid: [{ x: 0, y: 0.55, w: 0.3, h: 0.45, zh: '头像', en: 'Avatar' }],
+ zhHint: '个人主页横幅,头像会遮住左下角', enHint: 'Profile header; the avatar covers the lower-left' },
+ { id: 'square', zh: '方形 · 1:1', en: 'Square · 1:1', icon: 'square', group: 'general', width: 1080, height: 1080, margin: 0.06, avoid: [], zhHint: '通用方形', enHint: 'General square' },
+ { id: 'wide', zh: '横版 · 16:9', en: 'Landscape · 16:9', icon: 'rectangle-horizontal', group: 'general', width: 1920, height: 1080, margin: 0.05, avoid: [], zhHint: '通用横版', enHint: 'General landscape' },
+ { id: 'portrait', zh: '竖版 · 3:4', en: 'Portrait · 3:4', icon: 'rectangle-vertical', group: 'general', width: 1200, height: 1600, margin: 0.06, avoid: [], zhHint: '通用竖版', enHint: 'General portrait' },
+];
+
+export const DEFAULT_PLATFORM = 'xhs';
+export function platformById(id: string | undefined): Platform | undefined { return PLATFORMS.find(p => p.id === id); }
+export function platformFor(width: number, height: number, id?: string): Platform | undefined {
+ const exact = platformById(id);
+ if (exact && exact.width === width && exact.height === height) return exact;
+ return PLATFORMS.find(p => p.width === width && p.height === height);
+}
+export function platformName(p: Platform, zh: boolean): string { return zh ? p.zh : p.en; }
+export const GROUPS: { id: Platform['group']; zh: string; en: string }[] = [
+ { id: 'social', zh: '图文平台', en: 'Social' },
+ { id: 'video', zh: '视频平台', en: 'Video' },
+ { id: 'general', zh: '通用比例', en: 'General' },
+];
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/quality.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/quality.ts
new file mode 100644
index 00000000..3e5bc30b
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/quality.ts
@@ -0,0 +1,74 @@
+/**
+ * Automatic checks that run after the designer lays a cover out: text must stay readable on its background and clear of the
+ * parts of a platform's UI that cover the image (avatar, duration badge, stats bar). Pure geometry and colour, no canvas.
+ */
+export interface Box { x: number; y: number; w: number; h: number }
+export interface Zone extends Box { zh: string; en: string }
+
+const hexRgb = (hex: string): [number, number, number] | undefined => {
+ const m = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(hex.trim()); if (!m) return undefined; let h = m[1]!;
+ if (h.length === 3) h = [...h].map(c => c + c).join('');
+ return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
+};
+const lum = ([r, g, b]: [number, number, number]): number => {
+ const f = (v: number): number => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };
+ return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
+};
+/** WCAG contrast ratio (1–21) between two #hex colours; undefined when either is not plain hex. */
+export function contrast(a: string, b: string): number | undefined {
+ const x = hexRgb(a), y = hexRgb(b); if (!x || !y) return undefined;
+ const [hi, lo] = [lum(x), lum(y)].sort((p, q) => q - p) as [number, number]; return (hi + 0.05) / (lo + 0.05);
+}
+/** Whichever of near-black / white reads better on `bg`. */
+export function readableOn(bg: string): string { return (contrast('#111111', bg) ?? 21) >= (contrast('#ffffff', bg) ?? 1) ? '#111111' : '#ffffff'; }
+/** Keeps `fg` when it already has `min` contrast on `bg`, otherwise returns a readable replacement. */
+export function ensureReadable(fg: string, bg: string, min = 3): string {
+ const c = contrast(fg, bg); return c === undefined || c >= min ? fg : readableOn(bg);
+}
+/**
+ * The same hue, mixed toward black (or white on a dark ground) in small steps until it reaches `min` contrast on `bg`.
+ * For an accent that carries words: the colour stays recognisable instead of being swapped for black or white.
+ */
+export function toContrast(fg: string, bg: string, min = 3): string {
+ const a = hexRgb(fg), b = hexRgb(bg); if (!a || !b || (contrast(fg, bg) ?? 21) >= min) return fg;
+ const to = lum(b) > 0.4 ? 0 : 255; let out = fg;
+ for (let k = 1; k <= 20; k++) {
+ out = '#' + a.map(v => Math.round(v + (to - v) * k * 0.05).toString(16).padStart(2, '0')).join('');
+ if ((contrast(out, bg) ?? 0) >= min) break;
+ }
+ return out;
+}
+const hit = (a: Box, b: Box): boolean => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
+/**
+ * Where a text box should sit so it clears every avoid zone: the same x, moved up for zones in the lower half and down for
+ * zones in the upper half. Undefined when it already clears them or no move would keep it on the canvas.
+ */
+export function clearOfZones(box: Box, zones: Box[], canvasH: number, pad: number): number | undefined {
+ let y = box.y; let moved = false;
+ for (let pass = 0; pass < 3; pass++) {
+ const blocking = zones.find(z => hit({ ...box, y }, z)); if (!blocking) break;
+ const next = blocking.y + blocking.h / 2 > canvasH / 2 ? blocking.y - box.h - pad : blocking.y + blocking.h + pad; y = next; moved = true;
+ }
+ if (!moved || y < 0 || y + box.h > canvasH) return undefined; return y;
+}
+
+/**
+ * How big the words are when the cover is a card in a phone feed. Widths are the typical rendered card width in CSS px:
+ * a Xiaohongshu two-column card, a YouTube/Bilibili sidebar thumbnail, a WeChat share card.
+ */
+export const FEED_WIDTH: Record<string, number> = { xhs: 170, 'xhs-square': 170, portrait: 170, square: 170, youtube: 168, bilibili: 170, 'bilibili-43': 170, 'bilibili-hd': 170, wide: 168, vertical: 120, wechat: 150, x: 300 };
+export interface ThumbText { role: 'title' | 'subtitle'; size: number; text: string }
+export interface ThumbIssue { role: 'title' | 'subtitle'; kind: 'small' | 'long'; px?: number; min?: number }
+/** Below these the words blur into a smudge at feed size (glyph height in CSS px). */
+export const THUMB_MIN = { title: 11, subtitle: 6 };
+/** Problems a cover has at feed size: a headline or subtitle too small to read, or a headline too long to take in at a glance. */
+export function thumbCheck(texts: ThumbText[], canvasWidth: number, platformId?: string): ThumbIssue[] {
+ const k = (FEED_WIDTH[platformId ?? ''] ?? 150) / canvasWidth; const out: ThumbIssue[] = [];
+ for (const t of texts) {
+ const px = Math.round(t.size * k * 10) / 10; const min = THUMB_MIN[t.role];
+ if (px < min) out.push({ role: t.role, kind: 'small', px, min });
+ }
+ const title = texts.find(t => t.role === 'title');
+ if (title) { const flat = title.text.replace(/\s+/g, ''); const units = /[぀-鿿]/.test(flat) ? [...flat].length : flat.length / 2.2; if (units > 15) out.push({ role: 'title', kind: 'long' }); }
+ return out;
+}
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/templates.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/templates.ts
new file mode 100644
index 00000000..73739aa3
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/templates.ts
@@ -0,0 +1,1289 @@
+import { BadgeBox } from './badge';
+import { arch, barcode, blob, burst, cropMarks, dotGrid, glow as kitGlow, grain, metaBlock, paper, rays, regMark, rule, seal, sideText, sparkle, stickerDot, tape, ticker } from './kit';
+import { ghost } from './kit';
+import { Circle, FabricObject, getEnv, Gradient, Line, Polygon, Rect, Shadow, Textbox, TextboxProps, Triangle } from 'fabric';
+import { Background } from './model';
+import { GAODING } from './gaoding';
+import { toContrast } from './quality';
+
+/** Colours a template reads. An assistant (or the user) can override any of them without touching layout. */
+export interface Palette { bg: string; bg2: string; ink: string; sub: string; accent: string; accentInk: string }
+export interface Slot { x: number; y: number; w: number; h: number; radius: number }
+export interface TemplateInput { width: number; height: number; title: string; subtitle: string; zh: boolean; badge?: string; points?: string[]; palette?: Partial<Palette> }
+export interface TemplateResult { background: Background; objects: FabricObject[] }
+export interface Template {
+ id: string; zh: string; en: string;
+ /** Platform ids this layout was designed for. They sort first and get a "recommended" mark. */
+ fit: string[];
+ /** One line on when to pick it. Also shown to the assistant. */
+ zhUse: string; enUse: string;
+ /** The layout draws its own dark overlay, so a full-bleed picture can sit behind it. */
+ photo?: boolean;
+ /** Region reserved for a picture (a face, a product shot). Undefined when the layout has none at this size. */
+ slot?(i: TemplateInput): Slot | undefined;
+ build(i: TemplateInput): TemplateResult;
+}
+const XHS = ['xhs', 'xhs-square', 'portrait', 'square']; const VIDEO = ['youtube', 'bilibili', 'bilibili-43', 'bilibili-hd', 'wide']; const SHORT = ['vertical']; const BANNER = ['wechat', 'x'];
+
+import { titleFace, typeFor } from './typeset';
+const SANS = 'sans-serif';
+const SERIF = 'serif';
+
+interface TextOptions { qcRole?: string; fontSize: number; fill: string; fontWeight?: string; fontFamily?: string; lineHeight?: number; textAlign?: string; charSpacing?: number; stroke?: string; strokeWidth?: number; textBackgroundColor?: string; shadow?: Shadow; angle?: number; opacity?: number; fontStyle?: string }
+
+/**
+ * Textbox placed by its top-left corner. Any CJK text is wrapped here rather than by Fabric: Fabric's grapheme wrap splits Latin
+ * words ("A|I"), starts the next line with the space it broke at, and happily leaves one character alone on the last line.
+ */
+export function textbox(text: string, left: number, top: number, width: number, o: TextOptions): Textbox {
+ const own = hasCjk(text) && !!o.fontSize;
+ // Big CJK headlines end up at -18 tracking (see the finish pass below), so wrap them at that tracking.
+ const track = o.qcRole === 'title' && o.fontSize >= 64 ? -18 : o.charSpacing ?? 0;
+ const lines = own ? wrapLines(text, width, o.fontSize, o.fontWeight ?? 'normal', track) : undefined; const wrapped = !!lines && (lines.length > 1 || /\s/.test(text));
+ // Spaces inside a computed line become no-break spaces, so Fabric cannot break the line a second time with its own metrics.
+ const box = new Textbox(wrapped ? lines.map(glue).join('\n') : text, {
+ left, top, width, originX: 'left', originY: 'top', fontFamily: SANS, fontWeight: 'normal', lineHeight: 1.25, splitByGrapheme: hasCjk(text) && !wrapped, paintFirst: o.stroke ? 'stroke' : 'fill', ...o,
+ // The paired face goes in at construction: a Textbox only ever grows to fit, so a first layout in the wider fallback face would stick.
+ ...typeFor(o.qcRole, o.fontFamily ?? SANS, o.fontWeight), ...(own ? { charSpacing: track } : {}),
+ } as Partial<TextboxProps>);
+ // qcSource keeps the writer's own text (with their line breaks) so a re-layout starts from it, not from our wrapping.
+ if (wrapped) Object.assign(box, { qcWrapped: true, qcSource: text });
+ return box;
+}
+type Wrapped = Textbox & { qcWrapped?: boolean; qcSource?: string };
+const glue = (line: string): string => line.replace(/ /g, '\u00a0');
+/** The text as the writer typed it: their own line breaks survive, the breaks we inserted do not. */
+export function sourceOf(t: Textbox): string {
+ const q = t as Wrapped; if (!q.qcWrapped) return t.text;
+ return q.qcSource && unwrap(q.qcSource) === unwrap(t.text) ? q.qcSource : unwrap(t.text);
+}
+/** Wraps a text we wrapped before again, at its current width, size and real face (after a font loads or the box is resized). */
+export function rewrap(t: Textbox): void {
+ const q = t as Wrapped; if (!q.qcWrapped || !t.fontSize) return;
+ const src = sourceOf(t); const lines = wrapLines(src, t.width, t.fontSize, String(t.fontWeight), t.charSpacing ?? 0, t.fontFamily);
+ const next = lines.map(glue).join('\n'); if (next !== t.text) t.set({ text: next }); q.qcSource = src; t.initDimensions();
+}
+/** Undoes the hard line breaks `textbox` inserted, so a title can be re-laid-out at another width. */
+export function unwrap(text: string): string { return text.replace(/\u00a0/g, ' ').replace(/([A-Za-z0-9])\n([A-Za-z0-9])/g, '$1 $2').replace(/\n/g, ''); }
+
+let measureCtx: CanvasRenderingContext2D | null | undefined;
+/** Rendered width of a single line of text, in px. */
+export function textWidth(text: string, size: number, weight = 'bold'): number { return measure(text, size, weight); }
+/** Real rendered width when a canvas exists (the app), a close estimate otherwise (unit tests). Measures in the paired title face unless a family is given. */
+function measure(text: string, size: number, weight: string, family?: string): number {
+ try {
+ if (measureCtx === undefined) measureCtx = getEnv().document?.createElement('canvas').getContext('2d') ?? null;
+ if (measureCtx) { measureCtx.font = `${weight} ${size}px ${family ? `"${family}"` : titleFace()}, ${SANS}`; return measureCtx.measureText(text).width; }
+ } catch { measureCtx = null; }
+ let w = 0; for (const ch of text) w += hasCjk(ch) ? size : ch === ' ' ? size * 0.3 : size * 0.56; return w;
+}
+const CLOSING = /^[,。、!?;:)”’》】…,.!?;:)]$/;
+/** Greedy wrap that never splits a Latin word, never starts a line with closing punctuation and never strands one CJK character. */
+export function wrapLines(text: string, width: number, size: number, weight = 'bold', spacing = 0, family?: string): string[] {
+ const out: string[] = []; const track = size * spacing / 1000;
+ const fits = (s: string): boolean => measure(s, size, weight, family) + [...s].length * track <= width;
+ for (const para of text.split('\n')) {
+ const tokens = para.match(/[A-Za-z0-9][A-Za-z0-9.'’_+%$@#-]*|\s+|[\s\S]/gu) ?? []; let cur = ''; const start = out.length;
+ for (const tok of tokens) {
+ if (!cur) { if (tok.trim()) cur = tok; continue; }
+ if (fits((cur + tok).trimEnd()) || CLOSING.test(tok)) cur += tok;
+ else { out.push(cur.trimEnd()); cur = tok.trim() ? tok : ''; }
+ }
+ if (cur || out.length === start) out.push(cur.trimEnd());
+ // A lone CJK character on the last line reads as a mistake: borrow the previous line's last character.
+ const n = out.length;
+ if (n - start >= 2 && /^[^\sA-Za-z0-9]$/u.test(out[n - 1]!) && hasCjk(out[n - 1]!)) {
+ const prev = [...out[n - 2]!]; let take = 1; if (prev.length > 1 && CLOSING.test(prev[prev.length - 1]!)) take = 2;
+ if (prev.length - take >= 2 && hasCjk(prev.slice(-take).join(''))) { out[n - 2] = prev.slice(0, -take).join('').trimEnd(); out[n - 1] = prev.slice(-take).join('') + out[n - 1]; }
+ }
+ }
+ return out;
+}
+export function hasCjk(text: string): boolean { return /[぀-ヿ㐀-鿿豈-﫿＀-￯]/.test(text); }
+function rect(left: number, top: number, width: number, height: number, fill: string | Gradient<'linear'> | Gradient<'radial'>, extra: Record<string, unknown> = {}): Rect {
+ return new Rect({ left, top, width, height, fill, originX: 'left', originY: 'top', ...extra });
+}
+function gradient(w: number, h: number, from: string, to: string, angle = 180): Gradient<'linear'> {
+ const rad = (angle - 90) * Math.PI / 180; const dx = Math.cos(rad), dy = Math.sin(rad);
+ const half = Math.abs(w * dx) / 2 + Math.abs(h * dy) / 2;
+ return new Gradient({ type: 'linear', gradientUnits: 'pixels', coords: { x1: w / 2 - dx * half, y1: h / 2 - dy * half, x2: w / 2 + dx * half, y2: h / 2 + dy * half }, colorStops: [{ offset: 0, color: from }, { offset: 1, color: to }] });
+}
+export { gradient };
+
+const HEX = /^#(?:[\da-f]{3}|[\da-f]{6})$/i;
+/** Merges a template's own colours with valid overrides. Anything that is not a hex colour is ignored. */
+let lastPalette: Palette | undefined;
+/** The palette the most recent build resolved to; lets decoration pieces share the template's colours. */
+export const builtPalette = (): Palette | undefined => lastPalette;
+export function palette(i: TemplateInput, base: Palette): Palette {
+ const out = { ...base };
+ for (const key of Object.keys(base) as (keyof Palette)[]) { const v = i.palette?.[key]; if (typeof v === 'string' && HEX.test(v)) out[key] = v; }
+ if (i.palette?.bg && !i.palette.bg2 && HEX.test(i.palette.bg)) out.bg2 = i.palette.bg;
+ lastPalette = out; return out;
+}
+const solid = (c: string): Background => ({ kind: 'solid', color: c });
+const linear = (p: Palette, angle: number): Background => p.bg === p.bg2 ? solid(p.bg) : { kind: 'linear', from: p.bg, to: p.bg2, angle };
+
+/** Sizes follow the shorter side so one layout works on 3:4, 16:9 and 5:2. */
+function metrics(i: TemplateInput): { u: number; m: number; wide: boolean; tall: boolean; w: number; h: number } {
+ const w = i.width, h = i.height; const u = Math.min(w, h * 1.15) / 1000;
+ return { u, m: Math.round(Math.min(w, h) * 0.08), wide: w / h > 1.45, tall: h / w > 1.2, w, h };
+}
+/** Wrapped line count at a font size. CJK glyphs are square, Latin averages about 0.55 em. */
+export function lineCount(text: string, width: number, size: number): number { return wrapLines(text, width, size).length; }
+/** Fabric multiplies every line by an extra 1.13 on top of `lineHeight`. */
+const FABRIC_LINE = 1.13;
+/** Rendered height of wrapped text. */
+export function textHeight(text: string, width: number, size: number, lineHeight = 1.2): number { return lineCount(text, width, size) * size * lineHeight * FABRIC_LINE; }
+/** Largest font size whose wrapped title still fits the box. Short titles prefer two lines or fewer, and no size leaves an orphan. */
+export function fitTitle(text: string, width: number, maxHeight: number, max: number, min = 36, lineHeight = 1.2): number {
+ // Scale is what makes a cover feel designed: a very short headline is allowed to grow until the box stops it.
+ const units = [...text.replace(/\s+/g, '')].length * (hasCjk(text) ? 1 : 0.55);
+ max *= (units <= 3 ? 2.1 : units <= 5 ? 1.75 : units <= 8 ? 1.3 : 1) * 1.15;
+ const scan = (lineCap: number, floor: number): number | undefined => {
+ for (let size = max; size >= floor; size -= 4) {
+ const lines = wrapLines(text, width, size);
+ if (lines.length <= lineCap && lines.length * size * lineHeight * FABRIC_LINE <= maxHeight && !orphaned(lines) && lines.every(l => measure(l, size, 'bold') <= width + 1)) return size;
+ }
+ return undefined;
+ };
+ // Lines the writer broke themselves are kept one per line: their break is the design, so shrink before wrapping again.
+ const paras = text.split('\n').length;
+ if (paras > 1 && paras <= 4) return scan(paras, min + 1) ?? scan(99, min + 1) ?? min;
+ return (units <= 16 ? scan(2, Math.max(min, max * 0.5)) : undefined) ?? scan(99, min + 1) ?? min;
+}
+/** True when the last line is a lone character (CJK) or a very short word, which reads as a mistake. */
+export function orphaned(lines: string[]): boolean {
+ if (lines.length < 2) return false;
+ return lines.some(line => { const t = line.replace(/\s/g, ''); return [...t].length < (hasCjk(t) ? 2 : 3); });
+}
+const upper = (s: string): string => hasCjk(s) ? s : s.toUpperCase();
+
+/** A small filled pill with the word exactly centred in it (see badge.ts). Returns nothing when there is no text. */
+function pill(text: string, left: number, top: number, fill: string, ink: string, size: number, extra: Record<string, unknown> = {}): BadgeBox {
+ return new BadgeBox(text.trim(), { left, top, originX: 'left', originY: 'top', fontSize: size, fill: ink, badgeBg: fill, fontFamily: SANS, fontWeight: 'bold', ...typeFor(String(extra.qcRole ?? 'badge'), SANS, extra.fontWeight === undefined ? 'bold' : String(extra.fontWeight)), ...extra } as ConstructorParameters<typeof BadgeBox>[1]);
+}
+function badge(text: string | undefined, left: number, top: number, p: Palette, size: number, extra: Record<string, unknown> = {}): BadgeBox[] {
+ const t = text?.trim(); if (!t) return [];
+ const b = pill(t, left, top, p.accent, p.accentInk, Math.round(size * 1.3), { qcRole: 'badge', ...extra }); return [b];
+}
+/** A glow that fades to nothing at its rim; a flat translucent disc shows a hard edge and looks cheap. */
+function softGlow(left: number, top: number, radius: number, color: string, opacity: number): Circle {
+ return new Circle({ left, top, radius, originX: 'left', originY: 'top', opacity, fill: new Gradient({ type: 'radial', coords: { x1: radius, y1: radius, r1: 0, x2: radius, y2: radius, r2: radius }, colorStops: [{ offset: 0, color }, { offset: 0.5, color: `${color}55` }, { offset: 1, color: `${color}00` }] }) });
+}
+const shadowSoft = (u: number): Shadow => new Shadow({ color: 'rgba(0,0,0,0.25)', blur: 18 * u, offsetX: 0, offsetY: 6 * u });
+const shadowHard = (u: number, c = '#000000', d = 8): Shadow => new Shadow({ color: c, blur: 0, offsetX: d * u, offsetY: d * u });
+
+export const TEMPLATES: Template[] = [
+ {
+ id: 'minimal', zh: '简约白', en: 'Minimal', fit: [...XHS, ...BANNER], zhUse: '干净克制,适合观点、读书、知识类', enUse: 'Clean and restrained; opinions, reading, knowledge',
+ build(i) {
+ const p = palette(i, { bg: '#ffffff', bg2: '#ffffff', ink: '#171717', sub: '#737373', accent: '#171717', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2; const titleH = h * (wide ? 0.55 : 0.5);
+ const size = fitTitle(i.title, inner, titleH, 130 * u * (wide ? 1.1 : 1));
+ return { background: solid(p.bg), objects: [
+ rect(m, m, Math.min(inner, 180 * u), Math.max(4, 8 * u), p.accent),
+ ...badge(i.badge, m, m + 26 * u, p, Math.max(20, 28 * u)),
+ textbox(i.title, m, h * 0.3, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.18 }),
+ textbox(i.subtitle, m, h - m - 90 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 34 * u), fill: p.sub }),
+ ] };
+ },
+ },
+ {
+ id: 'editorial', zh: '杂志', en: 'Editorial', fit: [...BANNER, ...XHS], zhUse: '衬线大标题 + 细线,有质感,适合深度内容与公众号', enUse: 'Serif headline with rules; essays and articles',
+ build(i) {
+ const p = palette(i, { bg: '#f4efe4', bg2: '#f4efe4', ink: '#171717', sub: '#404040', accent: '#171717', accentInk: '#f4efe4' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.5, 124 * u);
+ return { background: solid(p.bg), objects: [
+ rect(m, m, inner, Math.max(3, 4 * u), p.ink),
+ textbox(i.badge?.trim() ? upper(i.badge.trim()) : 'COVER STORY', m, m + 26 * u, inner, { qcRole: 'badge', fontSize: Math.max(18, 24 * u), fill: p.ink, charSpacing: 300, fontWeight: 'bold' }),
+ textbox(i.title, m, h * 0.3, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.16 }),
+ rect(m, h - m - 110 * u, inner, Math.max(2, 3 * u), p.ink),
+ textbox(i.subtitle, m, h - m - 84 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 32 * u), fill: p.sub, fontFamily: SERIF }),
+ ] };
+ },
+ },
+ {
+ id: 'bold', zh: '醒目黄', en: 'Loud yellow', fit: [...XHS, ...VIDEO, ...SHORT], zhUse: '高饱和纯色 + 黑字,信息流里最抢眼', enUse: 'Saturated flat colour with black type; stops the scroll',
+ build(i) {
+ const p = palette(i, { bg: '#ffe04b', bg2: '#ffe04b', ink: '#111111', sub: '#111111', accent: '#111111', accentInk: '#ffe04b' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.55, 170 * u, 40, 1.1);
+ return { background: solid(p.bg), objects: [
+ ...badge(i.badge, m, m, p, Math.max(22, 32 * u)),
+ textbox(i.title, m, h * 0.2, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.1 }),
+ rect(m, h - m - 150 * u, Math.min(inner, 260 * u), Math.max(8, 18 * u), p.accent),
+ textbox(i.subtitle, m, h - m - 110 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(26, 38 * u), fill: p.sub, fontWeight: 'bold' }),
+ ] };
+ },
+ },
+ {
+ id: 'dark', zh: '深色科技', en: 'Dark tech', fit: [...VIDEO, ...BANNER, ...XHS], zhUse: '深底荧光点缀,适合 AI、编程、效率工具', enUse: 'Dark with a neon glow; AI, code, tools',
+ build(i) {
+ const p = palette(i, { bg: '#0a0a0a', bg2: '#1c1c22', ink: '#fafafa', sub: '#a1a1aa', accent: '#5eead4', accentInk: '#0a0a0a' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.5, 128 * u);
+ const glow = softGlow(w * 0.5, -h * 0.35, Math.max(w, h) * 0.42, p.accent, 0.5);
+ return { background: linear(p, 160), objects: [
+ glow, ...badge(i.badge ?? (i.zh ? '干货' : 'GUIDE'), m, m, p, Math.max(22, 30 * u)),
+ textbox(i.title, m, h * 0.28, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15 }),
+ textbox(i.subtitle, m, h - m - 90 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 34 * u), fill: p.sub }),
+ ] };
+ },
+ },
+ {
+ id: 'poster', zh: '大字报', en: 'Poster', fit: [...XHS, ...SHORT], zhUse: '满屏居中大字,情绪强,适合金句、避坑、警告', enUse: 'Full-bleed centred type; punchy statements',
+ build(i) {
+ const p = palette(i, { bg: '#e11d2e', bg2: '#e11d2e', ink: '#ffffff', sub: '#ffe4e6', accent: '#ffe04b', accentInk: '#111111' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.7, 210 * u, 40, 1.05);
+ return { background: solid(p.bg), objects: [
+ ...badge(i.badge, m, m, p, Math.max(22, 32 * u)),
+ textbox(i.title, m, h * 0.5 - textHeight(i.title, inner, size, 1.05) / 2, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.05, textAlign: 'center' }),
+ textbox(i.subtitle, m, h - m - 70 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 32 * u), fill: p.sub, textAlign: 'center' }),
+ ] };
+ },
+ },
+ {
+ id: 'split', zh: '左文右图', en: 'Split', fit: [...VIDEO, ...BANNER], zhUse: '左文案右主体,右侧可放人像或产品图', enUse: 'Copy left, subject right; leaves room for a portrait or product',
+ slot: i => { const { w, h } = metrics(i); const x = w * 0.54; return { x, y: 0, w: w - x, h, radius: 0 }; },
+ build(i) {
+ const p = palette(i, { bg: '#fff7ed', bg2: '#fff7ed', ink: '#1c1917', sub: '#57534e', accent: '#f97316', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const left = w * 0.54; const inner = left - m * 1.6;
+ const size = fitTitle(i.title, inner, h * 0.6, 120 * u * 1.15);
+ const panel = rect(left, 0, w - left, h, p.accent);
+ const circle = new Circle({ left: left + (w - left) * 0.18, top: h * 0.2, radius: Math.min(w - left, h) * 0.33, fill: p.bg, originX: 'left', originY: 'top' });
+ return { background: solid(p.bg), objects: [
+ panel, circle, ...badge(i.badge, m, m, p, Math.max(20, 28 * u)),
+ textbox(i.title, m, h * 0.2, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15 }),
+ textbox(i.subtitle, m, h - m - 80 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(22, 30 * u), fill: p.sub }),
+ ] };
+ },
+ },
+ {
+ id: 'sticker', zh: '便签', en: 'Sticky note', fit: XHS, zhUse: '粉底便签纸,生活感,适合种草、日常、分享', enUse: 'Pink backdrop, paper note; lifestyle posts',
+ build(i) {
+ const p = palette(i, { bg: '#fda4af', bg2: '#fda4af', ink: '#292524', sub: '#78716c', accent: '#fcd34d', accentInk: '#292524' });
+ const { u, m, w, h } = metrics(i); const pad = m * 1.4; const cardW = w - m * 2; const cardH = h - m * 2;
+ const size = fitTitle(i.title, cardW - pad * 2, cardH * 0.5, 120 * u);
+ const card = rect(m, m, cardW, cardH, '#fffbea', { rx: 24 * u, ry: 24 * u, shadow: new Shadow({ color: 'rgba(0,0,0,0.18)', blur: 30 * u, offsetX: 0, offsetY: 14 * u }) });
+ const tape = rect(w / 2 - 90 * u, m - 18 * u, 180 * u, 44 * u, p.accent, { opacity: 0.85 });
+ return { background: solid(p.bg), objects: [
+ card, tape, ...badge(i.badge, m + pad, m + pad * 0.7, p, Math.max(20, 28 * u)),
+ textbox(i.title, m + pad, m + cardH * 0.22, cardW - pad * 2, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.18 }),
+ textbox(i.subtitle, m + pad, m + cardH - pad - 60 * u, cardW - pad * 2, { qcRole: 'subtitle', fontSize: Math.max(22, 30 * u), fill: p.sub }),
+ ] };
+ },
+ },
+ {
+ id: 'gradient', zh: '渐变光感', en: 'Soft gradient', fit: [...VIDEO, ...BANNER, ...XHS], zhUse: '蓝青渐变 + 白字,通用、稳、不出错', enUse: 'Blue-cyan gradient with white type; safe and versatile',
+ build(i) {
+ const p = palette(i, { bg: '#2563eb', bg2: '#06b6d4', ink: '#ffffff', sub: '#e0f2fe', accent: '#ffffff', accentInk: '#1d4ed8' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.5, 128 * u);
+ const tri = new Triangle({ left: w * 0.62, top: h * 0.08, width: w * 0.5, height: w * 0.5, fill: '#ffffff', opacity: 0.12, angle: 18, originX: 'left', originY: 'top' });
+ return { background: linear(p, 135), objects: [
+ tri, ...badge(i.badge, m, m, p, Math.max(20, 28 * u)),
+ textbox(i.title, m, h * 0.3, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15, shadow: shadowSoft(u) }),
+ textbox(i.subtitle, m, h - m - 84 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 34 * u), fill: p.sub }),
+ ] };
+ },
+ },
+ {
+ id: 'center', zh: '居中标签', en: 'Centered', fit: [...XHS, ...VIDEO], zhUse: '细框居中,黄色高亮副标,通用百搭', enUse: 'Thin frame, centred, highlighted subtitle; all-purpose',
+ build(i) {
+ const p = palette(i, { bg: '#fafafa', bg2: '#fafafa', ink: '#171717', sub: '#262626', accent: '#ffe04b', accentInk: '#171717' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 3.2;
+ const size = fitTitle(i.title, inner, h * 0.5, 120 * u);
+ const th = textHeight(i.title, inner, size, 1.2);
+ return { background: solid(p.bg), objects: [
+ rect(m * 0.6, m * 0.6, w - m * 1.2, h - m * 1.2, 'rgba(0,0,0,0)', { stroke: p.ink, strokeWidth: Math.max(3, 5 * u) }),
+ ...badge(i.badge, 0, m * 1.1, p, Math.max(20, 28 * u)).map(b => { b.set({ left: w / 2 - b.width / 2 }); return b; }),
+ textbox(i.title, m * 1.6, h * 0.5 - th / 2 - 20 * u, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.2, textAlign: 'center' }),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, 0, Math.min(h - m * 2, h * 0.5 + th / 2 + 40 * u), p.accent, p.sub, Math.max(24, 32 * u), { qcRole: 'subtitle', fontWeight: 'normal' })].map(b => { b.set({ left: w / 2 - b.width / 2 }); return b; }) : []),
+ ] };
+ },
+ },
+ {
+ id: 'checklist', zh: '清单笔记', en: 'Checklist', fit: [...XHS], zhUse: '标题 + 3~4 条要点,信息密度高,小红书干货首选', enUse: 'Headline plus 3–4 points; dense and useful',
+ build(i) {
+ const p = palette(i, { bg: '#ecfdf3', bg2: '#ecfdf3', ink: '#052e16', sub: '#166534', accent: '#16a34a', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.3, 104 * u);
+ const listTop = Math.max(h * 0.4, m + 50 * u + textHeight(i.title, inner, size, 1.15) + 56 * u);
+ const rows = (i.points?.length ? i.points : i.subtitle.split(/[\n,,、;;]/)).map(s => s.trim()).filter(Boolean).slice(0, 4);
+ const items = (rows.length > 1 ? rows : ['01', '02', '03']).map((label, index) => textbox(rows.length > 1 ? `${index + 1} ${label}` : `${label} ${i.zh ? '要点' : 'Point'}`, m, listTop + index * 132 * u, inner, { fontSize: Math.max(30, 60 * u), fill: p.ink, fontWeight: 'bold' }));
+ return { background: solid(p.bg), objects: [
+ rect(m, m, 120 * u, Math.max(6, 12 * u), p.accent),
+ ...badge(i.badge, m + 150 * u, m - 12 * u, p, Math.max(20, 28 * u)),
+ textbox(i.title, m, m + 50 * u, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15 }),
+ ...items,
+ ] };
+ },
+ },
+ {
+ id: 'number', zh: '数字干货', en: 'Big number', fit: [...XHS, ...SHORT, 'youtube', 'bilibili', 'bilibili-43'], zhUse: '超大数字做钩子(7 个技巧 / 3 步),点击率高的榜单体', enUse: 'A huge numeral as the hook; listicles',
+ slot: i => { const { w, h, wide } = metrics(i); return wide ? undefined : { x: 0, y: h * 0.68, w, h: h * 0.32, radius: 0 }; },
+ build(i) {
+ const p = palette(i, { bg: '#fff7e6', bg2: '#fff7e6', ink: '#1a1a1a', sub: '#6b6b6b', accent: '#ef4444', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const num = /^[\d.+%×x-]{1,4}$/i.test(i.badge?.trim() ?? '') ? i.badge!.trim() : digits(i); // the hook is a numeral; a word like "实测" would overflow it
+ const cw = hasCjk(num) ? 1.05 : 0.64; const numSize = Math.round(wide ? Math.min(h * 0.66, (w * 0.32) / ([...num].length * cw)) : Math.min(h * 0.25, (w - m * 2) / ([...num].length * cw)));
+ if (wide) {
+ const left = m + w * 0.38; const inner = w - left - m; const size = fitTitle(i.title, inner, h * 0.5, 132 * u); const th = textHeight(i.title, inner, size, 1.15);
+ const subS = Math.max(22, size * 0.32); const subH = i.subtitle.trim() ? textHeight(i.subtitle, inner, subS, 1.25) + 24 * u : 0; const ty = (h - th - subH) / 2;
+ return { background: solid(p.bg), objects: [
+ textbox(num, m, h / 2 - numSize * 0.6, w * 0.36, { qcRole: 'badge', fontSize: numSize, fill: p.accent, fontWeight: 'bold', lineHeight: 1.05 }),
+ rect(left - m * 0.6, h * 0.22, Math.max(4, 8 * u), h * 0.56, p.ink),
+ textbox(i.title, left, ty, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15 }),
+ ...sub(i, left, ty + th + 24 * u, inner, subS, p.sub),
+ ] };
+ }
+ const inner = w - m * 2; const titleTop = m * 0.6 + numSize * 1.05 * 1.13 + 34 * u; const size = fitTitle(i.title, inner, Math.max(h * 0.12, h * 0.6 - titleTop), 150 * u, 32);
+ return { background: solid(p.bg), objects: [
+ textbox(num, m, m * 0.6, inner, { qcRole: 'badge', fontSize: numSize, fill: p.accent, fontWeight: 'bold', lineHeight: 1.05 }),
+ rect(m, m * 0.6 + numSize * 1.05 * 1.13, Math.min(inner, 220 * u), Math.max(8, 14 * u), p.ink),
+ textbox(i.title, m, m * 0.6 + numSize * 1.12 * 1.13 + 34 * u, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15 }),
+ textbox(i.subtitle, m, h * 0.62, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 32 * u), fill: p.sub }),
+ ] };
+ },
+ },
+ {
+ id: 'impact', zh: '油管冲击', en: 'Impact', fit: ['youtube', 'bilibili', 'bilibili-43', 'bilibili-hd', 'wide', 'vertical'], zhUse: '黄字黑描边 + 红标,右侧留人像位;短标题(≤8 字)效果最好', enUse: 'Yellow type with a black outline, red tag, subject area on the right; keep titles short',
+ photo: true,
+ slot: i => { const { w, h, wide } = metrics(i); return wide ? { x: w * 0.6, y: 0, w: w * 0.4, h, radius: 0 } : undefined; },
+ build(i) {
+ const p = palette(i, { bg: '#0b1020', bg2: '#1d2b64', ink: '#ffe14a', sub: '#ffffff', accent: '#ef233c', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = wide ? w * 0.58 - m : w - m * 2;
+ const shown = upper(i.title); const size = fitTitle(shown, inner, h * (wide ? 0.62 : 0.5), 230 * u, 44, 1.05);
+ const top = h - m * 1.1 - (i.subtitle.trim() ? 90 * u : 0) - textHeight(shown, inner, size, 1.05);
+ const glow = softGlow(w * (wide ? 0.56 : 0.4), -h * 0.05, Math.min(w, h) * 0.62, p.accent, 0.55);
+ const scrim = rect(0, h * 0.35, w, h * 0.65, new Gradient({ type: 'linear', gradientUnits: 'pixels', coords: { x1: 0, y1: 0, x2: 0, y2: h * 0.65 }, colorStops: [{ offset: 0, color: 'rgba(0,0,0,0)' }, { offset: 1, color: 'rgba(0,0,0,0.65)' }] }), { qcRole: 'scrim' });
+ return { background: linear(p, 135), objects: [
+ glow, scrim,
+ ...badge(i.badge, m, m, p, Math.max(26, 40 * u), { fontWeight: 'bold' }),
+ textbox(shown, m, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.05, stroke: '#000000', strokeWidth: Math.max(8, 14 * u), shadow: shadowHard(u, '#000000', 7) }),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, m, 0, 'rgba(0,0,0,0.55)', p.sub, Math.max(24, 36 * u), { qcRole: 'subtitle', radius: 0.18 })].map(b => { b.set({ top: h - m - b.height }); return b; }) : []),
+ ] };
+ },
+ },
+
+ {
+ id: 'compare', zh: '对比', en: 'Versus', fit: [...XHS, ...VIDEO], zhUse: '左右两栏对比:副标题用 “A | B” 或“前 | 后”,评测 / 前后效果', enUse: 'Two panels; subtitle as “A | B”; reviews and before/after',
+ build(i) {
+ const p = palette(i, { bg: '#f8fafc', bg2: '#f8fafc', ink: '#0f172a', sub: '#334155', accent: '#16a34a', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2;
+ const parts = (i.points?.length ? i.points : i.subtitle.split(/\s*(?:\||||\bvs\.?\b|VS|对比|→)\s*/i)).map(s => s.trim()).filter(Boolean);
+ const a = parts[0] ?? (i.zh ? '之前' : 'Before'); const b = parts[1] ?? (i.zh ? '之后' : 'After');
+ const titleSize = fitTitle(i.title, inner, h * 0.22, 100 * u, 32, 1.12); const top = m + (i.badge?.trim() ? 64 * u : 0); const panelTop = top + textHeight(i.title, inner, titleSize, 1.12) + 24 * u; const panelH = h - panelTop - m;
+ const gap = 28 * u; const pw = wide ? (inner - gap) / 2 : inner; const ph = wide ? panelH : (panelH - gap) / 2;
+ const panel = (x: number, y: number, fill: string, ink: string, label: string, mark: string): FabricObject[] => {
+ const fs = Math.max(30, Math.min(ph * 0.3, pw / Math.max(3, [...label].length * (hasCjk(label) ? 1 : 0.6)) * 1.1, 96 * u));
+ return [rect(x, y, pw, ph, fill, { rx: 28 * u, ry: 28 * u }),
+ textbox(mark, x + 28 * u, y + 20 * u, pw - 56 * u, { fontSize: Math.max(24, 44 * u), fill: ink, fontWeight: 'bold', opacity: 0.9 }),
+ textbox(label, x + 28 * u, y + ph / 2 - textHeight(label, pw - 56 * u, fs, 1.15) / 2, pw - 56 * u, { fontSize: fs, fill: ink, fontWeight: 'bold', lineHeight: 1.15 })];
+ };
+ const vs = new Circle({ left: wide ? m + pw + gap / 2 - 44 * u : w / 2 - 44 * u, top: wide ? panelTop + ph / 2 - 44 * u : panelTop + ph + gap / 2 - 44 * u, radius: 44 * u, fill: p.ink, stroke: p.bg, strokeWidth: 8 * u, originX: 'left', originY: 'top' });
+ const vsText = textbox('VS', vs.left, vs.top + 26 * u, 88 * u, { fontSize: Math.max(22, 34 * u), fill: p.bg, fontWeight: 'bold', textAlign: 'center' });
+ return { background: solid(p.bg), objects: [
+ ...badge(i.badge, m, m, p, Math.max(20, 28 * u)),
+ textbox(i.title, m, top, inner, { qcRole: 'title', fontSize: titleSize, fill: p.ink, fontWeight: 'bold', lineHeight: 1.12 }),
+ ...panel(m, panelTop, '#fee2e2', '#991b1b', a, '✕'),
+ ...panel(wide ? m + pw + gap : m, wide ? panelTop : panelTop + ph + gap, '#dcfce7', '#166534', b, '✓'),
+ vs, vsText,
+ ] };
+ },
+ },
+ {
+ id: 'neo', zh: '新粗野', en: 'Neo-brutal', fit: [...XHS, ...VIDEO, ...SHORT], zhUse: '黑粗框 + 硬阴影 + 荧光底,年轻、有趣、辨识度高', enUse: 'Thick black borders, hard shadows, bright backdrop',
+ build(i) {
+ const p = palette(i, { bg: '#a3e635', bg2: '#a3e635', ink: '#111111', sub: '#111111', accent: '#ff5fa2', accentInk: '#111111' });
+ const { u, m, w, h } = metrics(i); const bw = Math.max(5, 8 * u); const cx = m * 0.9; const cw = w - cx * 2; const ch = h - cx * 2; const pad = m * 0.9;
+ const size = fitTitle(i.title, cw - pad * 2, ch * 0.55, 140 * u, 38, 1.12);
+ const th = textHeight(i.title, cw - pad * 2, size, 1.12); const subS = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? subS * 1.7 + 34 * u : 0; const ty = cx + (ch - th - subH) / 2;
+ const card = rect(cx, cx, cw, ch, '#ffffff', { stroke: p.ink, strokeWidth: bw, rx: 14 * u, ry: 14 * u, shadow: shadowHard(u, p.ink, 16) });
+ const tag = pill(i.badge?.trim() || (i.zh ? '必看' : 'MUST'), 0, cx - 22 * u, p.accent, p.accentInk, Math.max(22, 36 * u), { qcRole: 'badge', angle: 5, radius: 0.2 }); tag.set({ left: cx + cw - tag.width - 24 * u });
+ return { background: solid(p.bg), objects: [
+ card, tag,
+ textbox(i.title, cx + pad, ty, cw - pad * 2, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.12 }),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, cx + pad, ty + th + 34 * u, '#ffe04b', p.sub, subS, { qcRole: 'subtitle', radius: 0.2 })] : []),
+ ] };
+ },
+ },
+ {
+ id: 'soft', zh: '柔雾莫兰迪', en: 'Soft haze', fit: [...XHS, ...BANNER], zhUse: '低饱和柔光,适合生活方式、情绪、穿搭、女性向', enUse: 'Muted haze; lifestyle, mood, fashion',
+ build(i) {
+ const p = palette(i, { bg: '#f6e7e3', bg2: '#e4dcf3', ink: '#3b2f4a', sub: '#7a6b8a', accent: '#b794d6', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2; const size = fitTitle(i.title, inner, h * 0.46, 118 * u);
+ const blob = (x: number, y: number, r: number, c: string, o: number): Circle => new Circle({ left: x, top: y, radius: r, fill: c, opacity: o, originX: 'left', originY: 'top' });
+ return { background: linear(p, 150), objects: [
+ blob(w * 0.52, -h * 0.12, Math.min(w, h) * 0.5, '#ffffff', 0.5), blob(-w * 0.12, h * 0.62, Math.min(w, h) * 0.46, p.accent, 0.28), blob(w * 0.7, h * 0.66, Math.min(w, h) * 0.2, '#f9a8d4', 0.4),
+ ...badge(i.badge, m, m, p, Math.max(20, 28 * u)),
+ textbox(i.title, m, h * 0.3, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.2 }),
+ textbox(i.subtitle, m, h - m - 84 * u, inner, { qcRole: 'subtitle', fontSize: Math.max(24, 32 * u), fill: p.sub }),
+ ] };
+ },
+ },
+];
+export function templateById(id: string): Template | undefined { return TEMPLATES.find(t => t.id === id); }
+
+/* ---------- premium templates: each one a distinct, finished visual style ---------- */
+const keep = <T,>(...xs: (T | undefined | false)[]): T[] => xs.filter((x): x is T => !!x);
+const meta = (text: string, left: number, top: number, width: number, size: number, fill: string, o: Partial<TextOptions> = {}): Textbox => textbox(text, left, top, width, { fontSize: size, fill, fontWeight: 'bold', charSpacing: 220, lineHeight: 1.1, ...o });
+const sub = (i: TemplateInput, left: number, top: number, width: number, size: number, fill: string, o: Partial<TextOptions> = {}): Textbox[] => i.subtitle.trim() ? [textbox(i.subtitle, left, top, width, { qcRole: 'subtitle', fontSize: size, fill, ...o })] : [];
+
+const PREMIUM: Template[] = [
+ {
+ id: 'swiss', zh: '瑞士网格', en: 'Swiss grid', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '米白底 + 红圆 + 极粗无衬线 + 网格细线,国际主义风格', enUse: 'Off-white, a red disc, ultra-bold sans and grid hairlines',
+ build(i) {
+ const p = palette(i, { bg: '#f3f1ea', bg2: '#f3f1ea', ink: '#111111', sub: '#555555', accent: '#e63312', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2; const tw = wide ? inner * 0.7 : inner;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.58 : 0.4), 230 * u, 40, 0.98); const th = textHeight(i.title, tw, size, 0.98);
+ const r = Math.min(w, h) * (wide ? 0.34 : 0.3); const subSize = Math.max(26, 36 * u); const top = h - m - (i.subtitle.trim() ? subSize * 1.5 + 30 * u : 0) - th;
+ const cols = wide ? 6 : 4;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.06, 3),
+ ...Array.from({ length: cols - 1 }, (_, k) => rule(m + (inner / cols) * (k + 1), 0, h, p.ink, Math.max(1, u), true, 0.1)),
+ new Circle({ left: w - r * 1.1, top: m * 0.9, radius: r, fill: p.accent, originX: 'left', originY: 'top' }),
+ i.badge?.trim() ? textbox(i.badge.trim(), m, m * 0.8, inner * 0.4, { qcRole: 'badge', fontSize: Math.max(60, 120 * u), fill: p.ink, fontWeight: 'bold', lineHeight: 1, charSpacing: -30 }) : undefined,
+ meta('NO. — / 2026', m, m * 0.8 + (i.badge?.trim() ? Math.max(60, 120 * u) * 1.15 : 0), inner * 0.5, Math.max(16, 20 * u), p.sub),
+ textbox(i.title, m, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 0.98, charSpacing: -30 }),
+ ...sub(i, m, top + th + 26 * u, tw, subSize, p.sub, { fontWeight: 'bold' }),
+ ) };
+ },
+ },
+ {
+ id: 'acid', zh: '酸性渐变', en: 'Acid mesh', fit: [...XHS, ...VIDEO, ...SHORT], zhUse: '浅粉紫弥散光斑 + 颗粒 + 居中深紫大字 + 一枚闪光;潮流、音乐、AI 话题', enUse: 'Pastel mesh glows and grain, a centred deep-violet headline and one sparkle; trendy, music, AI',
+ build(i) {
+ const p = palette(i, { bg: '#ffe3ef', bg2: '#ddd3ff', ink: '#24104a', sub: '#5b3f8c', accent: '#ff3d8b', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2; const tw = wide ? inner * 0.82 : inner;
+ const size = fitTitle(i.title, tw, h * 0.5, 210 * u, 40, 1.02); const th = textHeight(i.title, tw, size, 1.02);
+ const subS = Math.max(26, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, inner, subS, 1.25) + 30 * u : 0; const bs = Math.max(20, size * 0.18); const bH = i.badge?.trim() ? bs * 1.3 * 1.7 + 30 * u : 0;
+ const top = (h - th - subH - bH) / 2 + bH;
+ return { background: linear(p, 160), objects: keep<FabricObject>(
+ kitGlow(w * 0.15, h * 0.28, Math.min(w, h) * 0.6, p.accent, 0.5), kitGlow(w * 0.88, h * 0.78, Math.min(w, h) * 0.55, '#38bdf8', 0.5), kitGlow(w * 0.55, h * 0.02, Math.min(w, h) * 0.4, '#fde047', 0.7),
+ grain(w, h, 0.12, 11),
+ ...badge(i.badge, 0, top - bH, p, bs, { angle: -4 }).map(b => { b.set({ left: w / 2 - b.width / 2 }); return b; }),
+ textbox(i.title, m + (inner - tw) / 2, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.02, textAlign: 'center' }),
+ ...sub(i, m, top + th + 30 * u, inner, subS, p.sub, { textAlign: 'center', fontWeight: 'bold' }),
+ sparkle(w - m * 1.3, wide ? h * 0.2 : h * 0.14, 90 * u, p.accent, 12),
+ ) };
+ },
+ },
+ {
+ id: 'collage', zh: '拼贴手账', en: 'Paper collage', fit: [...XHS, 'bilibili', 'wechat'], zhUse: '牛皮纸 + 撕纸色块 + 胶带 + 贴纸,生活、手账、种草', enUse: 'Kraft paper, torn colour blocks, tape and stickers; lifestyle and journaling',
+ build(i) {
+ const p = palette(i, { bg: '#e6d5b8', bg2: '#e6d5b8', ink: '#2b2118', sub: '#6e5b45', accent: '#ef6f4f', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const pw = w - m * 2.2; const ph = h * (wide ? 0.7 : 0.52); const px = (w - pw) / 2; const py = (h - ph) / 2;
+ const inner = pw - m * 1.4; const size = fitTitle(i.title, inner, ph * 0.56, 170 * u, 36, 1.08); const th = textHeight(i.title, inner, size, 1.08);
+ const ty = py + (ph - th - (i.subtitle.trim() ? 80 * u : 0)) / 2;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.12, 5), blob(w * 0.82, h * 0.2, Math.min(w, h) * 0.55, p.accent, 0.9, 20), blob(w * 0.14, h * 0.82, Math.min(w, h) * 0.45, '#8ec5a3', 0.85, -30),
+ rect(px - 18 * u, py + 22 * u, pw, ph, p.accent, { angle: 3 }),
+ paper(px, py, pw, ph, '#fffaf0', -1.6, u),
+ tape(px + pw * 0.12, py - 22 * u, 160 * u, 46 * u, -8), tape(px + pw * 0.72, py + ph - 24 * u, 150 * u, 44 * u, 6, 'rgba(255,140,170,0.7)'),
+ textbox(i.title, px + m * 0.7, ty, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08, charSpacing: -14, angle: -1.6 }),
+ ...sub(i, px + m * 0.7, ty + th + 22 * u, inner, Math.max(26, 38 * u), p.sub, { angle: -1.6 }),
+ ...(i.badge?.trim() ? stickerDot(px + pw - 40 * u, py - 10 * u, 78 * u, '#ffd23f', i.badge.trim(), p.ink, 10, '#ffffff') : []),
+ sparkle(px + 30 * u, py + ph + 10 * u, 70 * u, p.accent, -10),
+ ) };
+ },
+ },
+ {
+ id: 'mega', zh: '大字满版', en: 'Mega type', fit: [...XHS, ...SHORT, 'youtube'], zhUse: '标题放大到撑满画面,高饱和纯色底,最强的信息流冲击力', enUse: 'The headline fills the artboard on a saturated colour; maximum scroll-stopping force',
+ build(i) {
+ const p = palette(i, { bg: '#ff4d2e', bg2: '#ff4d2e', ink: '#fff4e6', sub: '#1a1209', accent: '#1a1209', accentInk: '#fff4e6' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 1.6;
+ const size = fitTitle(i.title, inner, h * 0.74, 480 * u, 40, 0.92); const th = textHeight(i.title, inner, size, 0.92); const top = (h - th) / 2 - (i.subtitle.trim() ? 30 * u : 0);
+ const subPill = i.subtitle.trim() ? [pill(i.subtitle, 0, 0, p.accent, p.accentInk, Math.max(26, 36 * u), { qcRole: 'subtitle', radius: 0.5 })].map(b => { b.set({ left: m * 0.8, top: Math.min(h - m * 0.8 - b.height, top + th + 24 * u) }); return b; }) : [];
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.09, 13), ...badge(i.badge, m * 0.8, m * 0.6, { ...p, accent: p.accent, accentInk: p.accentInk }, Math.max(20, 26 * u)),
+ textbox(i.title, m * 0.8, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 0.92, charSpacing: -40 }), ...subPill,
+ ) };
+ },
+ },
+ {
+ id: 'ticker', zh: '跑马灯', en: 'Ticker', fit: [...VIDEO, ...XHS], zhUse: '奶黄底 + 斜向滚动字带 + 硬阴影大字,B 站 / YouTube 的信息流利器', enUse: 'Cream with diagonal ticker bands and hard-shadow type; built for video feeds',
+ build(i) {
+ const p = palette(i, { bg: '#fff1c9', bg2: '#ffd9b3', ink: '#ffffff', sub: '#2a1d0c', accent: '#111111', accentInk: '#facc15' });
+ const { u, m, w, h } = metrics(i); const inner = w - m * 2; const word = (i.badge?.trim() || i.subtitle.trim() || 'NEW').slice(0, 14); const bh = Math.max(70, 100 * u);
+ const size = fitTitle(i.title, inner, h * 0.44, 230 * u, 40, 1.02); const th = textHeight(i.title, inner, size, 1.02); const top = (h - th) / 2;
+ return { background: linear(p, 180), objects: keep<FabricObject>(
+ kitGlow(w * 0.5, h * 0.5, Math.min(w, h) * 0.7, '#fb7185', 0.3), grain(w, h, 0.1, 17),
+ ...ticker(w, h * 0.1, bh, word, bh * 0.52, p.accentInk, p.accent, -5), ...ticker(w, h * 0.82, bh, word, bh * 0.52, p.ink, '#ef4444', 4),
+ textbox(i.title, m, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.02, textAlign: 'center', stroke: '#000000', strokeWidth: Math.max(6, 12 * u), shadow: shadowHard(u, '#7c3aed', 9), charSpacing: -10 }),
+ ...sub(i, m, top + th + 24 * u, inner, Math.max(26, 38 * u), p.sub, { textAlign: 'center', fontWeight: 'bold' }),
+ ) };
+ },
+ },
+ {
+ id: 'memo', zh: '便签笔记', en: 'Memo paper', fit: [...XHS, 'wechat'], zhUse: '横线笔记纸 + 红色页边线 + 荧光笔划重点,学习、笔记、干货', enUse: 'Ruled notebook paper with a margin line and a highlighter; study notes and tips',
+ build(i) {
+ const p = palette(i, { bg: '#fbf8ef', bg2: '#fbf8ef', ink: '#1d2a44', sub: '#5b6a86', accent: '#fde047', accentInk: '#1d2a44' });
+ const { u, m, w, h } = metrics(i); const left = m * 1.9; const inner = w - left - m; const size = fitTitle(i.title, inner, h * 0.42, 150 * u, 36, 1.12); const th = textHeight(i.title, inner, size, 1.12);
+ const gap = Math.max(48, 74 * u); const top = Math.round((h * 0.28) / gap) * gap + 6;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.07, 21),
+ ...Array.from({ length: Math.floor(h / gap) }, (_, k) => rule(0, gap * (k + 1.5), w, '#9db4d6', Math.max(1.4, 2 * u), false, 0.55)),
+ rule(m * 1.45, 0, h, '#e8706a', Math.max(2, 3 * u), true, 0.8),
+ ...Array.from({ length: 3 }, (_, k) => new Circle({ left: m * 0.5, top: h * (0.2 + k * 0.3), radius: 16 * u, fill: '#e8dfc9', stroke: '#c9bd9f', strokeWidth: 2, originX: 'left', originY: 'top' })),
+ rect(left - 10 * u, top + size * 0.62, Math.min(inner, textWidth(i.title.split('\n')[0] ?? i.title, size, 'bold') + 20 * u), size * 0.5, p.accent, { opacity: 0.85, angle: -0.8 }),
+ ...badge(i.badge, left, top - Math.max(54, 70 * u), { ...p, accent: '#ef4444', accentInk: '#ffffff' }, Math.max(20, 26 * u), { angle: -3 }),
+ textbox(i.title, left, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.12, charSpacing: -10 }),
+ ...sub(i, left, top + th + 26 * u, inner, Math.max(26, 38 * u), p.sub),
+ ) };
+ },
+ },
+ {
+ id: 'pop', zh: '贴纸波普', en: 'Pop sticker', fit: [...XHS, ...VIDEO, ...SHORT], zhUse: '明黄底 + 黑色粗标题 + 几枚歪贴的粉、蓝、绿色块贴纸 + 白色胶囊副标题;年轻好玩,但不靠描边、硬投影和爆炸星', enUse: 'Yellow, heavy black type, a few tilted pink, blue and green stickers and a white pill subtitle; playful without outlines, hard shadows or bursts',
+ build(i) {
+ const p = palette(i, { bg: '#ffd23f', bg2: '#ffd23f', ink: '#151515', sub: '#151515', accent: '#ff4f8b', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.1; const tw = (w - x0 * 2) * (wide ? 0.7 : 1); const s0 = Math.min(w, h);
+ const size = fitTitle(i.title, tw, h * (wide ? 0.54 : 0.4), 230 * u, 40, 1.04); const th = textHeight(i.title, tw, size, 1.04);
+ const subS = Math.max(26, size * 0.3); const subH = i.subtitle.trim() ? subS * 1.7 + 34 * u : 0; const top = (h - th - subH) / 2 + (wide ? 0 : h * 0.03);
+ const dots: FabricObject[] = []; const step = 84 * u; for (let x = step / 2; x < w; x += step) for (let y = step / 2; y < h; y += step) dots.push(dot(x, y, 7 * u, 'rgba(0,0,0,0.06)'));
+ const r = s0 * (wide ? 0.2 : 0.17); const sx = w - m * 0.6 - r, sy = m * 0.6 + r;
+ const word = i.badge?.trim() ?? ''; const tag = word ? stickerDot(sx, sy, r, p.accent, hasCjk(word) ? [...word].slice(0, 4).join('') : word.slice(0, 8), p.accentInk, 8) : [dot(sx, sy, r, p.accent)];
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ ...dots, rect(-s0 * 0.05, h - s0 * 0.26, s0 * 0.3, s0 * 0.3, '#3b82f6', { rx: s0 * 0.06, ry: s0 * 0.06, angle: 12 }), dot(w - m * 1.2, h - s0 * 0.18, s0 * 0.06, '#22c55e'),
+ sparkle(x0 + 30 * u, top - 70 * u, 70 * u, '#ffffff', 0), ...tag,
+ textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.04, charSpacing: -18 }),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, x0, top + th + 34 * u, '#ffffff', p.ink, subS, { qcRole: 'subtitle', radius: 0.5 })] : []),
+ ) };
+ },
+ },
+ {
+ id: 'mag', zh: '杂志封面', en: 'Magazine', fit: [...BANNER, ...XHS, 'bilibili'], zhUse: '纸质底 + 衬线巨标题 + 巨型虚影期号 + 报头细线,像一本真杂志', enUse: 'Paper, a huge serif headline, a ghost issue numeral and masthead rules; a real magazine cover',
+ build(i) {
+ const p = palette(i, { bg: '#efe7d8', bg2: '#e5dac4', ink: '#17130d', sub: '#6b5f4b', accent: '#b6402a', accentInk: '#fff7ea' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2; const tw = wide ? inner * 0.62 : inner * 0.94; const topY = m * 0.7; const num = digits(i, false);
+ const size = fitTitle(i.title, tw, h * (wide ? 0.6 : 0.34), 200 * u, 40, 1.0); const th = textHeight(i.title, tw, size, 1.0); const ty = topY + (wide ? 100 : 96) * u;
+ const subSize = Math.max(26, 38 * u);
+ const titleBox = textbox(i.title, m, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.0, charSpacing: -20 }); const titleH = Math.max(th, titleBox.height * titleBox.scaleY);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.1),
+ ghost(num, wide ? w * 0.56 : w * 0.06, wide ? -h * 0.12 : h * 0.4, wide ? h * 1.1 : h * 0.62, p.accent, 0.16, false),
+ rule(m, topY, inner, p.ink, 5 * u), rule(m, topY + 14 * u, inner, p.ink, 1.4 * u),
+ meta(`NO.${num}`, m, topY + 32 * u, inner * 0.5, Math.max(18, 22 * u), p.ink), meta('COVER STORY', m + inner * 0.5, topY + 32 * u, inner * 0.5, Math.max(18, 22 * u), p.sub, { textAlign: 'right' }),
+ sideText('THE COVER STORY · SPECIAL EDITION · 2026', w - m * 0.62, m * 2.2, h - m * 4, Math.max(14, 17 * u), p.sub, 'down', 0.8),
+ titleBox,
+ rect(m, ty + titleH + 24 * u, 84 * u, Math.max(5, 7 * u), p.accent),
+ ...sub(i, m, ty + titleH + 46 * u, tw, subSize, p.sub, { fontFamily: SERIF, fontStyle: 'italic' }),
+ metaBlock(['VOL. 2026', 'SPECIAL EDITION'], m, h - m * 0.9 - 60 * u, inner * 0.4, Math.max(14, 17 * u), p.ink), metaBlock(['QIAOMU', 'COVER DESIGN'], m + inner * 0.6, h - m * 0.9 - 60 * u, inner * 0.4, Math.max(14, 17 * u), p.ink, 'right'),
+ ...(i.badge?.trim() ? stickerDot(w - m - 90 * u, topY + 250 * u, 80 * u, p.accent, i.badge.trim().slice(0, 4), p.accentInk, -10) : []),
+ ) };
+ },
+ },
+ {
+ id: 'print', zh: '印刷海报', en: 'Print poster', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '黑 + 米白 + 一抹朱红,裁切线、套准标、沿边文字、条码,欧洲字体海报的语汇', enUse: 'Black, paper and one vermilion; crop marks, registration target, edge text and barcode: the European typographic poster vocabulary',
+ build(i) {
+ const p = palette(i, { bg: '#f2efe6', bg2: '#f2efe6', ink: '#0d0d0d', sub: '#4a4a4a', accent: '#ff3b1f', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2.4; const x0 = m * 1.2; const tw = wide ? inner * 0.78 : inner;
+ const subS = Math.max(26, 38 * u); const subLines = i.subtitle.trim() ? lineCount(i.subtitle, inner - 44 * u, subS) : 0; // the bar grows with the subtitle, so a second line stays on red
+ const subH = subLines ? Math.max(60, 92 * u, subLines * subS * 1.25 * 1.13 + 40 * u) : 0; const bottom = h - m * 1.15; const head = m * 0.9 + 100 * u + (i.badge?.trim() ? Math.max(16, 20 * u) * 2.6 : 0) + 24 * u;
+ // The headline lives between the label block and the red bar; a taller one would be pushed down onto the bar.
+ const size = fitTitle(i.title, tw, Math.min(h * (wide ? 0.62 : 0.5), (bottom - subH - 28 * u - head) * 0.86), 280 * u, 40, 0.94); const th = textHeight(i.title, tw, size, 0.94);
+ const top = bottom - subH - 28 * u - size * 0.16 - th; const num = digits(i, false);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.1, 41), ...cropMarks(w, h, m * 0.42, 30 * u, p.ink, Math.max(1.5, 2 * u)), ...regMark(w - m * 1.1, m * 1.0, 15 * u, p.ink, Math.max(1.5, 2 * u)),
+ sideText('SERIES 2026 — COVER PROGRAM — SERIES 2026 — COVER PROGRAM', m * 0.2, m * 1.7, h - m * 3.4, Math.max(13, 15 * u), p.ink, 'up', 0.7),
+ metaBlock([`NO.${num}`, 'VOL. 2026', 'ISSUE'], x0, m * 0.9, inner * 0.3, Math.max(14, 17 * u), p.ink),
+ ...barcode(w - m * 1.2 - 150 * u, m * 1.9, 150 * u, 54 * u, p.ink, 6),
+ textbox('→', w - m * 1.2 - 130 * u, h * (wide ? 0.18 : 0.3), 130 * u, { fontSize: 130 * u, fill: p.accent, fontWeight: 'bold', lineHeight: 1, textAlign: 'right' }),
+ textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 0.94, charSpacing: -40 }),
+ ...(i.subtitle.trim() ? [rect(x0, bottom - subH, inner, subH, p.accent), ...sub(i, x0 + 22 * u, bottom - subH + (subH - subLines * subS * 1.25 * 1.13) / 2, inner - 44 * u, subS, p.accentInk, { fontWeight: 'bold' })] : []),
+ ...badge(i.badge, x0, m * 0.9 + 100 * u, { ...p, accent: p.ink, accentInk: p.bg }, Math.max(16, 20 * u)),
+ ) };
+ },
+ },
+ {
+ id: 'glass', zh: '玻璃卡片', en: 'Glass card', fit: [...XHS, ...VIDEO, ...BANNER], zhUse: '粉蓝弥散背景 + 大幅磨砂玻璃卡片 + 悬浮小胶囊,现代、产品、App 感', enUse: 'Pastel mesh background, a large frosted glass card and floating pills; modern, product, app',
+ build(i) {
+ const p = palette(i, { bg: '#ffd1e8', bg2: '#c7d7ff', ink: '#2b1b57', sub: 'rgba(43,27,87,0.78)', accent: '#2b1b57', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const cw = w - m * 1.6; const ch = h * (wide ? 0.8 : 0.64); const cx = (w - cw) / 2; const cy = (h - ch) / 2; const pad = m * 0.85; const inner = cw - pad * 2;
+ const size = fitTitle(i.title, inner, ch * 0.46, 170 * u, 36, 1.05); const th = textHeight(i.title, inner, size, 1.05); const ty = cy + pad + (i.badge?.trim() ? Math.max(58, 76 * u) : 0) + (ch - pad * 2 - th - (i.subtitle.trim() ? 130 * u : 40 * u)) * 0.28;
+ const pts = (i.points ?? []).slice(0, 3);
+ return { background: linear(p, 150), objects: keep<FabricObject>(
+ kitGlow(w * 0.18, h * 0.16, Math.min(w, h) * 0.65, '#22d3ee', 0.65), kitGlow(w * 0.9, h * 0.86, Math.min(w, h) * 0.65, '#f59e0b', 0.6), kitGlow(w * 0.5, h * 0.5, Math.min(w, h) * 0.5, '#6366f1', 0.4), grain(w, h, 0.1, 9),
+ rect(cx, cy, cw, ch, 'rgba(255,255,255,0.5)', { rx: 56 * u, ry: 56 * u, stroke: 'rgba(255,255,255,0.95)', strokeWidth: Math.max(2, 3 * u), shadow: new Shadow({ color: 'rgba(90,60,160,0.28)', blur: 70 * u, offsetX: 0, offsetY: 28 * u }) }),
+ rect(cx + cw - 230 * u, cy - 38 * u, 250 * u, 84 * u, 'rgba(255,255,255,0.75)', { rx: 42 * u, ry: 42 * u, stroke: 'rgba(255,255,255,0.95)', strokeWidth: Math.max(2, 3 * u) }),
+ textbox('✦ NEW', cx + cw - 230 * u, cy - 38 * u + 22 * u, 250 * u, { fontSize: Math.max(22, 30 * u), fill: p.ink, fontWeight: 'bold', textAlign: 'center', charSpacing: 120 }),
+ ...badge(i.badge, cx + pad, cy + pad * 0.8, p, Math.max(18, 24 * u)),
+ textbox(i.title, cx + pad, ty, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.05, charSpacing: -16, shadow: new Shadow({ color: 'rgba(255,255,255,0.7)', blur: 18 * u, offsetX: 0, offsetY: 4 * u }) }),
+ rule(cx + pad, ty + th + 26 * u, inner, 'rgba(43,27,87,0.2)', Math.max(1.5, 2 * u)),
+ ...sub(i, cx + pad, ty + th + 48 * u, inner, Math.max(26, 38 * u), p.sub),
+ ...pts.map((t, k) => pill(t, cx + pad + k * 200 * u, cy + ch - pad * 0.7 - 56 * u, 'rgba(43,27,87,0.1)', p.ink, Math.max(18, 24 * u), { radius: 0.5, padX: 0.8 })),
+ ) };
+ },
+ },
+ {
+ id: 'bento', zh: '便当清单', en: 'Bento list', fit: [...XHS, 'wechat'], zhUse: '深色标题卡 + 三张彩色要点卡拼成便当格,信息密度高又好看', enUse: 'A dark headline card and three colour cards in a bento grid; dense and good looking',
+ build(i) {
+ const p = palette(i, { bg: '#ecebe4', bg2: '#ecebe4', ink: '#141414', sub: '#6b6b6b', accent: '#ffd23f', accentInk: '#141414' });
+ const { u, m, w, h, wide } = metrics(i); const gap = 20 * u; const rows = (i.points?.length ? i.points : i.subtitle.split(/[\n,,、;;]/)).map(x => x.trim()).filter(Boolean).slice(0, 3);
+ const items = [...rows, ...(i.zh ? ['先明确目标', '再拆解步骤', '最后复盘'] : ['Set the goal', 'Break it down', 'Review']).slice(rows.length)].slice(0, 3);
+ const x0 = m * 0.75; const y0 = m * 0.75; const W = w - x0 * 2; const H = h - y0 * 2; const colors = [p.accent, '#ff7a6b', '#7dd3c0'];
+ const hw = wide ? W * 0.46 : W; const hh = wide ? H : H * 0.38; const inner = hw - m * 1.1;
+ const size = fitTitle(i.title, inner, hh * (wide ? 0.72 : 0.62), 240 * u, 36, 1.04); const th = textHeight(i.title, inner, size, 1.04);
+ const gx = wide ? x0 + hw + gap : x0; const gy = wide ? y0 : y0 + hh + gap; const gw = wide ? W - hw - gap : W; const gh = wide ? H : H - hh - gap;
+ const slots = wide ? [[gx, gy, gw, gh * 0.5 - gap / 2], [gx, gy + gh * 0.5 + gap / 2, gw / 2 - gap / 2, gh * 0.5 - gap / 2], [gx + gw / 2 + gap / 2, gy + gh * 0.5 + gap / 2, gw / 2 - gap / 2, gh * 0.5 - gap / 2]]
+ : [[gx, gy, gw, gh * 0.46 - gap / 2], [gx, gy + gh * 0.46 + gap / 2, gw / 2 - gap / 2, gh * 0.54 - gap / 2], [gx + gw / 2 + gap / 2, gy + gh * 0.46 + gap / 2, gw / 2 - gap / 2, gh * 0.54 - gap / 2]];
+ const cards = items.flatMap((label, k) => { const [sx, sy, sw, sh] = slots[k]! as [number, number, number, number]; const big = k === 0;
+ return [rect(sx, sy, sw, sh, colors[k]!, { rx: 40 * u, ry: 40 * u }), textbox(String(k + 1).padStart(2, '0'), sx + 28 * u, sy + 22 * u, sw - 50 * u, { fontSize: Math.max(40, (big ? 120 : 88) * u), fill: 'rgba(0,0,0,0.28)', fontWeight: 'bold', lineHeight: 1, charSpacing: -30 }),
+ textbox(label, sx + 28 * u, sy + sh - 28 * u - Math.max(36, (big ? 64 : 48) * u) * 2.4, sw - 56 * u, { fontSize: Math.max(26, (big ? 60 : 46) * u), fill: p.ink, fontWeight: 'bold', lineHeight: 1.12 })]; });
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.06, 43),
+ rect(x0, y0, hw, hh, '#141414', { rx: 40 * u, ry: 40 * u }),
+ ...badge(i.badge, x0 + m * 0.55, y0 + m * 0.5, p, Math.max(18, 24 * u)),
+ textbox(i.title, x0 + m * 0.55, y0 + hh - m * 0.55 - th, inner, { qcRole: 'title', fontSize: size, fill: '#ffffff', fontWeight: 'bold', lineHeight: 1.04, charSpacing: -16 }),
+ ...cards,
+ ) };
+ },
+ },
+ {
+ id: 'neon', zh: '霓虹网格', en: 'Neon grid', fit: [...VIDEO, ...BANNER, ...XHS], zhUse: '深色透视网格 + 霓虹发光字 + 取景框角标,AI、编程、赛博', enUse: 'Dark perspective grid, neon glow type and viewfinder corners; AI, code, cyber',
+ build(i) {
+ const p = palette(i, { bg: '#05060d', bg2: '#0b1226', ink: '#f8fafc', sub: '#7dd3fc', accent: '#22d3ee', accentInk: '#02131a' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2; const tw = wide ? inner * 0.74 : inner;
+ const size = fitTitle(i.title, tw, h * 0.46, 200 * u, 40, 1.04); const th = textHeight(i.title, tw, size, 1.04); const top = (h - th) / 2 - 20 * u;
+ const lines: FabricObject[] = []; const gy = h * 0.64;
+ for (let k = 0; k <= 12; k++) { const x = (w / 12) * k; lines.push(new Line([w / 2 + (x - w / 2) * 0.12, gy, x, h], { stroke: p.accent, strokeWidth: Math.max(1, 1.6 * u), opacity: 0.22, originX: 'left', originY: 'top', left: Math.min(w / 2 + (x - w / 2) * 0.12, x), top: gy })); }
+ for (let k = 1; k <= 6; k++) { const y = gy + (h - gy) * (k / 6) ** 1.8; lines.push(rule(0, y, w, p.accent, Math.max(1, 1.6 * u), false, 0.2)); }
+ return { background: linear(p, 180), objects: keep<FabricObject>(
+ kitGlow(w * 0.2, h * 0.3, Math.min(w, h) * 0.55, '#a855f7', 0.5), kitGlow(w * 0.8, h * 0.6, Math.min(w, h) * 0.55, p.accent, 0.5), ...lines, grain(w, h, 0.09, 23),
+ ...cropMarks(w, h, m * 0.5, 40 * u, p.accent, Math.max(2, 3 * u)),
+ meta(`● REC ${(i.badge?.trim() || 'SYS')} / ONLINE`, m, m * 0.85, inner * 0.7, Math.max(16, 20 * u), p.sub, { fontFamily: 'monospace', charSpacing: 120 }),
+ textbox(i.title, m, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.04, shadow: new Shadow({ color: p.accent, blur: 34 * u, offsetX: 0, offsetY: 0 }), charSpacing: -10 }),
+ ...sub(i, m, top + th + 26 * u, inner, Math.max(26, 36 * u), p.sub, { fontWeight: 'bold' }),
+ meta('00:03:21:07', m, h - m * 0.85 - 22 * u, inner * 0.5, Math.max(14, 18 * u), p.sub, { fontFamily: 'monospace' }), meta('2.39:1', m + inner * 0.5, h - m * 0.85 - 22 * u, inner * 0.5, Math.max(14, 18 * u), p.sub, { fontFamily: 'monospace', textAlign: 'right' }),
+ ) };
+ },
+ },
+ {
+ id: 'calm', zh: '松弛留白', en: 'Calm paper', fit: [...XHS, ...BANNER], zhUse: '云舞白纸 + 大号衬线标题 + 竖线与弧线 + 沿边小字,克制的“冷静风”', enUse: 'Cloud-white paper, a large serif headline, a vertical rule, an arc and edge text; quiet and restrained',
+ build(i) {
+ const p = palette(i, { bg: '#ebe8e0', bg2: '#ebe8e0', ink: '#24211b', sub: '#7a7466', accent: '#8a6f4d', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2.4; const tw = wide ? inner * 0.62 : inner * 0.9; const x0 = m * 1.5;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.5 : 0.4), 200 * u, 36, 1.1); const th = textHeight(i.title, tw, size, 1.1); const top = h * (wide ? 0.28 : 0.26);
+ const r = Math.min(w, h) * 0.42;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.09, 29),
+ new Circle({ left: w - r * 1.35, top: h - r * 1.6, radius: r, fill: 'rgba(0,0,0,0)', stroke: p.accent, strokeWidth: Math.max(2, 3 * u), originX: 'left', originY: 'top', opacity: 0.5 }),
+ new Circle({ left: w - r * 0.95, top: h - r * 1.2, radius: r * 0.42, fill: p.accent, originX: 'left', originY: 'top', opacity: 0.18 }),
+ rule(m * 0.9, m * 0.9, h - m * 1.8, p.accent, Math.max(2, 3 * u), true, 0.7),
+ sideText('QUIET NOTES — 2026 — QUIET NOTES', w - m * 0.6, m * 1.4, h - m * 2.8, Math.max(13, 16 * u), p.sub, 'down', 0.7),
+ meta(i.badge?.trim() ? i.badge.trim().toUpperCase() : 'NOTES', x0, m * 0.85, inner * 0.5, Math.max(16, 20 * u), p.sub, { qcRole: 'badge' }),
+ textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.1, charSpacing: -12 }),
+ ...sub(i, x0, top + th + 32 * u, tw, Math.max(24, 34 * u), p.sub, { fontFamily: SERIF, fontStyle: 'italic' }),
+ ) };
+ },
+ },
+ {
+ id: 'folio', zh: '编辑大标题', en: 'Editorial headline', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '纸面编辑版式:顶部粗线 + 栏目名与期号、贴左黑体大标题、宋体导语、底部细线收边;只有一个焦点,留白占一半', enUse: 'An editorial page: a heavy top rule with section and issue, a flush-left heavy headline, a serif standfirst and a hairline foot; one focal point, half the page left empty',
+ build(i) {
+ const p = palette(i, { bg: '#f3efe6', bg2: '#f3efe6', ink: '#191714', sub: '#5c574f', accent: '#c2410c', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.3; const inner = w - x0 * 2; const tw = wide ? inner * 0.7 : inner;
+ const headY = m * 1.05; const footY = h - m * 1.05;
+ // Kicker, headline and standfirst must all fit between the two rules; the headline gives way if they do not.
+ const fitsAt = (sz: number): number => { const k = Math.max(26, Math.min(58 * u, sz * 0.24)); const d = Math.max(26, sz * 0.3); return k * 2.6 + textHeight(i.title, tw, sz, 1.08) + (i.subtitle.trim() ? textHeight(i.subtitle, tw * 0.92, d, 1.35) + 52 * u : 0) + m * 0.5; };
+ let size = fitTitle(i.title, tw, (footY - headY) * (wide ? 0.6 : 0.46), 230 * u, 40, 1.08); for (let k = 0; k < 14 && size > 40 && fitsAt(size) > footY - headY; k++) size = Math.max(40, size * 0.92);
+ const th = textHeight(i.title, tw, size, 1.08);
+ const ks = Math.max(26, Math.min(58 * u, size * 0.24)); const dek = Math.max(26, size * 0.3); const dekH = i.subtitle.trim() ? textHeight(i.subtitle, tw * 0.92, dek, 1.35) + 52 * u : 0;
+ // The block sits a little above the middle of the space between the rules: optical centre, not geometric.
+ const room = footY - headY - ks * 2.6; const top = headY + ks * 2.6 + Math.max(m * 0.4, (room - th - dekH) * 0.42);
+ const kicker = i.badge?.trim() || (i.zh ? '编辑部' : 'EDITORIAL');
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.06, 11),
+ rule(x0, headY, inner, p.ink, Math.max(3, 4 * u), false, 1),
+ textbox(kicker, x0, headY + ks * 0.7, inner * 0.6, { qcRole: 'badge', fontSize: ks, fill: p.accent, fontWeight: 'bold', charSpacing: hasCjk(kicker) ? 80 : 200, lineHeight: 1 }),
+ textbox(`No. ${digits(i, false).padStart(2, '0')}`, x0 + inner * 0.5, headY + ks * 0.55, inner * 0.5, { fontSize: ks * 1.2, fill: p.ink, fontFamily: 'DM Serif Display', textAlign: 'right', lineHeight: 1 }),
+ textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08, charSpacing: -20 }),
+ rule(x0, top + th + 26 * u, Math.min(w * 0.12, 150 * u), p.accent, Math.max(5, 7 * u), false, 1),
+ ...sub(i, x0, top + th + 52 * u, tw * 0.92, dek, p.sub, { fontFamily: '思源宋体', lineHeight: 1.35 }),
+ rule(x0, footY, inner, p.ink, Math.max(1, 1.5 * u), false, 0.55),
+ ) };
+ },
+ },
+ {
+ id: 'numeral', zh: '单色大数字', en: 'Big numeral', fit: [...XHS, ...VIDEO, ...BANNER], zhUse: '一个巨型数字做钩子 + 其下小标题;单一强调色,适合清单、教程、数字干货', enUse: 'One oversized numeral as the hook, a quiet headline beneath; a single accent colour for lists, tutorials and number posts',
+ build(i) {
+ const p = palette(i, { bg: '#eef0ea', bg2: '#eef0ea', ink: '#1f2a24', sub: '#6b756e', accent: '#3f6b55', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.3; const num = (/\d+/.exec(i.badge ?? '') ?? /\d+/.exec(i.title) ?? ['01'])[0].slice(0, 2);
+ const ns = Math.min(h * (wide ? 0.74 : 0.42), wide ? (w * 0.46 - x0) / (num.length * 0.64) : w * 0.5); const tw = wide ? (w - x0 * 2) * 0.46 : w - x0 * 2;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.5 : 0.24), 120 * u, 34, 1.15); const th = textHeight(i.title, tw, size, 1.15);
+ const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, Math.max(22, 30 * u), 1.25) + 22 * u : 0; const numTop = wide ? (h - ns * 1.13) / 2 : h * 0.12; const tx = wide ? w * 0.52 : x0; const ty = wide ? (h - th - subH) / 2 + 11 * u : numTop + ns * 1.02 + 18 * u;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.05, 17),
+ textbox(num, wide ? x0 : x0, numTop, wide ? w * 0.44 : w - x0 * 2, { qcRole: 'ghost', fontSize: ns, fill: p.accent, fontWeight: 'bold', lineHeight: 1, charSpacing: -40 }),
+ rule(tx, ty - 22 * u, 90 * u, p.ink, Math.max(3, 4 * u), false, 1),
+ textbox(i.title, tx, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.15, charSpacing: -10 }),
+ ...sub(i, tx, ty + th + 22 * u, tw, Math.max(22, 30 * u), p.sub, {}),
+ ) };
+ },
+ },
+ {
+ id: 'sage', zh: '纸质卡片', en: 'Paper card', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '低饱和鼠尾草底 + 一张米白纸卡,标题落在卡片上;温和、干净、有质感', enUse: 'A muted sage ground with one warm paper card carrying the headline; gentle, clean and tactile',
+ build(i) {
+ const p = palette(i, { bg: '#d9e1d3', bg2: '#d9e1d3', ink: '#26302a', sub: '#6d786f', accent: '#b4572f', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const cx = m * 1.1; const cy = m * 1.1; const cw = w - cx * 2; const ch = h - cy * 2; const pad = m * 1.1;
+ const tw = cw - pad * 2 - (wide ? cw * 0.2 : 0); const size = fitTitle(i.title, tw, ch * (wide ? 0.5 : 0.4), 190 * u, 36, 1.1); const th = textHeight(i.title, tw, size, 1.1);
+ const top = cy + ch * (wide ? 0.3 : 0.28);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.07, 23),
+ new Rect({ left: cx, top: cy, width: cw, height: ch, rx: 18 * u, ry: 18 * u, fill: '#fbf9f4', originX: 'left', originY: 'top', shadow: new Shadow({ color: 'rgba(38,48,42,0.14)', blur: 36 * u, offsetX: 0, offsetY: 14 * u }) }),
+ meta(i.badge?.trim() ? i.badge.trim().toUpperCase() : 'NOTES', cx + pad, cy + pad * 0.8, cw * 0.5, Math.max(15, 19 * u), p.accent, { qcRole: 'badge' }),
+ textbox(i.title, cx + pad, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.1, charSpacing: -14 }),
+ ...sub(i, cx + pad, top + th + 28 * u, tw, Math.max(22, 30 * u), p.sub, {}),
+ ) };
+ },
+ },
+ {
+ id: 'seal', zh: '书法印章', en: 'Ink & seal', fit: [...XHS, ...BANNER, 'vertical'], zhUse: '宣纸底 + 淡墨巨圆 + 大号衬线标题 + 红印章;纯中文短标题自动改竖排', enUse: 'Rice paper, a huge ink wash disc, a big serif headline and a red seal; short Chinese titles run vertically',
+ build(i) {
+ const p = palette(i, { bg: '#f1ead8', bg2: '#f1ead8', ink: '#1b1814', sub: '#5d5446', accent: '#c0392b', accentInk: '#f6efe0' });
+ const { u, m, w, h, wide } = metrics(i); const flat = i.title.replace(/\s+/g, ''); const vertical = /^[㐀-鿿]{2,7}$/.test(flat); const stamp = (i.badge?.trim() || [...flat][0] || '印').slice(0, 2);
+ const R = Math.min(w, h) * 0.48; const disc = new Circle({ left: w - R * 1.2, top: h - R * 1.35, radius: R, fill: 'rgba(30,24,16,0.075)', originX: 'left', originY: 'top' });
+ if (vertical) {
+ const chars = [...flat]; const size = Math.min((h * 0.66) / chars.length / (1.1 * FABRIC_LINE), wide ? w * 0.2 : w * 0.34); const x = wide ? w * 0.52 : (w - size * 1.3) / 2;
+ return { background: solid(p.bg), objects: keep<FabricObject>(grain(w, h, 0.12, 31), disc,
+ textbox(chars.join('\n'), x, m * 1.1, size * 1.3, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.1, textAlign: 'center' }),
+ ...(i.subtitle.trim() ? [textbox([...i.subtitle.replace(/\s+/g, '')].slice(0, 16).join('\n'), x - size * 1.1, m * 1.5, size * 0.5, { qcRole: 'subtitle', fontSize: Math.max(22, size * 0.22), fill: p.sub, fontFamily: SERIF, lineHeight: 1.25, textAlign: 'center' })] : []),
+ ...seal(x + size * 1.35, h - m * 1.2 - size * 0.8, size * 0.8, stamp, p.accent)) };
+ }
+ const inner = w - m * 2.2; const size = fitTitle(i.title, inner, h * (wide ? 0.55 : 0.4), 190 * u, 36, 1.1); const th = textHeight(i.title, inner, size, 1.1); const top = h * 0.2; const sealSize = Math.max(90, 150 * u);
+ return { background: solid(p.bg), objects: keep<FabricObject>(grain(w, h, 0.12, 31), disc,
+ textbox(i.title, m * 1.1, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.1, charSpacing: -10 }),
+ rule(m * 1.1, top + th + 30 * u, 120 * u, p.ink, Math.max(2, 3 * u)),
+ ...sub(i, m * 1.1, top + th + 54 * u, inner * 0.7, Math.max(26, 36 * u), p.sub, { fontFamily: SERIF }),
+ ...seal(w - m * 1.3 - sealSize, h - m * 1.3 - sealSize, sealSize, stamp, p.accent)) };
+ },
+ },
+ {
+ id: 'quote', zh: '金句海报', en: 'Quote poster', fit: [...XHS, ...BANNER], zhUse: '墨黑底 + 巨型金色引号 + 衬线金句,一句话撑满一张海报', enUse: 'Ink black, a giant gold quotation mark and a serif statement; one line carries the poster',
+ build(i) {
+ const p = palette(i, { bg: '#121212', bg2: '#121212', ink: '#f5efe2', sub: '#b9ad94', accent: '#e8b960', accentInk: '#111111' });
+ const { u, m, w, h, wide } = metrics(i); const inner = w - m * 2.2; const tw = wide ? inner * 0.8 : inner;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.56 : 0.46), 150 * u, 36, 1.22); const th = textHeight(i.title, tw, size, 1.22); const top = h * (wide ? 0.26 : 0.34);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.1, 47), textbox('“', -m * 0.2, -h * (wide ? 0.28 : 0.1), w, { fontSize: h * (wide ? 1.3 : 0.78), fill: p.accent, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1, opacity: 0.9 }),
+ sideText('SAID · REMEMBERED · REPEATED', w - m * 0.6, m * 1.5, h - m * 3, Math.max(13, 16 * u), p.sub, 'down', 0.7),
+ textbox(i.title, m * 1.1, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.22, charSpacing: -6 }),
+ rule(m * 1.1, top + th + 36 * u, 90 * u, p.accent, Math.max(3, 4 * u)),
+ // Wide tracking suits a Latin byline; on CJK it pulls a phrase apart, so Chinese gets a light touch.
+ ...sub(i, m * 1.1, top + th + 62 * u, tw, Math.max(24, 34 * u), p.accent, { fontWeight: 'bold', charSpacing: hasCjk(i.subtitle) ? 30 : 120 }),
+ // The badge sits at the foot; when a long subtitle has taken the foot it goes to the empty top-right corner instead.
+ ...((): BadgeBox[] => {
+ const bs = Math.max(16, 22 * u); const subEnd = top + th + 62 * u + (i.subtitle.trim() ? textHeight(i.subtitle, tw, Math.max(24, 34 * u), 1.25) : 0) + 24 * u;
+ if (subEnd + bs * 2.3 <= h - m * 0.6) return badge(i.badge, m * 1.1, Math.max(h - m * 1.1 - 40 * u, subEnd), p, bs);
+ return badge(i.badge, w - m * 1.8, m, p, bs, { originX: 'right' });
+ })(),
+ ) };
+ },
+ },
+ {
+ id: 'compare', zh: '对比', en: 'Versus', fit: [...XHS, ...VIDEO], zhUse: '斜切分屏:左边黯淡的“之前”,右边鲜亮的“之后”,中间一枚 VS;副标题写成「A | B」', enUse: 'A slanted split: dull “before” against vivid “after” with a VS burst; write the subtitle as “A | B”',
+ build(i) {
+ const p = palette(i, { bg: '#0f0f12', bg2: '#0f0f12', ink: '#ffffff', sub: '#d4d4d8', accent: '#ffd23f', accentInk: '#111111' });
+ const { u, m, w, h, wide } = metrics(i); const parts = i.subtitle.split(/\s*[||]\s*|\s+vs\.?\s+/i).map(x => x.trim()).filter(Boolean);
+ const [A, B] = parts.length >= 2 ? [parts[0]!, parts[1]!] : [i.zh ? '之前' : 'Before', i.zh ? '之后' : 'After']; const caption = parts.length >= 2 ? '' : i.subtitle.trim();
+ const barH = h * (wide ? 0.3 : 0.2); const tw = w - m * 2; const size = fitTitle(i.title, tw, barH * 0.72, 150 * u, 36, 1.04); const th = textHeight(i.title, tw, size, 1.04);
+ const slant = Math.min(w, h) * 0.07; const py = barH; const ph = h - barH;
+ const dull = '#cfc9bf'; const dullInk = '#4a443a';
+ const polyA = wide ? [{ x: 0, y: py }, { x: w / 2 + slant, y: py }, { x: w / 2 - slant, y: h }, { x: 0, y: h }] : [{ x: 0, y: py }, { x: w, y: py }, { x: w, y: py + ph / 2 - slant }, { x: 0, y: py + ph / 2 + slant }];
+ const polyB = wide ? [{ x: w / 2 + slant, y: py }, { x: w, y: py }, { x: w, y: h }, { x: w / 2 - slant, y: h }] : [{ x: 0, y: py + ph / 2 + slant }, { x: w, y: py + ph / 2 - slant }, { x: w, y: h }, { x: 0, y: h }];
+ const aBox = wide ? { x: m, y: py + ph * 0.3, w: w / 2 - slant - m * 1.4 } : { x: m, y: py + ph * 0.12, w: tw }; const bBox = wide ? { x: w / 2 + slant + m * 0.6, y: py + ph * 0.3, w: w / 2 - slant - m * 1.4 } : { x: m, y: py + ph * 0.62, w: tw };
+ const lab = (txt: string, box: { x: number; y: number; w: number }, color: string, mark: string): FabricObject[] => { const sz = fitTitle(txt, box.w, ph * (wide ? 0.4 : 0.2), 130 * u, 30, 1.05); return [textbox(mark, box.x, box.y - 70 * u, box.w, { fontSize: Math.max(24, 40 * u), fill: color, fontWeight: 'bold', charSpacing: 200 }), textbox(txt, box.x, box.y, box.w, { fontSize: sz, fill: color, fontWeight: 'bold', lineHeight: 1.05, charSpacing: -14 })]; };
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ new Polygon(polyA, { fill: dull, originX: 'left', originY: 'top' }), ...dotGrid(m * 0.4, py + 20 * u, 12, 14, 70 * u, 6 * u, '#9a9387', 0.35),
+ new Polygon(polyB, { fill: p.accent, originX: 'left', originY: 'top' }), rays(wide ? w * 0.78 : w * 0.7, wide ? h * 0.7 : py + ph * 0.8, Math.max(w, h), 16, '#ffffff', 0.18), sparkle(w - m * 1.2, py + (wide ? ph * 0.15 : ph * 0.58), 70 * u, '#111111', 10),
+ grain(w, h, 0.08, 51), rect(0, 0, w, barH, '#111111'),
+ ...badge(i.badge, m, m * 0.6, { ...p, accent: p.accent, accentInk: p.accentInk }, Math.max(18, 24 * u)),
+ textbox(i.title, m, (barH - th) / 2 + (i.badge?.trim() ? 14 * u : 0), tw, { qcRole: 'title', fontSize: size, fill: '#ffffff', fontWeight: 'bold', lineHeight: 1.04, textAlign: 'center', charSpacing: -10 }),
+ ...lab(A, aBox, dullInk, '✕ BEFORE'), ...lab(B, bBox, '#111111', '✓ AFTER'),
+ burst(wide ? w / 2 : w / 2, wide ? py + ph / 2 : py + ph / 2, 92 * u, '#111111', 12, 8), textbox('VS', (wide ? w / 2 : w / 2) - 60 * u, (wide ? py + ph / 2 : py + ph / 2) - 34 * u, 120 * u, { fontSize: 62 * u, fill: p.accent, fontWeight: 'bold', textAlign: 'center', angle: 8 }),
+ ...(caption ? [textbox(caption, m, h - m * 0.9 - 40 * u, tw, { qcRole: 'subtitle', fontSize: Math.max(22, 30 * u), fill: '#111111', fontWeight: 'bold', textAlign: 'center' })] : []),
+ ) };
+ },
+ },
+ {
+ id: 'cinema', zh: '电影感', en: 'Cinematic', fit: [...VIDEO, ...BANNER], zhUse: '青橙调光 + 镜头光晕 + 金色取景角 + 字距拉开的衬线片名,纪录片、Vlog、深度内容', enUse: 'Teal-and-orange light, lens flare, gold viewfinder corners and a wide-tracked serif title; documentary and vlog', photo: true,
+ build(i) {
+ const p = palette(i, { bg: '#06141a', bg2: '#10303a', ink: '#f6ead2', sub: '#c9bda3', accent: '#e8b960', accentInk: '#111111' });
+ const { u, m, w, h } = metrics(i); const bar = h * 0.13; const inner = w - m * 2;
+ const size = fitTitle(i.title, inner, h * 0.3, 170 * u, 36, 1.08); const th = textHeight(i.title, inner, size, 1.08); const top = (h - th) / 2 - 18 * u;
+ const flare = rect(0, h * 0.5 - 3 * u, w, Math.max(4, 6 * u), new Gradient({ type: 'linear', gradientUnits: 'pixels', coords: { x1: 0, y1: 0, x2: w, y2: 0 }, colorStops: [{ offset: 0, color: 'rgba(120,200,255,0)' }, { offset: 0.5, color: 'rgba(210,235,255,0.95)' }, { offset: 1, color: 'rgba(120,200,255,0)' }] }), { opacity: 0.8 });
+ return { background: linear(p, 165), objects: keep<FabricObject>(
+ kitGlow(w * 0.12, h * 0.25, Math.min(w, h) * 0.75, '#1fa3a8', 0.6), kitGlow(w * 0.92, h * 0.8, Math.min(w, h) * 0.7, '#ff8a3d', 0.55), kitGlow(w * 0.5, h * 0.5, Math.min(w, h) * 0.5, '#9fd8ff', 0.28), flare,
+ grain(w, h, 0.16, 37),
+ rect(0, 0, w, h, new Gradient({ type: 'radial', coords: { x1: w / 2, y1: h / 2, r1: Math.min(w, h) * 0.28, x2: w / 2, y2: h / 2, r2: Math.max(w, h) * 0.78 }, colorStops: [{ offset: 0, color: 'rgba(0,0,0,0)' }, { offset: 1, color: 'rgba(0,0,0,0.78)' }] }), { qcRole: 'scrim' }),
+ rect(0, 0, w, bar, '#000000'), rect(0, h - bar, w, bar, '#000000'), ...cropMarks(w, h, bar + m * 0.4, 38 * u, p.accent, Math.max(2, 3 * u)),
+ meta((i.badge?.trim() || 'A FILM').toUpperCase(), m, bar + m * 0.5 + 26 * u, inner, Math.max(16, 20 * u), p.accent, { textAlign: 'center', qcRole: 'badge', charSpacing: 520 }),
+ textbox(i.title, m, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.08, textAlign: 'center', charSpacing: 120, shadow: new Shadow({ color: 'rgba(255,170,90,0.45)', blur: 38 * u, offsetX: 0, offsetY: 0 }) }),
+ rule(w / 2 - 60 * u, top + th + 24 * u, 120 * u, p.accent, Math.max(2, 3 * u)),
+ ...sub(i, m, top + th + 46 * u, inner, Math.max(24, 32 * u), p.sub, { textAlign: 'center', charSpacing: 180 }),
+ ...(w >= h * 1.3 ? [meta('PRESENTED BY QIAOMU', m, h - bar - m * 1.1 - 24 * u, inner * 0.5, Math.max(13, 16 * u), p.sub, { fontFamily: 'monospace' }), meta('2026 · 2.39:1', m + inner * 0.5, h - bar - m * 1.1 - 24 * u, inner * 0.5, Math.max(13, 16 * u), p.sub, { fontFamily: 'monospace', textAlign: 'right' })] : []),
+ ) };
+ },
+ },
+ {
+ id: 'split', zh: '左文右图', en: 'Arch split', fit: [...VIDEO, ...BANNER, ...XHS], zhUse: '左文案右拱门:奶油底 + 橙色拱门窗 + 太阳圆 + 细线,右侧放人像或产品最好看', enUse: 'Copy on the left, an orange arch window on the right for a portrait or product; cream paper, a sun disc and fine rules',
+ slot: i => { const { w, h } = metrics(i); const x = w * 0.54; return { x, y: 0, w: w - x, h, radius: 0 }; },
+ build(i) {
+ const p = palette(i, { bg: '#f6efe3', bg2: '#f6efe3', ink: '#1c1917', sub: '#6b5f55', accent: '#ff7a3d', accentInk: '#1c1917' }); // white on this orange is 2.6:1
+ const { u, m, w, h, wide } = metrics(i); const inner = wide ? w * 0.5 - m * 1.2 : w - m * 2;
+ const size = fitTitle(i.title, inner, h * (wide ? 0.5 : 0.28), 170 * u, 36, 1.06); const th = textHeight(i.title, inner, size, 1.06);
+ const aw = wide ? w * 0.36 : w * 0.7; const ah = wide ? h * 0.9 : h * 0.46; const ax = wide ? w - aw - m * 0.8 : (w - aw) / 2; const ay = wide ? h - ah : h - ah;
+ const ty = wide ? (h - th) / 2 - 30 * u : m * 1.2 + (i.badge?.trim() ? Math.max(58, 74 * u) : 0);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.09, 53),
+ arch(ax - 22 * u, ay - 22 * u, aw + 44 * u, ah + 22 * u, 'rgba(0,0,0,0)', p.accent, Math.max(3, 4 * u)), arch(ax, ay, aw, ah, p.accent),
+ new Circle({ left: ax + aw * 0.12, top: ay + aw * 0.24, radius: aw * 0.13, fill: '#fff3d6', originX: 'left', originY: 'top', opacity: 0.95 }),
+ rule(m, m * 0.7, wide ? w * 0.42 : w - m * 2, p.ink, Math.max(1.5, 2 * u)), meta('NO.' + (i.badge?.trim() || '01'), m, m * 0.7 + 14 * u, 260 * u, Math.max(14, 17 * u), p.sub),
+ ...badge(i.badge, m, ty - Math.max(58, 74 * u), p, Math.max(18, 24 * u)),
+ textbox(i.title, m, ty, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.06, charSpacing: -16 }),
+ rect(m, ty + th + 24 * u, 70 * u, Math.max(5, 6 * u), p.accent),
+ ...sub(i, m, ty + th + 46 * u, inner, Math.max(26, 36 * u), p.sub),
+ ) };
+ },
+ },
+ {
+ id: 'impact', zh: '油管冲击', en: 'Thumbnail punch', fit: ['youtube', 'bilibili', 'bilibili-43', 'bilibili-hd', 'wide', 'vertical'], zhUse: '深蓝放射光 + 黄字黑描边硬阴影 + 红色角标,右侧留主体位;短标题效果最好', enUse: 'Blue sunburst, yellow type with a black outline and hard shadow, a red arrow and burst badge; room for a subject on the right',
+ photo: true,
+ slot: i => { const { w, h, wide } = metrics(i); return wide ? { x: w * 0.6, y: 0, w: w * 0.4, h, radius: 0 } : undefined; },
+ build(i) {
+ const p = palette(i, { bg: '#0b1f6e', bg2: '#2b6bff', ink: '#ffe14a', sub: '#ffffff', accent: '#ef233c', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const inner = wide ? w * 0.58 - m : w - m * 2; const shown = upper(i.title);
+ const size = fitTitle(shown, inner, h * (wide ? 0.62 : 0.42), 250 * u, 44, 1.02); const th = textHeight(shown, inner, size, 1.02); const subH = i.subtitle.trim() ? Math.max(54, 74 * u) : 0;
+ const top = h - m * 1.1 - subH - 18 * u - th; const cx = wide ? w * 0.8 : w * 0.5; const cy = wide ? h * 0.46 : h * 0.3;
+ return { background: linear(p, 160), objects: keep<FabricObject>(
+ rays(cx, cy, Math.max(w, h) * 1.2, 22, '#ffffff', 0.06, 0.2), kitGlow(cx, cy, Math.min(w, h) * 0.7, '#7dd3fc', 0.5), grain(w, h, 0.06, 61),
+ rect(0, h * 0.4, w, h * 0.6, new Gradient({ type: 'linear', gradientUnits: 'pixels', coords: { x1: 0, y1: 0, x2: 0, y2: h * 0.6 }, colorStops: [{ offset: 0, color: 'rgba(0,0,0,0)' }, { offset: 1, color: 'rgba(0,0,0,0.7)' }] }), { qcRole: 'scrim' }),
+ ...(i.badge?.trim() ? badge(i.badge, m, m, p, Math.max(22, 34 * u), { angle: -4 }) : []),
+ textbox(shown, m, top, inner, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.02, stroke: '#000000', strokeWidth: Math.max(10, 18 * u), shadow: shadowHard(u, '#000000', 9), angle: -2, charSpacing: -10}),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, m, 0, '#000000', '#ffffff', Math.max(24, 34 * u), { qcRole: 'subtitle', radius: 0.16 })].map(b => { b.set({ top: h - m * 0.9 - b.height }); return b; }) : []),
+ ) };
+ },
+ },
+ {
+ id: 'bili', zh: 'B 站知识区', en: 'Bilibili explainer', fit: ['bilibili', 'bilibili-43', 'bilibili-hd', 'youtube', 'wide', ...SHORT, ...XHS], zhUse: '浅灰底 + B 站粉蓝双色 + 粉色分区标签 + 黑色大标题 + 小电视画框(屏幕是图位);知识区、科普、测评的干净信息感', enUse: 'Light grey with Bilibili pink and blue, a section tag, a bold headline and a little-TV frame whose screen takes a picture; explainers and reviews',
+ slot: i => biliTv(i).screen,
+ build(i) {
+ // Bilibili's pink and blue, a shade deeper where they carry words: the brand hexes are under 3:1 on light grey.
+ const p = palette(i, { bg: '#f4f5f7', bg2: '#f4f5f7', ink: '#18191c', sub: '#0086c0', accent: '#e8487b', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.2; const tv = biliTv(i); const x0 = m * 1.1;
+ const tw = side ? tv.x - x0 - m * 0.9 : w - x0 * 2; const areaTop = m; const areaH = side ? h - m * 2 : tv.y - m * 2.2;
+ const size = fitTitle(i.title, tw, areaH * (side ? 0.56 : 0.6), 200 * u, 36, 1.08); const th = textHeight(i.title, tw, size, 1.08);
+ const tagS = Math.max(20, size * 0.2); const tagH = tagS * 1.3 * 1.7 + 26 * u; const subS = Math.max(24, size * 0.32); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subS, 1.25) + 26 * u : 0;
+ const ty = areaTop + (areaH - tagH - th - subH) / 2 + tagH;
+ const ant = (dx: number): Line => new Line([0, 0, dx, -tv.h * 0.16], { left: tv.x + tv.w / 2 + Math.min(0, dx) - (dx < 0 ? tv.w * 0.12 : -tv.w * 0.12), top: tv.y - tv.h * 0.16 + tv.sw * 0.3, stroke: p.accent, strokeWidth: tv.sw, strokeLineCap: 'round', originX: 'left', originY: 'top' });
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ ...dotGrid(m * 0.4, h * 0.62, 12, 8, 46 * u, 5 * u, p.sub, 0.25), grain(w, h, 0.05, 139),
+ ant(-tv.w * 0.1), ant(tv.w * 0.1),
+ rect(tv.x, tv.y, tv.w, tv.h, '#ffffff', { rx: tv.w * 0.12, ry: tv.w * 0.12, stroke: p.accent, strokeWidth: tv.sw, shadow: new Shadow({ color: 'rgba(251,114,153,0.25)', blur: 40 * u, offsetX: 0, offsetY: 16 * u }) }),
+ kitGlow(tv.x + tv.w / 2, tv.y + tv.h / 2, tv.w * 0.36, '#bfe9fb', 0.8),
+ rect(tv.x + tv.w * 0.2, tv.y + tv.h + tv.sw * 0.4, tv.sw * 1.4, tv.h * 0.07, p.accent, { rx: tv.sw * 0.7, ry: tv.sw * 0.7 }), rect(tv.x + tv.w * 0.8 - tv.sw * 1.4, tv.y + tv.h + tv.sw * 0.4, tv.sw * 1.4, tv.h * 0.07, p.accent, { rx: tv.sw * 0.7, ry: tv.sw * 0.7 }),
+ pill(i.badge?.trim() || (i.zh ? '知识区' : 'EXPLAINER'), x0, ty - tagH, p.accent, p.accentInk, tagS * 1.3, { qcRole: 'badge', radius: 0.5 }),
+ textbox(i.title, x0, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08 }),
+ ...sub(i, x0, ty + th + 26 * u, tw, subS, p.sub, { fontWeight: 'bold' }),
+ ) };
+ },
+ },
+];
+/* ---------- studio templates: formats that keep winning on Xiaohongshu, YouTube, Bilibili and WeChat, redrawn to the design rules ---------- */
+const dot = (cx: number, cy: number, r: number, fill: string, extra: Record<string, unknown> = {}): Circle => new Circle({ left: cx, top: cy, radius: r, fill, originX: 'center', originY: 'center', ...extra });
+/** The number a layout shows as its hook: from the label first, then (when allowed) the headline. */
+const digits = (i: TemplateInput, fromTitle = true, fallback = '01'): string => (/\d+/.exec(i.badge ?? '') ?? (fromTitle ? /\d+/.exec(i.title) : null) ?? [fallback])[0].slice(0, 3);
+/** Width of a line as drawn at the tracking the finish pass gives big headlines. */
+const lineW = (line: string, size: number, weight = 'bold', spacing = -18): number => measure(line, size, weight) + [...line].length * size * spacing / 1000;
+/** A copy of the headline drawn behind it (echo, misregistration). Same face, same wrap, no role, so it never counts as text. */
+function echoOf(title: Textbox, text: string, left: number, top: number, width: number, o: TextOptions): Textbox {
+ const e = textbox(text, left, top, width, o); e.set({ fontFamily: title.fontFamily, fontWeight: title.fontWeight }); return e;
+}
+/** Polaroid geometry, shared by the picture slot and the build. */
+function polaroidFrame(i: TemplateInput): { x: number; y: number; w: number; h: number; b: number; photo: Slot } {
+ const { m, w, h } = metrics(i); const side = w / h > 1.2;
+ if (side) { const fh = h - m * 2.2; const b = fh * 0.05; const ps = fh - b * 4.6; const fw = ps + b * 2; const x = w - m * 1.6 - fw; const y = m * 1.1; return { x, y, w: fw, h: fh, b, photo: { x: x + b, y: y + b, w: ps, h: ps, radius: 0 } }; }
+ const fw = Math.min(w * 0.64, h * 0.42); const b = fw * 0.06; const ps = fw - b * 2; const fh = b + ps + b * 3.6; const x = (w - fw) / 2; const y = m * 1.3;
+ return { x, y, w: fw, h: fh, b, photo: { x: x + b, y: y + b, w: ps, h: ps, radius: 0 } };
+}
+/** The little-TV frame of the Bilibili layout. */
+function biliTv(i: TemplateInput): { x: number; y: number; w: number; h: number; sw: number; screen: Slot } {
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.2;
+ const tw = side ? Math.min(w * 0.38, h * 0.9) : Math.min(w * 0.7, h * 0.42); const th = tw * 0.74; const sw = Math.max(8, 14 * u);
+ const x = side ? w - m * 1.3 - tw : (w - tw) / 2; const y = side ? (h - th) / 2 + h * 0.05 : h - m * 1.6 - th;
+ return { x, y, w: tw, h: th, sw, screen: { x: x + sw, y: y + sw, w: tw - sw * 2, h: th - sw * 2, radius: tw * 0.08 } };
+}
+
+const STUDIO: Template[] = [
+ {
+ id: 'highlight', zh: '荧光标题', en: 'Highlighter', fit: [...XHS, ...VIDEO, ...SHORT, 'wechat'], zhUse: '白纸黑字 + 每行标题下一道圆头荧光笔(每行微微不同的倾斜),像在笔记上划重点;干货、观点、教程都稳', enUse: 'Black type on white with a round-ended highlighter stroke under every line, each at its own slight tilt; tips, opinions and tutorials',
+ build(i) {
+ const p = palette(i, { bg: '#fffdf7', bg2: '#fffdf7', ink: '#111111', sub: '#4a4a4a', accent: '#ffe14d', accentInk: '#111111' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m * 1.1; const tw = (w - x0 * 2) * (wide ? 0.8 : 1); const lh = 1.2;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.56 : 0.44), 210 * u, 40, lh); const lines = wrapLines(i.title, tw, size, 'bold', -18); const step = size * lh * FABRIC_LINE; const th = lines.length * step;
+ const subSize = Math.max(26, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.3) + 40 * u : 0; const bs = Math.max(20, size * 0.22); const badgeH = i.badge?.trim() ? bs * 1.3 * 1.7 + 26 * u : 0;
+ const top = (h - th - subH - badgeH) * 0.46 + badgeH;
+ // A real highlighter: round ends, a stroke that overshoots the words a little, and every line at its own slight tilt.
+ const tilt = [-0.9, 0.5, -0.4, 0.8]; const mh = size * 0.42;
+ const marks = lines.map((l, k) => rect(x0 - size * 0.08, top + k * step + size * 0.64, Math.min(w - x0 * 0.6, lineW(l, size) + size * 0.18), mh, p.accent, { angle: tilt[k % 4], rx: mh * 0.45, ry: mh * 0.45, qcKind: 'mark-title' }));
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.05, 19), ...marks,
+ ...badge(i.badge, x0, top - badgeH, { ...p, accent: p.ink, accentInk: p.bg }, bs),
+ textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: lh, charSpacing: -18 }),
+ ...sub(i, x0, top + th + 40 * u, tw, subSize, p.sub, { fontWeight: 'bold', lineHeight: 1.3 }),
+ ) };
+ },
+ },
+ {
+ id: 'notes', zh: '备忘录', en: 'Notes app', fit: [...XHS, 'wechat', ...VIDEO], zhUse: '手机备忘录截图:黄色返回键 + 日期 + 黑色大标题 + 勾选清单(要点写在 points 里);小红书“截图型”,亲切可信', enUse: 'A phone notes screenshot: yellow back button, date, bold headline and a checklist from the points; personal and trustworthy',
+ build(i) {
+ const p = palette(i, { bg: '#fbfaf6', bg2: '#fbfaf6', ink: '#1c1c1e', sub: '#7c7c80', accent: '#e2a300', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m; const inner = w - m * 2; const bar = Math.max(26, 44 * u); const dateS = Math.max(18, 26 * u);
+ const list = (i.points ?? []).map(t => t.trim()).filter(Boolean).slice(0, 4); const twoCol = wide && list.length >= 2;
+ const tw = twoCol ? inner * 0.56 : inner; const top = m * 0.8 + bar * 1.6 + dateS * 3;
+ const size = fitTitle(i.title, tw, h * (wide ? 0.5 : 0.36), 190 * u, 36, 1.12); const th = textHeight(i.title, tw, size, 1.12);
+ const subSize = Math.max(26, size * 0.32); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.25) + 30 * u : 0;
+ const ls = Math.max(26, Math.min(46 * u, size * 0.4)); const lx = twoCol ? x0 + tw + m : x0; const lw = twoCol ? inner - tw - m : inner; const ly0 = twoCol ? top + 8 * u : top + th + subH + 44 * u;
+ const rows = list.length >= 2 ? list.flatMap((t, k) => { const y = ly0 + k * ls * 2.1; return [new Circle({ left: lx, top: y + ls * 0.12, radius: ls * 0.44, fill: k === 0 ? p.accent : 'rgba(0,0,0,0)', stroke: p.accent, strokeWidth: Math.max(2, 3 * u), originX: 'left', originY: 'top' }), textbox(t, lx + ls * 1.4, y, lw - ls * 1.4, { fontSize: ls, fill: p.ink, lineHeight: 1.1 })]; }) : [];
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ textbox('‹ ' + (i.zh ? '备忘录' : 'Notes'), x0, m * 0.8, inner * 0.5, { fontSize: bar, fill: p.accent, fontWeight: 'bold' }),
+ textbox(i.zh ? '完成' : 'Done', x0 + inner * 0.5, m * 0.8, inner * 0.5, { fontSize: bar, fill: p.accent, fontWeight: 'bold', textAlign: 'right' }),
+ textbox(i.badge?.trim() || (i.zh ? '今天 · 笔记' : 'Today'), x0, m * 0.8 + bar * 1.6 + dateS * 0.8, inner, { qcRole: 'badge', fontSize: dateS, fill: p.sub, textAlign: 'center' }),
+ textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.12 }),
+ ...sub(i, x0, top + th + 30 * u, tw, subSize, p.sub), ...rows,
+ ) };
+ },
+ },
+ {
+ id: 'chat', zh: '聊天截图', en: 'Chat bubbles', fit: [...XHS, ...VIDEO, ...SHORT], zhUse: '一问一答的聊天气泡:副标题是提问,标题是回答;对话感强,适合问答、AI、情感、职场', enUse: 'A chat exchange: the subtitle asks, the headline answers; Q&A, AI, relationships and work',
+ build(i) {
+ const p = palette(i, { bg: '#ededed', bg2: '#ededed', ink: '#111111', sub: '#111111', accent: '#95ec69', accentInk: '#111111' });
+ const { u, m, w, h, wide } = metrics(i); const av = Math.max(56, 92 * u); const gap = 22 * u; const pad = Math.max(22, 32 * u); const head = Math.max(22, 30 * u); const barH = head * 2.6;
+ const L = wide ? w * 0.16 : m; const R = wide ? w * 0.84 : w - m; const maxW = R - L - av - gap - pad * 2 - av * 0.3;
+ const size = fitTitle(i.title, maxW, h * (wide ? 0.46 : 0.4), 170 * u, 36, 1.12); const aLines = wrapLines(i.title, maxW, size, 'bold', -18);
+ const aW = Math.max(...aLines.map(l => lineW(l, size))) + pad * 2; const aH = aLines.length * size * 1.12 * FABRIC_LINE + pad * 1.4;
+ const q = i.subtitle.trim(); const qs = Math.max(28, size * 0.34); const qLines = q ? wrapLines(q, maxW, qs, 'normal', 0) : [];
+ const qW = q ? Math.max(...qLines.map(l => measure(l, qs, 'normal'))) + pad * 2 : 0; const qH = q ? qLines.length * qs * 1.25 * FABRIC_LINE + pad * 1.4 : 0;
+ const between = gap * 2.4; const total = (q ? qH + between : 0) + aH; const y0 = barH + (h - barH - total) / 2; const ay = y0 + (q ? qH + between : 0);
+ const tail = (x: number, y: number, fill: string, right: boolean): Triangle => new Triangle({ left: x, top: y, width: 22 * u, height: 14 * u, fill, angle: right ? 90 : -90, originX: 'center', originY: 'center' });
+ const bx = R - av - gap - aW;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ rect(0, 0, w, barH, '#f7f7f7'), rule(0, barH, w, '#d4d4d4', Math.max(1, 1.5 * u)),
+ textbox('‹', m * 0.7, (barH - head * 1.6 * 1.13) / 2, head * 2, { fontSize: head * 1.6, fill: p.ink, lineHeight: 1 }),
+ textbox(i.badge?.trim() || (i.zh ? '对话' : 'Chat'), m * 2, (barH - head * 1.25 * 1.13) / 2, w - m * 4, { qcRole: 'badge', fontSize: head, fill: p.ink, fontWeight: 'bold', textAlign: 'center' }),
+ ...(q ? [rect(L, y0, av, av, '#8fb3dc', { rx: 10 * u, ry: 10 * u }), rect(L + av + gap, y0, qW, qH, '#ffffff', { rx: 14 * u, ry: 14 * u }), tail(L + av + gap - 6 * u, y0 + Math.min(av, qH) / 2, '#ffffff', false),
+ textbox(q, L + av + gap + pad, y0 + pad * 0.7, qW - pad * 2 + 6, { qcRole: 'subtitle', fontSize: qs, fill: p.sub })] : []),
+ rect(R - av, ay, av, av, '#f5a04a', { rx: 10 * u, ry: 10 * u }), rect(bx, ay, aW, aH, p.accent, { rx: 14 * u, ry: 14 * u }), tail(bx + aW + 6 * u, ay + Math.min(av, aH) / 2, p.accent, true),
+ textbox(i.title, bx + pad, ay + pad * 0.7, aW - pad * 2 + 6, { qcRole: 'title', fontSize: size, fill: p.accentInk, fontWeight: 'bold', lineHeight: 1.12, charSpacing: -18 }),
+ ) };
+ },
+ },
+ {
+ id: 'keyword', zh: '一词冲击', en: 'Keyword punch', fit: ['youtube', 'bilibili', 'bilibili-43', 'bilibili-hd', 'wide', ...SHORT, ...XHS], zhUse: '缩略图式三词标题:饱和蓝底 + 超粗白字 + 一块黄色关键词标签(副标题)+ 主体位上一枚浅色圆盘(有图时主体站在上面);不靠描边和爆炸星也抢眼', enUse: 'A three-word thumbnail: saturated blue, heavy white type, one yellow keyword tag (the subtitle) and a pale disc where the subject stands; loud without outlines or bursts',
+ photo: true,
+ slot: i => { const { w, h } = metrics(i); return w / h > 1.2 ? { x: w * 0.56, y: 0, w: w * 0.44, h, radius: 0 } : { x: 0, y: h * 0.5, w, h: h * 0.5, radius: 0 }; },
+ build(i) {
+ const p = palette(i, { bg: '#1740ff', bg2: '#1740ff', ink: '#ffffff', sub: '#111111', accent: '#ffd400', accentInk: '#111111' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.2; const x0 = m * 1.1; const tw = side ? w * 0.56 - x0 : w - x0 * 2; const shown = upper(i.title);
+ // Label, tag and headline are one stack: the headline is sized so the whole stack fits, or the layout pass would push it onto the tag.
+ const stackOf = (sz: number): number => { const ts = Math.max(28, sz * 0.32); const tg = i.subtitle.trim() ? ts * 1.8 + 30 * u + Math.min(tw, lineW(i.subtitle.trim(), ts, 'bold', 0) + ts * 1.2) * 0.035 : 0; const bd = i.badge?.trim() ? Math.max(20, sz * 0.18) * 2.2 + 34 * u + tw * 0.035 : 0; return textHeight(shown, tw, sz, 1.0) + tg + bd; };
+ let size = fitTitle(shown, tw, h * (side ? 0.56 : 0.36), 280 * u, 44, 1.0); for (let k = 0; k < 14 && size > 44 && stackOf(size) > h - m * 2.2; k++) size = Math.max(44, size * 0.92);
+ const th = textHeight(shown, tw, size, 1.0);
+ const tagS = Math.max(28, size * 0.32); const tagW = i.subtitle.trim() ? Math.min(tw, lineW(i.subtitle.trim(), tagS, 'bold', 0) + tagS * 1.2) : 0; const tagH = i.subtitle.trim() ? tagS * 1.8 + 30 * u + tagW * Math.sin(2 * Math.PI / 180) : 0; /* tilted 2°: its left end drops toward the headline */ const bs = Math.max(20, size * 0.18); const badgeH = i.badge?.trim() ? bs * 1.3 * 1.7 + 34 * u + tw * Math.sin(2 * Math.PI / 180) : 0; // the tag is tilted 2°: its right end rises toward the badge
+ const top = side ? Math.max(m + badgeH + tagH, (h - th - tagH) / 2 + tagH) : m * 1.2 + badgeH + tagH;
+ // Where the subject goes: a pale disc and a ring. Empty, it balances the type; with a picture, the subject stands on it.
+ const dr = side ? h * 0.4 : w * 0.36; const dx = side ? w * 0.78 : w * 0.5; const dy = side ? h * 0.54 : h * 0.76;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.06, 89),
+ dot(dx, dy, dr, '#ffffff', { opacity: 0.12, qcKind: 'mark' }), dot(dx, dy, dr * 1.18, 'rgba(0,0,0,0)', { stroke: '#ffffff', strokeWidth: Math.max(2, 3 * u), opacity: 0.22, qcKind: 'mark' }),
+ ...badge(i.badge, x0, m, { ...p, accent: '#ffffff', accentInk: p.bg }, bs),
+ ...(i.subtitle.trim() ? [pill(i.subtitle, x0, top - tagH, p.accent, p.accentInk, tagS, { qcRole: 'subtitle', radius: 0.14, angle: -2 })] : []),
+ textbox(shown, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.0, charSpacing: -18, shadow: new Shadow({ color: 'rgba(0,0,40,0.35)', blur: 26 * u, offsetX: 0, offsetY: 8 * u }) }),
+ ) };
+ },
+ },
+ {
+ id: 'riso', zh: '孔版印刷', en: 'Risograph', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '再生纸 + 荧光粉与蓝两种专色叠印 + 轻微错版 + 颗粒;独立杂志、展览、文艺与潮流话题', enUse: 'Recycled paper, fluorescent pink and blue overprinting with slight misregistration and grain; zines, shows and culture',
+ build(i) {
+ const p = palette(i, { bg: '#f3eee4', bg2: '#f3eee4', ink: '#1f4fd1', sub: '#1f4fd1', accent: '#ff4fa3', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.2; const x0 = m * 1.1;
+ const R = Math.min(w, h) * (side ? 0.4 : 0.34); const cx = side ? w * 0.8 : w * 0.64; const cy = side ? h * 0.4 : h * 0.27;
+ // Side by side, the words stop before the blue block: overprinting is the look, but blue type on blue ink cannot be read.
+ const tw = side ? Math.min((w - x0 * 2) * 0.64, cx - R * 1.3 - x0 - m * 0.4) : w - x0 * 2;
+ const size = fitTitle(i.title, tw, h * (side ? 0.56 : 0.34), 220 * u, 40, 1.02); const th = textHeight(i.title, tw, size, 1.02);
+ const subSize = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.25) + 26 * u : 0;
+ const top = h - m * 1.1 - subH - th; const off = Math.max(4, 7 * u); const mul = { globalCompositeOperation: 'multiply' };
+ const title = textbox(i.title, x0, top, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.02, charSpacing: -18 }); title.set(mul);
+ const echo = echoOf(title, i.title, x0 + off, top + off * 0.6, tw, { fontSize: size, fill: p.accent, fontWeight: 'bold', lineHeight: 1.02, charSpacing: -18, opacity: 0.9 }); echo.set(mul);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ dot(cx, cy, R, p.accent, { opacity: 0.92, ...mul }), rect(cx - R * 1.3, cy - R * 0.2, R * 1.05, R * 1.05, p.ink, { opacity: 0.82, ...mul }),
+ ...dotGrid(cx + R * 0.1, cy + R * 0.25, 9, 7, R * 0.16, R * 0.035, p.ink, 0.55),
+ grain(w, h, 0.14, 97),
+ meta(`RISO · NO.${digits(i, false)}`, x0, m * 0.9, w * 0.5, Math.max(15, 19 * u), p.ink, { opacity: 0.85 }),
+ ...badge(i.badge, x0, m * 0.9 + Math.max(15, 19 * u) * 2.2, p, Math.max(18, 24 * u)),
+ echo, title,
+ ...sub(i, x0, top + th + 26 * u, tw, subSize, p.sub, { fontWeight: 'bold' }),
+ ) };
+ },
+ },
+ {
+ id: 'ticket', zh: '票根', en: 'Ticket stub', fit: [...XHS, ...BANNER, ...VIDEO], zhUse: '一张带缺口和齿孔的入场券:主券写标题,存根放标签与条码;活动、课程、展览、旅行', enUse: 'An admission ticket with notches and perforation: headline on the main part, label and barcode on the stub; events, courses, travel',
+ build(i) {
+ const p = palette(i, { bg: '#ff6a3d', bg2: '#ff6a3d', ink: '#1f1a17', sub: '#6b6158', accent: '#ff6a3d', accentInk: '#fff6ea' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.05; const card = '#fff6ea';
+ const cx = m, cy = side ? m : m * 1.3; const cw = w - m * 2, ch = h - cy * 2; const stub = side ? cw * 0.26 : ch * 0.24;
+ const mainW = side ? cw - stub : cw; const mainH = side ? ch : ch - stub; const pad = Math.max(m * 0.75, 36 * u); const tw = mainW - pad * 2; const metaS = Math.max(15, 20 * u);
+ const size = fitTitle(i.title, tw, mainH * 0.5, 190 * u, 36, 1.06); const th = textHeight(i.title, tw, size, 1.06);
+ const subSize = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.25) + 24 * u : 0;
+ const head = metaS * 2.8; const ty = cy + pad + head + (mainH - pad * 2 - head - th - subH) * 0.5;
+ const nr = Math.max(18, 30 * u); const px = side ? cx + mainW : cx; const py = side ? cy : cy + mainH;
+ const dash = { stroke: p.ink, strokeWidth: Math.max(2, 3 * u), strokeDashArray: [12 * u, 10 * u], opacity: 0.35, originX: 'left' as const, originY: 'top' as const };
+ const perf = side ? new Line([0, 0, 0, ch - nr * 2.6], { left: px, top: cy + nr * 1.3, ...dash }) : new Line([0, 0, cw - nr * 2.6, 0], { left: cx + nr * 1.3, top: py, ...dash });
+ const notch = side ? [dot(px, cy, nr, p.bg), dot(px, cy + ch, nr, p.bg)] : [dot(cx, py, nr, p.bg), dot(cx + cw, py, nr, p.bg)];
+ const label = i.badge?.trim() || (i.zh ? '入场券' : 'ADMIT ONE'); const sx = side ? px : cx, sy = side ? cy : py, sw = side ? stub : cw, sh = side ? ch : stub;
+ const ls = side ? fitTitle(label, sw - pad * 1.4, sh * 0.34, 110 * u, 24, 1.05) : fitTitle(label, sw * 0.5, sh * 0.6, 110 * u, 24, 1.05);
+ const bw = side ? Math.min(sw - pad * 1.4, 240 * u) : Math.min(sw * 0.34, 300 * u); const bh = side ? Math.min(sh * 0.2, 80 * u) : Math.min(sh * 0.42, 90 * u);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.08, 101),
+ rect(cx, cy, cw, ch, card, { rx: 22 * u, ry: 22 * u, shadow: new Shadow({ color: 'rgba(80,20,0,0.25)', blur: 40 * u, offsetX: 0, offsetY: 16 * u }) }),
+ ...notch, perf,
+ meta(i.zh ? 'ADMIT ONE · 入场' : 'ADMIT ONE', cx + pad, cy + pad, tw * 0.6, metaS, p.sub),
+ meta(`NO.${digits(i, false, '0001').padStart(4, '0')}`, cx + pad + tw * 0.5, cy + pad, tw * 0.5, metaS, p.sub, { textAlign: 'right' }),
+ rule(cx + pad, cy + pad + metaS * 1.9, tw, p.ink, Math.max(1.5, 2 * u), false, 0.6),
+ textbox(i.title, cx + pad, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.06 }),
+ ...sub(i, cx + pad, ty + th + 24 * u, tw, subSize, p.sub),
+ textbox(label, side ? sx + pad * 0.7 : sx + pad, side ? sy + sh * 0.18 : sy + (sh - ls * 1.19) / 2, side ? sw - pad * 1.4 : sw * 0.5, { qcRole: 'badge', fontSize: ls, fill: toContrast(p.accent, card), fontWeight: 'bold', lineHeight: 1.05, textAlign: side ? 'center' : 'left' }),
+ ...barcode(side ? sx + (sw - bw) / 2 : sx + sw - pad - bw, side ? sy + sh - pad - bh : sy + (sh - bh) / 2, bw, bh, p.ink, 9),
+ ) };
+ },
+ },
+ {
+ id: 'window', zh: '窗口教程', en: 'App window', fit: [...VIDEO, ...XHS, ...BANNER], zhUse: '柔和渐变底上一扇 macOS 风格窗口:红黄绿三点 + 文件名标签 + 窗口里的大标题;教程、工具、编程、效率', enUse: 'A macOS-style window on a soft gradient: traffic lights, a file tab and the headline inside; tutorials, tools and code',
+ build(i) {
+ const p = palette(i, { bg: '#dfe3fb', bg2: '#dfe3fb', ink: '#111827', sub: '#4b5563', accent: '#6366f1', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const cx = m * (wide ? 1.4 : 0.9); const cw = w - cx * 2; const ch = h * (wide ? 0.76 : 0.6); const cy = (h - ch) / 2;
+ const bar = Math.max(44, 66 * u); const pad = Math.max(m * 0.9, 48 * u); const tw = cw - pad * 2; const r = Math.max(14, 24 * u);
+ const size = fitTitle(i.title, tw, (ch - bar) * 0.52, 180 * u, 36, 1.08); const th = textHeight(i.title, tw, size, 1.08);
+ const subSize = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.25) + 28 * u : 0; const kick = Math.max(6, 9 * u) + 30 * u;
+ const ty = cy + bar + (ch - bar - th - subH - kick) / 2 + kick;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ ...dotGrid(w - m * 0.5 - 7 * 34 * u, m * 0.5, 8, 5, 34 * u, 4 * u, p.accent, 0.4, false), grain(w, h, 0.06, 103),
+ rect(cx, cy, cw, ch, '#ffffff', { rx: r, ry: r, shadow: new Shadow({ color: 'rgba(49,46,129,0.22)', blur: 60 * u, offsetX: 0, offsetY: 24 * u }) }),
+ rect(cx, cy, cw, bar, '#f3f4f6', { rx: r, ry: r }), rect(cx, cy + bar / 2, cw, bar / 2, '#f3f4f6'), rule(cx, cy + bar, cw, '#e5e7eb', Math.max(1, 2 * u)),
+ dot(cx + bar * 0.55, cy + bar / 2, bar * 0.13, '#ff5f57'), dot(cx + bar * 0.95, cy + bar / 2, bar * 0.13, '#febc2e'), dot(cx + bar * 1.35, cy + bar / 2, bar * 0.13, '#28c840'),
+ textbox(i.badge?.trim() || 'cover.md', cx + bar * 2, cy + (bar - bar * 0.36 * 1.13) / 2, cw - bar * 4, { qcRole: 'badge', fontSize: bar * 0.36, fill: '#6b7280', textAlign: 'center', fontFamily: 'monospace', lineHeight: 1 }),
+ rect(cx + pad, ty - kick, Math.max(40, 64 * u), Math.max(6, 9 * u), p.accent, { rx: 4 * u, ry: 4 * u }),
+ textbox(i.title, cx + pad, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08 }),
+ ...sub(i, cx + pad, ty + th + 28 * u, tw, subSize, p.sub),
+ ) };
+ },
+ },
+ {
+ id: 'newspaper', zh: '报纸头版', en: 'Front page', fit: [...BANNER, ...XHS, ...VIDEO], zhUse: '新闻纸 + 衬线报头(标签做报名)+ 双线 + 期号栏 + 分栏灰条;把观点做成“头版头条”,评论、深度、年度盘点', enUse: 'Newsprint, a serif masthead (the label), double rules, a dateline and greeked columns; opinion, analysis, annual reviews',
+ build(i) {
+ const p = palette(i, { bg: '#efeadf', bg2: '#efeadf', ink: '#141210', sub: '#4d4740', accent: '#b3261e', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.2; const x0 = m; const inner = w - m * 2;
+ const mast = i.badge?.trim() || (i.zh ? '封面日报' : 'The Cover Daily');
+ const ms = Math.min(side ? h * 0.12 : h * 0.075, inner * 0.9 / Math.max(3, [...mast].length * (hasCjk(mast) ? 1.05 : 0.55)));
+ const my = m * 0.6; const ry = my + ms * 1.2 + 8 * u; const ds = Math.max(13, 17 * u); const dl = ry + 16 * u; const hy = dl + ds * 2.4 + 26 * u;
+ const tw = side ? inner * 0.6 : inner; const size = fitTitle(i.title, tw, (h - hy - m) * (side ? 0.7 : 0.42), 200 * u, 36, 1.06); const th = textHeight(i.title, tw, size, 1.06);
+ const subSize = Math.max(22, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.25) + 26 * u : 0;
+ const colX = side ? x0 + tw + m * 0.7 : x0; const colW = side ? w - m - colX : inner; const colY = side ? hy + 6 * u : hy + th + subH + 34 * u; const ncol = side ? 2 : 3; const cg = 26 * u; const cwid = (colW - cg * (ncol - 1)) / ncol;
+ const lg = Math.max(14, 22 * u); const bars: FabricObject[] = [];
+ for (let c = 0; c < ncol; c++) for (let k = 0; colY + k * lg + lg < h - m && k < 40; k++) { const end = (k + c * 3) % 9 === 8; bars.push(rect(colX + c * (cwid + cg), colY + k * lg, cwid * (end ? 0.55 : 0.88 + ((k * 7 + c * 5) % 5) * 0.03), lg * 0.34, p.ink, { opacity: 0.16 })); }
+ if (!side) for (let c = 1; c < ncol; c++) bars.push(rule(colX + c * (cwid + cg) - cg / 2, colY, h - m - colY, p.ink, 1, true, 0.25)); else bars.push(rule(colX - m * 0.35, hy, h - m - hy, p.ink, 1, true, 0.35));
+ const dlText = (t: string, x: number, align: string): Textbox => meta(t, x, dl, inner / 3, ds, p.ink, { textAlign: align });
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.12, 107),
+ textbox(mast, x0, my, inner, { qcRole: 'badge', fontSize: ms, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', textAlign: 'center', lineHeight: 1 }),
+ rule(x0, ry, inner, p.ink, Math.max(3, 4 * u)), rule(x0, ry + 8 * u, inner, p.ink, Math.max(1, 1.5 * u)),
+ dlText('VOL. 2026', x0, 'left'), dlText(i.zh ? '特 刊' : 'SPECIAL EDITION', x0 + inner / 3, 'center'), dlText(`NO. ${digits(i, false)}`, x0 + inner * 2 / 3, 'right'),
+ rule(x0, dl + ds * 1.7, inner, p.ink, Math.max(1, 1.5 * u)),
+ textbox(i.title, x0, hy, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontFamily: SERIF, fontWeight: 'bold', lineHeight: 1.06 }),
+ ...sub(i, x0, hy + th + 26 * u, tw, subSize, p.accent, { fontFamily: SERIF, fontWeight: 'bold' }),
+ ...bars,
+ ) };
+ },
+ },
+ {
+ id: 'polaroid', zh: '拍立得', en: 'Polaroid', fit: [...XHS, ...VIDEO, 'wechat'], zhUse: '一张贴着胶带的拍立得相纸(相纸里是图位)+ 标签写在相纸下沿 + 旁边大标题;旅行、Vlog、生活记录', enUse: 'A taped instant photo (the print is a picture slot), the label on its lip and a big headline beside it; travel, vlogs, everyday life',
+ slot: i => polaroidFrame(i).photo,
+ build(i) {
+ const p = palette(i, { bg: '#e7e0d3', bg2: '#e7e0d3', ink: '#2a241d', sub: '#6e6457', accent: '#d9653b', accentInk: '#ffffff' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.2; const f = polaroidFrame(i); const ph = f.photo;
+ const x0 = side ? m * 1.2 : m; const tw = side ? f.x - m * 2.2 : w - m * 2; const areaTop = side ? m : f.y + f.h + 40 * u; const areaH = side ? h - m * 2 : h - areaTop - m;
+ const size = fitTitle(i.title, tw, areaH * (side ? 0.6 : 0.62), 180 * u, 36, 1.08); const th = textHeight(i.title, tw, size, 1.08);
+ const subSize = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, tw, subSize, 1.25) + 24 * u : 0; const ty = areaTop + (areaH - th - subH) / 2;
+ const cap = i.badge?.trim(); const capS = Math.max(20, f.b * 1.1);
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.1, 109),
+ new Rect({ left: f.x + f.w / 2, top: f.y + f.h / 2, width: f.w, height: f.h, fill: '#f8f6f0', angle: -6, originX: 'center', originY: 'center', shadow: new Shadow({ color: 'rgba(40,25,10,0.18)', blur: 24 * u, offsetX: 0, offsetY: 8 * u }) }),
+ rect(f.x, f.y, f.w, f.h, '#fdfcf8', { shadow: new Shadow({ color: 'rgba(40,25,10,0.26)', blur: 30 * u, offsetX: 0, offsetY: 12 * u }) }),
+ rect(ph.x, ph.y, ph.w, ph.h, gradient(ph.w, ph.h, '#f4c99b', '#7f9bb5', 170)), kitGlow(ph.x + ph.w * 0.7, ph.y + ph.h * 0.42, ph.w * 0.32, '#fff3d6', 0.9),
+ tape(f.x + f.w / 2 - 80 * u, f.y - 22 * u, 160 * u, 44 * u, -4),
+ cap ? textbox(cap, f.x + f.b, ph.y + ph.h + (f.h - ph.h - f.b - capS * 1.3) / 2, f.w - f.b * 2, { qcRole: 'badge', fontSize: capS, fill: p.sub, fontFamily: SERIF, textAlign: 'center', lineHeight: 1.1 }) : undefined,
+ textbox(i.title, x0, ty, tw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08, textAlign: side ? 'left' : 'center' }),
+ ...sub(i, x0, ty + th + 24 * u, tw, subSize, p.sub, { textAlign: side ? 'left' : 'center' }),
+ ) };
+ },
+ },
+ {
+ id: 'stack', zh: '叠字海报', en: 'Echo stack', fit: [...XHS, ...SHORT, ...BANNER], zhUse: '同一句标题上下重复、逐层变淡,中间一行是红色实字;字体海报的节奏感,适合短标题、口号、金句', enUse: 'The headline repeated in fading layers around one solid red line; a rhythmic type poster for short titles and slogans',
+ build(i) {
+ const p = palette(i, { bg: '#ece6da', bg2: '#ece6da', ink: '#16130f', sub: '#5f574c', accent: '#e8432b', accentInk: '#ffffff' });
+ const { u, m, w, h, wide } = metrics(i); const x0 = m; const tw = w - m * 2; const lh = 0.98;
+ const subSize = Math.max(24, 34 * u); const reserve = (i.subtitle.trim() ? subSize * 1.5 + 40 * u : 0) + (i.badge?.trim() ? 70 * u : 0) + m * 2;
+ const one = Math.min(260 * u, h * (wide ? 0.17 : 0.11), (tw * 100) / Math.max(1, lineW(i.title, 100)) * 0.98);
+ const size = one >= 60 * u ? one : fitTitle(i.title, tw, h * 0.22, 160 * u, 32, lh); const rows = wrapLines(i.title, tw, size, 'bold', -18).length; const block = rows * size * lh * FABRIC_LINE + (rows > 1 ? size * 0.4 : 0);
+ let n = Math.max(3, Math.min(9, Math.floor((h - reserve) / block))); if (n % 2 === 0) n--; const mid = (n - 1) / 2;
+ const y0 = m + (i.badge?.trim() ? 70 * u : 0) + (h - reserve - n * block) / 2;
+ const title = textbox(i.title, x0, y0 + mid * block, tw, { qcRole: 'title', fontSize: size, fill: p.accent, fontWeight: 'bold', lineHeight: lh, charSpacing: -18, textAlign: 'center' });
+ const echoes = Array.from({ length: n }, (_, k) => k).filter(k => k !== mid).map(k => echoOf(title, i.title, x0, y0 + k * block, tw, { fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: lh, charSpacing: -18, textAlign: 'center', opacity: 0.08 + 0.5 * (1 - Math.abs(k - mid) / (mid + 1)) ** 2 }));
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.08, 113), ...echoes, title,
+ ...badge(i.badge, 0, m * 0.9, { ...p, accent: p.ink, accentInk: p.bg }, Math.max(18, 24 * u)).map(b => { b.set({ left: w / 2 - b.width / 2 }); return b; }),
+ ...sub(i, x0, Math.min(h - m - subSize * 1.3, y0 + n * block + 30 * u), tw, subSize, p.sub, { textAlign: 'center', fontWeight: 'bold' }),
+ ) };
+ },
+ },
+ {
+ id: 'serial', zh: '栏目头图', en: 'Column header', fit: [...BANNER, ...VIDEO, ...XHS], zhUse: '深绿栏目条(栏目名 + 大期号,标签写“周刊 12”)+ 标题;公众号系列文章、周刊、播客的固定头图,转发裁成方图时标题仍在中间', enUse: 'A dark column band with the series name and a big issue number (label like “Weekly 12”) beside the headline; recurring newsletters and podcasts',
+ build(i) {
+ const p = palette(i, { bg: '#f4f1ea', bg2: '#f4f1ea', ink: '#1a1a1a', sub: '#6b6560', accent: '#1f4d3a', accentInk: '#f4f1ea' });
+ const { u, m, w, h } = metrics(i); const side = w / h > 1.25; const num = digits(i, false).padStart(2, '0');
+ const name = (i.badge?.trim() ?? '').replace(/\d+/g, '').replace(/[#№.·\s-]+$/, '').trim() || (i.zh ? '深度专栏' : 'COLUMN');
+ const bw = side ? w * 0.3 : w; const bh = side ? h : h * 0.36; const ms = Math.max(16, 22 * u); const bp = m * 0.9;
+ const ns = side ? Math.min(h * 0.5, (bw - bp * 2) / (num.length * 0.62)) : Math.min(bh * 0.52, (bw - bp * 2) / (num.length * 0.62));
+ const cx = side ? bw + m * 1.2 : m; const cw = side ? w - cx - m : w - m * 2; const cTop = side ? m : bh + m; const cH = side ? h - m * 2 : h - bh - m * 2;
+ const size = fitTitle(i.title, cw, cH * 0.66, 180 * u, 36, 1.08); const th = textHeight(i.title, cw, size, 1.08);
+ const subSize = Math.max(24, size * 0.3); const subH = i.subtitle.trim() ? textHeight(i.subtitle, cw, subSize, 1.25) + 26 * u : 0; const kick = 34 * u; const ty = cTop + (cH - th - subH - kick) / 2 + kick;
+ return { background: solid(p.bg), objects: keep<FabricObject>(
+ grain(w, h, 0.07, 127), rect(0, 0, bw, bh, p.accent), grain(bw, bh, 0.1, 131),
+ textbox(name, bp, bp, bw - bp * 2, { qcRole: 'badge', fontSize: Math.max(30, 54 * u), fill: p.accentInk, fontWeight: 'bold', lineHeight: 1.1 }),
+ meta('NO.', bp, bh - bp - ns * 1.02 - ms * 1.6, bw * 0.5, ms, p.accentInk, { opacity: 0.7 }),
+ textbox(num, bp, bh - bp - ns * 1.02, bw - bp * 2, { fontSize: ns, fill: p.accentInk, fontWeight: 'bold', lineHeight: 0.9, charSpacing: -30 }),
+ rect(cx, ty - kick, Math.max(40, 64 * u), Math.max(5, 7 * u), p.accent),
+ textbox(i.title, cx, ty, cw, { qcRole: 'title', fontSize: size, fill: p.ink, fontWeight: 'bold', lineHeight: 1.08 }),
+ ...sub(i, cx, ty + th + 26 * u, cw, subSize, p.sub),
+ ) };
+ },
+ },
+
+];
+
+// Premium styles first; the three plainest classics (editorial, centred label, old sticker) are superseded by these.
+const RETIRED = new Set(['editorial', 'center', 'sticker', 'dark', 'gradient', 'checklist', 'soft', 'compare', 'split', 'impact', 'bili']);
+for (let k = TEMPLATES.length - 1; k >= 0; k--) if (RETIRED.has(TEMPLATES[k]!.id)) TEMPLATES.splice(k, 1);
+const MOODY = new Set(['neon', 'cinema', 'quote']); // dark by nature: still available, but never the first thing a new user sees
+TEMPLATES.unshift(...GAODING, ...STUDIO.filter(t => !MOODY.has(t.id)), ...PREMIUM.filter(t => !MOODY.has(t.id)), ...PREMIUM.filter(t => MOODY.has(t.id)), ...STUDIO.filter(t => MOODY.has(t.id)));
+// The first screen of the gallery alternates quiet and loud, paper and colour, so the range is visible without scrolling.
+const LEAD = ['folio', 'brush', 'keyword', 'regeng', 'highlight', 'frame', 'sage', 'notes', 'interview', 'riso', 'kicker', 'numeral', 'calendar', 'ticket', 'corner', 'polaroid', 'serial', 'chat', 'window', 'newspaper', 'stack', 'bili', 'pop'];
+// Looks built on mesh gradients and soft glows read as generic in a feed, so they are offered last.
+const GRADIENT_LED = new Set(['acid', 'glass']); TEMPLATES.sort((x, y) => (LEAD.indexOf(x.id) + 1 || (GRADIENT_LED.has(x.id) ? 199 : 99)) - (LEAD.indexOf(y.id) + 1 || (GRADIENT_LED.has(y.id) ? 199 : 99)));
+
+/**
+ * Typographic finish applied to every template, so the system is consistent rather than each layout inventing its own rules:
+ * tighter tracking on big CJK headlines, and for the left-aligned "text block" layouts the subtitle sits right under the
+ * headline and the block is optically centred (a little above the middle) instead of leaving the subtitle at the page foot.
+ */
+const STACKED = new Set(['minimal', 'dark', 'gradient', 'split', 'soft']);
+/** Layouts whose text is a plain block that can be re-stacked without breaking anything attached to it (stickers, rules, frames). */
+export const canReflow = (id: string | undefined): boolean => !!id && (STACKED.has(id) || ['bold', 'poster', 'impact', 'photo', 'bili', 'number', 'compare', 'neo'].includes(id));
+for (const t of TEMPLATES) {
+ const raw = t.build.bind(t);
+ t.build = (i: TemplateInput): TemplateResult => {
+ const r = raw(i);
+ const texts = r.objects.filter((o): o is Textbox & RoleBox => o instanceof Textbox);
+ const title = texts.find(x => x.qcRole === 'title'), sub = texts.find(x => x.qcRole === 'subtitle' && !(x instanceof BadgeBox)), tag = texts.find(x => x.qcRole === 'badge');
+ if (title && hasCjk(title.text) && title.fontSize >= 64) title.set({ charSpacing: -18 });
+ // A pill cannot wrap: one that would run past the far margin gets a smaller size instead of leaving the canvas.
+ for (const b of texts) if (b instanceof BadgeBox && b.originX === 'left' && Math.abs(b.angle ?? 0) < 10) {
+ const room = i.width - b.left * 2; if (room > 0 && b.width > room) { b.set({ fontSize: b.fontSize * room / b.width }); b.initDimensions(); b.setCoords(); }
+ }
+ // A subtitle has to be readable at thumbnail size: never smaller than about a third of the headline.
+ if (title && sub && !sub.angle && t.id !== 'print' && sub.fontSize < title.fontSize * 0.3) {
+ sub.set({ fontSize: Math.min(title.fontSize * 0.3, sub.fontSize * 2.6) });
+ // At the new size the line may no longer fit: wrap it with the CJK-aware rules, not Fabric's per-character split (which starts lines with ";").
+ if (hasCjk(sub.text)) { (sub as Wrapped).qcWrapped = true; sub.set({ splitByGrapheme: false }); rewrap(sub); }
+ }
+ if (STACKED.has(t.id)) tightenCopy(r.objects, i.width, i.height, 0.47);
+ // The subtitle must never sit on the headline: when they overlap, drop it just below.
+ // A label must not sit on the headline: push the headline below it when they collide.
+ if (title && tag && tag.top + tag.getScaledHeight() > title.top && tag.top < title.top + title.getScaledHeight() && tag.left < title.left + title.getScaledWidth() && tag.left + tag.getScaledWidth() > title.left) {
+ const lowest = tag.top + tag.getScaledHeight() + tag.fontSize * 0.5; const room = i.height - title.getScaledHeight() - 12; title.set({ top: Math.min(room, Math.max(title.top, lowest)) }); title.setCoords();
+ }
+ // (after the label rule, which can move the headline) a subtitle never sits inside the headline
+ if (title && sub && sub.top < title.top + title.getScaledHeight() && sub.top + sub.getScaledHeight() > title.top && sub.left < title.left + title.getScaledWidth() && sub.left + sub.getScaledWidth() > title.left && !sub.angle && !title.angle) {
+ const next = title.top + title.getScaledHeight() + title.fontSize * 0.18; if (next + sub.getScaledHeight() < i.height - 8) { sub.set({ top: next }); sub.setCoords(); }
+ }
+ return r;
+ };
+}
+
+/** Templates ordered so those designed for `platformId` come first. */
+// Dark, loud looks (sunburst punch, neon, letterbox): still resolvable for old covers, never offered in the gallery.
+const HIDDEN = new Set(['impact', 'neon', 'cinema', 'quote', 'compare', 'ticker']);
+export function templatesFor(platformId: string | undefined): Template[] {
+ return TEMPLATES.filter(t => !HIDDEN.has(t.id)).sort((a, b) => Number(b.fit.includes(platformId ?? '')) - Number(a.fit.includes(platformId ?? '')));
+}
+
+type RoleBox = FabricObject & { qcRole?: string };
+/**
+ * Proximity and optical centring for wide covers: when a left-aligned subtitle sits far below its headline, pull it up under
+ * the headline and centre the whole text block vertically. Leaves layouts with other text, centred type or tall canvases alone.
+ */
+export function tightenCopy(objects: FabricObject[], width: number, height: number, centre = 0.5): void {
+ const texts = objects.filter((o): o is Textbox & RoleBox => o instanceof Textbox);
+ const title = texts.find(t => t.qcRole === 'title'), sub = texts.find(t => t.qcRole === 'subtitle'), badgeBox = texts.find(t => t.qcRole === 'badge');
+ if (!title || !sub || texts.some(t => t !== title && t !== sub && t !== badgeBox)) return;
+ if (Math.abs(title.left - sub.left) > 6 || title.textAlign !== 'left' || sub.textAlign !== 'left' || sub.top < title.top) return;
+ const gap = (): number => title.fontSize * title.scaleY * 0.3;
+ const stack = (): { top: number; bottom: number } => {
+ const size = title.fontSize * title.scaleY; const want = Math.min(size * 0.3, sub.fontSize * 2);
+ if (want > sub.fontSize * sub.scaleY) sub.set({ fontSize: want, scaleX: 1, scaleY: 1 });
+ // Headline, then subtitle one gap below it: closer than the template's anchor when far apart, and clear of it when overlapping.
+ sub.set({ top: title.top + title.getScaledHeight() + gap() });
+ const head = badgeBox ? badgeBox.top : title.top; if (badgeBox) badgeBox.set({ top: title.top - badgeBox.getScaledHeight() - gap() * 0.9 });
+ return { top: badgeBox ? badgeBox.top : head, bottom: sub.top + sub.getScaledHeight() };
+ };
+ let block = stack();
+ for (let guard = 0; block.bottom - block.top > height * 0.78 && guard < 12; guard++) { title.set({ fontSize: Math.max(36, title.fontSize * 0.92) }); block = stack(); }
+ const shift = height * centre - (block.bottom + block.top) / 2;
+ for (const o of [badgeBox, title, sub]) if (o) { o.set({ top: o.top + shift }); o.setCoords(); }
+}
+
+/**
+ * Portrait covers with a subject on the lower half: stack badge, headline and subtitle together in the upper part so the
+ * words and the picture never fight for the same pixels. The headline shrinks only if the block would not fit.
+ */
+export function arrangeForSubject(objects: FabricObject[], width: number, height: number): void {
+ if (height < width * 1.1) return;
+ const texts = objects.filter((o): o is Textbox & RoleBox => o instanceof Textbox);
+ const title = texts.find(t => t.qcRole === 'title'), sub = texts.find(t => t.qcRole === 'subtitle'), badgeBox = texts.find(t => t.qcRole === 'badge');
+ if (!title) return;
+ // A huge faint glyph is a background ornament and an identical second copy of the title is its echo: neither blocks restacking.
+ const echoes = texts.filter(t => t !== title && !t.qcRole && t.text === title.text);
+ const ghost = (t: Textbox & RoleBox): boolean => t.qcRole === 'ghost' || (!t.qcRole && t.fontSize * (t.scaleY || 1) > height * 0.2);
+ if (texts.some(t => t !== title && t !== sub && t !== badgeBox && !echoes.includes(t) && !ghost(t))) return;
+ const offsets = echoes.map(e => ({ e, dx: e.left - title.left, dy: e.top - title.top }));
+ const top0 = height * 0.07; const limit = height * 0.46; const gap = (): number => title.fontSize * title.scaleY * 0.28;
+ const layout = (): number => {
+ let y = top0; if (badgeBox) { badgeBox.set({ top: y }); y += badgeBox.getScaledHeight() + gap(); }
+ title.set({ top: y }); y += title.getScaledHeight(); if (sub) { y += gap(); sub.set({ top: y }); y += sub.getScaledHeight(); } return y;
+ };
+ let bottom = layout();
+ for (let guard = 0; bottom > limit && guard < 12; guard++) { title.set({ fontSize: Math.max(36, title.fontSize * 0.9) }); bottom = layout(); }
+ for (const { e, dx, dy } of offsets) { e.set({ fontSize: title.fontSize, top: title.top + dy, left: title.left + dx }); e.initDimensions(); e.setCoords(); }
+ for (const o of [badgeBox, title, sub]) o?.setCoords();
+}
+
+/** A decoration hung under the headline takes room: nudge the subtitle below it so the two never overlap. */
+export function reserveBelowTitle(objects: FabricObject[], decorBottom: number): void {
+ const texts = objects.filter((o): o is Textbox & RoleBox => o instanceof Textbox);
+ const title = texts.find(t => t.qcRole === 'title'), sub = texts.find(t => t.qcRole === 'subtitle'); if (!title || !sub) return;
+ const need = decorBottom + title.fontSize * title.scaleY * 0.14;
+ if (sub.top >= title.top && sub.top < need) { sub.set({ top: need }); sub.setCoords(); }
+}
+
+/** Building blocks shared with the layout sets kept in their own files (gaoding.ts). */
+export { rect, metrics, solid, pill, badge, sub, keep, meta, dot, lineW, FABRIC_LINE };
diff --git a/apps/web/src/lib/poster-design/vendor/qiaomu/typeset.ts b/apps/web/src/lib/poster-design/vendor/qiaomu/typeset.ts
new file mode 100644
index 00000000..12059ad8
--- /dev/null
+++ b/apps/web/src/lib/poster-design/vendor/qiaomu/typeset.ts
@@ -0,0 +1,73 @@
+/**
+ * Font pairing rules. A cover uses at most two families: one display face for the title (and badge) and one calm face for everything
+ * else. Each template names a mood; the mood lists candidates best first, and the first installed one wins, so a cover always looks
+ * right with what the user has and better with what the starter pack installs.
+ *
+ * Rules the lists encode:
+ * 1. Title = display face, body = neutral face. Never two display faces.
+ * 2. Weight contrast does the hierarchy: a single-weight heavy title over a regular body, never bold-on-bold.
+ * 3. Heavy display faces are single-weight, so they are never faux-bolded.
+ * 4. Serif titles pair with a warm kai/song body; sans titles with a plain gothic body.
+ */
+export type Mood = 'heavy' | 'punch' | 'tech' | 'trend' | 'warm' | 'serif' | 'brush';
+export interface Pair { title: string[]; body: string[]; zh: string }
+
+// The default font library comes first everywhere, so a fresh install looks exactly like the design; system faces only catch
+// the moment before the library has landed.
+const BODY = ['思源黑体', 'PingFang SC', 'Microsoft YaHei'];
+export const MOODS: Record<Mood, Pair> = {
+ heavy: { zh: '稳重有力', title: ['思源黑体 Heavy', '思源黑体 Bold', 'PingFang SC'], body: BODY },
+ punch: { zh: '冲击抓眼', title: ['抖音美好体', '思源黑体 Heavy', '思源黑体 Bold', 'PingFang SC'], body: BODY },
+ tech: { zh: '科技数据', title: ['未来荧黑', '得意黑', '思源黑体 Heavy'], body: BODY },
+ trend: { zh: '潮流年轻', title: ['得意黑', '抖音美好体', '站酷庆科黄油体'], body: BODY },
+ warm: { zh: '亲切活泼', title: ['江城圆体', '站酷庆科黄油体', '猫啃什锦黑', '抖音美好体'], body: BODY },
+ serif: { zh: '文艺深度', title: ['思源宋体 Heavy', '朱雀仿宋', '思源宋体 Bold', 'Songti SC'], body: ['霞鹜文楷', '思源宋体', ...BODY] },
+ brush: { zh: '国风书法', title: ['马善政楷书', '志莽行书', '朱雀仿宋'], body: ['朱雀仿宋', '霞鹜文楷', '思源宋体', ...BODY] },
+};
+
+const TEMPLATE_FACES: Record<string, string[]> = {
+ keyword: ['得意黑'], riso: ['站酷快乐体', '站酷庆科黄油体'],
+ newspaper: ['思源宋体 Heavy'], mag: ['朱雀仿宋', '思源宋体 Heavy'],
+ notes: ['霞鹜文楷'], numeral: ['未来荧黑'],
+ window: ['未来荧黑', '得意黑'], brush: ['抖音美好体', '思源黑体 Heavy', '思源黑体 Bold'],
+ polaroid: ['霞鹜文楷', '站酷庆科黄油体'], stack: ['抖音美好体', '思源黑体 Heavy', '思源黑体 Bold'],
+};
+
+const MOOD_OF: Record<string, Mood> = {
+ minimal: 'heavy', editorial: 'serif', bold: 'punch', dark: 'tech', poster: 'heavy', split: 'heavy', sticker: 'warm', gradient: 'trend', center: 'punch',
+ checklist: 'warm', number: 'tech', impact: 'punch', photo: 'heavy', bili: 'punch', compare: 'punch', neo: 'punch', soft: 'serif', swiss: 'heavy',
+ acid: 'trend', collage: 'warm', mega: 'heavy', ticker: 'tech', memo: 'warm', pop: 'trend', mag: 'serif', print: 'heavy', glass: 'heavy', bento: 'heavy',
+ neon: 'tech', calm: 'serif', seal: 'brush', quote: 'serif', cinema: 'serif',
+ highlight: 'punch', notes: 'heavy', chat: 'heavy', keyword: 'punch', riso: 'trend', ticket: 'heavy', window: 'tech', newspaper: 'serif', polaroid: 'warm',
+ stack: 'heavy', serial: 'heavy', aurora: 'tech', folio: 'heavy', sage: 'heavy', numeral: 'tech',
+ regeng: 'heavy', interview: 'punch', brush: 'punch', calendar: 'heavy', frame: 'heavy', kicker: 'heavy', corner: 'heavy',
+};
+export const moodOf = (templateId: string | undefined): Mood => MOOD_OF[templateId ?? ''] ?? 'heavy';
+
+/** Faces that ship a real bold. Everything else in the lists is single-weight and must not be faux-bolded. */
+// Library faces are one weight per family (思源黑体 / Bold / Heavy are separate families), so only system faces get a real bold.
+const HAS_BOLD = new Set(['PingFang SC', 'Songti SC', 'Microsoft YaHei', 'MiSans', '鸿蒙黑体', '阿里巴巴普惠体']);
+
+export interface Resolved { title?: string; body?: string; titleBold: boolean; /** Best title/body families that are not installed yet. */ missing: string[] }
+/** Picks the first installed family of each list. `missing` names the top choice per role when it is not installed. */
+export function resolvePair(templateId: string | undefined, have: (family: string) => boolean): Resolved {
+ const mood = MOODS[moodOf(templateId)];
+ const title = [...(TEMPLATE_FACES[templateId ?? ''] ?? []), ...mood.title, ...BODY].find(have), body = mood.body.find(have);
+ const missing = [mood.title[0], mood.body[0]].filter((f): f is string => !!f && !have(f));
+ return { ...(title ? { title } : {}), ...(body ? { body } : {}), titleBold: !!title && HAS_BOLD.has(title), missing: [...new Set(missing)] };
+}
+
+/** The pairing the template builders read while they build. Set by the view just before `build`, cleared right after. */
+let active: Resolved | undefined;
+export function usePairing(r: Resolved | undefined): void { active = r; }
+const GENERIC = new Set(['sans-serif', 'serif']);
+/** Swaps the generic family a builder asked for with the paired one. Monospace and explicit families are left alone. */
+export function typeFor(role: string | undefined, family: string | undefined, weight: string | undefined): { fontFamily?: string; fontWeight?: string } {
+ if (!active || !family || !GENERIC.has(family)) return {};
+ const display = role === 'title' || role === 'badge';
+ const face = display ? active.title : active.body;
+ if (!face) return {};
+ return { fontFamily: face, ...(display && !active.titleBold && (weight === 'bold' || weight === '700') ? { fontWeight: 'normal' } : {}) };
+}
+/** Family the title is measured with, so wrapping decisions match what is drawn. */
+export const titleFace = (): string => (active?.title ? `"${active.title}"` : 'sans-serif');
diff --git a/apps/web/src/lib/poster-save.test.mjs b/apps/web/src/lib/poster-save.test.mjs
new file mode 100644
index 00000000..c5f70bce
--- /dev/null
+++ b/apps/web/src/lib/poster-save.test.mjs
@@ -0,0 +1,51 @@
+import { test, expect } from "bun:test";
+import { createPosterDocument, parsePosterDocument } from "@edgeever/shared";
+import { savePosterMemo } from "./poster-save";
+const memo = { id: "memo", title: "Poster", revision: 3, contentHash: "old", tags: ["design"] };
+test("saves source with optimistic revision/hash checks and immutable preview", async () => {
+ let payload;
+ const repository = {
+ uploadMemoResource: async () => ({ resource: { id: "res_new" } }),
+ updateMemo: async (_memo, input) => { payload = input; return { memo: { ...memo, ...input } }; },
+ deleteResource: async () => { throw new Error("must keep committed preview"); },
+ };
+ await savePosterMemo(repository, memo, createPosterDocument("Hello"), "Poster", "session", new Blob(["png"]));
+ expect(payload).toMatchObject({ expectedRevision: 3, expectedContentHash: "old", editSessionId: "session", tags: ["design"] });
+ expect(parsePosterDocument(payload.contentMarkdown)?.previewResourceId).toBe("res_new");
+ expect(JSON.stringify(payload.contentJson)).not.toContain("edgeever-poster-v1");
+});
+test("failed memo save removes only its uncommitted preview, never the previous revision", async () => {
+ const deleted = [];
+ const repository = {
+ uploadMemoResource: async () => ({ resource: { id: "res_new" } }),
+ updateMemo: async () => { throw new Error("revision conflict"); },
+ getMemo: async () => ({ memo }),
+ deleteResource: async (id) => { deleted.push(id); },
+ };
+ await expect(savePosterMemo(repository, memo, { ...createPosterDocument(), previewResourceId: "res_old" }, "Poster", "session", new Blob(["png"]))).rejects.toThrow("revision conflict");
+ expect(deleted).toEqual(["res_new"]);
+});
+test("metadata-only saves reuse the existing preview and persist edited tags", async () => {
+ let payload;
+ const repository = {
+ uploadMemoResource: async () => { throw new Error("should not upload"); },
+ updateMemo: async (_memo, input) => { payload = input; return { memo }; },
+ };
+ const result = await savePosterMemo(repository, memo, { ...createPosterDocument(), previewResourceId: "res_old" }, "New title", "session", undefined, ["poster", "layout"]);
+ expect(result.document.previewResourceId).toBe("res_old");
+ expect(payload.tags).toEqual(["poster", "layout"]);
+});
+
+test("an uncertain storage failure retains a preview already referenced by source", async () => {
+ const { serializePosterDocument } = await import("@edgeever/shared");
+ const document = { ...createPosterDocument(), previewResourceId: "res_new" };
+ let deleted = false;
+ const repository = {
+ uploadMemoResource: async () => ({ resource: { id: "res_new" } }),
+ updateMemo: async () => { throw new Error("acknowledgement lost"); },
+ getMemo: async () => ({ memo: { ...memo, contentMarkdown: serializePosterDocument(document) } }),
+ deleteResource: async () => { deleted = true; },
+ };
+ await expect(savePosterMemo(repository, memo, document, "Poster", "session", new Blob(["png"]))).rejects.toThrow("acknowledgement lost");
+ expect(deleted).toBe(false);
+});
diff --git a/apps/web/src/lib/poster-save.ts b/apps/web/src/lib/poster-save.ts
new file mode 100644
index 00000000..1205f407
--- /dev/null
+++ b/apps/web/src/lib/poster-save.ts
@@ -0,0 +1,32 @@
+import { markdownToDoc, posterFallbackMarkdown, parsePosterDocument, serializePosterDocument, type MemoDetail, type PosterDocument } from "@edgeever/shared";
+import type { EdgeEverRepository } from "./repository";
+
+// Immutable previews keep revision restores and concurrent drafts independent.
+// Only artwork changes upload a new, bounded-size preview; metadata edits reuse it.
+export const savePosterMemo = async (repository: EdgeEverRepository, memo: MemoDetail, document: PosterDocument, title: string, editSessionId: string, preview?: Blob, tags: string[] = memo.tags) => {
+ let previewId: string | undefined;
+ let committed = false;
+ try {
+ if (preview) {
+ if (typeof navigator !== "undefined" && navigator.onLine === false) throw new Error("Reconnect to save the poster preview. Your local draft is preserved.");
+ const { resource } = await repository.uploadMemoResource(memo.id, new File([preview], "poster-preview.png", { type: "image/png" }));
+ previewId = resource.id;
+ }
+ const next = { ...document, ...(previewId ? { previewResourceId: previewId } : {}) };
+ const result = await repository.updateMemo(memo, {
+ expectedRevision: memo.revision, expectedContentHash: memo.contentHash, editSessionId, title,
+ contentMarkdown: serializePosterDocument(next), contentJson: markdownToDoc(posterFallbackMarkdown(next)), tags,
+ });
+ committed = true;
+ return { memo: result.memo, document: next };
+ } finally {
+ if (previewId && !committed) {
+ // A storage failure can arrive after a local commit. Keep the attachment
+ // unless the current source confirms that it was never referenced.
+ const latest = await repository.getMemo(memo.id).catch(() => null);
+ if (latest && parsePosterDocument(latest.memo.contentMarkdown)?.previewResourceId !== previewId) {
+ await repository.deleteResource(previewId).catch(() => undefined);
+ }
+ }
+ }
+};
diff --git a/apps/web/tests/poster-design.html b/apps/web/tests/poster-design.html
new file mode 100644
index 00000000..5f2b06b7
--- /dev/null
+++ b/apps/web/tests/poster-design.html
@@ -0,0 +1,17 @@
+<!doctype html><html><meta charset="utf-8"><title>Poster design validation</title><style>body{font:14px system-ui;background:#eef0f3}#results{display:grid;grid-template-columns:repeat(6,1fr);gap:12px}article{padding:10px;background:white}img{width:100%}pre{white-space:pre-wrap}</style><h1>Real template rendering and persistence check</h1><output id="summary">Running</output><pre id="errors"></pre><div id="results"></div><script type="module">
+import {buildPosterDesign,DESIGN_TEMPLATES,PLATFORMS} from '/src/lib/poster-design/templates.ts';
+import {posterObject,posterElementFromObject,renderPosterThumbnail,ensurePosterContrast,ActiveSelection,Canvas} from '/src/lib/poster-canvas.ts';
+import {parsePosterDocument,serializePosterDocument} from '@edgeever/shared';
+let passed=0,failed=0;const errors=[];
+for(const size of PLATFORMS.map(({width,height})=>({width,height})))for(const template of DESIGN_TEMPLATES){try{
+ const doc=await buildPosterDesign({id:template.id,title:'把想法\n变成作品',subtitle:'认真记录,让每个好想法被看见。',badge:'创作笔记',...size,zh:true});
+ const parsed=parsePosterDocument(serializePosterDocument(doc));if(JSON.stringify(parsed)!==JSON.stringify(doc))throw new Error('source roundtrip differs');
+ const src=await renderPosterThumbnail(doc);passed++;if(size.width===1080&&size.height===1440){const item=document.createElement('article');item.innerHTML=`<img src="${src}"><p>${template.zh} · ${doc.elements.length}</p>`;document.querySelector('#results').append(item)}else URL.revokeObjectURL(src);
+}catch(error){failed++;errors.push(template.id+' '+size.width+'x'+size.height+': '+error.message);document.querySelector('#errors').textContent=errors.join('\n')}
+document.querySelector('#summary').textContent=`${passed} passed, ${failed} failed`;
+}
+// Persisted geometry must match the world coordinates of an active multi-selection.
+try{const canvas=new Canvas(document.createElement('canvas'),{width:1080,height:1440});const doc=await buildPosterDesign({id:'folio',title:'几何验证',subtitle:'保存前后保持排版',width:1080,height:1440,zh:true});const es=doc.elements.filter(e=>e.type==='text').slice(0,2);const os=await Promise.all(es.map(e=>posterObject(e,async()=>{throw Error('unexpected resource')})));canvas.add(...os);const before=os.map(o=>o.calcTransformMatrix());const group=new ActiveSelection(os,{canvas});canvas.setActiveObject(group);group.set({left:group.left+100,top:group.top+50,angle:15,scaleX:1.2,scaleY:1.2});for(let i=0;i<os.length;i++){const next=posterElementFromObject(es[i],os[i]);const restored=await posterObject(next,async()=>{throw Error('unexpected resource')});const a=os[i].calcTransformMatrix(),b=restored.calcTransformMatrix();if(a.some((v,j)=>Math.abs(v-b[j])>1.5))throw Error('multi-selection transform differs '+JSON.stringify({a,b,next}));}await canvas.dispose();passed++;}catch(e){failed++;errors.push(e.message);document.querySelector('#errors').textContent=errors.join('\n')}
+try { const input=await buildPosterDesign({id:'window',title:'对比度验证',subtitle:'白色卡片上的文字必须可读',badge:'EDGE EVER',width:1080,height:1440,zh:true,palette:{bg:'#0b163b',ink:'#ffffff',accent:'#2563eb'}});const fixed=await ensurePosterContrast(input,async()=>{throw Error('unexpected image')});const title=fixed.elements.find(e=>e.type==='text'&&e.role==='title');if(!title||title.fill==='#ffffff')throw Error('AI contrast not corrected');if(input.elements.length!==fixed.elements.length)throw Error('contrast check changed structure');passed++;}catch(e){failed++;errors.push(e.message);document.querySelector('#errors').textContent=errors.join('\n')}
+document.querySelector('#summary').textContent=`DONE: ${passed} passed, ${failed} failed`;
+</script></html>
diff --git a/bun.lock b/bun.lock
index b619bf69..0c5a8892 100644
--- a/bun.lock
+++ b/bun.lock
@@ -99,7 +99,7 @@
},
"apps/desktop": {
"name": "@edgeever/desktop",
- "version": "1.100.0",
+ "version": "1.107.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.5.1",
"@edgeever/public-network": "workspace:*",
@@ -246,6 +246,7 @@
"ai": "7.0.58",
"beautiful-mermaid": "^1.1.3",
"docx-preview": "0.4.1",
+ "fabric": "7.4.0",
"highlight.js": "^11.11.1",
"html-to-image": "^1.11.13",
"lowlight": "^3.3.0",
@@ -361,6 +362,8 @@
"@apideck/better-ajv-errors": ["@apideck/[email protected]", "", { "dependencies": { "jsonpointer": "^5.0.1", "leven": "^3.1.0" }, "peerDependencies": { "ajv": ">=8" } }, "sha512-TajUJwGWbDwkCx/CZi7tRE8PVB7simCvKJfHUsSdvps+aTM/PDPP4gkLmKnc+x3CE//y9i/nj74GqdL/hwk7Iw=="],
+ "@asamuzakjp/css-color": ["@asamuzakjp/[email protected]", "", { "dependencies": { "@csstools/css-calc": "^2.1.3", "@csstools/css-color-parser": "^3.0.9", "@csstools/css-parser-algorithms": "^3.0.4", "@csstools/css-tokenizer": "^3.0.3", "lru-cache": "^10.4.3" } }, "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw=="],
+
"@astrojs/check": ["@astrojs/[email protected]", "", { "dependencies": { "@astrojs/language-server": "^2.8.4", "chokidar": "^3.5.3", "fast-glob": "^3.3.1", "kleur": "^4.1.5", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": "^5.0.0" }, "bin": { "astro-check": "dist/bin.js" } }, "sha512-vliHXM9cu/viGeKiksUM4mXfO816ohWtawTl2ADPgTsd4nUMjFiyAl7xFZhF34yy4hq4qf7jvK1F2PlR3b5I5w=="],
"@astrojs/compiler": ["@astrojs/[email protected]", "", {}, "sha512-f3FN83d2G/v32ipNClRKgYv30onQlMZX1vCeZMjPsMMPl1mDpmbl0+N5BYo4S/ofzqJyS5hvwacEo0CCVDn/Qg=="],
@@ -693,6 +696,16 @@
"@cspotcode/source-map-support": ["@cspotcode/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],
+ "@csstools/color-helpers": ["@csstools/[email protected]", "", {}, "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA=="],
+
+ "@csstools/css-calc": ["@csstools/[email protected]", "", { "peerDependencies": { "@csstools/css-parser-algorithms": "^3.0.5", "@csstools/css-tokenizer": "^3.0.4" } }, "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ=="],
+
+ "@csstools/css-color-parser": ["@csstools/[email protected]", "", { "dependencies": { "@csstools/color-helpers": "^5.1.0", "@csstools/css-calc": "^2.1.4" }, "peerDependencies": { "@csstools/css-parser-algorithms": "^3.0.5", "@csstools/css-tokenizer": "^3.0.4" } }, "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA=="],
+
+ "@csstools/css-parser-algorithms": ["@csstools/[email protected]", "", { "peerDependencies": { "@csstools/css-tokenizer": "^3.0.4" } }, "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ=="],
+
+ "@csstools/css-tokenizer": ["@csstools/[email protected]", "", {}, "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw=="],
+
"@dagrejs/dagre": ["@dagrejs/[email protected]", "", { "dependencies": { "@dagrejs/graphlib": "4.0.5" } }, "sha512-zroZB1dFOFiGgv4Xcrn1DckB1o4aOikPqD2NDQPV0WM//CXGcS6xiD0rNkqHmw6FEg4tabt4nxPLwgCWT+Vb2A=="],
"@dagrejs/graphlib": ["@dagrejs/[email protected]", "", {}, "sha512-7xrBTqIts3o+PMUZX97wSc+7TUbW+/rULzGNCTP6yooNVDXbzw4Wutg/H/xOutTB/c/k0YqOAavgPh4/Zk9PFA=="],
@@ -1891,6 +1904,8 @@
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
+ "bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
+
"blake3-wasm": ["[email protected]", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="],
"bluebird": ["[email protected]", "", {}, "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg=="],
@@ -1915,6 +1930,8 @@
"bser": ["[email protected]", "", { "dependencies": { "node-int64": "^0.4.0" } }, "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ=="],
+ "buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
+
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"buffer-equal-constant-time": ["[email protected]", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
@@ -1951,6 +1968,8 @@
"caniuse-lite": ["[email protected]", "", {}, "sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw=="],
+ "canvas": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.0.0", "prebuild-install": "^7.1.3" } }, "sha512-PzE5nJZPz72YUAfo8oTp0u3fqqY7IzlTubneAihqDYAUcBk7ryeCmBbdJBEdaH0bptSOe2VT2Zwcb3UaFyaSWw=="],
+
"ccount": ["[email protected]", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
"chalk": ["[email protected]", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
@@ -2095,6 +2114,8 @@
"cssom": ["[email protected]", "", {}, "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw=="],
+ "cssstyle": ["[email protected]", "", { "dependencies": { "@asamuzakjp/css-color": "^3.2.0", "rrweb-cssom": "^0.8.0" } }, "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg=="],
+
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"culori": ["[email protected]", "", {}, "sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw=="],
@@ -2183,6 +2204,8 @@
"data-uri-to-buffer": ["[email protected]", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="],
+ "data-urls": ["[email protected]", "", { "dependencies": { "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.0.0" } }, "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg=="],
+
"data-view-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ=="],
"data-view-byte-length": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ=="],
@@ -2197,6 +2220,8 @@
"decamelize": ["[email protected]", "", {}, "sha512-G7Cqgaelq68XHJNGlZ7lrNQyhZGsFqpwtGFexqUv4IQdjKoSYF7ipZ9UuTJZUSQXFj/XaoBLuEVIVqr8EJngEQ=="],
+ "decimal.js": ["[email protected]", "", {}, "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg=="],
+
"decode-named-character-reference": ["[email protected]", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="],
"decode-uri-component": ["[email protected]", "", {}, "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ=="],
@@ -2421,6 +2446,8 @@
"eventsource-parser": ["[email protected]", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
+ "expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
+
"expo": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.20.0", "@expo/cli": "^57.0.20", "@expo/config": "~57.0.9", "@expo/config-plugins": "~57.0.9", "@expo/devtools": "~57.0.1", "@expo/dom-webview": "~57.0.1", "@expo/fingerprint": "^0.20.11", "@expo/local-build-cache-provider": "^57.0.8", "@expo/log-box": "^57.0.4", "@expo/metro": "~56.0.2", "@expo/metro-config": "~57.0.12", "@ungap/structured-clone": "^1.3.0", "babel-preset-expo": "~57.0.9", "expo-asset": "~57.0.15", "expo-constants": "~57.0.16", "expo-file-system": "~57.0.6", "expo-font": "~57.0.2", "expo-keep-awake": "~57.0.1", "expo-modules-autolinking": "~57.0.12", "expo-modules-core": "~57.0.14", "pretty-format": "^29.7.0", "react-refresh": "^0.14.2", "whatwg-url-minimum": "^0.1.2" }, "peerDependencies": { "@expo/metro-runtime": "*", "react": "*", "react-dom": "*", "react-native": "*", "react-native-web": "*", "react-native-webview": "*" }, "optionalPeers": ["@expo/metro-runtime", "react-dom", "react-native-web", "react-native-webview"], "bin": { "expo": "bin/cli", "fingerprint": "bin/fingerprint", "expo-modules-autolinking": "bin/autolinking" } }, "sha512-6nax9hJPhf9dWrstliXUABTJXDNIJrfJKcCtjSxuYVs2Yf127GIhKf3wsEYSFUl+LFdRbPPTNaweJePH159wZA=="],
"expo-asset": ["[email protected]", "", { "dependencies": { "@expo/image-utils": "^0.11.5", "expo-constants": "~57.0.15" }, "peerDependencies": { "expo": "*", "react": "*", "react-native": "*" } }, "sha512-ZoiUftQb1Nn1jvL6l1kZoUXvgRCx57tMQYxSsp+g4ZvY+jgVWp/THruXOtPtZVdC/WWZxPUTct53bfAm2EPDAQ=="],
@@ -2493,6 +2520,8 @@
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
+ "fabric": ["[email protected]", "", { "optionalDependencies": { "canvas": "^3.2.0", "jsdom": "^26.1.0" } }, "sha512-NalYDc3eifTl1C33zryQwpH6+XA/2ClxQrH9vkASkZw3tbkRmorpikhYMmxhUTmi7O3e9ODz0vOT8qfaCh9IVA=="],
+
"fake-indexeddb": ["[email protected]", "", {}, "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w=="],
"fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
@@ -2579,6 +2608,8 @@
"fresh": ["[email protected]", "", {}, "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q=="],
+ "fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
+
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
"fs.realpath": ["[email protected]", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
@@ -2619,6 +2650,8 @@
"getenv": ["[email protected]", "", {}, "sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ=="],
+ "github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
+
"github-slugger": ["[email protected]", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="],
"gl-matrix": ["[email protected]", "", {}, "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ=="],
@@ -2711,6 +2744,8 @@
"hot-patcher": ["[email protected]", "", {}, "sha512-ECg1JFG0YzehicQaogenlcs2qg6WsXQsxtnbr1i696u5tLUjtJdQAh0u2g0Q5YV45f263Ta1GnUJsc8WIfJf4Q=="],
+ "html-encoding-sniffer": ["[email protected]", "", { "dependencies": { "whatwg-encoding": "^3.1.1" } }, "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ=="],
+
"html-escaper": ["[email protected]", "", {}, "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ=="],
"html-parse-stringify": ["[email protected]", "", { "dependencies": { "void-elements": "3.1.0" } }, "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg=="],
@@ -2741,6 +2776,8 @@
"idb": ["[email protected]", "", {}, "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ=="],
+ "ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
+
"ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
"image-size": ["[email protected]", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w=="],
@@ -2847,6 +2884,8 @@
"is-plain-obj": ["[email protected]", "", {}, "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA=="],
+ "is-potential-custom-element-name": ["[email protected]", "", {}, "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ=="],
+
"is-regex": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="],
"is-regexp": ["[email protected]", "", {}, "sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA=="],
@@ -2909,6 +2948,8 @@
"jsc-safe-url": ["[email protected]", "", {}, "sha512-0wM3YBWtYePOjfyXQH5MWQ8H7sdk5EXSwZvmSLKk2RboVQ2Bu239jycHDz5J/8Blf3K0Qnoy2b6xD+z10MFB+Q=="],
+ "jsdom": ["[email protected]", "", { "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", "decimal.js": "^10.5.0", "html-encoding-sniffer": "^4.0.0", "http-proxy-agent": "^7.0.2", "https-proxy-agent": "^7.0.6", "is-potential-custom-element-name": "^1.0.1", "nwsapi": "^2.2.16", "parse5": "^7.2.1", "rrweb-cssom": "^0.8.0", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^5.1.1", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^3.1.1", "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.1.1", "ws": "^8.18.0", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "canvas": "^3.0.0" }, "optionalPeers": ["canvas"] }, "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg=="],
+
"jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
"json-bigint": ["[email protected]", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],
@@ -3265,6 +3306,8 @@
"mkdirp": ["[email protected]", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="],
+ "mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
+
"ml-array-max": ["[email protected]", "", { "dependencies": { "is-any-array": "^3.0.0" } }, "sha512-QQZ4kENwpWmyNb98UXRDFXrmtIXuXtt1+bSbda/2KA85+F+rrJP8hZk6QOkCQXM2Th9mUDYdq/PNByPdT9ID4A=="],
"ml-array-min": ["[email protected]", "", { "dependencies": { "is-any-array": "^3.0.0" } }, "sha512-GRj6Ky6sW9vGL6yIjgsHmXZ9YgrdmcQ8nCxPqEGeKc6dkfYg1XDYxGFxADUjNuZyoCd5PUscWAS4N+cFaX6hFg=="],
@@ -3295,6 +3338,8 @@
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw=="],
+ "napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
+
"natural-compare": ["[email protected]", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
"negotiator": ["[email protected]", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],
@@ -3309,6 +3354,8 @@
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.6.3" } }, "sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA=="],
+ "node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
+
"node-api-version": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q=="],
"node-domexception": ["[email protected]", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
@@ -3341,6 +3388,8 @@
"nullthrows": ["[email protected]", "", {}, "sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw=="],
+ "nwsapi": ["[email protected]", "", {}, "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg=="],
+
"ob1": ["[email protected]", "", { "dependencies": { "flow-enums-runtime": "^0.0.6" } }, "sha512-eJXMpz4aQHXF/YBB9ddqZDIS+ooO91hObo9FoW/xBkr54/zCwYYCDqT/O54vNo8kOkWs5Ou/y28NgdrV0edQNA=="],
"object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
@@ -3485,6 +3534,8 @@
"powershell-utils": ["[email protected]", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="],
+ "prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
+
"prelude-ls": ["[email protected]", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg=="],
@@ -3755,6 +3806,8 @@
"round-polygon": ["[email protected]", "", {}, "sha512-h5rNwOEP6+EHeRuZAGI2/HsNdl6UCKIFvQXzQfv7nTICZ4/sIURe51vOmQJgk/I6KW5LjQ87HJFoASKjaIEySQ=="],
+ "rrweb-cssom": ["[email protected]", "", {}, "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw=="],
+
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
"run-parallel": ["[email protected]", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="],
@@ -3781,6 +3834,8 @@
"sax": ["[email protected]", "", {}, "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA=="],
+ "saxes": ["[email protected]", "", { "dependencies": { "xmlchars": "^2.2.0" } }, "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA=="],
+
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
@@ -3831,6 +3886,10 @@
"signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+ "simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
+
+ "simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
+
"simple-plist": ["[email protected]", "", { "dependencies": { "bplist-creator": "0.1.0", "bplist-parser": "0.3.1", "plist": "^3.0.5" } }, "sha512-iMSw5i0XseMnrhtIzRb7XpQEXepa9xhWxGUojHBL43SIpQuDQkh3Wpy67ZbDzZVr6EKxvwVChnVpdl8hEVLDiw=="],
"simple-swizzle": ["[email protected]", "", { "dependencies": { "is-arrayish": "^0.3.1" } }, "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw=="],
@@ -3941,6 +4000,8 @@
"svgo": ["[email protected]", "", { "dependencies": { "commander": "^11.1.0", "css-select": "^5.1.0", "css-tree": "^3.0.1", "css-what": "^6.1.0", "csso": "^5.0.5", "picocolors": "^1.1.1", "sax": "^1.5.0" }, "bin": "./bin/svgo.js" }, "sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w=="],
+ "symbol-tree": ["[email protected]", "", {}, "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw=="],
+
"tailwind-merge": ["[email protected]", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
"tailwindcss": ["[email protected]", "", {}, "sha512-WtctNNSH8A9jlMIqxzuYumOHU5uGZyRv0Q5svQl+oEPy5w84YpBxdb7MdqyiSPQge5jTJ6zFQLq0PFygdccSBA=="],
@@ -3949,6 +4010,10 @@
"tar": ["[email protected]", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-4LeEWl96twnS2Q7Bz4MGqgazLqO+hJN63GZxXoIqh1T3VweYD997gbU1ItNsQafqqXTXd5WFyFdReLtwvRBNiw=="],
+ "tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw=="],
+
+ "tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
+
"temp": ["[email protected]", "", { "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" } }, "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA=="],
"temp-dir": ["[email protected]", "", {}, "sha512-aoBAniQmmwtcKp/7BzsH8Cxzv8OL736p7v1ihGb5e9DJ9kTwGWHrQrVB5+lfVDzfGrdRzXch+ig7LHaY1JTOrg=="],
@@ -3979,6 +4044,10 @@
"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
+ "tldts": ["[email protected]", "", { "dependencies": { "tldts-core": "^6.1.86" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ=="],
+
+ "tldts-core": ["[email protected]", "", {}, "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA=="],
+
"tmp": ["[email protected]", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="],
"tmp-promise": ["[email protected]", "", { "dependencies": { "tmp": "^0.2.0" } }, "sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ=="],
@@ -3991,7 +4060,9 @@
"toqr": ["[email protected]", "", {}, "sha512-FWAPzCIHZHnrE/5/w9MPk0kK25hSQSH2IKhYh9PyjS3SG/+IEMvlwIHbhz+oF7xl54I+ueZlVnMjyzdSwLmAwA=="],
- "tr46": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA=="],
+ "tough-cookie": ["[email protected]", "", { "dependencies": { "tldts": "^6.1.32" } }, "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A=="],
+
+ "tr46": ["[email protected]", "", { "dependencies": { "punycode": "^2.3.1" } }, "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw=="],
"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
@@ -4007,6 +4078,8 @@
"tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+ "tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
+
"turndown": ["[email protected]", "", { "dependencies": { "@mixmark-io/domino": "^2.2.0" } }, "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ=="],
"tw-animate-css": ["[email protected]", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
@@ -4183,6 +4256,8 @@
"w3c-keyname": ["[email protected]", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],
+ "w3c-xmlserializer": ["[email protected]", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA=="],
+
"walker": ["[email protected]", "", { "dependencies": { "makeerror": "1.0.12" } }, "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ=="],
"warn-once": ["[email protected]", "", {}, "sha512-VkQZJbO8zVImzYFteBXvBOZEl1qL175WH8VmZcxF2fZAoudNhNDvHi+doCaAEdU2l2vtcIwa2zn0QK5+I1HQ3Q=="],
@@ -4201,7 +4276,7 @@
"webdav": ["[email protected]", "", { "dependencies": { "@buttercup/fetch": "^0.2.1", "base-64": "^1.0.0", "byte-length": "^1.0.2", "entities": "^6.0.1", "fast-xml-parser": "^5.7.2", "hot-patcher": "^2.0.1", "layerr": "^3.0.0", "md5": "^2.3.0", "minimatch": "^9.0.9", "nested-property": "^4.0.0", "node-fetch": "^3.3.2", "path-posix": "^1.0.0", "url-join": "^5.0.0", "url-parse": "^1.5.10" } }, "sha512-fVPuRLtcduVGvSO7Tn/6TQCzIvI/g6BO/+xPRctCvi/GytYpjn4czxWbh4HsArsdom9qz9BI63k9/v2HBUui1A=="],
- "webidl-conversions": ["[email protected]", "", {}, "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg=="],
+ "webidl-conversions": ["[email protected]", "", {}, "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g=="],
"whatwg-encoding": ["[email protected]", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="],
@@ -4209,7 +4284,7 @@
"whatwg-mimetype": ["[email protected]", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="],
- "whatwg-url": ["[email protected]", "", { "dependencies": { "lodash.sortby": "^4.7.0", "tr46": "^1.0.1", "webidl-conversions": "^4.0.2" } }, "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg=="],
+ "whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "^5.1.0", "webidl-conversions": "^7.0.0" } }, "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw=="],
"whatwg-url-minimum": ["[email protected]", "", {}, "sha512-XPEm0XFQWNVG292lII1PrRRJl3sItrs7CettZ4ncYxuDVpLyy+NwlGyut2hXI0JswcJUxeCH+CyOJK0ZzAXD6A=="],
@@ -4281,12 +4356,16 @@
"xdg-basedir": ["[email protected]", "", {}, "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ=="],
+ "xml-name-validator": ["[email protected]", "", {}, "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg=="],
+
"xml-naming": ["[email protected]", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="],
"xml2js": ["[email protected]", "", { "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" } }, "sha512-eLTh0kA8uHceqesPqSE+VvO1CDDJWMwlQfB6LuN6T8w6MaDJ8Txm8P7s5cHD0miF0V+GGTZrDQfxPZQVsur33w=="],
"xmlbuilder": ["[email protected]", "", {}, "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg=="],
+ "xmlchars": ["[email protected]", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="],
+
"xxhash-wasm": ["[email protected]", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
"y-protocols": ["[email protected]", "", { "dependencies": { "lib0": "^0.2.85" }, "peerDependencies": { "yjs": "^13.0.0" } }, "sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw=="],
@@ -4329,6 +4408,8 @@
"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
+ "@asamuzakjp/css-color/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
+
"@astrojs/check/chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
"@astrojs/check/kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
@@ -4579,6 +4660,8 @@
"beautiful-mermaid/entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
+ "bl/readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
+
"boxen/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="],
"builder-util/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
@@ -4719,6 +4802,8 @@
"jest-worker/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],
+ "jsdom/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],
+
"katex/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
"linkedom/css-select": ["[email protected]", "", { "dependencies": { "boolbase": "^2.0.0", "css-what": "^8.0.0", "domhandler": "^6.0.1", "domutils": "^4.0.2", "nth-check": "^3.0.1" } }, "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g=="],
@@ -5143,6 +5228,8 @@
"postject/commander": ["[email protected]", "", {}, "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ=="],
+ "prebuild-install/node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-Llh8noNw7s15m+rmIrZnZQbe4gLyasL9loT74rC92PkmwWKeEedKvc7o6pjp8B3MhrYT/Cl846NOYZbz1wmddw=="],
+
"pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
"pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
@@ -5201,6 +5288,10 @@
"svgo/css-tree": ["[email protected]", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],
+ "tar-fs/chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
+
+ "tar-stream/readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
+
"temp/mkdirp": ["[email protected]", "", { "dependencies": { "minimist": "^1.2.6" }, "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw=="],
"tempy/type-fest": ["[email protected]", "", {}, "sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg=="],
@@ -5923,6 +6014,8 @@
"workbox-build/glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="],
+ "workbox-build/source-map/whatwg-url": ["[email protected]", "", { "dependencies": { "lodash.sortby": "^4.7.0", "tr46": "^1.0.1", "webidl-conversions": "^4.0.2" } }, "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg=="],
+
"wrap-ansi/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"@astrojs/check/chokidar/readdirp/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
@@ -6179,6 +6272,10 @@
"workbox-build/glob/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="],
+ "workbox-build/source-map/whatwg-url/tr46": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA=="],
+
+ "workbox-build/source-map/whatwg-url/webidl-conversions": ["[email protected]", "", {}, "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg=="],
+
"@expo/cli/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"@expo/config-plugins/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
diff --git a/crates/desktop-sidecar/src/note_summary.rs b/crates/desktop-sidecar/src/note_summary.rs
index 237a8aa3..1f4c3c59 100644
--- a/crates/desktop-sidecar/src/note_summary.rs
+++ b/crates/desktop-sidecar/src/note_summary.rs
@@ -49,6 +49,7 @@ pub(crate) fn note_list_metadata(markdown: &str) -> Value {
}
}
metadata.insert("infographic".to_owned(), json!(is_infographic(markdown)));
+ metadata.insert("poster".to_owned(), json!(markdown.contains("<!-- edgeever-poster-v1:")));
match table_preview(markdown) {
Some(preview) => {
metadata.insert("structuredTable".to_owned(), json!(true));
diff --git a/docs/poster-notes.md b/docs/poster-notes.md
new file mode 100644
index 00000000..c2a68890
--- /dev/null
+++ b/docs/poster-notes.md
@@ -0,0 +1,29 @@
+# Poster notes
+
+[简体中文](poster-notes.zh-CN.md)
+
+Choose **More types → Poster (Beta)** to create an editable poster. In an ordinary note, choose **Create poster** from the note actions to create a separate poster using the title and selected text (or the first 240 characters of the body). The original note remains intact.
+
+Web and desktop open a dedicated design workspace with 46 real templates adapted from Qiaomu Design's MIT-licensed layout engine, 12 platform presets, bundled licensed Chinese and Latin fonts, headline/subtitle/badge reflow, and actual rendered template previews. The template renderer and its attribution are in `apps/web/src/lib/poster-design`; font licenses ship alongside the font files. Generated raster grain is omitted when adapting vector templates.
+
+The canvas supports text, badges, shapes, paths, freehand drawing and images; multi-selection, grouping, alignment, snapping, zoom and pan; layers, visibility and locking; typography, outlines, shadows, gradients and image fit/crop/flip. Export PNG, JPEG or WebP at 1×–3× (up to 8192 pixels per side), copy a PNG, or insert an exported image into the source note. Edit text directly on the canvas; the template panel has no separate copy form. Applying a template rebuilds its layout from the current canvas copy and retains separately added elements; undo restores the previous layout. Editing individual elements preserves the existing layout.
+
+AI uses the shared assistant sidebar, with no separate AI panel in the poster workspace. The `get_poster` and `update_poster` tools let agents read the canvas and edit text, colors, typography and element positions through the existing agent action flow. Edits preserve unmentioned and locked elements and reject stale revisions. The editor regenerates the preview after an agent edit. This feature does not generate images.
+
+## Source and persistence
+
+`PosterDocument` is validated, versioned source, separate from Fabric.js state. An `edgeever-poster-v1` Markdown comment carries it; readable text and a PNG preview provide a portable fallback. Image elements reference existing workspace attachment IDs; arbitrary URLs and arbitrary Fabric object JSON are not accepted. The rendering engine loads only when entering the poster editor.
+
+Saving uses the existing note revision, content hash and edit session checks. Each artwork version gets an immutable preview up to 480 pixels wide; metadata-only changes reuse it. Historical previews are retained for revision restores. This increases attachment usage with the number of saved artwork versions. Failed source saves remove only the newly uploaded, uncommitted preview.
+
+Drafts are backed up on the current device. A draft based on a different note version must be downloaded and reconciled rather than silently overwriting the current note. Uploading images and saving a new preview require a network connection; offline edits remain local drafts. Inserting into the source note checks its current revision and creates an attachment owned by that note.
+
+## Compatibility and rollout
+
+Android and iOS show the readable preview and text and disable ordinary rich-text editing of poster notes. The API also rejects legacy saves that would strip a poster envelope. This guard requires the updated server. Earlier clients connected to an earlier server do not have that protection. Generic MCP `update_memo` cannot replace poster content.
+
+No database migration or authentication/update configuration is needed. To roll back the UI, remove the create/edit entries while retaining source, attachments and reader protection. Do not convert posters into ordinary notes or delete the source marker.
+
+Verification covers source round trips, format validation, preview save failures, revision conflicts and legacy contentJSON overwrite attempts in SQLite, native reader policy, and local Web creation/edit/save/reopen/export and source-note insertion. Native hardware, installed desktop cross-version flows and paid AI image generation require separate release validation; this feature does not implement image generation.
+
+For the browser rendering regression harness, run `bun run dev` and open `/tests/poster-design.html`. It checks every template on all 12 platform presets, source round trips, multi-selection geometry and AI text contrast.
diff --git a/docs/poster-notes.zh-CN.md b/docs/poster-notes.zh-CN.md
new file mode 100644
index 00000000..4a2fdcaf
--- /dev/null
+++ b/docs/poster-notes.zh-CN.md
@@ -0,0 +1,29 @@
+# 海报笔记
+
+[English](poster-notes.md)
+
+通过「更多类型 → 海报(Beta)」创建可编辑海报。在普通笔记操作菜单选择「制作海报」,会用标题及选中文字(未选中时取正文前 240 字)创建独立海报笔记,原笔记保留。
+
+Web 和桌面端打开独立设计工作台,提供 46 套真实模板、12 种平台画幅、内置的中英文字体、主标题/副标题/标签自动排版及真实渲染的模板预览。版式引擎改编自 MIT 许可的 Qiaomu Design,源码及署名位于 `apps/web/src/lib/poster-design`;字体许可随字体文件提供。转换矢量模板时省略生成的栅格颗粒纹理。
+
+画布支持文字、标签、形状、曲线、手绘和图片;多选、编组、对齐吸附、缩放和平移;图层排序、显示隐藏和锁定;字体排版、描边、阴影、渐变及图片适应/裁切/翻转。可按 1~3 倍输出 PNG、JPEG 或 WebP(每边不超过 8192 像素),复制 PNG 或插入原笔记。直接在画布上编辑文字,模板面板不再提供独立文案表单。应用模板时沿用当前画布文案重新排版,并保留独立添加的元素;撤销可恢复之前的布局。直接编辑元素时保留当前排版。
+
+AI 统一使用通用助手右侧栏,海报工作台不再提供独立 AI 面板。Agent 通过 `get_poster` 和 `update_poster` 读取画布、修改文案、配色、字体排版及元素位置,沿用现有 Agent 操作流程。修改保留未指定和已锁定的元素,版本过期时拒绝覆盖;Agent 修改后由编辑器重新生成预览。本功能不生成图片。
+
+## 源稿与保存
+
+`PosterDocument` 是经过校验、有版本号的源稿,与 Fabric.js 状态分离。源稿保存在 Markdown 的 `edgeever-poster-v1` 注释中,可读文字和 PNG 预览用于通用查看。图片元素引用工作区附件编号,不接受任意 URL 或任意 Fabric 对象 JSON。进入海报编辑器后才加载渲染引擎。
+
+保存沿用笔记版本、内容摘要和编辑会话校验。每个画布版本保存独立的、宽度不超过 480 像素的预览图;仅修改标题等元数据时复用预览。历史预览保留供版本恢复使用,因此附件用量随保存的画布版本增加。源稿保存失败时只清理本次未提交的预览。
+
+草稿在当前设备备份。草稿基于另一版本时,需要先下载并核对,不能静默覆盖当前笔记。添加图片和保存新预览需要联网;离线修改保留为本机草稿。插入原笔记时校验其当前版本,并把成品作为原笔记自己的附件保存。
+
+## 兼容与上线
+
+Android 和 iOS 展示可读预览与文字,并禁止把海报当作普通富文本编辑。API 同样拒绝旧客户端丢失海报源稿的保存请求。该门禁需要更新后的服务器;旧客户端连接旧服务器时没有这个保护。通用 MCP `update_memo` 不能替换海报内容。
+
+不需要数据库迁移,也没有修改认证或升级配置。回滚界面时撤下新建/编辑入口,保留源稿、附件与只读保护;不要把海报转换为普通笔记或删除源稿标记。
+
+验证覆盖源稿往返、格式校验、预览保存失败、SQLite 中的版本冲突与旧 contentJSON 覆盖请求、移动端读取策略,以及本地 Web 新建/编辑/保存/重开/导出与插回原笔记。原生硬件、已安装桌面端跨版本链路与付费 AI 生图仍需单独进行发布验证;本功能不实现生图。
+
+浏览器渲染回归页:运行 `bun run dev` 后打开 `/tests/poster-design.html`,检查每套模板在 12 种平台画幅下的渲染、源稿往返、多选变换及 AI 文字对比度。
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 0c931363..79f102dc 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -3,6 +3,199 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const enUS = {
noteProperties: {"heading": "Note properties", "source": "Show YAML source", "name": "Property name", "type": "Property type", "add": "Add property", "remove": "Remove {{name}}", "invalidName": "Use a unique name that is not a system property.", "invalidYaml": "Properties need attention:", "invalidNumber": "Enter a valid number.", "listHint": "One value per line", "text": "Text", "list": "List", "number": "Number", "checkbox": "Checkbox", "date": "Date"},
+ poster: {
+ design: {
+ downloadSource: "Download original source",
+ copyFailed: "Could not copy the image. Use Export image.",
+ canvasTab: "Canvas",
+ "name": "Poster Design",
+ "templates": "Templates",
+ "assets": "Assets",
+ "ai": "AI Design",
+ "copy": "Copy",
+ "headline": "Headline",
+ "subtitle": "Subtitle",
+ "badge": "Badge / signature",
+ "reflow": "Update copy & reflow",
+ "allTemplates": "All templates",
+ "recommended": "Recommended",
+ "searchTemplates": "Search styles or uses…",
+ "templateCredit": "Layout engine adapted from Qiaomu Design · MIT License",
+ "platform": "Publishing platform",
+ "customSize": "Custom size",
+ "width": "Width",
+ "height": "Height",
+ "gradient": "Gradient",
+ "solid": "Solid",
+ "gradientFrom": "Start color",
+ "gradientTo": "End color",
+ "rotation": "Rotation",
+ "opacity": "Opacity",
+ "position": "Position & size",
+ "typography": "Typography",
+ "italic": "Italic",
+ "underline": "Underline",
+ "lineHeight": "Line height",
+ "tracking": "Letter spacing",
+ "badgeBackground": "Badge background",
+ "fill": "Fill",
+ "radius": "Corner radius",
+ "imageAdjust": "Image adjustment",
+ "fitImage": "Fit image",
+ "coverImage": "Cover canvas",
+ "flipHorizontal": "Flip horizontally",
+ "flipVertical": "Flip vertically",
+ "cropX": "Crop position X (%)",
+ "cropY": "Crop position Y (%)",
+ "outline": "Outline",
+ "strokeWidth": "Weight",
+ "shadow": "Shadow",
+ "enableShadow": "Enable shadow",
+ "blur": "Blur",
+ "shape": "Shapes",
+ "images": "Image assets",
+ "uploadImage": "Upload image",
+ "searchImages": "Search note images…",
+ "imageLibraryHint": "Images selected from other notes are copied into this poster.",
+ "layerCount": "{{count}} layers",
+ "selectionCount": "{{count}} elements selected",
+ "show": "Show layer",
+ "hide": "Hide layer",
+ "group": "Group",
+ "ungroup": "Ungroup",
+ "multiSelectHint": "Shift-click to select several layers; group them to move and scale together.",
+ "selectHint": "Select an element on the canvas or in Layers to adjust it.",
+ "duplicate": "Duplicate elements",
+ "drawing": "Freehand drawing",
+ "copyImage": "Copy image",
+ "copied": "Image copied",
+ "export": "Export image",
+ "exportScale": "Output scale",
+ "exportQuality": "Image quality",
+ "download": "Download image",
+ "select": "Select elements",
+ "pan": "Pan canvas (Space)",
+ "draw": "Draw",
+ "grid": "Grid",
+ "snap": "Snap alignment",
+ "safeArea": "Platform safe area",
+ "canvasHint": "Double-click to edit text · Shift to select · Space to pan",
+ "zoom": "Canvas zoom",
+ "zoomIn": "Zoom in",
+ "zoomOut": "Zoom out",
+ "fit": "Fit window",
+ "aiSelection": "Adjust selection",
+ "aiGenerate": "Generate 3 layouts",
+ "aiSelectionHint": "Adjust only the {{count}} selected elements; preserve the rest of the design.",
+ "aiCanvasHint": "Generate 3 complete layouts from your copy and style, then preview and apply.",
+ "aiPlaceholder": "For example: a black and green reading cover, bold headline and understated subtitle…",
+ "aiPreviewHint": "Uses your configured AI model for copy and layout suggestions. Preview before applying; undo afterward.",
+ "aiPreview": "Choose a layout",
+ "aiStale": "The design changed while previewing. Generate a new proposal.",
+ "align": {
+ "left": "Align left",
+ "center": "Center horizontally",
+ "right": "Align right",
+ "top": "Align top",
+ "middle": "Center vertically",
+ "bottom": "Align bottom"
+ },
+ "textAlign": {
+ "left": "Text left",
+ "center": "Text center",
+ "right": "Text right"
+ },
+ "textStyles": {
+ "heading": "Add headline",
+ "subtitle": "Add subtitle",
+ "body": "Add body text",
+ "badge": "Add badge"
+ },
+ "shapes": {
+ "rect": "Rectangle",
+ "ellipse": "Circle",
+ "pill": "Rounded rectangle",
+ "line": "Line",
+ "arrow": "Arrow",
+ "star": "Star",
+ "sparkle": "Sparkle"
+ }
+},
+ aiInvalid: "The AI layout response could not be used. Adjust the prompt and retry.",
+ accent: "Accent",
+ offline: "Reconnect to save previews or add images. The design draft stays on this device.",
+ "name": "Poster",
+ "title": "Poster title",
+ "defaultHeading": "Your headline",
+ "defaultSubtitle": "Turn ideas into something worth sharing",
+ "createFromNote": "Create poster",
+ "back": "Back to notes",
+ "save": "Save",
+ "saving": "Saving…",
+ "unsaved": "Unsaved",
+ "saved": "Saved locally",
+ "format": "Canvas size",
+ "text": "Text",
+ "rect": "Rectangle",
+ "ellipse": "Ellipse",
+ "image": "Add image",
+ "undo": "Undo",
+ "redo": "Redo",
+ "insertSource": "Insert into source note",
+ "canvas": "Poster canvas",
+ "templates": "Templates",
+ "ai": "AI layout suggestions",
+ "prompt": "Describe a subject, copy or style…",
+ "propose": "Suggest layout",
+ "proposal": "Review layout proposal",
+ "background": "Background color",
+ "properties": "Element properties",
+ "layerName": "Layer name",
+ "fontSize": "Font size",
+ "fontFamily": "Font family",
+ "sans": "Sans serif",
+ "serif": "Serif",
+ "mono": "Monospace",
+ "bold": "Bold",
+ "color": "Element color",
+ "center": "Center horizontally",
+ "lock": "Lock",
+ "unlock": "Unlock",
+ "delete": "Delete element",
+ "layers": "Layers",
+ "front": "Bring to front",
+ "backLayer": "Send to back",
+ "hint": "Move, resize or rotate elements; double-click text to edit. Changes save automatically.",
+ "readOnly": "This poster is read-only. You can export an image.",
+ "replaceTemplate": "Replace template?",
+ "replaceHint": "Keep the headline and subtitle and replace the layout. Other elements will be replaced. You can undo.",
+ "apply": "Apply layout",
+ "error": "Could not complete the action. Retry; your draft stays on this device.",
+ "invalid": "The poster source is invalid or exceeds limits. Keep the source and open it with a compatible version.",
+ "retry": "Retry",
+ "recover": "An unsaved poster draft was found.",
+ "restore": "Restore draft",
+ "downloadDraft": "Download draft",
+ "later": "Later",
+ "staleDraft": "This draft is based on a different note version. Download it and compare both copies first.",
+ "recoveryError": "Local draft backup is unavailable. Save now.",
+ "remoteChanged": "Another device updated this poster. Your draft is preserved; download it and compare versions.",
+ "sourceUnavailable": "The source note was deleted or cannot accept images.",
+ "imageLimit": "Choose a PNG, JPEG or WebP up to 10 MB and 36 megapixels.",
+ "formats": {
+ "portrait": "Portrait 3:4",
+ "square": "Square 1:1",
+ "wechat": "Article cover",
+ "video": "Video cover 16:9",
+ "story": "Story 9:16"
+ },
+ "templatesList": {
+ "editorial": "Editorial",
+ "bold": "Bold headline",
+ "quote": "Quote card",
+ "minimal": "Minimal"
+ }
+},
infographic: {
name: "Infographic", autoLayout: "Auto layout", describe: "Describe and generate", chooseTemplate: "Choose a template and fill content",
prompt: "Describe the information, structure, and key points", generate: "Generate infographic", generating: "Generating…",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 5094bdfa..8d71b213 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -3,6 +3,188 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const ja = {
noteProperties: {"heading": "ノートのプロパティ", "source": "YAML ソースを表示", "name": "プロパティ名", "type": "プロパティの種類", "add": "プロパティを追加", "remove": "{{name}} を削除", "invalidName": "重複しない、システム予約名以外の名前を入力してください。", "invalidYaml": "プロパティを確認してください:", "invalidNumber": "有効な数値を入力してください。", "listHint": "1 行に 1 つの値", "text": "テキスト", "list": "リスト", "number": "数値", "checkbox": "チェックボックス", "date": "日付"},
+ poster: {
+ design: {
+ downloadSource: "元のソースをダウンロード",
+ copyFailed: "画像をコピーできません。画像を書き出してください。",
+ canvasTab: "キャンバス",
+ "name": "Poster Design",
+ "templates": "Templates",
+ "assets": "Assets",
+ "ai": "AI Design",
+ "copy": "Copy",
+ "headline": "Headline",
+ "subtitle": "Subtitle",
+ "badge": "Badge / signature",
+ "reflow": "Update copy & reflow",
+ "allTemplates": "All templates",
+ "recommended": "Recommended",
+ "searchTemplates": "Search styles or uses…",
+ "templateCredit": "Layout engine adapted from Qiaomu Design · MIT License",
+ "platform": "Publishing platform",
+ "customSize": "Custom size",
+ "width": "Width",
+ "height": "Height",
+ "gradient": "Gradient",
+ "solid": "Solid",
+ "gradientFrom": "Start color",
+ "gradientTo": "End color",
+ "rotation": "Rotation",
+ "opacity": "Opacity",
+ "position": "Position & size",
+ "typography": "Typography",
+ "italic": "Italic",
+ "underline": "Underline",
+ "lineHeight": "Line height",
+ "tracking": "Letter spacing",
+ "badgeBackground": "Badge background",
+ "fill": "Fill",
+ "radius": "Corner radius",
+ "imageAdjust": "Image adjustment",
+ "fitImage": "Fit image",
+ "coverImage": "Cover canvas",
+ "flipHorizontal": "Flip horizontally",
+ "flipVertical": "Flip vertically",
+ "cropX": "Crop position X (%)",
+ "cropY": "Crop position Y (%)",
+ "outline": "Outline",
+ "strokeWidth": "Weight",
+ "shadow": "Shadow",
+ "enableShadow": "Enable shadow",
+ "blur": "Blur",
+ "shape": "Shapes",
+ "images": "Image assets",
+ "uploadImage": "Upload image",
+ "searchImages": "Search note images…",
+ "imageLibraryHint": "Images selected from other notes are copied into this poster.",
+ "layerCount": "{{count}} layers",
+ "selectionCount": "{{count}} elements selected",
+ "show": "Show layer",
+ "hide": "Hide layer",
+ "group": "Group",
+ "ungroup": "Ungroup",
+ "multiSelectHint": "Shift-click to select several layers; group them to move and scale together.",
+ "selectHint": "Select an element on the canvas or in Layers to adjust it.",
+ "duplicate": "Duplicate elements",
+ "drawing": "Freehand drawing",
+ "copyImage": "Copy image",
+ "copied": "Image copied",
+ "export": "Export image",
+ "exportScale": "Output scale",
+ "exportQuality": "Image quality",
+ "download": "Download image",
+ "select": "Select elements",
+ "pan": "Pan canvas (Space)",
+ "draw": "Draw",
+ "grid": "Grid",
+ "snap": "Snap alignment",
+ "safeArea": "Platform safe area",
+ "canvasHint": "Double-click to edit text · Shift to select · Space to pan",
+ "zoom": "Canvas zoom",
+ "zoomIn": "Zoom in",
+ "zoomOut": "Zoom out",
+ "fit": "Fit window",
+ "aiSelection": "Adjust selection",
+ "aiGenerate": "Generate 3 layouts",
+ "aiSelectionHint": "Adjust only the {{count}} selected elements; preserve the rest of the design.",
+ "aiCanvasHint": "Generate 3 complete layouts from your copy and style, then preview and apply.",
+ "aiPlaceholder": "For example: a black and green reading cover, bold headline and understated subtitle…",
+ "aiPreviewHint": "Uses your configured AI model for copy and layout suggestions. Preview before applying; undo afterward.",
+ "aiPreview": "Choose a layout",
+ "aiStale": "The design changed while previewing. Generate a new proposal.",
+ "align": {
+ "left": "Align left",
+ "center": "Center horizontally",
+ "right": "Align right",
+ "top": "Align top",
+ "middle": "Center vertically",
+ "bottom": "Align bottom"
+ },
+ "textAlign": {
+ "left": "Text left",
+ "center": "Text center",
+ "right": "Text right"
+ },
+ "textStyles": {
+ "heading": "Add headline",
+ "subtitle": "Add subtitle",
+ "body": "Add body text",
+ "badge": "Add badge"
+ },
+ "shapes": {
+ "rect": "Rectangle",
+ "ellipse": "Circle",
+ "pill": "Rounded rectangle",
+ "line": "Line",
+ "arrow": "Arrow",
+ "star": "Star",
+ "sparkle": "Sparkle"
+ }
+},
+ aiInvalid: "AI のレイアウト案を使用できませんでした。説明を調整して再試行してください。",
+ accent: "装飾線",
+ offline: "プレビューの保存と画像の追加には接続が必要です。下書きはこの端末に保存されます。",
+ "name": "ポスター",
+ "title": "ポスターのタイトル",
+ "defaultHeading": "タイトルを入力",
+ "defaultSubtitle": "アイデアを共有できる作品に",
+ "createFromNote": "ポスターを作成",
+ "back": "ノート一覧へ",
+ "save": "保存",
+ "saving": "保存中…",
+ "unsaved": "未保存",
+ "saved": "この端末に保存済み",
+ "format": "キャンバスサイズ",
+ "text": "テキスト",
+ "rect": "長方形",
+ "ellipse": "楕円",
+ "image": "画像を追加",
+ "undo": "元に戻す",
+ "redo": "やり直す",
+ "insertSource": "元のノートに挿入",
+ "canvas": "ポスターキャンバス",
+ "templates": "テンプレート",
+ "ai": "AI レイアウト提案",
+ "prompt": "テーマ、文章、スタイルを説明…",
+ "propose": "案を生成",
+ "proposal": "レイアウト案を確認",
+ "background": "背景色",
+ "properties": "要素の設定",
+ "layerName": "レイヤー名",
+ "fontSize": "文字サイズ",
+ "fontFamily": "フォント",
+ "sans": "ゴシック体",
+ "serif": "明朝体",
+ "mono": "等幅",
+ "bold": "太字",
+ "color": "要素の色",
+ "center": "左右中央に配置",
+ "lock": "ロック",
+ "unlock": "ロック解除",
+ "delete": "要素を削除",
+ "layers": "レイヤー",
+ "front": "最前面へ",
+ "backLayer": "最背面へ",
+ "hint": "要素を移動、拡大縮小、回転できます。文字はダブルクリックで編集。変更は自動保存されます。",
+ "readOnly": "このポスターは読み取り専用です。画像の書き出しは可能です。",
+ "replaceTemplate": "テンプレートを変更しますか?",
+ "replaceHint": "最初の見出しと説明文を残してレイアウトを置き換えます。他の要素は置き換えられますが、元に戻せます。",
+ "apply": "案を適用",
+ "error": "操作を完了できませんでした。再試行してください。下書きはこの端末に残ります。",
+ "invalid": "ポスターのデータが無効、または制限を超えています。元データを保管し、対応バージョンで開いてください。",
+ "retry": "再試行",
+ "recover": "未保存のポスター下書きがあります。",
+ "restore": "下書きを復元",
+ "downloadDraft": "下書きをダウンロード",
+ "later": "後で",
+ "staleDraft": "下書きの元のノートが更新されています。ダウンロードして両方を確認してください。",
+ "recoveryError": "下書きの端末バックアップが使えません。すぐに保存してください。",
+ "remoteChanged": "別の端末でポスターが更新されました。下書きをダウンロードして確認してください。",
+ "sourceUnavailable": "元のノートが削除されているか、画像を挿入できません。",
+ "imageLimit": "10 MB、3600 万画素以下の PNG、JPEG、WebP を選択してください。",
+ "formats": {"portrait": "縦型 3:4", "square": "正方形 1:1", "wechat": "記事カバー", "video": "動画カバー 16:9", "story": "ストーリー 9:16"},
+ "templatesList": {"editorial": "雑誌風", "bold": "大きな見出し", "quote": "引用カード", "minimal": "ミニマル"}
+},
infographic: {
name: "インフォグラフィック", autoLayout: "自動配置", describe: "説明して生成", chooseTemplate: "テンプレートを選んで入力",
prompt: "表示したい情報、構成、要点を説明してください", generate: "インフォグラフィックを生成", generating: "生成中…",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index dbf8b521..12c38723 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -3,6 +3,188 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const pl = {
noteProperties: {"heading": "Właściwości notatki", "source": "Pokaż źródło YAML", "name": "Nazwa właściwości", "type": "Typ właściwości", "add": "Dodaj właściwość", "remove": "Usuń {{name}}", "invalidName": "Użyj unikalnej nazwy, która nie jest właściwością systemową.", "invalidYaml": "Sprawdź właściwości:", "invalidNumber": "Wprowadź poprawną liczbę.", "listHint": "Jedna wartość w wierszu", "text": "Tekst", "list": "Lista", "number": "Liczba", "checkbox": "Pole wyboru", "date": "Data"},
+ poster: {
+ design: {
+ downloadSource: "Pobierz oryginalne źródło",
+ copyFailed: "Nie udało się skopiować obrazu. Użyj eksportu.",
+ canvasTab: "Płótno",
+ "name": "Poster Design",
+ "templates": "Templates",
+ "assets": "Assets",
+ "ai": "AI Design",
+ "copy": "Copy",
+ "headline": "Headline",
+ "subtitle": "Subtitle",
+ "badge": "Badge / signature",
+ "reflow": "Update copy & reflow",
+ "allTemplates": "All templates",
+ "recommended": "Recommended",
+ "searchTemplates": "Search styles or uses…",
+ "templateCredit": "Layout engine adapted from Qiaomu Design · MIT License",
+ "platform": "Publishing platform",
+ "customSize": "Custom size",
+ "width": "Width",
+ "height": "Height",
+ "gradient": "Gradient",
+ "solid": "Solid",
+ "gradientFrom": "Start color",
+ "gradientTo": "End color",
+ "rotation": "Rotation",
+ "opacity": "Opacity",
+ "position": "Position & size",
+ "typography": "Typography",
+ "italic": "Italic",
+ "underline": "Underline",
+ "lineHeight": "Line height",
+ "tracking": "Letter spacing",
+ "badgeBackground": "Badge background",
+ "fill": "Fill",
+ "radius": "Corner radius",
+ "imageAdjust": "Image adjustment",
+ "fitImage": "Fit image",
+ "coverImage": "Cover canvas",
+ "flipHorizontal": "Flip horizontally",
+ "flipVertical": "Flip vertically",
+ "cropX": "Crop position X (%)",
+ "cropY": "Crop position Y (%)",
+ "outline": "Outline",
+ "strokeWidth": "Weight",
+ "shadow": "Shadow",
+ "enableShadow": "Enable shadow",
+ "blur": "Blur",
+ "shape": "Shapes",
+ "images": "Image assets",
+ "uploadImage": "Upload image",
+ "searchImages": "Search note images…",
+ "imageLibraryHint": "Images selected from other notes are copied into this poster.",
+ "layerCount": "{{count}} layers",
+ "selectionCount": "{{count}} elements selected",
+ "show": "Show layer",
+ "hide": "Hide layer",
+ "group": "Group",
+ "ungroup": "Ungroup",
+ "multiSelectHint": "Shift-click to select several layers; group them to move and scale together.",
+ "selectHint": "Select an element on the canvas or in Layers to adjust it.",
+ "duplicate": "Duplicate elements",
+ "drawing": "Freehand drawing",
+ "copyImage": "Copy image",
+ "copied": "Image copied",
+ "export": "Export image",
+ "exportScale": "Output scale",
+ "exportQuality": "Image quality",
+ "download": "Download image",
+ "select": "Select elements",
+ "pan": "Pan canvas (Space)",
+ "draw": "Draw",
+ "grid": "Grid",
+ "snap": "Snap alignment",
+ "safeArea": "Platform safe area",
+ "canvasHint": "Double-click to edit text · Shift to select · Space to pan",
+ "zoom": "Canvas zoom",
+ "zoomIn": "Zoom in",
+ "zoomOut": "Zoom out",
+ "fit": "Fit window",
+ "aiSelection": "Adjust selection",
+ "aiGenerate": "Generate 3 layouts",
+ "aiSelectionHint": "Adjust only the {{count}} selected elements; preserve the rest of the design.",
+ "aiCanvasHint": "Generate 3 complete layouts from your copy and style, then preview and apply.",
+ "aiPlaceholder": "For example: a black and green reading cover, bold headline and understated subtitle…",
+ "aiPreviewHint": "Uses your configured AI model for copy and layout suggestions. Preview before applying; undo afterward.",
+ "aiPreview": "Choose a layout",
+ "aiStale": "The design changed while previewing. Generate a new proposal.",
+ "align": {
+ "left": "Align left",
+ "center": "Center horizontally",
+ "right": "Align right",
+ "top": "Align top",
+ "middle": "Center vertically",
+ "bottom": "Align bottom"
+ },
+ "textAlign": {
+ "left": "Text left",
+ "center": "Text center",
+ "right": "Text right"
+ },
+ "textStyles": {
+ "heading": "Add headline",
+ "subtitle": "Add subtitle",
+ "body": "Add body text",
+ "badge": "Add badge"
+ },
+ "shapes": {
+ "rect": "Rectangle",
+ "ellipse": "Circle",
+ "pill": "Rounded rectangle",
+ "line": "Line",
+ "arrow": "Arrow",
+ "star": "Star",
+ "sparkle": "Sparkle"
+ }
+},
+ aiInvalid: "Nie można użyć propozycji AI. Zmień opis i spróbuj ponownie.",
+ accent: "Akcent",
+ offline: "Połącz się z siecią, aby zapisać podgląd lub dodać obraz. Szkic pozostaje na tym urządzeniu.",
+ "name": "Plakat",
+ "title": "Tytuł plakatu",
+ "defaultHeading": "Twój nagłówek",
+ "defaultSubtitle": "Zamień pomysły w coś, czym warto się podzielić",
+ "createFromNote": "Utwórz plakat",
+ "back": "Wróć do notatek",
+ "save": "Zapisz",
+ "saving": "Zapisywanie…",
+ "unsaved": "Niezapisane",
+ "saved": "Zapisano lokalnie",
+ "format": "Rozmiar płótna",
+ "text": "Tekst",
+ "rect": "Prostokąt",
+ "ellipse": "Elipsa",
+ "image": "Dodaj obraz",
+ "undo": "Cofnij",
+ "redo": "Ponów",
+ "insertSource": "Wstaw do notatki źródłowej",
+ "canvas": "Płótno plakatu",
+ "templates": "Szablony",
+ "ai": "Propozycje układu AI",
+ "prompt": "Opisz temat, tekst lub styl…",
+ "propose": "Zaproponuj układ",
+ "proposal": "Sprawdź propozycję układu",
+ "background": "Kolor tła",
+ "properties": "Właściwości elementu",
+ "layerName": "Nazwa warstwy",
+ "fontSize": "Rozmiar czcionki",
+ "fontFamily": "Czcionka",
+ "sans": "Bezszeryfowa",
+ "serif": "Szeryfowa",
+ "mono": "Monospace",
+ "bold": "Pogrubienie",
+ "color": "Kolor elementu",
+ "center": "Wyśrodkuj poziomo",
+ "lock": "Zablokuj",
+ "unlock": "Odblokuj",
+ "delete": "Usuń element",
+ "layers": "Warstwy",
+ "front": "Przenieś na wierzch",
+ "backLayer": "Przenieś na spód",
+ "hint": "Przesuwaj, skaluj i obracaj elementy; kliknij tekst dwukrotnie, aby go edytować. Zmiany zapisują się automatycznie.",
+ "readOnly": "Ten plakat jest tylko do odczytu. Możesz wyeksportować obraz.",
+ "replaceTemplate": "Zastąpić szablon?",
+ "replaceHint": "Zachowaj pierwszy nagłówek i opis, zastępując układ. Pozostałe elementy zostaną zastąpione. Możesz cofnąć zmianę.",
+ "apply": "Zastosuj układ",
+ "error": "Nie udało się ukończyć operacji. Spróbuj ponownie; szkic pozostaje na tym urządzeniu.",
+ "invalid": "Źródło plakatu jest nieprawidłowe lub przekracza limity. Zachowaj je i otwórz w zgodnej wersji.",
+ "retry": "Spróbuj ponownie",
+ "recover": "Znaleziono niezapisany szkic plakatu.",
+ "restore": "Przywróć szkic",
+ "downloadDraft": "Pobierz szkic",
+ "later": "Później",
+ "staleDraft": "Szkic opiera się na innej wersji notatki. Pobierz go i porównaj obie kopie.",
+ "recoveryError": "Lokalna kopia szkicu jest niedostępna. Zapisz teraz.",
+ "remoteChanged": "Inne urządzenie zaktualizowało plakat. Pobierz szkic i porównaj wersje.",
+ "sourceUnavailable": "Notatkę źródłową usunięto lub nie można do niej wstawić obrazu.",
+ "imageLimit": "Wybierz PNG, JPEG lub WebP do 10 MB i 36 megapikseli.",
+ "formats": {"portrait": "Pionowy 3:4", "square": "Kwadrat 1:1", "wechat": "Okładka artykułu", "video": "Okładka filmu 16:9", "story": "Relacja 9:16"},
+ "templatesList": {"editorial": "Magazyn", "bold": "Mocny nagłówek", "quote": "Karta cytatu", "minimal": "Minimalistyczny"}
+},
infographic: {
name: "Infografika", autoLayout: "Układ automatyczny", describe: "Opisz i wygeneruj", chooseTemplate: "Wybierz szablon i uzupełnij treść",
prompt: "Opisz informacje, strukturę i kluczowe punkty", generate: "Wygeneruj infografikę", generating: "Generowanie…",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index e62e0602..924ed974 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -3,6 +3,199 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const zhCN = {
noteProperties: {"heading": "笔记属性", "source": "显示 YAML 源码", "name": "属性名称", "type": "属性类型", "add": "添加属性", "remove": "删除 {{name}}", "invalidName": "请输入不重复且非系统保留的属性名称。", "invalidYaml": "请检查笔记属性:", "invalidNumber": "请输入有效数字。", "listHint": "每行一个值", "text": "文本", "list": "列表", "number": "数字", "checkbox": "复选框", "date": "日期"},
+ poster: {
+ design: {
+ downloadSource: "下载原始源稿",
+ copyFailed: "图片复制失败,请使用导出图片。",
+ canvasTab: "画布",
+ "name": "海报设计",
+ "templates": "模板",
+ "assets": "素材",
+ "ai": "AI 设计",
+ "copy": "文案",
+ "headline": "主标题",
+ "subtitle": "副标题",
+ "badge": "标签 / 署名",
+ "reflow": "更新文案并自动排版",
+ "allTemplates": "全部模板",
+ "recommended": "推荐模板",
+ "searchTemplates": "搜索风格或用途…",
+ "templateCredit": "版式引擎改编自 Qiaomu Design · MIT 开源许可",
+ "platform": "发布平台",
+ "customSize": "自定义尺寸",
+ "width": "宽度",
+ "height": "高度",
+ "gradient": "渐变",
+ "solid": "纯色",
+ "gradientFrom": "起始颜色",
+ "gradientTo": "结束颜色",
+ "rotation": "旋转",
+ "opacity": "不透明度",
+ "position": "位置与大小",
+ "typography": "文字排版",
+ "italic": "斜体",
+ "underline": "下划线",
+ "lineHeight": "行距",
+ "tracking": "字距",
+ "badgeBackground": "标签底色",
+ "fill": "填充",
+ "radius": "圆角",
+ "imageAdjust": "图片调整",
+ "fitImage": "完整显示",
+ "coverImage": "铺满画布",
+ "flipHorizontal": "水平翻转",
+ "flipVertical": "垂直翻转",
+ "cropX": "裁切位置 X (%)",
+ "cropY": "裁切位置 Y (%)",
+ "outline": "描边",
+ "strokeWidth": "粗细",
+ "shadow": "阴影",
+ "enableShadow": "启用阴影",
+ "blur": "模糊",
+ "shape": "形状",
+ "images": "图片素材",
+ "uploadImage": "上传图片",
+ "searchImages": "搜索笔记图片…",
+ "imageLibraryHint": "从已有笔记选择图片时,会为当前海报保存独立副本。",
+ "layerCount": "{{count}} 个图层",
+ "selectionCount": "已选择 {{count}} 个元素",
+ "show": "显示图层",
+ "hide": "隐藏图层",
+ "group": "编组",
+ "ungroup": "解散编组",
+ "multiSelectHint": "按 Shift 多选图层;编组后可一起移动、缩放。",
+ "selectHint": "点击画布上的元素,或在图层面板中选择,开始调整。",
+ "duplicate": "复制元素",
+ "drawing": "手绘线条",
+ "copyImage": "复制图片",
+ "copied": "图片已复制",
+ "export": "导出图片",
+ "exportScale": "输出倍率",
+ "exportQuality": "图片质量",
+ "download": "下载图片",
+ "select": "选择元素",
+ "pan": "移动画布(空格)",
+ "draw": "画笔",
+ "grid": "网格",
+ "snap": "对齐吸附",
+ "safeArea": "平台安全区域",
+ "canvasHint": "双击编辑文字 · Shift 多选 · 空格移动画布",
+ "zoom": "画布缩放",
+ "zoomIn": "放大",
+ "zoomOut": "缩小",
+ "fit": "适应窗口",
+ "aiSelection": "调整选中元素",
+ "aiGenerate": "生成 3 个排版方案",
+ "aiSelectionHint": "只修改选中的 {{count}} 个元素,其余设计保持当前状态。",
+ "aiCanvasHint": "根据文案和风格生成 3 个完整方案,预览后再应用。",
+ "aiPlaceholder": "例如:做成黑绿配色的读书分享封面,标题醒目,副标题克制…",
+ "aiPreviewHint": "使用你配置的 AI 模型生成文字与排版建议。应用前可预览,应用后可撤销。",
+ "aiPreview": "选择排版方案",
+ "aiStale": "预览期间设计已改变,请重新生成方案。",
+ "align": {
+ "left": "左对齐",
+ "center": "水平居中",
+ "right": "右对齐",
+ "top": "顶部对齐",
+ "middle": "垂直居中",
+ "bottom": "底部对齐"
+ },
+ "textAlign": {
+ "left": "文字左对齐",
+ "center": "文字居中",
+ "right": "文字右对齐"
+ },
+ "textStyles": {
+ "heading": "添加大标题",
+ "subtitle": "添加副标题",
+ "body": "添加正文",
+ "badge": "添加标签"
+ },
+ "shapes": {
+ "rect": "矩形",
+ "ellipse": "圆形",
+ "pill": "圆角矩形",
+ "line": "直线",
+ "arrow": "箭头",
+ "star": "星形",
+ "sparkle": "闪光"
+ }
+},
+ aiInvalid: "AI 返回的排版方案无法使用,请调整描述后重试。",
+ accent: "装饰线",
+ offline: "请联网后保存预览图或添加图片。当前设计草稿保留在本机。",
+ "name": "海报",
+ "title": "海报标题",
+ "defaultHeading": "写下你的标题",
+ "defaultSubtitle": "把想法变成值得分享的作品",
+ "createFromNote": "制作海报",
+ "back": "返回笔记列表",
+ "save": "保存",
+ "saving": "保存中…",
+ "unsaved": "未保存",
+ "saved": "已保存到本机",
+ "format": "画幅尺寸",
+ "text": "文字",
+ "rect": "矩形",
+ "ellipse": "椭圆",
+ "image": "添加图片",
+ "undo": "撤销",
+ "redo": "重做",
+ "insertSource": "插入原笔记",
+ "canvas": "海报画布",
+ "templates": "选择模板",
+ "ai": "AI 排版建议",
+ "prompt": "描述主题、文案或风格…",
+ "propose": "生成方案",
+ "proposal": "确认排版方案",
+ "background": "背景颜色",
+ "properties": "元素属性",
+ "layerName": "图层名称",
+ "fontSize": "字号",
+ "fontFamily": "字体",
+ "sans": "黑体",
+ "serif": "宋体",
+ "mono": "等宽",
+ "bold": "粗体",
+ "color": "元素颜色",
+ "center": "水平居中",
+ "lock": "锁定",
+ "unlock": "解锁",
+ "delete": "删除元素",
+ "layers": "图层",
+ "front": "移至最前",
+ "backLayer": "移至最后",
+ "hint": "拖动、缩放或旋转元素;双击文字编辑。修改后自动保存。",
+ "readOnly": "当前海报只读,可导出图片。",
+ "replaceTemplate": "更换模板?",
+ "replaceHint": "保留主标题与副标题,重新生成布局。其他元素会被替换,可撤销。",
+ "apply": "应用方案",
+ "error": "操作未完成,请重试。草稿会保留在本机。",
+ "invalid": "海报源稿无法读取或超出限制。请保留源文件,并用支持此格式的版本打开。",
+ "retry": "重试",
+ "recover": "发现未保存的海报草稿。",
+ "restore": "恢复草稿",
+ "downloadDraft": "下载草稿",
+ "later": "稍后处理",
+ "staleDraft": "草稿与当前笔记版本不同。请先下载备份,再核对两份内容。",
+ "recoveryError": "本机草稿备份不可用,请立即保存。",
+ "remoteChanged": "另一端已更新海报。当前草稿仍保留,请先下载草稿并核对版本。",
+ "sourceUnavailable": "原笔记已删除或不支持插入图片。",
+ "imageLimit": "请选择不超过 10 MB、3600 万像素的 PNG、JPEG 或 WebP 图片。",
+ "formats": {
+ "portrait": "小红书 3:4",
+ "square": "方形 1:1",
+ "wechat": "公众号头图",
+ "video": "视频封面 16:9",
+ "story": "竖版 9:16"
+ },
+ "templatesList": {
+ "editorial": "编辑杂志",
+ "bold": "醒目大字",
+ "quote": "观点卡片",
+ "minimal": "简约留白"
+ }
+},
infographic: {
name: "信息图", autoLayout: "自动排版", describe: "描述内容并生成", chooseTemplate: "选择模板手动填内容",
prompt: "描述你想呈现的信息、结构与重点", generate: "生成信息图", generating: "正在生成…",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index bce25992..6b85aa75 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -61,3 +61,5 @@ export {
export { attachDiagramScroll } from "./diagram-scroll";
export * from "./front-matter";
+
+export * from "./poster";
diff --git a/packages/shared/src/poster.test.mjs b/packages/shared/src/poster.test.mjs
new file mode 100644
index 00000000..4f014ab8
--- /dev/null
+++ b/packages/shared/src/poster.test.mjs
@@ -0,0 +1,50 @@
+import { describe, test, expect } from "bun:test";
+import { Base64 } from "js-base64";
+import { createPosterDocument, parsePosterDocument, serializePosterDocument, posterFallbackMarkdown, resizePosterDocument, PosterDocumentSchema } from "./poster";
+
+describe("poster source compatibility", () => {
+ test("round-trips editable elements, resources, source links and a portable preview", () => {
+ const document = { ...createPosterDocument("知识卡片", "Read & share"), previewResourceId: "res_preview", sourceMemoId: "memo_source" };
+ document.elements.push({ id: "image", name: "photo", type: "image", resourceId: "res_image", x: 10, y: 20, width: 50, height: 80, opacity: .5, locked: true, rotation: 30 });
+ const markdown = serializePosterDocument(document);
+ expect(parsePosterDocument(markdown)).toEqual(document);
+ expect(posterFallbackMarkdown(document)).toContain("/api/v1/resources/res_preview/blob");
+ expect(posterFallbackMarkdown(document)).toContain("/api/v1/resources/res_image/blob");
+ expect(posterFallbackMarkdown(document)).not.toContain("edgeever-poster-v1");
+ });
+ test("rejects corrupt, unsupported and unsafe sources without executing arbitrary Fabric JSON", () => {
+ for (const value of [null, { ...createPosterDocument(), schemaVersion: 2 }, { ...createPosterDocument(), width: Infinity }, { ...createPosterDocument(), elements: [{ type: "image", src: "https://example.com/tracker" }] }]) {
+ const encoded = Base64.encodeURI(JSON.stringify(value));
+ expect(parsePosterDocument(`<!-- edgeever-poster-v1:${encoded} -->`)).toBeNull();
+ }
+ expect(parsePosterDocument("ordinary note")).toBeNull();
+ expect(PosterDocumentSchema.safeParse({ ...createPosterDocument(), elements: [createPosterDocument().elements[0], createPosterDocument().elements[0]] }).success).toBe(false);
+ });
+ test("resizing preserves IDs, source and locked elements with proportional geometry", () => {
+ const document = createPosterDocument("Hello");
+ const next = resizePosterDocument(document, 1080, 1080);
+ expect(next.elements.map((element) => element.id)).toEqual(document.elements.map((element) => element.id));
+ expect(next.elements[0].y).toBeCloseTo(document.elements[0].y * .75);
+ expect(document.height).toBe(1440);
+ });
+ test("legacy Markdown shows text without allowing injected markup", () => {
+ const fallback = posterFallbackMarkdown(createPosterDocument('<script>alert(1)</script>', '![x](https://example.com)'));
+ expect(fallback).not.toContain('<script>');
+ expect(fallback).toContain('\\!\\[x\\]');
+ });
+});
+
+describe("editable design styles", () => {
+ test("preserves real template curves, gradients, typography, badges, grouping and crop", () => {
+ const document = { ...createPosterDocument("设计源稿", "Round trip"), templateId: "folio", platformId: "xhs", backgroundGradient: { kind: "linear", from: "#f4efe4", to: "#baf264", angle: 120 } };
+ document.elements[1] = { ...document.elements[1], role: "title", sourceText: "设计源稿", fontFamily: "思源黑体 Heavy", fontStyle: "italic", underline: true, lineHeight: 1.08, charSpacing: -20, shadow: { color: "rgba(0,0,0,0.2)", blur: 20, offsetX: 4, offsetY: 6 }, groupId: "group_1" };
+ document.elements.push({ id: "curve", name: "Curve", type: "path", path: "M 0 100 Q 100 0 200 100 Z", x: 40, y: 80, width: 200, height: 100, rotation: 15, opacity: .8, locked: false, fill: "#16a06e", stroke: "#07130b", strokeWidth: 12, gradient: { kind: "radial", from: "#ffffff", to: "#16a06e", angle: 90, stops: [{ offset: 0, color: "#ffffff" }, { offset: 1, color: "rgba(22,160,110,0.5)" }], coords: { x1: .5, y1: .5, x2: .5, y2: .5, r1: 0, r2: 1 } } });
+ document.elements.push({ id: "image_crop", name: "Photo", type: "image", resourceId: "resource_photo", x: 0, y: 0, width: 1080, height: 1440, rotation: 0, opacity: 1, flipX: true, crop: { x: .2, y: 0, width: .6, height: 1 } });
+ expect(parsePosterDocument(serializePosterDocument(document))).toEqual(document);
+ });
+ test("rejects executable SVG source, CSS injection, invalid gradients and huge geometry", () => {
+ const base = createPosterDocument();
+ const shape = { ...base.elements[0], type: "path", path: "M 0 0 L 50 50", fill: "#16a06e" };
+ for (const patch of [{ path: '<svg onload="alert(1)">' }, { fill: "url(https://example.com/track)" }, { width: 100000 }, { gradient: { kind: "linear", from: "#ffffff", to: "#07130b", angle: 90, stops: [{ offset: 0, color: "url(foo)" }, { offset: 1, color: "#07130b" }] } }]) expect(PosterDocumentSchema.safeParse({ ...base, elements: [{ ...shape, ...patch }] }).success).toBe(false);
+ });
+});
diff --git a/packages/shared/src/poster.ts b/packages/shared/src/poster.ts
new file mode 100644
index 00000000..44e20069
--- /dev/null
+++ b/packages/shared/src/poster.ts
@@ -0,0 +1,313 @@
+import { Base64 } from "js-base64";
+import { z } from "zod";
+
+const MARKER = "edgeever-poster-v1";
+const COLOR = z.string().regex(/^#[0-9a-f]{6}$/i);
+export const PosterGradientSchema = z.object({
+ kind: z.enum(["linear", "radial"]),
+ from: COLOR,
+ to: COLOR,
+ angle: z.number().finite().min(-360).max(360).default(90),
+});
+export type PosterGradient = z.infer<typeof PosterGradientSchema>;
+const strokeColor = z
+ .string()
+ .max(80)
+ .regex(/^(?:#[0-9a-f]{3,8}|rgba?\([\d.,\s]+\)|transparent)$/i);
+const shadow = z.object({
+ color: strokeColor,
+ blur: z.number().min(0).max(300),
+ offsetX: z.number().min(-300).max(300),
+ offsetY: z.number().min(-300).max(300),
+});
+
+const ID = z
+ .string()
+ .min(1)
+ .max(160)
+ .regex(/^[\w-]+$/);
+const gradientStops = z
+ .array(
+ z.object({
+ offset: z.number().min(0).max(1),
+ color: strokeColor,
+ opacity: z.number().min(0).max(1).optional(),
+ }),
+ )
+ .min(2)
+ .max(16);
+export const PosterPaintGradientSchema = z.object({
+ kind: z.enum(["linear", "radial"]),
+ from: COLOR,
+ to: COLOR,
+ angle: z.number().finite().default(90),
+ stops: gradientStops.optional(),
+ coords: z
+ .object({
+ x1: z.number().finite(),
+ y1: z.number().finite(),
+ x2: z.number().finite(),
+ y2: z.number().finite(),
+ r1: z.number().finite().optional(),
+ r2: z.number().finite().optional(),
+ })
+ .optional(),
+});
+export type PosterPaintGradient = z.infer<typeof PosterPaintGradientSchema>;
+const geometry = {
+ id: ID,
+ name: z.string().max(120),
+ role: z.enum(["title", "subtitle", "badge", "decor"]).optional(),
+ visible: z.boolean().optional(),
+ flipX: z.boolean().optional(),
+ flipY: z.boolean().optional(),
+ stroke: strokeColor.optional(),
+ strokeWidth: z.number().min(0).max(1024).optional(),
+ shadow: shadow.optional(),
+ gradient: PosterPaintGradientSchema.optional(),
+ groupId: ID.optional(),
+ x: z.number().finite().min(-8192).max(8192),
+ y: z.number().finite().min(-8192).max(8192),
+ width: z.number().finite().min(1).max(8192),
+ height: z.number().finite().min(1).max(8192),
+ rotation: z.number().finite().min(-360).max(360).default(0),
+ opacity: z.number().min(0).max(1).default(1),
+ locked: z.boolean().optional(),
+};
+const text = z.object({
+ ...geometry,
+ type: z.literal("text"),
+ text: z.string().max(8000),
+ fill: strokeColor,
+ fontSize: z.number().min(4).max(8192),
+ fontFamily: z
+ .string()
+ .min(1)
+ .max(100)
+ .regex(/^[\w\s\-\u3400-\u9fff]+$/),
+ fontStyle: z.enum(["normal", "italic"]).optional(),
+ underline: z.boolean().optional(),
+ lineHeight: z.number().min(0.5).max(3).optional(),
+ charSpacing: z.number().min(-300).max(1000).optional(),
+ sourceText: z.string().max(8000).optional(),
+ badge: z
+ .object({
+ background: COLOR,
+ padX: z.number().min(0).max(3),
+ padY: z.number().min(0).max(3),
+ radius: z.number().min(0).max(1),
+ })
+ .optional(),
+ fontWeight: z.enum(["normal", "bold"]),
+ textAlign: z.enum(["left", "center", "right"]),
+});
+const shape = z.object({
+ ...geometry,
+ type: z.enum(["rect", "ellipse"]),
+ fill: strokeColor,
+ radius: z.number().min(0).max(4096).optional(),
+});
+const image = z.object({
+ ...geometry,
+ type: z.literal("image"),
+ resourceId: ID,
+ crop: z
+ .object({
+ x: z.number().min(0).max(1),
+ y: z.number().min(0).max(1),
+ width: z.number().min(0.01).max(1),
+ height: z.number().min(0.01).max(1),
+ })
+ .optional(),
+});
+const path = z.object({
+ ...geometry,
+ type: z.literal("path"),
+ fill: strokeColor,
+ path: z
+ .string()
+ .min(1)
+ .max(100_000)
+ .regex(/^[MmLlHhVvCcSsQqTtAaZz\d\s,.eE+\-]+$/),
+});
+export const PosterElementSchema = z.union([text, shape, image, path]);
+export const PosterDocumentSchema = z
+ .object({
+ schemaVersion: z.literal(1),
+ width: z.number().int().min(320).max(4096),
+ height: z.number().int().min(320).max(4096),
+ background: COLOR,
+ backgroundGradient: PosterGradientSchema.optional(),
+ elements: z.array(PosterElementSchema).max(500),
+ copy: z
+ .object({
+ title: z.string().max(8000),
+ subtitle: z.string().max(8000),
+ badge: z.string().max(8000),
+ })
+ .optional(),
+ templateId: z.string().max(80).optional(),
+ platformId: z.string().max(80).optional(),
+ sourceMemoId: ID.optional(),
+ previewResourceId: ID.optional(),
+ })
+ .superRefine((document, ctx) => {
+ if (
+ new Set(document.elements.map((element) => element.id)).size !==
+ document.elements.length
+ ) {
+ ctx.addIssue({ code: "custom", message: "Element IDs must be unique" });
+ }
+ });
+export type PosterDocument = z.infer<typeof PosterDocumentSchema>;
+export type PosterElement = z.infer<typeof PosterElementSchema>;
+export type PosterText = Extract<PosterElement, { type: "text" }>;
+export const POSTER_FORMATS = [
+ { id: "portrait", width: 1080, height: 1440 },
+ { id: "square", width: 1080, height: 1080 },
+ { id: "wechat", width: 1410, height: 600 },
+ { id: "video", width: 1280, height: 720 },
+ { id: "story", width: 1080, height: 1920 },
+] as const;
+export const POSTER_TEMPLATES = [
+ "editorial",
+ "bold",
+ "quote",
+ "minimal",
+] as const;
+export type PosterTemplate = (typeof POSTER_TEMPLATES)[number];
+export const createPosterDocument = (
+ heading = "",
+ subtitle = "",
+ template: PosterTemplate = "editorial",
+ width = 1080,
+ height = 1440,
+): PosterDocument => {
+ const dark = template === "bold";
+ const padding = width * 0.09;
+ const fontSize = Math.round(Math.min(width * 0.085, height * 0.13));
+ const headingY = template === "quote" ? height * 0.3 : height * 0.24;
+ const makeText = (
+ id: string,
+ content: string,
+ y: number,
+ size: number,
+ ): PosterText => ({
+ id,
+ name: id,
+ type: "text",
+ text: content,
+ x: padding,
+ y,
+ width: width - padding * 2,
+ height: size * 1.5,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ fill: dark ? "#ffffff" : "#07130b",
+ fontSize: size,
+ fontFamily:
+ template === "editorial" || template === "quote" ? "serif" : "sans-serif",
+ fontWeight: id === "heading" ? "bold" : "normal",
+ textAlign: template === "minimal" ? "center" : "left",
+ });
+ return {
+ schemaVersion: 1,
+ width,
+ height,
+ background: dark
+ ? "#07130b"
+ : template === "editorial"
+ ? "#f4efe4"
+ : "#ffffff",
+ elements: [
+ {
+ id: "accent",
+ name: "accent",
+ type: "rect",
+ x: padding,
+ y: height * 0.12,
+ width: width * 0.12,
+ height: Math.max(8, height * 0.008),
+ fill: dark ? "#baf264" : "#16a06e",
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ },
+ makeText("heading", heading, headingY, fontSize),
+ makeText("subtitle", subtitle, height * 0.7, Math.round(fontSize * 0.4)),
+ ],
+ };
+};
+export const resizePosterDocument = (
+ document: PosterDocument,
+ width: number,
+ height: number,
+): PosterDocument => {
+ const sx = width / document.width,
+ sy = height / document.height;
+ return PosterDocumentSchema.parse({
+ ...document,
+ width,
+ height,
+ elements: document.elements.map((element) => ({
+ ...element,
+ x: element.x * sx,
+ y: element.y * sy,
+ width: element.width * sx,
+ height: element.height * sy,
+ ...(element.type === "text"
+ ? {
+ fontSize: Math.max(
+ 8,
+ Math.min(512, element.fontSize * Math.min(sx, sy)),
+ ),
+ }
+ : {}),
+ })),
+ });
+};
+export const hasPosterDocumentMarker = (markdown: string | null | undefined) =>
+ Boolean(markdown?.includes(`<!-- ${MARKER}:`));
+export const stripPosterDocumentMarker = (markdown: string) =>
+ markdown.replace(/<!--\s*edgeever-poster-v1:[\s\S]*?-->/g, "").trim();
+export const parsePosterDocument = (
+ markdown: string | null | undefined,
+): PosterDocument | null => {
+ const encoded = markdown?.match(
+ /<!--\s*edgeever-poster-v1:([A-Za-z0-9_-]+)\s*-->/,
+ )?.[1];
+ if (!encoded || encoded.length > 2_000_000) return null;
+ try {
+ return PosterDocumentSchema.parse(JSON.parse(Base64.decode(encoded)));
+ } catch {
+ return null;
+ }
+};
+const resourceUrl = (id: string) =>
+ `/api/v1/resources/${encodeURIComponent(id)}/blob`;
+export const posterFallbackMarkdown = (document: PosterDocument) =>
+ [
+ document.previewResourceId
+ ? `![Poster](${resourceUrl(document.previewResourceId)})`
+ : "",
+ ...document.elements
+ .filter((element): element is PosterText => element.type === "text")
+ .map((element) => element.text.replace(/([\\`*_{}\[\]<>#!])/g, "\\$1")),
+ document.sourceMemoId ? `[Source](#memo=${document.sourceMemoId})` : "",
+ ...document.elements
+ .filter((element) => element.type === "image")
+ .map(
+ (element) =>
+ `[Image](${resourceUrl((element as Extract<PosterElement, { type: "image" }>).resourceId)})`,
+ ),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+export const serializePosterDocument = (document: PosterDocument) => {
+ const safe = PosterDocumentSchema.parse(document);
+ return `${posterFallbackMarkdown(safe)}\n\n<!-- ${MARKER}:${Base64.encodeURI(JSON.stringify(safe))} -->`.trim();
+};
+export const getPosterSummary = (markdown: string | null | undefined) => ({
+ poster: hasPosterDocumentMarker(markdown),
+});
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 3a39cb5d..c71c8034 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -3,7 +3,7 @@ import type { AiAction, AiPromptParameterKind, AiPromptResultMode } from "./ai-a
import type { DiagramKind, DiagramSummaryPreview } from "./diagram";
import type { TableSummaryPreview } from "./table";
-export type NoteCreateKind = DiagramKind | "infographic" | "table";
+export type NoteCreateKind = DiagramKind | "infographic" | "table" | "poster";
export type Notebook = {
id: string;
@@ -29,6 +29,7 @@ export type MemoSummary = {
structuredTable?: boolean;
tablePreview?: TableSummaryPreview;
infographic?: boolean;
+ poster?: boolean;
videoNote?: boolean;
tags: string[];
isPinned: boolean;