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
fix(ppt): validate the text blocks read back from storage
codingFeng101b3fe1ba405fb
diff --git a/client/workspaces/ppt/canvas/PptCanvas.tsx b/client/workspaces/ppt/canvas/PptCanvas.tsxindex 54d6ee6..eb4a287 100644--- a/client/workspaces/ppt/canvas/PptCanvas.tsx+++ b/client/workspaces/ppt/canvas/PptCanvas.tsx@@ -117,7 +117,7 @@ export function PptCanvas({const raw = localStorage.getItem(PPT_WORKSPACE_STORAGE_KEY);const parsed = raw ? JSON.parse(raw) : null;if (!parsed || typeof parsed !== "object") return null;- return migrateLegacyTextlessVersions(parsed as any);+ return migrateLegacyTextlessVersions(parsed);} catch {return null;}diff --git a/client/workspaces/ppt/canvas/lib/persisted-state.ts b/client/workspaces/ppt/canvas/lib/persisted-state.tsindex 5163f38..d23b1c6 100644--- a/client/workspaces/ppt/canvas/lib/persisted-state.ts+++ b/client/workspaces/ppt/canvas/lib/persisted-state.ts@@ -7,6 +7,7 @@ import type {SlideRenderLayer,UploadTemplate,} from "@/workspaces/ppt/canvas/types";+import type { PptElement, PptTextBlock } from "@/workspaces/ppt/lib/ppt-service";/*** Reading the workspace back from storage.@@ -16,31 +17,35 @@ import type {* normaliser drops what it cannot understand rather than throwing.*/-export const migrateLegacyTextlessVersions = (rawState: any) => {- if (!rawState || typeof rawState !== "object") return rawState;+export const migrateLegacyTextlessVersions = (rawState: unknown): Unknown => {+ if (!isRecord(rawState)) return {};- const imageVersions =- rawState.imageVersions && typeof rawState.imageVersions === "object" && !Array.isArray(rawState.imageVersions)- ? { ...rawState.imageVersions }+ const state = rawState as {+ imageVersions?: unknown;+ renderLayers?: unknown;+ currentImageVersionId?: unknown;+ };++ const imageVersions: Unknown =+ state.imageVersions && typeof state.imageVersions === "object" && !Array.isArray(state.imageVersions)+ ? { ...state.imageVersions }: {};- const renderLayers =- rawState.renderLayers && typeof rawState.renderLayers === "object" && !Array.isArray(rawState.renderLayers)- ? { ...rawState.renderLayers }+ const renderLayers: Unknown =+ state.renderLayers && typeof state.renderLayers === "object" && !Array.isArray(state.renderLayers)+ ? { ...state.renderLayers }: {};- const currentImageVersionId =- rawState.currentImageVersionId &&- typeof rawState.currentImageVersionId === "object" &&- !Array.isArray(rawState.currentImageVersionId)- ? { ...rawState.currentImageVersionId }+ const currentImageVersionId: Unknown =+ state.currentImageVersionId &&+ typeof state.currentImageVersionId === "object" &&+ !Array.isArray(state.currentImageVersionId)+ ? { ...state.currentImageVersionId }: {};for (const [slideId, rawVersions] of Object.entries(imageVersions)) {if (!Array.isArray(rawVersions)) continue;const versions = rawVersions as SlideImageVersion[];- const layerMap =- renderLayers[slideId] && typeof renderLayers[slideId] === "object" && !Array.isArray(renderLayers[slideId])- ? { ...renderLayers[slideId] }- : {};+ const storedLayers = renderLayers[slideId];+ const layerMap: Unknown = isRecord(storedLayers) ? { ...storedLayers } : {};let changed = false;for (const version of versions) {@@ -128,7 +133,7 @@ export const shouldInlinePersistImageUrl = (url: string) => {return raw.startsWith("blob:") || raw.startsWith("http://") || raw.startsWith("https://");};-export const normalizePersistedSlides = (value: any): SlideData[] => {+export const normalizePersistedSlides = (value: unknown): SlideData[] => {if (!Array.isArray(value)) return [];return value.filter((s: any) => s && typeof s.id === "string")@@ -142,7 +147,7 @@ export const normalizePersistedSlides = (value: any): SlideData[] => {}));};-export const normalizePersistedImageMap = (value: any): Record<string, string> => {+export const normalizePersistedImageMap = (value: unknown): Record<string, string> => {if (!value || typeof value !== "object" || Array.isArray(value)) return {};const out: Record<string, string> = {};for (const [k, val] of Object.entries(value)) {@@ -151,7 +156,7 @@ export const normalizePersistedImageMap = (value: any): Record<string, string> =return out;};-export const normalizePersistedImageVersions = (value: any): Record<string, SlideImageVersion[]> => {+export const normalizePersistedImageVersions = (value: unknown): Record<string, SlideImageVersion[]> => {if (!value || typeof value !== "object" || Array.isArray(value)) return {};const out: Record<string, SlideImageVersion[]> = {};for (const [k, val] of Object.entries(value)) {@@ -170,24 +175,85 @@ export const normalizePersistedImageVersions = (value: any): Record<string, Slidreturn out;};-export const normalizePersistedRenderLayers = (value: any): Record<string, Record<string, SlideRenderLayer>> => {+/** A record whose fields still have to be checked one by one. */+type Unknown = Record<string, unknown>;++const isRecord = (value: unknown): value is Unknown =>+ !!value && typeof value === "object" && !Array.isArray(value);++const asArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);++const isFiniteNumber = (value: unknown): value is number =>+ typeof value === "number" && Number.isFinite(value);++const TEXT_BLOCK_ROLES = ["title", "bullet", "summary", "tag"];+const ELEMENT_TYPES = ["text", "image", "shape", "table", "chart", "formula", "video", "audio"];++/**+ * A block the review canvas can actually place, repaired where it can be.+ *+ * Geometry is the part that cannot be guessed: the canvas positions a block+ * from x/y/w/h, so one missing number puts an unreachable box somewhere off+ * the slide and nothing downstream looks again. An id or a role can be filled+ * in the same way the extractor fills them, which keeps layers stored before+ * either was guaranteed.+ */+const toTextBlock = (value: unknown, index: number): PptTextBlock | null => {+ if (!isRecord(value)) return null;+ if (typeof value.text !== "string") return null;+ if (![value.x, value.y, value.w, value.h].every(isFiniteNumber)) return null;++ const role = TEXT_BLOCK_ROLES.includes(String(value.role))+ ? (value.role as PptTextBlock["role"])+ : "bullet";+ const id =+ typeof value.id === "string" && value.id.trim() ? value.id.trim() : `text-block-${index + 1}`;++ return {+ ...(value as unknown as PptTextBlock),+ id,+ role,+ text: value.text,+ x: value.x as number,+ y: value.y as number,+ w: value.w as number,+ h: value.h as number,+ };+};++/** The same geometry check for the shapes the exporter draws. */+const isElement = (value: unknown): value is PptElement =>+ isRecord(value) &&+ typeof value.id === "string" &&+ ELEMENT_TYPES.includes(String(value.type)) &&+ [value.x, value.y, value.w, value.h].every(isFiniteNumber);++export const normalizePersistedRenderLayers = (value: unknown): Record<string, Record<string, SlideRenderLayer>> => {if (!value || typeof value !== "object" || Array.isArray(value)) return {};const out: Record<string, Record<string, SlideRenderLayer>> = {};for (const [slideId, versions] of Object.entries(value)) {if (typeof slideId !== "string" || !versions || typeof versions !== "object" || Array.isArray(versions)) continue;const nextVersions: Record<string, SlideRenderLayer> = {};for (const [versionId, layer] of Object.entries(versions)) {- if (typeof versionId !== "string" || !layer || typeof layer !== "object" || Array.isArray(layer)) continue;- const backgroundImageUrl = typeof (layer as any).backgroundImageUrl === "string" ? (layer as any).backgroundImageUrl : "";- const textBlocks = Array.isArray((layer as any).textBlocks) ? (layer as any).textBlocks : [];- const elements = Array.isArray((layer as any).elements) ? (layer as any).elements : deriveTextElementsFromBlocks(textBlocks);- const status = (layer as any).status === "pending" || (layer as any).status === "failed" ? (layer as any).status : "ready";+ if (typeof versionId !== "string" || !isRecord(layer)) continue;+ const backgroundImageUrl = typeof layer.backgroundImageUrl === "string" ? layer.backgroundImageUrl : "";+ const textBlocks = asArray(layer.textBlocks)+ .map(toTextBlock)+ .filter((block): block is PptTextBlock => !!block);+ const storedElements = asArray(layer.elements);+ // Elements come back only if every one of them survives: a partial+ // set would render fewer shapes than the layer says it has.+ const elements =+ storedElements.length > 0 && storedElements.every(isElement)+ ? (storedElements as PptElement[])+ : deriveTextElementsFromBlocks(textBlocks);+ const status = layer.status === "pending" || layer.status === "failed" ? layer.status : "ready";nextVersions[versionId] = {backgroundImageUrl,textBlocks,elements,status,- error: typeof (layer as any).error === "string" ? (layer as any).error : undefined,+ error: typeof layer.error === "string" ? layer.error : undefined,};}out[slideId] = nextVersions;@@ -195,7 +261,7 @@ export const normalizePersistedRenderLayers = (value: any): Record<string, Recorreturn out;};-export const normalizePersistedStringMap = (value: any, trim = false): Record<string, string> => {+export const normalizePersistedStringMap = (value: unknown, trim = false): Record<string, string> => {if (!value || typeof value !== "object" || Array.isArray(value)) return {};const out: Record<string, string> = {};for (const [k, val] of Object.entries(value)) {@@ -214,7 +280,7 @@ export const filterRecordByAllowedKeys = <T,>(value: Record<string, T>, allowedKreturn out;};-export const normalizePersistedSlideMaterials = (value: any): Record<string, SlideMaterialImage[]> => {+export const normalizePersistedSlideMaterials = (value: unknown): Record<string, SlideMaterialImage[]> => {if (!value || typeof value !== "object" || Array.isArray(value)) return {};const out: Record<string, SlideMaterialImage[]> = {};for (const [k, val] of Object.entries(value)) {@@ -235,14 +301,14 @@ export const normalizePersistedSlideMaterials = (value: any): Record<string, Slireturn out;};-export const normalizePersistedUploadedTemplates = (value: any): UploadTemplate[] => {+export const normalizePersistedUploadedTemplates = (value: unknown): UploadTemplate[] => {if (!Array.isArray(value)) return [];return value.filter((x: any) => x && typeof x.id === "string" && typeof x.name === "string" && typeof x.dataUrl === "string").map((x: any) => ({ id: x.id, name: x.name, dataUrl: x.dataUrl }));};-export const normalizePersistedStringArray = (value: any): string[] => {+export const normalizePersistedStringArray = (value: unknown): string[] => {if (!Array.isArray(value)) return [];return value.map((item: any) => String(item));};diff --git a/client/workspaces/ppt/canvas/lib/slide-content.ts b/client/workspaces/ppt/canvas/lib/slide-content.tsindex bfe1241..fb738c6 100644--- a/client/workspaces/ppt/canvas/lib/slide-content.ts+++ b/client/workspaces/ppt/canvas/lib/slide-content.ts@@ -3,8 +3,11 @@ import type { SlideRenderLayer } from "@/workspaces/ppt/canvas/types";/** Text-shape helpers: bullets, layout hints, and slide-title normalisation. */-export const hasRenderableTextBlocks = (layer?: SlideRenderLayer) =>- Array.isArray(layer?.textBlocks) && layer.textBlocks.length > 0;+/** Also called on stored layers, before anything has vouched for their shape. */+export const hasRenderableTextBlocks = (layer?: SlideRenderLayer | unknown) => {+ const blocks = (layer as SlideRenderLayer | undefined)?.textBlocks;+ return Array.isArray(blocks) && blocks.length > 0;+};export const cloneSerializable = <T,>(value: T): T => JSON.parse(JSON.stringify(value));diff --git a/tests/ppt-persisted-state.test.ts b/tests/ppt-persisted-state.test.tsindex 8a09781..b1fca7d 100644--- a/tests/ppt-persisted-state.test.ts+++ b/tests/ppt-persisted-state.test.ts@@ -184,14 +184,17 @@ test("the textless migration folds a derived layer back onto its source", () =>currentImageVersionId: { s1: "v2" },});- assert.deepEqual(migrated.imageVersions.s1.map((v: { id: string }) => v.id), ["v1"],+ assert.deepEqual((read(migrated, "imageVersions.s1") as { id: string }[]).map((v) => v.id), ["v1"],"the derived version is gone");- assert.equal(migrated.renderLayers.s1.v1.textBlocks.length, 1,+ assert.equal((read(migrated, "renderLayers.s1.v1.textBlocks") as unknown[]).length, 1,"its text blocks moved onto the source version");- assert.equal(migrated.currentImageVersionId.s1, "v1",+ assert.equal(read(migrated, "currentImageVersionId.s1"), "v1","and the selection follows, rather than pointing at a version that no longer exists");});+/** The migration hands back the record it was given; tests read into it. */+const read = (state: unknown, path: string): unknown =>+ path.split(".").reduce<unknown>((value, key) => (value as Record<string, unknown>)?.[key], state);test("the migration leaves a deck without derived versions alone", () => {const state = {imageVersions: { s1: [{ id: "v1", url: "u", timestamp: 1, type: "generated" }] },@@ -201,15 +204,105 @@ test("the migration leaves a deck without derived versions alone", () => {};const migrated = migrateLegacyTextlessVersions(state);- assert.deepEqual(migrated.imageVersions, state.imageVersions);- assert.equal(migrated.currentImageVersionId.s1, "v1");- assert.equal(migrated.somethingElse, "preserved", "unrelated keys pass through");+ assert.deepEqual(read(migrated, "imageVersions"), state.imageVersions);+ assert.equal(read(migrated, "currentImageVersionId.s1"), "v1");+ assert.equal(read(migrated, "somethingElse"), "preserved", "unrelated keys pass through");});test("the migration tolerates junk instead of throwing", () => {- assert.equal(migrateLegacyTextlessVersions(null), null);- assert.equal(migrateLegacyTextlessVersions("nonsense"), "nonsense");+ // It always hands back something the callers can read fields off, so a+ // stored value that is not an object at all becomes an empty one.+ assert.deepEqual(migrateLegacyTextlessVersions(null), {});+ assert.deepEqual(migrateLegacyTextlessVersions("nonsense"), {});+const migrated = migrateLegacyTextlessVersions({ imageVersions: "bad", renderLayers: [] });- assert.deepEqual(migrated.imageVersions, {});- assert.deepEqual(migrated.renderLayers, {});+ assert.deepEqual(read(migrated, "imageVersions"), {});+ assert.deepEqual(read(migrated, "renderLayers"), {});+});++/**+ * These readers exist to make stored data safe to use. Anything that gets+ * past them is typed as real from that point on, so a field they wave+ * through is a field nothing checks again.+ */++test("a version's type is checked, not just copied", () => {+ // resolveSlideVersion keys its central rule off this field -- a textless+ // background must never become the default -- so a corrupted type would+ // silently show the user a slide with its text stripped out.+ const out = normalizePersistedImageVersions({+ "slide-1": [+ { id: "v1", url: "a.png", timestamp: 1, type: "generated" },+ { id: "v2", url: "b.png", timestamp: 2, type: "not-a-real-type" },+ { id: "v3", url: "c.png", timestamp: 3 },+ ],+ });++ const types = out["slide-1"].map((v) => v.type);+ assert.ok(+ types.every((t) => t === "generated" || t === "edited" || t === "derived_textless"),+ `unknown types survived: ${JSON.stringify(types)}`,+ );+});++test("a text block missing its geometry does not reach the render layer", () => {+ // The review canvas positions blocks from x/y/w/h, so a missing number puts+ // an unreachable box somewhere off the slide and nothing looks again.+ const out = normalizePersistedRenderLayers({+ "slide-1": {+ v1: {+ backgroundImageUrl: "bg.png",+ status: "ready",+ textBlocks: [+ { id: "b1", role: "title", text: "ok", x: 0.1, y: 0.1, w: 0.4, h: 0.1 },+ { id: "b2", role: "title", text: "no geometry" },+ { id: "b3", role: "title", text: "half", x: 0.1, y: 0.1 },+ "not an object",+ ],+ },+ },+ });++ assert.deepEqual(+ out["slide-1"].v1.textBlocks.map((b) => b.id),+ ["b1"],+ );+});++test("a block stored before ids and roles were guaranteed is repaired, not dropped", () => {+ // Losing a layer that only lacks a label would cost the user their text;+ // the extractor fills both the same way, so this agrees with it.+ const out = normalizePersistedRenderLayers({+ "slide-1": {+ v1: {+ backgroundImageUrl: "bg.png",+ textBlocks: [{ text: "legacy", x: 0, y: 0, w: 1, h: 0.2 }],+ },+ },+ });++ const [block] = out["slide-1"].v1.textBlocks;+ assert.equal(block.text, "legacy");+ assert.equal(block.role, "bullet", "a missing role defaults rather than dropping the block");+ assert.ok(block.id, "and it gets an id to be selectable by");+});++test("a partly malformed element set is redrawn from the blocks", () => {+ // Keeping the good half would render fewer shapes than the layer claims.+ const out = normalizePersistedRenderLayers({+ "slide-1": {+ v1: {+ backgroundImageUrl: "bg.png",+ textBlocks: [{ id: "b1", role: "title", text: "T", x: 0, y: 0, w: 1, h: 0.2 }],+ elements: [+ { id: "e1", type: "text", x: 0, y: 0, w: 1, h: 0.2 },+ { id: "e2", type: "text" },+ ],+ },+ },+ });++ const elements = out["slide-1"].v1.elements;+ assert.equal(elements.length, 1, "derived from the one block, not the one good element");+ assert.equal(elements[0].id, "b1");});