Skip to content

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

feat(web): export infographic notes as pictures

tianma-if17dfff1ad515
diff --git a/apps/web/src/components/InfographicEditorPane.test.mjs b/apps/web/src/components/InfographicEditorPane.test.mjs
index 6a0b975c..736df3d4 100644
--- a/apps/web/src/components/InfographicEditorPane.test.mjs
+++ b/apps/web/src/components/InfographicEditorPane.test.mjs
@@ -14,8 +14,12 @@ describe("infographic editor header", () => {
expect(status).toBeGreaterThan(metadata);
expect(headerEnd).toBeGreaterThan(status);
expect(source).toContain("<MemoEditorHeaderActions");
+ expect(source).toContain('t("infographic.export")');
+ expect(source).toContain("data-infographic-export");
+ expect(source).toContain("rasterizeInfographicSvg");
expect(source).toContain('t("infographic.exportSvg")');
expect(source).toContain('t("infographic.exportPng")');
+ expect(source).not.toContain("toDataURL");
expect(source).not.toContain("<PieChart");
expect(source).not.toContain('t("infographic.save")');
expect(source).toContain("parseTagsText(tagsRef.current)");
diff --git a/apps/web/src/components/InfographicEditorPane.tsx b/apps/web/src/components/InfographicEditorPane.tsx
index ff04936c..f3790c7f 100644
--- a/apps/web/src/components/InfographicEditorPane.tsx
+++ b/apps/web/src/components/InfographicEditorPane.tsx
@@ -1,11 +1,11 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { Check, ChevronLeft, FileCode2, FileImage, LoaderCircle, Pencil, Sparkles } from "lucide-react";
+import { Check, ChevronLeft, Download, FileCode2, FileImage, LoaderCircle, Pencil, Sparkles } from "lucide-react";
import * as m from "motion/react-m";
import { useTranslation } from "react-i18next";
import { INFOGRAPHIC_AGENT_SOURCE_MAX_LENGTH, markdownToDoc, infographicFallbackMarkdown, parseInfographicDocument, serializeInfographicDocument, type InfographicConversationTurn, type InfographicDocument, type MemoDetail, type MemoEditSession, type Notebook } from "@edgeever/shared";
import type { Infographic as InfographicInstance, SyntaxParseResult } from "@antv/infographic";
import { Button } from "@/components/ui/button";
-import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { AiSidebar, readAiSidebarOpen, writeAiSidebarOpen } from "@/components/ai-sidebar/AiSidebar";
import { AiSidebarErrorBoundary } from "@/components/ai-sidebar/AiSidebarErrorBoundary";
import type { InfographicSidebarController } from "@/components/ai-sidebar/InfographicSidebarSession";
@@ -19,6 +19,7 @@ import { MemoTitleInput } from "@/components/MemoTitleInput";
import { api } from "@/lib/api";
import { formatShortcutBinding, getNotebookMoveOptions, type ShortcutSettings } from "@/lib/app-helpers";
import { createLocalEditSession, requiresLocalEditSession } from "@/components/editor/editor-pane-helpers";
+import { canvasToPngBlob, downloadBlob, frameInfographicExportSvg, infographicExportBasename, rasterizeInfographicSvg, readInfographicSheetColor } from "@/lib/infographic-image-export";
import { buildInfographicSyntax, buildOfficialInfographicSyntax, infographicAgentCandidates, INFOGRAPHIC_TEMPLATES, parseGeneratedOfficialData, type InfographicItem } from "@/lib/infographic-generation";
import { statusSettleMotion } from "@/lib/motion";
import type { EdgeEverRepository } from "@/lib/repository";
@@ -179,15 +180,6 @@ const applyOfficialVisualTextChange = (syntax: string, payload: VisualTextChange
return buildOfficialInfographicSyntax(parsed.options.template, data, editable.dark);
};
-const downloadDataUrl = (dataUrl: string, filename: string) => {
- const link = document.createElement("a");
- link.href = dataUrl;
- link.download = filename;
- document.body.appendChild(link);
- link.click();
- link.remove();
-};
-
export default function InfographicEditorPane({
memo,
notebooks,
@@ -526,11 +518,22 @@ export default function InfographicEditorPane({
};
const exportImage = async (type: "svg" | "png") => {
- if (!instanceRef.current || renderError || !previewReady) return;
+ const svg = containerRef.current?.querySelector("svg");
+ if (!(svg instanceof SVGSVGElement) || renderError || !previewReady) return;
try {
- const url = await instanceRef.current.toDataURL({ type });
- downloadDataUrl(url, `${(title.trim() || "infographic").replace(/[\\/:*?"<>|]/g, "-")}.${type}`);
- } catch (caught) { setError(caught instanceof Error ? caught.message : t("infographic.renderError")); }
+ const { exportToSVG } = await import("@antv/infographic");
+ const exported = await exportToSVG(svg);
+ const sheetColor = readInfographicSheetColor(containerRef.current?.parentElement ?? null, syntax.split("\n")[1] === "theme dark");
+ frameInfographicExportSvg(exported, sheetColor);
+ const basename = infographicExportBasename(title.trim() || t("infographic.name"));
+ if (type === "svg") {
+ downloadBlob(new Blob([new XMLSerializer().serializeToString(exported)], { type: "image/svg+xml;charset=utf-8" }), `${basename}.svg`);
+ return;
+ }
+ downloadBlob(await canvasToPngBlob(await rasterizeInfographicSvg(exported, sheetColor)), `${basename}.png`);
+ } catch {
+ setError(t("infographic.exportError"));
+ }
};
const previewUsesLightSheet = Boolean(syntax.trim()) && syntax.split("\n")[1] !== "theme dark";
@@ -600,6 +603,32 @@ export default function InfographicEditorPane({
<MemoEditorToolbarDivider className="mx-0.5 hidden h-4 sm:block" />
<div className="flex items-center gap-0.5">
<MemoEditorFocusModeButton desktopFocusMode={desktopFocusMode} onToggleDesktopFocusMode={onToggleDesktopFocusMode} />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-8 gap-1 px-2 text-xs"
+ data-infographic-export=""
+ disabled={!previewReady || Boolean(renderError)}
+ aria-label={t("infographic.export")}
+ >
+ <Download className="h-4 w-4" />
+ <span className="hidden sm:inline">{t("infographic.export")}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem className="gap-2" disabled={!previewReady || Boolean(renderError)} onClick={() => void exportImage("png")}>
+ <FileImage className="h-4 w-4 text-slate-500" />
+ {t("infographic.exportPng")}
+ </DropdownMenuItem>
+ <DropdownMenuItem className="gap-2" disabled={!previewReady || Boolean(renderError)} onClick={() => void exportImage("svg")}>
+ <FileCode2 className="h-4 w-4 text-slate-500" />
+ {t("infographic.exportSvg")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
<MemoEditorHeaderActions
moreMenuClassName="w-48"
onOpenExecutionCenter={onOpenExecutionCenter}
diff --git a/apps/web/src/lib/infographic-image-export.ts b/apps/web/src/lib/infographic-image-export.ts
new file mode 100644
index 00000000..61def19c
--- /dev/null
+++ b/apps/web/src/lib/infographic-image-export.ts
@@ -0,0 +1,89 @@
+const SVG_NS = "http://www.w3.org/2000/svg";
+const EXPORT_PADDING = 28;
+const EXPORT_PIXEL_RATIO = 2;
+
+// AntV `toDataURL` draws onto a transparent canvas. Shape fills are translucent,
+// so the file looks empty wherever it is opened. Rasterize the exported SVG onto
+// the same sheet color as the preview instead.
+export const INFOGRAPHIC_EXPORT_PIXEL_RATIO = EXPORT_PIXEL_RATIO;
+
+export const infographicExportBasename = (title: string) =>
+ (title.trim() || "infographic").replace(/[\\/:*?"<>|]/g, "-").slice(0, 80);
+
+export const readInfographicSheetColor = (sheet: Element | null, dark: boolean) => {
+ const fallback = dark ? "#1F1F1F" : "#FFFFFF";
+ if (!sheet || typeof getComputedStyle !== "function") return fallback;
+ const color = getComputedStyle(sheet).backgroundColor;
+ const match = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/.exec(color);
+ if (!match) return fallback;
+ const alpha = match[4] === undefined ? 1 : Number(match[4]);
+ if (!Number.isFinite(alpha) || alpha < 1) return fallback;
+ return color;
+};
+
+export const frameInfographicExportSvg = (svg: SVGSVGElement, sheetColor: string) => {
+ const box = svg.viewBox.baseVal;
+ const width = box.width > 0 ? box.width : Number(svg.getAttribute("width")) || svg.getBoundingClientRect().width;
+ const height = box.height > 0 ? box.height : Number(svg.getAttribute("height")) || svg.getBoundingClientRect().height;
+ if (!(width > 0) || !(height > 0)) throw new Error("empty");
+ const x = (box.width > 0 ? box.x : 0) - EXPORT_PADDING;
+ const y = (box.height > 0 ? box.y : 0) - EXPORT_PADDING;
+ const framedWidth = width + EXPORT_PADDING * 2;
+ const framedHeight = height + EXPORT_PADDING * 2;
+ svg.setAttribute("xmlns", SVG_NS);
+ svg.setAttribute("viewBox", `${x} ${y} ${framedWidth} ${framedHeight}`);
+ svg.setAttribute("width", String(framedWidth));
+ svg.setAttribute("height", String(framedHeight));
+ const background = document.createElementNS(SVG_NS, "rect");
+ background.setAttribute("data-infographic-export-sheet", "");
+ background.setAttribute("x", String(x));
+ background.setAttribute("y", String(y));
+ background.setAttribute("width", String(framedWidth));
+ background.setAttribute("height", String(framedHeight));
+ background.setAttribute("fill", sheetColor);
+ svg.insertBefore(background, svg.firstChild);
+ return { height: framedHeight, width: framedWidth };
+};
+
+export const rasterizeInfographicSvg = (svg: SVGSVGElement, sheetColor: string) => {
+ const width = Number(svg.getAttribute("width"));
+ const height = Number(svg.getAttribute("height"));
+ const xml = new XMLSerializer().serializeToString(svg);
+ const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xml)}`;
+ return new Promise<HTMLCanvasElement>((resolve, reject) => {
+ const image = new Image();
+ image.onload = () => {
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.max(1, Math.ceil(width * EXPORT_PIXEL_RATIO));
+ canvas.height = Math.max(1, Math.ceil(height * EXPORT_PIXEL_RATIO));
+ const context = canvas.getContext("2d");
+ if (!context) {
+ reject(new Error("canvas"));
+ return;
+ }
+ context.fillStyle = sheetColor;
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
+ resolve(canvas);
+ };
+ image.onerror = () => reject(new Error("svg"));
+ image.src = url;
+ });
+};
+
+export const canvasToPngBlob = (canvas: HTMLCanvasElement) =>
+ new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("empty"))), "image/png");
+ });
+
+export const downloadBlob = (blob: Blob, filename: string) => {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ link.hidden = true;
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
+};
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index a90c9c11..da5c854f 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -10,7 +10,8 @@ export const enUS = {
doubleClickText: "Double-click text in the graphic to edit it. Changes save automatically.",
structureSettings: "Structure and style · Bulk edit", editSyntax: "Edit source syntax", backToStructure: "Back to structure and style",
title: "Title", description: "Description", items: "Items (one per line, use ‘Title | Description’)", comparisonItems: "One line per side; add aspects as ‘- Aspect | Description’", template: "Template", theme: "Color theme",
- content: "Content", syntax: "Syntax", preview: "Preview", save: "Save", saving: "Saving…", exportSvg: "Export SVG", exportPng: "Export PNG",
+ content: "Content", syntax: "Syntax", preview: "Preview", save: "Save", saving: "Saving…", export: "Export", exportSvg: "Export SVG", exportPng: "Export PNG",
+ exportError: "Could not export the image. Try again.",
empty: "Describe your content or start from a template.", noPreview: "Add content to see a preview.",
invalidSyntax: "The infographic syntax is invalid. Check it and try again.", renderError: "Rendering failed. Adjust the syntax or template.", contentTooLarge: "This infographic is too large for AI editing. Shorten it first.",
saveError: "Could not save. Try again.", sessionError: "Could not start an editing session. Try again.", aiError: "Generation failed. Check your AI model settings and try again.", aiInvalidResponse: "The generated content could not make an infographic. Try again.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 25d7bda4..6c325e79 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -10,7 +10,8 @@ export const ja = {
doubleClickText: "図内の文字をダブルクリックして編集できます。変更は自動保存されます。",
structureSettings: "構成とスタイル · 一括編集", editSyntax: "元の構文を編集", backToStructure: "構成とスタイルに戻る",
title: "タイトル", description: "説明", items: "項目(1 行に 1 件、「タイトル | 説明」)", comparisonItems: "比較する 2 者を各 1 行にし、観点は「- 項目 | 説明」で追加", template: "テンプレート", theme: "配色",
- content: "内容", syntax: "構文", preview: "プレビュー", save: "保存", saving: "保存中…", exportSvg: "SVG を出力", exportPng: "PNG を出力",
+ content: "内容", syntax: "構文", preview: "プレビュー", save: "保存", saving: "保存中…", export: "エクスポート", exportSvg: "SVG を出力", exportPng: "PNG を出力",
+ exportError: "画像をエクスポートできませんでした。再試行してください。",
empty: "内容を説明するか、テンプレートから始めてください。", noPreview: "内容を入力するとプレビューが表示されます。",
invalidSyntax: "構文が正しくありません。確認して再試行してください。", renderError: "描画に失敗しました。構文またはテンプレートを調整してください。", contentTooLarge: "内容が長すぎるため AI で修正できません。先に短くしてください。",
saveError: "保存できませんでした。再試行してください。", sessionError: "編集セッションを開始できませんでした。", aiError: "生成に失敗しました。AI モデルの設定を確認してください。", aiInvalidResponse: "生成内容からインフォグラフィックを作成できません。再試行してください。",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index a6622242..70a7b329 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -10,7 +10,8 @@ export const zhCN = {
doubleClickText: "双击图中文字可直接修改,修改后自动保存。",
structureSettings: "结构与样式 · 批量调整", editSyntax: "编辑源语法", backToStructure: "返回结构与样式",
title: "标题", description: "说明", items: "条目(每行一个,使用“标题 | 说明”)", comparisonItems: "对比双方各占一行;子项用“- 维度 | 说明”", template: "模板", theme: "配色",
- content: "内容", syntax: "语法", preview: "预览", save: "保存", saving: "保存中…", exportSvg: "导出 SVG", exportPng: "导出 PNG",
+ content: "内容", syntax: "语法", preview: "预览", save: "保存", saving: "保存中…", export: "导出", exportSvg: "导出 SVG", exportPng: "导出 PNG",
+ exportError: "导出图片失败,请重试。",
empty: "用一句话描述内容,或从模板开始。", noPreview: "填写内容后显示预览。",
invalidSyntax: "信息图语法无效,请检查后重试。", renderError: "信息图渲染失败,请调整语法或模板。", contentTooLarge: "信息图内容过长,请先精简后再用 AI 修改。",
saveError: "保存失败,请重试。", sessionError: "无法开启编辑会话,请重试。", aiError: "生成失败,请检查 AI 模型设置后重试。", aiInvalidResponse: "生成内容无法组成信息图,请重试。",