From bd3f0cb6515b70d5c90fb7fc2287e2f780bea7a6 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Fri, 4 Dec 2026 19:30:41 +0900 Subject: [PATCH] fix(notebook): apply the Markdown soft line breaks setting to Markdown cells (#8000) Notebook Markdown cells always parsed with a single Marked instance with breaks off and didn't read languages.markdown.softLineBreaks, so "Break on single newline" had no effect there. Markdown cells now use the setting and re-render when it changes; hard breaks, code blocks and math are unchanged. Fixes #7941 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- e2e/notebookRunCell.spec.ts | 153 +++++++++++++--------- src/features/notebook/OutputView.test.tsx | 41 +++++- src/features/notebook/OutputView.tsx | 4 +- src/features/notebook/security.test.ts | 21 +++ src/features/notebook/security.ts | 8 +- src/platform/languageSettings.ts | 2 +- 6 files changed, 163 insertions(+), 66 deletions(-) diff --git a/e2e/notebookRunCell.spec.ts b/e2e/notebookRunCell.spec.ts index 21afb45cc0..2081b8e73d 100644 --- a/e2e/notebookRunCell.spec.ts +++ b/e2e/notebookRunCell.spec.ts @@ -1,69 +1,86 @@ import type { Page } from "@playwright/test"; -import { expect, openFromTree, stubDesktop, test } from "./fixtures"; +import { expect, openFromTree, stubDesktop, stubSettingsWrites, test } from "./fixtures"; const NOTEBOOK_PATH = "/dev/acme-api/run-cells.ipynb"; +async function chooseSoftLineBreaks(page: Page, mode: "Standard Markdown" | "Break on single newline") { + await page.keyboard.press("Meta+,"); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + await settings.getByRole("textbox", { name: "Search settings" }).fill("Soft line breaks"); + await settings.getByRole("treeitem", { name: "Markdown", exact: true, level: 2 }).click(); + const select = settings.getByRole("button", { name: "Soft line breaks", exact: true }); + await expect(select).toBeVisible(); + await select.click(); + await page.getByRole("option", { name: mode, exact: true }).click(); + await settings.getByRole("button", { name: "OK", exact: true }).click(); + await expect(settings).toBeHidden(); +} + /** Opens a notebook whose kernel answers a cell with its source as output. */ -async function openNotebook(page: Page) { +async function openNotebook(page: Page, markdownSource = "## Totals") { await openFromTree(page, "README.md"); await stubDesktop(page); - await page.evaluate(async (path) => { - const cell = (id: string, cellType: string, source: string) => ({ - id, - cellType, - source, - metadata: {}, - attachments: {}, - executionCount: null as number | null, - outputs: [] as unknown[], - }); - let runs = 0; - let added = 0; - const snapshot = { - id: "run-cells", - path, - version: 1, - dirty: false, - nbformat: 4, - nbformatMinor: 5, - metadata: {}, - canUndo: false, - canRedo: false, - cells: [ - cell("load", "code", "orders = [12, 30, 8]"), - cell("notes", "markdown", "## Totals"), - cell("total", "code", "sum(orders)"), - ], - }; - const answer = () => { - snapshot.version++; - return structuredClone(snapshot); - }; - Object.assign(window.__ipc.handlers, { - notebook_open: () => structuredClone(snapshot), - notebook_get: () => structuredClone(snapshot), - notebook_cell_docs: () => [], - sdk_detect: () => [], - sdk_python_effective: () => null, - jupyter_servers: () => [], - notebook_edit: ({ edit }: { edit: Record }) => { - const at = snapshot.cells.findIndex((c) => c.id === (edit.cell ?? edit.after)); - if (edit.type === "setSource") snapshot.cells[at]!.source = edit.source!; - else if (edit.type === "insertCell") - snapshot.cells.splice(at + 1, 0, cell(`added-${++added}`, edit.cellType!, "")); - return answer(); - }, - notebook_execute: ({ cells }: { cells: string[] }) => { - const run = snapshot.cells.find((c) => c.id === cells[0])!; - run.executionCount = ++runs; - run.outputs = [{ output_type: "stream", name: "stdout", text: `ran: ${run.source}\n` }]; - return answer(); - }, - }); - const module = "/src/workbench/contributions.ts"; - const { editorService } = await import(/* @vite-ignore */ module); - await editorService().openFile(path, { preview: false }); - }, NOTEBOOK_PATH); + await stubSettingsWrites(page); + await page.evaluate( + async ({ path, markdownSource }) => { + const cell = (id: string, cellType: string, source: string) => ({ + id, + cellType, + source, + metadata: {}, + attachments: {}, + executionCount: null as number | null, + outputs: [] as unknown[], + }); + let runs = 0; + let added = 0; + const snapshot = { + id: "run-cells", + path, + version: 1, + dirty: false, + nbformat: 4, + nbformatMinor: 5, + metadata: {}, + canUndo: false, + canRedo: false, + cells: [ + cell("load", "code", "orders = [12, 30, 8]"), + cell("notes", "markdown", markdownSource), + cell("total", "code", "sum(orders)"), + ], + }; + const answer = () => { + snapshot.version++; + return structuredClone(snapshot); + }; + Object.assign(window.__ipc.handlers, { + notebook_open: () => structuredClone(snapshot), + notebook_get: () => structuredClone(snapshot), + notebook_cell_docs: () => [], + sdk_detect: () => [], + sdk_python_effective: () => null, + jupyter_servers: () => [], + notebook_edit: ({ edit }: { edit: Record }) => { + const at = snapshot.cells.findIndex((c) => c.id === (edit.cell ?? edit.after)); + if (edit.type === "setSource") snapshot.cells[at]!.source = edit.source!; + else if (edit.type === "insertCell") + snapshot.cells.splice(at + 1, 0, cell(`added-${++added}`, edit.cellType!, "")); + return answer(); + }, + notebook_execute: ({ cells }: { cells: string[] }) => { + const run = snapshot.cells.find((c) => c.id === cells[0])!; + run.executionCount = ++runs; + run.outputs = [{ output_type: "stream", name: "stdout", text: `ran: ${run.source}\n` }]; + return answer(); + }, + }); + const module = "/src/workbench/contributions.ts"; + const { editorService } = await import(/* @vite-ignore */ module); + await editorService().openFile(path, { preview: false }); + }, + { path: NOTEBOOK_PATH, markdownSource }, + ); await expect(region(page, 1)).toBeVisible(); } @@ -113,3 +130,21 @@ test("the run actions are in Find Action and act on the notebook behind it", asy await expect(region(page, 3)).toContainText("Totals"); expect(await runs(page)).toEqual(["load"]); }); + +test("Markdown soft line breaks setting applies to notebook Markdown cells", async ({ workbench: page }) => { + await openNotebook(page, "first line\nsecond line\nthird line\n\nhard one \nhard two\n\nnext paragraph"); + const paragraphs = region(page, 2).locator("p"); + await expect(paragraphs).toHaveCount(3); + await expect(paragraphs.nth(0).locator("br")).toHaveCount(0); + await expect(paragraphs.nth(1).locator("br")).toHaveCount(1); + + await chooseSoftLineBreaks(page, "Break on single newline"); + await expect(paragraphs).toHaveCount(3); + await expect(paragraphs.nth(0).locator("br")).toHaveCount(2); + await expect(paragraphs.nth(1).locator("br")).toHaveCount(1); + + await chooseSoftLineBreaks(page, "Standard Markdown"); + await expect(paragraphs).toHaveCount(3); + await expect(paragraphs.nth(0).locator("br")).toHaveCount(0); + await expect(paragraphs.nth(1).locator("br")).toHaveCount(1); +}); diff --git a/src/features/notebook/OutputView.test.tsx b/src/features/notebook/OutputView.test.tsx index 6c0f0813cf..8a9c4332da 100644 --- a/src/features/notebook/OutputView.test.tsx +++ b/src/features/notebook/OutputView.test.tsx @@ -1,5 +1,6 @@ -import { describe, expect, it, vi } from "vitest"; -import { createEvent, fireEvent, render } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { act, createEvent, fireEvent, render } from "@testing-library/react"; +import { useProject } from "@/platform/project"; const openExternalUrl = vi.hoisted(() => vi.fn(async () => {})); const sanitizedSvgUrl = vi.hoisted(() => vi.fn((_source: string) => "data:image/svg+xml,clean")); @@ -19,6 +20,10 @@ const { CellOutputs, MarkdownCell } = await import("./OutputView"); const PNG = "iVBORw0KGgo="; describe("notebook Markdown preview", () => { + afterEach(() => { + useProject.setState({ settings: null }); + }); + it("leaves native interactions such as
alone and only claims links", () => { const { container } = render( Morebody
"} attachments={{}} path="/p/a.ipynb" />, @@ -117,6 +122,38 @@ describe("notebook Markdown preview", () => { expect(container.querySelector(".katex-display")).not.toBeNull(); expect(container.querySelector("div[style]")).toBeNull(); }); + + it("updates rendered paragraphs immediately when the Markdown soft line breaks setting changes", () => { + const { container } = render( + , + ); + const paragraphs = () => container.querySelectorAll("p"); + expect(paragraphs()).toHaveLength(3); + expect(paragraphs()[0]?.querySelectorAll("br")).toHaveLength(0); + expect(paragraphs()[1]?.querySelectorAll("br")).toHaveLength(1); + + act(() => { + useProject.setState({ + settings: { languages: { markdown: { softLineBreaks: "break" } } } as never, + }); + }); + expect(paragraphs()).toHaveLength(3); + expect(paragraphs()[0]?.querySelectorAll("br")).toHaveLength(2); + expect(paragraphs()[1]?.querySelectorAll("br")).toHaveLength(1); + + act(() => { + useProject.setState({ + settings: { languages: { markdown: { softLineBreaks: "standard" } } } as never, + }); + }); + expect(paragraphs()).toHaveLength(3); + expect(paragraphs()[0]?.querySelectorAll("br")).toHaveLength(0); + expect(paragraphs()[1]?.querySelectorAll("br")).toHaveLength(1); + }); }); describe("notebook image outputs", () => { diff --git a/src/features/notebook/OutputView.tsx b/src/features/notebook/OutputView.tsx index df5fc61370..e620edf223 100644 --- a/src/features/notebook/OutputView.tsx +++ b/src/features/notebook/OutputView.tsx @@ -1,6 +1,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import Anser from "anser"; import { tx } from "@/platform/i18n"; +import { useMarkdownSoftLineBreaks } from "@/platform/languageSettings"; import { openExternalUrl } from "@/platform/openUrl"; import { subscribeTheme } from "@/platform/themeWatch"; import { editorService, notifications } from "@/workbench/contributions"; @@ -179,7 +180,8 @@ function referencedImages(names: string[], attachments: unknown) { export function MarkdownCell({ source, attachments, path }: { source: string; attachments: unknown; path: string }) { const ref = useRef(null); - const parsed = useMemo(() => markdownRoot(source), [source]); + const breaks = useMarkdownSoftLineBreaks() === "break"; + const parsed = useMemo(() => markdownRoot(source, { breaks }), [source, breaks]); const names = useMemo(() => markdownAttachmentNames(parsed), [parsed]); // Full snapshots carry fresh attachment objects. Rebuilding on identity would // re-render every visible preview per commit and drop a reader's selection, so diff --git a/src/features/notebook/security.test.ts b/src/features/notebook/security.test.ts index 21ac9b4679..1e958f3eaa 100644 --- a/src/features/notebook/security.test.ts +++ b/src/features/notebook/security.test.ts @@ -93,4 +93,25 @@ describe("static notebook output sanitization", () => { expect(link?.getAttribute("data-notebook-href")).toBe("./other.py#L8"); expect(root.querySelector("script,[style]")).toBeNull(); }); + + it("renders single newlines as
only when breaks is enabled, preserving hard breaks, code blocks and math", () => { + const source = + "First line\nSecond line\nThird line\n\nHard one \nHard two\n\n```python\na = 1\nb = 2\n```\n\n$$\n\\sum_{i=1}^n i\n$$"; + + const standard = markdownRoot(source); + const standardParagraphs = standard.querySelectorAll("p"); + expect(standardParagraphs).toHaveLength(2); + expect(standardParagraphs[0]?.querySelectorAll("br")).toHaveLength(0); + expect(standardParagraphs[1]?.querySelectorAll("br")).toHaveLength(1); + expect(standard.querySelectorAll("pre br")).toHaveLength(0); + expect(standard.querySelectorAll(".katex-display")).toHaveLength(1); + + const broken = markdownRoot(source, { breaks: true }); + const brokenParagraphs = broken.querySelectorAll("p"); + expect(brokenParagraphs).toHaveLength(2); + expect(brokenParagraphs[0]?.querySelectorAll("br")).toHaveLength(2); + expect(brokenParagraphs[1]?.querySelectorAll("br")).toHaveLength(1); + expect(broken.querySelectorAll("pre br")).toHaveLength(0); + expect(broken.querySelectorAll(".katex-display")).toHaveLength(1); + }); }); diff --git a/src/features/notebook/security.ts b/src/features/notebook/security.ts index baa72292aa..df5934efab 100644 --- a/src/features/notebook/security.ts +++ b/src/features/notebook/security.ts @@ -239,13 +239,15 @@ export function staticOutputDocument(html: string, palette?: OutputPalette): str return `${root.innerHTML}`; } -const markdown = new Marked({ gfm: true }).use(mathExtension()); +const markdown = new Marked({ gfm: true, breaks: false }).use(mathExtension()); +const markdownBreaks = new Marked({ gfm: true, breaks: true }).use(mathExtension()); /** * Sanitized Markdown with inert links; link clicks are handled by the editor and * `attachment:` images are left for `resolveMarkdownAttachments`. */ -export function markdownRoot(source: string): HTMLElement { - const root = htmlRoot(markdown.parse(source, { async: false }) as string, true); +export function markdownRoot(source: string, options?: { breaks?: boolean }): HTMLElement { + const parser = options?.breaks ? markdownBreaks : markdown; + const root = htmlRoot(parser.parse(source, { async: false }) as string, true); renderMath(root); for (const link of root.querySelectorAll("a[href]")) { const href = link.getAttribute("href")!; diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index 8ba1d6f79e..b0bfb9993d 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -276,7 +276,7 @@ export interface LanguagesValid { previewLayout: MarkdownPreviewLayout; /** Preview font size in px; `null` follows the editor font size. */ previewFontSize: number | null; - /** How single newlines inside a paragraph are rendered in the Markdown preview. */ + /** How single newlines inside a paragraph are rendered in Markdown previews and notebook Markdown cells. */ softLineBreaks: MarkdownSoftLineBreaks; /** Whether `.mdx` previews ask before running JSX, run automatically in trusted projects, or stay disabled. */ mdxExecution: MdxExecutionPolicy;