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 PptCanvas's pure helpers into tested modules
codingFeng101b6c2e3818d97
diff --git a/client/workspaces/ppt/canvas/PptCanvas.tsx b/client/workspaces/ppt/canvas/PptCanvas.tsxindex 60ca131..c24e772 100644--- a/client/workspaces/ppt/canvas/PptCanvas.tsx+++ b/client/workspaces/ppt/canvas/PptCanvas.tsx@@ -1,6 +1,12 @@import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';import { motion } from "motion/react";import { useLatestRef } from "@/shared/lib/use-latest-ref";+import { errorText, isRetryableBeautifyError } from "./lib/errors";+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 { buildBeautifyInstruction } from "./lib/beautify-instruction";import { generateImage, generateChatMessage } from '@/ai/client';import {pptService,@@ -775,20 +781,6 @@ export function PptCanvas({return () => observer.disconnect();}, [currentSlideIndex, imageVersions, currentImageVersionId, generatedImages, creationStep]);- const getSlideshowDimensions = () => {- if (!windowDimensions.width) return { width: '90vw', height: '50.625vw' }; // Fallback- const maxWidth = windowDimensions.width * 0.9;- const maxHeight = windowDimensions.height * 0.85;-- let w = maxWidth;- let h = w * 9 / 16;-- if (h > maxHeight) {- h = maxHeight;- w = h * 16 / 9;- }- return { width: w, height: h };- };const setTemplateFromItem = useCallback(async (item: TemplateItem) => {setSelectedTemplateId(item.id);@@ -2520,31 +2512,6 @@ export function PptCanvas({return uiLang === "zh" ? `第${index}张` : `Image ${index}`;};- const parseJsonLoose = (text: string) => {- const raw = String(text || "").trim();- if (!raw) return null;- try {- return JSON.parse(raw);- } catch {- }- const jsonBlock = raw.match(/```json\s*([\s\S]*?)\s*```/i);- if (jsonBlock?.[1]) {- try {- return JSON.parse(String(jsonBlock[1]).trim());- } catch {- }- }- const firstBracket = raw.indexOf("[");- const lastBracket = raw.lastIndexOf("]");- if (firstBracket >= 0 && lastBracket > firstBracket) {- const candidate = raw.slice(firstBracket, lastBracket + 1);- try {- return JSON.parse(candidate);- } catch {- }- }- return null;- };const buildReferenceVisualAssetsWithCaptions = async (): Promise<ReferenceVisualAsset[]> => {const raw = (referenceVisualAssetsRaw || []).filter((x: any) => x && typeof x.dataUrl === "string" && x.dataUrl.startsWith("data:image"));@@ -3018,69 +2985,22 @@ export function PptCanvas({setCurrentSlideIndex(0);};- const runInParallel = async (tasks: (() => Promise<void>)[], limit: number) => {- const results: Promise<void>[] = [];- const executing: Promise<void>[] = [];- for (const task of tasks) {- const p = Promise.resolve().then(() => task());- results.push(p);- let e: Promise<void>;- e = p- .catch(() => {- })- .then(() => {- executing.splice(executing.indexOf(e), 1);- });- executing.push(e);- if (executing.length >= limit) {- await Promise.race(executing);- }- }- await Promise.all(results);- };- const isBeautifyPdfFile = (file: File) => {- const name = String(file?.name || "").toLowerCase();- return file?.type === "application/pdf" || name.endsWith(".pdf");- };- const isImageTransformSourceFile = (file: File) => {- const name = String(file?.name || "").toLowerCase();- return file?.type === "application/pdf" || name.endsWith(".pdf");- };- const extractPdfPagesAsImages = async (file: File) => {- const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/shared/files");- const objectUrl = URL.createObjectURL(file);- try {- const pdf = await getPdfDocumentFromUrl(objectUrl);- const pageCount = (pdf as any)?.numPages ?? 0;- const out: string[] = [];- for (let pageNumber = 1; pageNumber <= pageCount; pageNumber += 1) {- setProgress({- current: pageNumber - 1,- total: pageCount,- message: tr(`正在解析 PDF... (${pageNumber - 1}/${pageCount})`, `Parsing PDF... (${pageNumber - 1}/${pageCount})`),- });- const canvas = document.createElement("canvas");- await renderPdfPageToCanvas({ pdf, pageNumber, canvas, targetWidth: 1280 });- const dataUrl = canvas.toDataURL("image/png");- if (dataUrl && dataUrl.startsWith("data:image")) out.push(dataUrl);- }- setProgress({- current: pageCount,- total: pageCount,- message: tr(`正在解析 PDF... (${pageCount}/${pageCount})`, `Parsing PDF... (${pageCount}/${pageCount})`),- });- return out;- } finally {- URL.revokeObjectURL(objectUrl);- }- };++ // extractPdfPagesAsImages counts pages; the wording stays here with tr.+ const reportPdfParseProgress = useCallback((done: number, total: number) => {+ setProgress({+ current: done,+ total,+ message: tr(`正在解析 PDF... (${done}/${total})`, `Parsing PDF... (${done}/${total})`),+ });+ }, [tr]);const extractImageDeckPages = async (file: File) => {- if (isBeautifyPdfFile(file)) {- return await extractPdfPagesAsImages(file);+ if (isPdfFile(file)) {+ return await extractPdfPagesAsImages(file, reportPdfParseProgress);}throw new Error(tr("仅支持 PDF 文件。", "Only PDF files are supported."));};@@ -3218,38 +3138,12 @@ export function PptCanvas({}};- const buildBeautifyInstruction = (req: string) => {- const r = String(req || "").trim();- const parts = [- "Beautify the slide while preserving all original text, numbers, and meaning.",- "Improve typography, spacing, alignment, color harmony, hierarchy, and visual balance.",- "Do not add watermarks. Keep 16:9 landscape.",- "Do not translate or rewrite text unless explicitly requested.",- r ? `User requirements: ${r}` : "",- ].filter(Boolean);- return parts.join("\n");- };-- const getErrorMessage = (error: unknown) => {- if (error instanceof Error && error.message) return error.message;- if (typeof error === "string" && error.trim()) return error.trim();- return tr("未知错误", "Unknown error");- };- const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+ const getErrorMessage = useCallback(+ (error: unknown) => errorText(error) || tr("未知错误", "Unknown error"),+ [tr],+ );- const isRetryableBeautifyError = (error: unknown) => {- const msg = getErrorMessage(error).toLowerCase();- return (- msg.includes("429") ||- msg.includes("524") ||- msg.includes("timeout") ||- msg.includes("timed out") ||- msg.includes("networkerror") ||- msg.includes("fetch") ||- msg.includes("rate limit")- );- };const editPageImageWithRetry = async (page: PptPage,@@ -3287,8 +3181,8 @@ export function PptCanvas({setProgress({ current: 0, total: 0, message: tr("正在解析文件...", "Parsing file...") });try {- const pageImages = isBeautifyPdfFile(file)- ? await extractPdfPagesAsImages(file)+ const pageImages = isPdfFile(file)+ ? await extractPdfPagesAsImages(file, reportPdfParseProgress): [];if (pageImages.length === 0) {@@ -4316,7 +4210,7 @@ export function PptCanvas({<ButtononClick={creationMode === "beautify" ? handleStartBeautify : creationMode === "image_transform" ? handleStartImageTransform : creationMode === "idea" ? handleGenerateOutline : handleLoadOutline}- disabled={Boolean(progress.message) || (creationMode === "beautify" ? !beautifyFile : creationMode === "image_transform" ? !imageTransformFile || !isImageTransformSourceFile(imageTransformFile) : isParsingReferenceFiles || (creationMode === "idea" ? !ideaInput.trim() : !outlineInput.trim()))}+ disabled={Boolean(progress.message) || (creationMode === "beautify" ? !beautifyFile : creationMode === "image_transform" ? !imageTransformFile || !isPdfFile(imageTransformFile) : isParsingReferenceFiles || (creationMode === "idea" ? !ideaInput.trim() : !outlineInput.trim()))}className="w-full py-6 text-lg font-medium bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white shadow-lg shadow-blue-500/20 rounded-xl transition-all hover:scale-[1.01] active:scale-[0.99]">{progress.message ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : <Sparkles className="w-5 h-5 mr-2" />}@@ -5172,7 +5066,7 @@ export function PptCanvas({<div className="flex-1 flex items-center justify-center p-8 overflow-hidden bg-black/90">{activeSlides[slideshowIndex] ? ((() => {- const slideDims = getSlideshowDimensions();+ const slideDims = getSlideshowDimensions(windowDimensions);const slideWidth = typeof slideDims.width === "number" ? slideDims.width : 1100;const slideHeight = typeof slideDims.height === "number" ? slideDims.height : 619;return (diff --git a/client/workspaces/ppt/canvas/lib/beautify-instruction.ts b/client/workspaces/ppt/canvas/lib/beautify-instruction.tsnew file mode 100644index 0000000..304e644--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/beautify-instruction.ts@@ -0,0 +1,14 @@+const BASE_INSTRUCTION = [+ "Beautify the slide while preserving all original text, numbers, and meaning.",+ "Improve typography, spacing, alignment, color harmony, hierarchy, and visual balance.",+ "Do not add watermarks. Keep 16:9 landscape.",+ "Do not translate or rewrite text unless explicitly requested.",+];++/** The image-edit prompt for one slide, with the user's own wording appended. */+export function buildBeautifyInstruction(requirement: string): string {+ const extra = String(requirement || "").trim();+ return [...BASE_INSTRUCTION, extra ? `User requirements: ${extra}` : ""]+ .filter(Boolean)+ .join("\n");+}diff --git a/client/workspaces/ppt/canvas/lib/concurrency.ts b/client/workspaces/ppt/canvas/lib/concurrency.tsnew file mode 100644index 0000000..1a21320--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/concurrency.ts@@ -0,0 +1,40 @@+/** Waits `ms` before resolving. */+export function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => {+ setTimeout(resolve, ms);+ });+}++/**+ * Runs `tasks` with at most `limit` in flight.+ *+ * Every task is awaited before this returns, even once one has failed: the+ * callers here are generating a deck slide by slide, and bailing out early+ * would leave the remaining slides writing state into a flow that has already+ * given up. The first failure is re-thrown once the rest have settled.+ */+export async function runInParallel(+ tasks: (() => Promise<void>)[],+ limit: number,+): Promise<void> {+ const results: Promise<void>[] = [];+ const executing: Promise<void>[] = [];++ for (const task of tasks) {+ const started = Promise.resolve().then(() => task());+ results.push(started);++ const slot: Promise<void> = started+ .catch(() => {})+ .then(() => {+ executing.splice(executing.indexOf(slot), 1);+ });+ executing.push(slot);++ if (executing.length >= limit) await Promise.race(executing);+ }++ const settled = await Promise.allSettled(results);+ const failed = settled.find((r) => r.status === "rejected");+ if (failed) throw (failed as PromiseRejectedResult).reason;+}diff --git a/client/workspaces/ppt/canvas/lib/deck-source.ts b/client/workspaces/ppt/canvas/lib/deck-source.tsnew file mode 100644index 0000000..6fdd44c--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/deck-source.ts@@ -0,0 +1,42 @@+/**+ * Turning an uploaded file into the page images the beautify and+ * image-transform flows work on.+ */++/** Both source flows accept PDFs only; the name check covers browsers that send an empty type. */+export function isPdfFile(file: File): boolean {+ return file?.type === "application/pdf" || String(file?.name || "").toLowerCase().endsWith(".pdf");+}++/**+ * Renders every page of a PDF to a PNG data URL.+ *+ * `onProgress` is called with pages completed and the total, including a+ * final call at completion, so the caller owns the wording of the message.+ */+export async function extractPdfPagesAsImages(+ file: File,+ onProgress?: (done: number, total: number) => void,+): Promise<string[]> {+ const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/shared/files");+ const objectUrl = URL.createObjectURL(file);++ try {+ const pdf = await getPdfDocumentFromUrl(objectUrl);+ const pageCount: number = (pdf as { numPages?: number })?.numPages ?? 0;+ const pages: string[] = [];++ for (let pageNumber = 1; pageNumber <= pageCount; pageNumber += 1) {+ onProgress?.(pageNumber - 1, pageCount);+ const canvas = document.createElement("canvas");+ await renderPdfPageToCanvas({ pdf, pageNumber, canvas, targetWidth: 1280 });+ const dataUrl = canvas.toDataURL("image/png");+ if (dataUrl.startsWith("data:image")) pages.push(dataUrl);+ }++ onProgress?.(pageCount, pageCount);+ return pages;+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+}diff --git a/client/workspaces/ppt/canvas/lib/errors.ts b/client/workspaces/ppt/canvas/lib/errors.tsnew file mode 100644index 0000000..accf04e--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/errors.ts@@ -0,0 +1,33 @@+/**+ * Error text and retry classification for the slide-generation flows.+ *+ * Kept free of the translator so it stays testable: callers supply their own+ * wording for the "no message at all" case.+ */++/** The human-readable part of a thrown value, or "" if there is none. */+export function errorText(error: unknown): string {+ if (error instanceof Error && error.message) return error.message;+ if (typeof error === "string" && error.trim()) return error.trim();+ return "";+}++const RETRYABLE = [+ "429",+ "524",+ "timeout",+ "timed out",+ "networkerror",+ "fetch",+ "rate limit",+];++/**+ * Whether a failed page edit is worth sending again. Beautify runs a whole+ * deck through the image model, so transient rate limits and gateway+ * timeouts are the common case and a permanent refusal is not.+ */+export function isRetryableBeautifyError(error: unknown): boolean {+ const message = errorText(error).toLowerCase();+ return RETRYABLE.some((needle) => message.includes(needle));+}diff --git a/client/workspaces/ppt/canvas/lib/parse-json.ts b/client/workspaces/ppt/canvas/lib/parse-json.tsnew file mode 100644index 0000000..ecf2f25--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/parse-json.ts@@ -0,0 +1,38 @@+/**+ * Parses JSON out of a model reply.+ *+ * Models wrap their answer in prose or a ```json fence often enough that a+ * bare JSON.parse loses usable output, so this falls back to the fence and+ * then to the outermost bracket pair before giving up.+ */+export function parseJsonLoose(text: string): unknown {+ const raw = String(text || "").trim();+ if (!raw) return null;++ try {+ return JSON.parse(raw);+ } catch {+ // Not bare JSON; try the wrapped forms below.+ }++ const fenced = raw.match(/```json\s*([\s\S]*?)\s*```/i);+ if (fenced?.[1]) {+ try {+ return JSON.parse(fenced[1].trim());+ } catch {+ // Fence content was not valid either.+ }+ }++ const open = raw.indexOf("[");+ const close = raw.lastIndexOf("]");+ if (open >= 0 && close > open) {+ try {+ return JSON.parse(raw.slice(open, close + 1));+ } catch {+ // Fall through to null.+ }+ }++ return null;+}diff --git a/client/workspaces/ppt/canvas/lib/slideshow-size.ts b/client/workspaces/ppt/canvas/lib/slideshow-size.tsnew file mode 100644index 0000000..6b170fe--- /dev/null+++ b/client/workspaces/ppt/canvas/lib/slideshow-size.ts@@ -0,0 +1,18 @@+/** The largest 16:9 box that fits the window with room to spare around it. */+export function getSlideshowDimensions(+ window: { width: number; height: number },+): { width: number | string; height: number | string } {+ // Before the first measurement, fall back to viewport units.+ if (!window.width) return { width: "90vw", height: "50.625vw" };++ const maxWidth = window.width * 0.9;+ const maxHeight = window.height * 0.85;++ let width = maxWidth;+ let height = (width * 9) / 16;+ if (height > maxHeight) {+ height = maxHeight;+ width = (height * 16) / 9;+ }+ return { width, height };+}diff --git a/tests/ppt-canvas-lib.test.ts b/tests/ppt-canvas-lib.test.tsnew file mode 100644index 0000000..7d0e2ac--- /dev/null+++ b/tests/ppt-canvas-lib.test.ts@@ -0,0 +1,119 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { errorText, isRetryableBeautifyError } from "../client/workspaces/ppt/canvas/lib/errors";+import { runInParallel, sleep } from "../client/workspaces/ppt/canvas/lib/concurrency";+import { parseJsonLoose } from "../client/workspaces/ppt/canvas/lib/parse-json";+import { buildBeautifyInstruction } from "../client/workspaces/ppt/canvas/lib/beautify-instruction";+import { getSlideshowDimensions } from "../client/workspaces/ppt/canvas/lib/slideshow-size";++/**+ * The pure helpers behind slide generation, lifted out of PptCanvas. Each one+ * decides something the user sees: whether a failed slide is retried, whether+ * a model reply is usable, how many slides render at once.+ */++test("errorText prefers a real message and reports absence as empty", () => {+ assert.equal(errorText(new Error("boom")), "boom");+ assert.equal(errorText(" spaced "), "spaced");+ assert.equal(errorText(new Error("")), "", "the caller supplies its own wording");+ assert.equal(errorText(null), "");+ assert.equal(errorText({ message: "not an Error" }), "");+});++test("transient failures are retried and refusals are not", () => {+ assert.equal(isRetryableBeautifyError(new Error("429 Too Many Requests")), true);+ assert.equal(isRetryableBeautifyError(new Error("524 origin timeout")), true);+ assert.equal(isRetryableBeautifyError(new Error("Rate Limit exceeded")), true, "matching is case-insensitive");+ assert.equal(isRetryableBeautifyError(new Error("TypeError: Failed to fetch")), true);+ assert.equal(isRetryableBeautifyError(new Error("content policy violation")), false);+ assert.equal(isRetryableBeautifyError(new Error("400 invalid image")), false);+});++test("an unreadable error is not retried forever", () => {+ assert.equal(isRetryableBeautifyError(null), false);+});++test("runInParallel never exceeds the limit", async () => {+ let inFlight = 0;+ let peak = 0;+ const tasks = Array.from({ length: 10 }, () => async () => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await sleep(5);+ inFlight -= 1;+ });++ await runInParallel(tasks, 3);+ assert.equal(peak, 3);+ assert.equal(inFlight, 0);+});++test("one failed slide does not abandon the rest of the deck", async () => {+ const done: number[] = [];+ const tasks = [0, 1, 2, 3, 4].map((n) => async () => {+ if (n === 1) throw new Error("slide 1 failed");+ await sleep(1);+ done.push(n);+ });++ await assert.rejects(runInParallel(tasks, 2), /slide 1 failed/);+ assert.deepEqual(done.sort(), [0, 2, 3, 4], "every other slide finished before the throw");+});++test("runInParallel accepts an empty deck", async () => {+ await runInParallel([], 4);+});++test("parseJsonLoose reads bare JSON", () => {+ assert.deepEqual(parseJsonLoose('[{"a":1}]'), [{ a: 1 }]);+ assert.deepEqual(parseJsonLoose(' {"a":1} '), { a: 1 });+});++test("parseJsonLoose digs the answer out of a fenced block", () => {+ const reply = 'Sure, here you go:\n```json\n[{"slide":1}]\n```\nHope that helps!';+ assert.deepEqual(parseJsonLoose(reply), [{ slide: 1 }]);+});++test("parseJsonLoose falls back to the outermost brackets", () => {+ assert.deepEqual(parseJsonLoose('Here: [1, 2, 3] — done.'), [1, 2, 3]);+});++test("parseJsonLoose returns null rather than throwing on junk", () => {+ assert.equal(parseJsonLoose(""), null);+ assert.equal(parseJsonLoose("no json at all"), null);+ assert.equal(parseJsonLoose("[unclosed"), null);+ assert.equal(parseJsonLoose("[not, valid, json]"), null);+});++test("the beautify instruction always carries its preservation rules", () => {+ const plain = buildBeautifyInstruction("");+ assert.match(plain, /preserving all original text/);+ assert.match(plain, /16:9 landscape/);+ assert.ok(!plain.includes("User requirements"), "nothing to append");+});++test("the user's wording is appended, whitespace-only counts as none", () => {+ assert.match(buildBeautifyInstruction("make it blue"), /User requirements: make it blue$/);+ assert.ok(!buildBeautifyInstruction(" ").includes("User requirements"));+});++test("the slideshow box keeps 16:9 inside the window", () => {+ const wide = getSlideshowDimensions({ width: 4000, height: 1000 });+ assert.equal(typeof wide.width, "number");+ // 0.9 * 4000 = 3600 wide would need 2025 high, past the 850 budget.+ assert.equal(wide.height, 850);+ assert.ok(Math.abs((wide.width as number) / (wide.height as number) - 16 / 9) < 1e-9);+});++test("a tall window is limited by width instead", () => {+ const tall = getSlideshowDimensions({ width: 1000, height: 4000 });+ assert.equal(tall.width, 900);+ assert.equal(tall.height, 506.25);+});++test("before the window is measured it falls back to viewport units", () => {+ assert.deepEqual(getSlideshowDimensions({ width: 0, height: 0 }), {+ width: "90vw",+ height: "50.625vw",+ });+});