CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.
TypeScript ai-agentsai-diagramai-presentationbomcadcanvasdiagramdiagram-generatordrawioflowchartinfographicspptppt-generatorpresentation-generatorreactsvgedittext-to-diagramtypescriptworkflow
refactor(ppt): lift the material-token logic out, with tests
codingFeng10118233463b57c
diff --git a/client/workspaces/ppt/canvas/PptCanvas.tsx b/client/workspaces/ppt/canvas/PptCanvas.tsxindex eb511ca..b0b2243 100644--- a/client/workspaces/ppt/canvas/PptCanvas.tsx+++ b/client/workspaces/ppt/canvas/PptCanvas.tsx@@ -6,6 +6,12 @@ import { runInParallel, sleep } from "./lib/concurrency";import { parseJsonLoose } from "./lib/parse-json";import { extractPdfPagesAsImages, isPdfFile } from "./lib/deck-source";import { getSlideshowDimensions } from "./lib/slideshow-size";+import {+ buildSlideMaterialsFromAutoLabels,+ materialLabel,+ materialToken,+ removeMaterialToken,+} from "./lib/material-tokens";import {creationReducer,initialCreationState,@@ -2247,9 +2253,6 @@ export function PptCanvas({setReferencePreviewOpen(true);};- const getMaterialLabel = (index: number) => {- return uiLang === "zh" ? `第${index}张` : `Image ${index}`;- };const buildReferenceVisualAssetsWithCaptions = async (): Promise<ReferenceVisualAsset[]> => {@@ -2307,118 +2310,7 @@ export function PptCanvas({}));};- const ensureDescriptionHasMaterialTokens = (description: string, materials: Array<{ name: string; caption?: string }>) => {- const source = String(description || "");- const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- const placementsZh = [- "放在左侧主视觉区域,约占画面宽度 40%",- "放在右上区域,作为辅助图示",- "放在底部横向区域,作为补充对比",- ];- const placementsEn = [- "place it in the left primary visual area, about 40% width",- "place it in the upper-right area as a supporting visual",- "place it in the bottom horizontal area as supplementary comparison",- ];-- let working = source;- const lines: string[] = [];- for (let i = 0; i < materials.length; i += 1) {- const m = materials[i];- const token = `{{image:${m.name}}}`;- const tokenEscaped = escapeRegExp(token);- const placement = uiLang === "zh"- ? placementsZh[Math.min(i, placementsZh.length - 1)]- : placementsEn[Math.min(i, placementsEn.length - 1)];- const captionPart = String(m.caption || "").trim();- const sentence = uiLang === "zh"- ? `${token}${placement}${captionPart ? `,内容重点为:${captionPart}` : ""}。`- : `${token} ${placement}${captionPart ? `, focus: ${captionPart}` : ""}.`;-- const wrongLangPlacementRe = uiLang === "zh"- ? new RegExp(`${tokenEscaped}[^\\n]*\\bplace\\b[^\\n]*`, "gi")- : new RegExp(`${tokenEscaped}[^\\n]*放在[^\\n]*`, "g");- if (wrongLangPlacementRe.test(working)) {- working = working.replace(wrongLangPlacementRe, "");- }-- const hasToken = working.includes(token);- const hasPlacement = uiLang === "zh"- ? new RegExp(`${tokenEscaped}[^\\n]*放在`).test(working)- : new RegExp(`${tokenEscaped}[^\\n]*\\bplace\\b`, "i").test(working);- if (!hasToken || !hasPlacement) lines.push(sentence);- }-- working = working- .replace(/[ \t]+\n/g, "\n")- .replace(/\n{3,}/g, "\n\n")- .trim();- if (lines.length === 0) return working || source;- const trimmed = working.trim();- if (!trimmed) return lines.join("\n");- return `${trimmed}\n${lines.join("\n")}`;- };-- const buildSlideMaterialsFromAutoLabels = (- pages: PptPage[],- slides: SlideData[],- assets: ReferenceVisualAsset[]- ) => {- const assetMap = new Map<string, ReferenceVisualAsset>();- for (const a of assets) assetMap.set(a.label, a);-- const pageLabels: string[][] = slides.map((_, idx) => {- const labels = Array.isArray(pages[idx]?.materialLabels)- ? pages[idx]!.materialLabels!.map((x) => String(x || "").trim()).filter(Boolean)- : [];- return labels.slice(0, 3);- });- const explicitLabelCount = pageLabels.reduce((sum, arr) => sum + arr.length, 0);-- // Fallback: if AI returned no labels at all but assets exist, attach a few assets- // to representative slides so users can review and adjust instead of seeing empty materials.- if (explicitLabelCount === 0 && assets.length > 0 && slides.length > 0) {- const fallbackCount = Math.min(assets.length, Math.max(1, Math.min(6, Math.ceil(slides.length / 2))));- const step = Math.max(1, Math.floor(slides.length / fallbackCount));- for (let n = 0; n < fallbackCount; n += 1) {- const slideIndex = Math.min(slides.length - 1, n * step);- const label = assets[n]?.label;- if (!label) continue;- if (!pageLabels[slideIndex]) pageLabels[slideIndex] = [];- if (!pageLabels[slideIndex].includes(label)) pageLabels[slideIndex].push(label);- }- }-- const nextMaterials: Record<string, SlideMaterialImage[]> = {};- const nextSlides = slides.map((slide, idx) => {- const labels = (pageLabels[idx] || []).slice(0, 3);- const matched = labels- .map((lb) => assetMap.get(lb))- .filter((x): x is ReferenceVisualAsset => !!x)- .slice(0, 3);- if (matched.length === 0) return slide;-- const materialItems: SlideMaterialImage[] = matched.map((asset, mIdx) => ({- id: `auto-mat-${slide.id}-${asset.label}-${mIdx + 1}`,- name: getMaterialLabel(mIdx + 1),- fileName: asset.sourceFileName,- dataUrl: asset.dataUrl,- refLabel: asset.label,- caption: asset.caption,- sourceFileName: asset.sourceFileName,- sourcePage: asset.sourcePage,- }));- nextMaterials[slide.id] = materialItems;-- const withTokens = ensureDescriptionHasMaterialTokens(- String(slide.description || ""),- materialItems.map((m) => ({ name: m.name, caption: m.caption }))- );- return { ...slide, description: withTokens };- });- return { nextSlides, nextMaterials };- };const addSlideMaterialImages = async (slideId: string, files: File[]) => {const imageFiles = files.filter((f) => f.type.startsWith("image/"));@@ -2438,7 +2330,7 @@ export function PptCanvas({try {const dataUrl = await toDataUrl(file);if (!dataUrl.startsWith("data:image")) continue;- const label = getMaterialLabel(currentCount + i + 1);+ const label = materialLabel(currentCount + i + 1, uiLang as "zh" | "en");created.push({id: `mat-${Date.now()}-${Math.random().toString(16).slice(2)}`,name: label,@@ -2464,17 +2356,12 @@ export function PptCanvas({}));if (!removed) return;- const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- const tokenRe = new RegExp(`\\{\\{image:${escapeRegExp(removed.name)}\\}\\}`, "g");setLocalSlides((prev) =>- prev.map((s) => {- if (s.id !== slideId) return s;- const nextDesc = String(s.description || "")- .replace(tokenRe, "")- .replace(/[ \t]{2,}/g, " ")- .replace(/ *\n */g, "\n");- return { ...s, description: nextDesc };- })+ prev.map((s) =>+ s.id === slideId+ ? { ...s, description: removeMaterialToken(s.description || "", removed.name) }+ : s,+ ),);const editor = descriptionEditorRefs.current[slideId];@@ -2497,7 +2384,7 @@ export function PptCanvas({.filter((x) => !!x.url);const insertMaterialTokenToSlideDescription = (slideIndex: number, slideId: string, materialName: string) => {- const token = `{{image:${materialName}}}`;+ const token = materialToken(materialName);const editor = descriptionEditorRefs.current[slideId];if (editor) {const sel = window.getSelection();@@ -2544,7 +2431,7 @@ export function PptCanvas({}const tokenName = el.getAttribute("data-material-token");if (tokenName) {- parts.push(`{{image:${tokenName}}}`);+ parts.push(materialToken(tokenName));continue;}parts.push(el.textContent || "");@@ -2707,7 +2594,7 @@ export function PptCanvas({}const name = el.getAttribute("data-material-token");if (name) {- out.push(`{{image:${name}}}`);+ out.push(materialToken(name));continue;}out.push(el.textContent || "");@@ -3096,7 +2983,7 @@ export function PptCanvas({note: p.note || "",layout: localizeLayoutHint(p.layout || "", uiLang as "zh" | "en"),}));- const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets);+ const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets, uiLang as "zh" | "en");setSlideMaterials(autoMaterial.nextMaterials);setLocalSlides(autoMaterial.nextSlides);dispatchCreation({ type: "outlined" });@@ -3139,7 +3026,7 @@ export function PptCanvas({note: p.note,layout: localizeLayoutHint(p.layout || "", uiLang as "zh" | "en")}));- const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets);+ const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets, uiLang as "zh" | "en");setSlideMaterials(autoMaterial.nextMaterials);setLocalSlides(autoMaterial.nextSlides);dispatchCreation({ type: "outlined" });diff --git a/client/workspaces/ppt/canvas/lib/material-tokens.ts b/client/workspaces/ppt/canvas/lib/material-tokens.tsnew file mode 100644index 0000000..9de378a--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/material-tokens.ts@@ -0,0 +1,179 @@+import type { PptPage } from "@/workspaces/ppt/lib/ppt-service";+import type {+ ReferenceVisualAsset,+ SlideData,+ SlideMaterialImage,+} from "@/workspaces/ppt/canvas/types";++/**+ * Reference images are attached to a slide and referred to from its+ * description by a `{{image:Name}}` token. The token is what tells the image+ * model which picture goes where, so losing one silently drops the user's+ * material from the rendered slide.+ */++export type MaterialLang = "zh" | "en";++const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++/** The display name a material gets from its position in the slide's list. */+export function materialLabel(index: number, lang: MaterialLang): string {+ return lang === "zh" ? `第${index}张` : `Image ${index}`;+}++export function materialToken(name: string): string {+ return `{{image:${name}}}`;+}++/**+ * Drops every reference to a material from a description, and tidies the+ * whitespace the removal leaves behind.+ */+export function removeMaterialToken(description: string, name: string): string {+ const pattern = new RegExp(escapeRegExp(materialToken(name)), "g");+ return String(description || "")+ .replace(pattern, "")+ .replace(/[ \t]{2,}/g, " ")+ .replace(/ *\n */g, "\n");+}++const PLACEMENTS: Record<MaterialLang, string[]> = {+ zh: [+ "放在左侧主视觉区域,约占画面宽度 40%",+ "放在右上区域,作为辅助图示",+ "放在底部横向区域,作为补充对比",+ ],+ en: [+ "place it in the left primary visual area, about 40% width",+ "place it in the upper-right area as a supporting visual",+ "place it in the bottom horizontal area as supplementary comparison",+ ],+};++/**+ * Makes sure every attached material is both mentioned and placed in the+ * description, appending a sentence for any that is not.+ *+ * A token carried over from the other language keeps its placement wording in+ * that language, which the image model then follows inconsistently; those are+ * stripped so the sentence below replaces them.+ */+export function ensureDescriptionHasMaterialTokens(+ description: string,+ materials: Array<{ name: string; caption?: string }>,+ lang: MaterialLang,+): string {+ const source = String(description || "");+ const placements = PLACEMENTS[lang];+ let working = source;+ const added: string[] = [];++ materials.forEach((material, i) => {+ const token = materialToken(material.name);+ const escaped = escapeRegExp(token);+ const placement = placements[Math.min(i, placements.length - 1)];+ const caption = String(material.caption || "").trim();+ const sentence =+ lang === "zh"+ ? `${token}${placement}${caption ? `,内容重点为:${caption}` : ""}。`+ : `${token} ${placement}${caption ? `, focus: ${caption}` : ""}.`;++ const wrongLanguage =+ lang === "zh"+ ? new RegExp(`${escaped}[^\\n]*\\bplace\\b[^\\n]*`, "gi")+ : new RegExp(`${escaped}[^\\n]*放在[^\\n]*`, "g");+ if (wrongLanguage.test(working)) working = working.replace(wrongLanguage, "");++ const hasToken = working.includes(token);+ const hasPlacement =+ lang === "zh"+ ? new RegExp(`${escaped}[^\\n]*放在`).test(working)+ : new RegExp(`${escaped}[^\\n]*\\bplace\\b`, "i").test(working);+ if (!hasToken || !hasPlacement) added.push(sentence);+ });++ working = working+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();++ if (added.length === 0) return working || source;+ return working ? `${working}\n${added.join("\n")}` : added.join("\n");+}++/** At most this many reference images ride along with one slide. */+const MAX_MATERIALS_PER_SLIDE = 3;++/**+ * Attaches the reference images the model asked for, by label, to the slides+ * that asked for them.+ *+ * When the model returns no labels at all, a few assets are spread across the+ * deck instead: the user can then see and adjust real attachments rather than+ * an empty materials list that looks like the upload failed.+ */+export function buildSlideMaterialsFromAutoLabels(+ pages: PptPage[],+ slides: SlideData[],+ assets: ReferenceVisualAsset[],+ lang: MaterialLang,+): { nextSlides: SlideData[]; nextMaterials: Record<string, SlideMaterialImage[]> } {+ const byLabel = new Map(assets.map((a) => [a.label, a]));++ const pageLabels: string[][] = slides.map((_, idx) => {+ const labels = pages[idx]?.materialLabels;+ if (!Array.isArray(labels)) return [];+ return labels+ .map((x) => String(x || "").trim())+ .filter(Boolean)+ .slice(0, MAX_MATERIALS_PER_SLIDE);+ });++ const explicitCount = pageLabels.reduce((sum, arr) => sum + arr.length, 0);+ if (explicitCount === 0 && assets.length > 0 && slides.length > 0) {+ const fallbackCount = Math.min(+ assets.length,+ Math.max(1, Math.min(6, Math.ceil(slides.length / 2))),+ );+ const step = Math.max(1, Math.floor(slides.length / fallbackCount));+ for (let n = 0; n < fallbackCount; n += 1) {+ const slideIndex = Math.min(slides.length - 1, n * step);+ const label = assets[n]?.label;+ if (!label) continue;+ if (!pageLabels[slideIndex].includes(label)) pageLabels[slideIndex].push(label);+ }+ }++ const nextMaterials: Record<string, SlideMaterialImage[]> = {};+ const nextSlides = slides.map((slide, idx) => {+ const matched = pageLabels[idx]+ .slice(0, MAX_MATERIALS_PER_SLIDE)+ .map((label) => byLabel.get(label))+ .filter((a): a is ReferenceVisualAsset => !!a)+ .slice(0, MAX_MATERIALS_PER_SLIDE);+ if (matched.length === 0) return slide;++ const items: SlideMaterialImage[] = matched.map((asset, n) => ({+ id: `auto-mat-${slide.id}-${asset.label}-${n + 1}`,+ name: materialLabel(n + 1, lang),+ fileName: asset.sourceFileName,+ dataUrl: asset.dataUrl,+ refLabel: asset.label,+ caption: asset.caption,+ sourceFileName: asset.sourceFileName,+ sourcePage: asset.sourcePage,+ }));+ nextMaterials[slide.id] = items;++ return {+ ...slide,+ description: ensureDescriptionHasMaterialTokens(+ String(slide.description || ""),+ items.map((m) => ({ name: m.name, caption: m.caption })),+ lang,+ ),+ };+ });++ return { nextSlides, nextMaterials };+}diff --git a/tests/ppt-material-tokens.test.ts b/tests/ppt-material-tokens.test.tsnew file mode 100644index 0000000..2c6ffee--- /dev/null+++ b/tests/ppt-material-tokens.test.ts@@ -0,0 +1,199 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import {+ buildSlideMaterialsFromAutoLabels,+ ensureDescriptionHasMaterialTokens,+ materialLabel,+ materialToken,+ removeMaterialToken,+} from "../client/workspaces/ppt/canvas/lib/material-tokens";+import type { PptPage } from "../client/workspaces/ppt/lib/ppt-service";+import type {+ ReferenceVisualAsset,+ SlideData,+} from "../client/workspaces/ppt/canvas/types";++/**+ * Reference images reach the image model only through the `{{image:Name}}`+ * token in a slide's description. A token that goes missing, or one that+ * survives after its image was deleted, both end up as a wrong slide.+ */++test("labels and tokens follow the UI language", () => {+ assert.equal(materialLabel(2, "zh"), "第2张");+ assert.equal(materialLabel(2, "en"), "Image 2");+ assert.equal(materialToken("第1张"), "{{image:第1张}}");+});++test("removing a material takes its token with it", () => {+ const before = "标题页。{{image:第1张}}放在左侧。";+ const after = removeMaterialToken(before, "第1张");+ assert.ok(!after.includes("{{image:"), after);+ assert.ok(after.includes("标题页。"), "the rest of the description survives");+});++test("removal takes every occurrence and tidies the gap", () => {+ const after = removeMaterialToken("a {{image:Image 1}} b {{image:Image 1}} c", "Image 1");+ assert.ok(!after.includes("{{image:"));+ assert.ok(!/ {2,}/.test(after), `double spaces left behind: ${JSON.stringify(after)}`);+});++test("removal leaves other materials alone", () => {+ const after = removeMaterialToken("{{image:Image 1}} and {{image:Image 2}}", "Image 1");+ assert.ok(after.includes("{{image:Image 2}}"));+ assert.ok(!after.includes("{{image:Image 1}}"));+});++test("a name with regex characters is removed literally", () => {+ // Material names come from user filenames, so they can contain anything.+ const after = removeMaterialToken("x {{image:a.b(c)}} y", "a.b(c)");+ assert.ok(!after.includes("{{image:"), after);+});++test("a material with no mention gets a placement sentence", () => {+ const out = ensureDescriptionHasMaterialTokens("封面页。", [{ name: "第1张" }], "zh");+ assert.ok(out.startsWith("封面页。"), "the original text is kept");+ assert.ok(out.includes("{{image:第1张}}"), out);+ assert.ok(out.includes("放在左侧主视觉区域"), out);+});++test("a caption is folded into the placement sentence", () => {+ const out = ensureDescriptionHasMaterialTokens(+ "",+ [{ name: "Image 1", caption: "quarterly revenue" }],+ "en",+ );+ assert.match(out, /focus: quarterly revenue/);+});++test("a material already placed is left as it is", () => {+ const already = "{{image:第1张}}放在右上角,不要改。";+ assert.equal(ensureDescriptionHasMaterialTokens(already, [{ name: "第1张" }], "zh"), already);+});++test("a token mentioned but never placed still gets its sentence", () => {+ const out = ensureDescriptionHasMaterialTokens("see {{image:Image 1}}", [{ name: "Image 1" }], "en");+ assert.match(out, /place it in the left primary visual area/);+});++test("a placement left over from the other language is replaced", () => {+ // Switching UI language mid-deck used to leave both wordings in the prompt.+ const out = ensureDescriptionHasMaterialTokens(+ "{{image:第1张}} place it in the left primary visual area",+ [{ name: "第1张" }],+ "zh",+ );+ assert.ok(!/place it in the left/i.test(out), out);+ assert.ok(out.includes("放在左侧主视觉区域"), out);+});++test("each of the first three materials gets its own placement", () => {+ const out = ensureDescriptionHasMaterialTokens(+ "",+ [{ name: "Image 1" }, { name: "Image 2" }, { name: "Image 3" }],+ "en",+ );+ assert.match(out, /left primary visual area/);+ assert.match(out, /upper-right area/);+ assert.match(out, /bottom horizontal area/);+});++const asset = (label: string, page = 1): ReferenceVisualAsset =>+ ({+ label,+ dataUrl: `data:image/png;base64,${label}`,+ caption: `${label} caption`,+ sourceFileName: "deck.pdf",+ sourcePage: page,+ }) as ReferenceVisualAsset;++const slide = (n: number): SlideData => ({+ id: `slide-${n}`,+ title: `Slide ${n}`,+ content: [],+ description: "",+});++test("labelled assets attach to the slides that asked for them", () => {+ const slides = [slide(1), slide(2)];+ const pages = [+ { id: "slide-1", materialLabels: ["FIG-1"] },+ { id: "slide-2", materialLabels: ["FIG-2"] },+ ] as unknown as PptPage[];++ const { nextSlides, nextMaterials } = buildSlideMaterialsFromAutoLabels(+ pages,+ slides,+ [asset("FIG-1"), asset("FIG-2")],+ "en",+ );++ assert.equal(nextMaterials["slide-1"][0].refLabel, "FIG-1");+ assert.equal(nextMaterials["slide-2"][0].refLabel, "FIG-2");+ assert.match(nextSlides[0].description!, /\{\{image:Image 1\}\}/);+});++test("a label nothing matches leaves the slide untouched", () => {+ const slides = [slide(1)];+ const pages = [{ id: "slide-1", materialLabels: ["MISSING"] }] as unknown as PptPage[];+ const { nextSlides, nextMaterials } = buildSlideMaterialsFromAutoLabels(+ pages,+ slides,+ [asset("FIG-1")],+ "en",+ );+ assert.equal(nextMaterials["slide-1"], undefined);+ assert.equal(nextSlides[0], slides[0], "the same object comes back");+});++test("no labels at all spreads a few assets rather than showing none", () => {+ // Without this the user uploads a PDF, gets an empty materials list, and+ // reasonably concludes the upload failed.+ const slides = [slide(1), slide(2), slide(3), slide(4)];+ const pages = [{}, {}, {}, {}] as unknown as PptPage[];+ const { nextMaterials } = buildSlideMaterialsFromAutoLabels(+ pages,+ slides,+ [asset("A"), asset("B")],+ "en",+ );+ const touched = Object.keys(nextMaterials);+ assert.equal(touched.length, 2, `expected two slides to get one each, got ${touched}`);+});++test("the fallback does nothing when there is nothing to spread", () => {+ const { nextMaterials } = buildSlideMaterialsFromAutoLabels(+ [{}] as unknown as PptPage[],+ [slide(1)],+ [],+ "en",+ );+ assert.deepEqual(nextMaterials, {});+});++test("a slide takes at most three materials", () => {+ const pages = [+ { id: "slide-1", materialLabels: ["A", "B", "C", "D", "E"] },+ ] as unknown as PptPage[];+ const { nextMaterials } = buildSlideMaterialsFromAutoLabels(+ pages,+ [slide(1)],+ ["A", "B", "C", "D", "E"].map((l) => asset(l)),+ "en",+ );+ assert.equal(nextMaterials["slide-1"].length, 3);+});++test("attached materials are numbered from one on each slide", () => {+ const pages = [{ id: "slide-1", materialLabels: ["A", "B"] }] as unknown as PptPage[];+ const { nextMaterials } = buildSlideMaterialsFromAutoLabels(+ pages,+ [slide(1)],+ [asset("A"), asset("B")],+ "zh",+ );+ assert.deepEqual(+ nextMaterials["slide-1"].map((m) => m.name),+ ["第1张", "第2张"],+ );+});