Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(editor): render html and mermaid blocks in the editor as dynamic blocks (MUL-9760) (#11163)

Jiayuan Zhangab620050945c
diff --git a/packages/views/editor/dynamic-block.tsx b/packages/views/editor/dynamic-block.tsx
index 45b18bad2a..c7430835dd 100644
--- a/packages/views/editor/dynamic-block.tsx
+++ b/packages/views/editor/dynamic-block.tsx
@@ -15,6 +15,9 @@
*
* The kinds supply only the preview; the frame owns the chrome, the source
* view and the error panel.
+ *
+ * The editor draws the same frame (MUL-9760); see DynamicBlockEditing for what
+ * differs there.
*/
import {
@@ -39,8 +42,10 @@ import {
import { Button } from "@multica/ui/components/ui/button";
import { IconButton } from "@multica/ui/components/common/icon-button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { Spinner } from "@multica/ui/components/ui/spinner";
import { copyText } from "@multica/ui/lib/clipboard";
+import { isImeComposing } from "@multica/core/utils";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../i18n";
import { CodeBlockStatic } from "./code-block-static";
@@ -77,7 +82,40 @@ export interface DynamicBlockError {
line?: number;
}
-type DynamicBlockView = "preview" | "source";
+export type DynamicBlockView = "preview" | "source";
+
+/**
+ * The block inside the editor (Docs, an issue description being edited). It
+ * is the read-only frame with three differences: the source view is
+ * ProseMirror's own editable `<pre>`, the title can be renamed in place, and
+ * the NodeView owns the view, because it has to keep the caret out of a
+ * source the preview is hiding.
+ */
+export interface DynamicBlockEditing {
+ /**
+ * The editable source. Mounted for the block's whole life and only hidden
+ * behind the preview: ProseMirror owns its DOM, and unmounting it would
+ * break editing.
+ */
+ source: ReactNode;
+ view: DynamicBlockView;
+ onViewChange: (view: DynamicBlockView) => void;
+ /** Writes the title back to the fence; absent while the editor is read-only. */
+ onTitleChange?: (title: string) => void;
+ /** The block is node-selected: outline it and keep its actions up. */
+ selected?: boolean;
+}
+
+/**
+ * `value` while `visible`, else the last value that was shown. A hidden
+ * preview is not rebuilt on every keystroke in the source; it catches up the
+ * moment it is shown again.
+ */
+export function useValueWhileVisible<T>(value: T, visible: boolean): T {
+ const [shown, setShown] = useState(value);
+ if (visible && shown !== value) setShown(value);
+ return visible ? value : shown;
+}
interface DynamicBlockProps {
kind: DynamicBlockKind;
@@ -112,6 +150,8 @@ interface DynamicBlockProps {
* for previews the frame must measure (mermaid).
*/
bodyHeight?: number | null;
+ /** Set inside the editor. */
+ editing?: DynamicBlockEditing;
className?: string;
}
@@ -126,10 +166,13 @@ export function DynamicBlock({
fullscreenButtonRef,
preview,
bodyHeight,
+ editing,
className,
}: DynamicBlockProps) {
const { t } = useT("editor");
- const [view, setView] = useState<DynamicBlockView>("preview");
+ const [ownView, setOwnView] = useState<DynamicBlockView>("preview");
+ const view = editing?.view ?? ownView;
+ const setView = editing?.onViewChange ?? setOwnView;
const [copied, setCopied] = useState(false);
const [expanded, setExpanded] = useState(false);
// Overflow state for previews the frame must measure itself (mermaid). A
@@ -164,8 +207,11 @@ export function DynamicBlock({
const kindLabel = KIND_LABEL[kind];
const trimmedTitle = title?.trim();
// The actions stay up while they carry state the reader has to see: the
- // source view (Preview is how to get back) and the copy confirmation.
- const actionsPinned = view === "source" || copied;
+ // source view (Preview is how to get back) and the copy confirmation. In the
+ // editor they also stay up on a node-selected block, which has no hover.
+ const actionsPinned = view === "source" || copied || !!editing?.selected;
+ // Chrome inside a NodeView must not be editable text; the source must be.
+ const chromeEditable = editing ? false : undefined;
const handleCopy = async () => {
if (await copyText(source)) {
@@ -179,24 +225,39 @@ export function DynamicBlock({
value={view}
onValueChange={(value) => setView(value as DynamicBlockView)}
data-dynamic-block={kind}
+ // Read by the editor's arrow keys (CodeBlockExtension).
+ data-dynamic-block-view={editing ? view : undefined}
// No outer margin: the lazy shell around the block owns that spacing.
className={cn(
"group/dynamic-block gap-0 overflow-hidden rounded-lg border bg-surface shadow-[var(--surface-shadow)]",
error && view === "preview" && "border-destructive/35",
+ editing?.selected && "outline-2 outline-offset-2 outline-brand",
className,
)}
>
- <div className="flex h-9 items-center gap-2 border-b pr-1.5 pl-3">
+ <div
+ contentEditable={chromeEditable}
+ suppressContentEditableWarning
+ className="flex h-9 items-center gap-2 border-b pr-1.5 pl-3"
+ >
<Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
{/* With no title, the kind name stands in and the chip would repeat it. */}
- <span
- className={cn(
- "min-w-0 truncate text-label font-medium",
- !trimmedTitle && "text-muted-foreground",
- )}
- >
- {trimmedTitle || kindLabel}
- </span>
+ {editing?.onTitleChange ? (
+ <DynamicBlockTitleInput
+ title={trimmedTitle ?? null}
+ kindLabel={kindLabel}
+ onChange={editing.onTitleChange}
+ />
+ ) : (
+ <span
+ className={cn(
+ "min-w-0 truncate text-label font-medium",
+ !trimmedTitle && "text-muted-foreground",
+ )}
+ >
+ {trimmedTitle || kindLabel}
+ </span>
+ )}
{trimmedTitle && (
<span className="inline-flex h-[18px] shrink-0 items-center rounded-sm bg-secondary px-1.5 text-micro text-muted-foreground">
{kindLabel}
@@ -270,6 +331,8 @@ export function DynamicBlock({
keepMounted
hidden={!fullscreen && view !== "preview"}
inert={!fullscreen && view !== "preview"}
+ contentEditable={chromeEditable}
+ suppressContentEditableWarning
>
{error && view === "preview" && (
<DynamicBlockErrorPanel
@@ -288,19 +351,104 @@ export function DynamicBlock({
</CollapsibleBody>
</div>
</TabsContent>
- <TabsContent value="source">
- <SelfCollapsingBody>
- <CodeBlockStatic
- language={SOURCE_LANGUAGE[kind]}
- body={source}
- className="!m-0 !rounded-none !bg-muted"
- />
- </SelfCollapsingBody>
- </TabsContent>
+ {editing ? (
+ // display:none rather than a 1px visually-hidden box, where the
+ // source would wrap every character onto its own line: tens of
+ // thousands of pixels of layout for a chart. The NodeView keeps the
+ // caret out while it is hidden. Shown, it does not collapse: the
+ // caret must never sit in a clipped line.
+ <div data-dynamic-block-source="" hidden={view !== "source"}>
+ {editing.source}
+ </div>
+ ) : (
+ <TabsContent value="source">
+ <SelfCollapsingBody>
+ <CodeBlockStatic
+ language={SOURCE_LANGUAGE[kind]}
+ body={source}
+ className="!m-0 !rounded-none !bg-muted"
+ />
+ </SelfCollapsingBody>
+ </TabsContent>
+ )}
</Tabs>
);
}
+/**
+ * The editor's title: reads like the read-only title, renames in place on
+ * click. Enter or leaving the field saves; Escape keeps the old title. A blank
+ * title removes the attribute, and the kind name stands in again.
+ */
+function DynamicBlockTitleInput({
+ title,
+ kindLabel,
+ onChange,
+}: {
+ title: string | null;
+ kindLabel: string;
+ onChange: (title: string) => void;
+}) {
+ const { t } = useT("editor");
+ const [draft, setDraft] = useState<string | null>(null);
+ // Escape unmounts the field, which blurs it; the blur must not save.
+ const discarded = useRef(false);
+
+ const commit = (value: string) => {
+ setDraft(null);
+ if (discarded.current) {
+ discarded.current = false;
+ return;
+ }
+ const next = value.trim();
+ if (next !== (title ?? "")) onChange(next);
+ };
+
+ if (draft != null) {
+ return (
+ <input
+ autoFocus
+ value={draft}
+ placeholder={kindLabel}
+ aria-label={t(($) => $.dynamic_block.title)}
+ onFocus={(event) => event.currentTarget.select()}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={(event) => commit(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (isImeComposing(event)) return;
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.currentTarget.blur();
+ } else if (event.key === "Escape") {
+ // Escape cancels the rename only; it must not also close or
+ // leave whatever surface holds the editor.
+ event.preventDefault();
+ event.stopPropagation();
+ discarded.current = true;
+ event.currentTarget.blur();
+ }
+ }}
+ className="-mx-1 h-6 min-w-0 flex-1 rounded-sm bg-transparent px-1 text-label font-medium outline-none ring-1 ring-ring placeholder:text-muted-foreground"
+ />
+ );
+ }
+
+ return (
+ <TooltipHint label={title ? t(($) => $.dynamic_block.rename) : t(($) => $.dynamic_block.add_title)}>
+ <button
+ type="button"
+ onClick={() => setDraft(title ?? "")}
+ className={cn(
+ "-mx-1 min-w-0 truncate rounded-sm px-1 text-left text-label font-medium transition-colors hover:bg-accent",
+ !title && "text-muted-foreground",
+ )}
+ >
+ {title || kindLabel}
+ </button>
+ </TooltipHint>
+ );
+}
+
/**
* Clips the preview body past DYNAMIC_BLOCK_COLLAPSE_AT_PX with a fade and
* "Show all". Whether to clip is decided by the frame (`collapsed`): either
diff --git a/packages/views/editor/extensions/code-block-view.clipboard.test.tsx b/packages/views/editor/extensions/code-block-view.clipboard.test.tsx
index a616df8fd6..460a102960 100644
--- a/packages/views/editor/extensions/code-block-view.clipboard.test.tsx
+++ b/packages/views/editor/extensions/code-block-view.clipboard.test.tsx
@@ -15,7 +15,10 @@ import { CodeBlockView } from "./code-block-view";
const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, "clipboard");
-vi.mock("../mermaid-diagram", () => ({ MermaidDiagram: () => null }));
+vi.mock("../mermaid-diagram", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../mermaid-diagram")>()),
+ MermaidDiagram: () => null,
+}));
vi.mock("../../i18n", () => ({
useT: () => ({
t: (select: (value: unknown) => string) =>
diff --git a/packages/views/editor/extensions/code-block-view.test.tsx b/packages/views/editor/extensions/code-block-view.test.tsx
index 05c7056199..4a0d602f00 100644
--- a/packages/views/editor/extensions/code-block-view.test.tsx
+++ b/packages/views/editor/extensions/code-block-view.test.tsx
@@ -1,31 +1,19 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- act,
- cleanup,
- fireEvent,
- render,
- screen,
- within,
-} from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { EditorContent, useEditor, type Editor } from "@tiptap/react";
+import type { JSONContent } from "@tiptap/core";
+import { NodeSelection, TextSelection } from "@tiptap/pm/state";
+import { useEffect } from "react";
import { mockNativeDialog } from "../test-utils/native-dialog";
+import { HTML_BLOCK_MESSAGE_KEY } from "../utils/html-block-document";
-// Tiptap's NodeView primitives are hard to instantiate in jsdom without a
-// full editor. Stub them so the test can render <CodeBlockView /> as a plain
-// React component and inspect the resulting DOM shape.
-vi.mock("@tiptap/react", () => {
- const NodeViewWrapper = ({ children, ...rest }: any) => (
- <div data-testid="nvw" {...rest}>
- {children}
- </div>
- );
- // The real NodeViewContent renders an element managed by ProseMirror. For
- // the test it's enough to surface a sentinel element so we can assert it
- // remains mounted while CSS-hidden.
- const NodeViewContent = ({ as = "div", ...rest }: any) => {
- const Tag = as;
- return <Tag data-testid="nvc" {...rest} />;
+vi.mock("../../i18n", async () => {
+ const editor = (await import("../../locales/en/editor.json")).default;
+ return {
+ useT: () => ({
+ t: (select: (bundle: typeof editor) => string) => select(editor),
+ }),
};
- return { NodeViewWrapper, NodeViewContent };
});
// jsdom resolves no theme, so the embed theme reports a scheme the test sets.
@@ -37,235 +25,339 @@ vi.mock("../../common/embed-theme", () => ({
}),
}));
-vi.mock("../mermaid-diagram", () => ({
- MermaidDiagram: () => null,
+vi.mock("../mermaid-diagram", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../mermaid-diagram")>()),
+ MermaidDiagram: ({ chart }: { chart: string }) => <div data-testid="diagram">{chart}</div>,
}));
-vi.mock("../../i18n", () => ({
- useT: () => ({
- t: (sel: (s: Record<string, Record<string, string>>) => string) =>
- sel({
- code_block: {
- html_preview: "Localized HTML preview",
- copy_code: "Copy code",
- show_preview: "Show preview",
- show_source: "Show source",
- fullscreen: "Fullscreen",
- close_preview: "Close",
- },
- attachment: { reload: "Reload" },
+import { createEditorExtensions } from ".";
+
+function TestEditor({ content, onEditor }: { content: JSONContent[]; onEditor: (editor: Editor) => void }) {
+ // The editor's real extension set, so other keymaps get their turn first.
+ const editor = useEditor({
+ extensions: createEditorExtensions({ disableMentions: true }),
+ content: { type: "doc", content },
+ });
+ useEffect(() => {
+ if (editor) onEditor(editor);
+ }, [editor, onEditor]);
+ return <EditorContent editor={editor} />;
+}
+
+const paragraph = (text: string): JSONContent => ({ type: "paragraph", content: [{ type: "text", text }] });
+const codeBlock = (language: string, text: string, meta: string | null = null): JSONContent => ({
+ type: "codeBlock",
+ attrs: { language, meta },
+ content: text ? [{ type: "text", text }] : [],
+});
+
+/** "before" paragraph (8) puts the block at 8; its text starts at 9. */
+const BLOCK_POS = 8;
+
+async function mount(block: JSONContent, around: { before?: JSONContent[]; after?: JSONContent[] } = {}) {
+ let editor: Editor | undefined;
+ const content = [...(around.before ?? [paragraph("before")]), block, ...(around.after ?? [paragraph("after")])];
+ render(<TestEditor content={content} onEditor={(e) => (editor = e)} />);
+ await waitFor(() => expect(document.querySelector("[data-dynamic-code-block], pre")).not.toBeNull());
+ return editor!;
+}
+
+function frame(): HTMLIFrameElement {
+ const iframe = document.querySelector<HTMLIFrameElement>('[data-dynamic-block="html"] iframe');
+ expect(iframe).not.toBeNull();
+ return iframe!;
+}
+
+function sourceRegion(): HTMLElement {
+ return document.querySelector<HTMLElement>("[data-dynamic-block-source]")!;
+}
+
+function postHeight(height: number) {
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { [HTML_BLOCK_MESSAGE_KEY]: 1, type: "height", height },
+ source: frame().contentWindow,
}),
- }),
-}));
+ );
+ });
+}
-import { CodeBlockView } from "./code-block-view";
+function press(editor: Editor, key: string) {
+ return act(async () => {
+ fireEvent.keyDown(editor.view.dom, { key });
+ });
+}
-function makeProps(language: string, text: string) {
- return {
- node: {
- attrs: { language },
- textContent: text,
- },
- } as unknown as Parameters<typeof CodeBlockView>[0];
+function select(editor: Editor, pos: number) {
+ return act(async () => {
+ editor.commands.setTextSelection(pos);
+ });
+}
+
+/** Top-level node texts, so a join or a lost paragraph shows. */
+function blocks(editor: Editor): string[] {
+ const out: string[] = [];
+ editor.state.doc.forEach((node) => out.push(`${node.type.name}:${node.textContent}`));
+ return out;
}
-describe("CodeBlockView — html language toggle", () => {
- let restoreDialog: () => void;
- // Inner async timers in useDebouncedValue make the iframe srcDoc lag by
- // ~200ms; use fake timers so the test stays deterministic.
- beforeEach(() => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- restoreDialog = mockNativeDialog();
+function blockMeta(editor: Editor): string | null {
+ return editor.state.doc.nodeAt(BLOCK_POS)?.attrs.meta ?? null;
+}
+
+const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 300)));
+
+let restoreDialog: () => void;
+beforeEach(() => {
+ window.sessionStorage.clear();
+ restoreDialog = mockNativeDialog();
+});
+afterEach(() => {
+ cleanup();
+ restoreDialog();
+ embedScheme.current = "light";
+ document.documentElement.classList.remove("dark");
+ vi.restoreAllMocks();
+});
+
+describe("CodeBlockView — ```html in the editor", () => {
+ it("draws the dynamic block: a title bar with the fence title over the preview", async () => {
+ await mount(codeBlock("html", "<p>hi</p>", 'title="Weekly p95"'));
+ expect(screen.getByRole("button", { name: "Weekly p95" })).toBeTruthy();
+ expect(screen.getByText("HTML")).toBeTruthy();
+ expect(screen.getByRole("tab", { name: "Preview" }).getAttribute("aria-selected")).toBe("true");
+ expect(frame().getAttribute("sandbox")).toBe("allow-scripts");
+ expect(frame().className).not.toContain("h-[480px]");
+ // The editable source stays mounted under the preview, only hidden.
+ const code = sourceRegion().querySelector("pre code");
+ expect(code?.textContent).toBe("<p>hi</p>");
+ expect(sourceRegion().hidden).toBe(true);
});
- afterEach(() => {
- cleanup();
- vi.useRealTimers();
- restoreDialog();
+
+ it("names the block after its kind when the fence has no title", async () => {
+ await mount(codeBlock("html", "<p>hi</p>"));
+ expect(screen.getByRole("button", { name: "HTML" })).toBeTruthy();
});
- it("defaults to preview view: renders an iframe with sandbox='allow-scripts' and keeps the <pre> mounted (hidden)", () => {
- render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
- act(() => {
- vi.advanceTimersByTime(250);
- });
- const frame = document.querySelector("iframe");
- expect(frame).toBeTruthy();
- expect(frame?.getAttribute("title")).toBe("Localized HTML preview");
- expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
- // NodeViewContent (and its enclosing <pre>) MUST remain mounted —
- // unmounting would break Tiptap's bindings and prevent editing.
- const nvc = screen.getByTestId("nvc");
- expect(nvc).toBeTruthy();
- const pre = nvc.closest("pre");
- expect(pre).toBeTruthy();
- expect(pre?.className).toContain("sr-only");
+ it("takes its content's height and collapses a tall document", async () => {
+ await mount(codeBlock("html", "<p>hi</p>"));
+ postHeight(200);
+ expect(frame().parentElement!.style.height).toBe("200px");
+ expect(screen.queryByRole("button", { name: "Show all" })).toBeNull();
+
+ postHeight(900);
+ expect(frame().parentElement!.style.height).toBe("900px");
+ expect(document.querySelector<HTMLElement>("[data-collapsed]")!.style.maxHeight).toBe("480px");
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+ expect(document.querySelector("[data-collapsed]")).toBeNull();
});
- it("gives the preview the embed tokens, like a read-only html block", () => {
- render(
- <CodeBlockView {...makeProps("html", '<p style="color: var(--foreground)">hi</p>')} />,
- );
+ it("edits in the source view; the hidden preview catches up when shown", async () => {
+ const editor = await mount(codeBlock("html", "<p>first</p>"));
+ const original = frame().getAttribute("srcdoc");
+ fireEvent.click(screen.getByRole("tab", { name: "Source" }));
+ expect(sourceRegion().hidden).toBe(false);
+ expect(frame().closest("[hidden]")).not.toBeNull();
+
act(() => {
- vi.advanceTimersByTime(250);
+ editor.view.dispatch(editor.state.tr.insertText("<b>new</b>", BLOCK_POS + 1));
});
- const srcdoc = document.querySelector("iframe")?.getAttribute("srcdoc") ?? "";
- expect(srcdoc).toMatch(/^<style>:root\{[^}]*--color-scheme:light;color-scheme:light\}<\/style>/);
- expect(srcdoc).toContain('<p style="color: var(--foreground)">hi</p>');
+ await settle();
+ // Not rebuilt while nobody can see it.
+ expect(frame().getAttribute("srcdoc")).toBe(original);
+
+ fireEvent.click(screen.getByRole("tab", { name: "Preview" }));
+ await waitFor(() => expect(frame().getAttribute("srcdoc")).toContain("<b>new</b><p>first</p>"));
});
- it("keeps the document of HTML that reads no token across a theme switch", async () => {
- render(<CodeBlockView {...makeProps("html", '<input value="initial">')} />);
+ it("enlarges the latest source from the source view", async () => {
+ const editor = await mount(codeBlock("html", "<p>first</p>"));
+ fireEvent.click(screen.getByRole("tab", { name: "Source" }));
act(() => {
- vi.advanceTimersByTime(250);
+ editor.view.dispatch(editor.state.tr.insertText("<i>x</i>", BLOCK_POS + 1));
});
- const frame = document.querySelector("iframe")!;
- const before = frame.getAttribute("srcdoc");
- expect(before).toMatch(/^<style>:root\{\}<\/style>/);
+ await settle();
+ fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
+ await waitFor(() =>
+ expect(screen.getByRole("dialog").querySelector("iframe")?.getAttribute("srcdoc")).toContain("<i>x</i>"),
+ );
+ });
- embedScheme.current = "dark";
- document.documentElement.classList.add("dark");
- await act(() => Promise.resolve());
- expect(document.querySelector("iframe")).toBe(frame);
- expect(frame.getAttribute("srcdoc")).toBe(before);
- document.documentElement.classList.remove("dark");
- embedScheme.current = "light";
+ it("opens an empty block in the source view", async () => {
+ await mount(codeBlock("html", ""));
+ expect(screen.getByRole("tab", { name: "Source" }).getAttribute("aria-selected")).toBe("true");
+ expect(sourceRegion().hidden).toBe(false);
});
- it("rebuilds the document of HTML that reads a token when the theme switches", async () => {
- render(<CodeBlockView {...makeProps("html", '<p style="color: var(--foreground)">hi</p>')} />);
- act(() => {
- vi.advanceTimersByTime(250);
- });
- const frame = document.querySelector("iframe")!;
- expect(frame.getAttribute("srcdoc")).toContain("color-scheme:light");
+ it("renames from the title bar and keeps the rest of the info string", async () => {
+ const editor = await mount(codeBlock("html", "<p>hi</p>", 'title="Weekly p95" theme=dark'));
+ fireEvent.click(screen.getByRole("button", { name: "Weekly p95" }));
+ const input = screen.getByRole("textbox", { name: "Title" }) as HTMLInputElement;
+ expect(input.value).toBe("Weekly p95");
+ fireEvent.change(input, { target: { value: "Daily p95" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(blockMeta(editor)).toBe('title="Daily p95" theme=dark');
+ expect(await screen.findByRole("button", { name: "Daily p95" })).toBeTruthy();
+ });
- embedScheme.current = "dark";
- document.documentElement.classList.add("dark");
- await act(() => Promise.resolve());
- expect(frame.getAttribute("srcdoc")).toContain("color-scheme:dark");
- document.documentElement.classList.remove("dark");
- embedScheme.current = "light";
+ it("adds a title to an untitled block, and Escape discards a rename", async () => {
+ const editor = await mount(codeBlock("html", "<p>hi</p>"));
+ fireEvent.click(screen.getByRole("button", { name: "HTML" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "Title" }), { target: { value: "Funnel" } });
+ fireEvent.keyDown(screen.getByRole("textbox", { name: "Title" }), { key: "Enter" });
+ expect(blockMeta(editor)).toBe('title="Funnel"');
+
+ fireEvent.click(await screen.findByRole("button", { name: "Funnel" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "Title" }), { target: { value: "Other" } });
+ fireEvent.keyDown(screen.getByRole("textbox", { name: "Title" }), { key: "Escape" });
+ expect(blockMeta(editor)).toBe('title="Funnel"');
+ expect(screen.getByRole("button", { name: "Funnel" })).toBeTruthy();
});
- it("toggles to source view without unloading the preview or editor content", () => {
- render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
- act(() => {
- vi.advanceTimersByTime(250);
+ it("selects a previewed block whole instead of putting the caret in its hidden source", async () => {
+ const editor = await mount(codeBlock("html", "<p>hi</p>"));
+ await act(async () => {
+ editor.commands.setTextSelection(BLOCK_POS + 3);
});
- const frame = document.querySelector("iframe");
- expect(frame).toBeTruthy();
- const toggle = screen.getByRole("button", { name: "Show source" });
- fireEvent.click(toggle);
- expect(document.querySelector("iframe")).toBe(frame);
- expect(frame?.closest("[hidden]")).toBeTruthy();
- const nvc = screen.getByTestId("nvc");
- const pre = nvc.closest("pre")!;
- expect(pre.className).not.toContain("sr-only");
+ const { selection } = editor.state;
+ expect(selection).toBeInstanceOf(NodeSelection);
+ expect(selection.from).toBe(BLOCK_POS);
+
+ // Enter opens the source with the caret at its start.
+ await act(async () => {
+ fireEvent.keyDown(editor.view.dom, { key: "Enter" });
+ });
+ expect(screen.getByRole("tab", { name: "Source" }).getAttribute("aria-selected")).toBe("true");
+ expect(editor.state.selection).toBeInstanceOf(TextSelection);
+ expect(editor.state.selection.from).toBe(BLOCK_POS + 1);
+ expect(editor.state.doc.nodeAt(BLOCK_POS)?.textContent).toBe("<p>hi</p>");
});
- it("opens the current HTML in a larger sandboxed preview without replacing editor content", () => {
- const { rerender } = render(
- <CodeBlockView {...makeProps("html", "<p>first</p>")} />,
- );
- act(() => {
- vi.advanceTimersByTime(250);
+ it("selects a previewed block whole when the arrow keys reach it", async () => {
+ const editor = await mount(codeBlock("html", "<p>hi</p>"));
+ // jsdom has no layout; every caret here sits on its textblock's edge.
+ vi.spyOn(editor.view, "endOfTextblock").mockReturnValue(true);
+
+ await act(async () => {
+ editor.commands.setTextSelection(3);
});
- const editorContent = screen.getByTestId("nvc");
- rerender(<CodeBlockView {...makeProps("html", "<p>latest</p>")} />);
- act(() => {
- vi.advanceTimersByTime(250);
+ await press(editor, "ArrowDown");
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
+ expect(editor.state.selection.from).toBe(BLOCK_POS);
+
+ const after = BLOCK_POS + editor.state.doc.nodeAt(BLOCK_POS)!.nodeSize + 1;
+ await act(async () => {
+ editor.commands.setTextSelection(after);
});
- const original = document.querySelector("iframe");
- const opener = screen.getByRole("button", { name: "Fullscreen" });
- fireEvent.click(opener);
- const dialog = screen.getByRole("dialog", {
- name: "Localized HTML preview",
+ await press(editor, "ArrowUp");
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
+ expect(editor.state.selection.from).toBe(BLOCK_POS);
+
+ // A block showing its source is ordinary text to move through.
+ fireEvent.click(screen.getByRole("tab", { name: "Source" }));
+ await act(async () => {
+ editor.commands.setTextSelection(3);
});
- const frame = dialog.querySelector("iframe");
- expect(frame).toBe(original);
- expect(document.querySelectorAll("iframe")).toHaveLength(1);
- expect(frame?.getAttribute("srcdoc")).toContain("<p>latest</p>");
- expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
- expect(screen.getByTestId("nvc")).toBe(editorContent);
- expect(document.querySelector("iframe")).toBe(original);
- fireEvent.click(screen.getByRole("button", { name: "Close" }));
- act(() => {
- vi.advanceTimersByTime(250);
+ await press(editor, "ArrowDown");
+ expect(editor.state.selection).toBeInstanceOf(TextSelection);
+ });
+
+ it("selects a previewed block on Backspace or Delete instead of joining its hidden source", async () => {
+ const editor = await mount(codeBlock("html", "<p>hi</p>"));
+ const original = blocks(editor);
+ const afterStart = BLOCK_POS + editor.state.doc.nodeAt(BLOCK_POS)!.nodeSize + 1;
+
+ // Backspace at the start of the next paragraph would append it to the source.
+ await select(editor, afterStart);
+ await press(editor, "Backspace");
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
+ expect(editor.state.selection.from).toBe(BLOCK_POS);
+ expect(blocks(editor)).toEqual(original);
+
+ // Delete at the end of the previous paragraph would pull the source into it.
+ await select(editor, BLOCK_POS - 1);
+ await press(editor, "Delete");
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
+ expect(editor.state.selection.from).toBe(BLOCK_POS);
+ expect(blocks(editor)).toEqual(original);
+ });
+
+ it("removes an empty paragraph beside a previewed block and selects the block", async () => {
+ const empty: JSONContent = { type: "paragraph" };
+ const editor = await mount(codeBlock("html", "<p>hi</p>"), {
+ before: [paragraph("before"), empty],
+ after: [empty, paragraph("after")],
});
- expect(screen.queryByRole("dialog")).toBeNull();
- expect(screen.getByTestId("nvc")).toBe(editorContent);
- fireEvent.click(opener);
- expect(screen.getByRole("dialog").querySelector("iframe")).toBe(original);
- fireEvent.click(screen.getByRole("button", { name: "Close" }));
- fireEvent.click(screen.getByRole("button", { name: "Show source" }));
- expect(editorContent.closest("pre")?.className).not.toContain("sr-only");
- fireEvent.click(opener);
- expect(screen.getByRole("dialog").querySelector("iframe")).toBe(original);
- expect(original?.closest("[hidden]")).toBeNull();
+ const blockPos = BLOCK_POS + 2;
+ const blockSize = editor.state.doc.nodeAt(blockPos)!.nodeSize;
+
+ await select(editor, blockPos + blockSize + 1);
+ await press(editor, "Backspace");
+ expect(blocks(editor)).toEqual(["paragraph:before", "paragraph:", "codeBlock:<p>hi</p>", "paragraph:after"]);
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
+ expect(editor.state.selection.from).toBe(blockPos);
+
+ await select(editor, BLOCK_POS + 1);
+ await press(editor, "Delete");
+ expect(blocks(editor)).toEqual(["paragraph:before", "codeBlock:<p>hi</p>", "paragraph:after"]);
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
+ expect(editor.state.selection.from).toBe(BLOCK_POS);
});
- it("does not show the toggle or an iframe for a non-html language", () => {
- render(<CodeBlockView {...makeProps("typescript", "const x = 1;")} />);
- expect(screen.queryByRole("button", { name: "Show source" })).toBeNull();
- expect(screen.queryByRole("button", { name: "Show preview" })).toBeNull();
- expect(document.querySelector("iframe")).toBeNull();
- expect(screen.queryByRole("button", { name: "Reload" })).toBeNull();
+ it("moves the caret out of the source when the preview comes back", async () => {
+ const editor = await mount(codeBlock("html", "<p>hi</p>"));
+ fireEvent.click(screen.getByRole("tab", { name: "Source" }));
+ await act(async () => {
+ editor.commands.setTextSelection(BLOCK_POS + 3);
+ });
+ expect(editor.state.selection).toBeInstanceOf(TextSelection);
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("tab", { name: "Preview" }));
+ });
+ expect(editor.state.selection).toBeInstanceOf(NodeSelection);
});
- it("reloads inline and enlarged HTML while preserving the editor and surface", () => {
- render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
- const original = document.querySelector("iframe");
- const content = screen.getByTestId("nvc");
- fireEvent.click(screen.getByRole("button", { name: "Reload" }));
- const inline = document.querySelector("iframe");
- expect(inline).not.toBe(original);
- expect(inline?.getAttribute("srcdoc")).toContain("<p>hello</p>");
- expect(screen.getByTestId("nvc")).toBe(content);
-
- fireEvent.click(screen.getByRole("button", { name: "Show source" }));
- expect(screen.getByRole("button", { name: "Reload" }).hasAttribute("disabled")).toBe(true);
- fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
- const dialog = screen.getByRole("dialog");
- fireEvent.click(within(dialog).getByRole("button", { name: "Reload" }));
- const enlarged = dialog.querySelector("iframe");
- expect(enlarged).not.toBe(inline);
- expect(enlarged?.getAttribute("sandbox")).toBe("allow-scripts");
- expect(screen.getByRole("dialog")).toBe(dialog);
- expect(document.querySelectorAll("iframe")).toHaveLength(1);
- fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
- expect(document.querySelector("iframe")).toBe(enlarged);
- expect(screen.getByTestId("nvc")).toBe(content);
- expect(content.closest("pre")?.className).not.toContain("sr-only");
+ it("keeps the document of HTML that reads no token across a theme switch", async () => {
+ await mount(codeBlock("html", '<input value="initial">'));
+ const iframe = frame();
+ const before = iframe.getAttribute("srcdoc");
+ expect(before).toMatch(/^<style>:root\{\}<\/style>/);
+
+ embedScheme.current = "dark";
+ await act(async () => {
+ document.documentElement.classList.add("dark");
+ });
+ expect(frame()).toBe(iframe);
+ expect(iframe.getAttribute("srcdoc")).toBe(before);
});
- it("defers source edits until the retained preview is visible", () => {
- const { rerender } = render(
- <CodeBlockView {...makeProps("html", "<p>initial</p>")} />,
- );
- const frame = document.querySelector("iframe")!;
- const editorContent = screen.getByTestId("nvc");
+ it("rebuilds the document of HTML that reads a token when the theme switches", async () => {
+ await mount(codeBlock("html", '<p style="color: var(--foreground)">hi</p>'));
+ expect(frame().getAttribute("srcdoc")).toContain("color-scheme:light");
+
+ embedScheme.current = "dark";
+ await act(async () => {
+ document.documentElement.classList.add("dark");
+ });
+ await waitFor(() => expect(frame().getAttribute("srcdoc")).toContain("color-scheme:dark"));
+ });
+});
- rerender(<CodeBlockView {...makeProps("html", "<p>pending</p>")} />);
- fireEvent.click(screen.getByRole("button", { name: "Show source" }));
- act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toContain("<p>initial</p>");
- rerender(<CodeBlockView {...makeProps("html", "<p>edited</p>")} />);
- act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toContain("<p>initial</p>");
+describe("CodeBlockView — other languages", () => {
+ it("draws ```mermaid in the same frame", async () => {
+ await mount(codeBlock("mermaid", "graph TD; A-->B", 'title="Request flow"'));
+ expect(document.querySelector('[data-dynamic-block="mermaid"]')).not.toBeNull();
+ expect(screen.getByRole("button", { name: "Request flow" })).toBeTruthy();
+ expect(screen.getByText("Mermaid")).toBeTruthy();
+ expect(screen.getByTestId("diagram").textContent).toBe("graph TD; A-->B");
+ });
- fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
- act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toContain("<p>edited</p>");
- expect(screen.getByRole("dialog").querySelector("iframe")).toBe(frame);
- fireEvent.click(screen.getByRole("button", { name: "Close" }));
-
- rerender(<CodeBlockView {...makeProps("html", "<p>latest</p>")} />);
- act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toContain("<p>edited</p>");
- fireEvent.click(screen.getByRole("button", { name: "Show preview" }));
- act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toContain("<p>latest</p>");
- expect(document.querySelector("iframe")).toBe(frame);
- expect(screen.getByTestId("nvc")).toBe(editorContent);
+ it("keeps plain code as an editable block with a copy button", async () => {
+ await mount(codeBlock("typescript", "const x = 1;"));
+ expect(document.querySelector("[data-dynamic-block]")).toBeNull();
+ expect(screen.getByRole("button", { name: "Copy code" })).toBeTruthy();
+ expect(document.querySelector("pre code")?.textContent).toBe("const x = 1;");
});
});
diff --git a/packages/views/editor/extensions/code-block-view.tsx b/packages/views/editor/extensions/code-block-view.tsx
index c08b13fa01..f75a63281f 100644
--- a/packages/views/editor/extensions/code-block-view.tsx
+++ b/packages/views/editor/extensions/code-block-view.tsx
@@ -1,82 +1,128 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { NodeViewWrapper, NodeViewContent } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import { Code as CodeIcon, Copy, Check, Eye, Maximize2, RotateCw } from "@multica/ui/icons";
-import { IconButton } from "@multica/ui/components/common/icon-button";
+import { NodeSelection } from "@tiptap/pm/state";
+import { Copy, Check } from "@multica/ui/icons";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-import { HtmlPreviewSurface } from "../html-preview-surface";
-import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
import { useDebouncedValue } from "../../common/use-debounced-value";
import { useT } from "../../i18n";
-import { MermaidDiagram } from "../mermaid-diagram";
-import { CodeBlockIframe } from "../code-block-iframe";
-import { useThemeVersion } from "../hooks/use-theme-version";
-import { readEmbedTheme } from "../../common/embed-theme";
-import {
- HTML_BLOCK_EMBED_OPTIONS,
- NO_HTML_BLOCK_THEME,
- buildHtmlBlockDocument,
- htmlBlockTheme,
- mentionsThemeTokens,
-} from "../utils/html-block-document";
+import type { DynamicBlockEditing, DynamicBlockView } from "../dynamic-block";
+import { HtmlBlockPreview } from "../html-block-preview";
+import { MermaidBlock } from "../mermaid-block";
+import { parseFenceTitle, withFenceTitle } from "../utils/fence-title";
+import { OPEN_BLOCK_SOURCE_META, isDynamicBlockLanguage } from "./code-block";
// Coalesces fast keystrokes before re-rendering live previews.
// `mermaid.initialize()` mutates a process-global config, so back-to-back
// renders during typing can race a concurrent ReadonlyContent render
// (e.g. a comment card) and clobber its theme variables. 200ms keeps the
// "live preview" feel while making concurrent inits unlikely in practice.
-// HTML preview reuses the same debounce: re-keying iframe.srcDoc on every
-// keystroke causes the iframe to re-load and flicker.
+// The HTML preview takes the same debounce: every new document reloads its
+// iframe.
const PREVIEW_DEBOUNCE_MS = 200;
-const HTML_PREVIEW_HEIGHT_PX = 480;
+function CodeBlockView(props: NodeViewProps) {
+ return isDynamicBlockLanguage(props.node.attrs.language) ? (
+ <DynamicCodeBlockView {...props} />
+ ) : (
+ <PlainCodeBlockView {...props} />
+ );
+}
+
+/**
+ * ```html and ```mermaid in the editor: the same dynamic block the read-only
+ * renderers draw (MUL-9760) — title bar, content height, collapse past 480px —
+ * with ProseMirror's editable `<pre>` as its source view and a title that
+ * renames in place.
+ */
+function DynamicCodeBlockView({ node, editor, getPos, selected, updateAttributes }: NodeViewProps) {
+ const text = node.textContent;
+ // A new, empty block has nothing to preview; it opens where it is written.
+ const [view, setView] = useState<DynamicBlockView>(() => (text.trim() ? "preview" : "source"));
+ const debounced = useDebouncedValue(text, PREVIEW_DEBOUNCE_MS);
+ const meta: string | null = node.attrs.meta ?? null;
+ const title = parseFenceTitle(meta);
+
+ // Read by editor listeners, which run outside React's render.
+ const viewRef = useRef(view);
+ const showView = useCallback((next: DynamicBlockView) => {
+ viewRef.current = next;
+ setView(next);
+ }, []);
+
+ // The source the preview hides must never hold the caret: typing there
+ // would change the block unseen. A selection that lands inside it — arrow
+ // keys, undo, switching back to the preview — selects the whole block
+ // instead, and Enter opens the source (CodeBlockExtension).
+ const containSelection = useCallback(() => {
+ if (viewRef.current !== "preview" || editor.isDestroyed) return;
+ const pos = getPos();
+ if (typeof pos !== "number") return;
+ const block = editor.state.doc.nodeAt(pos);
+ const { selection } = editor.state;
+ if (!block || selection instanceof NodeSelection) return;
+ if (selection.from > pos && selection.to < pos + block.nodeSize) {
+ editor.commands.setNodeSelection(pos);
+ }
+ }, [editor, getPos]);
+
+ useEffect(() => {
+ const onTransaction = ({ transaction }: { transaction: { getMeta: (key: string) => unknown } }) => {
+ const pos = getPos();
+ if (typeof pos === "number" && transaction.getMeta(OPEN_BLOCK_SOURCE_META) === pos) {
+ showView("source");
+ }
+ };
+ // After the dispatch that moved the selection has finished.
+ const onSelectionUpdate = () => queueMicrotask(containSelection);
+ editor.on("transaction", onTransaction);
+ editor.on("selectionUpdate", onSelectionUpdate);
+ return () => {
+ editor.off("transaction", onTransaction);
+ editor.off("selectionUpdate", onSelectionUpdate);
+ };
+ }, [editor, getPos, showView, containSelection]);
+
+ useEffect(() => {
+ if (view === "preview") containSelection();
+ }, [view, containSelection]);
+
+ const editing: DynamicBlockEditing = {
+ source: (
+ <pre spellCheck={false} className="!m-0 !rounded-none">
+ {/* @ts-expect-error -- NodeViewContent supports as="code" at runtime */}
+ <NodeViewContent as="code" />
+ </pre>
+ ),
+ view,
+ onViewChange: showView,
+ onTitleChange: editor.isEditable
+ ? (next) => updateAttributes({ meta: withFenceTitle(meta, next) })
+ : undefined,
+ selected,
+ };
+
+ return (
+ // Block, against the editor's inline default for NodeView wrappers; the
+ // margin matches the read-only block's shell, so the doc does not shift
+ // when the live editor replaces the read-only render.
+ <NodeViewWrapper className="my-5 !block" data-dynamic-code-block="">
+ {node.attrs.language === "mermaid" ? (
+ <MermaidBlock chart={debounced} title={title} editing={editing} />
+ ) : (
+ <HtmlBlockPreview html={debounced} title={title} editing={editing} />
+ )}
+ </NodeViewWrapper>
+ );
+}
-function CodeBlockView({ node }: NodeViewProps) {
+function PlainCodeBlockView({ node }: NodeViewProps) {
const { t } = useT("editor");
const [copied, setCopied] = useState(false);
- const [fullscreen, setFullscreen] = useState(false);
- const [reloadKey, setReloadKey] = useState(0);
- const reload = () => setReloadKey((key) => key + 1);
- // HTML blocks default to "preview"; the user can flip to "source" to
- // edit the markup directly. Note: the source `<pre>` MUST stay mounted
- // (just hidden) so ProseMirror keeps its NodeView bindings — unmounting
- // it would break editing.
- const [view, setView] = useState<"preview" | "source">("preview");
const language = node.attrs.language || "";
- const isMermaid = language === "mermaid";
- const isHtml = language === "html";
- const showHtmlPreview = isHtml && view === "preview";
- const chart = node.textContent;
- const debouncedChart = useDebouncedValue(
- isMermaid ? chart : "",
- PREVIEW_DEBOUNCE_MS,
- );
- const debouncedHtml = useDebouncedValue(
- isHtml ? chart : "",
- PREVIEW_DEBOUNCE_MS,
- showHtmlPreview || fullscreen,
- );
- // The same document a read-only ```html block gets, so the embed tokens
- // resolve while the block is being edited too. HTML that names no token
- // gets the same document under every theme: a new srcDoc reloads the frame
- // and loses whatever was typed or toggled in it.
- const previewRef = useRef<HTMLDivElement>(null);
- const themeVersion = useThemeVersion();
- const [srcDoc, setSrcDoc] = useState("");
- useEffect(() => {
- const host = previewRef.current;
- if (!host || !debouncedHtml) {
- setSrcDoc("");
- return;
- }
- const theme = mentionsThemeTokens(debouncedHtml)
- ? htmlBlockTheme(readEmbedTheme(host, HTML_BLOCK_EMBED_OPTIONS))
- : NO_HTML_BLOCK_THEME;
- setSrcDoc(buildHtmlBlockDocument(debouncedHtml, theme));
- }, [debouncedHtml, themeVersion]);
const handleCopy = async () => {
const text = node.textContent;
@@ -87,46 +133,8 @@ function CodeBlockView({ node }: NodeViewProps) {
}
};
- const toggleView = () =>
- setView((v) => (v === "preview" ? "source" : "preview"));
-
return (
<NodeViewWrapper className="code-block-wrapper group/code relative my-3">
- {isMermaid && debouncedChart.trim() && (
- <div
- contentEditable={false}
- className="mermaid-diagram-preview mb-1"
- >
- <MermaidDiagram chart={debouncedChart} />
- </div>
- )}
- {isHtml && (
- // CSS-hidden when toggled off so the `<pre>` below stays mounted —
- // unmounting either side would either lose ProseMirror bindings
- // (source) or thrash iframe.srcDoc (preview).
- <div
- ref={previewRef}
- contentEditable={false}
- className={showHtmlPreview ? "mb-1" : undefined}
- hidden={!showHtmlPreview && !fullscreen}
- >
- <HtmlPreviewSurface
- open={fullscreen}
- inlineHeight={showHtmlPreview ? HTML_PREVIEW_HEIGHT_PX : 0}
- onOpenChange={setFullscreen}
- onReload={reload}
- title={t(($) => $.code_block.html_preview)}
- >
- <CodeBlockIframe
- key={reloadKey}
- html={srcDoc}
- title={t(($) => $.code_block.html_preview)}
- heightClassName={fullscreen ? "h-full" : "h-[480px]"}
- className={fullscreen ? "rounded-none border-0" : undefined}
- />
- </HtmlPreviewSurface>
- </div>
- )}
<div
contentEditable={false}
className="code-block-header absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100"
@@ -136,57 +144,6 @@ function CodeBlockView({ node }: NodeViewProps) {
{language}
</span>
)}
- {isHtml && (
- <TooltipHint
- label={
- view === "preview"
- ? t(($) => $.code_block.show_source)
- : t(($) => $.code_block.show_preview)
- }
- >
- <button
- type="button"
- onClick={toggleView}
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- aria-label={
- view === "preview"
- ? t(($) => $.code_block.show_source)
- : t(($) => $.code_block.show_preview)
- }
- >
- {view === "preview" ? (
- <CodeIcon className="h-3.5 w-3.5" />
- ) : (
- <Eye className="h-3.5 w-3.5" />
- )}
- </button>
- </TooltipHint>
- )}
- {isHtml && (
- <IconButton
- type="button"
- variant="ghost"
- size="icon-xs"
- className="text-muted-foreground"
- disabled={!showHtmlPreview}
- label={t(($) => $.attachment.reload)}
- onClick={reload}
- >
- <RotateCw className="size-3.5" />
- </IconButton>
- )}
- {isHtml && (
- <IconButton
- type="button"
- variant="ghost"
- size="icon-xs"
- className="text-muted-foreground"
- label={t(($) => $.code_block.fullscreen)}
- onClick={() => setFullscreen(true)}
- >
- <Maximize2 className="size-3.5" />
- </IconButton>
- )}
<TooltipHint label={t(($) => $.code_block.copy_code)}>
<button
type="button"
@@ -202,14 +159,7 @@ function CodeBlockView({ node }: NodeViewProps) {
</button>
</TooltipHint>
</div>
- {/* `<pre>` + NodeViewContent must remain mounted so the user can keep
- editing the code block contents. When the HTML preview is showing
- we just visually hide it — ProseMirror still tracks it. */}
- <pre
- spellCheck={false}
- className={cn(showHtmlPreview && "sr-only")}
- aria-hidden={showHtmlPreview ? "true" : undefined}
- >
+ <pre spellCheck={false}>
{/* @ts-expect-error -- NodeViewContent supports as="code" at runtime */}
<NodeViewContent as="code" />
</pre>
diff --git a/packages/views/editor/extensions/code-block.ts b/packages/views/editor/extensions/code-block.ts
index 000c3b9b2e..8a41ebe26b 100644
--- a/packages/views/editor/extensions/code-block.ts
+++ b/packages/views/editor/extensions/code-block.ts
@@ -1,6 +1,8 @@
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
-import type { Node as PMNode } from "@tiptap/pm/model";
-import { Plugin, PluginKey } from "@tiptap/pm/state";
+import { Slice, type Node as PMNode, type ResolvedPos } from "@tiptap/pm/model";
+import type { Editor } from "@tiptap/core";
+import { NodeSelection, Plugin, PluginKey, Selection, TextSelection } from "@tiptap/pm/state";
+import { ReplaceStep, replaceStep } from "@tiptap/pm/transform";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import type { createLowlight } from "lowlight";
@@ -98,7 +100,136 @@ export function splitFenceInfo(info: string | null | undefined): {
};
}
+/**
+ * Languages whose block renders in place — a preview in the shared dynamic
+ * block frame — instead of as highlighted code (MUL-7649, MUL-9760).
+ */
+export function isDynamicBlockLanguage(language: unknown): language is "html" | "mermaid" {
+ return language === "html" || language === "mermaid";
+}
+
+/**
+ * Transaction meta: the position of the dynamic block whose source should
+ * open. The NodeView at that position switches to its source view.
+ */
+export const OPEN_BLOCK_SOURCE_META = "multica:openBlockSource";
+
+/** Whether `node` at `pos` is a dynamic block currently showing its preview. */
+function isPreviewedBlock(editor: Editor, typeName: string, node: PMNode | null | undefined, pos: number): boolean {
+ if (!node || node.type.name !== typeName || !isDynamicBlockLanguage(node.attrs.language)) return false;
+ const dom = editor.view.nodeDOM(pos);
+ return dom instanceof HTMLElement && !!dom.querySelector('[data-dynamic-block-view="preview"]');
+}
+
+/**
+ * Up or Down from the edge of a textblock onto a dynamic block that shows its
+ * preview selects that block whole. Left to the browser, the caret would skip
+ * the block going up and land in its hidden source going down. Mirrors
+ * ProseMirror's own vertical block motion (moveSelectionBlock).
+ */
+function selectPreviewedBlock(editor: Editor, typeName: string, dir: 1 | -1): boolean {
+ const { state, view } = editor;
+ const { selection } = state;
+ if (!(selection instanceof TextSelection) || !selection.empty) return false;
+ const $side = selection.$head;
+ if (!$side.depth || !view.endOfTextblock(dir < 0 ? "up" : "down")) return false;
+ const next = Selection.findFrom(state.doc.resolve(dir > 0 ? $side.after() : $side.before()), dir);
+ if (!(next instanceof TextSelection)) return false;
+ const pos = next.$head.before();
+ if (!isPreviewedBlock(editor, typeName, next.$head.parent, pos)) return false;
+ view.dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)).scrollIntoView());
+ return true;
+}
+
+/**
+ * Backspace at the start of a textblock right after a previewed dynamic
+ * block, or Delete at its end right before one, selects the block, as it
+ * would an image. The default join would append the paragraph to the hidden
+ * source (Backspace) or pour the source into the paragraph (Delete). An empty
+ * textblock is removed on the way, as ProseMirror does next to a leaf block.
+ * Only a sibling textblock is handled: a list item or quote keeps its own
+ * Backspace (lifting it out), which never reaches into the block.
+ */
+function deleteTowardPreviewedBlock(editor: Editor, typeName: string, dir: 1 | -1): boolean {
+ const { state, view } = editor;
+ const { selection } = state;
+ if (!(selection instanceof TextSelection) || !selection.empty) return false;
+ const $cursor = selection.$head;
+ if (dir < 0 ? $cursor.parentOffset > 0 : $cursor.parentOffset < $cursor.parent.content.size) return false;
+ const $cut = dir < 0 ? cutBefore($cursor) : cutAfter($cursor);
+ if (!$cut || $cut.depth !== $cursor.depth - 1) return false;
+ const block = dir < 0 ? $cut.nodeBefore : $cut.nodeAfter;
+ const blockPos = dir < 0 ? $cut.pos - (block?.nodeSize ?? 0) : $cut.pos;
+ if (!isPreviewedBlock(editor, typeName, block, blockPos)) return false;
+
+ const tr = state.tr;
+ if ($cursor.parent.content.size === 0) {
+ const step = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
+ if (step instanceof ReplaceStep && step.slice.size < step.to - step.from) tr.step(step);
+ }
+ view.dispatch(tr.setSelection(NodeSelection.create(tr.doc, tr.mapping.map(blockPos))).scrollIntoView());
+ return true;
+}
+
+// ProseMirror's findCutBefore / findCutAfter (prosemirror-commands), which it
+// does not export: the boundary a join at the cursor would cross.
+function cutBefore($pos: ResolvedPos): ResolvedPos | null {
+ if ($pos.parent.type.spec.isolating) return null;
+ for (let depth = $pos.depth - 1; depth >= 0; depth--) {
+ if ($pos.index(depth) > 0) return $pos.doc.resolve($pos.before(depth + 1));
+ if ($pos.node(depth).type.spec.isolating) break;
+ }
+ return null;
+}
+
+function cutAfter($pos: ResolvedPos): ResolvedPos | null {
+ if ($pos.parent.type.spec.isolating) return null;
+ for (let depth = $pos.depth - 1; depth >= 0; depth--) {
+ const parent = $pos.node(depth);
+ if ($pos.index(depth) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(depth + 1));
+ if (parent.type.spec.isolating) break;
+ }
+ return null;
+}
+
export const CodeBlockExtension = CodeBlockLowlight.extend({
+ addKeyboardShortcuts() {
+ const inherited = this.parent?.() ?? {};
+ return {
+ ...inherited,
+ ArrowUp: (props) =>
+ selectPreviewedBlock(props.editor, this.name, -1) || (inherited.ArrowUp?.(props) ?? false),
+ ArrowDown: (props) =>
+ selectPreviewedBlock(props.editor, this.name, 1) || (inherited.ArrowDown?.(props) ?? false),
+ // The inherited Backspace (clearing an empty code block) goes first.
+ Backspace: (props) =>
+ (inherited.Backspace?.(props) ?? false) || deleteTowardPreviewedBlock(props.editor, this.name, -1),
+ Delete: (props) =>
+ deleteTowardPreviewedBlock(props.editor, this.name, 1) || (inherited.Delete?.(props) ?? false),
+ // A previewed dynamic block is selected as a whole (its NodeView keeps
+ // the caret out of the hidden source); Enter opens the source with the
+ // caret at its start.
+ Enter: (props) => {
+ const { editor } = props;
+ const { selection } = editor.state;
+ if (
+ editor.isEditable &&
+ selection instanceof NodeSelection &&
+ selection.node.type.name === this.name &&
+ isDynamicBlockLanguage(selection.node.attrs.language)
+ ) {
+ const pos = selection.from;
+ return editor.commands.command(({ tr }) => {
+ tr.setSelection(TextSelection.create(tr.doc, pos + 1))
+ .setMeta(OPEN_BLOCK_SOURCE_META, pos)
+ .scrollIntoView();
+ return true;
+ });
+ }
+ return inherited.Enter?.(props) ?? false;
+ },
+ };
+ },
addProseMirrorPlugins() {
// Drops the stock plugin, and ours when an extension of this one calls
// back into it. Plugin keys are runtime strings ProseMirror leaves out of
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
index b108a4c445..fc6e4b33d2 100644
--- a/packages/views/editor/html-block-preview.tsx
+++ b/packages/views/editor/html-block-preview.tsx
@@ -21,8 +21,8 @@
* tracks the document that is actually shown.
*
* Reached through RichFenceBlock (rich-content/rich-code-block.tsx) for closed
- * fences only. NOT used in the editable Tiptap NodeView — that path must keep
- * `<NodeViewContent as="code" />` so the user can continue typing.
+ * fences, and from the editable code block's NodeView (MUL-9760), which hands
+ * in its own editable source through `editing`.
*/
import { useEffect, useLayoutEffect, useRef, useState } from "react";
@@ -36,6 +36,8 @@ import {
DYNAMIC_BLOCK_MIN_BODY_PX,
DynamicBlock,
DynamicBlockSkeleton,
+ useValueWhileVisible,
+ type DynamicBlockEditing,
type DynamicBlockError,
} from "./dynamic-block";
import { useThemeVersion } from "./hooks/use-theme-version";
@@ -44,8 +46,10 @@ import {
HTML_BLOCK_EMBED_OPTIONS,
HTML_BLOCK_MESSAGE_KEY,
INITIAL_HTML_BLOCK_HEIGHT,
+ NO_HTML_BLOCK_THEME,
buildHtmlBlockDocument,
htmlBlockTheme,
+ mentionsThemeTokens,
nextHtmlBlockHeight,
readHtmlBlockMessage,
} from "./utils/html-block-document";
@@ -109,9 +113,11 @@ interface HtmlBlockPreviewProps {
html: string;
/** From the fence info string: ```html title="…". */
title?: string | null;
+ /** Set by the editor's NodeView. */
+ editing?: DynamicBlockEditing;
}
-export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
+export function HtmlBlockPreview({ html: source, title, editing }: HtmlBlockPreviewProps) {
const { t } = useT("editor");
const hostRef = useRef<HTMLDivElement>(null);
const themeVersion = useThemeVersion();
@@ -124,6 +130,12 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
// (see the flicker note in the file header).
const [bodyHeight, setBodyHeight] = useState<number | null>(null);
const frameTitle = t(($) => $.code_block.html_preview);
+ // While the editor shows the source, edits wait for the preview to be shown
+ // (or enlarged) instead of reloading a hidden frame on every pause.
+ const html = useValueWhileVisible(
+ source,
+ !editing || editing.view === "preview" || fullscreen,
+ );
const reload = () => {
setError(null);
@@ -133,11 +145,20 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
// Built after mount: the theme tokens come from the host's computed style.
// A theme switch rebuilds the document, which reruns its scripts — a chart
// reads its colors when it draws, so this is the only way it can follow.
+ // HTML that names no token gets the same document under every theme, so a
+ // switch does not reload it and lose what was typed or toggled inside.
+ const builtRef = useRef<string | null>(null);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
+ const theme = mentionsThemeTokens(html)
+ ? htmlBlockTheme(readEmbedTheme(host, HTML_BLOCK_EMBED_OPTIONS))
+ : NO_HTML_BLOCK_THEME;
+ const next = buildHtmlBlockDocument(html, theme);
+ if (next === builtRef.current) return;
+ builtRef.current = next;
setError(null);
- setSrcDoc(buildHtmlBlockDocument(html, htmlBlockTheme(readEmbedTheme(host, HTML_BLOCK_EMBED_OPTIONS))));
+ setSrcDoc(next);
}, [html, themeVersion]);
return (
@@ -145,12 +166,13 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
<DynamicBlock
kind="html"
title={title}
- source={html}
+ source={source}
error={error}
fullscreen={fullscreen}
onFullscreen={() => setFullscreen(true)}
onReload={reload}
bodyHeight={bodyHeight}
+ editing={editing}
preview={({ active, collapsed }) => (
// Keyed by the content: a re-authored block restarts measurement
// from scratch — a stale `frozen`/`loaded` from the previous
diff --git a/packages/views/editor/mermaid-block.tsx b/packages/views/editor/mermaid-block.tsx
index b94af064e8..9bbac726f1 100644
--- a/packages/views/editor/mermaid-block.tsx
+++ b/packages/views/editor/mermaid-block.tsx
@@ -4,7 +4,8 @@
* MermaidBlock — a fenced ```mermaid block rendered in place, inside the shared
* DynamicBlock frame (MUL-7649). The diagram, its viewer and its layout cache
* stay in MermaidDiagram; the frame takes the title bar, source view, copy,
- * fullscreen and the error panel.
+ * fullscreen and the error panel. The editor's NodeView draws it too, with its
+ * own editable source (`editing`, MUL-9760).
*/
import { useMemo, useRef, useState } from "react";
@@ -12,6 +13,8 @@ import {
DYNAMIC_BLOCK_CHROME_PX,
DYNAMIC_BLOCK_COLLAPSE_AT_PX,
DynamicBlock,
+ useValueWhileVisible,
+ type DynamicBlockEditing,
} from "./dynamic-block";
import {
MERMAID_SKELETON_HEIGHT_PX,
@@ -36,8 +39,23 @@ export function reservedMermaidBlockHeightPx(chart: string): number {
return blockHeightPx(framedMermaidBodyHeightPx(chart));
}
-export function MermaidBlock({ chart, title }: { chart: string; title?: string | null }) {
+export function MermaidBlock({
+ chart: source,
+ title,
+ editing,
+}: {
+ chart: string;
+ title?: string | null;
+ /** Set by the editor's NodeView. */
+ editing?: DynamicBlockEditing;
+}) {
const [viewerOpen, setViewerOpen] = useState(false);
+ // While the editor shows the source, the hidden diagram is not redrawn on
+ // every pause; it catches up when shown or opened in the viewer.
+ const chart = useValueWhileVisible(
+ source,
+ !editing || editing.view === "preview" || viewerOpen,
+ );
const [error, setError] = useState<string | null>(null);
const fullscreenButtonRef = useRef<HTMLButtonElement>(null);
@@ -55,11 +73,12 @@ export function MermaidBlock({ chart, title }: { chart: string; title?: string |
<DynamicBlock
kind="mermaid"
title={title}
- source={chart}
+ source={source}
error={error == null ? null : { message: error }}
// A diagram that did not draw has nothing to blow up.
onFullscreen={error == null ? () => setViewerOpen(true) : undefined}
fullscreenButtonRef={fullscreenButtonRef}
+ editing={editing}
preview={() => <MermaidDiagram chart={chart} frame={frame} />}
/>
);
diff --git a/packages/views/editor/utils/fence-title.test.ts b/packages/views/editor/utils/fence-title.test.ts
new file mode 100644
index 0000000000..13bc94de55
--- /dev/null
+++ b/packages/views/editor/utils/fence-title.test.ts
@@ -0,0 +1,40 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { parseFenceTitle, withFenceTitle } from "./fence-title";
+
+describe("parseFenceTitle", () => {
+ it("accepts double, single and bare values", () => {
+ expect(parseFenceTitle('title="Weekly p95" theme=dark')).toBe("Weekly p95");
+ expect(parseFenceTitle("title='Sign-up funnel'")).toBe("Sign-up funnel");
+ expect(parseFenceTitle("title=Funnel")).toBe("Funnel");
+ expect(parseFenceTitle('subtitle="nope"')).toBeNull();
+ expect(parseFenceTitle('title=" "')).toBeNull();
+ expect(parseFenceTitle(null)).toBeNull();
+ });
+});
+
+describe("withFenceTitle", () => {
+ it.each([
+ ["adds a title to a fence that has none", null, "Weekly p95", 'title="Weekly p95"'],
+ ["appends after other attributes", "theme=dark", "Funnel", 'theme=dark title="Funnel"'],
+ ["replaces the title in place", 'a=1 title="Old" b=2', "New", 'a=1 title="New" b=2'],
+ ["replaces a leading single-quoted title", "title='Old' b=2", "New", 'title="New" b=2'],
+ ["replaces a bare title", "title=Old", "New", 'title="New"'],
+ ["removes the title when blank", 'a=1 title="Old" b=2', " ", "a=1 b=2"],
+ ["drops meta that held only the title", 'title="Old"', "", null],
+ ["leaves subtitle alone", 'subtitle="Keep"', "New", 'subtitle="Keep" title="New"'],
+ ])("%s", (_name, meta, title, expected) => {
+ expect(withFenceTitle(meta, title)).toBe(expected);
+ });
+
+ it("quotes so the title reads back unchanged", () => {
+ for (const title of ['Say "hi"', "It's p95", "Plain"]) {
+ expect(parseFenceTitle(withFenceTitle(null, title))).toBe(title);
+ }
+ expect(parseFenceTitle(withFenceTitle(null, `Both "kinds" it's`))).toBe("Both 'kinds' it's");
+ });
+
+ it("keeps the info string on one line and free of backticks", () => {
+ expect(withFenceTitle(null, "Weekly\n`p95`")).toBe('title="Weekly p95"');
+ });
+});
diff --git a/packages/views/editor/utils/fence-title.ts b/packages/views/editor/utils/fence-title.ts
new file mode 100644
index 0000000000..d57e4f04a1
--- /dev/null
+++ b/packages/views/editor/utils/fence-title.ts
@@ -0,0 +1,47 @@
+/**
+ * The `title` attribute of a fence info string — ```html title="Weekly p95"
+ * (MUL-7649). The read-only renderers read it; the editable block's title bar
+ * reads and writes it (MUL-9760).
+ */
+
+const TITLE_RE = /(?:^|\s)title=(?:"([^"]*)"|'([^']*)'|(\S+))/;
+
+/** The title in a fence's meta (the info string after the language). Double, single or no quotes. */
+export function parseFenceTitle(meta: string | null | undefined): string | null {
+ if (!meta) return null;
+ const match = TITLE_RE.exec(meta);
+ const title = (match?.[1] ?? match?.[2] ?? match?.[3] ?? "").trim();
+ return title || null;
+}
+
+function quoteTitle(title: string): string {
+ if (!title.includes('"')) return `"${title}"`;
+ if (!title.includes("'")) return `'${title}'`;
+ // The attribute has no escape for a quote; a title with both kinds keeps one.
+ return `"${title.replace(/"/g, "'")}"`;
+}
+
+/**
+ * `meta` with its title set to `title`, or without a title when `title` is
+ * blank. The rest of the info string stays exactly as written, so attributes
+ * other renderers read survive a rename.
+ */
+export function withFenceTitle(meta: string | null | undefined, title: string): string | null {
+ // A backtick ends the info string of a backtick fence and a line break ends
+ // the fence line; either would break the block when it is saved.
+ const clean = title.replace(/`/g, "").replace(/\s+/g, " ").trim();
+ const attribute = clean ? `title=${quoteTitle(clean)}` : "";
+ const current = meta ?? "";
+ const match = TITLE_RE.exec(current);
+ let next: string;
+ if (match) {
+ const lead = match[0].startsWith("title=") ? "" : match[0].charAt(0);
+ next =
+ current.slice(0, match.index) +
+ (attribute ? lead + attribute : "") +
+ current.slice(match.index + match[0].length);
+ } else {
+ next = attribute ? `${current} ${attribute}` : current;
+ }
+ return next.trim() || null;
+}
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index fe16c48777..edf207f7fe 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -129,8 +129,6 @@
"html_preview": "HTML preview",
"close_preview": "Close",
"copy_code": "Copy code",
- "show_preview": "Show preview",
- "show_source": "View source",
"fullscreen": "Fullscreen"
},
"dynamic_block": {
@@ -144,7 +142,10 @@
"error_mermaid": "Couldn't draw this diagram",
"error_at_line": "{{message}} (line {{line}})",
"view_source": "View source",
- "copy_error": "Copy error"
+ "copy_error": "Copy error",
+ "title": "Title",
+ "rename": "Rename",
+ "add_title": "Add title"
},
"file_card": {
"uploading": "Uploading {{filename}}"
diff --git a/packages/views/locales/es/editor.json b/packages/views/locales/es/editor.json
index b1b45c799a..000d72c9f5 100644
--- a/packages/views/locales/es/editor.json
+++ b/packages/views/locales/es/editor.json
@@ -128,8 +128,6 @@
"code_block": {
"html_preview": "Vista previa HTML",
"copy_code": "Copiar código",
- "show_preview": "Mostrar vista previa",
- "show_source": "Ver código fuente",
"fullscreen": "Pantalla completa",
"close_preview": "Cerrar"
},
@@ -174,7 +172,10 @@
"error_mermaid": "No se ha podido dibujar este diagrama",
"error_at_line": "{{message}} (línea {{line}})",
"view_source": "Ver fuente",
- "copy_error": "Copiar error"
+ "copy_error": "Copiar error",
+ "title": "Título",
+ "rename": "Cambiar nombre",
+ "add_title": "Añadir título"
},
"table": {
"reset_widths": "Restablecer anchos",
diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.json
index 92d4d9a904..3742cee3a4 100644
--- a/packages/views/locales/fr/editor.json
+++ b/packages/views/locales/fr/editor.json
@@ -129,8 +129,6 @@
"html_preview": "Aperçu HTML",
"close_preview": "Fermer",
"copy_code": "Copier le code",
- "show_preview": "Afficher l'aperçu",
- "show_source": "Voir la source",
"fullscreen": "Plein écran"
},
"dynamic_block": {
@@ -144,7 +142,10 @@
"error_mermaid": "Impossible de dessiner ce diagramme",
"error_at_line": "{{message}} (ligne {{line}})",
"view_source": "Voir la source",
- "copy_error": "Copier l’erreur"
+ "copy_error": "Copier l’erreur",
+ "title": "Titre",
+ "rename": "Renommer",
+ "add_title": "Ajouter un titre"
},
"file_card": {
"uploading": "Envoi de {{filename}}"
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index ca75e34565..4384ff703a 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -118,8 +118,6 @@
"html_preview": "HTML プレビュー",
"close_preview": "閉じる",
"copy_code": "コードをコピー",
- "show_preview": "プレビューを表示",
- "show_source": "ソースを表示",
"fullscreen": "全画面"
},
"dynamic_block": {
@@ -133,7 +131,10 @@
"error_mermaid": "この図を描画できませんでした",
"error_at_line": "{{message}}({{line}} 行目)",
"view_source": "ソースを表示",
- "copy_error": "エラーをコピー"
+ "copy_error": "エラーをコピー",
+ "title": "タイトル",
+ "rename": "名前を変更",
+ "add_title": "タイトルを追加"
},
"file_card": {
"uploading": "{{filename}} をアップロード中"
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index d92309631d..92a94d0db4 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -118,8 +118,6 @@
"html_preview": "HTML 미리보기",
"close_preview": "닫기",
"copy_code": "코드 복사",
- "show_preview": "미리보기 표시",
- "show_source": "소스 보기",
"fullscreen": "전체 화면"
},
"dynamic_block": {
@@ -133,7 +131,10 @@
"error_mermaid": "이 다이어그램을 그릴 수 없습니다",
"error_at_line": "{{message}} ({{line}}행)",
"view_source": "소스 보기",
- "copy_error": "오류 복사"
+ "copy_error": "오류 복사",
+ "title": "제목",
+ "rename": "이름 바꾸기",
+ "add_title": "제목 추가"
},
"file_card": {
"uploading": "{{filename}} 업로드 중"
diff --git a/packages/views/locales/ru/editor.json b/packages/views/locales/ru/editor.json
index 8246037b74..06ea1ce36a 100644
--- a/packages/views/locales/ru/editor.json
+++ b/packages/views/locales/ru/editor.json
@@ -137,8 +137,6 @@
"html_preview": "HTML-предпросмотр",
"close_preview": "Закрыть",
"copy_code": "Скопировать код",
- "show_preview": "Показать предпросмотр",
- "show_source": "Показать исходный код",
"fullscreen": "На весь экран"
},
"dynamic_block": {
@@ -152,7 +150,10 @@
"error_mermaid": "Не удалось построить диаграмму",
"error_at_line": "{{message}} (строка {{line}})",
"view_source": "Просмотреть исходный код",
- "copy_error": "Скопировать ошибку"
+ "copy_error": "Скопировать ошибку",
+ "title": "Заголовок",
+ "rename": "Переименовать",
+ "add_title": "Добавить заголовок"
},
"file_card": {
"uploading": "Загрузка {{filename}}"
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index 18ee5fa9ae..c21cff1871 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -125,8 +125,6 @@
"html_preview": "HTML 预览",
"close_preview": "关闭",
"copy_code": "复制代码",
- "show_preview": "显示预览",
- "show_source": "显示源码",
"fullscreen": "全屏"
},
"dynamic_block": {
@@ -140,7 +138,10 @@
"error_mermaid": "无法绘制这张图",
"error_at_line": "{{message}}(第 {{line}} 行)",
"view_source": "查看源码",
- "copy_error": "复制错误"
+ "copy_error": "复制错误",
+ "title": "标题",
+ "rename": "重命名",
+ "add_title": "添加标题"
},
"file_card": {
"uploading": "正在上传 {{filename}}"
diff --git a/packages/views/locales/zh-Hant/editor.json b/packages/views/locales/zh-Hant/editor.json
index 5193afcb2f..1951425a30 100644
--- a/packages/views/locales/zh-Hant/editor.json
+++ b/packages/views/locales/zh-Hant/editor.json
@@ -125,8 +125,6 @@
"html_preview": "HTML 預覽",
"close_preview": "關閉",
"copy_code": "複製程式碼",
- "show_preview": "顯示預覽",
- "show_source": "檢視原始碼",
"fullscreen": "放大"
},
"dynamic_block": {
@@ -140,7 +138,10 @@
"error_mermaid": "無法繪製這張圖",
"error_at_line": "{{message}}(第 {{line}} 行)",
"view_source": "檢視原始碼",
- "copy_error": "複製錯誤"
+ "copy_error": "複製錯誤",
+ "title": "標題",
+ "rename": "重新命名",
+ "add_title": "新增標題"
},
"file_card": {
"uploading": "正在上傳 {{filename}}"
diff --git a/packages/views/rich-content/streaming-fence.test.ts b/packages/views/rich-content/streaming-fence.test.ts
index 2de21c09f7..86086c3512 100644
--- a/packages/views/rich-content/streaming-fence.test.ts
+++ b/packages/views/rich-content/streaming-fence.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import { computeClosedFences, parseFenceTitle } from "./streaming-fence";
+import { computeClosedFences } from "./streaming-fence";
const isClosed = (src: string, offset = 0): boolean =>
computeClosedFences(src).has(offset);
@@ -111,13 +111,4 @@ describe("fence titles", () => {
it("has no title when the info string carries none", () => {
expect(computeClosedFences("```html\n<b>x</b>\n```\n").get(0)).toEqual({ title: null });
});
-
- it("accepts double, single and bare values", () => {
- expect(parseFenceTitle('title="Weekly p95" theme=dark')).toBe("Weekly p95");
- expect(parseFenceTitle("title='Sign-up funnel'")).toBe("Sign-up funnel");
- expect(parseFenceTitle("title=Funnel")).toBe("Funnel");
- expect(parseFenceTitle('subtitle="nope"')).toBeNull();
- expect(parseFenceTitle('title=" "')).toBeNull();
- expect(parseFenceTitle(null)).toBeNull();
- });
});
diff --git a/packages/views/rich-content/streaming-fence.ts b/packages/views/rich-content/streaming-fence.ts
index 6e19b6fb7a..f967cd78e4 100644
--- a/packages/views/rich-content/streaming-fence.ts
+++ b/packages/views/rich-content/streaming-fence.ts
@@ -1,5 +1,6 @@
import { fromMarkdown } from "mdast-util-from-markdown";
import type { Root, RootContent, Code } from "mdast";
+import { parseFenceTitle } from "../editor/utils/fence-title";
/**
* Fenced-code closedness gate for streaming RichContent (MUL-4922).
@@ -75,19 +76,6 @@ function endsWithClosingFence(raw: string): boolean {
return closeFence[0] === marker && closeFence.length >= openFence.length;
}
-const TITLE_RE = /(?:^|\s)title=(?:"([^"]*)"|'([^']*)'|(\S+))/;
-
-/**
- * The `title` attribute of a fence info string, e.g. `title="Weekly p95"` in
- * ```html title="Weekly p95". Double, single or no quotes.
- */
-export function parseFenceTitle(meta: string | null | undefined): string | null {
- if (!meta) return null;
- const match = TITLE_RE.exec(meta);
- const title = (match?.[1] ?? match?.[2] ?? match?.[3] ?? "").trim();
- return title || null;
-}
-
export interface ClosedFence {
title: string | null;
}