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): generate infographics from the AI sidebar

tianma-ifea8b64da8a30
diff --git a/apps/web/src/components/InfographicEditorPane.test.mjs b/apps/web/src/components/InfographicEditorPane.test.mjs
index 67c68a78..6a0b975c 100644
--- a/apps/web/src/components/InfographicEditorPane.test.mjs
+++ b/apps/web/src/components/InfographicEditorPane.test.mjs
@@ -23,4 +23,14 @@ describe("infographic editor header", () => {
expect(source).not.toContain("MemoEditorUpdatedLabel");
expect(source).not.toContain("formatDateTime(memo.updatedAt)");
});
+
+ test("gives the preview the editor column and sends generation through the sidebar", () => {
+ expect(source).not.toContain("lg:grid-cols-[minmax(300px,34%)_1fr]");
+ expect(source).not.toContain('t("infographic.historyTitle")');
+ expect(source).not.toContain('id="infographic-prompt"');
+ expect(source).toContain("data-ai-assistant-launcher");
+ expect(source).toContain("<AiSidebar");
+ expect(source).toContain("infographic={infographicAssistant}");
+ expect(source).toContain("edgeever-infographic-preview");
+ });
});
diff --git a/apps/web/src/components/InfographicEditorPane.tsx b/apps/web/src/components/InfographicEditorPane.tsx
index 05d9d059..ff04936c 100644
--- a/apps/web/src/components/InfographicEditorPane.tsx
+++ b/apps/web/src/components/InfographicEditorPane.tsx
@@ -1,14 +1,14 @@
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { Check, ChevronLeft, FileCode2, FileImage, LoaderCircle, Pencil, Sparkles, Undo2 } from "lucide-react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { Check, ChevronLeft, 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 { Conversation, ConversationContent, ConversationScrollButton } from "@/components/ai-elements/conversation";
-import { Message, MessageContent, MessageResponse } from "@/components/ai-elements/message";
-import { EditorNoteSearchBar } from "@/components/editor/EditorNoteSearchBar";
+import { AiSidebar, readAiSidebarOpen, writeAiSidebarOpen } from "@/components/ai-sidebar/AiSidebar";
+import { AiSidebarErrorBoundary } from "@/components/ai-sidebar/AiSidebarErrorBoundary";
+import type { InfographicSidebarController } from "@/components/ai-sidebar/InfographicSidebarSession";
import { IconTooltip } from "@/components/editor/EditorPaneChrome";
import { MemoEditorHeaderActions } from "@/components/MemoEditorHeaderActions";
import { MemoEditorMetadataRow } from "@/components/MemoEditorMetadataRow";
@@ -17,7 +17,7 @@ import { MEMO_EDITOR_METADATA_ROW_CLASS_NAME, MEMO_EDITOR_TOP_ROW_CLASS_NAME, ne
import { MemoEditorToolbarDivider } from "@/components/MemoEditorToolbarChrome";
import { MemoTitleInput } from "@/components/MemoTitleInput";
import { api } from "@/lib/api";
-import { getNotebookMoveOptions } from "@/lib/app-helpers";
+import { formatShortcutBinding, getNotebookMoveOptions, type ShortcutSettings } from "@/lib/app-helpers";
import { createLocalEditSession, requiresLocalEditSession } from "@/components/editor/editor-pane-helpers";
import { buildInfographicSyntax, buildOfficialInfographicSyntax, infographicAgentCandidates, INFOGRAPHIC_TEMPLATES, parseGeneratedOfficialData, type InfographicItem } from "@/lib/infographic-generation";
import { statusSettleMotion } from "@/lib/motion";
@@ -34,6 +34,8 @@ type Props = {
onOpenExecutionCenter: () => void;
onSaved: (memo: MemoDetail) => Promise<void>;
onToggleDesktopFocusMode: () => void;
+ aiAssistantOpenToken: number;
+ shortcutSettings: ShortcutSettings;
};
const plainLine = (value: string) => value.replace(/\s+/g, " ").trim();
@@ -196,6 +198,8 @@ export default function InfographicEditorPane({
onOpenExecutionCenter,
onSaved,
onToggleDesktopFocusMode,
+ aiAssistantOpenToken,
+ shortcutSettings,
}: Props) {
const { t, i18n } = useTranslation();
const parsed = useMemo(() => parseInfographicDocument(memo.contentMarkdown), [memo.contentMarkdown]);
@@ -204,8 +208,8 @@ export default function InfographicEditorPane({
const [tagsText, setTagsText] = useState(initialTags);
const [syntax, setSyntax] = useState(parsed?.syntax ?? "");
const [history, setHistory] = useState<InfographicConversationTurn[]>(parsed?.history ?? []);
- const [prompt, setPrompt] = useState("");
const [activeTurn, setActiveTurn] = useState<{ prompt: string; response: string; template?: string; decision?: string; question?: string } | null>(null);
+ const [aiAssistantOpen, setAiAssistantOpenState] = useState(readAiSidebarOpen);
const [previousGeneration, setPreviousGeneration] = useState<{ title: string; syntax: string; turnId: string } | null>(null);
const [generating, setGenerating] = useState(false);
const [saving, setSaving] = useState(false);
@@ -220,16 +224,13 @@ export default function InfographicEditorPane({
const [headerTitleSlot, setHeaderTitleSlot] = useState<HTMLDivElement | null>(null);
const [headerStatusCluster, setHeaderStatusCluster] = useState<HTMLDivElement | null>(null);
const [titleStatusClearancePx, setTitleStatusClearancePx] = useState(0);
- const [searchOpen, setSearchOpen] = useState(false);
- const [searchQuery, setSearchQuery] = useState("");
- const [searchIndex, setSearchIndex] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const instanceRef = useRef<InfographicInstance | null>(null);
const sessionRef = useRef<MemoEditSession | null>(null);
const generationControllerRef = useRef<AbortController | null>(null);
+ const handledAiAssistantOpenTokenRef = useRef(aiAssistantOpenToken);
const memoRef = useRef(memo);
const tagsRef = useRef(initialTags);
- const searchInputRef = useRef<HTMLInputElement | null>(null);
const saveRef = useRef<() => boolean | Promise<boolean>>(() => false);
const snapshot = JSON.stringify([title, syntax, history, tagsText]);
const notebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
@@ -242,6 +243,18 @@ export default function InfographicEditorPane({
useEffect(() => () => generationControllerRef.current?.abort(), []);
+ const setAiSidebarOpen = useCallback((open: boolean) => {
+ setAiAssistantOpenState(open);
+ writeAiSidebarOpen(open);
+ }, []);
+
+ useEffect(() => {
+ if (handledAiAssistantOpenTokenRef.current === aiAssistantOpenToken) return;
+ handledAiAssistantOpenTokenRef.current = aiAssistantOpenToken;
+ if (readOnly) return;
+ setAiSidebarOpen(true);
+ }, [aiAssistantOpenToken, readOnly, setAiSidebarOpen]);
+
useEffect(() => {
if (readOnly) return;
let cancelled = false;
@@ -439,27 +452,10 @@ export default function InfographicEditorPane({
};
}, [dirty, headerStatusCluster, headerTitleSlot, saving]);
- const searchMatches = useMemo(() => {
- const query = searchQuery.trim().toLocaleLowerCase();
- if (!searchOpen || !query) return [];
- return history.filter((turn) => `${turn.prompt}\n${turn.response}\n${turn.resultTitle}`.toLocaleLowerCase().includes(query));
- }, [history, searchOpen, searchQuery]);
-
- useEffect(() => {
- setSearchIndex(0);
- }, [searchQuery, searchMatches.length]);
-
- const moveSearchMatch = (direction: -1 | 1) => {
- if (!searchMatches.length) return;
- const next = (searchIndex + direction + searchMatches.length) % searchMatches.length;
- setSearchIndex(next);
- document.querySelector(`[data-infographic-turn="${searchMatches[next]?.id}"]`)?.scrollIntoView({ block: "nearest" });
- };
-
- const generate = async () => {
- const message = prompt.trim();
- if (!message || generating || readOnly) return;
- setGenerating(true); setError(null); setActiveTurn({ prompt: message, response: "" });
+ const generate = async (message: string) => {
+ const promptText = message.trim();
+ if (!promptText || generating || readOnly) throw new Error("empty");
+ setGenerating(true); setError(null); setActiveTurn({ prompt: promptText, response: "" }); setAiSidebarOpen(true);
const controller = new AbortController();
generationControllerRef.current = controller;
let response = "";
@@ -472,10 +468,10 @@ export default function InfographicEditorPane({
const currentContent = existingTemplate && existingOptions.data
? JSON.stringify({ template: existingTemplate, data: existingOptions.data }) : syntax;
if (currentContent.length > INFOGRAPHIC_AGENT_SOURCE_MAX_LENGTH) throw new Error(t("infographic.contentTooLarge"));
- const candidates = infographicAgentCandidates(message, getTemplates(), existingTemplate);
+ const candidates = infographicAgentCandidates(promptText, getTemplates(), existingTemplate);
if (!candidates.length) throw new Error(t("infographic.aiInvalidResponse"));
await api.streamInfographicAgent({
- prompt: message,
+ prompt: promptText,
locale: i18n.resolvedLanguage,
...(existingTemplate ? { currentTemplate: existingTemplate } : {}),
currentContent,
@@ -497,6 +493,7 @@ export default function InfographicEditorPane({
}
if (event.type === "error") throw new Error(event.message);
} });
+ if (controller.signal.aborted) throw new DOMException("aborted", "AbortError");
if (proposal) {
const selected = proposal as { template: string; data: Record<string, unknown>; explanation: string };
if (!candidates.includes(selected.template)) throw new Error(t("infographic.aiInvalidResponse"));
@@ -509,7 +506,7 @@ export default function InfographicEditorPane({
const turnId = crypto.randomUUID();
setPreviousGeneration({ title, syntax, turnId });
setHistory((turns) => [...turns, {
- id: turnId, prompt: message, createdAt: new Date().toISOString(),
+ id: turnId, prompt: promptText, createdAt: new Date().toISOString(),
kind: syntax.trim() ? "refined" : "generated", resultTitle: generatedTitle,
response: (response.trim() || selected.explanation).slice(0, 4000), decision: selected.explanation.slice(0, 500), template: selected.template,
}]);
@@ -517,14 +514,14 @@ export default function InfographicEditorPane({
const previousGraphicTitle = String(existingOptions.data?.title ?? "").trim();
if (!title.trim() || title.trim() === t("infographic.name") || (previousGraphicTitle && title.trim() === previousGraphicTitle)) setTitle(generatedTitle);
} else if (question) {
- setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: message, createdAt: new Date().toISOString(), kind: "clarified", resultTitle: "", response: (response.trim() || question).slice(0, 4000) }]);
+ setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: promptText, createdAt: new Date().toISOString(), kind: "clarified", resultTitle: "", response: (response.trim() || question).slice(0, 4000) }]);
} else throw new Error(t("infographic.aiInvalidResponse"));
- setPrompt("");
} catch (caught) {
- if (controller.signal.aborted) return;
+ if (controller.signal.aborted) throw caught;
const messageText = caught instanceof Error ? caught.message : t("infographic.aiError");
setError(messageText);
- setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: message, createdAt: new Date().toISOString(), kind: "failed", resultTitle: "", response: response.slice(0, 4000), error: messageText.slice(0, 1000) }]);
+ setHistory((turns) => [...turns, { id: crypto.randomUUID(), prompt: promptText, createdAt: new Date().toISOString(), kind: "failed", resultTitle: "", response: response.slice(0, 4000), error: messageText.slice(0, 1000) }]);
+ throw caught instanceof Error ? caught : new Error(messageText);
} finally { if (generationControllerRef.current === controller) generationControllerRef.current = null; setActiveTurn(null); setGenerating(false); }
};
@@ -540,10 +537,20 @@ export default function InfographicEditorPane({
const saveStatus = saving ? "saving" : dirty ? "unsaved" : "saved";
const saveLabel = t(`editor.saveState.${saveStatus}`);
const saveStatusClassName = saveStatus === "saved" ? "text-slate-400" : "bg-slate-100 text-slate-700";
- const visibleHistory = !searchOpen || !searchQuery.trim() ? history : searchMatches;
- const activeSearchId = searchOpen && searchQuery.trim() ? searchMatches[searchIndex]?.id : undefined;
+ const infographicAssistant: InfographicSidebarController = {
+ turns: history,
+ activeTurn,
+ generating,
+ readOnly,
+ canUndo: Boolean(previousGeneration),
+ hasGraphic: Boolean(syntax.trim()),
+ onSubmit: generate,
+ onUndo: undoGeneration,
+ onStop: () => generationControllerRef.current?.abort(),
+ };
- return <div className="flex h-full min-h-0 flex-col bg-card text-foreground">
+ return <div className="relative flex h-full min-h-0 min-w-0 bg-card text-foreground">
+ <div className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col">
<header className="shrink-0 border-b border-slate-200 bg-card">
<div className={cn(MEMO_EDITOR_TOP_ROW_CLASS_NAME, "border-b-0")}>
<div className="min-w-0 w-full" style={titleStatusClearancePx > 0 ? { paddingRight: titleStatusClearancePx } : undefined}>
@@ -596,10 +603,6 @@ export default function InfographicEditorPane({
<MemoEditorHeaderActions
moreMenuClassName="w-48"
onOpenExecutionCenter={onOpenExecutionCenter}
- onSearch={() => {
- setSearchOpen(true);
- window.requestAnimationFrame(() => searchInputRef.current?.focus());
- }}
moreMenuItems={(
<>
<DropdownMenuItem disabled={!previewReady || Boolean(renderError)} onClick={() => void exportImage("svg")}>
@@ -616,64 +619,45 @@ export default function InfographicEditorPane({
</div>
</div>
</div>
- {searchOpen ? (
- <EditorNoteSearchBar
- inputRef={searchInputRef}
- query={searchQuery}
- replacement=""
- replaceOpen={false}
- readOnly
- matchCount={searchMatches.length}
- matchLabel={searchQuery.trim() ? `${searchMatches.length ? searchIndex + 1 : 0}/${searchMatches.length}` : ""}
- onQueryChange={setSearchQuery}
- onReplacementChange={() => undefined}
- onMoveMatch={moveSearchMatch}
- onReplaceAll={() => undefined}
- onClose={() => setSearchOpen(false)}
- />
- ) : null}
</header>
{error ? <p role="alert" className="border-b border-red-100 bg-red-50 px-5 py-2 text-sm text-red-700">{error}</p> : null}
- <div className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(300px,34%)_1fr]">
- <section className="flex min-h-[320px] max-h-[60vh] flex-col border-b border-slate-200 p-5 lg:min-h-0 lg:max-h-none lg:border-b-0 lg:border-r">
- <h2 className="mb-3 text-sm font-semibold text-slate-800">{t("infographic.historyTitle")}</h2>
- <Conversation className="min-h-0 flex-1" aria-label={t("infographic.historyTitle")}>
- <ConversationContent className="gap-4 p-0 pb-5">
- {visibleHistory.map((turn) => <div key={turn.id} data-infographic-turn={turn.id} className={cn("space-y-2", turn.id === activeSearchId && "rounded-xl ring-1 ring-slate-300")}>
- <Message from="user"><MessageContent className="whitespace-pre-wrap break-words group-[.is-user]:rounded-xl group-[.is-user]:bg-slate-100 group-[.is-user]:px-3 group-[.is-user]:py-2">{turn.prompt}</MessageContent></Message>
- <Message from="assistant"><MessageContent className="w-full rounded-xl border border-slate-200 bg-card px-3 py-2 text-foreground">
- <MessageResponse className="edgeever-infographic-chat-response break-words">{turn.response || (turn.kind === "clarified" ? t("infographic.historyClarified") : turn.kind === "failed" ? t("infographic.historyFailed") : t(turn.kind === "generated" ? "infographic.historyGenerated" : "infographic.historyRefined", { title: turn.resultTitle || t("infographic.name") }))}</MessageResponse>
- {turn.decision && turn.decision !== turn.response && <p className="text-xs text-slate-600">{turn.decision}</p>}
- {turn.template && <p className="text-xs text-slate-500">{turn.template}</p>}
- {turn.error && <p className="text-xs text-red-600">{turn.error}</p>}
- {turn.undoneAt && <p className="text-xs text-slate-500">{t("infographic.historyUndone")}</p>}
- <time className="block text-xs text-slate-500" dateTime={turn.createdAt}>{new Date(turn.createdAt).toLocaleString(i18n.resolvedLanguage)}</time>
- </MessageContent></Message>
- </div>)}
- {activeTurn && <div className="space-y-2" aria-live="polite">
- <Message from="user"><MessageContent className="whitespace-pre-wrap break-words group-[.is-user]:rounded-xl group-[.is-user]:bg-slate-100 group-[.is-user]:px-3 group-[.is-user]:py-2">{activeTurn.prompt}</MessageContent></Message>
- <Message from="assistant"><MessageContent className="w-full rounded-xl border border-slate-200 bg-card px-3 py-2 text-foreground">
- <MessageResponse className="edgeever-infographic-chat-response break-words" isAnimating={generating}>{activeTurn.response || activeTurn.question || t("infographic.generating")}</MessageResponse>
- {activeTurn.decision && activeTurn.decision !== activeTurn.response && <p className="text-xs text-slate-600">{activeTurn.decision}</p>}
- {activeTurn.template && <p className="text-xs text-slate-500">{activeTurn.template}</p>}
- </MessageContent></Message>
- </div>}
- </ConversationContent>
- <ConversationScrollButton aria-label={t("infographic.scrollToBottom")} />
- </Conversation>
- {!readOnly && <div className="shrink-0 rounded-xl border border-slate-200 bg-slate-50 p-4">
- <label className="mb-2 block text-sm font-medium text-slate-800" htmlFor="infographic-prompt"><Sparkles className="mr-1 inline h-4 w-4 text-slate-700" />{t(syntax.trim() ? "infographic.refine" : "infographic.describe")}</label>
- <textarea id="infographic-prompt" maxLength={1000} disabled={generating} className="min-h-24 w-full rounded-md border border-slate-200 bg-card p-3 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-slate-900/20 disabled:opacity-60" placeholder={t(syntax.trim() ? "infographic.refinePrompt" : "infographic.prompt")} value={prompt} onChange={(event) => setPrompt(event.target.value)} onKeyDown={(event) => {
- if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing || event.keyCode === 229) return;
- event.preventDefault();
- if (!event.repeat && prompt.trim() && !generating) void generate();
- }} />
- <div className="mt-2 flex flex-wrap items-center gap-2"><Button size="sm" disabled={!prompt.trim() || generating} onClick={() => void generate()}>{generating ? <LoaderCircle className="mr-1 h-4 w-4 animate-spin" /> : <Sparkles className="mr-1 h-4 w-4" />}{generating ? t("infographic.generating") : t(syntax.trim() ? "infographic.applyRefinement" : "infographic.generate")}</Button>
- {previousGeneration && <Button size="sm" variant="outline" onClick={undoGeneration}><Undo2 className="mr-1 h-4 w-4" />{t("infographic.undoGeneration")}</Button>}
- </div>
- </div>}
- </section>
- <section className="min-h-0 overflow-auto bg-slate-50 p-4"><div className={`min-h-[420px] rounded-xl border border-slate-200 p-4 shadow-sm ${previewUsesLightSheet ? "bg-white" : "bg-card"}`}><div ref={containerRef} className="edgeever-infographic-preview min-h-[380px] w-full" />{!syntax.trim() && <p className="pt-32 text-center text-sm text-muted-foreground">{t("infographic.noPreview")}</p>}{renderError && <p role="alert" className="text-sm text-destructive">{renderError}</p>}</div></section>
+ <section className="min-h-0 flex-1 overflow-auto bg-slate-50 p-4">
+ <div className={`relative flex min-h-full flex-col rounded-xl border border-slate-200 p-4 shadow-sm ${previewUsesLightSheet ? "bg-white" : "bg-card"}`}>
+ <div ref={containerRef} className="edgeever-infographic-preview min-h-[380px] w-full flex-1" />
+ {!syntax.trim() ? <p className="pointer-events-none absolute inset-0 flex items-center justify-center px-6 text-center text-sm text-muted-foreground">{t("infographic.noPreview")}</p> : null}
+ {renderError ? <p role="alert" className="text-sm text-destructive">{renderError}</p> : null}
+ </div>
+ </section>
+ {!readOnly && !aiAssistantOpen ? (
+ <IconTooltip
+ side="left"
+ label={`${t("aiAssistant.open")} (${formatShortcutBinding(shortcutSettings.openAiAssistant)})`}
+ >
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ data-ai-assistant-launcher=""
+ className="absolute bottom-[calc(1.25rem+env(safe-area-inset-bottom))] right-5 z-30 size-11 rounded-full border-slate-200 bg-card text-slate-950 shadow-[0_8px_24px_rgba(15,23,42,0.14)] hover:bg-card hover:text-slate-950"
+ aria-label={t("aiAssistant.open")}
+ onClick={() => setAiSidebarOpen(true)}
+ >
+ <Sparkles className="size-5" strokeWidth={1.75} />
+ </Button>
+ </IconTooltip>
+ ) : null}
</div>
+ <AiSidebarErrorBoundary open={aiAssistantOpen} onOpenChange={setAiSidebarOpen}>
+ <AiSidebar
+ open={aiAssistantOpen}
+ onOpenChange={setAiSidebarOpen}
+ companionAvailable={false}
+ contentMarkdown={syntax}
+ memoId={memo.id}
+ notebookId={memo.notebookId}
+ noteTitle={title}
+ infographic={infographicAssistant}
+ />
+ </AiSidebarErrorBoundary>
</div>;
}
diff --git a/apps/web/src/components/MemoEditorHeaderActions.tsx b/apps/web/src/components/MemoEditorHeaderActions.tsx
index 5751fbd9..174ee5ea 100644
--- a/apps/web/src/components/MemoEditorHeaderActions.tsx
+++ b/apps/web/src/components/MemoEditorHeaderActions.tsx
@@ -26,7 +26,7 @@ export const MemoEditorHeaderActions = ({
moreMenuClassName?: string;
moreMenuItems: ReactNode;
onOpenExecutionCenter: () => void;
- onSearch: () => void;
+ onSearch?: () => void;
textNoteActions?: ReactNode;
textNoteMenuItems?: ReactNode;
}) => {
@@ -63,13 +63,15 @@ export const MemoEditorHeaderActions = ({
className={cn("border border-slate-200 bg-card py-1 shadow-md", moreMenuClassName)}
>
{textNoteMenuItems}
- <DropdownMenuItem
- className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
- onClick={onSearch}
- >
- <Search className="h-4 w-4 text-slate-500" />
- {t("editor.searchCurrentMemo")}
- </DropdownMenuItem>
+ {onSearch ? (
+ <DropdownMenuItem
+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
+ onClick={onSearch}
+ >
+ <Search className="h-4 w-4 text-slate-500" />
+ {t("editor.searchCurrentMemo")}
+ </DropdownMenuItem>
+ ) : null}
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
onClick={() => setPreference(nextTheme)}
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index d0e447c2..0fd84de0 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -3557,6 +3557,8 @@ export const WorkspaceApp = ({
}}
onOpenExecutionCenter={handleOpenExecutionCenter}
onToggleDesktopFocusMode={toggleDesktopFocusMode}
+ aiAssistantOpenToken={noteAiAssistantOpenToken}
+ shortcutSettings={shortcutSettings}
onSaved={async (memo) => {
await putLocalMemo(localDataScope, memo);
cacheMemoDetail(queryClient, memo, memoView);
diff --git a/apps/web/src/components/ai-sidebar/AiSidebar.tsx b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
index 5252b12b..87c70153 100644
--- a/apps/web/src/components/ai-sidebar/AiSidebar.tsx
+++ b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
@@ -85,6 +85,7 @@ import { cn } from "@/lib/utils";
import { CompanionQuestionForm } from "../CompanionQuestionForm";
import { AiSidebarMessage } from "./AiSidebarMessage";
import { AiSidebarLocalProcess } from "./AiSidebarLocalProcess";
+import { InfographicSidebarSession, type InfographicSidebarController } from "./InfographicSidebarSession";
const SIDEBAR_DEFAULT_WIDTH = 380;
const sidebarThreadClassName = cn(
@@ -176,6 +177,7 @@ type AiSidebarProps = AiSidebarFocus & {
beforeCompanionApply?: () => Promise<void>;
onCompanionNotesChanged?: () => Promise<void>;
onOpenCompanionNote?: (id: string, notebookId: string) => void;
+ infographic?: InfographicSidebarController | null;
};
const SELECTION_TURN_STORAGE = "edgeever.aiSidebar.selectionTurns";
@@ -1840,7 +1842,15 @@ export function AiSidebar(props: AiSidebarProps) {
</Tooltip>
</TooltipProvider>
) : null}
- <AiSidebarSession {...props} addFilesRef={addFilesRef} onStopReady={onStopReady} />
+ {props.infographic ? (
+ <InfographicSidebarSession
+ session={props.infographic}
+ noteTitle={props.noteTitle}
+ onOpenChange={onOpenChange}
+ />
+ ) : (
+ <AiSidebarSession {...props} addFilesRef={addFilesRef} onStopReady={onStopReady} />
+ )}
</div>
</m.aside>
</>
diff --git a/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx b/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx
new file mode 100644
index 00000000..b3f78719
--- /dev/null
+++ b/apps/web/src/components/ai-sidebar/InfographicSidebarSession.tsx
@@ -0,0 +1,182 @@
+import { useTranslation } from "react-i18next";
+import { PanelRightClose, Sparkles, Undo2 } from "lucide-react";
+import type { InfographicConversationTurn } from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+import { Conversation, ConversationContent, ConversationEmptyState, ConversationScrollButton } from "@/components/ai-elements/conversation";
+import { Message, MessageContent, MessageResponse } from "@/components/ai-elements/message";
+import {
+ PromptInput,
+ PromptInputFooter,
+ PromptInputProvider,
+ PromptInputSubmit,
+ PromptInputTextarea,
+ PromptInputTools,
+ usePromptInputController,
+} from "@/components/ai-elements/prompt-input";
+import { cn } from "@/lib/utils";
+
+const threadClassName = cn(
+ "gap-3 p-3 text-[13px] leading-[1.6]",
+ "[&_[data-streamdown=heading-1]]:mt-3 [&_[data-streamdown=heading-1]]:mb-1 [&_[data-streamdown=heading-1]]:text-[15px] [&_[data-streamdown=heading-1]]:leading-snug",
+ "[&_[data-streamdown=heading-2]]:mt-3 [&_[data-streamdown=heading-2]]:mb-1 [&_[data-streamdown=heading-2]]:text-[15px] [&_[data-streamdown=heading-2]]:leading-snug",
+ "[&_[data-streamdown=heading-3]]:mt-2.5 [&_[data-streamdown=heading-3]]:mb-1 [&_[data-streamdown=heading-3]]:text-sm [&_[data-streamdown=heading-3]]:leading-snug",
+ "[&_[data-streamdown=inline-code]]:text-[12px]",
+);
+const userMessageClassName = "whitespace-pre-wrap break-words text-[13px] leading-5 group-[.is-user]:rounded-xl group-[.is-user]:bg-slate-100 group-[.is-user]:px-3 group-[.is-user]:py-2";
+
+export type InfographicSidebarTurn = {
+ prompt: string;
+ response: string;
+ template?: string;
+ decision?: string;
+ question?: string;
+};
+
+export type InfographicSidebarController = {
+ turns: InfographicConversationTurn[];
+ activeTurn: InfographicSidebarTurn | null;
+ generating: boolean;
+ readOnly: boolean;
+ canUndo: boolean;
+ hasGraphic: boolean;
+ onSubmit: (prompt: string) => Promise<void>;
+ onUndo: () => void;
+ onStop: () => void;
+};
+
+function InfographicSidebarComposer({ session }: { session: InfographicSidebarController }) {
+ const { t } = useTranslation();
+ const { textInput } = usePromptInputController();
+ const draft = textInput.value.trim();
+ return (
+ <PromptInput
+ onSubmit={async ({ text }) => {
+ const raw = text.trim().slice(0, 1000);
+ if (!raw || session.generating) throw new Error("empty");
+ await session.onSubmit(raw);
+ }}
+ >
+ <PromptInputTextarea
+ className="text-[13px] leading-5 md:text-[13px]"
+ disabled={session.generating}
+ maxLength={1000}
+ placeholder={t(session.hasGraphic ? "infographic.refinePrompt" : "infographic.prompt")}
+ />
+ <PromptInputFooter>
+ <PromptInputTools>
+ {session.canUndo ? (
+ <Button type="button" size="sm" variant="outline" disabled={session.generating} onClick={session.onUndo}>
+ <Undo2 className="mr-1 h-3.5 w-3.5" />
+ {t("infographic.undoGeneration")}
+ </Button>
+ ) : null}
+ </PromptInputTools>
+ {session.generating ? (
+ <Button type="button" size="sm" variant="outline" onClick={session.onStop}>
+ {t("aiAssistant.sidebar.stop")}
+ </Button>
+ ) : (
+ <PromptInputSubmit
+ aria-label={t(session.hasGraphic ? "infographic.applyRefinement" : "infographic.generate")}
+ className="border-slate-900 bg-slate-900 text-slate-50 hover:border-slate-800 hover:bg-slate-800"
+ disabled={!draft}
+ variant="solid"
+ />
+ )}
+ </PromptInputFooter>
+ </PromptInput>
+ );
+}
+
+export function InfographicSidebarSession({
+ session,
+ noteTitle,
+ onOpenChange,
+}: {
+ session: InfographicSidebarController;
+ noteTitle?: string;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const title = noteTitle?.trim() || t("infographic.name");
+ const reply = (turn: InfographicConversationTurn) => turn.response
+ || (turn.kind === "clarified"
+ ? t("infographic.historyClarified")
+ : turn.kind === "failed"
+ ? t("infographic.historyFailed")
+ : t(turn.kind === "generated" ? "infographic.historyGenerated" : "infographic.historyRefined", { title: turn.resultTitle || t("infographic.name") }));
+
+ return (
+ <div className="flex h-full min-h-0 min-w-0 flex-col bg-card" data-infographic-ai-sidebar="">
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b border-slate-200 px-2">
+ <span className="flex min-w-0 items-center gap-1.5 px-1.5 text-[13px] text-slate-800">
+ <Sparkles className="size-3.5 shrink-0" aria-hidden="true" />
+ <span className="truncate">{title}</span>
+ </span>
+ <Button
+ className="ml-auto"
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ title={t("aiAssistant.sidebar.close")}
+ aria-label={t("aiAssistant.sidebar.close")}
+ onClick={() => onOpenChange(false)}
+ >
+ <PanelRightClose className="h-4 w-4" />
+ </Button>
+ </div>
+ <Conversation className="min-h-0 flex-1" aria-label={t("infographic.historyTitle")}>
+ <ConversationContent className={threadClassName}>
+ {!session.turns.length && !session.activeTurn ? (
+ <ConversationEmptyState
+ icon={<Sparkles className="h-6 w-6" />}
+ title={t(session.hasGraphic ? "infographic.refine" : "infographic.describe")}
+ description={t(session.hasGraphic ? "infographic.refinePrompt" : "infographic.prompt")}
+ />
+ ) : null}
+ {session.turns.map((turn) => (
+ <div key={turn.id} data-infographic-turn={turn.id} className="space-y-2">
+ <Message from="user">
+ <MessageContent className={userMessageClassName}>{turn.prompt}</MessageContent>
+ </Message>
+ <Message from="assistant">
+ <MessageContent className="w-full text-foreground">
+ <MessageResponse className="edgeever-infographic-chat-response break-words">{reply(turn)}</MessageResponse>
+ {turn.decision && turn.decision !== turn.response ? <p className="text-xs text-slate-600">{turn.decision}</p> : null}
+ {turn.template ? <p className="text-xs text-slate-500">{turn.template}</p> : null}
+ {turn.error ? <p className="text-xs text-red-600">{turn.error}</p> : null}
+ {turn.undoneAt ? <p className="text-xs text-slate-500">{t("infographic.historyUndone")}</p> : null}
+ <time className="block text-xs text-slate-500" dateTime={turn.createdAt}>{new Date(turn.createdAt).toLocaleString(i18n.resolvedLanguage)}</time>
+ </MessageContent>
+ </Message>
+ </div>
+ ))}
+ {session.activeTurn ? (
+ <div className="space-y-2" aria-live="polite">
+ <Message from="user">
+ <MessageContent className={userMessageClassName}>{session.activeTurn.prompt}</MessageContent>
+ </Message>
+ <Message from="assistant">
+ <MessageContent className="w-full text-foreground">
+ <MessageResponse className="edgeever-infographic-chat-response break-words" isAnimating={session.generating}>
+ {session.activeTurn.response || session.activeTurn.question || t("infographic.generating")}
+ </MessageResponse>
+ {session.activeTurn.decision && session.activeTurn.decision !== session.activeTurn.response ? <p className="text-xs text-slate-600">{session.activeTurn.decision}</p> : null}
+ {session.activeTurn.template ? <p className="text-xs text-slate-500">{session.activeTurn.template}</p> : null}
+ </MessageContent>
+ </Message>
+ </div>
+ ) : null}
+ </ConversationContent>
+ <ConversationScrollButton aria-label={t("infographic.scrollToBottom")} />
+ </Conversation>
+ {!session.readOnly ? (
+ <div className="shrink-0 border-t border-slate-200 p-3">
+ <PromptInputProvider>
+ <InfographicSidebarComposer session={session} />
+ </PromptInputProvider>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs b/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs
index 20981d64..5c3feb78 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.test.mjs
@@ -14,6 +14,8 @@ describe("AI assistant modes", () => {
expect(sidebar).toContain("sidebarRevealTransition");
expect(sidebar).not.toContain("{open && <AiSidebarSession");
expect(sidebar).not.toContain("hidden w-0");
+ expect(sidebar).toContain("props.infographic ? (");
+ expect(sidebar).toContain("<InfographicSidebarSession");
});
test("agent mode opens a fresh thread and only resumes last chat on request", () => {