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(hooks): close the stale-closure gaps behind the 21 deps warnings
codingFeng101bff402730bd4
diff --git a/client/shared/chat/chat-input.tsx b/client/shared/chat/chat-input.tsxindex 2625466..de4529e 100644--- a/client/shared/chat/chat-input.tsx+++ b/client/shared/chat/chat-input.tsx@@ -140,6 +140,9 @@ export function ChatInput({if (focusKey === undefined) return;if (isRich) richRef.current?.focus();else textareaRef.current?.focus();+ // Bumped by the parent to request focus. Depending on isRich as well+ // would steal focus every time the input flips mode.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [focusKey]);useEffect(() => {@@ -152,6 +155,10 @@ export function ChatInput({root.appendChild(document.createTextNode(""));richAppliedRef.current = "";onRichSegmentsChange?.([{ type: "text", text: "" }]);+ // Bumped by the parent to request a clear. onRichSegmentsChange is an+ // inline arrow from the parent, so depending on it would re-clear on+ // every parent render and wipe what the user is typing.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [clearKey, isRich]);const serializeSegments = (segments: RichInputSegment[]) => {@@ -263,6 +270,9 @@ export function ChatInput({richAppliedRef.current = key;if (richHasFocus) return;setRichContentFromSegments(segments);+ // setRichContentFromSegments is redefined every render; the segment key+ // above is what decides whether the DOM actually needs rewriting.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [isRich, richSegments, richHasFocus]);const insertPptTokenAtCursor = (slideId: string, label: string, tag: string, tokenKind: "outline" | "slide_image") => {@@ -298,6 +308,9 @@ export function ChatInput({if (!insertPptToken) return;insertPptTokenAtCursor(insertPptToken.slideId, insertPptToken.label, insertPptToken.tag, insertPptToken.tokenKind);onInsertPptTokenHandled?.();+ // Keyed on .key so the parent can request the same token twice; the+ // token object itself is rebuilt each render and would re-insert.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [isRich, insertPptToken?.key]);const richPlainText = useMemo(() => {diff --git a/client/shared/lib/use-latest-ref.ts b/client/shared/lib/use-latest-ref.tsnew file mode 100644index 0000000..50743f1--- /dev/null+++ b/client/shared/lib/use-latest-ref.ts@@ -0,0 +1,20 @@+import { useEffect, useRef, type MutableRefObject } from "react";++/**+ * Keeps a ref pointing at the newest value.+ *+ * For long-lived effects — an event listener registered once on mount, a+ * timer, a subscription — that need the current value of something without+ * re-registering when it changes. Adding the value to the dependency array+ * would tear the subscription down and rebuild it on every change, which for+ * these is worse than the staleness it fixes.+ *+ * Read it as `ref.current` inside the callback, never during render.+ */+export function useLatestRef<T>(value: T): MutableRefObject<T> {+ const ref = useRef(value);+ useEffect(() => {+ ref.current = value;+ }, [value]);+ return ref;+}diff --git a/client/workspaces/cad/canvas/CadCanvas.tsx b/client/workspaces/cad/canvas/CadCanvas.tsxindex a3343b3..d3a917c 100644--- a/client/workspaces/cad/canvas/CadCanvas.tsx+++ b/client/workspaces/cad/canvas/CadCanvas.tsx@@ -1,4 +1,5 @@-import { useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useLatestRef } from "@/shared/lib/use-latest-ref";import { Loader2, MessageSquarePlus, Box, Image as ImageIcon, Table2, Download } from 'lucide-react';import {ContextMenu,@@ -166,33 +167,15 @@ export function CadCanvas({const externalSvgApplyAtRef = useRef(0);const EXTERNAL_APPLY_GUARD_MS = 2500;- useEffect(() => {- if (typeof svg2d === "string") {- const normalized = normalizeSvgMarkup(svg2d);- setSvgContent(normalized || null);- desiredSvgRef.current = normalized;- externalSvgApplyAtRef.current = Date.now();- if (normalized) {- loadSvgToEditorWithRetry(normalized);- latestLoadedSvgRef.current = normalized;- } else {- postToSvgEditor({ type: "cad_svg_editor_clear" });- latestLoadedSvgRef.current = EMPTY_SENTINEL;- }- return;- }- setSvgContent(null);- desiredSvgRef.current = "";- postToSvgEditor({ type: "cad_svg_editor_clear" });- latestLoadedSvgRef.current = EMPTY_SENTINEL;- }, [svg2d]);+ const uiLangRef = useLatestRef(uiLang);- const postToSvgEditor = (payload: Record<string, unknown>) => {+ // Reads only refs, so it never needs to change identity.+ const postToSvgEditor = useCallback((payload: Record<string, unknown>) => {const win = svgEditorIframeRef.current?.contentWindow;if (!win) return false;win.postMessage(payload, window.location.origin);return true;- };+ }, []);const handleSvgEditorIframeLoad = () => {setIsSvgEditorReady(false);@@ -220,7 +203,11 @@ export function CadCanvas({}};- const loadSvgToEditorWithRetry = (svg: string) => {+ /**+ * The editor iframe drops loads sent before it is ready and gives no+ * acknowledgement, so the same payload is re-sent on a fixed ladder.+ */+ const loadSvgToEditorWithRetry = useCallback((svg: string) => {const normalized = normalizeSvgMarkup(svg);if (!normalized) return false;const sent = postToSvgEditor({ type: "cad_svg_editor_load", svg: normalized });@@ -232,7 +219,28 @@ export function CadCanvas({}, delay);}return true;- };+ }, [postToSvgEditor]);++ useEffect(() => {+ if (typeof svg2d === "string") {+ const normalized = normalizeSvgMarkup(svg2d);+ setSvgContent(normalized || null);+ desiredSvgRef.current = normalized;+ externalSvgApplyAtRef.current = Date.now();+ if (normalized) {+ loadSvgToEditorWithRetry(normalized);+ latestLoadedSvgRef.current = normalized;+ } else {+ postToSvgEditor({ type: "cad_svg_editor_clear" });+ latestLoadedSvgRef.current = EMPTY_SENTINEL;+ }+ return;+ }+ setSvgContent(null);+ desiredSvgRef.current = "";+ postToSvgEditor({ type: "cad_svg_editor_clear" });+ latestLoadedSvgRef.current = EMPTY_SENTINEL;+ }, [svg2d, loadSvgToEditorWithRetry, postToSvgEditor]);useEffect(() => {if (typeof window === "undefined") return;@@ -269,9 +277,9 @@ export function CadCanvas({if (ok) return;const reason = String((data as any).reason || "").trim();if (reason) {- toast.error(uiLang === "zh" ? `SVG加载失败:${reason}` : `SVG load failed: ${reason}`);+ toast.error(uiLangRef.current === "zh" ? `SVG加载失败:${reason}` : `SVG load failed: ${reason}`);} else {- toast.error(uiLang === "zh" ? "SVG加载失败" : "SVG load failed");+ toast.error(uiLangRef.current === "zh" ? "SVG加载失败" : "SVG load failed");}const next = String(desiredSvgRef.current || "").trim();if (!next) return;@@ -282,11 +290,12 @@ export function CadCanvas({};window.addEventListener("message", onMessage);+ const pending = svgEditorPendingRef.current;return () => {window.removeEventListener("message", onMessage);- svgEditorPendingRef.current.clear();+ pending.clear();};- }, []);+ }, [loadSvgToEditorWithRetry, postToSvgEditor, uiLangRef]);useEffect(() => {const next = normalizeSvgMarkup(typeof svgContent === "string" ? svgContent : "");@@ -303,7 +312,7 @@ export function CadCanvas({if (postToSvgEditor({ type: "cad_svg_editor_clear" })) {latestLoadedSvgRef.current = EMPTY_SENTINEL;}- }, [svgContent]);+ }, [svgContent, loadSvgToEditorWithRetry, postToSvgEditor]);useEffect(() => {if (!Array.isArray(images) || images.length === 0) {@@ -370,7 +379,7 @@ export function CadCanvas({}}, [plan, svg2d, images, bom, focusPanel]);- const requestSvgFromEditor = async (opts?: { preferFallbackOnEmpty?: boolean }) => {+ const requestSvgFromEditor = useCallback(async (opts?: { preferFallbackOnEmpty?: boolean }) => {const fallback = normalizeSvgMarkup(String(svgContent || svg2d || ""));if (!isSvgEditorReady) return fallback;@@ -402,7 +411,7 @@ export function CadCanvas({resolve(fallback);}});- };+ }, [isSvgEditorReady, svgContent, svg2d, postToSvgEditor]);useEffect(() => {if (!ENABLE_EDITOR_AUTOSYNC) return;@@ -449,7 +458,7 @@ export function CadCanvas({})();}, 1800);return () => window.clearInterval(timer);- }, [isSvgEditorReady, viewMode, svgContent, svg2d, onSvgChange]);+ }, [isSvgEditorReady, viewMode, svgContent, svg2d, onSvgChange, loadSvgToEditorWithRetry, postToSvgEditor, requestSvgFromEditor]);const downloadBlob = (blob: Blob, filename: string) => {const link = document.createElement("a");diff --git a/client/workspaces/flow/chat/ChatMessageDisplay.tsx b/client/workspaces/flow/chat/ChatMessageDisplay.tsxindex bc02da6..f109e37 100644--- a/client/workspaces/flow/chat/ChatMessageDisplay.tsx+++ b/client/workspaces/flow/chat/ChatMessageDisplay.tsx@@ -386,7 +386,7 @@ export function ChatMessageDisplay({})}})- }, [messages, handleDisplayChart])+ }, [messages, handleDisplayChart, processedToolCalls])const renderToolPart = (part: ToolPartLike) => {const callId = part.toolCallIddiff --git a/client/workspaces/ppt/canvas/PptCanvas.tsx b/client/workspaces/ppt/canvas/PptCanvas.tsxindex ed4a437..60ca131 100644--- a/client/workspaces/ppt/canvas/PptCanvas.tsx+++ b/client/workspaces/ppt/canvas/PptCanvas.tsx@@ -1,5 +1,6 @@-import React, { useState, useEffect, useRef } from 'react';+import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';import { motion } from "motion/react";+import { useLatestRef } from "@/shared/lib/use-latest-ref";import { generateImage, generateChatMessage } from '@/ai/client';import {pptService,@@ -120,7 +121,7 @@ export function PptCanvas({onResetWorkspace}: PptCanvasProps) {const uiLang = useUiLanguage();- const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);+ const tr = useCallback((zh: string, en: string) => (uiLang === "zh" ? zh : en), [uiLang]);const initialPptStateRef = useRef<any>(undefined);if (typeof initialPptStateRef.current === "undefined") {initialPptStateRef.current = (() => {@@ -555,12 +556,12 @@ export function PptCanvas({};}, []);- const templates: TemplateItem[] = [+ const templates: TemplateItem[] = useMemo(() => [...PRESET_TEMPLATES.filter((t) => !hiddenPresetTemplateIds.includes(t.id)).map((t) => ({ id: t.id, name: uiLang === "zh" ? t.zhName : t.enName, kind: "preset" as const, previewSrc: t.path, presetPath: t.path })),...uploadedTemplates.map((t) => ({ id: t.id, name: t.name, kind: "upload" as const, previewSrc: t.dataUrl, dataUrl: t.dataUrl })),- ];+ ], [hiddenPresetTemplateIds, uploadedTemplates, uiLang]);useEffect(() => {if (typeof window === "undefined") return;@@ -743,9 +744,11 @@ export function PptCanvas({};}, [generatedImages, imageVersions, renderLayers]);+ const onPptReadyChangeRef = useLatestRef(onPptReadyChange);+ const isPptReady = localSlides.length > 0;useEffect(() => {- onPptReadyChange?.(localSlides.length > 0);- }, [localSlides.length]);+ onPptReadyChangeRef.current?.(isPptReady);+ }, [isPptReady, onPptReadyChangeRef]);useEffect(() => {if (typeof window === "undefined") return;@@ -787,7 +790,7 @@ export function PptCanvas({return { width: w, height: h };};- const setTemplateFromItem = async (item: TemplateItem) => {+ const setTemplateFromItem = useCallback(async (item: TemplateItem) => {setSelectedTemplateId(item.id);if (item.kind === "upload") {setTemplateImage(item.dataUrl);@@ -804,7 +807,7 @@ export function PptCanvas({} catch (e) {console.error("Failed to load template", e);}- };+ }, []);useEffect(() => {if (templates.length === 0) {@@ -824,7 +827,7 @@ export function PptCanvas({if (selected.kind === "upload" && templateImage !== selected.dataUrl) {setTemplateImage(selected.dataUrl);}- }, [selectedTemplateId, templateImage, hiddenPresetTemplateIds.join("|"), uploadedTemplates.map((t) => t.id).join("|")]);+ }, [selectedTemplateId, templateImage, templates, setTemplateFromItem]);const addUploadedTemplates = async (files: File[]) => {const imageFiles = Array.from(files || []).filter((f) => f && f.type.startsWith("image/"));@@ -915,8 +918,11 @@ export function PptCanvas({const [isApplyingEdits, setIsApplyingEdits] = useState(false);- const setSlidesKeepingSelection = (nextSlides: SlideData[]) => {- const currentId = localSlides[currentSlideIndex]?.id;+ const localSlidesRef = useLatestRef(localSlides);+ const currentSlideIndexRef = useLatestRef(currentSlideIndex);++ const setSlidesKeepingSelection = useCallback((nextSlides: SlideData[]) => {+ const currentId = localSlidesRef.current[currentSlideIndexRef.current]?.id;setLocalSlides(nextSlides);if (!Array.isArray(nextSlides) || nextSlides.length === 0) {setCurrentSlideIndex(0);@@ -933,15 +939,15 @@ export function PptCanvas({const safePrev = Number.isFinite(prev) ? Math.max(0, Math.floor(prev)) : 0;return Math.min(safePrev, nextSlides.length - 1);});- };+ }, [localSlidesRef, currentSlideIndexRef]);useEffect(() => {if (data && data.slides && data.slides.length > 0) {setSlidesKeepingSelection(data.slides);setCreationStep('done');- onPptReadyChange?.(true);+ onPptReadyChangeRef.current?.(true);}- }, [data]);+ }, [data, onPptReadyChangeRef, setSlidesKeepingSelection]);const applyIncomingSlideEdits = async (payload: string) => {let parsed: any;@@ -1390,9 +1396,28 @@ export function PptCanvas({.finally(() => {if (id) onIncomingEditHandled?.(id);});+ // One-shot per edit request: the id identifies the request, and the effect+ // reads that render's payload when it fires. Depending on the object would+ // re-apply the same edits on every parent render.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [incomingEdit?.id]);- const getSlideVersionMeta = (slideId: string) => {+ const getVisibleSlideVersions = useCallback((slideId: string) => {+ const versions = imageVersions[slideId] || [];+ const hasPrimaryVersion = versions.some((version) => version.type !== "derived_textless");+ if (hasPrimaryVersion || !generatedImages[slideId]) return versions;+ return [+ {+ id: `${SYNTHETIC_PRIMARY_VERSION_PREFIX}${slideId}`,+ url: generatedImages[slideId],+ timestamp: Date.now(),+ type: "generated" as const,+ instruction: tr("原始版本", "Original version"),+ },+ ...versions,+ ];+ }, [imageVersions, generatedImages, tr]);+ const getSlideVersionMeta = useCallback((slideId: string) => {const visibleVersions = getVisibleSlideVersions(slideId);const versions = imageVersions[slideId] || [];const requestedVersionId = currentImageVersionId[slideId] || "";@@ -1412,32 +1437,17 @@ export function PptCanvas({version,imageUrl: version?.url || generatedImages[slideId] || "",};- };- const getVisibleSlideVersions = (slideId: string) => {- const versions = imageVersions[slideId] || [];- const hasPrimaryVersion = versions.some((version) => version.type !== "derived_textless");- if (hasPrimaryVersion || !generatedImages[slideId]) return versions;- return [- {- id: `${SYNTHETIC_PRIMARY_VERSION_PREFIX}${slideId}`,- url: generatedImages[slideId],- timestamp: Date.now(),- type: "generated" as const,- instruction: tr("原始版本", "Original version"),- },- ...versions,- ];- };+ }, [getVisibleSlideVersions, imageVersions, currentImageVersionId, generatedImages]);const getSlideImageUrl = (slideId: string) => getSlideVersionMeta(slideId).imageUrl;const getOriginalSlideVersion = (slideId: string) => {const versions = imageVersions[slideId] || [];return versions.find((version) => !version.sourceVersionId) || versions[0];};- const getSlideRenderLayer = (slideId: string) => {+ const getSlideRenderLayer = useCallback((slideId: string) => {const { versionId } = getSlideVersionMeta(slideId);if (!versionId) return undefined;return renderLayers[slideId]?.[versionId];- };+ }, [getSlideVersionMeta, renderLayers]);const getTextlessBackgroundVersion = (slideId: string) => {const versions = imageVersions[slideId] || [];return versions.find((version) => version.type === "derived_textless");@@ -1783,6 +1793,11 @@ export function PptCanvas({window.removeEventListener("pointerup", stopDrag);window.removeEventListener("pointercancel", stopDrag);};+ // Registered for the duration of one drag. The updaters it calls write+ // through setRenderLayers's functional form, so they see current state+ // despite being captured at drag start; depending on them would tear the+ // listeners down and rebuild them on every pointermove.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [draggingTextBlockId, resizingTextBlockId]);useEffect(() => {const activeSlide = localSlides[currentSlideIndex];@@ -1801,7 +1816,7 @@ export function PptCanvas({if (!selectedReviewTextBlockId || !blocks.some((block) => block.id === selectedReviewTextBlockId)) {setSelectedReviewTextBlockId(blocks[0].id);}- }, [exportReviewMode, localSlides, currentSlideIndex, renderLayers, selectedReviewTextBlockId]);+ }, [exportReviewMode, localSlides, currentSlideIndex, renderLayers, selectedReviewTextBlockId, getSlideRenderLayer]);useEffect(() => {if (!reviewDrawRef.current) return;const handlePointerMove = (event: PointerEvent) => {@@ -1842,6 +1857,8 @@ export function PptCanvas({window.removeEventListener("pointerup", stopPointer);window.removeEventListener("pointercancel", stopPointer);};+ // Same as the text-block drag above: rebuilt per draw gesture, not per frame.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [reviewDraftRect]);useEffect(() => {const handlePointerMove = (event: PointerEvent) => {@@ -2215,6 +2232,9 @@ export function PptCanvas({};window.addEventListener("keydown", onKeyDown);return () => window.removeEventListener("keydown", onKeyDown);+ // closeSlideshow only flips slideshowOpen and leaves fullscreen, so the+ // captured copy behaves identically to a fresh one.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [slideshowOpen, activeSlides.length, slideshowFullscreen]);useEffect(() => {diff --git a/client/workspaces/ppt/chat/ChatPanel.tsx b/client/workspaces/ppt/chat/ChatPanel.tsxindex 557f3f4..ae2c5a9 100644--- a/client/workspaces/ppt/chat/ChatPanel.tsx+++ b/client/workspaces/ppt/chat/ChatPanel.tsx@@ -1,4 +1,4 @@-import { useState, useRef, useEffect } from 'react';+import { useState, useRef, useEffect, useCallback } from 'react';import { PanelRightClose, PanelRightOpen } from 'lucide-react';import { cn } from '@/shared/lib/utils';import { streamChatMessage, generatePptProxyChatMessage, ChatMessage, getAIConfig } from '@/ai/client';@@ -114,37 +114,37 @@ export function ChatPanel({const [pptClearTick, setPptClearTick] = useState(0);const lastUploadedImagesRef = useRef<string[]>([]);- const getPptLabel = (slideId: string, title: string) => {- const m = String(slideId || "").match(/(\d+)/);- const n = m ? Number(m[1]) : NaN;- if (!Number.isNaN(n)) {- return title ? `Slide ${n}: ${title}` : `Slide ${n}`;- }- return title || slideId;- };-- const getPptTag = (slideId: string, title: string, kind: "outline" | "slide_image") => {- const m = String(slideId || "").match(/(\d+)/);- const n = m ? Number(m[1]) : NaN;- if (Number.isNaN(n)) return "";- const safeTitle = String(title || "").split("|").join(",").split("]]").join("");- return `[[PPT_SLIDE|${n}|${safeTitle}|${kind}]]`;- };-- const pumpPptInsertQueue = () => {+const getPptLabel = (slideId: string, title: string) => {+ const m = String(slideId || "").match(/(\d+)/);+ const n = m ? Number(m[1]) : NaN;+ if (!Number.isNaN(n)) {+ return title ? `Slide ${n}: ${title}` : `Slide ${n}`;+ }+ return title || slideId;+};++const getPptTag = (slideId: string, title: string, kind: "outline" | "slide_image") => {+ const m = String(slideId || "").match(/(\d+)/);+ const n = m ? Number(m[1]) : NaN;+ if (Number.isNaN(n)) return "";+ const safeTitle = String(title || "").split("|").join(",").split("]]").join("");+ return `[[PPT_SLIDE|${n}|${safeTitle}|${kind}]]`;+};++ const pumpPptInsertQueue = useCallback(() => {if (pptInsertBusyRef.current) return;const next = pptInsertQueueRef.current.shift();if (!next) return;pptInsertBusyRef.current = true;const tag = getPptTag(next.slideId, next.title, next.kind);setPptInsertToken({ key: Date.now() + Math.random(), slideId: next.slideId, label: next.label, tag, tokenKind: next.kind });- };+ }, []);- const enqueuePptToken = (slideId: string, title: string, kind: "outline" | "slide_image") => {+ const enqueuePptToken = useCallback((slideId: string, title: string, kind: "outline" | "slide_image") => {const label = getPptLabel(slideId, title);pptInsertQueueRef.current.push({ slideId, title, label, kind });pumpPptInsertQueue();- };+ }, [pumpPptInsertQueue]);useEffect(() => {const prev = prevPptDraftCountRef.current;@@ -162,7 +162,7 @@ export function ChatPanel({prevPptDraftIdsRef.current = nextIds;if (added.length === 0) return;for (const s of added) enqueuePptToken(s.slideId, s.title, s.kind);- }, [pptDraftSlides, setInput]);+ }, [pptDraftSlides, enqueuePptToken]);// CAD strips its tool payloads out of the transcript; PPT has none to strip.const sanitizeAssistantContentForDisplay = (content: string) => content;