дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 17:21:13 +02:00
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 <[email protected]>
Цей коміт міститься в:
1 джерело
fe1838aca6
коміт
bd3f0cb651
6 files changed
+163
-66
No files matched your search
@@ -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<string, string> }) => {
|
||||
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<string, string> }) => {
|
||||
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);
|
||||
});
|
||||
@@ -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 <details> alone and only claims links", () => {
|
||||
const { container } = render(
|
||||
<MarkdownCell source={"<details><summary>More</summary>body</details>"} 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(
|
||||
<MarkdownCell
|
||||
source={"first line\nsecond line\nthird line\n\nhard one \nhard two\n\nnext paragraph"}
|
||||
attachments={{}}
|
||||
path="/p/a.ipynb"
|
||||
/>,
|
||||
);
|
||||
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", () => {
|
||||
|
||||
@@ -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<HTMLDivElement>(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
|
||||
|
||||
@@ -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 <br> 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);
|
||||
});
|
||||
});
|
||||
@@ -239,13 +239,15 @@ export function staticOutputDocument(html: string, palette?: OutputPalette): str
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:${fg};background:${bg};color-scheme:${scheme};overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid ${border};text-align:left}th{background:${headerBg}}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
|
||||
}
|
||||
|
||||
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")!;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Заблокувати користувача