From 2275546c2b4741a43cd927aaeaff7c0b39a11971 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Fri, 13 Nov 2026 14:45:27 +0100 Subject: [PATCH 01/14] test: cover BasicTextStyleButton with real editor interactions --- .../BasicTextStyleButton.browser.test.tsx | 210 +++++++++++++++++ ...BasicTextStyleButton.browser.test.tsx.snap | 211 +++++++++++++++++ .../FormattingToolbar.browser.test.tsx | 36 --- .../end-to-end/fixtures/selection.test.tsx | 131 +++++++++++ tests/src/fixtures/editor.tsx | 216 ++++++++++++++++++ tests/tsconfig.browser.json | 1 + tests/vitestSetup.browser.ts | 4 + 7 files changed, 773 insertions(+), 36 deletions(-) create mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx create mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap create mode 100644 tests/src/end-to-end/fixtures/selection.test.tsx create mode 100644 tests/src/fixtures/editor.tsx diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx new file mode 100644 index 0000000000..e3d912783d --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -0,0 +1,210 @@ +import { describe, expect } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { + BlockNoteSchema, + createStyleSpec, + defaultStyleSpecs, +} from "@blocknote/core"; +import { BasicTextStyleButton } from "./BasicTextStyleButton.js"; + +const STYLES = ["bold", "italic", "underline", "strike", "code"] as const; + +describe("BasicTextStyleButton", () => { + it.for(STYLES)( + "toggles %s on and off", + async (basicTextStyle, { renderEditor, selectText }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "format", type: "paragraph", content: "Format this text" }, + ], + // To test just the button, we don't even need the toolbar + // the button reads the editor context directly + props: { formattingToolbar: false }, + children: , + }); + + selectText(editor, "Format this text"); + + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); + + for (const state of ["on", "off"] as const) { + await button.click(); + + expect(editor.getBlock("format")).toMatchSnapshot(state); + await expect + .element(button) + .toHaveAttribute("aria-pressed", String(state === "on")); + } + }, + ); + + it.for(STYLES)( + "applies %s only to selected text without changing surrounding content", + async (basicTextStyle, { renderEditor, selectText }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "format", + type: "paragraph", + content: [ + { + type: "text", + text: "Before selected after", + styles: { textColor: "red" }, + }, + ], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); + + await button.click(); + + expect(editor.getBlock("format")?.content).toEqual([ + { type: "text", text: "Before ", styles: { textColor: "red" } }, + { + type: "text", + text: "selected", + // Inline code excludes other formatting styles. + styles: + basicTextStyle === "code" + ? { code: true } + : { textColor: "red", [basicTextStyle]: true }, + }, + { type: "text", text: " after", styles: { textColor: "red" } }, + ]); + }, + ); + + it.for(STYLES)( + "applies %s to subsequently typed text at a collapsed cursor", + async (basicTextStyle, { renderEditor }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "format", type: "paragraph", content: "Existing" }, + ], + props: { formattingToolbar: false }, + children: , + }); + editor.setTextCursorPosition("format", "end"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); + + await button.click(); + await userEvent.keyboard(" typed"); + + expect(editor.getBlock("format")?.content).toEqual([ + { type: "text", text: "Existing", styles: {} }, + { type: "text", text: " typed", styles: { [basicTextStyle]: true } }, + ]); + }, + ); + + it("hides in read-only mode and responds to editability changes", async ({ + renderEditor, + }) => { + const { rerender } = await renderEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + + rerender({ editable: true }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + rerender({ editable: false }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides when the style is missing from the schema", async ({ + renderEditor, + }) => { + await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { italic: defaultStyleSpecs.italic }, + }), + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides when the style has a non-boolean prop schema", async ({ + renderEditor, + }) => { + await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { + bold: createStyleSpec( + { type: "bold", propSchema: "string" }, + { render: () => ({ dom: document.createElement("span") }) }, + ), + }, + }), + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides on blocks without inline content and reappears on text blocks", async ({ + renderEditor, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "divider", type: "divider" }, + { id: "text", type: "paragraph", content: "Text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + editor.setTextCursorPosition("divider"); + await expect.element(button).not.toBeInTheDocument(); + + editor.setTextCursorPosition("text"); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + }); + + it("reflects the active style when selection moves between blocks", async ({ + renderEditor, + selectText, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "styled", + type: "paragraph", + content: [{ type: "text", text: "Bold", styles: { bold: true } }], + }, + { id: "plain", type: "paragraph", content: "Plain" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + + selectText(editor, "Plain"); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); +}); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap b/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap new file mode 100644 index 0000000000..91ddaaa00d --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap @@ -0,0 +1,211 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`BasicTextStyleButton > toggles bold on and off > off 1`] = ` +{ + "children": [], + "content": [ + { + "styles": {}, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles bold on and off > on 1`] = ` +{ + "children": [], + "content": [ + { + "styles": { + "bold": true, + }, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles code on and off > off 1`] = ` +{ + "children": [], + "content": [ + { + "styles": {}, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles code on and off > on 1`] = ` +{ + "children": [], + "content": [ + { + "styles": { + "code": true, + }, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles italic on and off > off 1`] = ` +{ + "children": [], + "content": [ + { + "styles": {}, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles italic on and off > on 1`] = ` +{ + "children": [], + "content": [ + { + "styles": { + "italic": true, + }, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles strike on and off > off 1`] = ` +{ + "children": [], + "content": [ + { + "styles": {}, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles strike on and off > on 1`] = ` +{ + "children": [], + "content": [ + { + "styles": { + "strike": true, + }, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles underline on and off > off 1`] = ` +{ + "children": [], + "content": [ + { + "styles": {}, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; + +exports[`BasicTextStyleButton > toggles underline on and off > on 1`] = ` +{ + "children": [], + "content": [ + { + "styles": { + "underline": true, + }, + "text": "Format this text", + "type": "text", + }, + ], + "id": "format", + "props": { + "backgroundColor": "default", + "textAlignment": "left", + "textColor": "default", + }, + "type": "paragraph", +} +`; diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx index 8db56b5548..869a15588c 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx @@ -95,42 +95,6 @@ const centeredToolbarDocument: PartialBlock[] = [ // Register these suites only in the regular browser run. if (!screenReader) { test.describe("behavior", () => { - test("formatting toolbar: Bold", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Bold"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); - - test("formatting toolbar: Italic", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Italic"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); - - test("formatting toolbar: Underline", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Underline"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); - - test("formatting toolbar: Strike", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Strike"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); - test("formatting toolbar: Align text left", async ({ onTestFinished }) => { const editor = await renderTestEditor(centeredToolbarDocument); await focusToolbarItem("Align text left"); diff --git a/tests/src/end-to-end/fixtures/selection.test.tsx b/tests/src/end-to-end/fixtures/selection.test.tsx new file mode 100644 index 0000000000..392b2bc2da --- /dev/null +++ b/tests/src/end-to-end/fixtures/selection.test.tsx @@ -0,0 +1,131 @@ +import { BlockNoteSchema, defaultStyleSpecs } from "@blocknote/core"; +import { describe, expect } from "vite-plus/test"; + +describe("selectText", () => { + it("finds a substring across differently marked text nodes", async ({ + renderEditor, + selectText, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: [ + { type: "text", text: "Before sel", styles: {} }, + { type: "text", text: "ect", styles: { bold: true } }, + { type: "text", text: "ed after", styles: { italic: true } }, + ], + }, + ], + }); + const documentBefore = editor.document; + + selectText(editor, "selected"); + + expect(editor.getSelectedText()).toBe("selected"); + expect(editor.document).toEqual(documentBefore); + }); + + it("resets the search at hard breaks and block boundaries", async ({ + renderEditor, + selectText, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { type: "paragraph", content: "split\nword" }, + { type: "paragraph", content: "split" }, + { type: "paragraph", content: "word" }, + { id: "match", type: "paragraph", content: "splitword" }, + ], + }); + + selectText(editor, "splitword"); + + expect(editor.getSelectedText()).toBe("splitword"); + expect(editor.getSelection()?.blocks.map((block) => block.id)).toEqual([ + "match", + ]); + }); + + it("restricts matching to one block by default, or an inclusive block range", async ({ + renderEditor, + selectText, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Repeated text" }, + { id: "start", type: "paragraph", content: "Repeated text" }, + { id: "end", type: "paragraph", content: "Last text" }, + { id: "after", type: "paragraph", content: "Outside text" }, + ], + }); + + selectText(editor, "Repeated", { startBlockId: "start" }); + + expect(editor.getSelectedText()).toBe("Repeated"); + expect(editor.getSelection()?.blocks.map((block) => block.id)).toEqual([ + "start", + ]); + expect(() => selectText(editor, "Last", { startBlockId: "start" })).toThrow( + 'selectText could not find "Last"', + ); + + selectText(editor, "Last", { startBlockId: "start", endBlockId: "end" }); + + expect(editor.getSelectedText()).toBe("Last"); + expect(editor.getSelection()?.blocks.map((block) => block.id)).toEqual([ + "end", + ]); + expect(() => + selectText(editor, "Outside", { + startBlockId: "start", + endBlockId: "end", + }), + ).toThrow('selectText could not find "Outside"'); + }); + + it("supports an editor with a custom schema", async ({ + renderEditor, + selectText, + }) => { + const { editor } = await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { italic: defaultStyleSpecs.italic }, + }), + initialContent: [{ type: "paragraph", content: "Custom schema" }], + }); + + selectText(editor, "schema"); + + expect(editor.getSelectedText()).toBe("schema"); + }); + + it("fails clearly for invalid input without changing the selection", async ({ + renderEditor, + selectText, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "first", type: "paragraph", content: "First" }, + { id: "last", type: "paragraph", content: "Last" }, + ], + }); + selectText(editor, "First"); + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + + expect(() => selectText(editor, "")).toThrow("non-empty substring"); + expect(() => selectText(editor, "Missing")).toThrow( + 'selectText could not find "Missing"', + ); + expect(() => + selectText(editor, "First", { startBlockId: "missing" }), + ).toThrow("could not find the requested block range"); + expect(() => + selectText(editor, "First", { + startBlockId: "last", + endBlockId: "first", + }), + ).toThrow("blocks in document order"); + expect(editor.prosemirrorState.selection.toJSON()).toEqual(selectionBefore); + }); +}); diff --git a/tests/src/fixtures/editor.tsx b/tests/src/fixtures/editor.tsx new file mode 100644 index 0000000000..372d3b17c7 --- /dev/null +++ b/tests/src/fixtures/editor.tsx @@ -0,0 +1,216 @@ +import { + BlockNoteEditor, + type BlockNoteEditorOptions, + BlockNoteSchema, + type BlockSchema, + type CustomBlockNoteSchema, + type DefaultBlockSchema, + type DefaultInlineContentSchema, + type DefaultStyleSchema, + type InlineContentSchema, + type StyleSchema, + getNodeById, +} from "@blocknote/core"; +import { BlockNoteView } from "@blocknote/mantine"; +import { TextSelection } from "@tiptap/pm/state"; +import "../../../packages/mantine/src/style.css"; +import type { ComponentProps, ReactNode } from "react"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; +import { test as base, type TestContext } from "vite-plus/test"; + +type ViewProps< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, +> = Omit>, "editor">; + +type RenderOptions< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, +> = Partial> & { + props?: Omit, "children">; + children?: + | ReactNode + | ((props: { editor: BlockNoteEditor }) => ReactNode); + outside?: (props: { + editor: BlockNoteEditor; + children: ReactNode; + }) => ReactNode; +}; + +type DefaultRenderOptions = Omit< + RenderOptions< + DefaultBlockSchema, + DefaultInlineContentSchema, + DefaultStyleSchema + >, + "schema" +> & { schema?: never }; + +// A named result keeps editor hovers from recursively expanding the factory's +// inferred ReturnType through the generic renderEditor overloads (TS 6). +type RenderedEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, +> = { + editor: BlockNoteEditor; + rerender: (props: ViewProps) => void; +}; + +function createRenderEditor(onFinished: TestContext["onTestFinished"]) { + async function renderWithSchema< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >(schema: CustomBlockNoteSchema, options: RenderOptions) { + const { props: viewProps, children, outside, ...editorOptions } = options; + const editor = BlockNoteEditor.create({ + ...editorOptions, + schema, + }); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + onFinished(() => { + root.unmount(); + editor._tiptapEditor.destroy(); + host.remove(); + }); + + let props = { + ...viewProps, + children: + typeof children === "function" ? children({ editor }) : children, + }; + function rerender(nextProps: ViewProps) { + props = { ...props, ...nextProps }; + flushSync(() => { + const children = ; + root.render(outside ? outside({ editor, children }) : children); + }); + } + rerender(props); + await document.fonts.ready; + return { editor, rerender }; + } + + function renderEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + options: RenderOptions & { + schema: CustomBlockNoteSchema; + }, + ): Promise>; + function renderEditor( + options?: DefaultRenderOptions, + ): Promise< + RenderedEditor< + DefaultBlockSchema, + DefaultInlineContentSchema, + DefaultStyleSchema + > + >; + function renderEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + options: + | (RenderOptions & { schema: CustomBlockNoteSchema }) + | DefaultRenderOptions = {}, + ) { + if (options.schema === undefined) { + return renderWithSchema(BlockNoteSchema.create(), options); + } + return renderWithSchema(options.schema, options); + } + return renderEditor; +} + +export type RenderEditor = ReturnType; + +/** Selects the first substring, ignoring marks but never crossing non-text nodes. */ +export function selectText( + editor: Pick, + substring: string, + range?: { startBlockId: string; endBlockId?: string }, +) { + if (substring.length === 0) { + throw new Error("selectText requires a non-empty substring"); + } + editor.transact((tr) => { + let from = 0; + let to = tr.doc.content.size; + if (range) { + const start = getNodeById(range.startBlockId, tr.doc); + const end = getNodeById(range.endBlockId ?? range.startBlockId, tr.doc); + if (!start || !end) { + throw new Error("selectText could not find the requested block range"); + } + from = start.posBeforeNode; + to = end.posBeforeNode + end.node.nodeSize; + if (from >= to) { + throw new Error("selectText requires blocks in document order"); + } + } + + let text = ""; + let textStart = 0; + let match: { from: number; to: number } | undefined; + tr.doc.nodesBetween(from, to, (node, pos) => { + if (match) { + return false; + } + if (!node.isText) { + if (node.isBlock || node.isLeaf) { + text = ""; + } + return true; + } + // Adjacent text nodes can have different marks. Gaps indicate a hard + // break, another inline node, or a new block, and must reset the search. + if (pos !== textStart + text.length) { + text = ""; + textStart = pos; + } + text += node.textContent; + const index = text.indexOf(substring); + if (index !== -1) { + match = { + from: textStart + index, + to: textStart + index + substring.length, + }; + } + return true; + }); + if (!match) { + throw new Error(`selectText could not find ${JSON.stringify(substring)}`); + } + tr.setSelection(TextSelection.create(tr.doc, match.from, match.to)); + }); +} + +export const test = base.extend<{ + renderEditor: RenderEditor; + selectText: typeof selectText; +}>({ + renderEditor: async ({ onTestFinished }, use) => { + await use(createRenderEditor(onTestFinished)); + }, + // Vitest requires destructured fixture arguments, even without dependencies. + // eslint-disable-next-line no-empty-pattern + selectText: async ({}, use) => { + await use(selectText); + }, +}); + +// The browser setup installs this extended API; imported Vitest APIs are not +// extended. tests/tsconfig.browser.json includes the setup for colocated tests. +declare global { + var it: typeof test; +} diff --git a/tests/tsconfig.browser.json b/tests/tsconfig.browser.json index 3f395e49b7..4c439e0446 100644 --- a/tests/tsconfig.browser.json +++ b/tests/tsconfig.browser.json @@ -23,6 +23,7 @@ "include": [ "src/utils/**/*.ts", "src/utils/**/*.tsx", + "src/fixtures/**/*.tsx", "screen-reader/**/*.ts", "vitestSetup.browser.ts", "../packages/*/src/**/*.browser.test.*", diff --git a/tests/vitestSetup.browser.ts b/tests/vitestSetup.browser.ts index fd93e2712c..fac83ee0d6 100644 --- a/tests/vitestSetup.browser.ts +++ b/tests/vitestSetup.browser.ts @@ -2,8 +2,12 @@ import type {} from "./src/utils/keyboard.js"; import { afterEach, beforeAll, beforeEach } from "vite-plus/test"; import { commands, page } from "./src/utils/context.js"; +import { test } from "./src/fixtures/editor.js"; import { ensureTouchEmulation } from "./src/utils/ensureTouchEmulation.js"; +// Only the global `it` uses these fixtures; imported Vitest APIs stay unchanged. +globalThis.it = test; + // Browser-mode setup. Unlike the jsdom `vitestSetup.ts`, we don't mock // ClipboardEvent/DragEvent/matchMedia here — the real browser provides them. // We only seed the `window.__TEST_OPTIONS` object that examples read from From b014b3d2a13db527e010f22c2edd9d14509c0904 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Fri, 13 Nov 2026 18:02:50 +0100 Subject: [PATCH 02/14] test: establish focused component testing examples --- .../BasicTextStyleButton.browser.test.tsx | 43 +- .../ColorStyleButton.browser.test.tsx | 174 +++++ .../CreateLinkButton.browser.test.tsx | 121 ++++ .../NestBlockButtons.browser.test.tsx | 99 +++ .../TextAlignButton.browser.test.tsx | 46 ++ .../BlockTypeSelect.browser.test.tsx | 225 +++++++ ...rmattingToolbarController.browser.test.tsx | 115 ++++ .../FormattingToolbar.browser.test.tsx | 625 +++++------------- .../FormattingToolbar.screen-reader.test.ts | 55 +- .../FormattingToolbar.browser.test.tsx.snap | 135 ---- tests/src/fixtures/editor.tsx | 5 + 11 files changed, 1015 insertions(+), 628 deletions(-) create mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx create mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx create mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx create mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx create mode 100644 packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx create mode 100644 packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx delete mode 100644 packages/react/src/components/FormattingToolbar/__snapshots__/FormattingToolbar.browser.test.tsx.snap diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx index e3d912783d..ec75f92202 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -1,5 +1,5 @@ import { describe, expect } from "vite-plus/test"; -import { page, userEvent } from "vite-plus/test/browser"; +import { userEvent } from "vite-plus/test/browser"; import { BlockNoteSchema, @@ -13,7 +13,7 @@ const STYLES = ["bold", "italic", "underline", "strike", "code"] as const; describe("BasicTextStyleButton", () => { it.for(STYLES)( "toggles %s on and off", - async (basicTextStyle, { renderEditor, selectText }) => { + async (basicTextStyle, { renderEditor, selectText, page }) => { const { editor } = await renderEditor({ initialContent: [ { id: "format", type: "paragraph", content: "Format this text" }, @@ -44,7 +44,7 @@ describe("BasicTextStyleButton", () => { it.for(STYLES)( "applies %s only to selected text without changing surrounding content", - async (basicTextStyle, { renderEditor, selectText }) => { + async (basicTextStyle, { renderEditor, selectText, page }) => { const { editor } = await renderEditor({ initialContent: [ { @@ -88,7 +88,7 @@ describe("BasicTextStyleButton", () => { it.for(STYLES)( "applies %s to subsequently typed text at a collapsed cursor", - async (basicTextStyle, { renderEditor }) => { + async (basicTextStyle, { renderEditor, page }) => { const { editor } = await renderEditor({ initialContent: [ { id: "format", type: "paragraph", content: "Existing" }, @@ -114,6 +114,7 @@ describe("BasicTextStyleButton", () => { it("hides in read-only mode and responds to editability changes", async ({ renderEditor, + page, }) => { const { rerender } = await renderEditor({ props: { editable: false, formattingToolbar: false }, @@ -131,6 +132,7 @@ describe("BasicTextStyleButton", () => { it("hides when the style is missing from the schema", async ({ renderEditor, + page, }) => { await renderEditor({ schema: BlockNoteSchema.create({ @@ -145,6 +147,7 @@ describe("BasicTextStyleButton", () => { it("hides when the style has a non-boolean prop schema", async ({ renderEditor, + page, }) => { await renderEditor({ schema: BlockNoteSchema.create({ @@ -164,6 +167,7 @@ describe("BasicTextStyleButton", () => { it("hides on blocks without inline content and reappears on text blocks", async ({ renderEditor, + page, }) => { const { editor } = await renderEditor({ initialContent: [ @@ -184,6 +188,7 @@ describe("BasicTextStyleButton", () => { it("reflects the active style when selection moves between blocks", async ({ renderEditor, selectText, + page, }) => { const { editor } = await renderEditor({ initialContent: [ @@ -207,4 +212,34 @@ describe("BasicTextStyleButton", () => { selectText(editor, "Bold"); await expect.element(button).toHaveAttribute("aria-pressed", "true"); }); + + describe("keyboard", () => { + it("can be activated with Enter and returns focus to the editor", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.bold.tooltip, + exact: true, + }); + + await commands.pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + + await commands.pressKey("Enter"); + + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx new file mode 100644 index 0000000000..a172fe4022 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -0,0 +1,174 @@ +import { BlockNoteSchema, defaultStyleSpecs } from "@blocknote/core"; +import { describe, expect } from "vite-plus/test"; +import { ColorStyleButton } from "./ColorStyleButton.js"; + +describe("ColorStyleButton", () => { + describe("unit", () => { + it("only offers text colors when the schema does not support background colors", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { textColor: defaultStyleSpecs.textColor }, + }), + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + + const menu = page.getByRole("menu"); + await expect + .element( + menu.getByText(editor.dictionary.color_picker.text_title, { + exact: true, + }), + ) + .toBeVisible(); + await expect + .element( + menu.getByText(editor.dictionary.color_picker.background_title, { + exact: true, + }), + ) + .not.toBeInTheDocument(); + }); + + it("applies the chosen text color only to the selected substring", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Before selected after" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + await button.click(); + + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .first() + .click(); + + expect(editor.getBlock("text")?.content).toEqual([ + { type: "text", text: "Before ", styles: {} }, + { type: "text", text: "selected", styles: { textColor: "gray" } }, + { type: "text", text: " after", styles: {} }, + ]); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + }); + + describe("keyboard", () => { + it("supports opening, navigating, and dismissing its menu without editing the document", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + const documentBefore = editor.document; + + button.element().focus(); + + await expect.element(button).toHaveFocus(); + + await commands.pressKey("Enter"); + + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + const firstItem = menu.getByRole("menuitem").first(); + const outline = await commands.readOutline(firstItem.selector); + + await commands.pressKey("ArrowDown"); + + await expect.element(firstItem).toHaveFocus(); + await commands.checkFocusOutline(firstItem.selector, outline); + + await commands.pressKey("Escape"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect.element(button).toHaveFocus(); + expect(editor.document).toEqual(documentBefore); + }); + }); + + describe("ARIA", () => { + // Expected failure in our Mantine adapter (packages/mantine/src/menu/Menu.tsx): + // it renders `checked` as a visual checkmark without exposing the checked + // state to assistive technology. + it.fails("exposes a color change in the trigger or menu's accessibility tree", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + await button.click(); + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + const before = [ + await commands.readAriaSnapshot(button.selector), + await commands.readAriaSnapshot(menu.selector), + ].join("\n"); + + await menu + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .first() + .click(); + await expect.element(menu).not.toBeInTheDocument(); + await button.click(); + + await expect.element(menu).toBeVisible(); + const after = [ + await commands.readAriaSnapshot(button.selector), + await commands.readAriaSnapshot(menu.selector), + ].join("\n"); + expect(after).not.toBe(before); + }); + }); +}); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx new file mode 100644 index 0000000000..7e91ff7460 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -0,0 +1,121 @@ +import { describe, expect } from "vite-plus/test"; +import { CreateLinkButton } from "./CreateLinkButton.js"; + +describe("CreateLinkButton", () => { + it("submits a link for the original substring and returns focus to the editor", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: "Before selected text after", + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected text"); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + + await input.fill("https://example.com"); + await commands.pressKey("Enter"); + + expect(editor.getBlock("text")?.content).toEqual([ + { type: "text", text: "Before ", styles: {} }, + { + type: "link", + href: "https://example.com", + content: [{ type: "text", text: "selected text", styles: {} }], + }, + { type: "text", text: " after", styles: {} }, + ]); + await expect.element(input).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + + it("opens the link form without changing the selected text range or document", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: "Before selected text after", + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected text"); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + + await expect + .element( + page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ), + ) + .toHaveFocus(); + expect(editor.prosemirrorState.selection.toJSON()).toEqual(selectionBefore); + expect(editor.document).toEqual(documentBefore); + }); + + describe("axe", () => { + it("opens a link form with no automated accessibility violations", async ({ + renderEditor, + selectText, + annotate, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + + await expect + .element( + page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ), + ) + .toBeVisible(); + for (const warning of await commands.checkAxe(".bn-form-popover")) { + await annotate(warning, "warning"); + } + }); + }); +}); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx new file mode 100644 index 0000000000..0f6c21f909 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -0,0 +1,99 @@ +import { describe, expect } from "vite-plus/test"; +import { NestBlockButton, UnnestBlockButton } from "./NestBlockButtons.js"; + +describe("NestBlockButton", () => { + it("updates its disabled state when selection moves to a block that can be nested", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { type: "paragraph", content: "First block" }, + { type: "paragraph", content: "Second block" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.nest.tooltip, + exact: true, + }); + selectText(editor, "First block"); + + await expect.element(button).toBeDisabled(); + + selectText(editor, "Second block"); + + await expect.element(button).toBeEnabled(); + }); + + it("moves the selected block under its previous sibling without changing their contents", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "parent", type: "paragraph", content: "Parent" }, + { id: "selected", type: "paragraph", content: "Selected text" }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const [parent, selected, after] = editor.document; + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.nest.tooltip, + exact: true, + }) + .click(); + + expect(editor.document).toEqual([ + { ...parent, children: [selected] }, + after, + ]); + }); +}); + +describe("UnnestBlockButton", () => { + it("moves the selected block out of its parent without changing their contents", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "parent", + type: "paragraph", + content: "Parent", + children: [ + { id: "selected", type: "paragraph", content: "Selected text" }, + ], + }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const [parent, after] = editor.document; + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.unnest.tooltip, + exact: true, + }) + .click(); + + expect(editor.document).toEqual([ + { ...parent, children: [] }, + parent.children[0], + after, + ]); + }); +}); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx new file mode 100644 index 0000000000..6b6489ca47 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -0,0 +1,46 @@ +import { describe, expect } from "vite-plus/test"; +import { TextAlignButton } from "./TextAlignButton.js"; + +describe("TextAlignButton", () => { + it.for(["left", "center", "right"] as const)( + "aligns the selected block %s without changing its text or neighboring blocks", + async (textAlignment, { renderEditor, selectText, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { + id: "selected", + type: "paragraph", + props: { + textAlignment: textAlignment === "left" ? "center" : "left", + }, + content: "Selected text", + }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const documentBefore = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[`align_${textAlignment}`] + .tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + await button.click(); + + expect(editor.document).toEqual([ + documentBefore[0], + { + ...documentBefore[1], + props: { ...documentBefore[1].props, textAlignment }, + }, + documentBefore[2], + ]); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }, + ); +}); diff --git a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx new file mode 100644 index 0000000000..bd17bd40ee --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -0,0 +1,225 @@ +import { describe, expect } from "vite-plus/test"; +import { FormattingToolbar } from "../FormattingToolbar.js"; +import { BlockTypeSelect } from "./BlockTypeSelect.js"; + +describe("BlockTypeSelect", () => { + it("filters custom choices whose block type or property types do not match the schema", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + props: { formattingToolbar: false }, + children: ({ editor }) => ( + null, + }, + { name: "Unavailable block", type: "missing", icon: () => null }, + { + name: "Invalid heading", + type: "heading", + props: { level: "one" }, + icon: () => null, + }, + ]} + /> + ), + }); + + await page + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); + + const items = page.getByRole("menu").getByRole("menuitem"); + await expect.element(items).toHaveLength(1); + await expect + .element(items) + .toHaveTextContent(editor.dictionary.slash_menu.paragraph.title); + }); + + it("converts the selected block and updates its label without changing neighboring blocks or text", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { id: "selected", type: "paragraph", content: "Selected text" }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const documentBefore = editor.document; + + await page + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }) + .click(); + + expect(editor.document).toEqual([ + documentBefore[0], + { + ...documentBefore[1], + type: "heading", + props: { + ...documentBefore[1].props, + level: 1, + isToggleable: false, + }, + }, + documentBefore[2], + ]); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }), + ) + .toBeVisible(); + }); + + describe("keyboard", () => { + it("opens, navigates, and chooses a block type from the keyboard", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + button.element().focus(); + await expect.element(button).toHaveFocus(); + + await commands.pressKey("Enter"); + + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + const paragraph = menu.getByRole("menuitem", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + const heading = menu.getByRole("menuitem", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }); + const outline = await commands.readOutline(heading.selector); + + await commands.pressKey("ArrowDown"); + + await expect.element(paragraph).toHaveFocus(); + + await commands.pressKey("ArrowDown"); + + await expect.element(heading).toHaveFocus(); + await commands.checkFocusOutline(heading.selector, outline); + + await commands.pressKey("Enter"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }), + ) + .toHaveFocus(); + expect(editor.getBlock("text")?.type).toBe("heading"); + }); + }); + + describe("axe", () => { + it("checks the trigger", async ({ + renderEditor, + selectText, + commands, + page, + annotate, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + await expect.element(button).toBeVisible(); + + for (const warning of await commands.checkAxe('[role="toolbar"]')) { + await annotate(warning, "warning"); + } + }); + + // Expected failure: Mantine inserts a focusable placeholder div inside the + // menu, violating aria-required-children. + it.fails("checks the open menu", async ({ + renderEditor, + selectText, + commands, + page, + annotate, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + selectText(editor, "Selected text"); + + await page + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); + + await expect.element(page.getByRole("menu")).toBeVisible(); + for (const warning of await commands.checkAxe('[role="menu"]')) { + await annotate(warning, "warning"); + } + }); + }); +}); diff --git a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx new file mode 100644 index 0000000000..34ff27889c --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx @@ -0,0 +1,115 @@ +import { FormattingToolbarExtension } from "@blocknote/core/extensions"; +import { describe, expect } from "vite-plus/test"; +import { DesktopFormattingToolbarController } from "./DesktopFormattingToolbarController.js"; + +describe("DesktopFormattingToolbarController", () => { + it("mounts its custom toolbar while the extension requests it and unmounts it on dismissal", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); + const extension = editor.getExtension(FormattingToolbarExtension)!; + const toolbar = page.getByRole("toolbar"); + selectText(editor, "Selected text"); + extension.store.setState(false); + await expect.element(toolbar).not.toBeInTheDocument(); + + extension.store.setState(true); + + await expect + .element( + toolbar.getByRole("button", { name: "Custom action", exact: true }), + ) + .toBeVisible(); + + extension.store.setState(false); + + await expect.element(toolbar).not.toBeInTheDocument(); + }); + + it("dismisses with Escape and restores editor focus without changing its selection or document", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); + selectText(editor, "Selected text"); + await page + .getByRole("button", { name: "Custom action", exact: true }) + .click(); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + + await commands.pressKey("Escape"); + + expect(editor.getExtension(FormattingToolbarExtension)!.store.state).toBe( + false, + ); + await expect.element(page.getByRole("toolbar")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + expect(editor.prosemirrorState.selection.toJSON()).toEqual(selectionBefore); + expect(editor.document).toEqual(documentBefore); + }); + + it("renders its toolbar into the supplied portal", async ({ + renderEditor, + selectText, + page, + onTestFinished, + }) => { + const portal = document.createElement("div"); + document.body.append(portal); + onTestFinished(() => portal.remove()); + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); + + selectText(editor, "Selected text"); + + await expect.element(page.getByRole("toolbar")).toBeVisible(); + expect(portal.contains(page.getByRole("toolbar").element())).toBe(true); + }); +}); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx index 869a15588c..3275c6e873 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx @@ -1,511 +1,200 @@ -import { commands } from "@root/tests/src/utils/context.js"; -import { selectToLineEndKey } from "@root/tests/src/utils/context.js"; -import { type PartialBlock } from "@blocknote/core"; -import { expect, test, vi } from "vite-plus/test"; -import "@blocknote/core/fonts/inter.css"; -import { BlockNoteView } from "@blocknote/mantine"; -import "@blocknote/mantine/style.css"; -import { useCreateBlockNote } from "@blocknote/react"; -import { useEffect } from "react"; -import { render } from "vitest-browser-react"; -import type { BlockNoteEditor } from "@blocknote/core"; -import { page, server } from "vite-plus/test/browser"; - -function TestEditor({ - initialContent, - onReady, -}: { - initialContent: PartialBlock[]; - onReady: (editor: BlockNoteEditor) => void; -}) { - const editor = useCreateBlockNote({ initialContent }); - useEffect(() => { - onReady(editor); - }, [editor, onReady]); - return ; -} - -export async function renderTestEditor(initialContent: PartialBlock[]) { - let editor!: BlockNoteEditor; - await render( - { - editor = instance; - }} - />, - ); - await expect.element(page.getByRole("textbox")).toBeVisible(); - await document.fonts.ready; - editor.focus(); - return editor; -} - -const screenReader = - server.config.name === "voiceover" || server.config.name === "nvda"; - -// Start with the editor focused after renderTestEditor(). Keep the navigation steps -// identical to focusToolbarItemWithAssertions in the keyboard suite. -export async function focusToolbarItem(toolbarItem: string) { - await commands.pressKey("ArrowDown"); - await commands.pressKey(selectToLineEndKey); - const toolbar = page.getByRole("toolbar"); - await commands.pressKey("Tab"); - const target = toolbar.getByRole("button", { - name: toolbarItem, - exact: true, - }); - while (document.activeElement !== target.element()) { - await commands.pressKey("Tab"); - } - return { toolbar, button: target }; -} - -// The middle paragraph is selected; its neighbours provide navigation context. -export const toolbarDocument: PartialBlock[] = [ - { id: "preceding", type: "paragraph", content: "Preceding paragraph" }, - { id: "format", type: "paragraph", content: "Format this text" }, - { id: "following", type: "paragraph", content: "Following paragraph" }, -]; - -const nestedToolbarDocument: PartialBlock[] = [ - { - id: "preceding", - type: "paragraph", - content: "Preceding paragraph", - children: [ - { id: "format", type: "paragraph", content: "Format this text" }, - ], - }, -]; - -// Left alignment must change the selected paragraph rather than reapply its default. -const centeredToolbarDocument: PartialBlock[] = [ - { id: "preceding", type: "paragraph", content: "Preceding paragraph" }, - { - id: "format", - type: "paragraph", - props: { textAlignment: "center" }, - content: "Format this text", - }, - { id: "following", type: "paragraph", content: "Following paragraph" }, -]; - -// Screen-reader tests import the shared helpers and fixtures from this file. -// Register these suites only in the regular browser run. -if (!screenReader) { - test.describe("behavior", () => { - test("formatting toolbar: Align text left", async ({ onTestFinished }) => { - const editor = await renderTestEditor(centeredToolbarDocument); - await focusToolbarItem("Align text left"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); - - test("formatting toolbar: Align text center", async ({ - onTestFinished, +import { describe, expect } from "vite-plus/test"; +import { BasicTextStyleButton } from "./DefaultButtons/BasicTextStyleButton.js"; +import { FormattingToolbar } from "./FormattingToolbar.js"; + +describe("FormattingToolbar", () => { + describe("unit", () => { + it("allows custom children instead of default controls", async ({ + renderEditor, + page, }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Align text center"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); - - test("formatting toolbar: Align text right", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Align text right"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); + await renderEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); - test("formatting toolbar: Colors", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Colors"); - await commands.pressKey("Enter"); - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - // Mantine initially focuses a placeholder before the first menu item. + const toolbar = page.getByRole("toolbar"); + await expect.element(toolbar.getByRole("button")).toHaveLength(1); await expect - .element(menu.element().querySelector("[data-autofocus]")) - .toHaveFocus(); - await commands.pressKey("ArrowDown"); - await commands.pressKey("ArrowDown"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); + .element( + toolbar.getByRole("button", { name: "Custom action", exact: true }), + ) + .toBeVisible(); }); - test("formatting toolbar: Nest block", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Nest block"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); + it("passes custom block-type choices to its select", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + props: { formattingToolbar: false }, + children: ({ editor }) => ( + null, + }, + ]} + /> + ), + }); - test("formatting toolbar: Unnest block", async ({ onTestFinished }) => { - const editor = await renderTestEditor(nestedToolbarDocument); - await focusToolbarItem("Unnest block"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); - }); + await page + .getByRole("toolbar") + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); - test("formatting toolbar: Paragraph", async ({ onTestFinished }) => { - const editor = await renderTestEditor(toolbarDocument); - await focusToolbarItem("Paragraph"); - await commands.pressKey("Enter"); const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - // Mantine initially focuses a placeholder before the first menu item. + await expect.element(menu.getByRole("menuitem")).toHaveLength(1); await expect - .element(menu.element().querySelector("[data-autofocus]")) - .toHaveFocus(); - await commands.pressKey("ArrowDown"); - await commands.pressKey("ArrowDown"); - const onChange = vi.fn(); - onTestFinished(editor.onChange(onChange)); - await commands.pressKey("Enter"); - expect(onChange).toHaveBeenCalled(); + .element( + menu.getByRole("menuitem", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }), + ) + .toBeVisible(); }); }); - test.describe("keyboard", () => { - // Same navigation as the shared focusToolbarItem, with focus assertions. - async function focusToolbarItemWithAssertions(toolbarItem: string) { - const editor = page.getByRole("textbox"); - await expect.element(editor).toHaveFocus(); - await commands.pressKey("ArrowDown"); - await commands.pressKey(selectToLineEndKey); - const toolbar = page.getByRole("toolbar"); - await expect.element(toolbar).toBeVisible(); - const target = toolbar.getByRole("button", { - name: toolbarItem, - exact: true, + describe("integration", () => { + it("preserves the editor selection while keyboard focus moves through the toolbar", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { type: "paragraph", content: "Before selected text after" }, + ], }); - const unfocusedOutline = await commands.readOutline(target.selector); - await commands.pressKey("Tab"); - await expect - .poll(() => toolbar.element().contains(document.activeElement)) - .toBe(true); - while (document.activeElement !== target.element()) { - await commands.pressKey("Tab"); - } - await expect.element(target).toHaveFocus(); - await commands.checkFocusOutline(target.selector, unfocusedOutline); - return { toolbar, button: target }; - } + await page.getByRole("textbox").click(); + selectText(editor, "selected text"); + const toolbar = page.getByRole("toolbar"); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); - async function checkToolbarButtonKeyboard(toolbarButton: string) { - await focusToolbarItemWithAssertions(toolbarButton); - await commands.pressKey("Enter"); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - } + await commands.pressKey("Tab"); - async function checkToolbarMenuKeyboard( - toolbarMenu: string, - item: () => ReturnType, - ) { - await focusToolbarItemWithAssertions(toolbarMenu); - await commands.pressKey("Enter"); - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - // Mantine initially focuses a placeholder before the first menu item. await expect - .element(menu.element().querySelector("[data-autofocus]")) + .element( + toolbar.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }), + ) .toHaveFocus(); - const firstItem = menu.getByRole("menuitem").first(); - const unfocusedOutline = await commands.readOutline(firstItem.selector); - await commands.pressKey("ArrowDown"); - await expect.element(firstItem).toHaveFocus(); - await commands.checkFocusOutline(firstItem.selector, unfocusedOutline); - const targetItem = item(); - const targetUnfocusedOutline = await commands.readOutline( - targetItem.selector, - ); - await commands.pressKey("ArrowDown"); - await expect.element(targetItem).toHaveFocus(); - await commands.checkFocusOutline( - targetItem.selector, - targetUnfocusedOutline, + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, ); - await commands.pressKey("Enter"); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - } - async function checkToolbarSelectKeyboard( - toolbarSelect: string, - selectedValue: string, - ) { - await focusToolbarItemWithAssertions(toolbarSelect); - await commands.pressKey("Enter"); - // Mantine implements the select using a menu and initially focuses a - // placeholder before the first option. - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - await expect - .element(menu.element().querySelector("[data-autofocus]")) - .toHaveFocus(); - const firstItem = menu.getByRole("menuitem").first(); - const unfocusedOutline = await commands.readOutline(firstItem.selector); - await commands.pressKey("ArrowDown"); - await expect.element(firstItem).toHaveFocus(); - await commands.checkFocusOutline(firstItem.selector, unfocusedOutline); - const targetItem = menu.getByRole("menuitem", { - name: selectedValue, - exact: true, - }); - const targetUnfocusedOutline = await commands.readOutline( - targetItem.selector, - ); - await commands.pressKey("ArrowDown"); - await expect.element(targetItem).toHaveFocus(); - await commands.checkFocusOutline( - targetItem.selector, - targetUnfocusedOutline, - ); - await commands.pressKey("Enter"); - // Selects return focus to the trigger, unlike menus, which focus the editor. + await commands.pressKey("Tab"); + await expect - .element(page.getByRole("button", { name: selectedValue, exact: true })) + .element( + toolbar.getByRole("button", { + name: editor.dictionary.formatting_toolbar.bold.tooltip, + exact: true, + }), + ) .toHaveFocus(); - } - - async function checkToolbarPopoverKeyboard( - toolbarPopover: string, - input: ReturnType, - ) { - await focusToolbarItemWithAssertions(toolbarPopover); - await commands.pressKey("Enter"); - await expect.element(input).toHaveFocus(); - await commands.checkFocusOutline(input.selector); - await commands.pressKey("Escape"); - await expect.element(input).not.toBeInTheDocument(); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - } - - test("formatting toolbar: Paragraph", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarSelectKeyboard("Paragraph", "Heading 1"); - }); - - test("formatting toolbar: Bold", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Bold"); - }); - - test("formatting toolbar: Italic", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Italic"); - }); - - test("formatting toolbar: Underline", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Underline"); - }); - - test("formatting toolbar: Strike", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Strike"); - }); - - test("formatting toolbar: Align text left", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Align text left"); - }); - - test("formatting toolbar: Align text center", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Align text center"); - }); - - test("formatting toolbar: Align text right", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Align text right"); - }); - - test("formatting toolbar: Colors", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarMenuKeyboard("Colors", () => - page.elementLocator( - document.querySelector('[data-test="text-color-gray"]')!, - ), - ); - }); - - test("formatting toolbar: Nest block", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Nest block"); - }); - - test("formatting toolbar: Unnest block", async () => { - await renderTestEditor(nestedToolbarDocument); - await checkToolbarButtonKeyboard("Unnest block"); - }); - - // The autofocused URL input has outline-style: none in all three browsers. - // Enable once the input has a visible keyboard focus outline. - test.skip("formatting toolbar: Create link", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarPopoverKeyboard( - "Create link", - page.getByPlaceholder("Edit URL"), + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, ); + expect(editor.document).toEqual(documentBefore); }); }); - test.describe("ARIA", () => { - async function checkToolbarButtonAria(toolbarButton: string) { - const { button } = await focusToolbarItem(toolbarButton); - expect(await commands.readAriaSnapshot(button.selector)).toMatchSnapshot( - "before activation", - ); - await commands.pressKey("Enter"); - expect(await commands.readAriaSnapshot(button.selector)).toMatchSnapshot( - "after activation", - ); - } - - async function checkToolbarMenuAria( - toolbarMenu: string, - activatedName: string, - ) { - const { toolbar, button } = await focusToolbarItem(toolbarMenu); - expect(await commands.readAriaSnapshot(button.selector)).toMatchSnapshot( - "before activation", - ); - await commands.pressKey("Enter"); - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - // Mantine initially focuses a placeholder before the first menu item. - await expect - .element(menu.element().querySelector("[data-autofocus]")) - .toHaveFocus(); - await commands.pressKey("ArrowDown"); - await commands.pressKey("ArrowDown"); - await commands.pressKey("Enter"); - expect( - await commands.readAriaSnapshot( - toolbar.getByRole("button", { name: activatedName, exact: true }) - .selector, + describe("keyboard", () => { + it("provides visible keyboard focus when entering and traversing its controls", async ({ + renderEditor, + commands, + page, + }) => { + const { editor } = await renderEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), - ).toMatchSnapshot("after activation"); - } - - test("formatting toolbar: complete accessibility tree", async () => { - await renderTestEditor(toolbarDocument); - const { toolbar } = await focusToolbarItem("Paragraph"); - expect(await commands.readAriaSnapshot(toolbar.selector)).toMatchSnapshot( - "toolbar", - ); - }); - - test("formatting toolbar: Paragraph", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarMenuAria("Paragraph", "Heading 1"); - }); - - test("formatting toolbar: Bold", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Bold"); - }); - - test("formatting toolbar: Italic", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Italic"); - }); - - test("formatting toolbar: Underline", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Underline"); - }); - - test("formatting toolbar: Strike", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Strike"); - }); + }); + await page.getByRole("textbox").click(); + const first = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.bold.tooltip, + exact: true, + }); + const second = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.italic.tooltip, + exact: true, + }); + const firstOutline = await commands.readOutline(first.selector); + const secondOutline = await commands.readOutline(second.selector); - test("formatting toolbar: Align text left", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Align text left"); - }); + await commands.pressKey("Tab"); - test("formatting toolbar: Align text center", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Align text center"); - }); + await expect.element(first).toHaveFocus(); + await commands.checkFocusOutline(first.selector, firstOutline); - test("formatting toolbar: Align text right", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Align text right"); - }); + await commands.pressKey("Tab"); - test("formatting toolbar: Colors", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarMenuAria("Colors", "Colors"); + await expect.element(second).toHaveFocus(); + await commands.checkFocusOutline(second.selector, secondOutline); }); + }); - test("formatting toolbar: Nest block", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Nest block"); - }); + describe("ARIA", () => { + it("exposes its custom controls as a toolbar", async ({ + renderEditor, + commands, + page, + }) => { + await renderEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); - test("formatting toolbar: Unnest block", async () => { - await renderTestEditor(nestedToolbarDocument); - await checkToolbarButtonAria("Unnest block"); + expect( + await commands.readAriaSnapshot(page.getByRole("toolbar").selector), + ).toMatchInlineSnapshot(` + "- toolbar: + - button "Custom action"" + `); }); }); - test.describe("axe", () => { - test("formatting toolbar: axe", async ({ annotate }) => { - await renderTestEditor(toolbarDocument); - await focusToolbarItem("Paragraph"); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } - }); - - // Mantine inserts a focusable div inside the menu, triggering axe aria-required-children violations. - test.skip("formatting toolbar: block type menu axe", async ({ + describe("axe", () => { + it("has no automated accessibility violations with the default controls", async ({ + renderEditor, + selectText, annotate, + commands, + page, }) => { - await renderTestEditor(toolbarDocument); - await focusToolbarItem("Paragraph"); - await commands.pressKey("Enter"); - await expect.element(page.getByRole("menu")).toBeVisible(); - for (const warning of await commands.checkAxe('[role="menu"]')) { - await annotate(warning, "warning"); - } - }); - - // Mantine inserts a focusable div inside the menu, triggering axe aria-required-children violations. - test.skip("formatting toolbar: colors menu axe", async ({ annotate }) => { - await renderTestEditor(toolbarDocument); - await focusToolbarItem("Colors"); - await commands.pressKey("Enter"); - await expect.element(page.getByRole("menu")).toBeVisible(); - for (const warning of await commands.checkAxe('[role="menu"]')) { - await annotate(warning, "warning"); - } - }); + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + }); + selectText(editor, "Selected text"); + await expect.element(page.getByRole("toolbar")).toBeVisible(); - test("formatting toolbar: link popover axe", async ({ annotate }) => { - await renderTestEditor(toolbarDocument); - await focusToolbarItem("Create link"); - await commands.pressKey("Enter"); - await expect.element(page.getByPlaceholder("Edit URL")).toBeVisible(); - for (const warning of await commands.checkAxe(".bn-form-popover")) { + for (const warning of await commands.checkAxe('[role="toolbar"]')) { await annotate(warning, "warning"); } }); }); -} +}); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts index dc778946bf..948c6b4653 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts @@ -1,29 +1,42 @@ -import { commands } from "@root/tests/src/utils/context.js"; -import { afterEach, expect, test } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; -import { - renderTestEditor, - focusToolbarItem, - toolbarDocument, -} from "./FormattingToolbar.browser.test.js"; - -afterEach(async () => { - try { - const transcript = await commands.readTranscript(); - expect(transcript.length).toBeGreaterThan(0); - expect(transcript).toMatchSnapshot(); - } finally { - await commands.stopReader(); - } -}); +import { selectToLineEndKey } from "@root/tests/src/utils/context.js"; +import { expect } from "vite-plus/test"; // Record selection → toolbar → Escape → editor. // Individual toolbar item actions and focus rings are covered by the browser tests. // Screen reader announcements do not clearly communicate entering the toolbar. -test.skip("formatting toolbar: open, focus, and close", async () => { - await renderTestEditor(toolbarDocument); +it.skip("announces entering and leaving the formatting toolbar", async ({ + renderEditor, + commands, + page, + onTestFinished, +}) => { + onTestFinished(async () => { + try { + const transcript = await commands.readTranscript(); + expect(transcript.length).toBeGreaterThan(0); + expect(transcript).toMatchSnapshot(); + } finally { + await commands.stopReader(); + } + }); + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + }); + editor.setTextCursorPosition("text", "start"); await commands.startReader(page.getByRole("textbox").selector); - const { toolbar } = await focusToolbarItem("Paragraph"); + await commands.pressKey(selectToLineEndKey); + await commands.pressKey("Tab"); + const toolbar = page.getByRole("toolbar"); + await expect + .element( + toolbar.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }), + ) + .toHaveFocus(); await commands.pressKey("Escape"); await expect.element(toolbar).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); diff --git a/packages/react/src/components/FormattingToolbar/__snapshots__/FormattingToolbar.browser.test.tsx.snap b/packages/react/src/components/FormattingToolbar/__snapshots__/FormattingToolbar.browser.test.tsx.snap deleted file mode 100644 index d1a95798a1..0000000000 --- a/packages/react/src/components/FormattingToolbar/__snapshots__/FormattingToolbar.browser.test.tsx.snap +++ /dev/null @@ -1,135 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`ARIA > formatting toolbar: Align text center > after activation 1`] = ` -"- button "Align text center" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Align text center > before activation 1`] = ` -"- button "Align text center": - - img" -`; - -exports[`ARIA > formatting toolbar: Align text left > after activation 1`] = ` -"- button "Align text left" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Align text left > before activation 1`] = ` -"- button "Align text left" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Align text right > after activation 1`] = ` -"- button "Align text right" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Align text right > before activation 1`] = ` -"- button "Align text right": - - img" -`; - -exports[`ARIA > formatting toolbar: Bold > after activation 1`] = ` -"- button "Bold" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Bold > before activation 1`] = ` -"- button "Bold": - - img" -`; - -exports[`ARIA > formatting toolbar: Colors > after activation 1`] = `"- button "Colors": A"`; - -exports[`ARIA > formatting toolbar: Colors > before activation 1`] = `"- button "Colors": A"`; - -exports[`ARIA > formatting toolbar: Italic > after activation 1`] = ` -"- button "Italic" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Italic > before activation 1`] = ` -"- button "Italic": - - img" -`; - -exports[`ARIA > formatting toolbar: Nest block > after activation 1`] = ` -"- button "Nest block" [disabled]: - - img" -`; - -exports[`ARIA > formatting toolbar: Nest block > before activation 1`] = ` -"- button "Nest block": - - img" -`; - -exports[`ARIA > formatting toolbar: Paragraph > after activation 1`] = ` -"- button "Heading 1": - - img - - text: Heading 1" -`; - -exports[`ARIA > formatting toolbar: Paragraph > before activation 1`] = ` -"- button "Paragraph": - - img - - text: Paragraph" -`; - -exports[`ARIA > formatting toolbar: Strike > after activation 1`] = ` -"- button "Strike" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Strike > before activation 1`] = ` -"- button "Strike": - - img" -`; - -exports[`ARIA > formatting toolbar: Underline > after activation 1`] = ` -"- button "Underline" [pressed]: - - img" -`; - -exports[`ARIA > formatting toolbar: Underline > before activation 1`] = ` -"- button "Underline": - - img" -`; - -exports[`ARIA > formatting toolbar: Unnest block > after activation 1`] = ` -"- button "Unnest block" [disabled]: - - img" -`; - -exports[`ARIA > formatting toolbar: Unnest block > before activation 1`] = ` -"- button "Unnest block": - - img" -`; - -exports[`ARIA > formatting toolbar: complete accessibility tree > toolbar 1`] = ` -"- toolbar: - - button "Paragraph": - - img - - text: Paragraph - - button "Bold": - - img - - button "Italic": - - img - - button "Underline": - - img - - button "Strike": - - img - - button "Align text left" [pressed]: - - img - - button "Align text center": - - img - - button "Align text right": - - img - - button "Colors": A - - button "Nest block": - - img - - button "Unnest block" [disabled]: - - img - - button "Create link": - - img" -`; diff --git a/tests/src/fixtures/editor.tsx b/tests/src/fixtures/editor.tsx index 372d3b17c7..d717f3c9a0 100644 --- a/tests/src/fixtures/editor.tsx +++ b/tests/src/fixtures/editor.tsx @@ -18,6 +18,7 @@ import type { ComponentProps, ReactNode } from "react"; import { flushSync } from "react-dom"; import { createRoot } from "react-dom/client"; import { test as base, type TestContext } from "vite-plus/test"; +import { commands, page } from "../utils/context.js"; type ViewProps< B extends BlockSchema, @@ -196,9 +197,13 @@ export function selectText( } export const test = base.extend<{ + commands: typeof commands; + page: typeof page; renderEditor: RenderEditor; selectText: typeof selectText; }>({ + commands, + page, renderEditor: async ({ onTestFinished }, use) => { await use(createRenderEditor(onTestFinished)); }, From 1c187b0d92cacbd5eb4457521c6ec66663ec554c Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Mon, 16 Nov 2026 16:36:34 +0100 Subject: [PATCH 03/14] test: complete toolbar accessibility coverage and shared commands --- .../references/accessibility-tests.md | 2 +- .vscode/settings.json | 3 +- .../BasicTextStyleButton.browser.test.tsx | 437 ++++++++++-------- .../ColorStyleButton.browser.test.tsx | 324 ++++++++++++- .../CreateLinkButton.browser.test.tsx | 408 +++++++++++++--- .../NestBlockButtons.browser.test.tsx | 340 ++++++++++---- .../TextAlignButton.browser.test.tsx | 300 ++++++++++-- ...BasicTextStyleButton.browser.test.tsx.snap | 20 +- .../BlockTypeSelect.browser.test.tsx | 381 +++++++++++---- ...rmattingToolbarController.browser.test.tsx | 255 ++++++---- .../FormattingToolbar.browser.test.tsx | 382 ++++++++++++++- .../end-to-end/fixtures/selection.test.tsx | 131 ------ tests/src/screen-reader/commands.ts | 7 + .../screen-reader/run-screen-reader.mjs | 8 +- tests/{ => src}/screen-reader/screenReader.ts | 6 +- .../vite.config.screen-reader.ts | 40 +- tests/src/utils/commands.browser.ts | 1 + tests/src/utils/commands.ts | 11 + tests/src/utils/context.ts | 39 +- tests/src/utils/focus.ts | 49 ++ tests/src/utils/imeComposition.ts | 6 - tests/src/utils/positionalMouse.ts | 11 - tests/tsconfig.browser.json | 1 - tests/vite.config.browser.ts | 24 +- vite.config.ts | 2 +- 25 files changed, 2360 insertions(+), 828 deletions(-) delete mode 100644 tests/src/end-to-end/fixtures/selection.test.tsx create mode 100644 tests/src/screen-reader/commands.ts rename tests/{ => src}/screen-reader/run-screen-reader.mjs (74%) rename tests/{ => src}/screen-reader/screenReader.ts (93%) rename tests/{ => src}/screen-reader/vite.config.screen-reader.ts (66%) create mode 100644 tests/src/utils/commands.browser.ts create mode 100644 tests/src/utils/commands.ts create mode 100644 tests/src/utils/focus.ts diff --git a/.claude/skills/testing-skill/references/accessibility-tests.md b/.claude/skills/testing-skill/references/accessibility-tests.md index 254bbb655d..7aae792e80 100644 --- a/.claude/skills/testing-skill/references/accessibility-tests.md +++ b/.claude/skills/testing-skill/references/accessibility-tests.md @@ -54,7 +54,7 @@ Use accessible locators (`getByRole` with a name or `getByLabel`) and pass their Use a separate `*.screen-reader.test.ts` only for actual reader announcements/navigation that ARIA snapshots cannot establish. Reuse keyboard navigation helpers, render the suite’s editor and call `commands.startReader(locator.selector)`, and assert the transcript and stop the reader in `afterEach`. Avoid duplicating every browser scenario. Transcripts are reader-specific; review changes rather than accepting them blindly. -These tests run locally with VoiceOver on macOS or NVDA on Windows and require the installed reader and GuidePup permissions. They must stay excluded from regular e2e, node tests, and CI. `tests/screen-reader/vite.config.screen-reader.ts` is for this native runner only. +These tests run locally with VoiceOver on macOS or NVDA on Windows and require the installed reader and GuidePup permissions. They must stay excluded from regular e2e, node tests, and CI. `tests/src/screen-reader/vite.config.screen-reader.ts` is for this native runner only. ## Discovery and commands diff --git a/.vscode/settings.json b/.vscode/settings.json index 80f6014497..eb9b79ff47 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -16,7 +16,8 @@ "packages/website/docs/.vitepress": false, "**/.*": false }, - "typescript.tsdk": "node_modules/typescript/lib", + "js/ts.experimental.useTsgo": true, + "js/ts.tsdk.path": "./node_modules/typescript", "[xml]": { "editor.defaultFormatter": "redhat.vscode-xml" }, diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx index ec75f92202..51910667e1 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -7,239 +7,292 @@ import { defaultStyleSpecs, } from "@blocknote/core"; import { BasicTextStyleButton } from "./BasicTextStyleButton.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; const STYLES = ["bold", "italic", "underline", "strike", "code"] as const; describe("BasicTextStyleButton", () => { - it.for(STYLES)( - "toggles %s on and off", - async (basicTextStyle, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "format", type: "paragraph", content: "Format this text" }, - ], - // To test just the button, we don't even need the toolbar - // the button reads the editor context directly - props: { formattingToolbar: false }, - children: , - }); + describe("integration", () => { + it.for(STYLES)( + "toggles %s on and off", + async (basicTextStyle, { renderEditor, selectText, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "format", type: "paragraph", content: "Format this text" }, + ], + // To test just the button, we don't even need the toolbar + // the button reads the editor context directly + props: { formattingToolbar: false }, + children: , + }); - selectText(editor, "Format this text"); + selectText(editor, "Format this text"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, - exact: true, - }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); - for (const state of ["on", "off"] as const) { - await button.click(); + for (const state of ["on", "off"] as const) { + await button.click(); - expect(editor.getBlock("format")).toMatchSnapshot(state); - await expect - .element(button) - .toHaveAttribute("aria-pressed", String(state === "on")); - } - }, - ); + expect(editor.getBlock("format")).toMatchSnapshot(state); + await expect + .element(button) + .toHaveAttribute("aria-pressed", String(state === "on")); + } + }, + ); - it.for(STYLES)( - "applies %s only to selected text without changing surrounding content", - async (basicTextStyle, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ - initialContent: [ + it.for(STYLES)( + "applies %s only to selected text without changing surrounding content", + async (basicTextStyle, { renderEditor, selectText, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "format", + type: "paragraph", + content: [ + { + type: "text", + text: "Before selected after", + styles: { textColor: "red" }, + }, + ], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); + + await button.click(); + + expect(editor.getBlock("format")?.content).toEqual([ + { type: "text", text: "Before ", styles: { textColor: "red" } }, { - id: "format", - type: "paragraph", - content: [ - { - type: "text", - text: "Before selected after", - styles: { textColor: "red" }, - }, - ], + type: "text", + text: "selected", + // Inline code excludes other formatting styles. + styles: + basicTextStyle === "code" + ? { code: true } + : { textColor: "red", [basicTextStyle]: true }, }, - ], + { type: "text", text: " after", styles: { textColor: "red" } }, + ]); + }, + ); + + it.for(STYLES)( + "applies %s to subsequently typed text at a collapsed cursor", + async (basicTextStyle, { renderEditor, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "format", type: "paragraph", content: "Existing" }, + ], + props: { formattingToolbar: false }, + children: , + }); + editor.setTextCursorPosition("format", "end"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); + + await button.click(); + await userEvent.keyboard(" typed"); + + expect(editor.getBlock("format")?.content).toEqual([ + { type: "text", text: "Existing", styles: {} }, + { type: "text", text: " typed", styles: { [basicTextStyle]: true } }, + ]); + }, + ); + }); + + describe("unit", () => { + it("hides in read-only mode and responds to editability changes", async ({ + renderEditor, + page, + }) => { + const { rerender } = await renderEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + + rerender({ editable: true }); + await expect.element(button).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + rerender({ editable: false }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides when the style is missing from the schema", async ({ + renderEditor, + page, + }) => { + await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { italic: defaultStyleSpecs.italic }, + }), props: { formattingToolbar: false }, - children: , + children: , }); - selectText(editor, "selected"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, - exact: true, + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides when the style has a non-boolean prop schema", async ({ + renderEditor, + page, + }) => { + await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { + bold: createStyleSpec( + { type: "bold", propSchema: "string" }, + { render: () => ({ dom: document.createElement("span") }) }, + ), + }, + }), + props: { formattingToolbar: false }, + children: , }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + }); - await button.click(); - - expect(editor.getBlock("format")?.content).toEqual([ - { type: "text", text: "Before ", styles: { textColor: "red" } }, - { - type: "text", - text: "selected", - // Inline code excludes other formatting styles. - styles: - basicTextStyle === "code" - ? { code: true } - : { textColor: "red", [basicTextStyle]: true }, - }, - { type: "text", text: " after", styles: { textColor: "red" } }, - ]); - }, - ); - - it.for(STYLES)( - "applies %s to subsequently typed text at a collapsed cursor", - async (basicTextStyle, { renderEditor, page }) => { + it("hides on blocks without inline content and reappears on text blocks", async ({ + renderEditor, + page, + }) => { const { editor } = await renderEditor({ initialContent: [ - { id: "format", type: "paragraph", content: "Existing" }, + { id: "divider", type: "divider" }, + { id: "text", type: "paragraph", content: "Text" }, ], props: { formattingToolbar: false }, - children: , - }); - editor.setTextCursorPosition("format", "end"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, - exact: true, + children: , }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + editor.setTextCursorPosition("divider"); + await expect.element(button).not.toBeInTheDocument(); - await button.click(); - await userEvent.keyboard(" typed"); - - expect(editor.getBlock("format")?.content).toEqual([ - { type: "text", text: "Existing", styles: {} }, - { type: "text", text: " typed", styles: { [basicTextStyle]: true } }, - ]); - }, - ); - - it("hides in read-only mode and responds to editability changes", async ({ - renderEditor, - page, - }) => { - const { rerender } = await renderEditor({ - props: { editable: false, formattingToolbar: false }, - children: , + editor.setTextCursorPosition("text"); + await expect.element(button).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - await expect.element(button).not.toBeInTheDocument(); + }); - rerender({ editable: true }); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); + describe("ARIA", () => { + it("reflects the active style when selection moves between blocks", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "styled", + type: "paragraph", + content: [{ type: "text", text: "Bold", styles: { bold: true } }], + }, + { id: "plain", type: "paragraph", content: "Plain" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); - rerender({ editable: false }); - await expect.element(button).not.toBeInTheDocument(); - }); + selectText(editor, "Plain"); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); - it("hides when the style is missing from the schema", async ({ - renderEditor, - page, - }) => { - await renderEditor({ - schema: BlockNoteSchema.create({ - styleSpecs: { italic: defaultStyleSpecs.italic }, - }), - props: { formattingToolbar: false }, - children: , + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - await expect.element(button).not.toBeInTheDocument(); }); - it("hides when the style has a non-boolean prop schema", async ({ - renderEditor, - page, - }) => { - await renderEditor({ - schema: BlockNoteSchema.create({ - styleSpecs: { - bold: createStyleSpec( - { type: "bold", propSchema: "string" }, - { render: () => ({ dom: document.createElement("span") }) }, - ), - }, - }), - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - await expect.element(button).not.toBeInTheDocument(); - }); + describe("keyboard", () => { + it.for(STYLES)( + "shows a keyboard focus ring for %s", + async (style, { renderEditor, selectText, commands, page }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[style].tooltip, + exact: true, + }); + const outline = await commands.readOutline(button.selector); - it("hides on blocks without inline content and reappears on text blocks", async ({ - renderEditor, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "divider", type: "divider" }, - { id: "text", type: "paragraph", content: "Text" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - editor.setTextCursorPosition("divider"); - await expect.element(button).not.toBeInTheDocument(); + await commands.pressKey("Tab"); - editor.setTextCursorPosition("text"); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); - }); + await expect.element(button).toHaveFocus(); + await commands.checkFocusOutline(button.selector, outline); + }, + ); - it("reflects the active style when selection moves between blocks", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { - id: "styled", - type: "paragraph", - content: [{ type: "text", text: "Bold", styles: { bold: true } }], - }, - { id: "plain", type: "paragraph", content: "Plain" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - selectText(editor, "Bold"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); + it.for(["Enter", "Space"])( + "activates with %s and returns focus to the editor", + async (key, { renderEditor, selectText, commands, page }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.bold.tooltip, + exact: true, + }); + + await commands.pressKey("Tab"); - selectText(editor, "Plain"); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); + await expect.element(button).toHaveFocus(); - selectText(editor, "Bold"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); + await commands.pressKey(key); + + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }, + ); }); - describe("keyboard", () => { - it("can be activated with Enter and returns focus to the editor", async ({ + describe("axe", () => { + it("checks all supported style buttons", async ({ renderEditor, - selectText, commands, - page, + annotate, }) => { - const { editor } = await renderEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], + await renderEditor({ props: { formattingToolbar: false }, - children: , - }); - await page.getByRole("textbox").click(); - selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.bold.tooltip, - exact: true, + children: ( + + {STYLES.map((style) => ( + + ))} + + ), }); - await commands.pressKey("Tab"); - - await expect.element(button).toHaveFocus(); - - await commands.pressKey("Enter"); - - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - await expect.element(page.getByRole("textbox")).toHaveFocus(); + for (const warning of await commands.checkAxe('[role="toolbar"]')) { + await annotate(warning, "warning"); + } }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx index a172fe4022..d060e68779 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -1,6 +1,7 @@ import { BlockNoteSchema, defaultStyleSpecs } from "@blocknote/core"; import { describe, expect } from "vite-plus/test"; import { ColorStyleButton } from "./ColorStyleButton.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; describe("ColorStyleButton", () => { describe("unit", () => { @@ -43,44 +44,252 @@ describe("ColorStyleButton", () => { .not.toBeInTheDocument(); }); - it("applies the chosen text color only to the selected substring", async ({ + it("only offers background colors when text colors are not in the schema", async ({ renderEditor, selectText, page, }) => { const { editor } = await renderEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Before selected after" }, - ], + schema: BlockNoteSchema.create({ + styleSpecs: { backgroundColor: defaultStyleSpecs.backgroundColor }, + }), + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + + const menu = page.getByRole("menu"); + await expect + .element( + menu.getByText(editor.dictionary.color_picker.background_title, { + exact: true, + }), + ) + .toBeVisible(); + await expect + .element( + menu.getByText(editor.dictionary.color_picker.text_title, { + exact: true, + }), + ) + .not.toBeInTheDocument(); + }); + + it("hides when neither color style is supported", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { bold: defaultStyleSpecs.bold }, + }), props: { formattingToolbar: false }, children: , }); - selectText(editor, "selected"); + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }), + ) + .not.toBeInTheDocument(); + }); + + it("responds to editability and hides on blocks without inline content", async ({ + renderEditor, + page, + }) => { + const { editor, rerender } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Text" }, + { id: "divider", type: "divider" }, + ], + props: { editable: false, formattingToolbar: false }, + children: , + }); const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar.colors.tooltip, exact: true, }); - await button.click(); + await expect.element(button).not.toBeInTheDocument(); - await page - .getByRole("menuitem", { - name: editor.dictionary.color_picker.colors.gray, - }) - .first() - .click(); + rerender({ editable: true }); + await expect.element(button).toBeVisible(); - expect(editor.getBlock("text")?.content).toEqual([ - { type: "text", text: "Before ", styles: {} }, - { type: "text", text: "selected", styles: { textColor: "gray" } }, - { type: "text", text: " after", styles: {} }, - ]); - await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); - await expect.element(page.getByRole("textbox")).toHaveFocus(); + editor.setTextCursorPosition("divider"); + await expect.element(button).not.toBeInTheDocument(); + + editor.setTextCursorPosition("text"); + await expect.element(button).toBeVisible(); }); }); + describe("integration", () => { + it.for(["textColor", "backgroundColor"] as const)( + "applies %s only to the selected substring", + async (style, { renderEditor, selectText, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Before selected after" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + await button.click(); + + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .nth(style === "textColor" ? 0 : 1) + .click(); + + expect(editor.getBlock("text")?.content).toEqual([ + { type: "text", text: "Before ", styles: {} }, + { type: "text", text: "selected", styles: { [style]: "gray" } }, + { type: "text", text: " after", styles: {} }, + ]); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }, + ); + + it.for(["textColor", "backgroundColor"] as const)( + "resets %s without removing the other color", + async (style, { renderEditor, selectText, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: [ + { + type: "text", + text: "Selected text", + styles: { textColor: "gray", backgroundColor: "gray" }, + }, + ], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.default, + }) + .nth(style === "textColor" ? 0 : 1) + .click(); + + expect(editor.getBlock("text")?.content).toEqual([ + { + type: "text", + text: "Selected text", + styles: + style === "textColor" + ? { backgroundColor: "gray" } + : { textColor: "gray" }, + }, + ]); + }, + ); + }); + describe("keyboard", () => { + it("shows a keyboard focus ring on its trigger", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + const outline = await commands.readOutline(button.selector); + + await commands.pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await commands.checkFocusOutline(button.selector, outline); + }); + + it("chooses a color with the keyboard and returns focus to the editor", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + button.element().focus(); + + await commands.pressKey("Enter"); + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + await commands.pressKey("ArrowDown"); + await commands.pressKey("ArrowDown"); + + await expect + .element( + menu + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .first(), + ) + .toHaveFocus(); + + await commands.pressKey("Enter"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + expect(editor.getActiveStyles().textColor).toBe("gray"); + }); it("supports opening, navigating, and dismissing its menu without editing the document", async ({ renderEditor, selectText, @@ -127,6 +336,33 @@ describe("ColorStyleButton", () => { }); describe("ARIA", () => { + it("exposes the menu trigger's expanded state and relationship", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-haspopup", "menu"); + await expect.element(button).toHaveAttribute("aria-expanded", "false"); + + await button.click(); + + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-expanded", "true"); + expect(button.element().getAttribute("aria-controls")).toBe( + menu.element().id, + ); + }); // Expected failure in our Mantine adapter (packages/mantine/src/menu/Menu.tsx): // it renders `checked` as a visual checkmark without exposing the checked // state to assistive technology. @@ -171,4 +407,54 @@ describe("ColorStyleButton", () => { expect(after).not.toBe(before); }); }); + + describe("axe", () => { + it("checks the color trigger", async ({ + renderEditor, + commands, + annotate, + }) => { + await renderEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + + for (const warning of await commands.checkAxe('[role="toolbar"]')) { + await annotate(warning, "warning"); + } + }); + + // Mantine's focusable menu placeholder violates aria-required-children, + // as it does in BlockTypeSelect. Keep the open state covered explicitly. + it.fails("checks the open color menu", async ({ + renderEditor, + commands, + page, + annotate, + }) => { + const { editor } = await renderEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + await expect.element(page.getByRole("menu")).toBeVisible(); + + for (const warning of await commands.checkAxe('[role="menu"]')) { + await annotate(warning, "warning"); + } + }); + }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx index 7e91ff7460..f3e56d93d2 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -1,90 +1,360 @@ import { describe, expect } from "vite-plus/test"; import { CreateLinkButton } from "./CreateLinkButton.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; describe("CreateLinkButton", () => { - it("submits a link for the original substring and returns focus to the editor", async ({ - renderEditor, - selectText, - commands, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { - id: "text", - type: "paragraph", - content: "Before selected text after", - }, - ], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "selected text"); - await page - .getByRole("button", { + describe("unit", () => { + it("requires selected text and responds to editability changes", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor, rerender } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar.link.tooltip, exact: true, - }) - .click(); - const input = page.getByPlaceholder( - editor.dictionary.link_toolbar.form.url_placeholder, - ); - - await input.fill("https://example.com"); - await commands.pressKey("Enter"); - - expect(editor.getBlock("text")?.content).toEqual([ - { type: "text", text: "Before ", styles: {} }, - { - type: "link", - href: "https://example.com", - content: [{ type: "text", text: "selected text", styles: {} }], - }, - { type: "text", text: " after", styles: {} }, - ]); - await expect.element(input).not.toBeInTheDocument(); - await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + await expect.element(button).not.toBeInTheDocument(); + + selectText(editor, "Selected text"); + await expect.element(button).toBeVisible(); + + rerender({ editable: false }); + await expect.element(button).not.toBeInTheDocument(); + + rerender({ editable: true }); + await expect.element(button).toBeVisible(); + + editor.setTextCursorPosition("text", "end"); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("prefills the selected link and closes the form when selection changes", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: [ + { + type: "link", + href: "https://example.com", + content: "Linked text", + }, + { type: "text", text: " Plain text", styles: {} }, + ], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Linked text"); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveValue("https://example.com"); + + selectText(editor, "Plain text"); + + await expect.element(input).not.toBeInTheDocument(); + }); }); - it("opens the link form without changing the selected text range or document", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ + describe("integration", () => { + it("submits a link for the original substring and returns focus to the editor", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: "Before selected text after", + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected text"); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + + await input.fill("https://example.com"); + await commands.pressKey("Enter"); + + expect(editor.getBlock("text")?.content).toEqual([ + { type: "text", text: "Before ", styles: {} }, { - id: "text", - type: "paragraph", - content: "Before selected text after", + type: "link", + href: "https://example.com", + content: [{ type: "text", text: "selected text", styles: {} }], }, - ], - props: { formattingToolbar: false }, - children: , + { type: "text", text: " after", styles: {} }, + ]); + await expect.element(input).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + + it("opens the link form without changing the selected text range or document", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: "Before selected text after", + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected text"); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + + await expect + .element( + page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ), + ) + .toHaveFocus(); + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, + ); + expect(editor.document).toEqual(documentBefore); }); - selectText(editor, "selected text"); - const documentBefore = editor.document; - const selectionBefore = editor.prosemirrorState.selection.toJSON(); + }); - await page - .getByRole("button", { + describe("keyboard", () => { + it("shows a keyboard focus ring on its trigger", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar.link.tooltip, exact: true, - }) - .click(); + }); + const outline = await commands.readOutline(button.selector); - await expect - .element( - page.getByPlaceholder( - editor.dictionary.link_toolbar.form.url_placeholder, - ), - ) - .toHaveFocus(); - expect(editor.prosemirrorState.selection.toJSON()).toEqual(selectionBefore); - expect(editor.document).toEqual(documentBefore); + await commands.pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await commands.checkFocusOutline(button.selector, outline); + }); + + // Our Mantine form-popover CSS removes the input border, and there is no + // replacement keyboard focus outline (blocknoteStyles.css). + it.fails("shows a visible keyboard focus indicator on the URL field", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }); + await expect.element(button).toBeVisible(); + button.element().focus(); + + await commands.pressKey("Enter"); + + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveFocus(); + await commands.checkFocusOutline(input.selector); + }); + + it("opens with Enter and returns focus to its trigger on Escape without editing", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + await expect.element(button).toBeVisible(); + button.element().focus(); + + await commands.pressKey("Enter"); + + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveFocus(); + + await commands.pressKey("Escape"); + + await expect.element(input).not.toBeInTheDocument(); + await expect.element(button).toHaveFocus(); + expect(editor.document).toEqual(documentBefore); + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, + ); + }); + + it("opens with the editor's link shortcut but not in read-only mode", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor, rerender } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + + await commands.pressKey("Control+k"); + + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveFocus(); + await commands.pressKey("Escape"); + rerender({ editable: false }); + + // Read-only content is not a textbox, but still receives DOM key events. + const shortcut = new KeyboardEvent("keydown", { + key: "k", + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + editor.prosemirrorView.dom.dispatchEvent(shortcut); + + await expect.element(input).not.toBeInTheDocument(); + expect(shortcut.defaultPrevented).toBe(false); + }); + }); + + describe("ARIA", () => { + it("exposes the popup's relationship to its named trigger and its URL field", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-haspopup", "dialog"); + await expect.element(button).toHaveAttribute("aria-expanded", "false"); + + await button.click(); + + const dialog = page.getByRole("dialog"); + await expect.element(dialog).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-expanded", "true"); + expect(button.element().getAttribute("aria-controls")).toBe( + dialog.element().id, + ); + expect(dialog.element().getAttribute("aria-labelledby")).toBe( + button.element().id, + ); + await expect + .element( + dialog.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ), + ) + .toHaveFocus(); + }); }); describe("axe", () => { + it("checks the closed trigger", async ({ + renderEditor, + selectText, + commands, + annotate, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + selectText(editor, "Selected text"); + + for (const warning of await commands.checkAxe('[role="toolbar"]')) { + await annotate(warning, "warning"); + } + }); it("opens a link form with no automated accessibility violations", async ({ renderEditor, selectText, diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx index 0f6c21f909..c26c20a875 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -1,99 +1,277 @@ import { describe, expect } from "vite-plus/test"; import { NestBlockButton, UnnestBlockButton } from "./NestBlockButtons.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; -describe("NestBlockButton", () => { - it("updates its disabled state when selection moves to a block that can be nested", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { type: "paragraph", content: "First block" }, - { type: "paragraph", content: "Second block" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.nest.tooltip, - exact: true, - }); - selectText(editor, "First block"); +describe("NestBlockButtons", () => { + describe("unit", () => { + it.for([ + { name: "nest", Button: NestBlockButton }, + { name: "unnest", Button: UnnestBlockButton }, + ])( + "hides $name in read-only mode and on blocks without inline content", + async ({ Button }, { renderEditor, page }) => { + const { editor, rerender } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Text" }, + { id: "divider", type: "divider" }, + ], + props: { editable: false, formattingToolbar: false }, + children: + + ), + }); + await page.getByRole("textbox").click(); + + await commands.pressKey("Tab"); + + await expect + .element(page.getByRole("button", { name: "Next action", exact: true })) + .toHaveFocus(); + }); + }); + + describe("axe", () => { + it("checks enabled and disabled nesting controls", async ({ + renderEditor, + selectText, + commands, + annotate, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + ], + props: { formattingToolbar: false }, + children: ( + + + + + ), + }); + selectText(editor, "Child"); + + for (const warning of await commands.checkAxe('[role="toolbar"]')) { + await annotate(warning, "warning"); + } + }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx index 6b6489ca47..383dc6e872 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -1,46 +1,292 @@ import { describe, expect } from "vite-plus/test"; import { TextAlignButton } from "./TextAlignButton.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; +import { CellSelection } from "@tiptap/pm/tables"; describe("TextAlignButton", () => { - it.for(["left", "center", "right"] as const)( - "aligns the selected block %s without changing its text or neighboring blocks", - async (textAlignment, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ + describe("unit", () => { + it("hides for read-only content and blocks without alignment, and reappears for text", async ({ + renderEditor, + page, + }) => { + const { editor, rerender } = await renderEditor({ initialContent: [ - { id: "before", type: "paragraph", content: "Before" }, - { - id: "selected", - type: "paragraph", - props: { - textAlignment: textAlignment === "left" ? "center" : "left", + { id: "text", type: "paragraph", content: "Text" }, + { id: "divider", type: "divider" }, + ], + props: { editable: false, formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }); + await expect.element(button).not.toBeInTheDocument(); + + rerender({ editable: true }); + await expect.element(button).toBeVisible(); + + editor.setTextCursorPosition("divider"); + await expect.element(button).not.toBeInTheDocument(); + + editor.setTextCursorPosition("text"); + await expect.element(button).toBeVisible(); + }); + }); + + describe("integration", () => { + it.for(["left", "center", "right", "justify"] as const)( + "aligns the selected block %s without changing its text or neighboring blocks", + async (textAlignment, { renderEditor, selectText, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { + id: "selected", + type: "paragraph", + props: { + textAlignment: textAlignment === "left" ? "center" : "left", + }, + content: "Selected text", }, - content: "Selected text", + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const documentBefore = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[`align_${textAlignment}`] + .tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + await button.click(); + + expect(editor.document).toEqual([ + documentBefore[0], + { + ...documentBefore[1], + props: { ...documentBefore[1].props, textAlignment }, }, + documentBefore[2], + ]); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }, + ); + + it("aligns every selected block without changing an unselected neighbor", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "first", type: "paragraph", content: "First" }, + { id: "second", type: "paragraph", content: "Second" }, { id: "after", type: "paragraph", content: "After" }, ], props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - const documentBefore = editor.document; - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar[`align_${textAlignment}`] - .tooltip, - exact: true, + children: , }); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); + editor.setSelection("first", "second"); + const before = editor.document; - await button.click(); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }) + .click(); expect(editor.document).toEqual([ - documentBefore[0], { - ...documentBefore[1], - props: { ...documentBefore[1].props, textAlignment }, + ...before[0], + props: { ...before[0].props, textAlignment: "center" }, + }, + { + ...before[1], + props: { ...before[1].props, textAlignment: "center" }, }, - documentBefore[2], + before[2], ]); + }); + + it("aligns only the selected table cells", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + id: "table", + type: "table", + content: { + type: "tableContent", + rows: [ + { cells: ["First", "Second"] }, + { cells: ["Third", "Fourth"] }, + ], + }, + }, + ], + props: { formattingToolbar: false }, + children: , + }); + editor.transact((tr) => { + const cells: number[] = []; + tr.doc.descendants((node, pos) => { + if (node.type.name === "tableCell") { + cells.push(pos); + } + }); + tr.setSelection(CellSelection.create(tr.doc, cells[0], cells[1])); + }); + const tableBefore = editor.getBlock("table"); + if (tableBefore?.type !== "table") { + throw new Error("Expected table fixture"); + } + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }) + .click(); + + expect(editor.getBlock("table")).toEqual({ + ...tableBefore, + content: { + ...tableBefore.content, + rows: tableBefore.content.rows.map((row, index) => + index === 0 + ? { + ...row, + cells: row.cells.map((cell) => { + if (Array.isArray(cell)) { + throw new Error("Expected normalized table cells"); + } + return { + ...cell, + props: { ...cell.props, textAlignment: "center" }, + }; + }), + } + : row, + ), + }, + }); + }); + }); + + describe("keyboard", () => { + it.for(["left", "center", "right", "justify"] as const)( + "shows a keyboard focus ring for %s alignment", + async (alignment, { renderEditor, selectText, commands, page }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[`align_${alignment}`] + .tooltip, + exact: true, + }); + const outline = await commands.readOutline(button.selector); + + await commands.pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await commands.checkFocusOutline(button.selector, outline); + }, + ); + + it.for(["Enter", "Space"])( + "aligns with %s and restores editor focus", + async (key, { renderEditor, selectText, commands, page }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }); + + await commands.pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + + await commands.pressKey(key); + + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }, + ); + }); + + describe("ARIA", () => { + it("updates its pressed state when selection moves between differently aligned blocks", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { type: "paragraph", content: "Left" }, + { + type: "paragraph", + content: "Center", + props: { textAlignment: "center" }, + }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }); + selectText(editor, "Center"); await expect.element(button).toHaveAttribute("aria-pressed", "true"); - }, - ); + + selectText(editor, "Left"); + + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + }); + }); + + describe("axe", () => { + it("checks all alignment controls, including the selected one", async ({ + renderEditor, + commands, + annotate, + }) => { + await renderEditor({ + props: { formattingToolbar: false }, + children: ( + + {(["left", "center", "right", "justify"] as const).map( + (alignment) => ( + + ), + )} + + ), + }); + + for (const warning of await commands.checkAxe('[role="toolbar"]')) { + await annotate(warning, "warning"); + } + }); + }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap b/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap index 91ddaaa00d..7a50940e3c 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap @@ -1,6 +1,6 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`BasicTextStyleButton > toggles bold on and off > off 1`] = ` +exports[`BasicTextStyleButton > integration > toggles bold on and off > off 1`] = ` { "children": [], "content": [ @@ -20,7 +20,7 @@ exports[`BasicTextStyleButton > toggles bold on and off > off 1`] = ` } `; -exports[`BasicTextStyleButton > toggles bold on and off > on 1`] = ` +exports[`BasicTextStyleButton > integration > toggles bold on and off > on 1`] = ` { "children": [], "content": [ @@ -42,7 +42,7 @@ exports[`BasicTextStyleButton > toggles bold on and off > on 1`] = ` } `; -exports[`BasicTextStyleButton > toggles code on and off > off 1`] = ` +exports[`BasicTextStyleButton > integration > toggles code on and off > off 1`] = ` { "children": [], "content": [ @@ -62,7 +62,7 @@ exports[`BasicTextStyleButton > toggles code on and off > off 1`] = ` } `; -exports[`BasicTextStyleButton > toggles code on and off > on 1`] = ` +exports[`BasicTextStyleButton > integration > toggles code on and off > on 1`] = ` { "children": [], "content": [ @@ -84,7 +84,7 @@ exports[`BasicTextStyleButton > toggles code on and off > on 1`] = ` } `; -exports[`BasicTextStyleButton > toggles italic on and off > off 1`] = ` +exports[`BasicTextStyleButton > integration > toggles italic on and off > off 1`] = ` { "children": [], "content": [ @@ -104,7 +104,7 @@ exports[`BasicTextStyleButton > toggles italic on and off > off 1`] = ` } `; -exports[`BasicTextStyleButton > toggles italic on and off > on 1`] = ` +exports[`BasicTextStyleButton > integration > toggles italic on and off > on 1`] = ` { "children": [], "content": [ @@ -126,7 +126,7 @@ exports[`BasicTextStyleButton > toggles italic on and off > on 1`] = ` } `; -exports[`BasicTextStyleButton > toggles strike on and off > off 1`] = ` +exports[`BasicTextStyleButton > integration > toggles strike on and off > off 1`] = ` { "children": [], "content": [ @@ -146,7 +146,7 @@ exports[`BasicTextStyleButton > toggles strike on and off > off 1`] = ` } `; -exports[`BasicTextStyleButton > toggles strike on and off > on 1`] = ` +exports[`BasicTextStyleButton > integration > toggles strike on and off > on 1`] = ` { "children": [], "content": [ @@ -168,7 +168,7 @@ exports[`BasicTextStyleButton > toggles strike on and off > on 1`] = ` } `; -exports[`BasicTextStyleButton > toggles underline on and off > off 1`] = ` +exports[`BasicTextStyleButton > integration > toggles underline on and off > off 1`] = ` { "children": [], "content": [ @@ -188,7 +188,7 @@ exports[`BasicTextStyleButton > toggles underline on and off > off 1`] = ` } `; -exports[`BasicTextStyleButton > toggles underline on and off > on 1`] = ` +exports[`BasicTextStyleButton > integration > toggles underline on and off > on 1`] = ` { "children": [], "content": [ diff --git a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx index bd17bd40ee..091ced4691 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -3,101 +3,257 @@ import { FormattingToolbar } from "../FormattingToolbar.js"; import { BlockTypeSelect } from "./BlockTypeSelect.js"; describe("BlockTypeSelect", () => { - it("filters custom choices whose block type or property types do not match the schema", async ({ - renderEditor, - page, - }) => { - const { editor } = await renderEditor({ - props: { formattingToolbar: false }, - children: ({ editor }) => ( - null, - }, - { name: "Unavailable block", type: "missing", icon: () => null }, - { - name: "Invalid heading", - type: "heading", - props: { level: "one" }, - icon: () => null, - }, - ]} - /> - ), - }); - - await page - .getByRole("button", { + describe("unit", () => { + it("hides when the current block has no offered type and reappears on a supported block", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Text" }, + { id: "divider", type: "divider" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: editor.dictionary.slash_menu.paragraph.title, exact: true, - }) - .click(); - - const items = page.getByRole("menu").getByRole("menuitem"); - await expect.element(items).toHaveLength(1); - await expect - .element(items) - .toHaveTextContent(editor.dictionary.slash_menu.paragraph.title); - }); + }); + await expect.element(button).toBeVisible(); + + editor.setTextCursorPosition("divider"); + await expect.element(page.getByRole("button")).not.toBeInTheDocument(); + + editor.setTextCursorPosition("text"); + await expect.element(button).toBeVisible(); + }); + + it("hides in read-only mode", async ({ renderEditor, page }) => { + await renderEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); - it("converts the selected block and updates its label without changing neighboring blocks or text", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "before", type: "paragraph", content: "Before" }, - { id: "selected", type: "paragraph", content: "Selected text" }, - { id: "after", type: "paragraph", content: "After" }, - ], - props: { formattingToolbar: false }, - children: , + await expect.element(page.getByRole("button")).not.toBeInTheDocument(); }); - selectText(editor, "Selected text"); - const documentBefore = editor.document; - await page - .getByRole("button", { + // BlockTypeSelect subscribes to selected blocks, not editability. A change + // to editable alone does not update the control until selection changes. + it.fails("reappears when the editor becomes editable without moving selection", async ({ + renderEditor, + page, + }) => { + const { editor, rerender } = await renderEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: editor.dictionary.slash_menu.paragraph.title, exact: true, - }) - .click(); - await page - .getByRole("menuitem", { - name: editor.dictionary.slash_menu.heading.title, - exact: true, - }) - .click(); - - expect(editor.document).toEqual([ - documentBefore[0], - { - ...documentBefore[1], - type: "heading", - props: { - ...documentBefore[1].props, - level: 1, - isToggleable: false, + }); + await expect.element(button).not.toBeInTheDocument(); + + rerender({ editable: true }); + + await expect.poll(() => editor.isEditable).toBe(true); + expect(button.query()).not.toBeNull(); + }); + it("filters custom choices whose block type or property types do not match the schema", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + props: { formattingToolbar: false }, + children: ({ editor }) => ( + null, + }, + { name: "Unavailable block", type: "missing", icon: () => null }, + { + name: "Invalid heading", + type: "heading", + props: { level: "one" }, + icon: () => null, + }, + ]} + /> + ), + }); + + await page + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); + + const items = page.getByRole("menu").getByRole("menuitem"); + await expect.element(items).toHaveLength(1); + await expect + .element(items) + .toHaveTextContent(editor.dictionary.slash_menu.paragraph.title); + }); + }); + + describe("integration", () => { + it("converts the selected block and updates its label without changing neighboring blocks or text", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { id: "selected", type: "paragraph", content: "Selected text" }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const documentBefore = editor.document; + + await page + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }) + .click(); + + expect(editor.document).toEqual([ + documentBefore[0], + { + ...documentBefore[1], + type: "heading", + props: { + ...documentBefore[1].props, + level: 1, + isToggleable: false, + }, }, - }, - documentBefore[2], - ]); - await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); - await expect - .element( - page.getByRole("button", { + documentBefore[2], + ]); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }), + ) + .toBeVisible(); + }); + + it("converts all selected blocks while leaving an unselected neighbor intact", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "first", type: "paragraph", content: "First" }, + { id: "second", type: "paragraph", content: "Second" }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + editor.setSelection("first", "second"); + const before = editor.document; + + await page + .getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { name: editor.dictionary.slash_menu.heading.title, exact: true, - }), - ) - .toBeVisible(); + }) + .click(); + + expect(editor.document).toEqual([ + ...before.slice(0, 2).map((block) => ({ + ...block, + type: "heading", + props: { ...block.props, level: 1, isToggleable: false }, + })), + before[2], + ]); + }); }); describe("keyboard", () => { + it("shows a keyboard focus ring on its trigger", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + const outline = await commands.readOutline(button.selector); + + await commands.pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await commands.checkFocusOutline(button.selector, outline); + }); + + it("dismisses with Escape and restores trigger focus without editing", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + const before = editor.document; + const selection = editor.prosemirrorState.selection.toJSON(); + button.element().focus(); + await commands.pressKey("Enter"); + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + + await commands.pressKey("Escape"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect.element(button).toHaveFocus(); + expect(editor.document).toEqual(before); + expect(editor.prosemirrorState.selection.toJSON()).toEqual(selection); + }); it("opens, navigates, and chooses a block type from the keyboard", async ({ renderEditor, selectText, @@ -160,6 +316,67 @@ describe("BlockTypeSelect", () => { }); }); + describe("ARIA", () => { + it("names the current block type and exposes the popup relationship", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { type: "paragraph", content: "Paragraph text" }, + { type: "heading", props: { level: 2 }, content: "Heading text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Paragraph text"); + const paragraph = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + await expect.element(paragraph).toBeVisible(); + + selectText(editor, "Heading text"); + + const heading = page.getByRole("button", { + name: editor.dictionary.slash_menu.heading_2.title, + exact: true, + }); + await expect.element(heading).toBeVisible(); + await expect.element(paragraph).not.toBeInTheDocument(); + await expect.element(heading).toHaveAttribute("aria-haspopup", "menu"); + await expect.element(heading).toHaveAttribute("aria-expanded", "false"); + + await heading.click(); + + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect.element(heading).toHaveAttribute("aria-expanded", "true"); + expect(heading.element().getAttribute("aria-controls")).toBe( + menu.element().id, + ); + }); + + // Our Mantine ToolbarSelect renders the selected option as a checkmark + // only; it does not expose its checked state to assistive technology. + it.fails("exposes the current menu choice as checked", async ({ + renderEditor, + page, + }) => { + const { editor } = await renderEditor({ + props: { formattingToolbar: false }, + children: , + }); + const name = editor.dictionary.slash_menu.paragraph.title; + await page.getByRole("button", { name, exact: true }).click(); + + const item = page.getByRole("menuitem", { name, exact: true }); + await expect.element(item).toBeVisible(); + expect(item.element().getAttribute("aria-checked")).toBe("true"); + }); + }); + describe("axe", () => { it("checks the trigger", async ({ renderEditor, diff --git a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx index 34ff27889c..cdb5a21c89 100644 --- a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx @@ -3,113 +3,176 @@ import { describe, expect } from "vite-plus/test"; import { DesktopFormattingToolbarController } from "./DesktopFormattingToolbarController.js"; describe("DesktopFormattingToolbarController", () => { - it("mounts its custom toolbar while the extension requests it and unmounts it on dismissal", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Selected text" }, - ], - props: { formattingToolbar: false }, - children: ( - ( -
- -
- )} - /> - ), - }); - const extension = editor.getExtension(FormattingToolbarExtension)!; - const toolbar = page.getByRole("toolbar"); - selectText(editor, "Selected text"); - extension.store.setState(false); - await expect.element(toolbar).not.toBeInTheDocument(); + describe("unit", () => { + it("mounts its custom toolbar while the extension requests it and unmounts it on dismissal", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); + const extension = editor.getExtension(FormattingToolbarExtension)!; + const toolbar = page.getByRole("toolbar"); + selectText(editor, "Selected text"); + extension.store.setState(false); + await expect.element(toolbar).not.toBeInTheDocument(); + + extension.store.setState(true); + + await expect + .element( + toolbar.getByRole("button", { name: "Custom action", exact: true }), + ) + .toBeVisible(); - extension.store.setState(true); + extension.store.setState(false); - await expect - .element( - toolbar.getByRole("button", { name: "Custom action", exact: true }), - ) - .toBeVisible(); + await expect.element(toolbar).not.toBeInTheDocument(); + }); + it("renders its toolbar into the supplied portal", async ({ + renderEditor, + selectText, + page, + onTestFinished, + }) => { + const portal = document.createElement("div"); + document.body.append(portal); + onTestFinished(() => portal.remove()); + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); - extension.store.setState(false); + selectText(editor, "Selected text"); - await expect.element(toolbar).not.toBeInTheDocument(); + await expect.element(page.getByRole("toolbar")).toBeVisible(); + expect(portal.contains(page.getByRole("toolbar").element())).toBe(true); + }); }); - it("dismisses with Escape and restores editor focus without changing its selection or document", async ({ - renderEditor, - selectText, - commands, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Selected text" }, - ], - props: { formattingToolbar: false }, - children: ( - ( -
- -
- )} - /> - ), + describe("keyboard", () => { + it("dismisses with Escape and restores editor focus without changing its selection or document", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); + selectText(editor, "Selected text"); + await page + .getByRole("button", { name: "Custom action", exact: true }) + .click(); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + + await commands.pressKey("Escape"); + + expect(editor.getExtension(FormattingToolbarExtension)!.store.state).toBe( + false, + ); + await expect.element(page.getByRole("toolbar")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, + ); + expect(editor.document).toEqual(documentBefore); }); - selectText(editor, "Selected text"); - await page - .getByRole("button", { name: "Custom action", exact: true }) - .click(); - const documentBefore = editor.document; - const selectionBefore = editor.prosemirrorState.selection.toJSON(); - - await commands.pressKey("Escape"); - - expect(editor.getExtension(FormattingToolbarExtension)!.store.state).toBe( - false, - ); - await expect.element(page.getByRole("toolbar")).not.toBeInTheDocument(); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - expect(editor.prosemirrorState.selection.toJSON()).toEqual(selectionBefore); - expect(editor.document).toEqual(documentBefore); }); - it("renders its toolbar into the supplied portal", async ({ - renderEditor, - selectText, - page, - onTestFinished, - }) => { - const portal = document.createElement("div"); - document.body.append(portal); - onTestFinished(() => portal.remove()); - const { editor } = await renderEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Selected text" }, - ], - props: { formattingToolbar: false }, - children: ( - ( -
- -
- )} - /> - ), + describe("integration", () => { + it("does not steal editor focus when the default toolbar appears", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + const textbox = page.getByRole("textbox"); + await textbox.click(); + const before = editor.document; + + selectText(editor, "Selected text"); + + await expect.element(page.getByRole("toolbar")).toBeVisible(); + await expect.element(textbox).toHaveFocus(); + expect(editor.getSelectedText()).toBe("Selected text"); + expect(editor.document).toEqual(before); }); - selectText(editor, "Selected text"); + it("dismisses on an outside click without stealing focus from the outside action", async ({ + renderEditor, + selectText, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + outside: ({ children }) => ( + <> + + {children} + + ), + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + await expect.element(page.getByRole("toolbar")).toBeVisible(); + const before = editor.document; - await expect.element(page.getByRole("toolbar")).toBeVisible(); - expect(portal.contains(page.getByRole("toolbar").element())).toBe(true); + await page + .getByRole("button", { name: "Outside action", exact: true }) + .click(); + + await expect.element(page.getByRole("toolbar")).not.toBeInTheDocument(); + await expect + .element( + page.getByRole("button", { name: "Outside action", exact: true }), + ) + .toHaveFocus(); + expect(editor.document).toEqual(before); + }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx index 3275c6e873..4f9868fada 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx @@ -1,5 +1,4 @@ import { describe, expect } from "vite-plus/test"; -import { BasicTextStyleButton } from "./DefaultButtons/BasicTextStyleButton.js"; import { FormattingToolbar } from "./FormattingToolbar.js"; describe("FormattingToolbar", () => { @@ -116,41 +115,384 @@ describe("FormattingToolbar", () => { }); describe("keyboard", () => { - it("provides visible keyboard focus when entering and traversing its controls", async ({ + it("tabs forward through the default controls for Parent and allows leaving", async ({ renderEditor, + selectText, commands, page, }) => { const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + { type: "paragraph", content: "Sibling" }, + ], props: { formattingToolbar: false }, - children: ( - - - - - ), + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Parent"); + const toolbar = page.getByRole("toolbar"); + await expect.element(toolbar).toBeVisible(); + const sequence: string[] = []; + + await commands.focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(await commands.readAriaSnapshot(active.selector)); + return false; + }); + + expect(sequence).toMatchInlineSnapshot(` + [ + "- button "Paragraph": + - img + - text: Paragraph", + "- button "Bold": + - img", + "- button "Italic": + - img", + "- button "Underline": + - img", + "- button "Strike": + - img", + "- button "Align text left" [pressed]: + - img", + "- button "Align text center": + - img", + "- button "Align text right": + - img", + "- button "Colors": A", + "- button "Create link": + - img", + ] + `); + expect(toolbar.element().contains(document.activeElement)).toBe(false); + }); + + it("tabs forward through the default controls for Child and allows leaving", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + { type: "paragraph", content: "Sibling" }, + ], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Child"); + const toolbar = page.getByRole("toolbar"); + await expect.element(toolbar).toBeVisible(); + const sequence: string[] = []; + + await commands.focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(await commands.readAriaSnapshot(active.selector)); + return false; + }); + + expect(sequence).toMatchInlineSnapshot(` + [ + "- button "Paragraph": + - img + - text: Paragraph", + "- button "Bold": + - img", + "- button "Italic": + - img", + "- button "Underline": + - img", + "- button "Strike": + - img", + "- button "Align text left" [pressed]: + - img", + "- button "Align text center": + - img", + "- button "Align text right": + - img", + "- button "Colors": A", + "- button "Unnest block": + - img", + "- button "Create link": + - img", + ] + `); + expect(toolbar.element().contains(document.activeElement)).toBe(false); + }); + + it("tabs forward through the default controls for Sibling and allows leaving", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + { type: "paragraph", content: "Sibling" }, + ], + props: { formattingToolbar: false }, + children: , }); await page.getByRole("textbox").click(); - const first = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.bold.tooltip, + selectText(editor, "Sibling"); + const toolbar = page.getByRole("toolbar"); + await expect.element(toolbar).toBeVisible(); + const sequence: string[] = []; + + await commands.focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(await commands.readAriaSnapshot(active.selector)); + return false; + }); + + expect(sequence).toMatchInlineSnapshot(` + [ + "- button "Paragraph": + - img + - text: Paragraph", + "- button "Bold": + - img", + "- button "Italic": + - img", + "- button "Underline": + - img", + "- button "Strike": + - img", + "- button "Align text left" [pressed]: + - img", + "- button "Align text center": + - img", + "- button "Align text right": + - img", + "- button "Colors": A", + "- button "Nest block": + - img", + "- button "Create link": + - img", + ] + `); + expect(toolbar.element().contains(document.activeElement)).toBe(false); + }); + + it("tabs backward through the default controls for Parent and allows leaving", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + { type: "paragraph", content: "Sibling" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Parent"); + const toolbar = page.getByRole("toolbar"); + const lastControl = toolbar.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, exact: true, }); - const second = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.italic.tooltip, + await expect.element(lastControl).toBeVisible(); + lastControl.element().focus(); + const sequence = [await commands.readAriaSnapshot(lastControl.selector)]; + + await commands.focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(await commands.readAriaSnapshot(active.selector)); + return false; + }, "backward"); + + expect(sequence).toMatchInlineSnapshot(` + [ + "- button "Create link": + - img", + "- button "Colors": A", + "- button "Align text right": + - img", + "- button "Align text center": + - img", + "- button "Align text left" [pressed]: + - img", + "- button "Strike": + - img", + "- button "Underline": + - img", + "- button "Italic": + - img", + "- button "Bold": + - img", + "- button "Paragraph": + - img + - text: Paragraph", + ] + `); + expect(toolbar.element().contains(document.activeElement)).toBe(false); + }); + + it("tabs backward through the default controls for Child and allows leaving", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + { type: "paragraph", content: "Sibling" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Child"); + const toolbar = page.getByRole("toolbar"); + const lastControl = toolbar.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, exact: true, }); - const firstOutline = await commands.readOutline(first.selector); - const secondOutline = await commands.readOutline(second.selector); + await expect.element(lastControl).toBeVisible(); + lastControl.element().focus(); + const sequence = [await commands.readAriaSnapshot(lastControl.selector)]; - await commands.pressKey("Tab"); + await commands.focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(await commands.readAriaSnapshot(active.selector)); + return false; + }, "backward"); - await expect.element(first).toHaveFocus(); - await commands.checkFocusOutline(first.selector, firstOutline); + expect(sequence).toMatchInlineSnapshot(` + [ + "- button "Create link": + - img", + "- button "Unnest block": + - img", + "- button "Colors": A", + "- button "Align text right": + - img", + "- button "Align text center": + - img", + "- button "Align text left" [pressed]: + - img", + "- button "Strike": + - img", + "- button "Underline": + - img", + "- button "Italic": + - img", + "- button "Bold": + - img", + "- button "Paragraph": + - img + - text: Paragraph", + ] + `); + expect(toolbar.element().contains(document.activeElement)).toBe(false); + }); - await commands.pressKey("Tab"); + it("tabs backward through the default controls for Sibling and allows leaving", async ({ + renderEditor, + selectText, + commands, + page, + }) => { + const { editor } = await renderEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + { type: "paragraph", content: "Sibling" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Sibling"); + const toolbar = page.getByRole("toolbar"); + const lastControl = toolbar.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }); + await expect.element(lastControl).toBeVisible(); + lastControl.element().focus(); + const sequence = [await commands.readAriaSnapshot(lastControl.selector)]; + + await commands.focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(await commands.readAriaSnapshot(active.selector)); + return false; + }, "backward"); - await expect.element(second).toHaveFocus(); - await commands.checkFocusOutline(second.selector, secondOutline); + expect(sequence).toMatchInlineSnapshot(` + [ + "- button "Create link": + - img", + "- button "Nest block": + - img", + "- button "Colors": A", + "- button "Align text right": + - img", + "- button "Align text center": + - img", + "- button "Align text left" [pressed]: + - img", + "- button "Strike": + - img", + "- button "Underline": + - img", + "- button "Italic": + - img", + "- button "Bold": + - img", + "- button "Paragraph": + - img + - text: Paragraph", + ] + `); + expect(toolbar.element().contains(document.activeElement)).toBe(false); }); }); diff --git a/tests/src/end-to-end/fixtures/selection.test.tsx b/tests/src/end-to-end/fixtures/selection.test.tsx deleted file mode 100644 index 392b2bc2da..0000000000 --- a/tests/src/end-to-end/fixtures/selection.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -import { BlockNoteSchema, defaultStyleSpecs } from "@blocknote/core"; -import { describe, expect } from "vite-plus/test"; - -describe("selectText", () => { - it("finds a substring across differently marked text nodes", async ({ - renderEditor, - selectText, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { - type: "paragraph", - content: [ - { type: "text", text: "Before sel", styles: {} }, - { type: "text", text: "ect", styles: { bold: true } }, - { type: "text", text: "ed after", styles: { italic: true } }, - ], - }, - ], - }); - const documentBefore = editor.document; - - selectText(editor, "selected"); - - expect(editor.getSelectedText()).toBe("selected"); - expect(editor.document).toEqual(documentBefore); - }); - - it("resets the search at hard breaks and block boundaries", async ({ - renderEditor, - selectText, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { type: "paragraph", content: "split\nword" }, - { type: "paragraph", content: "split" }, - { type: "paragraph", content: "word" }, - { id: "match", type: "paragraph", content: "splitword" }, - ], - }); - - selectText(editor, "splitword"); - - expect(editor.getSelectedText()).toBe("splitword"); - expect(editor.getSelection()?.blocks.map((block) => block.id)).toEqual([ - "match", - ]); - }); - - it("restricts matching to one block by default, or an inclusive block range", async ({ - renderEditor, - selectText, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "before", type: "paragraph", content: "Repeated text" }, - { id: "start", type: "paragraph", content: "Repeated text" }, - { id: "end", type: "paragraph", content: "Last text" }, - { id: "after", type: "paragraph", content: "Outside text" }, - ], - }); - - selectText(editor, "Repeated", { startBlockId: "start" }); - - expect(editor.getSelectedText()).toBe("Repeated"); - expect(editor.getSelection()?.blocks.map((block) => block.id)).toEqual([ - "start", - ]); - expect(() => selectText(editor, "Last", { startBlockId: "start" })).toThrow( - 'selectText could not find "Last"', - ); - - selectText(editor, "Last", { startBlockId: "start", endBlockId: "end" }); - - expect(editor.getSelectedText()).toBe("Last"); - expect(editor.getSelection()?.blocks.map((block) => block.id)).toEqual([ - "end", - ]); - expect(() => - selectText(editor, "Outside", { - startBlockId: "start", - endBlockId: "end", - }), - ).toThrow('selectText could not find "Outside"'); - }); - - it("supports an editor with a custom schema", async ({ - renderEditor, - selectText, - }) => { - const { editor } = await renderEditor({ - schema: BlockNoteSchema.create({ - styleSpecs: { italic: defaultStyleSpecs.italic }, - }), - initialContent: [{ type: "paragraph", content: "Custom schema" }], - }); - - selectText(editor, "schema"); - - expect(editor.getSelectedText()).toBe("schema"); - }); - - it("fails clearly for invalid input without changing the selection", async ({ - renderEditor, - selectText, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "first", type: "paragraph", content: "First" }, - { id: "last", type: "paragraph", content: "Last" }, - ], - }); - selectText(editor, "First"); - const selectionBefore = editor.prosemirrorState.selection.toJSON(); - - expect(() => selectText(editor, "")).toThrow("non-empty substring"); - expect(() => selectText(editor, "Missing")).toThrow( - 'selectText could not find "Missing"', - ); - expect(() => - selectText(editor, "First", { startBlockId: "missing" }), - ).toThrow("could not find the requested block range"); - expect(() => - selectText(editor, "First", { - startBlockId: "last", - endBlockId: "first", - }), - ).toThrow("blocks in document order"); - expect(editor.prosemirrorState.selection.toJSON()).toEqual(selectionBefore); - }); -}); diff --git a/tests/src/screen-reader/commands.ts b/tests/src/screen-reader/commands.ts new file mode 100644 index 0000000000..a393a101d2 --- /dev/null +++ b/tests/src/screen-reader/commands.ts @@ -0,0 +1,7 @@ +export * from "../utils/commands.js"; +export { + startReader, + screenReaderPressKey as pressKey, + readTranscript, + stopReader, +} from "./screenReader.js"; diff --git a/tests/screen-reader/run-screen-reader.mjs b/tests/src/screen-reader/run-screen-reader.mjs similarity index 74% rename from tests/screen-reader/run-screen-reader.mjs rename to tests/src/screen-reader/run-screen-reader.mjs index 87bf9ae652..3e64518109 100644 --- a/tests/screen-reader/run-screen-reader.mjs +++ b/tests/src/screen-reader/run-screen-reader.mjs @@ -10,15 +10,17 @@ if (!reader) { const result = spawnSync( process.execPath, [ - fileURLToPath(new URL("../node_modules/vite-plus/bin/vp", import.meta.url)), + fileURLToPath( + new URL("../../node_modules/vite-plus/bin/vp", import.meta.url), + ), "test", "--config", - "screen-reader/vite.config.screen-reader.ts", + "src/screen-reader/vite.config.screen-reader.ts", "--run", ...args, ], { - cwd: fileURLToPath(new URL("..", import.meta.url)), + cwd: fileURLToPath(new URL("../..", import.meta.url)), env: { ...process.env, BLOCKNOTE_SCREEN_READER: reader }, stdio: "inherit", }, diff --git a/tests/screen-reader/screenReader.ts b/tests/src/screen-reader/screenReader.ts similarity index 93% rename from tests/screen-reader/screenReader.ts rename to tests/src/screen-reader/screenReader.ts index 674344aede..f563688c35 100644 --- a/tests/screen-reader/screenReader.ts +++ b/tests/src/screen-reader/screenReader.ts @@ -1,6 +1,6 @@ -import { pressKey } from "../src/utils/keyboard.js"; +import { pressKey } from "../utils/keyboard.js"; import type { BrowserCommand } from "vite-plus/test/node"; -import type {} from "../src/utils/positionalMouse.js"; +import type {} from "../utils/positionalMouse.js"; // Import only on native runs: GuidePup cannot initialize on Linux. async function reader() { @@ -56,7 +56,7 @@ export const screenReaderPressKey: BrowserCommand<[key: string]> = async ( * nonempty before comparing it with a Vitest snapshot in the consuming test. * Reading the log does not stop the reader; cleanup belongs in `finally`. */ -export const readTranscript: BrowserCommand<[]> = async () => +export const readTranscript: BrowserCommand<[], string[]> = async () => (await reader()).spokenPhraseLog(); /** * Stops the native reader. Call in an `afterEach` hook's `finally` block so diff --git a/tests/screen-reader/vite.config.screen-reader.ts b/tests/src/screen-reader/vite.config.screen-reader.ts similarity index 66% rename from tests/screen-reader/vite.config.screen-reader.ts rename to tests/src/screen-reader/vite.config.screen-reader.ts index 7a8bc32f59..fdca0d086e 100644 --- a/tests/screen-reader/vite.config.screen-reader.ts +++ b/tests/src/screen-reader/vite.config.screen-reader.ts @@ -1,19 +1,7 @@ -import { - readAriaSnapshot, - readOutline, - checkFocusOutline, - readSelection, - checkAxe, -} from "../src/utils/accessibility.js"; import { fileURLToPath } from "node:url"; import { defineConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; -import { - startReader, - screenReaderPressKey, - readTranscript, - stopReader, -} from "./screenReader.js"; +import * as commands from "./commands.js"; const reader = process.env.BLOCKNOTE_SCREEN_READER; if (reader !== "voiceover" && reader !== "nvda") { @@ -27,19 +15,19 @@ if ( } export default defineConfig({ - root: fileURLToPath(new URL("../", import.meta.url)), - publicDir: fileURLToPath(new URL("../public", import.meta.url)), + root: fileURLToPath(new URL("../../", import.meta.url)), + publicDir: fileURLToPath(new URL("../../public", import.meta.url)), resolve: { alias: { - "@root": fileURLToPath(new URL("../../", import.meta.url)), + "@root": fileURLToPath(new URL("../../../", import.meta.url)), "@blocknote/core": fileURLToPath( - new URL("../../packages/core/src", import.meta.url), + new URL("../../../packages/core/src", import.meta.url), ), "@blocknote/react": fileURLToPath( - new URL("../../packages/react/src", import.meta.url), + new URL("../../../packages/react/src", import.meta.url), ), "@blocknote/mantine": fileURLToPath( - new URL("../../packages/mantine/src", import.meta.url), + new URL("../../../packages/mantine/src", import.meta.url), ), }, dedupe: ["react", "react-dom", "vitest-browser-react"], @@ -47,7 +35,7 @@ export default defineConfig({ test: { name: "screen-reader", setupFiles: [ - fileURLToPath(new URL("../vitestSetup.browser.ts", import.meta.url)), + fileURLToPath(new URL("../../vitestSetup.browser.ts", import.meta.url)), ], include: ["../packages/*/src/**/*.screen-reader.test.ts"], testTimeout: 300_000, @@ -81,17 +69,7 @@ export default defineConfig({ name: reader, }, ], - commands: { - readAriaSnapshot, - readOutline, - checkFocusOutline, - readSelection, - checkAxe, - startReader, - pressKey: screenReaderPressKey, - readTranscript, - stopReader, - }, + commands, }, }, }); diff --git a/tests/src/utils/commands.browser.ts b/tests/src/utils/commands.browser.ts new file mode 100644 index 0000000000..0dcc4f59d5 --- /dev/null +++ b/tests/src/utils/commands.browser.ts @@ -0,0 +1 @@ +export { focusUntil } from "./focus.js"; diff --git a/tests/src/utils/commands.ts b/tests/src/utils/commands.ts new file mode 100644 index 0000000000..7d5cefe28f --- /dev/null +++ b/tests/src/utils/commands.ts @@ -0,0 +1,11 @@ +export { + readAriaSnapshot, + readOutline, + checkFocusOutline, + readSelection, + checkAxe, +} from "./accessibility.js"; +export { pressKey } from "./keyboard.js"; +export { positionalMouse } from "./positionalMouse.js"; +export { imeComposition } from "./imeComposition.js"; +export { restoreTouchEmulation } from "./restoreTouchEmulation.js"; diff --git a/tests/src/utils/context.ts b/tests/src/utils/context.ts index 7c08bca368..23422be992 100644 --- a/tests/src/utils/context.ts +++ b/tests/src/utils/context.ts @@ -1,12 +1,10 @@ -import type { ImeCompositionCommand } from "./imeComposition.js"; -import type { PositionalMouseCommand } from "./positionalMouse.js"; -import type { Outline, EditorSelection } from "./accessibility.js"; import { commands as vitestCommands, page, server, userEvent, } from "vite-plus/test/browser"; +import * as browserCommands from "./commands.browser.js"; // `vite-plus/test/browser` re-exports `vitest/browser`, which Vitest replaces // with a generated virtual module while running in Browser Mode. Import it from @@ -14,24 +12,23 @@ import { // (it preserves keyboard/pointer state across calls) and one command surface. export { page, server, userEvent }; -// Vite+ does not expose the augmentable BrowserCommands interface. -export const commands = vitestCommands as typeof vitestCommands & { - positionalMouse: PositionalMouseCommand; - imeComposition: ImeCompositionCommand; - restoreTouchEmulation(): Promise; - // Registered only by the native screen-reader configuration. - startReader(selector: string): Promise; - readTranscript(): Promise; - stopReader(): Promise; - pressKey(key: string): Promise; - readAriaSnapshot(selector: string): Promise; - readOutline(selector: string): Promise; - checkFocusOutline( - selector: string, - unfocusedOutline?: Outline, - ): Promise; - readSelection(): Promise; - checkAxe(scope?: string): Promise; +type BrowserCommands = { + [Name in keyof Implementations]: Implementations[Name] extends ( + ...args: infer Args + ) => infer Result + ? Args extends [unknown, ...infer BrowserArgs] + ? (...args: BrowserArgs) => Promise> + : never + : never; +}; + +// Vite+ does not expose the augmentable BrowserCommands interface. Derive the +// browser signatures from the implementations, omitting their Node context. +// Reader commands are available only in the native screen-reader configuration. +export const commands = { + ...(vitestCommands as typeof vitestCommands & + BrowserCommands), + ...browserCommands, }; /** The browser instance the current test is running in. */ diff --git a/tests/src/utils/focus.ts b/tests/src/utils/focus.ts new file mode 100644 index 0000000000..d31a95f6d5 --- /dev/null +++ b/tests/src/utils/focus.ts @@ -0,0 +1,49 @@ +import type { Locator } from "vite-plus/test/browser"; +import { commands, page } from "./context.js"; + +type FocusTarget = + | Locator + | ((locator: Locator) => void | boolean | Promise); + +/** + * Tabs in the given direction, calling the predicate after each step, until it returns true + * or the target locator receives focus. The starting element is not visited. + * Throws if focus cycles, stops moving, or leaves the document first. + */ +export async function focusUntil( + target: FocusTarget, + direction: "forward" | "backward" = "forward", +): Promise { + const key = direction === "forward" ? "Tab" : "Shift+Tab"; + const visited = new Set(); + if (!document.activeElement) { + throw new Error(`${key}: document.activeElement is null`); + } + visited.add(document.activeElement); + + while (true) { + await commands.pressKey(key); + const active = document.activeElement; + if (!active) { + throw new Error(`${key}: document.activeElement is null`); + } + if (visited.has(active)) { + throw new Error( + `${key}: focus cycled or stopped moving before finding the target`, + ); + } + visited.add(active); + + const locator = page.elementLocator(active); + const found = + typeof target === "function" + ? await target(locator) + : target.query() === active; + if (found === true) { + return locator; + } + if (active === document.body || active === document.documentElement) { + throw new Error(`${key}: reached the end of focusable elements`); + } + } +} diff --git a/tests/src/utils/imeComposition.ts b/tests/src/utils/imeComposition.ts index 6579a10239..6b1e229ca9 100644 --- a/tests/src/utils/imeComposition.ts +++ b/tests/src/utils/imeComposition.ts @@ -23,12 +23,6 @@ export type ImeStep = } | { type: "commit"; text: string }; -/** - * Browser-side signature of the {@link imeComposition} command (Vitest strips - * the Node-only context parameter — see positionalMouse.ts for the pattern). - */ -export type ImeCompositionCommand = (steps: ImeStep[]) => Promise; - /** * Drives Chromium's real IME composition pipeline over CDP * (`Input.imeSetComposition` / `Input.insertText`): the browser produces the diff --git a/tests/src/utils/positionalMouse.ts b/tests/src/utils/positionalMouse.ts index 840a088840..4c893455ba 100644 --- a/tests/src/utils/positionalMouse.ts +++ b/tests/src/utils/positionalMouse.ts @@ -25,17 +25,6 @@ export type MouseAction = | { type: "up" } | { type: "click"; x: number; y: number; clickCount?: number }; -/** - * Browser-side signature of the {@link positionalMouse} command below, i.e. what - * `BrowserCommand` turns into once Vitest strips the (Node-only) - * `BrowserCommandContext` first parameter. Used by `context.ts` to type the - * shared browser `commands` object — see the note there on why this - * can't be a `declare module` augmentation. - */ -export type PositionalMouseCommand = ( - ...actions: MouseAction[] -) => Promise; - /** * Vitest's `userEvent` doesn't have several mouse commands that we relied on in Playwright, namely * clicking at the current mouse position, and moving the mouse to a given position across N steps. diff --git a/tests/tsconfig.browser.json b/tests/tsconfig.browser.json index 4c439e0446..917e1bbe5c 100644 --- a/tests/tsconfig.browser.json +++ b/tests/tsconfig.browser.json @@ -24,7 +24,6 @@ "src/utils/**/*.ts", "src/utils/**/*.tsx", "src/fixtures/**/*.tsx", - "screen-reader/**/*.ts", "vitestSetup.browser.ts", "../packages/*/src/**/*.browser.test.*", "../packages/*/src/**/*.screen-reader.test.ts" diff --git a/tests/vite.config.browser.ts b/tests/vite.config.browser.ts index 4d18c603d7..62d6457deb 100644 --- a/tests/vite.config.browser.ts +++ b/tests/vite.config.browser.ts @@ -3,16 +3,7 @@ import * as fs from "fs"; import * as path from "path"; import { configDefaults, defineConfig, type UserConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; -import { - readAriaSnapshot, - readOutline, - checkFocusOutline, - readSelection, - checkAxe, -} from "./src/utils/accessibility.js"; -import { pressKey } from "./src/utils/keyboard.js"; -import { positionalMouse } from "./src/utils/positionalMouse.js"; -import { imeComposition } from "./src/utils/imeComposition.js"; +import * as commands from "./src/utils/commands.js"; // For the desktop instances: end-to-end/mobile runs only in the "android" // instance. An instance-level `exclude` replaces the resolved base exclude @@ -30,7 +21,6 @@ const DESKTOP_EXCLUDE = [ "**/end-to-end/mobile/**", "../packages/*/src/**/*.screen-reader.test.ts", ]; -import { restoreTouchEmulation } from "./src/utils/restoreTouchEmulation.js"; // 1280x720 matches the old Playwright defaults so visual baselines have room. // Used as the playwright context viewport for every browser instance. @@ -180,17 +170,7 @@ export default defineConfig( // still show in the HTML report (errors + stack traces don't depend // on these shots), so disable them. See `e2e:report` to view. screenshotFailures: false, - commands: { - positionalMouse, - imeComposition, - restoreTouchEmulation, - readAriaSnapshot, - readOutline, - checkFocusOutline, - readSelection, - checkAxe, - pressKey, - }, + commands, instances: [ { browser: "chromium", diff --git a/vite.config.ts b/vite.config.ts index ebf5f9eb7a..8bb4cd5042 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -15,7 +15,7 @@ export default defineConfig({ cache: { scripts: true }, tasks: { "test:screen-reader": { - command: "node tests/screen-reader/run-screen-reader.mjs", + command: "node tests/src/screen-reader/run-screen-reader.mjs", cache: false, }, "copy-package-readmes": { From 38411fa386c924e58cda0576bb5b1446be0d6691 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Tue, 17 Nov 2026 19:22:14 +0100 Subject: [PATCH 04/14] test: refine shared fixtures and component testing conventions --- .claude/skills/playwright-cli/SKILL.md | 2 +- .../references/spec-driven-testing.md | 2 +- .claude/skills/testing-skill/SKILL.md | 112 ++++---- .../references/accessibility-tests.md | 77 ----- .../references/component-testing.md | 62 ++++ .../__snapshots__/block.browser.test.tsx.snap | 20 -- .../src/blocks/Heading/block.browser.test.tsx | 185 ++++++------ .../BasicTextStyleButton.browser.test.tsx | 267 +++++++++--------- .../ColorStyleButton.browser.test.tsx | 165 ++++++----- .../CreateLinkButton.browser.test.tsx | 107 +++---- .../NestBlockButtons.browser.test.tsx | 164 +++++------ .../TextAlignButton.browser.test.tsx | 65 +++-- .../BlockTypeSelect.browser.test.tsx | 126 +++++---- ...rmattingToolbarController.browser.test.tsx | 102 +++---- .../FormattingToolbar.browser.test.tsx | 132 +++++---- .../FormattingToolbar.screen-reader.test.ts | 21 +- .../src/editor/BlockNoteView.browser.test.tsx | 48 +++- scripts/lint/README.md | 36 +++ scripts/lint/component-browser-tests.mjs | 209 ++++++++++++++ scripts/lint/component-browser-tests.test.mjs | 237 ++++++++++++++++ tests/src/commands/browser/ariaSnapshot.ts | 30 ++ tests/src/commands/browser/axe.ts | 29 ++ tests/src/commands/browser/focus.ts | 67 +++++ tests/src/commands/browser/index.ts | 9 + tests/src/commands/browser/outline.ts | 67 +++++ tests/src/commands/browser/selectText.ts | 84 ++++++ tests/src/commands/browser/setupEditor.tsx | 207 ++++++++++++++ tests/src/commands/index.ts | 74 +++++ .../node}/imeComposition.ts | 23 ++ .../commands.ts => commands/node/index.ts} | 8 +- tests/src/commands/node/keyboard.ts | 35 +++ .../node}/positionalMouse.ts | 26 +- .../node}/restoreTouchEmulation.ts | 15 + tests/src/commands/node/setupEditor.ts | 108 +++++++ tests/src/commands/transport.ts | 28 ++ tests/src/fixtures/editor.node.ts | 12 + tests/src/fixtures/editor.tsx | 217 +------------- tests/src/screen-reader/commands.ts | 2 +- tests/src/screen-reader/screenReader.ts | 47 ++- tests/src/utils/accessibility.ts | 153 ---------- tests/src/utils/commands.browser.ts | 1 - tests/src/utils/context.ts | 36 +-- tests/src/utils/focus.ts | 49 ---- tests/src/utils/keyboard.ts | 24 -- tests/src/utils/mouse.ts | 2 +- tests/vite.config.browser.ts | 2 +- tests/vitestSetup.browser.ts | 4 +- vite.config.ts | 96 ++++++- 48 files changed, 2294 insertions(+), 1300 deletions(-) delete mode 100644 .claude/skills/testing-skill/references/accessibility-tests.md create mode 100644 .claude/skills/testing-skill/references/component-testing.md delete mode 100644 packages/core/src/blocks/Heading/__snapshots__/block.browser.test.tsx.snap create mode 100644 scripts/lint/README.md create mode 100644 scripts/lint/component-browser-tests.mjs create mode 100644 scripts/lint/component-browser-tests.test.mjs create mode 100644 tests/src/commands/browser/ariaSnapshot.ts create mode 100644 tests/src/commands/browser/axe.ts create mode 100644 tests/src/commands/browser/focus.ts create mode 100644 tests/src/commands/browser/index.ts create mode 100644 tests/src/commands/browser/outline.ts create mode 100644 tests/src/commands/browser/selectText.ts create mode 100644 tests/src/commands/browser/setupEditor.tsx create mode 100644 tests/src/commands/index.ts rename tests/src/{utils => commands/node}/imeComposition.ts (69%) rename tests/src/{utils/commands.ts => commands/node/index.ts} (64%) create mode 100644 tests/src/commands/node/keyboard.ts rename tests/src/{utils => commands/node}/positionalMouse.ts (63%) rename tests/src/{utils => commands/node}/restoreTouchEmulation.ts (71%) create mode 100644 tests/src/commands/node/setupEditor.ts create mode 100644 tests/src/commands/transport.ts create mode 100644 tests/src/fixtures/editor.node.ts delete mode 100644 tests/src/utils/accessibility.ts delete mode 100644 tests/src/utils/commands.browser.ts delete mode 100644 tests/src/utils/focus.ts delete mode 100644 tests/src/utils/keyboard.ts diff --git a/.claude/skills/playwright-cli/SKILL.md b/.claude/skills/playwright-cli/SKILL.md index 8bfa4bafd8..8a2c4c4cfd 100644 --- a/.claude/skills/playwright-cli/SKILL.md +++ b/.claude/skills/playwright-cli/SKILL.md @@ -8,7 +8,7 @@ allowed-tools: Bash(playwright-cli:*) Bash(npx:*) Bash(npm:*) ## BlockNote test conventions -When authoring or changing tests in this repository, follow [testing-skill](../testing-skill/SKILL.md). Colocated component/accessibility tests use Vitest browser mode, one `*.test.ts` file with separate describe groups, and the shared Docker e2e runner. Read its [accessibility reference](../testing-skill/references/accessibility-tests.md) for assertion scopes, navigation helpers, and native-only screen-reader tests. These repository conventions take precedence over the generic Playwright test-generation examples below and in the references: do not introduce a standalone Playwright runner, one `.spec.ts` per scenario, or native browser-suite runs. +When authoring or changing tests in this repository, follow [testing-skill](../testing-skill/SKILL.md). Colocated component tests use Vitest browser mode, one `*.browser.test.{ts,tsx}` file with separate describe groups, and the shared Docker e2e runner. Read its [React component testing reference](../testing-skill/references/component-testing.md) for component testing conventions. These repository conventions take precedence over the generic Playwright test-generation examples below and in the references: do not introduce a standalone Playwright runner, one `.spec.ts` per scenario, or native browser-suite runs. ## Quick start diff --git a/.claude/skills/playwright-cli/references/spec-driven-testing.md b/.claude/skills/playwright-cli/references/spec-driven-testing.md index f07d45f90f..859d3267d8 100644 --- a/.claude/skills/playwright-cli/references/spec-driven-testing.md +++ b/.claude/skills/playwright-cli/references/spec-driven-testing.md @@ -1,6 +1,6 @@ # Spec-driven testing (plan → generate → heal) -For BlockNote repository tests, use [testing-skill](../../testing-skill/SKILL.md) and its [accessibility conventions](../../testing-skill/references/accessibility-tests.md). The generic runner setup and one-test-per-file instructions here do not apply to BlockNote's Vitest browser suite. +For BlockNote repository tests, use [testing-skill](../../testing-skill/SKILL.md) and its [React component testing conventions](../../testing-skill/references/component-testing.md). The generic runner setup and one-test-per-file instructions here do not apply to BlockNote's Vitest browser suite. End-to-end workflow for authoring and maintaining Playwright tests using `playwright-cli`. The three sections below can be used independently: diff --git a/.claude/skills/testing-skill/SKILL.md b/.claude/skills/testing-skill/SKILL.md index 0607ae97d9..9ba299c238 100644 --- a/.claude/skills/testing-skill/SKILL.md +++ b/.claude/skills/testing-skill/SKILL.md @@ -1,93 +1,77 @@ --- name: testing-skill -description: Instructions for writing, running, and updating unit, end-to-end, and colocated accessibility tests. Use when adding or changing tests for a feature, bug, or regression. +description: Rules and examples for placing, writing, and running unit, integration, browser component, and accessibility tests. --- # Testing -In most cases, once a feature, bug fix, or other modification has been written, it will need to have tests added, or existing tests updated. +## Decide where to test -## The test-layer ladder +Test behavior beside its owner, at the lowest reasonable rung of the test ladder that can reliably prove it works: -Six layers, ordered by cost (speed, determinism, machinery), cheapest first. Prefer the first rung where the test can go red: +| Rung | Environment and location | +| ---------------------------- | ------------------------------------------------------------------------------------------------------- | +| 1. Unit | Node, colocated `packages/*/src/**/*.test.ts`. | +| 2. Browser component | Real DOM/rendering, colocated `*.browser.test.{ts,tsx}`; includes focused component integrations. | +| 3. Cross-package integration | Node, `tests/src/unit`; documents through real pipelines, parsing, and exports. | +| 4. Browser e2e | `tests/src/end-to-end`; broader journeys and complete browser pipelines. | +| 5. Mobile-emulated | `end-to-end/mobile/**`, Android browser instance; touch, viewport, emulated IME differences. | +| 6. Real device | Only behavior emulation cannot establish; device suite is parked on `mobile/emulator-layer` (PR #3034). | -1. **Unit tests** — node, colocated in `packages/*` (`vp run test`) -2. **Browser unit tests** — colocated `*.browser.test.{ts,tsx}`: one unit that genuinely needs real DOM/rendering -3. **Cross-package integration tests** — node, `tests/src/unit`: full documents through real pipelines (parsing, format conversion, export) -4. **Browser e2e** — `tests/src/end-to-end`: UI flows in real browsers (Docker) -5. **Mobile-emulated e2e** — `end-to-end/mobile/**` and the suites on the `android` instance: only for behavior that differs under mobile conditions (touch, viewport, UA, emulated IME). One restriction: suites here must not take iframe-element screenshots (`screenshotFull`) — that path permanently drops the context's touch emulation for every later test file (see `utils/ensureTouchEmulation.ts`), so such suites stay out of the android instance's include -6. **Device suite** — _parked_: a real emulator/simulator suite (one session interface, Android via Playwright `_android` + adb, iOS via Appium/XCUITest) lives on the `mobile/emulator-layer` branch (PR #3034). It left the active stack because every fix it guarded is red-first provable on the emulated instance; revive it only for a bug class that emulation demonstrably cannot observe (the IME's own action-key choice, real-keyboard viewport resize, real iOS Safari focus/zoom) — until then those are the manual checklist below. +The ladder guides placement, not a requirement to try every environment. Use a real browser, not jsdom, for clicking, keyboard navigation, focus, or rendered component behavior. Editor/document logic stays in faster Node tests, where `setupEditor` mounts the core editor in jsdom. Rungs 2 and 3 distinguish ownership/location, not strictly runtime cost. -**One rule decides placement: red-first.** Every test must fail without the change it guards — a test that passes either way proves nothing, and for regression fixes this means actually running it against the pre-fix code. Red-first also _places_ the test: write it at the first (cheapest) rung where it goes red. If the failure isn't observable there (the rung's environment fakes away the very thing that breaks), move one rung further down the list and try again. Once it goes red, stop — the rungs after it add cost, not proof. +Integrations verify boundaries, not repeat dependencies' tests. A parent assumes its children work: test toolbar composition/traversal at the toolbar, button activation at the button, and detailed document operations at their editor commands. -Corollaries: +## Rules -- **No duplicate coverage below.** Behavior proven red at rung N is not re-tested at N+1. One narrow exception: when a rung works by faking something (CDP-emulated IME, touch emulation), a single thin test one rung down may pin that the fake matches reality — it guards the _fake_, not the feature. -- **Bulk lives high, lower rungs stay thin.** Layers 1–4 hold the breadth; layer 5 holds only mobile-conditional behavior. -- **When a rung can't observe the OS's half of a bug, say so in the test.** Example: `mobile/linkSubmit.test.tsx` proves submission works with no key event, and its header documents the un-emulatable half (which action the IME chooses) — that half lives on the manual checklist, visible where the coverage stops. -- Rungs 2 and 3 order by colocation, not machinery cost — a browser unit test needs heavier machinery than a node integration test, but it lives next to the unit it covers, and colocation wins. They are rarely substitutes anyway: if the code needs no browser, use 1 or 3; if one unit needs a browser, use 2. +- **Cover user-important behavior and applicable categories**, not every branch or state combination. Low-value defensive branches need not be exercised merely for coverage. +- **Reported bugs generally warrant regression tests.** Prove regressions red-first against the bug, then green with the fix. Follow TDD for new behavior; modifying existing tests does not require manufacturing another red run. Styling fixes may reasonably lack regression tests when automation is cumbersome or implementation-coupled. +- **Use real internal dependencies.** Mock/fake only when necessary, such as external services. Observation-only spies are fine. +- **Distinguish unit from integration by scope.** A function changing block color is a unit contract; clicking a button and checking the editor/UI color change crosses subsystems. +- **Arrange → Act → Assert.** Name the outcome, establish the case, exercise the real entry point, and assert its relevant behavior. Repeated act/assert pairs are fine when clearer. Setup APIs must not perform the action the test claims to verify. +- **Share understandable conventions.** Prefer `setupEditor` and common mechanics to bespoke setup. Abstract repeated patterns when they improve understanding. Choose inline cases versus `it.for` for readability, not minimum line count. +- **Keep assertions relevant.** Verify the owner's contract without coupling to unrelated details. For example, an extra unused callback argument should not break a test that only cares whether it was called. +- **Wait for observable state.** Use retrying assertions and `expect.poll`, not arbitrary sleeps. Investigate local retries; limited retries may be warranted for inherently flaky environments, not as a substitute for readiness. +- **Expose defects.** Notify the user when tests reveal issues. If a known defect must remain, assert its precise expected violation or use a narrow `it.fails`, with a linked issue. Do not hide it with a skip. +- **Verify proportionately.** Targeted tests, sometimes one browser, can suffice. Broaden for shared infrastructure, browser differences, or uncertain impact. Run lint/format on touched code. -## Mobile release checklist (manual) +## Structure and assertions -The device-only behaviors above, checked on real hardware before a release: +Component browser files have one owner-named outer `describe` and applicable groups in this order: `unit`, `integration`, `keyboard`, `a11y`. Reasonably cover each applicable category; omit irrelevant groups. ARIA assertions and axe scans share `a11y`; there is no separate `axe` group. Accessibility belongs alongside normal behavior. -- **Android phone** (ideally with an OEM keyboard, e.g. Samsung Keyboard): create a link from an editor that is _not_ the last on the page — the keyboard's action key must submit the popover (not jump focus to the next editor), with the keyboard and toolbar staying up. Then type in the editor and press the on-screen Enter: a new block, no stray space or table corruption. -- **iOS Safari**: open the link popover — focusing the URL input must not zoom the page; submit with the return key. +Pure-function tests use a function-named `describe`; give integrated scenarios a separate `describe` when needed. Follow established patterns without inventing unnecessary structure. -## Test File Locations +| Assertion | Use | +| ----------------- | ------------------------------------------------------------------------------------------------------ | +| `toEqual` | Deliberate expected values/object shapes. Use partial assertions when only part of the result matters. | +| Inline snapshot | Small serialized results; prefer inline when readable. Size is a guideline, not a cutoff. | +| External snapshot | Large documents, exports, or trees whose output would obscure the test. | -### Unit Tests +Screenshots are a last resort for behavior. Prefer state, DOM, or accessibility assertions; do not compare before/after screenshots to prove a click worked. A few deliberate subsystem baselines can guard visual regressions, with awareness of false positives. -`/tests/src/unit`: Contains the bulk of unit tests, mainly relating to interoperability between BlockNote's JSON format and HTML/Markdown. Also includes some miscellaneous tests, like React rendering, selection handling, and NextJS integration. +## Golden examples -`/packages/core/src/api`: Contains mainly tests for getting, inserting, updating, and removing blocks, etc, under `/blockManipulation/commands`. Also includes tests for intermediary functionality between BlockNote and the underlying TipTap editor, like converting between blocks & nodes, or setting editor event handlers. +- [BasicTextStyleButton](../../../packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx): component behavior, editor integration, keyboard, a11y (ARIA and axe). +- [FormattingToolbar](../../../packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx): composition and traversal of child controls. -`/packages/xl-*`: Contain tests for functionality included in a given `xl-*` package. +Use these as patterns, not templates to copy mechanically. For testing a React component, read [Component testing](references/component-testing.md). -### Colocated Browser Unit Tests +## Editor setup -`packages/*/src/**/*.browser.test.{ts,tsx}`: Unit tests for browser-only implementations (e.g. canvas or DOM-dependent code) live next to the code they test, with a `.browser.test` suffix. They run as part of the browser suite in Docker (the `tests` package's browser config includes them); the packages' own node-mode vitest configs exclude them. Use this when the unit under test genuinely needs a real browser — everything else should be a plain node unit test. +Use `const { editor } = await setupEditor({ ...editorOptions })` in either environment. Browser tests receive it from the shared fixture; it renders a view and additionally accepts `skin`, `props`, `children`, and `outside`, returning `rerender` too. Node tests import `test` from `tests/src/fixtures/editor.node.ts` and use the jsdom environment; their helper mounts the core editor without React or skin styles. Both preserve custom-schema types and clean up after the test. For headless logic, use `BlockNoteEditor.create` directly. -### End-to-End Tests +## Run -`tests/src/end-to-end`: Tests that need a real browser and span multiple packages go here — chiefly tests which interact with the editor UI or simulate user interaction, but also browser integration tests that exercise complete flows without interaction (e.g. exporting a full document, static rendering). New subdirectories can be added if the functionality being tested is not covered by any of the existing ones. Important note about existing E2E tests - many are written poorly and should only loosely be used as reference. We want to avoid abstraction layers and `waitForTimeout` as much as possible. - -### Colocated Component and Accessibility Tests - -Component accessibility coverage is colocated with the component/block, but runs in the existing Docker e2e suite. Use the same `*.browser.test.ts` file as for browser unit tests. Use separate `test.describe("keyboard")`, `"ARIA"`, `"axe"`, and, where needed, `"visual"` groups, as well as an additional `"behaviour"` group for existing unit tests. Native screen-reader edge cases belong in an optional `*.screen-reader.test.ts` file and run locally only, outside regular e2e/CI. - -When adding or changing this coverage, read [Accessibility test structure and helpers](references/accessibility-tests.md). It defines each group's assertions, fixture/helper conventions, discovery configuration, and run commands. Use the colocated FormattingToolbar, BlockNoteView, and Heading tests as the concrete examples; do not create per-component `a11y/` directories or separate files for each assertion type. - -## When & How to Add Tests - -Placement and proof obligations are governed by the ladder above: pick the rung red-first, and verify every new test fails without the code change it covers (for edge cases and new features too — existing tests continuing to pass is exactly the situation that demands new red-first ones). - -**Don't use jsdom** (`@vitest-environment jsdom`) in new tests. It's a murky middle ground — `document` exists but rendering doesn't — which makes browser-capability checks pass while the capability itself is broken. Use the default node environment with pluggable seams for logic, and the browser suite (`tests/src/end-to-end`, vitest browser mode in Docker) for anything that needs real rendering. - -## Running & Updating Tests - -### Unit Tests - -Unit tests can be run from the root directory using `vp run test`, which will run all of them across all directories. A specific test file may be targeted by appending its name, i.e. `vp run test fileName`. Individual tests in a file may be disabled using `skip`, i.e. `it.skip("Test name", ...)` (remember to revert this once all tests pass). - -Updating tests can be done by adding the `-u` argument, i.e. `vp run test -u`. All of the other things you can do to scope which tests to target still apply. - -### End-to-End Tests - -End-to-end tests run in vitest browser mode (chromium, firefox and webkit) inside a Docker container, so screenshot baselines are identical locally and on CI. Run them from the repository root: +Use `vite-plus/test` imports and repository commands: ```bash -bash tests/docker-run.sh -e CI=1 -- --run [filters] +vp run test +bash tests/docker-run.sh -e CI=1 -- --run --retry=0 +# Optional: --project "e2e (chromium)" or -t keyboard +vp run lint +vp run format ``` -**Never run the browser suite natively** (`vp test -c vite.config.browser.ts` outside the container) — not even "just one file". Two failure modes, both silent: the screenshot matcher _seeds_ a new `-darwin`/`-win32` baseline for every screenshot test that has none (passing without comparing anything, and littering the tree with hundreds of unvetted PNGs — these are gitignored as a backstop, and only `-linux` baselines are tracked), and several suites genuinely behave differently outside Linux (e.g. caret placement is font-metric-dependent, so platform-shared JSON snapshots mismatch). If Docker isn't running, notify the user to launch it instead of falling back to a native run. - -Native screen-reader tests use the separate local runner described in the accessibility reference; the Docker-only rule above applies to the regular browser suite. - -A specific test file may be targeted by appending (part of) its name as a filter. A single browser may be targeted with `--project "e2e (chromium)"`. Individual tests in a file may be disabled using `skip`, i.e. `test.skip("Test name", ...)` (remember to revert this once all tests pass). - -Screenshot baselines can be regenerated with `--update=true` (as `e2e:updateSnaps` does). Always attach the value: vitest declares the flag as `-u, --update [type]` (it also accepts `new`/`all`/`none`), so a bare `-u` before a filter swallows the filter as its value and silently runs the **whole** suite in update mode. `--update=true` cannot, so filters stay filters in any position. Note that `-u` only rewrites baselines whose comparison **fails** — a small intended change (e.g. a short text edit) that fits inside the suite's 2% pixel tolerance leaves the baseline stale while the test passes. To force a fresh capture, delete the baseline file first. Baselines are per-browser (`--linux.png`); after regenerating, always inspect the images before committing them. - -When testing a visual change, prefer writing screenshots to verify that the change is working as expected. +**Browser tests always run in Docker.** Native runs produce incompatible platform snapshots and behavior. If Docker is unavailable, ask the user to start it. Native screen-reader tests use their separate intentional local workflow. -**Screenshots of tall content**: browser-suite tests run inside a tester iframe sized to the browser window (1280x720), and element screenshots only contain what the iframe actually paints — anything below its fold captures as blank white, silently. Growing the iframe with `page.viewport()` alone doesn't fix this at full resolution: the harness scales the iframe down to fit the window, shrinking the resulting baseline (`static.test.tsx` accepts that trade-off). For full-resolution captures use `screenshotFull` (`tests/src/utils/screenshotFull.ts`), which grows the iframe past the content and neutralizes the harness's scale transform during the capture — the same mechanism upstream Vitest adopted in vitest-dev/vitest#9745 (milestone 5.0.0; the util can be deleted once vite-plus ships it). Always eyeball newly generated baselines for truncation. +For filtered snapshot updates, attach the value: `--update=true`. A bare `-u` can consume the file filter and update the entire suite. diff --git a/.claude/skills/testing-skill/references/accessibility-tests.md b/.claude/skills/testing-skill/references/accessibility-tests.md deleted file mode 100644 index 7aae792e80..0000000000 --- a/.claude/skills/testing-skill/references/accessibility-tests.md +++ /dev/null @@ -1,77 +0,0 @@ -# Colocated component and accessibility tests - -All paths below are relative to the repository root. These are browser integration tests, identified by the `.browser.test.ts` or `.browser.test.tsx` suffix. They use the existing e2e configuration and CI jobs, not a separate accessibility browser project or workflow. - -## Files and fixtures - -Place files directly beside the component or block: - -```text -FormattingToolbar.tsx -FormattingToolbar.browser.test.tsx -FormattingToolbar.screen-reader.test.ts # optional, native/local only -__snapshots__/ # ARIA snapshots -__screenshots__/ # browser-specific visual baselines -``` - -Examples to read before extending an area: - -- `packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx` -- `packages/react/src/editor/BlockNoteView.browser.test.tsx` -- `packages/core/src/blocks/Heading/block.browser.test.tsx` - -Keep the browser scenarios in one file, grouped by assertion purpose. Do not split them into `.keyboard.test.ts`, `.aria.test.ts`, `.axe.test.ts`, or `.visual.test.ts` files or put them in a component-local `a11y/` directory. Only add groups relevant to the component. - -Declare document fixtures in their consuming test files, with names ending in `Document` and typed as `PartialBlock[]`. Prefer plain data; avoid fixture-selection factories and separate `fixtures.ts` files. If browser and screen-reader tests share a fixture or helper, export it from the owning test file and import it in the other. Guard browser suite registration with `if (!screenReader)` when the native suite imports that file, so importing helpers does not collect browser scenarios in the native run. - -Write explicit named tests for the distinct user interactions covered by the component. Name each test after the outcome it asserts, rather than only the actions it performs. Share repeated test logic through named functions near the start of the file or describe block, rather than registering different interactions in a loop. Use names specific to the component and element being tested, such as `toggleButton`, `linkInput`, or `toolbarMenu`, rather than `control`. - -## Describe blocks and assertion scope - -The same keyboard actions may appear in several groups. Each group checks a different outcome; avoid adding every kind of assertion to every test. - -| Group | Actions and assertions | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `behavior` | Navigate using the keyboard and activate with Enter. Assert the component's functional effect. For document edits, subscribe with `editor.onChange(vi.fn())` after navigation and before activation, register the unsubscribe with `onTestFinished`, and assert the callback ran. View-only changes may need another observable effect: toggle-heading tests check persisted expansion state. Keep detailed editor-command unit tests colocated with those commands rather than duplicating them here. | -| `keyboard` | Assert the relevant focus transitions explicitly with `toHaveFocus()`: entering the editor, reaching the toolbar/menu/item, and returning to the editor or leaving it. Assert visibility and, for document traversal, selection/block/table-cell changes through the selection command. Check the visual focus indicator as well; DOM focus alone does not prove that focus is visible. | -| `ARIA` | Follow the keyboard interaction and compare named ARIA snapshots before and after activation to check names, roles, pressed/expanded state, etc. Scope item tests to the item: adding another toolbar button must not invalidate Bold's snapshots. Use a separate whole-toolbar tree snapshot to cover membership and overall structure. If activation changes the item's accessible name, locate its resulting name explicitly. | -| `axe` | Open the relevant UI state and run the axe command. Scan a toolbar, menu, or popover independently where appropriate; use a whole-document scan for broad schema coverage. Attach the returned manual-review warnings to the test. Axe scans do not replace keyboard navigation or focus-indicator checks. | -| `visual` | Cover visual accessibility scenarios such as text-spacing overrides and 200% text resizing. Use `screenshotFull` for tall documents, wait for fonts/media, and mask nondeterministic video frames where needed. These checks concern layout/readability rather than individual button activation and should only ever be used for specific requirements defined in the WCAG 2.0-2.2 guidelines. | - -## Test setup and commands - -Define a local `TestEditor` component using `useCreateBlockNote` and `BlockNoteView`. Use `.tsx` and JSX when rendering React components. Add a `renderTestEditor` function when the suite needs repeated rendering or readiness steps. Keep document data, initial focus, and setup specific to the scenario; do not introduce a shared editor fixture for unrelated suites. - -Consume browser operations through the typed `commands` export in `tests/src/utils/context.ts`. The implementations live in `tests/src/utils/accessibility.ts` and `tests/src/utils/keyboard.ts`; their JSDoc describes inputs, results, synchronization, and usage. Register new reusable browser operations in the relevant Vite configuration and add their client signatures to `context.ts`. Do not import command implementations into tests, add per-caller type casts, or wrap a command just to forward its arguments. - -Keep scenario-specific sequences, such as navigating to a toolbar item, in the consuming test file. Share them only where another test actually needs the same sequence. Keep action sequences separate from behavior assertions; keyboard tests should explicitly assert the focus and selection transitions they cover. - -The default browser setup already disables motion and tracks ProseMirror focus reconciliation. Do not duplicate those mechanisms in fixtures. Wait for observable readiness with retrying assertions instead of arbitrary sleeps. For example, an opened menu can be visible before its initial item receives focus: assert that focus before sending navigation keys. - -Use accessible locators (`getByRole` with a name or `getByLabel`) and pass their selectors to commands. Prefer live locators for asynchronously mounted elements. When tabbing to an item, advance until the target has focus, bounded by the test timeout, rather than maintaining a duplicate list of controls or a fixed Tab count. - -## Native screen-reader edge cases - -Use a separate `*.screen-reader.test.ts` only for actual reader announcements/navigation that ARIA snapshots cannot establish. Reuse keyboard navigation helpers, render the suite’s editor and call `commands.startReader(locator.selector)`, and assert the transcript and stop the reader in `afterEach`. Avoid duplicating every browser scenario. Transcripts are reader-specific; review changes rather than accepting them blindly. - -These tests run locally with VoiceOver on macOS or NVDA on Windows and require the installed reader and GuidePup permissions. They must stay excluded from regular e2e, node tests, and CI. `tests/src/screen-reader/vite.config.screen-reader.ts` is for this native runner only. - -## Discovery and commands - -Browser files use `*.browser.test.ts` (or `.tsx`); native screen-reader tests use `*.screen-reader.test.ts`; node tests use `*.test.ts`. Existing glob patterns discover browser tests and exclude them from node runs without per-file configuration. Accessibility checks are part of the regular suite. Production files must not import test files; lint enforces this boundary. - -Run from the repository root: - -```bash -# Existing e2e suite, always Docker; narrow by file, group, and/or browser. -vp run e2e FormattingToolbar.browser.test.tsx -vp run e2e FormattingToolbar.browser.test.tsx -t keyboard --project "e2e (webkit)" --retry=0 - -# Update only the selected suite, then review and rerun without updating. -vp run e2e:updateSnaps FormattingToolbar.browser.test.tsx - -# Native/local only, never part of regular e2e or CI. -vp run test:screen-reader FormattingToolbar.screen-reader.test.ts -``` - -Evaluate known functionality gaps individually; any intentional skip needs a comment explaining the specific failure. Do not skip timing failures or increase retries to hide them: fix readiness/locator handling and verify repeated runs with retries disabled. Do not refresh snapshots to accept an unexplained regression. diff --git a/.claude/skills/testing-skill/references/component-testing.md b/.claude/skills/testing-skill/references/component-testing.md new file mode 100644 index 0000000000..2a901d7f6b --- /dev/null +++ b/.claude/skills/testing-skill/references/component-testing.md @@ -0,0 +1,62 @@ +# React component testing + +Use a browser when testing clicks, keyboard navigation, focus, or other rendering-dependent behavior. Keep logic that does not need rendering in faster Node tests. + +## Component structure + +Keep behavior and accessibility in one colocated `.browser.test.{ts,tsx}` file. Use an owner-named outer `describe`, then applicable groups in order: + +| Group | Assert | +| ------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `unit` | The owner's decisions: visibility, schema support, composition, callbacks. | +| `integration` | Subsystems working together: an actual control updates the editor correctly. | +| `keyboard` | Activation, traversal, dismissal, focus destination, visible focus. | +| `a11y` | Names, roles, relationships, pressed/expanded/checked state; axe scans in relevant states, including open menus/dialogs. | + +Cover relevant categories reasonably, not every possible combination. A child owns its interaction and focus indicator; a container owns composition, traversal, and exit. ARIA assertions and axe scans share `a11y`. + +## Setup + +Destructure typed helpers from the test context. Find the current listing in [`tests/src/commands/index.ts`](../../../../tests/src/commands/index.ts) and usage documentation beside each implementation. The browser setup supplies the extended global `it`. + +```tsx +const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , +}); +selectText(editor, "Selected text"); +``` + +Render the component directly with unrelated default UI disabled, rather than navigating a parent merely to reach it. Use the actual control for the action under test; editor APIs may establish the initial state. + +Shared rendering handles StrictMode, initial commit, fonts, and cleanup. Wait for later selection-driven UI explicitly. Skin selection defaults to Mantine and loads lazily; loaded CSS remains, so prefer one skin per file. + +Prefer accessible locators using dictionary labels. Direct focus is valid setup; use real Tab input when traversal is the contract. Wait for observable readiness: a menu can be visible before it receives focus. + +## Accessibility assertions + +- Assert focus with `toHaveFocus()` and check each owned control's indicator independently. +- Scope accessible-state assertions to the control/popup. Use built-in `toMatchAriaInlineSnapshot` / `toMatchAriaSnapshot` for standalone trees. +- For container traversal, an ordered sequence of focused controls' trees can detect skipped controls or changed order. Assert that focus can leave the container without prescribing an unrelated next destination. +- Scan closed triggers and open UI as applicable. Assert returned axe `violations`; for known issues, match their precise violation/check shapes with an issue link so additional violations fail. Do not mark a whole axe journey `it.fails`. +- ARIA trees, axe, keyboard checks, and visual checks complement each other; none proves actual reader speech. + +## Native screen readers + +Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. Register cleanup so the reader stops on failure; consult the command implementations for usage. + +This operates the real desktop using VoiceOver/NVDA and GuidePup permissions. Run only as intentional native verification, outside browser CI: + +```bash +vp run test:screen-reader FormattingToolbar.screen-reader.test.ts +``` + +Configuration: `tests/src/screen-reader/vite.config.screen-reader.ts`. + +## Mobile and visual checks + +- Mobile-emulated tests cover mobile-specific behavior, not duplicate desktop contracts. Do not use `screenshotFull` in Android-instance tests: its iframe resize drops touch emulation for subsequent tests. +- State the limit when emulation cannot reproduce the OS behavior. Real-device suite is parked on `mobile/emulator-layer` (PR #3034). +- Tall screenshots need `tests/src/utils/screenshotFull.ts`: ordinary iframe screenshots can silently clip below the fold; viewport resizing alone can scale the capture. +- Screenshot baselines are browser/Linux-specific. Update in Docker with `--update=true`. Changes within pixel tolerance may leave a stale baseline; remove the specific baseline first when a fresh capture is required. diff --git a/packages/core/src/blocks/Heading/__snapshots__/block.browser.test.tsx.snap b/packages/core/src/blocks/Heading/__snapshots__/block.browser.test.tsx.snap deleted file mode 100644 index 9a2a845526..0000000000 --- a/packages/core/src/blocks/Heading/__snapshots__/block.browser.test.tsx.snap +++ /dev/null @@ -1,20 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`ARIA > read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it > collapsed 1`] = ` -"- textbox: - - button "Expand or collapse" - - heading "Details" [level=2]" -`; - -exports[`ARIA > read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it > collapsed again 1`] = ` -"- textbox: - - button "Expand or collapse" - - heading "Details" [level=2]" -`; - -exports[`ARIA > read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it > expanded 1`] = ` -"- textbox: - - button "Expand or collapse" [expanded] - - heading "Details" [level=2] - - paragraph: Nested read-only content" -`; diff --git a/packages/core/src/blocks/Heading/block.browser.test.tsx b/packages/core/src/blocks/Heading/block.browser.test.tsx index 3745a0f448..aae47890d0 100644 --- a/packages/core/src/blocks/Heading/block.browser.test.tsx +++ b/packages/core/src/blocks/Heading/block.browser.test.tsx @@ -1,27 +1,7 @@ -import { commands } from "@root/tests/src/utils/context.js"; import { type PartialBlock } from "@blocknote/core"; import "@blocknote/core/fonts/inter.css"; -import { BlockNoteView } from "@blocknote/mantine"; -import "@blocknote/mantine/style.css"; -import { useCreateBlockNote } from "@blocknote/react"; -import { render } from "vitest-browser-react"; - -import { expect, test, vi, beforeEach, afterEach } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; - -// Start from "Before editor" after setup. Keep these navigation steps -// identical to focusToggleHeadingWithAssertions in the keyboard suite. -async function focusToggleHeading() { - const toggleButton = page.getByRole("button", { - name: "Expand or collapse", - exact: true, - }); - while (document.activeElement !== toggleButton.element()) { - await commands.pressKey("Tab"); - } - - return toggleButton; -} +import type { ReactNode } from "react"; +import { expect, describe, vi, beforeEach, afterEach } from "vite-plus/test"; const toggleHeadingDocument: PartialBlock[] = [ { @@ -33,26 +13,18 @@ const toggleHeadingDocument: PartialBlock[] = [ }, ]; -function TestEditor() { - const editor = useCreateBlockNote({ initialContent: toggleHeadingDocument }); +function outside({ children }: { children: ReactNode }) { return ( <> - + {children} ); } -beforeEach(async () => { +beforeEach(() => { localStorage.removeItem("toggle-read-only-toggle-heading"); - await render(); - await expect.element(page.getByRole("textbox")).toBeVisible(); - await document.fonts.ready; - page - .getByRole("button", { name: "Before editor", exact: true }) - .element() - .focus(); }); afterEach(() => { @@ -60,17 +32,35 @@ afterEach(() => { localStorage.removeItem("toggle-read-only-toggle-heading"); }); -test.describe("behavior", () => { - test("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async () => { +describe("behavior", () => { + it("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async ({ + setupEditor, + page, + focusUntil, + pressKey, + }) => { + await setupEditor({ + initialContent: toggleHeadingDocument, + props: { editable: false, theme: "light" }, + outside, + }); + page + .getByRole("button", { name: "Before editor", exact: true }) + .element() + .focus(); + const toggleButton = page.getByRole("button", { + name: "Expand or collapse", + exact: true, + }); const setItem = vi.spyOn(Storage.prototype, "setItem"); - await focusToggleHeading(); - await commands.pressKey("Enter"); + await focusUntil(toggleButton); + await pressKey("Enter"); expect(setItem).toHaveBeenCalledExactlyOnceWith( "toggle-read-only-toggle-heading", "true", ); setItem.mockClear(); - await commands.pressKey("Enter"); + await pressKey("Enter"); expect(setItem).toHaveBeenCalledExactlyOnceWith( "toggle-read-only-toggle-heading", "false", @@ -78,27 +68,10 @@ test.describe("behavior", () => { }); }); -test.describe("keyboard", () => { - // Same navigation as focusToggleHeading, with focus and visibility assertions. - async function focusToggleHeadingWithAssertions() { - const toggleButton = page.getByRole("button", { - name: "Expand or collapse", - exact: true, - }); - await expect.element(toggleButton).toBeVisible(); - const unfocusedOutline = await commands.readOutline(toggleButton.selector); - - while (document.activeElement !== toggleButton.element()) { - await commands.pressKey("Tab"); - } - await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); - - return { toggleButton, unfocusedOutline }; - } +describe("keyboard", () => { // Toggle headings represent interactive blocks in this accessibility vertical slice. // Keyboard access to toggle controls from within an editable block is not implemented. - test.skip("editable toggle heading: toggle is keyboard accessible while the editor has focus", async () => { + it.skip("editable toggle heading: toggle is keyboard accessible while the editor has focus", async () => { // TODO: The keyboard interaction for controls within an editable editor is TBD. // Reach the toggle while the editor has focus, expand/collapse its children, // and return to editing without changing the document content. @@ -109,40 +82,90 @@ test.describe("keyboard", () => { // this placeholder covers the eventual keyboard focus/navigation behavior. }); - test("read-only toggle heading: Tab navigation and visible focus after Enter", async () => { - const { toggleButton, unfocusedOutline } = - await focusToggleHeadingWithAssertions(); - await commands.pressKey("Enter"); + it("read-only toggle heading: Tab navigation and visible focus after Enter", async ({ + setupEditor, + page, + focusUntil, + pressKey, + readFocusOutline, + assertFocusOutline, + }) => { + await setupEditor({ + initialContent: toggleHeadingDocument, + props: { editable: false, theme: "light" }, + outside, + }); + page + .getByRole("button", { name: "Before editor", exact: true }) + .element() + .focus(); + const toggleButton = page.getByRole("button", { + name: "Expand or collapse", + exact: true, + }); + await expect.element(toggleButton).toBeVisible(); + const unfocusedOutline = readFocusOutline(toggleButton); + await focusUntil(toggleButton); await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); - await commands.pressKey("Enter"); + await assertFocusOutline(toggleButton, unfocusedOutline); + + await pressKey("Enter"); + await expect.element(toggleButton).toHaveFocus(); + await assertFocusOutline(toggleButton, unfocusedOutline); + await pressKey("Enter"); await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); + await assertFocusOutline(toggleButton, unfocusedOutline); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect .element(page.getByRole("button", { name: "After editor", exact: true })) .toHaveFocus(); - await commands.pressKey("Shift+Tab"); + await pressKey("Shift+Tab"); await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); + await assertFocusOutline(toggleButton, unfocusedOutline); }); }); -test.describe("ARIA", () => { - test("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async () => { - await focusToggleHeading(); - const editor = page.getByRole("textbox"); - expect(await commands.readAriaSnapshot(editor.selector)).toMatchSnapshot( - "collapsed", - ); - await commands.pressKey("Enter"); - expect(await commands.readAriaSnapshot(editor.selector)).toMatchSnapshot( - "expanded", - ); - await commands.pressKey("Enter"); - expect(await commands.readAriaSnapshot(editor.selector)).toMatchSnapshot( - "collapsed again", +describe("a11y", () => { + it("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async ({ + setupEditor, + page, + focusUntil, + pressKey, + }) => { + await setupEditor({ + initialContent: toggleHeadingDocument, + props: { editable: false, theme: "light" }, + outside, + }); + page + .getByRole("button", { name: "Before editor", exact: true }) + .element() + .focus(); + await focusUntil( + page.getByRole("button", { + name: "Expand or collapse", + exact: true, + }), ); + const editor = page.getByRole("textbox"); + await expect.element(editor).toMatchAriaInlineSnapshot(` + - textbox: + - button "Expand or collapse" + - heading "Details" [level=2] + `); + await pressKey("Enter"); + await expect.element(editor).toMatchAriaInlineSnapshot(` + - textbox: + - button "Expand or collapse" [expanded] + - heading "Details" [level=2] + - paragraph: Nested read-only content + `); + await pressKey("Enter"); + await expect.element(editor).toMatchAriaInlineSnapshot(` + - textbox: + - button "Expand or collapse" + - heading "Details" [level=2] + `); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx index 51910667e1..0c4b084596 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -12,11 +12,88 @@ import { FormattingToolbar } from "../FormattingToolbar.js"; const STYLES = ["bold", "italic", "underline", "strike", "code"] as const; describe("BasicTextStyleButton", () => { + describe("unit", () => { + it("hides in read-only mode and responds to editability changes", async ({ + setupEditor, + page, + }) => { + const { rerender } = await setupEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + + rerender({ editable: true }); + await expect.element(button).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + rerender({ editable: false }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides when the style is missing from the schema", async ({ + setupEditor, + page, + }) => { + await setupEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { italic: defaultStyleSpecs.italic }, + }), + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides when the style has a non-boolean prop schema", async ({ + setupEditor, + page, + }) => { + await setupEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { + bold: createStyleSpec( + { type: "bold", propSchema: "string" }, + { render: () => ({ dom: document.createElement("span") }) }, + ), + }, + }), + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + await expect.element(button).not.toBeInTheDocument(); + }); + + it("hides on blocks without inline content and reappears on text blocks", async ({ + setupEditor, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "divider", type: "divider" }, + { id: "text", type: "paragraph", content: "Text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + editor.setTextCursorPosition("divider"); + await expect.element(button).not.toBeInTheDocument(); + + editor.setTextCursorPosition("text"); + await expect.element(button).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + }); + }); + describe("integration", () => { it.for(STYLES)( "toggles %s on and off", - async (basicTextStyle, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ + async (basicTextStyle, { setupEditor, selectText, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "format", type: "paragraph", content: "Format this text" }, ], @@ -46,8 +123,8 @@ describe("BasicTextStyleButton", () => { it.for(STYLES)( "applies %s only to selected text without changing surrounding content", - async (basicTextStyle, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ + async (basicTextStyle, { setupEditor, selectText, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "format", @@ -90,8 +167,8 @@ describe("BasicTextStyleButton", () => { it.for(STYLES)( "applies %s to subsequently typed text at a collapsed cursor", - async (basicTextStyle, { renderEditor, page }) => { - const { editor } = await renderEditor({ + async (basicTextStyle, { setupEditor, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "format", type: "paragraph", content: "Existing" }, ], @@ -115,118 +192,21 @@ describe("BasicTextStyleButton", () => { ); }); - describe("unit", () => { - it("hides in read-only mode and responds to editability changes", async ({ - renderEditor, - page, - }) => { - const { rerender } = await renderEditor({ - props: { editable: false, formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - await expect.element(button).not.toBeInTheDocument(); - - rerender({ editable: true }); - await expect.element(button).toBeVisible(); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); - - rerender({ editable: false }); - await expect.element(button).not.toBeInTheDocument(); - }); - - it("hides when the style is missing from the schema", async ({ - renderEditor, - page, - }) => { - await renderEditor({ - schema: BlockNoteSchema.create({ - styleSpecs: { italic: defaultStyleSpecs.italic }, - }), - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - await expect.element(button).not.toBeInTheDocument(); - }); - - it("hides when the style has a non-boolean prop schema", async ({ - renderEditor, - page, - }) => { - await renderEditor({ - schema: BlockNoteSchema.create({ - styleSpecs: { - bold: createStyleSpec( - { type: "bold", propSchema: "string" }, - { render: () => ({ dom: document.createElement("span") }) }, - ), - }, - }), - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - await expect.element(button).not.toBeInTheDocument(); - }); - - it("hides on blocks without inline content and reappears on text blocks", async ({ - renderEditor, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "divider", type: "divider" }, - { id: "text", type: "paragraph", content: "Text" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - editor.setTextCursorPosition("divider"); - await expect.element(button).not.toBeInTheDocument(); - - editor.setTextCursorPosition("text"); - await expect.element(button).toBeVisible(); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); - }); - }); - - describe("ARIA", () => { - it("reflects the active style when selection moves between blocks", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { - id: "styled", - type: "paragraph", - content: [{ type: "text", text: "Bold", styles: { bold: true } }], - }, - { id: "plain", type: "paragraph", content: "Plain" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - selectText(editor, "Bold"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - - selectText(editor, "Plain"); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); - - selectText(editor, "Bold"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - }); - }); - describe("keyboard", () => { it.for(STYLES)( "shows a keyboard focus ring for %s", - async (style, { renderEditor, selectText, commands, page }) => { - const { editor } = await renderEditor({ + async ( + style, + { + setupEditor, + selectText, + readFocusOutline, + pressKey, + assertFocusOutline, + page, + }, + ) => { + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -237,19 +217,19 @@ describe("BasicTextStyleButton", () => { name: editor.dictionary.formatting_toolbar[style].tooltip, exact: true, }); - const outline = await commands.readOutline(button.selector); + const outline = readFocusOutline(button); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.checkFocusOutline(button.selector, outline); + await assertFocusOutline(button, outline); }, ); it.for(["Enter", "Space"])( "activates with %s and returns focus to the editor", - async (key, { renderEditor, selectText, commands, page }) => { - const { editor } = await renderEditor({ + async (key, { setupEditor, selectText, pressKey, page }) => { + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -261,11 +241,11 @@ describe("BasicTextStyleButton", () => { exact: true, }); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.pressKey(key); + await pressKey(key); await expect.element(button).toHaveAttribute("aria-pressed", "true"); await expect.element(page.getByRole("textbox")).toHaveFocus(); @@ -273,13 +253,41 @@ describe("BasicTextStyleButton", () => { ); }); - describe("axe", () => { + describe("a11y", () => { + it("reflects the active style when selection moves between blocks", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + id: "styled", + type: "paragraph", + content: [{ type: "text", text: "Bold", styles: { bold: true } }], + }, + { id: "plain", type: "paragraph", content: "Plain" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + + selectText(editor, "Plain"); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); + it("checks all supported style buttons", async ({ - renderEditor, - commands, - annotate, + setupEditor, + runAxe, + page, }) => { - await renderEditor({ + await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -290,9 +298,8 @@ describe("BasicTextStyleButton", () => { ), }); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx index d060e68779..30c0181fde 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -6,11 +6,11 @@ import { FormattingToolbar } from "../FormattingToolbar.js"; describe("ColorStyleButton", () => { describe("unit", () => { it("only offers text colors when the schema does not support background colors", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ schema: BlockNoteSchema.create({ styleSpecs: { textColor: defaultStyleSpecs.textColor }, }), @@ -45,11 +45,11 @@ describe("ColorStyleButton", () => { }); it("only offers background colors when text colors are not in the schema", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ schema: BlockNoteSchema.create({ styleSpecs: { backgroundColor: defaultStyleSpecs.backgroundColor }, }), @@ -84,10 +84,10 @@ describe("ColorStyleButton", () => { }); it("hides when neither color style is supported", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ schema: BlockNoteSchema.create({ styleSpecs: { bold: defaultStyleSpecs.bold }, }), @@ -106,10 +106,10 @@ describe("ColorStyleButton", () => { }); it("responds to editability and hides on blocks without inline content", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor, rerender } = await renderEditor({ + const { editor, rerender } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Text" }, { id: "divider", type: "divider" }, @@ -137,8 +137,8 @@ describe("ColorStyleButton", () => { describe("integration", () => { it.for(["textColor", "backgroundColor"] as const)( "applies %s only to the selected substring", - async (style, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ + async (style, { setupEditor, selectText, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Before selected after" }, ], @@ -172,8 +172,8 @@ describe("ColorStyleButton", () => { it.for(["textColor", "backgroundColor"] as const)( "resets %s without removing the other color", - async (style, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ + async (style, { setupEditor, selectText, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "text", @@ -221,12 +221,14 @@ describe("ColorStyleButton", () => { describe("keyboard", () => { it("shows a keyboard focus ring on its trigger", async ({ - renderEditor, + setupEditor, selectText, - commands, + readFocusOutline, + pressKey, + assertFocusOutline, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -237,21 +239,21 @@ describe("ColorStyleButton", () => { name: editor.dictionary.formatting_toolbar.colors.tooltip, exact: true, }); - const outline = await commands.readOutline(button.selector); + const outline = readFocusOutline(button); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.checkFocusOutline(button.selector, outline); + await assertFocusOutline(button, outline); }); it("chooses a color with the keyboard and returns focus to the editor", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], @@ -265,14 +267,14 @@ describe("ColorStyleButton", () => { }); button.element().focus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); const menu = page.getByRole("menu"); await expect.element(menu).toBeVisible(); await expect .poll(() => menu.element().contains(document.activeElement)) .toBe(true); - await commands.pressKey("ArrowDown"); - await commands.pressKey("ArrowDown"); + await pressKey("ArrowDown"); + await pressKey("ArrowDown"); await expect .element( @@ -284,19 +286,21 @@ describe("ColorStyleButton", () => { ) .toHaveFocus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); await expect.element(menu).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); expect(editor.getActiveStyles().textColor).toBe("gray"); }); it("supports opening, navigating, and dismissing its menu without editing the document", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, + readFocusOutline, + assertFocusOutline, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -312,7 +316,7 @@ describe("ColorStyleButton", () => { await expect.element(button).toHaveFocus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); const menu = page.getByRole("menu"); await expect.element(menu).toBeVisible(); @@ -320,14 +324,14 @@ describe("ColorStyleButton", () => { .poll(() => menu.element().contains(document.activeElement)) .toBe(true); const firstItem = menu.getByRole("menuitem").first(); - const outline = await commands.readOutline(firstItem.selector); + const outline = readFocusOutline(firstItem); - await commands.pressKey("ArrowDown"); + await pressKey("ArrowDown"); await expect.element(firstItem).toHaveFocus(); - await commands.checkFocusOutline(firstItem.selector, outline); + await assertFocusOutline(firstItem, outline); - await commands.pressKey("Escape"); + await pressKey("Escape"); await expect.element(menu).not.toBeInTheDocument(); await expect.element(button).toHaveFocus(); @@ -335,13 +339,13 @@ describe("ColorStyleButton", () => { }); }); - describe("ARIA", () => { + describe("a11y", () => { it("exposes the menu trigger's expanded state and relationship", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -367,12 +371,12 @@ describe("ColorStyleButton", () => { // it renders `checked` as a visual checkmark without exposing the checked // state to assistive technology. it.fails("exposes a color change in the trigger or menu's accessibility tree", async ({ - renderEditor, + setupEditor, selectText, - commands, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -385,10 +389,9 @@ describe("ColorStyleButton", () => { await button.click(); const menu = page.getByRole("menu"); await expect.element(menu).toBeVisible(); - const before = [ - await commands.readAriaSnapshot(button.selector), - await commands.readAriaSnapshot(menu.selector), - ].join("\n"); + const before = [readAriaSnapshot(button), readAriaSnapshot(menu)].join( + "\n", + ); await menu .getByRole("menuitem", { @@ -400,21 +403,14 @@ describe("ColorStyleButton", () => { await button.click(); await expect.element(menu).toBeVisible(); - const after = [ - await commands.readAriaSnapshot(button.selector), - await commands.readAriaSnapshot(menu.selector), - ].join("\n"); + const after = [readAriaSnapshot(button), readAriaSnapshot(menu)].join( + "\n", + ); expect(after).not.toBe(before); }); - }); - describe("axe", () => { - it("checks the color trigger", async ({ - renderEditor, - commands, - annotate, - }) => { - await renderEditor({ + it("checks the color trigger", async ({ setupEditor, runAxe, page }) => { + await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -423,20 +419,15 @@ describe("ColorStyleButton", () => { ), }); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); - // Mantine's focusable menu placeholder violates aria-required-children, - // as it does in BlockTypeSelect. Keep the open state covered explicitly. - it.fails("checks the open color menu", async ({ - renderEditor, - commands, - page, - annotate, - }) => { - const { editor } = await renderEditor({ + // Mantine's placeholder violates aria-required-children. Axe can also report + // scrollable-region-focusable depending on the menu's scrolling/focus state. + // Allow only that exact additional known issue, not arbitrary scan failures. + it("checks the open color menu", async ({ setupEditor, runAxe, page }) => { + const { editor } = await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -452,8 +443,44 @@ describe("ColorStyleButton", () => { .click(); await expect.element(page.getByRole("menu")).toBeVisible(); - for (const warning of await commands.checkAxe('[role="menu"]')) { - await annotate(warning, "warning"); + const { violations } = await runAxe(page.getByRole("menu")); + const scrollViolations = violations.filter( + ({ id }) => id === "scrollable-region-focusable", + ); + expect( + violations.filter(({ id }) => id !== "scrollable-region-focusable"), + ).toMatchObject([ + { + id: "aria-required-children", + nodes: [ + { + any: [ + { + id: "aria-required-children", + data: { messageKey: "unallowed", values: "div[tabindex]" }, + }, + ], + all: [], + none: [], + }, + ], + }, + ]); + expect(scrollViolations.length).toBeLessThanOrEqual(1); + for (const violation of scrollViolations) { + expect(violation).toMatchObject({ + id: "scrollable-region-focusable", + nodes: [ + { + any: [ + { id: "focusable-content", data: null }, + { id: "focusable-element", data: null }, + ], + all: [], + none: [], + }, + ], + }); } }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx index f3e56d93d2..d787b3bdd5 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -5,11 +5,11 @@ import { FormattingToolbar } from "../FormattingToolbar.js"; describe("CreateLinkButton", () => { describe("unit", () => { it("requires selected text and responds to editability changes", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor, rerender } = await renderEditor({ + const { editor, rerender } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], @@ -36,11 +36,11 @@ describe("CreateLinkButton", () => { }); it("prefills the selected link and closes the form when selection changes", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", @@ -78,12 +78,12 @@ describe("CreateLinkButton", () => { describe("integration", () => { it("submits a link for the original substring and returns focus to the editor", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", @@ -106,7 +106,7 @@ describe("CreateLinkButton", () => { ); await input.fill("https://example.com"); - await commands.pressKey("Enter"); + await pressKey("Enter"); expect(editor.getBlock("text")?.content).toEqual([ { type: "text", text: "Before ", styles: {} }, @@ -122,11 +122,11 @@ describe("CreateLinkButton", () => { }); it("opens the link form without changing the selected text range or document", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", @@ -164,12 +164,14 @@ describe("CreateLinkButton", () => { describe("keyboard", () => { it("shows a keyboard focus ring on its trigger", async ({ - renderEditor, + setupEditor, selectText, - commands, + readFocusOutline, + pressKey, + assertFocusOutline, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -180,23 +182,25 @@ describe("CreateLinkButton", () => { name: editor.dictionary.formatting_toolbar.link.tooltip, exact: true, }); - const outline = await commands.readOutline(button.selector); + await expect.element(button).toBeVisible(); + const outline = readFocusOutline(button); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.checkFocusOutline(button.selector, outline); + await assertFocusOutline(button, outline); }); // Our Mantine form-popover CSS removes the input border, and there is no // replacement keyboard focus outline (blocknoteStyles.css). it.fails("shows a visible keyboard focus indicator on the URL field", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, + assertFocusOutline, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -209,22 +213,22 @@ describe("CreateLinkButton", () => { await expect.element(button).toBeVisible(); button.element().focus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); const input = page.getByPlaceholder( editor.dictionary.link_toolbar.form.url_placeholder, ); await expect.element(input).toHaveFocus(); - await commands.checkFocusOutline(input.selector); + await assertFocusOutline(input); }); it("opens with Enter and returns focus to its trigger on Escape without editing", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -239,14 +243,14 @@ describe("CreateLinkButton", () => { await expect.element(button).toBeVisible(); button.element().focus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); const input = page.getByPlaceholder( editor.dictionary.link_toolbar.form.url_placeholder, ); await expect.element(input).toHaveFocus(); - await commands.pressKey("Escape"); + await pressKey("Escape"); await expect.element(input).not.toBeInTheDocument(); await expect.element(button).toHaveFocus(); @@ -257,12 +261,12 @@ describe("CreateLinkButton", () => { }); it("opens with the editor's link shortcut but not in read-only mode", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, page, }) => { - const { editor, rerender } = await renderEditor({ + const { editor, rerender } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -270,13 +274,13 @@ describe("CreateLinkButton", () => { await page.getByRole("textbox").click(); selectText(editor, "Selected text"); - await commands.pressKey("Control+k"); + await pressKey("Control+k"); const input = page.getByPlaceholder( editor.dictionary.link_toolbar.form.url_placeholder, ); await expect.element(input).toHaveFocus(); - await commands.pressKey("Escape"); + await pressKey("Escape"); rerender({ editable: false }); // Read-only content is not a textbox, but still receives DOM key events. @@ -293,13 +297,13 @@ describe("CreateLinkButton", () => { }); }); - describe("ARIA", () => { + describe("a11y", () => { it("exposes the popup's relationship to its named trigger and its URL field", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -331,16 +335,14 @@ describe("CreateLinkButton", () => { ) .toHaveFocus(); }); - }); - describe("axe", () => { it("checks the closed trigger", async ({ - renderEditor, + setupEditor, selectText, - commands, - annotate, + runAxe, + page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: ( @@ -351,18 +353,24 @@ describe("CreateLinkButton", () => { }); selectText(editor, "Selected text"); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }), + ) + .toBeVisible(); + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); it("opens a link form with no automated accessibility violations", async ({ - renderEditor, + setupEditor, selectText, - annotate, - commands, + runAxe, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -383,9 +391,8 @@ describe("CreateLinkButton", () => { ), ) .toBeVisible(); - for (const warning of await commands.checkAxe(".bn-form-popover")) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("dialog")); + expect(violations).toEqual([]); }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx index c26c20a875..86650b80ee 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -9,8 +9,8 @@ describe("NestBlockButtons", () => { { name: "unnest", Button: UnnestBlockButton }, ])( "hides $name in read-only mode and on blocks without inline content", - async ({ Button }, { renderEditor, page }) => { - const { editor, rerender } = await renderEditor({ + async ({ Button }, { setupEditor, page }) => { + const { editor, rerender } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Text" }, { id: "divider", type: "divider" }, @@ -33,69 +33,13 @@ describe("NestBlockButtons", () => { ); }); - describe("ARIA", () => { - it("only enables nesting when a previous sibling is available", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { type: "paragraph", content: "First block" }, - { type: "paragraph", content: "Second block" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.nest.tooltip, - exact: true, - }); - selectText(editor, "First block"); - - await expect.element(button).toBeDisabled(); - - selectText(editor, "Second block"); - - await expect.element(button).toBeEnabled(); - }); - - it("only enables unnesting for a nested block", async ({ - renderEditor, - selectText, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { - type: "paragraph", - content: "Parent", - children: [{ type: "paragraph", content: "Child" }], - }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.unnest.tooltip, - exact: true, - }); - selectText(editor, "Parent"); - await expect.element(button).toBeDisabled(); - - selectText(editor, "Child"); - - await expect.element(button).toBeEnabled(); - }); - }); - describe("integration", () => { it("moves the selected block under its previous sibling without changing their contents", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "parent", type: "paragraph", content: "Parent" }, { id: "selected", type: "paragraph", content: "Selected text" }, @@ -121,11 +65,11 @@ describe("NestBlockButtons", () => { }); it("moves the selected block out of its parent without changing their contents", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "parent", @@ -166,9 +110,16 @@ describe("NestBlockButtons", () => { "activates $direction and returns focus to the editor", async ( { direction, Button }, - { renderEditor, selectText, commands, page }, + { + setupEditor, + selectText, + readFocusOutline, + pressKey, + assertFocusOutline, + page, + }, ) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: direction === "nest" ? [ @@ -202,14 +153,14 @@ describe("NestBlockButtons", () => { name: editor.dictionary.formatting_toolbar[direction].tooltip, exact: true, }); - const outline = await commands.readOutline(button.selector); + const outline = readFocusOutline(button); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.checkFocusOutline(button.selector, outline); + await assertFocusOutline(button, outline); - await commands.pressKey("Enter"); + await pressKey("Enter"); await expect.element(page.getByRole("textbox")).toHaveFocus(); expect( @@ -220,11 +171,11 @@ describe("NestBlockButtons", () => { ); it("skips disabled actions when tabbing", async ({ - renderEditor, - commands, + setupEditor, + pressKey, page, }) => { - await renderEditor({ + await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -236,7 +187,7 @@ describe("NestBlockButtons", () => { }); await page.getByRole("textbox").click(); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect .element(page.getByRole("button", { name: "Next action", exact: true })) @@ -244,14 +195,68 @@ describe("NestBlockButtons", () => { }); }); - describe("axe", () => { + describe("a11y", () => { + it("only enables nesting when a previous sibling is available", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { type: "paragraph", content: "First block" }, + { type: "paragraph", content: "Second block" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.nest.tooltip, + exact: true, + }); + selectText(editor, "First block"); + + await expect.element(button).toBeDisabled(); + + selectText(editor, "Second block"); + + await expect.element(button).toBeEnabled(); + }); + + it("only enables unnesting for a nested block", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.unnest.tooltip, + exact: true, + }); + selectText(editor, "Parent"); + await expect.element(button).toBeDisabled(); + + selectText(editor, "Child"); + + await expect.element(button).toBeEnabled(); + }); + it("checks enabled and disabled nesting controls", async ({ - renderEditor, + setupEditor, selectText, - commands, - annotate, + runAxe, + page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -269,9 +274,8 @@ describe("NestBlockButtons", () => { }); selectText(editor, "Child"); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx index 383dc6e872..82c44f104b 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -6,10 +6,10 @@ import { CellSelection } from "@tiptap/pm/tables"; describe("TextAlignButton", () => { describe("unit", () => { it("hides for read-only content and blocks without alignment, and reappears for text", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor, rerender } = await renderEditor({ + const { editor, rerender } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Text" }, { id: "divider", type: "divider" }, @@ -37,8 +37,8 @@ describe("TextAlignButton", () => { describe("integration", () => { it.for(["left", "center", "right", "justify"] as const)( "aligns the selected block %s without changing its text or neighboring blocks", - async (textAlignment, { renderEditor, selectText, page }) => { - const { editor } = await renderEditor({ + async (textAlignment, { setupEditor, selectText, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "before", type: "paragraph", content: "Before" }, { @@ -78,10 +78,10 @@ describe("TextAlignButton", () => { ); it("aligns every selected block without changing an unselected neighbor", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "first", type: "paragraph", content: "First" }, { id: "second", type: "paragraph", content: "Second" }, @@ -114,10 +114,10 @@ describe("TextAlignButton", () => { }); it("aligns only the selected table cells", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "table", @@ -183,8 +183,18 @@ describe("TextAlignButton", () => { describe("keyboard", () => { it.for(["left", "center", "right", "justify"] as const)( "shows a keyboard focus ring for %s alignment", - async (alignment, { renderEditor, selectText, commands, page }) => { - const { editor } = await renderEditor({ + async ( + alignment, + { + setupEditor, + selectText, + readFocusOutline, + pressKey, + assertFocusOutline, + page, + }, + ) => { + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -196,19 +206,19 @@ describe("TextAlignButton", () => { .tooltip, exact: true, }); - const outline = await commands.readOutline(button.selector); + const outline = readFocusOutline(button); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.checkFocusOutline(button.selector, outline); + await assertFocusOutline(button, outline); }, ); it.for(["Enter", "Space"])( "aligns with %s and restores editor focus", - async (key, { renderEditor, selectText, commands, page }) => { - const { editor } = await renderEditor({ + async (key, { setupEditor, selectText, pressKey, page }) => { + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], @@ -222,11 +232,11 @@ describe("TextAlignButton", () => { exact: true, }); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.pressKey(key); + await pressKey(key); await expect.element(button).toHaveAttribute("aria-pressed", "true"); await expect.element(page.getByRole("textbox")).toHaveFocus(); @@ -234,13 +244,13 @@ describe("TextAlignButton", () => { ); }); - describe("ARIA", () => { + describe("a11y", () => { it("updates its pressed state when selection moves between differently aligned blocks", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", content: "Left" }, { @@ -263,15 +273,13 @@ describe("TextAlignButton", () => { await expect.element(button).toHaveAttribute("aria-pressed", "false"); }); - }); - describe("axe", () => { it("checks all alignment controls, including the selected one", async ({ - renderEditor, - commands, - annotate, + setupEditor, + runAxe, + page, }) => { - await renderEditor({ + await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -284,9 +292,8 @@ describe("TextAlignButton", () => { ), }); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx index 091ced4691..9d69049cca 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -5,10 +5,10 @@ import { BlockTypeSelect } from "./BlockTypeSelect.js"; describe("BlockTypeSelect", () => { describe("unit", () => { it("hides when the current block has no offered type and reappears on a supported block", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Text" }, { id: "divider", type: "divider" }, @@ -29,8 +29,8 @@ describe("BlockTypeSelect", () => { await expect.element(button).toBeVisible(); }); - it("hides in read-only mode", async ({ renderEditor, page }) => { - await renderEditor({ + it("hides in read-only mode", async ({ setupEditor, page }) => { + await setupEditor({ props: { editable: false, formattingToolbar: false }, children: , }); @@ -41,10 +41,10 @@ describe("BlockTypeSelect", () => { // BlockTypeSelect subscribes to selected blocks, not editability. A change // to editable alone does not update the control until selection changes. it.fails("reappears when the editor becomes editable without moving selection", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor, rerender } = await renderEditor({ + const { editor, rerender } = await setupEditor({ props: { editable: false, formattingToolbar: false }, children: , }); @@ -60,10 +60,10 @@ describe("BlockTypeSelect", () => { expect(button.query()).not.toBeNull(); }); it("filters custom choices whose block type or property types do not match the schema", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ props: { formattingToolbar: false }, children: ({ editor }) => ( { describe("integration", () => { it("converts the selected block and updates its label without changing neighboring blocks or text", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "before", type: "paragraph", content: "Before" }, { id: "selected", type: "paragraph", content: "Selected text" }, @@ -156,10 +156,10 @@ describe("BlockTypeSelect", () => { }); it("converts all selected blocks while leaving an unselected neighbor intact", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "first", type: "paragraph", content: "First" }, { id: "second", type: "paragraph", content: "Second" }, @@ -197,12 +197,14 @@ describe("BlockTypeSelect", () => { describe("keyboard", () => { it("shows a keyboard focus ring on its trigger", async ({ - renderEditor, + setupEditor, selectText, - commands, + readFocusOutline, + pressKey, + assertFocusOutline, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -213,21 +215,21 @@ describe("BlockTypeSelect", () => { name: editor.dictionary.slash_menu.paragraph.title, exact: true, }); - const outline = await commands.readOutline(button.selector); + const outline = readFocusOutline(button); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await commands.checkFocusOutline(button.selector, outline); + await assertFocusOutline(button, outline); }); it("dismisses with Escape and restores trigger focus without editing", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -240,14 +242,14 @@ describe("BlockTypeSelect", () => { const before = editor.document; const selection = editor.prosemirrorState.selection.toJSON(); button.element().focus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); const menu = page.getByRole("menu"); await expect.element(menu).toBeVisible(); await expect .poll(() => menu.element().contains(document.activeElement)) .toBe(true); - await commands.pressKey("Escape"); + await pressKey("Escape"); await expect.element(menu).not.toBeInTheDocument(); await expect.element(button).toHaveFocus(); @@ -255,12 +257,14 @@ describe("BlockTypeSelect", () => { expect(editor.prosemirrorState.selection.toJSON()).toEqual(selection); }); it("opens, navigates, and chooses a block type from the keyboard", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, + readFocusOutline, + assertFocusOutline, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], @@ -275,7 +279,7 @@ describe("BlockTypeSelect", () => { button.element().focus(); await expect.element(button).toHaveFocus(); - await commands.pressKey("Enter"); + await pressKey("Enter"); const menu = page.getByRole("menu"); await expect.element(menu).toBeVisible(); @@ -290,18 +294,18 @@ describe("BlockTypeSelect", () => { name: editor.dictionary.slash_menu.heading.title, exact: true, }); - const outline = await commands.readOutline(heading.selector); + const outline = readFocusOutline(heading); - await commands.pressKey("ArrowDown"); + await pressKey("ArrowDown"); await expect.element(paragraph).toHaveFocus(); - await commands.pressKey("ArrowDown"); + await pressKey("ArrowDown"); await expect.element(heading).toHaveFocus(); - await commands.checkFocusOutline(heading.selector, outline); + await assertFocusOutline(heading, outline); - await commands.pressKey("Enter"); + await pressKey("Enter"); await expect.element(menu).not.toBeInTheDocument(); await expect @@ -316,13 +320,13 @@ describe("BlockTypeSelect", () => { }); }); - describe("ARIA", () => { + describe("a11y", () => { it("names the current block type and exposes the popup relationship", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", content: "Paragraph text" }, { type: "heading", props: { level: 2 }, content: "Heading text" }, @@ -361,10 +365,10 @@ describe("BlockTypeSelect", () => { // Our Mantine ToolbarSelect renders the selected option as a checkmark // only; it does not expose its checked state to assistive technology. it.fails("exposes the current menu choice as checked", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ props: { formattingToolbar: false }, children: , }); @@ -375,17 +379,14 @@ describe("BlockTypeSelect", () => { await expect.element(item).toBeVisible(); expect(item.element().getAttribute("aria-checked")).toBe("true"); }); - }); - describe("axe", () => { it("checks the trigger", async ({ - renderEditor, + setupEditor, selectText, - commands, + runAxe, page, - annotate, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: ( @@ -401,21 +402,19 @@ describe("BlockTypeSelect", () => { }); await expect.element(button).toBeVisible(); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); - // Expected failure: Mantine inserts a focusable placeholder div inside the - // menu, violating aria-required-children. - it.fails("checks the open menu", async ({ - renderEditor, + // Mantine inserts a focusable placeholder div inside the menu. Assert this + // known violation precisely so additional accessibility failures still fail. + it("checks the open menu", async ({ + setupEditor, selectText, - commands, + runAxe, page, - annotate, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: ( @@ -434,9 +433,24 @@ describe("BlockTypeSelect", () => { .click(); await expect.element(page.getByRole("menu")).toBeVisible(); - for (const warning of await commands.checkAxe('[role="menu"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("menu")); + expect(violations).toMatchObject([ + { + id: "aria-required-children", + nodes: [ + { + any: [ + { + id: "aria-required-children", + data: { messageKey: "unallowed", values: "div[tabindex]" }, + }, + ], + all: [], + none: [], + }, + ], + }, + ]); }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx index cdb5a21c89..fb08a75f34 100644 --- a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx @@ -5,11 +5,11 @@ import { DesktopFormattingToolbarController } from "./DesktopFormattingToolbarCo describe("DesktopFormattingToolbarController", () => { describe("unit", () => { it("mounts its custom toolbar while the extension requests it and unmounts it on dismissal", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], @@ -43,7 +43,7 @@ describe("DesktopFormattingToolbarController", () => { await expect.element(toolbar).not.toBeInTheDocument(); }); it("renders its toolbar into the supplied portal", async ({ - renderEditor, + setupEditor, selectText, page, onTestFinished, @@ -51,7 +51,7 @@ describe("DesktopFormattingToolbarController", () => { const portal = document.createElement("div"); document.body.append(portal); onTestFinished(() => portal.remove()); - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], @@ -75,56 +75,13 @@ describe("DesktopFormattingToolbarController", () => { }); }); - describe("keyboard", () => { - it("dismisses with Escape and restores editor focus without changing its selection or document", async ({ - renderEditor, - selectText, - commands, - page, - }) => { - const { editor } = await renderEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Selected text" }, - ], - props: { formattingToolbar: false }, - children: ( - ( -
- -
- )} - /> - ), - }); - selectText(editor, "Selected text"); - await page - .getByRole("button", { name: "Custom action", exact: true }) - .click(); - const documentBefore = editor.document; - const selectionBefore = editor.prosemirrorState.selection.toJSON(); - - await commands.pressKey("Escape"); - - expect(editor.getExtension(FormattingToolbarExtension)!.store.state).toBe( - false, - ); - await expect.element(page.getByRole("toolbar")).not.toBeInTheDocument(); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - expect(editor.prosemirrorState.selection.toJSON()).toEqual( - selectionBefore, - ); - expect(editor.document).toEqual(documentBefore); - }); - }); - describe("integration", () => { it("does not steal editor focus when the default toolbar appears", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -142,11 +99,11 @@ describe("DesktopFormattingToolbarController", () => { }); it("dismisses on an outside click without stealing focus from the outside action", async ({ - renderEditor, + setupEditor, selectText, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], props: { formattingToolbar: false }, children: , @@ -175,4 +132,47 @@ describe("DesktopFormattingToolbarController", () => { expect(editor.document).toEqual(before); }); }); + + describe("keyboard", () => { + it("dismisses with Escape and restores editor focus without changing its selection or document", async ({ + setupEditor, + selectText, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: ( + ( +
+ +
+ )} + /> + ), + }); + selectText(editor, "Selected text"); + await page + .getByRole("button", { name: "Custom action", exact: true }) + .click(); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); + + await pressKey("Escape"); + + expect(editor.getExtension(FormattingToolbarExtension)!.store.state).toBe( + false, + ); + await expect.element(page.getByRole("toolbar")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, + ); + expect(editor.document).toEqual(documentBefore); + }); + }); }); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx index 4f9868fada..cfd923e13d 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx @@ -4,10 +4,10 @@ import { FormattingToolbar } from "./FormattingToolbar.js"; describe("FormattingToolbar", () => { describe("unit", () => { it("allows custom children instead of default controls", async ({ - renderEditor, + setupEditor, page, }) => { - await renderEditor({ + await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -26,10 +26,10 @@ describe("FormattingToolbar", () => { }); it("passes custom block-type choices to its select", async ({ - renderEditor, + setupEditor, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ props: { formattingToolbar: false }, children: ({ editor }) => ( { describe("integration", () => { it("preserves the editor selection while keyboard focus moves through the toolbar", async ({ - renderEditor, + setupEditor, selectText, - commands, + pressKey, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", content: "Before selected text after" }, ], @@ -83,7 +83,7 @@ describe("FormattingToolbar", () => { const documentBefore = editor.document; const selectionBefore = editor.prosemirrorState.selection.toJSON(); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect .element( @@ -97,7 +97,7 @@ describe("FormattingToolbar", () => { selectionBefore, ); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect .element( @@ -116,12 +116,13 @@ describe("FormattingToolbar", () => { describe("keyboard", () => { it("tabs forward through the default controls for Parent and allows leaving", async ({ - renderEditor, + setupEditor, selectText, - commands, + focusUntil, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -137,14 +138,16 @@ describe("FormattingToolbar", () => { selectText(editor, "Parent"); const toolbar = page.getByRole("toolbar"); await expect.element(toolbar).toBeVisible(); + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. const sequence: string[] = []; - await commands.focusUntil(async (active) => { + await focusUntil(async (active) => { if (!toolbar.element().contains(active.element())) { return true; } await expect.element(active).toBeEnabled(); - sequence.push(await commands.readAriaSnapshot(active.selector)); + sequence.push(readAriaSnapshot(active)); return false; }); @@ -176,12 +179,13 @@ describe("FormattingToolbar", () => { }); it("tabs forward through the default controls for Child and allows leaving", async ({ - renderEditor, + setupEditor, selectText, - commands, + focusUntil, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -197,14 +201,16 @@ describe("FormattingToolbar", () => { selectText(editor, "Child"); const toolbar = page.getByRole("toolbar"); await expect.element(toolbar).toBeVisible(); + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. const sequence: string[] = []; - await commands.focusUntil(async (active) => { + await focusUntil(async (active) => { if (!toolbar.element().contains(active.element())) { return true; } await expect.element(active).toBeEnabled(); - sequence.push(await commands.readAriaSnapshot(active.selector)); + sequence.push(readAriaSnapshot(active)); return false; }); @@ -238,12 +244,13 @@ describe("FormattingToolbar", () => { }); it("tabs forward through the default controls for Sibling and allows leaving", async ({ - renderEditor, + setupEditor, selectText, - commands, + focusUntil, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -259,14 +266,16 @@ describe("FormattingToolbar", () => { selectText(editor, "Sibling"); const toolbar = page.getByRole("toolbar"); await expect.element(toolbar).toBeVisible(); + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. const sequence: string[] = []; - await commands.focusUntil(async (active) => { + await focusUntil(async (active) => { if (!toolbar.element().contains(active.element())) { return true; } await expect.element(active).toBeEnabled(); - sequence.push(await commands.readAriaSnapshot(active.selector)); + sequence.push(readAriaSnapshot(active)); return false; }); @@ -300,12 +309,13 @@ describe("FormattingToolbar", () => { }); it("tabs backward through the default controls for Parent and allows leaving", async ({ - renderEditor, + setupEditor, selectText, - commands, + focusUntil, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -325,14 +335,16 @@ describe("FormattingToolbar", () => { }); await expect.element(lastControl).toBeVisible(); lastControl.element().focus(); - const sequence = [await commands.readAriaSnapshot(lastControl.selector)]; + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. + const sequence = [readAriaSnapshot(lastControl)]; - await commands.focusUntil(async (active) => { + await focusUntil(async (active) => { if (!toolbar.element().contains(active.element())) { return true; } await expect.element(active).toBeEnabled(); - sequence.push(await commands.readAriaSnapshot(active.selector)); + sequence.push(readAriaSnapshot(active)); return false; }, "backward"); @@ -364,12 +376,13 @@ describe("FormattingToolbar", () => { }); it("tabs backward through the default controls for Child and allows leaving", async ({ - renderEditor, + setupEditor, selectText, - commands, + focusUntil, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -389,14 +402,16 @@ describe("FormattingToolbar", () => { }); await expect.element(lastControl).toBeVisible(); lastControl.element().focus(); - const sequence = [await commands.readAriaSnapshot(lastControl.selector)]; + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. + const sequence = [readAriaSnapshot(lastControl)]; - await commands.focusUntil(async (active) => { + await focusUntil(async (active) => { if (!toolbar.element().contains(active.element())) { return true; } await expect.element(active).toBeEnabled(); - sequence.push(await commands.readAriaSnapshot(active.selector)); + sequence.push(readAriaSnapshot(active)); return false; }, "backward"); @@ -430,12 +445,13 @@ describe("FormattingToolbar", () => { }); it("tabs backward through the default controls for Sibling and allows leaving", async ({ - renderEditor, + setupEditor, selectText, - commands, + focusUntil, + readAriaSnapshot, page, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { type: "paragraph", @@ -455,14 +471,16 @@ describe("FormattingToolbar", () => { }); await expect.element(lastControl).toBeVisible(); lastControl.element().focus(); - const sequence = [await commands.readAriaSnapshot(lastControl.selector)]; + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. + const sequence = [readAriaSnapshot(lastControl)]; - await commands.focusUntil(async (active) => { + await focusUntil(async (active) => { if (!toolbar.element().contains(active.element())) { return true; } await expect.element(active).toBeEnabled(); - sequence.push(await commands.readAriaSnapshot(active.selector)); + sequence.push(readAriaSnapshot(active)); return false; }, "backward"); @@ -496,13 +514,12 @@ describe("FormattingToolbar", () => { }); }); - describe("ARIA", () => { + describe("a11y", () => { it("exposes its custom controls as a toolbar", async ({ - renderEditor, - commands, + setupEditor, page, }) => { - await renderEditor({ + await setupEditor({ props: { formattingToolbar: false }, children: ( @@ -511,32 +528,27 @@ describe("FormattingToolbar", () => { ), }); - expect( - await commands.readAriaSnapshot(page.getByRole("toolbar").selector), - ).toMatchInlineSnapshot(` - "- toolbar: - - button "Custom action"" + await expect.element(page.getByRole("toolbar")) + .toMatchAriaInlineSnapshot(` + - toolbar: + - button "Custom action" `); }); - }); - describe("axe", () => { it("has no automated accessibility violations with the default controls", async ({ - renderEditor, + setupEditor, selectText, - annotate, - commands, page, + runAxe, }) => { - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], }); selectText(editor, "Selected text"); await expect.element(page.getByRole("toolbar")).toBeVisible(); - for (const warning of await commands.checkAxe('[role="toolbar"]')) { - await annotate(warning, "warning"); - } + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); }); }); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts index 948c6b4653..2cceeb03d3 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts @@ -5,29 +5,32 @@ import { expect } from "vite-plus/test"; // Individual toolbar item actions and focus rings are covered by the browser tests. // Screen reader announcements do not clearly communicate entering the toolbar. it.skip("announces entering and leaving the formatting toolbar", async ({ - renderEditor, - commands, + setupEditor, + readTranscript, + stopReader, + startReader, + pressKey, page, onTestFinished, }) => { onTestFinished(async () => { try { - const transcript = await commands.readTranscript(); + const transcript = await readTranscript(); expect(transcript.length).toBeGreaterThan(0); expect(transcript).toMatchSnapshot(); } finally { - await commands.stopReader(); + await stopReader(); } }); - const { editor } = await renderEditor({ + const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], }); editor.setTextCursorPosition("text", "start"); - await commands.startReader(page.getByRole("textbox").selector); - await commands.pressKey(selectToLineEndKey); - await commands.pressKey("Tab"); + await startReader(page.getByRole("textbox").selector); + await pressKey(selectToLineEndKey); + await pressKey("Tab"); const toolbar = page.getByRole("toolbar"); await expect .element( @@ -37,7 +40,7 @@ it.skip("announces entering and leaving the formatting toolbar", async ({ }), ) .toHaveFocus(); - await commands.pressKey("Escape"); + await pressKey("Escape"); await expect.element(toolbar).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); }); diff --git a/packages/react/src/editor/BlockNoteView.browser.test.tsx b/packages/react/src/editor/BlockNoteView.browser.test.tsx index 5a8b2ed7f7..2fde033e2c 100644 --- a/packages/react/src/editor/BlockNoteView.browser.test.tsx +++ b/packages/react/src/editor/BlockNoteView.browser.test.tsx @@ -21,6 +21,21 @@ import { useCreateBlockNote } from "@blocknote/react"; import { render } from "vitest-browser-react"; import { screenshotFull } from "@root/tests/src/utils/screenshotFull.js"; +// These keyboard-navigation tests inspect the focus end of the DOM selection. +function readDOMSelection() { + const node = document.getSelection()?.focusNode; + const element = node instanceof Element ? node : node?.parentElement; + const cell = element?.closest("td, th"); + const row = cell?.parentElement; + return { + tableCell: + cell instanceof HTMLTableCellElement && row instanceof HTMLTableRowElement + ? { row: row.rowIndex, column: cell.cellIndex } + : null, + blockId: element?.closest("[data-id]")?.getAttribute("data-id") ?? null, + }; +} + function TestEditor({ initialContent, editable, @@ -195,8 +210,8 @@ export async function navigateDefaultSchemaDocument() { // Follow the document until its endpoint; an unreachable endpoint times out. const visitedTableCells = new Set(); - while ((await commands.readSelection()).blockId !== "end") { - const { tableCell } = await commands.readSelection(); + while (readDOMSelection().blockId !== "end") { + const { tableCell } = readDOMSelection(); if (tableCell) { visitedTableCells.add(`${tableCell.row},${tableCell.column}`); } @@ -208,7 +223,7 @@ export async function navigateDefaultSchemaDocument() { await commands.pressKey("ArrowDown"); } } - while ((await commands.readSelection()).blockId !== "start") { + while (readDOMSelection().blockId !== "start") { await commands.pressKey("ArrowUp"); } } @@ -422,8 +437,8 @@ if (!screenReader) { // Follow the document until its endpoint; an unreachable endpoint times out. const visitedTableCells = new Set(); - while ((await commands.readSelection()).blockId !== "end") { - const { tableCell } = await commands.readSelection(); + while (readDOMSelection().blockId !== "end") { + const { tableCell } = readDOMSelection(); if (tableCell) { visitedTableCells.add(`${tableCell.row},${tableCell.column}`); } @@ -440,14 +455,14 @@ if (!screenReader) { "Every table cell is visited", ).toEqual(["0,0", "0,1", "1,0", "1,1"]); expect( - (await commands.readSelection()).blockId, + readDOMSelection().blockId, "Arrow keys reach the final block", ).toBe("end"); - while ((await commands.readSelection()).blockId !== "start") { + while (readDOMSelection().blockId !== "start") { await commands.pressKey("ArrowUp"); } expect( - (await commands.readSelection()).blockId, + readDOMSelection().blockId, "ArrowUp returns to the first block", ).toBe("start"); } @@ -458,12 +473,12 @@ if (!screenReader) { exact: true, }); await expect.element(link).toBeVisible(); - const unfocusedOutline = await commands.readOutline(link.selector); + const unfocusedOutline = commands.readFocusOutline(link); while (document.activeElement !== link.element()) { await commands.pressKey("Tab"); } await expect.element(link).toHaveFocus(); - await commands.checkFocusOutline(link.selector, unfocusedOutline); + await commands.assertFocusOutline(link, unfocusedOutline); return link; } @@ -536,9 +551,7 @@ if (!screenReader) { // Numbered list item indices are separate text elements, among other issues. test.skip("default schema: accessibility tree snapshot", async () => { await renderTestEditor(schemaDocument); - expect( - await commands.readAriaSnapshot(page.getByRole("textbox").selector), - ).toMatchSnapshot("default schema"); + await expect.element(page.getByRole("textbox")).toMatchAriaSnapshot(); }); }); @@ -548,8 +561,13 @@ if (!screenReader) { // insufficient contrast, and undersized targets. test.skip(`default schema: axe (${theme})`, async ({ annotate }) => { await renderTestEditor(schemaDocument, { theme }); - for (const warning of await commands.checkAxe()) { - await annotate(warning, "warning"); + const results = await commands.runAxe(); + expect(results.violations).toEqual([]); + for (const result of results.incomplete) { + await annotate( + `axe manual review: ${result.id} — ${result.help}`, + "warning", + ); } }); } diff --git a/scripts/lint/README.md b/scripts/lint/README.md new file mode 100644 index 0000000000..4bdd835393 --- /dev/null +++ b/scripts/lint/README.md @@ -0,0 +1,36 @@ +# Component browser test structure + +`component-browser-tests.mjs` is a local Oxlint JavaScript plugin, loaded by +`vite.config.ts`. The initial override covers FormattingToolbar browser tests +only. Older component suites must be migrated before widening that glob. + +- Exactly one top-level owner `describe`, named after the full filename before + `.browser.test.tsx` (or `.ts`). `NestBlockButtons` owns both button exports; + `BasicTextStyleButton` and controller files keep their full names. No import + analysis or singularization guesses are used to infer the owner. +- Direct child groups are an ordered, unique subset of `unit`, `integration`, + `keyboard`, `a11y`. Missing groups are fine; unknown groups are not. ARIA + assertions and axe scans belong together in `a11y`, not separate groups. +- Tests belong inside those groups. Scenario describes may nest further. +- Empty describes, including hooks-only or comments-only placeholders, fail. + Emptiness means no syntactic test registration in the describe's subtree, not + proof that a test will execute. Skipped/todo tests still count as declarations. + +The rule resolves Vitest globals and named/namespace imports from `vite-plus/test` +or `vitest`, including aliases, shadowing, and common modifiers/parameterized +calls. Owner/category titles must be static strings, and describe callbacks must +be inline functions with block bodies. It intentionally does not evaluate code, +resolve fixture re-exports or arbitrary wrapper helpers, infer test categories +from assertions, or autofix ordering (moving hooks can change behavior). +Tagged-template parameterization and generated suites are outside this pilot's +supported declaration style. Extend the focused cases before expanding support. + +Run the focused tests against the installed Oxlint engine (no browser needed): + +```sh +pnpm exec node --test scripts/lint/component-browser-tests.test.mjs +vp run lint packages/react/src/components/FormattingToolbar +``` + +The tests use an isolated temporary config and TSX source fixtures; they do not +modify real component tests. No new package dependency is required. diff --git a/scripts/lint/component-browser-tests.mjs b/scripts/lint/component-browser-tests.mjs new file mode 100644 index 0000000000..fd75320df7 --- /dev/null +++ b/scripts/lint/component-browser-tests.mjs @@ -0,0 +1,209 @@ +import { basename } from "node:path"; + +const groups = ["unit", "integration", "keyboard", "a11y"]; +const testModules = new Set(["vite-plus/test", "vitest"]); +const apis = new Set(["describe", "suite", "it", "test"]); +const modifiers = new Set([ + "each", + "for", + "skip", + "only", + "todo", + "fails", + "concurrent", + "sequential", + "shuffle", + "skipIf", + "runIf", +]); + +function propertyName(node) { + return node.computed ? node.property.value : node.property.name; +} + +// Resolve bindings, not spelling: aliases work and locally shadowed names don't +// become test declarations. Unresolved names are Vitest's configured globals. +function importedName(identifier, context) { + let scope = context.sourceCode.getScope(identifier); + while (scope) { + const variable = scope.set.get(identifier.name); + if (variable) { + const definition = variable.defs[0]; + if (!definition) { + return identifier.name; + } + if ( + definition.type !== "ImportBinding" || + !testModules.has(definition.parent.source.value) + ) { + return undefined; + } + return definition.node.type === "ImportNamespaceSpecifier" + ? "namespace" + : (definition.node.imported?.name ?? definition.node.imported?.value); + } + scope = scope.upper; + } + return identifier.name; +} + +function testApi(callee, context) { + if (callee.type === "Identifier") { + const name = importedName(callee, context); + return apis.has(name) ? name : undefined; + } + if (callee.type === "CallExpression") { + return testApi(callee.callee, context); + } + if (callee.type === "MemberExpression") { + if ( + callee.object.type === "Identifier" && + importedName(callee.object, context) === "namespace" + ) { + const name = propertyName(callee); + return apis.has(name) ? name : undefined; + } + // test.extend(), test.scoped(), etc. create fixtures; they do not register + // tests. Unknown/dynamic APIs are deliberately not guessed from spelling. + return modifiers.has(propertyName(callee)) + ? testApi(callee.object, context) + : undefined; + } + return undefined; +} + +function staticTitle(node) { + if (node?.type === "Literal" && typeof node.value === "string") { + return node.value; + } + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { + return node.quasis[0].value.cooked; + } + return undefined; +} + +function directStatement(call, body) { + return ( + call.parent.type === "ExpressionStatement" && call.parent.parent === body + ); +} + +const structure = { + meta: { + type: "suggestion", + schema: [], + messages: { + owner: 'Use exactly one top-level describe("{{owner}}", () => { ... }).', + callback: "Use an inline describe callback with a block body.", + group: + "Place each applicable group directly inside the owner, once, in this order: unit, integration, keyboard, a11y. Omit inapplicable groups.", + placement: + "Place tests inside an applicable group, not directly in the owner or at file scope.", + empty: "Omit empty describe groups; hooks or comments are not tests.", + }, + }, + create(context) { + const filename = basename(context.filename); + if (!/\.browser\.test\.[cm]?[jt]sx?$/.test(filename)) { + return {}; + } + // File owner, not imported symbol: NestBlockButtons deliberately owns both + // NestBlockButton and UnnestBlockButton. Controllers retain their full name. + const owner = filename.replace(/\.browser\.test\.[cm]?[jt]sx?$/, ""); + const suites = []; + const tests = []; + + return { + CallExpression(node) { + // Only the final registration, not the factory in it.each(cases)(...). + if ( + (node.parent.type === "CallExpression" && + node.parent.callee === node) || + (node.parent.type === "MemberExpression" && + node.parent.object === node) + ) { + return; + } + const api = testApi(node.callee, context); + if (!api) { + return; + } + if (api === "describe" || api === "suite") { + const callback = node.arguments.at(-1); + const body = + (callback?.type === "ArrowFunctionExpression" || + callback?.type === "FunctionExpression") && + callback.body.type === "BlockStatement" + ? callback.body + : undefined; + suites.push({ node, body, title: staticTitle(node.arguments[0]) }); + if (!body) { + context.report({ node, messageId: "callback" }); + } + } else { + tests.push(node); + } + }, + "Program:exit"(program) { + const roots = suites.filter(({ node }) => + directStatement(node, program), + ); + if (roots.length !== 1 || roots[0].title !== owner) { + context.report({ + node: program, + messageId: "owner", + data: { owner }, + }); + return; + } + const root = roots[0]; + if (!root.body) { + return; + } + const categories = suites.filter(({ node }) => + directStatement(node, root.body), + ); + let previous = -1; + for (const category of categories) { + const index = groups.indexOf(category.title); + if (index < 0 || index <= previous) { + context.report({ node: category.node, messageId: "group" }); + } + previous = Math.max(previous, index); + } + function inside(node, body) { + for (let parent = node.parent; parent; parent = parent.parent) { + if (parent === body) { + return true; + } + } + return false; + } + for (const node of tests) { + if (!categories.some(({ body }) => body && inside(node, body))) { + context.report({ node, messageId: "placement" }); + } + } + for (const suite of suites) { + if (suite === root || !suite.body) { + continue; + } + if (!inside(suite.node, root.body)) { + context.report({ node: suite.node, messageId: "group" }); + } + if (!tests.some((node) => inside(node, suite.body))) { + context.report({ node: suite.node, messageId: "empty" }); + } + } + if (categories.length === 0) { + context.report({ node: root.node, messageId: "group" }); + } + }, + }; + }, +}; + +export default { + meta: { name: "blocknote-tests" }, + rules: { "component-browser-structure": structure }, +}; diff --git a/scripts/lint/component-browser-tests.test.mjs b/scripts/lint/component-browser-tests.test.mjs new file mode 100644 index 0000000000..200fd99c52 --- /dev/null +++ b/scripts/lint/component-browser-tests.test.mjs @@ -0,0 +1,237 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, test } from "node:test"; + +// Exercise the installed Oxlint engine, including scope analysis and TSX +// parsing. No ESLint dependency, mock ASTs, or browser process is needed. +const directory = mkdtempSync(join(tmpdir(), "blocknote-lint-")); +after(() => rmSync(directory, { recursive: true, force: true })); +const config = join(directory, ".oxlintrc.json"); +writeFileSync( + config, + JSON.stringify({ + categories: { correctness: "off" }, + jsPlugins: [ + { + name: "blocknote-tests", + specifier: fileURLToPath( + new URL("./component-browser-tests.mjs", import.meta.url), + ), + }, + ], + rules: { "blocknote-tests/component-browser-structure": "error" }, + }), +); + +function lint(code, filename = "Button.browser.test.tsx") { + const path = join(directory, filename); + writeFileSync(path, code); + const result = spawnSync( + "vp", + ["lint", "--config", config, "--format", "json", path], + { encoding: "utf8" }, + ); + assert.ifError(result.error); + assert.ok( + result.status === 0 || result.status === 1, + `Oxlint failed: ${result.stdout}\n${result.stderr}`, + ); + const output = JSON.parse(result.stdout); + assert.ok( + !output.diagnostics.some( + (item) => + item.severity === "error" && + !item.code?.includes("component-browser-structure"), + ), + result.stdout, + ); + return output.diagnostics.map((item) => item.message); +} + +const body = 'it("works", () => {});'; +function group(name) { + return `describe(${JSON.stringify(name)}, () => { ${body} });`; +} +function owner(content, name = "Button") { + return `describe(${JSON.stringify(name)}, () => { ${content} });`; +} + +void test("accepts all groups in order and any nonempty subset", () => { + assert.deepEqual( + lint( + owner(["unit", "integration", "keyboard", "a11y"].map(group).join("\n")), + ), + [], + ); + assert.deepEqual(lint(owner(group("a11y"))), []); + assert.deepEqual(lint(owner(group("unit") + group("a11y"))), []); +}); + +void test("accepts ARIA assertions and axe scans inside the same a11y group", () => { + assert.deepEqual( + lint( + owner(`describe("a11y", () => { + it("exposes its role", () => { expect(button).toHaveAttribute("role", "button"); }); + it("has no axe violations", async () => { expect((await runAxe()).violations).toEqual([]); }); + });`), + ), + [], + ); +}); + +void test("owner is the full filename stem, not an imported symbol", () => { + for (const name of [ + "NestBlockButtons", + "BasicTextStyleButton", + "DesktopFormattingToolbarController", + ]) { + assert.deepEqual( + lint(owner(group("unit"), name), `${name}.browser.test.tsx`), + [], + ); + } + assert.match( + lint( + owner(group("unit"), "NestBlockButton"), + "NestBlockButtons.browser.test.tsx", + )[0], + /NestBlockButtons/, + ); +}); + +void test("rejects missing, multiple, or wrongly named owners", () => { + for (const code of [ + body, + owner(group("unit")) + owner(group("a11y")), + owner(group("unit"), "Other"), + ]) { + assert.match(lint(code)[0], /exactly one top-level/); + } +}); + +void test("rejects out-of-order, duplicate and unknown categories", () => { + for (const content of [ + group("a11y") + group("unit"), + group("unit") + group("unit"), + group("a11y") + group("a11y"), + group("behaviour"), + group("ARIA"), + group("aria"), + group("axe"), + group("visual"), + ]) { + assert.match(lint(owner(content)).join("\n"), /in this order/); + } +}); + +void test("rejects test declarations outside a category", () => { + assert.match( + lint(owner(group("unit") + body)).join("\n"), + /inside an applicable group/, + ); + assert.match( + lint(owner(group("unit")) + body).join("\n"), + /inside an applicable group/, + ); +}); + +void test("rejects empty, comment-only, hooks-only and nested-empty groups", () => { + for (const content of [ + "", + "// placeholder\n", + "beforeEach(() => {});", + 'describe("scenario", () => {});', + ]) { + assert.match( + lint(owner(`describe("unit", () => { ${content} });`)).join("\n"), + /Omit empty/, + ); + } +}); + +void test("accepts nested scenarios, hooks, TSX and parameterized registrations", () => { + assert.deepEqual( + lint( + owner(`beforeEach(() => {}); describe("unit", () => { + describe("scenario", () => { + it.for([1, 2])("case %s", () => { const element = , + * }); + */ + function setupEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + options: RenderOptions & { + schema: CustomBlockNoteSchema; + }, + ): Promise>; + function setupEditor( + options?: DefaultRenderOptions, + ): Promise< + RenderedEditor< + DefaultBlockSchema, + DefaultInlineContentSchema, + DefaultStyleSchema + > + >; + function setupEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + options: + | (RenderOptions & { schema: CustomBlockNoteSchema }) + | DefaultRenderOptions = {}, + ) { + if (options.schema === undefined) { + return renderWithSchema(BlockNoteSchema.create(), options); + } + return renderWithSchema(options.schema, options); + } + return setupEditor; +} + +export type SetupEditor = ReturnType; + +async function loadSkin(skin: "mantine" | "shadcn" | "ariakit") { + switch (skin) { + case "mantine": { + return ( + await Promise.all([ + import("@blocknote/mantine"), + import("@blocknote/mantine/style.css"), + ]) + )[0]; + } + case "shadcn": + return import("@blocknote/shadcn"); + case "ariakit": + return import("@blocknote/ariakit"); + } +} diff --git a/tests/src/commands/index.ts b/tests/src/commands/index.ts new file mode 100644 index 0000000000..2887f8bae8 --- /dev/null +++ b/tests/src/commands/index.ts @@ -0,0 +1,74 @@ +/* eslint-disable no-empty-pattern -- Vitest requires destructured fixture dependencies. */ +import type { TestAPI } from "vite-plus/test"; +import * as browserCommands from "./browser/index.js"; +import { createSetupEditor, type SetupEditor } from "./browser/setupEditor.js"; +import { commands as nodeCommands, page } from "./transport.js"; + +export type CommandContext = Pick< + typeof nodeCommands, + keyof typeof import("../screen-reader/commands.js") +> & + typeof browserCommands & { + page: typeof page; + setupEditor: SetupEditor; + }; + +/** Top-level test fixtures; pass this collection to test.extend unchanged. */ +export const commands: Required< + Parameters["scoped"]>[0] +> = { + page, + pressKey: async ({}, use) => { + await use(nodeCommands.pressKey); + }, + positionalMouse: async ({}, use) => { + await use(nodeCommands.positionalMouse); + }, + imeComposition: async ({}, use) => { + await use(nodeCommands.imeComposition); + }, + restoreTouchEmulation: async ({}, use) => { + await use(nodeCommands.restoreTouchEmulation); + }, + startReader: async ({}, use) => { + await use(nodeCommands.startReader); + }, + readTranscript: async ({}, use) => { + await use(nodeCommands.readTranscript); + }, + stopReader: async ({}, use) => { + await use(nodeCommands.stopReader); + }, + focusUntil: async ({}, use) => { + await use(browserCommands.focusUntil); + }, + readFocusOutline: async ({}, use) => { + await use(browserCommands.readFocusOutline); + }, + readAriaSnapshot: async ({}, use) => { + await use(browserCommands.readAriaSnapshot); + }, + assertFocusOutline: async ({}, use) => { + await use(browserCommands.assertFocusOutline); + }, + selectText: async ({}, use) => { + await use(browserCommands.selectText); + }, + setupEditor: async ({ onTestFinished }, use) => { + await use(createSetupEditor(onTestFinished)); + }, + runAxe: async ({ annotate }, use) => { + await use(async (scope) => { + const results = await browserCommands.runAxe(scope); + for (const result of results.incomplete) { + for (const node of result.nodes) { + await annotate( + `axe manual review: ${result.id} — ${result.help}\nTarget: ${JSON.stringify(node.target)}\n${node.failureSummary ?? ""}\n${result.helpUrl}`, + "warning", + ); + } + } + return results; + }); + }, +}; diff --git a/tests/src/utils/imeComposition.ts b/tests/src/commands/node/imeComposition.ts similarity index 69% rename from tests/src/utils/imeComposition.ts rename to tests/src/commands/node/imeComposition.ts index 6b1e229ca9..3bab411554 100644 --- a/tests/src/utils/imeComposition.ts +++ b/tests/src/commands/node/imeComposition.ts @@ -1,5 +1,10 @@ import type { BrowserCommand } from "vite-plus/test/node"; +// eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. +import type { userEvent } from "../transport.js"; +// eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. +import type { selectText } from "../browser/selectText.js"; + /** * One step of an emulated IME session. `setComposition` updates the active * composition (starting one if none is active); `commit` finalizes it with @@ -31,6 +36,24 @@ export type ImeStep = * focused element — the same events a mobile IME (Gboard, Samsung Keyboard) * generates, which no synthetic `CompositionEvent` dispatch can reproduce * (those are untrusted and never touch the DOM). Chromium-only. + * + * Use for bugs involving active composition, replacement, or IME commit semantics, + * not ordinary text entry ({@link userEvent.keyboard}) or selection setup + * ({@link selectText}). + * Focus the editable and establish its caret first. This emulates browser IME + * input, not an OS keyboard UI, candidate picker, or device-specific action key. + * + * @example + * const { editor } = await setupEditor(); + * await page.getByRole("textbox").click(); + * await imeComposition([ + * { type: "setComposition", text: "に" }, + * { type: "setComposition", text: "日本" }, + * { type: "commit", text: "日本" }, + * ]); + * expect(editor.document[0].content).toEqual([ + * { type: "text", text: "日本", styles: {} }, + * ]); */ export const imeComposition: BrowserCommand<[steps: ImeStep[]]> = async ( ctx, diff --git a/tests/src/utils/commands.ts b/tests/src/commands/node/index.ts similarity index 64% rename from tests/src/utils/commands.ts rename to tests/src/commands/node/index.ts index 7d5cefe28f..8e4b246d08 100644 --- a/tests/src/utils/commands.ts +++ b/tests/src/commands/node/index.ts @@ -1,10 +1,4 @@ -export { - readAriaSnapshot, - readOutline, - checkFocusOutline, - readSelection, - checkAxe, -} from "./accessibility.js"; +// Only commands that require Playwright or CDP are registered with Vitest. export { pressKey } from "./keyboard.js"; export { positionalMouse } from "./positionalMouse.js"; export { imeComposition } from "./imeComposition.js"; diff --git a/tests/src/commands/node/keyboard.ts b/tests/src/commands/node/keyboard.ts new file mode 100644 index 0000000000..15593b3c49 --- /dev/null +++ b/tests/src/commands/node/keyboard.ts @@ -0,0 +1,35 @@ +import type { BrowserCommand } from "vite-plus/test/node"; + +// eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. +import type { userEvent } from "../transport.js"; +// eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. +import type { selectText } from "../browser/selectText.js"; + +declare global { + interface Window { + __blockNoteWaitForEditorFocus(): Promise; + } +} + +/** + * Sends one real Playwright key press to the currently focused element after + * pending ProseMirror focus/selection reconciliation has settled. Use for keyboard + * navigation, shortcuts, and activation; use {@link userEvent.keyboard} for typing + * plain text, and {@link selectText} for selection setup unrelated to keyboard behavior. + * + * Accepts Playwright key names/chords, such as "Tab", "Shift+Tab", or "Control+k". + * Does not choose a target: establish focus first. Requires the shared browser + * setup's reconciliation hook. In the native screen-reader configuration the same + * fixture also captures speech; callers do not need a separate keyboard helper. + * + * @example + * await page.getByRole("textbox").click(); + * await pressKey("Tab"); + * await expect.element(boldButton).toHaveFocus(); + * await pressKey("Enter"); + */ +export const pressKey: BrowserCommand<[key: string]> = async (context, key) => { + const frame = await context.frame(); + await frame.evaluate(() => window.__blockNoteWaitForEditorFocus()); + await context.page.keyboard.press(key); +}; diff --git a/tests/src/utils/positionalMouse.ts b/tests/src/commands/node/positionalMouse.ts similarity index 63% rename from tests/src/utils/positionalMouse.ts rename to tests/src/commands/node/positionalMouse.ts index 4c893455ba..971326e873 100644 --- a/tests/src/utils/positionalMouse.ts +++ b/tests/src/commands/node/positionalMouse.ts @@ -26,15 +26,27 @@ export type MouseAction = | { type: "click"; x: number; y: number; clickCount?: number }; /** - * Vitest's `userEvent` doesn't have several mouse commands that we relied on in Playwright, namely - * clicking at the current mouse position, and moving the mouse to a given position across N steps. + * Performs real mouse actions at coordinates relative to the test iframe's + * viewport, correcting for the iframe's position in the outer browser page. + * Use for dragging, hit-testing, or movement across multiple steps where a + * locator's `.click()`/`.hover()` cannot express the interaction. Prefer locators + * for ordinary control activation so tests do not depend on layout coordinates. * - * Additionally, Vitest runs component tests in an `iframe`, so any given position needs to be - * offset, as it should refer to a point within the `iframe` rather then the full page. + * Actions are positional arguments, not an array. `down` and `up` use the current + * mouse position; `move` supports intermediate steps and `click` a click count. + * Coordinates from `element().getBoundingClientRect()` are in the expected space. + * This is mouse input, not touch emulation. Requires the shared Node registration. * - * This function adds that functionality. It must be registered as a command in - * `vite.config.browser.ts` as that's the only way to have access to the internal Playwright - * context. + * @example + * const box = handle.element().getBoundingClientRect(); + * const x = box.left + box.width / 2; + * const y = box.top + box.height / 2; + * await positionalMouse( + * { type: "move", x, y }, + * { type: "down" }, + * { type: "move", x: x + 100, y, steps: 10 }, + * { type: "up" }, + * ); */ export const positionalMouse: BrowserCommand = async ( // eslint-disable-next-line typescript/unbound-method -- destructuring page/frame from parameter object, not a class diff --git a/tests/src/utils/restoreTouchEmulation.ts b/tests/src/commands/node/restoreTouchEmulation.ts similarity index 71% rename from tests/src/utils/restoreTouchEmulation.ts rename to tests/src/commands/node/restoreTouchEmulation.ts index 47b4844dba..0478debde5 100644 --- a/tests/src/utils/restoreTouchEmulation.ts +++ b/tests/src/commands/node/restoreTouchEmulation.ts @@ -19,6 +19,21 @@ import type { BrowserCommand } from "vite-plus/test/node"; */ const sessions = new WeakMap>(); +/** + * Restores Chromium touch capability after a screenshot disables it. Use only in + * a Chromium context configured with touch support (the Android-emulated project), + * not to turn a desktop test into a mobile test. Shared setup already calls this + * before each Android test; call explicitly only if the same test takes a + * screenshot and then needs to continue exercising touch-dependent behavior. + * + * Does not reset the viewport, user agent, or input state. The CDP session stays + * attached because detaching it would undo the emulation override. + * + * @example + * // In an Android-emulated test, after a screenshot: + * await restoreTouchEmulation(); + * expect(navigator.maxTouchPoints).toBeGreaterThan(0); + */ export const restoreTouchEmulation: BrowserCommand<[]> = async (ctx) => { let session = sessions.get(ctx.page); if (session === undefined) { diff --git a/tests/src/commands/node/setupEditor.ts b/tests/src/commands/node/setupEditor.ts new file mode 100644 index 0000000000..4f3cef63f1 --- /dev/null +++ b/tests/src/commands/node/setupEditor.ts @@ -0,0 +1,108 @@ +import { + BlockNoteEditor, + BlockNoteSchema, + type BlockNoteEditorOptions, + type BlockSchema, + type CustomBlockNoteSchema, + type DefaultBlockSchema, + type DefaultInlineContentSchema, + type DefaultStyleSchema, + type InlineContentSchema, + type StyleSchema, +} from "@blocknote/core"; +import type { TestContext } from "vite-plus/test"; + +type DefaultOptions = Omit< + Partial< + BlockNoteEditorOptions< + DefaultBlockSchema, + DefaultInlineContentSchema, + DefaultStyleSchema + > + >, + "schema" +> & { schema?: never }; + +/** Binds mounted editor cleanup to the current Node test (not a browser RPC). */ +export function createSetupEditor(onFinished: TestContext["onTestFinished"]) { + async function setupWithSchema< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + schema: CustomBlockNoteSchema, + options: Partial>, + ) { + const rootNode = document.createElement("div"); + const editor = BlockNoteEditor.create({ ...options, schema }); + document.body.append(rootNode); + onFinished(() => { + editor.unmount(); + rootNode.remove(); + }); + editor.mount(rootNode); + return { editor, rootNode }; + } + + /** + * Creates a real editor, mounts its contenteditable into the test environment's + * jsdom document, and unmounts/removes it after the test. Requires Vitest's + * `jsdom` environment; it does not install DOM globals itself. + * + * Use for Node tests of editor/document logic. This mounts the core editor, not + * a React view or skin. Use browser setupEditor for component rendering and real + * input/focus behavior, or BlockNoteEditor.create directly for headless logic. + * Accepts the same top-level editor options as the browser setupEditor, + * including custom schemas, but no view props, skin, children, or rerender. + * Returns `{ editor, rootNode }`, where `rootNode` is the mounting container + * attached to document.body and removed during cleanup. + * + * @example + * // @vitest-environment jsdom + * import { test as it } from "@root/tests/src/fixtures/editor.node.js"; + * + * it("updates a block", async ({ setupEditor }) => { + * const { editor } = await setupEditor({ + * initialContent: [{ id: "text", type: "paragraph", content: "Hello" }], + * }); + * editor.updateBlock("text", { props: { textAlignment: "center" } }); + * expect(editor.getBlock("text")?.props.textAlignment).toBe("center"); + * }); + */ + function setupEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + options: Partial> & { + schema: CustomBlockNoteSchema; + }, + ): Promise<{ editor: BlockNoteEditor; rootNode: HTMLDivElement }>; + function setupEditor(options?: DefaultOptions): Promise<{ + editor: BlockNoteEditor< + DefaultBlockSchema, + DefaultInlineContentSchema, + DefaultStyleSchema + >; + rootNode: HTMLDivElement; + }>; + function setupEditor< + B extends BlockSchema, + I extends InlineContentSchema, + S extends StyleSchema, + >( + options: + | (Partial> & { + schema: CustomBlockNoteSchema; + }) + | DefaultOptions = {}, + ) { + if (options.schema === undefined) { + return setupWithSchema(BlockNoteSchema.create(), options); + } + return setupWithSchema(options.schema, options); + } + return setupEditor; +} + +export type SetupEditor = ReturnType; diff --git a/tests/src/commands/transport.ts b/tests/src/commands/transport.ts new file mode 100644 index 0000000000..c281439622 --- /dev/null +++ b/tests/src/commands/transport.ts @@ -0,0 +1,28 @@ +import { + commands as vitestCommands, + page, + server, + userEvent, +} from "vite-plus/test/browser"; + +// `vite-plus/test/browser` re-exports `vitest/browser`, which Vitest replaces +// with a generated virtual module while running in Browser Mode. Import it from +// this single place so the e2e utils + tests share one `userEvent` instance +// (it preserves keyboard/pointer state across calls) and one command surface. +export { page, server, userEvent }; + +type BrowserCommands = { + [Name in keyof Implementations]: Implementations[Name] extends ( + ...args: infer Args + ) => infer Result + ? Args extends [unknown, ...infer BrowserArgs] + ? (...args: BrowserArgs) => Promise> + : never + : never; +}; + +// Vite+ does not expose the augmentable BrowserCommands interface. Derive the +// browser signatures from the implementations, omitting their Node context. +// Reader commands are available only in the native screen-reader configuration. +export const commands = vitestCommands as typeof vitestCommands & + BrowserCommands; diff --git a/tests/src/fixtures/editor.node.ts b/tests/src/fixtures/editor.node.ts new file mode 100644 index 0000000000..6f1f15d87f --- /dev/null +++ b/tests/src/fixtures/editor.node.ts @@ -0,0 +1,12 @@ +import { test as base } from "vite-plus/test"; +import { + createSetupEditor, + type SetupEditor, +} from "../commands/node/setupEditor.js"; + +/** Node fixtures: mounts the core editor in jsdom, without React or skin styles. */ +export const test = base.extend<{ setupEditor: SetupEditor }>({ + setupEditor: async ({ onTestFinished }, use) => { + await use(createSetupEditor(onTestFinished)); + }, +}); diff --git a/tests/src/fixtures/editor.tsx b/tests/src/fixtures/editor.tsx index d717f3c9a0..385f899d6a 100644 --- a/tests/src/fixtures/editor.tsx +++ b/tests/src/fixtures/editor.tsx @@ -1,218 +1,7 @@ -import { - BlockNoteEditor, - type BlockNoteEditorOptions, - BlockNoteSchema, - type BlockSchema, - type CustomBlockNoteSchema, - type DefaultBlockSchema, - type DefaultInlineContentSchema, - type DefaultStyleSchema, - type InlineContentSchema, - type StyleSchema, - getNodeById, -} from "@blocknote/core"; -import { BlockNoteView } from "@blocknote/mantine"; -import { TextSelection } from "@tiptap/pm/state"; -import "../../../packages/mantine/src/style.css"; -import type { ComponentProps, ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { test as base, type TestContext } from "vite-plus/test"; -import { commands, page } from "../utils/context.js"; +import { test as base } from "vite-plus/test"; +import { commands, type CommandContext } from "../commands/index.js"; -type ViewProps< - B extends BlockSchema, - I extends InlineContentSchema, - S extends StyleSchema, -> = Omit>, "editor">; - -type RenderOptions< - B extends BlockSchema, - I extends InlineContentSchema, - S extends StyleSchema, -> = Partial> & { - props?: Omit, "children">; - children?: - | ReactNode - | ((props: { editor: BlockNoteEditor }) => ReactNode); - outside?: (props: { - editor: BlockNoteEditor; - children: ReactNode; - }) => ReactNode; -}; - -type DefaultRenderOptions = Omit< - RenderOptions< - DefaultBlockSchema, - DefaultInlineContentSchema, - DefaultStyleSchema - >, - "schema" -> & { schema?: never }; - -// A named result keeps editor hovers from recursively expanding the factory's -// inferred ReturnType through the generic renderEditor overloads (TS 6). -type RenderedEditor< - B extends BlockSchema, - I extends InlineContentSchema, - S extends StyleSchema, -> = { - editor: BlockNoteEditor; - rerender: (props: ViewProps) => void; -}; - -function createRenderEditor(onFinished: TestContext["onTestFinished"]) { - async function renderWithSchema< - B extends BlockSchema, - I extends InlineContentSchema, - S extends StyleSchema, - >(schema: CustomBlockNoteSchema, options: RenderOptions) { - const { props: viewProps, children, outside, ...editorOptions } = options; - const editor = BlockNoteEditor.create({ - ...editorOptions, - schema, - }); - const host = document.createElement("div"); - document.body.append(host); - const root = createRoot(host); - onFinished(() => { - root.unmount(); - editor._tiptapEditor.destroy(); - host.remove(); - }); - - let props = { - ...viewProps, - children: - typeof children === "function" ? children({ editor }) : children, - }; - function rerender(nextProps: ViewProps) { - props = { ...props, ...nextProps }; - flushSync(() => { - const children = ; - root.render(outside ? outside({ editor, children }) : children); - }); - } - rerender(props); - await document.fonts.ready; - return { editor, rerender }; - } - - function renderEditor< - B extends BlockSchema, - I extends InlineContentSchema, - S extends StyleSchema, - >( - options: RenderOptions & { - schema: CustomBlockNoteSchema; - }, - ): Promise>; - function renderEditor( - options?: DefaultRenderOptions, - ): Promise< - RenderedEditor< - DefaultBlockSchema, - DefaultInlineContentSchema, - DefaultStyleSchema - > - >; - function renderEditor< - B extends BlockSchema, - I extends InlineContentSchema, - S extends StyleSchema, - >( - options: - | (RenderOptions & { schema: CustomBlockNoteSchema }) - | DefaultRenderOptions = {}, - ) { - if (options.schema === undefined) { - return renderWithSchema(BlockNoteSchema.create(), options); - } - return renderWithSchema(options.schema, options); - } - return renderEditor; -} - -export type RenderEditor = ReturnType; - -/** Selects the first substring, ignoring marks but never crossing non-text nodes. */ -export function selectText( - editor: Pick, - substring: string, - range?: { startBlockId: string; endBlockId?: string }, -) { - if (substring.length === 0) { - throw new Error("selectText requires a non-empty substring"); - } - editor.transact((tr) => { - let from = 0; - let to = tr.doc.content.size; - if (range) { - const start = getNodeById(range.startBlockId, tr.doc); - const end = getNodeById(range.endBlockId ?? range.startBlockId, tr.doc); - if (!start || !end) { - throw new Error("selectText could not find the requested block range"); - } - from = start.posBeforeNode; - to = end.posBeforeNode + end.node.nodeSize; - if (from >= to) { - throw new Error("selectText requires blocks in document order"); - } - } - - let text = ""; - let textStart = 0; - let match: { from: number; to: number } | undefined; - tr.doc.nodesBetween(from, to, (node, pos) => { - if (match) { - return false; - } - if (!node.isText) { - if (node.isBlock || node.isLeaf) { - text = ""; - } - return true; - } - // Adjacent text nodes can have different marks. Gaps indicate a hard - // break, another inline node, or a new block, and must reset the search. - if (pos !== textStart + text.length) { - text = ""; - textStart = pos; - } - text += node.textContent; - const index = text.indexOf(substring); - if (index !== -1) { - match = { - from: textStart + index, - to: textStart + index + substring.length, - }; - } - return true; - }); - if (!match) { - throw new Error(`selectText could not find ${JSON.stringify(substring)}`); - } - tr.setSelection(TextSelection.create(tr.doc, match.from, match.to)); - }); -} - -export const test = base.extend<{ - commands: typeof commands; - page: typeof page; - renderEditor: RenderEditor; - selectText: typeof selectText; -}>({ - commands, - page, - renderEditor: async ({ onTestFinished }, use) => { - await use(createRenderEditor(onTestFinished)); - }, - // Vitest requires destructured fixture arguments, even without dependencies. - // eslint-disable-next-line no-empty-pattern - selectText: async ({}, use) => { - await use(selectText); - }, -}); +export const test = base.extend(commands); // The browser setup installs this extended API; imported Vitest APIs are not // extended. tests/tsconfig.browser.json includes the setup for colocated tests. diff --git a/tests/src/screen-reader/commands.ts b/tests/src/screen-reader/commands.ts index a393a101d2..3e98d52790 100644 --- a/tests/src/screen-reader/commands.ts +++ b/tests/src/screen-reader/commands.ts @@ -1,4 +1,4 @@ -export * from "../utils/commands.js"; +export * from "../commands/node/index.js"; export { startReader, screenReaderPressKey as pressKey, diff --git a/tests/src/screen-reader/screenReader.ts b/tests/src/screen-reader/screenReader.ts index f563688c35..2651db2f40 100644 --- a/tests/src/screen-reader/screenReader.ts +++ b/tests/src/screen-reader/screenReader.ts @@ -1,6 +1,6 @@ -import { pressKey } from "../utils/keyboard.js"; +import { pressKey } from "../commands/node/keyboard.js"; import type { BrowserCommand } from "vite-plus/test/node"; -import type {} from "../utils/positionalMouse.js"; +import type {} from "../commands/node/positionalMouse.js"; // Import only on native runs: GuidePup cannot initialize on Linux. async function reader() { @@ -12,9 +12,15 @@ async function reader() { * selector in the test iframe. Synchronizes VoiceOver's cursor with keyboard * focus and clears startup speech so the transcript contains only the scenario. * Available only in the native screen-reader configuration; render first. + * Use only to test actual spoken announcements that browser ARIA/keyboard tests + * cannot prove. This controls the real desktop reader and foreground browser; + * do not use in ordinary Docker browser tests. Register cleanup before starting. * * @example - * await commands.startReader(page.getByRole("textbox").selector); + * onTestFinished(async () => { await stopReader(); }); + * await startReader(page.getByRole("textbox").selector); + * await pressKey("ArrowDown"); + * expect((await readTranscript()).length).toBeGreaterThan(0); */ export const startReader: BrowserCommand<[selector: string]> = async ( context, @@ -40,9 +46,16 @@ export const startReader: BrowserCommand<[selector: string]> = async ( /** * Captures native speech while executing the shared keyboard command, including - * its focus-reconciliation wait. Registered as `commands.pressKey` by the + * its focus-reconciliation wait. Registered as the top-level {@link pressKey} by the * native screen-reader configuration, so navigation can be shared with browser * tests without a separate keyboard helper. + * Use the public {@link pressKey} fixture after {@link startReader}, not this implementation + * directly; use browser tests when no spoken output needs verification. + * + * @example + * await startReader(page.getByRole("textbox").selector); + * await pressKey("Tab"); + * expect((await readTranscript()).length).toBeGreaterThan(0); */ export const screenReaderPressKey: BrowserCommand<[key: string]> = async ( context, @@ -55,12 +68,34 @@ export const screenReaderPressKey: BrowserCommand<[key: string]> = async ( * Returns the running native reader's spoken phrase log. Assert that it is * nonempty before comparing it with a Vitest snapshot in the consuming test. * Reading the log does not stop the reader; cleanup belongs in `finally`. + * Use for real announcement assertions after {@link startReader} and keyboard actions, + * not as a replacement for browser accessibility-tree or focus assertions. + * + * @example + * try { + * const transcript = await readTranscript(); + * expect(transcript.length).toBeGreaterThan(0); + * expect(transcript).toMatchSnapshot(); + * } finally { + * await stopReader(); + * } */ export const readTranscript: BrowserCommand<[], string[]> = async () => (await reader()).spokenPhraseLog(); /** - * Stops the native reader. Call in an `afterEach` hook's `finally` block so - * assertion or transcript failures do not leave the reader running. + * Stops the native reader after a test that started it. Always register cleanup + * before calling {@link startReader}, so assertions failing early do not leave the real + * desktop reader running. Available only in the native screen-reader runner. + * + * @example + * onTestFinished(async () => { + * try { + * const transcript = await readTranscript(); + * expect(transcript.length).toBeGreaterThan(0); + * } finally { + * await stopReader(); + * } + * }); */ export const stopReader: BrowserCommand<[]> = async () => (await reader()).stop(); diff --git a/tests/src/utils/accessibility.ts b/tests/src/utils/accessibility.ts deleted file mode 100644 index 25defa55e3..0000000000 --- a/tests/src/utils/accessibility.ts +++ /dev/null @@ -1,153 +0,0 @@ -import axe from "axe-core"; -import { expect } from "@playwright/test"; -import type { BrowserCommand } from "vite-plus/test/node"; - -export type Outline = { width: number; style: string; color: string }; -export type EditorSelection = { - tableCell: { row: number; column: number } | null; - blockId: string | null; - offset: number; - text: string; -}; - -declare global { - interface Window { - axe: typeof axe; - } -} - -/** - * Reads computed outline width (CSS pixels), style, and color in the test iframe. - * Pass a browser locator's `selector`, not its DOM element. Capture this before - * focusing the target to compare against its focused appearance. - * - * @example - * const unfocusedOutline = await commands.readOutline(button.selector); - */ -export const readOutline: BrowserCommand<[selector: string], Outline> = async ( - context, - selector, -) => - (await context.frame()).locator(selector).evaluate((element) => { - const style = getComputedStyle(element); - return { - width: Number.parseFloat(style.outlineWidth), - style: style.outlineStyle, - color: style.outlineColor, - }; - }); - -/** - * Waits for the target to match `:focus-visible` and have a nonzero outline - * whose style is neither `none` nor `hidden` and whose color is not transparent. - * When supplied, the outline must also differ from `unfocusedOutline`. - * Omit that baseline for autofocused inputs that cannot be observed unfocused. - * These checks cover CSS outline properties, not contrast or visual occlusion. - * - * @example - * await commands.checkFocusOutline(button.selector, unfocusedOutline); - */ -export const checkFocusOutline: BrowserCommand< - [selector: string, unfocusedOutline?: Outline], - void -> = async (context, selector, unfocusedOutline) => { - const target = (await context.frame()).locator(selector); - await expect - .poll(() => target.evaluate((element) => element.matches(":focus-visible"))) - .toBe(true); - // Autofocused inputs cannot be observed unfocused; compare when available. - if (unfocusedOutline) { - await expect - .poll(async () => await readOutline(context, selector)) - .not.toEqual(unfocusedOutline); - } - await expect - .poll(async () => (await readOutline(context, selector)).width) - .toBeGreaterThan(0); - await expect - .poll(async () => (await readOutline(context, selector)).style) - .not.toMatch(/^(none|hidden)$/); - await expect - .poll(async () => (await readOutline(context, selector)).color) - .not.toMatch(/^(transparent|rgba\(0, 0, 0, 0\))$/); -}; - -/** - * Reads the DOM selection in the test iframe for keyboard-navigation assertions. - * Block ID and zero-based table coordinates refer to the selection's focus end; - * offset is relative to its focus node. Text is the complete selected text. - * Without a selection, returns null locations, zero offset, and empty text. - * - * @example - * expect((await commands.readSelection()).blockId).toBe("end"); - */ -export const readSelection: BrowserCommand<[], EditorSelection> = async ( - context, -) => - (await context.frame()).evaluate(() => { - const selection = document.getSelection(); - const node = selection?.focusNode; - const element = node instanceof Element ? node : node?.parentElement; - const cell = element?.closest("td, th"); - const row = cell?.parentElement; - return { - tableCell: - cell instanceof HTMLTableCellElement && - row instanceof HTMLTableRowElement - ? { row: row.rowIndex, column: cell.cellIndex } - : null, - blockId: element?.closest("[data-id]")?.getAttribute("data-id") ?? null, - offset: selection?.focusOffset ?? 0, - text: selection?.toString() ?? "", - }; - }); - -/** - * Runs axe in the test iframe and asserts that it finds no violations, including - * the target-size rule. `scope` is an optional CSS selector; otherwise scans the - * document body. Returns incomplete-result messages for manual review. - * Call after the intended UI state is ready and annotate the returned warnings - * in the test, since annotation callbacks cannot cross the command boundary. - * - * @example - * for (const warning of await commands.checkAxe('[role="toolbar"]')) { - * await annotate(warning, "warning"); - * } - */ -export const checkAxe: BrowserCommand<[scope?: string], string[]> = async ( - context, - scope, -) => { - const frame = await context.frame(); - await frame.evaluate(axe.source); - const results = await frame.evaluate( - (scope) => - window.axe.run(scope ? { include: [scope] } : document.body, { - rules: { "target-size": { enabled: true } }, - }), - scope, - ); - expect(results.violations, "axe violations").toEqual([]); - return results.incomplete.flatMap((result) => - result.nodes.map( - (node) => - `axe manual review: ${result.id} — ${result.help}\nTarget: ${JSON.stringify(node.target)}\n${node.failureSummary ?? ""}\n${result.helpUrl}`, - ), - ); -}; - -/** - * Reads Playwright's semantic accessibility snapshot for a selector in the test - * iframe. Compare the returned string in the test so Vitest owns the named - * snapshot and its update policy. This does not run a native screen reader. - * - * @example - * expect(await commands.readAriaSnapshot(button.selector)).toMatchSnapshot( - * "before activation", - * ); - */ -export const readAriaSnapshot: BrowserCommand< - [selector: string], - string -> = async (context, selector) => - (await context.frame()).locator(selector).ariaSnapshot(); diff --git a/tests/src/utils/commands.browser.ts b/tests/src/utils/commands.browser.ts deleted file mode 100644 index 0dcc4f59d5..0000000000 --- a/tests/src/utils/commands.browser.ts +++ /dev/null @@ -1 +0,0 @@ -export { focusUntil } from "./focus.js"; diff --git a/tests/src/utils/context.ts b/tests/src/utils/context.ts index 23422be992..c7407a6acd 100644 --- a/tests/src/utils/context.ts +++ b/tests/src/utils/context.ts @@ -1,35 +1,11 @@ -import { - commands as vitestCommands, - page, - server, - userEvent, -} from "vite-plus/test/browser"; -import * as browserCommands from "./commands.browser.js"; +import { server } from "../commands/transport.js"; -// `vite-plus/test/browser` re-exports `vitest/browser`, which Vitest replaces -// with a generated virtual module while running in Browser Mode. Import it from -// this single place so the e2e utils + tests share one `userEvent` instance -// (it preserves keyboard/pointer state across calls) and one command surface. -export { page, server, userEvent }; +export { page, server, userEvent } from "../commands/transport.js"; +import * as browserCommands from "../commands/browser/index.js"; +import { commands as nodeCommands } from "../commands/transport.js"; -type BrowserCommands = { - [Name in keyof Implementations]: Implementations[Name] extends ( - ...args: infer Args - ) => infer Result - ? Args extends [unknown, ...infer BrowserArgs] - ? (...args: BrowserArgs) => Promise> - : never - : never; -}; - -// Vite+ does not expose the augmentable BrowserCommands interface. Derive the -// browser signatures from the implementations, omitting their Node context. -// Reader commands are available only in the native screen-reader configuration. -export const commands = { - ...(vitestCommands as typeof vitestCommands & - BrowserCommands), - ...browserCommands, -}; +// Compatibility for existing suites; extended tests use top-level fixtures. +export const commands = { ...nodeCommands, ...browserCommands }; /** The browser instance the current test is running in. */ export const browserName = server.browser as "chromium" | "firefox" | "webkit"; diff --git a/tests/src/utils/focus.ts b/tests/src/utils/focus.ts deleted file mode 100644 index d31a95f6d5..0000000000 --- a/tests/src/utils/focus.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { Locator } from "vite-plus/test/browser"; -import { commands, page } from "./context.js"; - -type FocusTarget = - | Locator - | ((locator: Locator) => void | boolean | Promise); - -/** - * Tabs in the given direction, calling the predicate after each step, until it returns true - * or the target locator receives focus. The starting element is not visited. - * Throws if focus cycles, stops moving, or leaves the document first. - */ -export async function focusUntil( - target: FocusTarget, - direction: "forward" | "backward" = "forward", -): Promise { - const key = direction === "forward" ? "Tab" : "Shift+Tab"; - const visited = new Set(); - if (!document.activeElement) { - throw new Error(`${key}: document.activeElement is null`); - } - visited.add(document.activeElement); - - while (true) { - await commands.pressKey(key); - const active = document.activeElement; - if (!active) { - throw new Error(`${key}: document.activeElement is null`); - } - if (visited.has(active)) { - throw new Error( - `${key}: focus cycled or stopped moving before finding the target`, - ); - } - visited.add(active); - - const locator = page.elementLocator(active); - const found = - typeof target === "function" - ? await target(locator) - : target.query() === active; - if (found === true) { - return locator; - } - if (active === document.body || active === document.documentElement) { - throw new Error(`${key}: reached the end of focusable elements`); - } - } -} diff --git a/tests/src/utils/keyboard.ts b/tests/src/utils/keyboard.ts deleted file mode 100644 index e67ee23476..0000000000 --- a/tests/src/utils/keyboard.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { BrowserCommand } from "vite-plus/test/node"; - -declare global { - interface Window { - __blockNoteWaitForEditorFocus(): Promise; - } -} - -/** - * Sends a Playwright key press after pending ProseMirror focus/selection - * reconciliation in the test iframe has settled. Requires the shared browser - * setup, which installs the reconciliation wait function. - * Accepts Playwright key names and chords, such as "Tab" or "Shift+ArrowDown". - * The native screen-reader configuration registers a speech-capturing version - * under the same command name. - * - * @example - * await commands.pressKey("ArrowDown"); - */ -export const pressKey: BrowserCommand<[key: string]> = async (context, key) => { - const frame = await context.frame(); - await frame.evaluate(() => window.__blockNoteWaitForEditorFocus()); - await context.page.keyboard.press(key); -}; diff --git a/tests/src/utils/mouse.ts b/tests/src/utils/mouse.ts index 9cee7a7608..8733f8dc1c 100644 --- a/tests/src/utils/mouse.ts +++ b/tests/src/utils/mouse.ts @@ -1,7 +1,7 @@ import { commands } from "./context.js"; import { DRAG_HANDLE_SELECTOR } from "./const.js"; import { sleep, waitForSelector } from "./editor.js"; -import type { MouseAction } from "./positionalMouse.js"; +import type { MouseAction } from "../commands/node/positionalMouse.js"; function runMouse(actions: MouseAction[]): Promise { return commands.positionalMouse(...actions); diff --git a/tests/vite.config.browser.ts b/tests/vite.config.browser.ts index 62d6457deb..5b6b688b70 100644 --- a/tests/vite.config.browser.ts +++ b/tests/vite.config.browser.ts @@ -3,7 +3,7 @@ import * as fs from "fs"; import * as path from "path"; import { configDefaults, defineConfig, type UserConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; -import * as commands from "./src/utils/commands.js"; +import * as commands from "./src/commands/node/index.js"; // For the desktop instances: end-to-end/mobile runs only in the "android" // instance. An instance-level `exclude` replaces the resolved base exclude diff --git a/tests/vitestSetup.browser.ts b/tests/vitestSetup.browser.ts index fac83ee0d6..706ccd01c2 100644 --- a/tests/vitestSetup.browser.ts +++ b/tests/vitestSetup.browser.ts @@ -1,4 +1,4 @@ -import type {} from "./src/utils/keyboard.js"; +import type {} from "./src/commands/node/keyboard.js"; import { afterEach, beforeAll, beforeEach } from "vite-plus/test"; import { commands, page } from "./src/utils/context.js"; @@ -58,7 +58,7 @@ beforeAll(async () => { // Chromium drops the context's touch emulation after any screenshot captured // beyond the viewport, which on this mobile context is every element // screenshot, and Playwright never re-arms it (microsoft/playwright#42607; -// mechanism and repro in `src/utils/restoreTouchEmulation.ts`). Before every +// mechanism and repro in `src/commands/node/restoreTouchEmulation.ts`). Before every // test on the android instance: re-arm the emulation, then assert it actually // holds — the assert is what catches the deeper failure class where the // *mechanism* breaks (provider contextOptions silently ignored, a vitest diff --git a/vite.config.ts b/vite.config.ts index 8bb4cd5042..5081e850c0 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,5 +1,30 @@ import { defineConfig } from "vite-plus"; +// Opt existing suites into the new conventions as they are migrated, rather +// than requiring unrelated legacy tests to change in this PR. +const componentTestFiles = [ + "packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx", + "packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx", +]; +const testIdRestriction = { + property: "getByTestId", + message: + "Use accessible locators such as getByRole with a name or getByLabel in browser tests.", +}; +const testSleepMessage = + "Wait for an observable condition (for example expect.element or expect.poll), not elapsed time. If testing timer behavior itself, document a targeted lint exception."; +const testSleepProperties = [ + { property: "waitForTimeout", message: testSleepMessage }, + { property: "setTimeout", message: testSleepMessage }, + { property: "sleep", message: testSleepMessage }, +]; + export default defineConfig({ staged: { // Format + fast lint (no type-aware) on pre-commit for speed. @@ -66,8 +91,14 @@ export default defineConfig({ }, lint: { plugins: ["typescript", "react", "import"], - // Adds pre-migration ESLint rules with no oxlint equivalents. - jsPlugins: [{ name: "import-eslint", specifier: "eslint-plugin-import" }], + // ESLint compatibility rules and a focused local component-test convention. + jsPlugins: [ + { name: "import-eslint", specifier: "eslint-plugin-import" }, + { + name: "blocknote-tests", + specifier: "./scripts/lint/component-browser-tests.mjs", + }, + ], options: { typeAware: true, typeCheck: true, @@ -100,16 +131,48 @@ export default defineConfig({ }, overrides: [ { - files: ["packages/*/src/**/*.{ts,tsx}"], - excludeFiles: ["**/*.test.{ts,tsx}"], + files: ["**/*.browser.test.{ts,tsx}", "**/*.screen-reader.test.ts"], + rules: { + "no-restricted-properties": ["error", testIdRestriction], + }, + }, + { + files: componentTestFiles, rules: { + "no-restricted-globals": [ + "error", + { name: "setTimeout", message: testSleepMessage }, + ], + "no-restricted-properties": [ + "error", + ...testSleepProperties, + testIdRestriction, + ], "no-restricted-imports": [ "error", { + paths: [ + { + name: "node:timers", + importNames: ["setTimeout"], + message: testSleepMessage, + }, + { + name: "timers", + importNames: ["setTimeout"], + message: testSleepMessage, + }, + { + name: "node:timers/promises", + message: testSleepMessage, + }, + { name: "timers/promises", message: testSleepMessage }, + ], patterns: [ { - group: ["**/*.test", "**/*.test.*"], - message: "Production code must not import test files.", + group: ["**/utils/editor.js", "**/utils/editor"], + importNames: ["sleep"], + message: testSleepMessage, }, ], }, @@ -117,14 +180,25 @@ export default defineConfig({ }, }, { - files: ["**/*.browser.test.{ts,tsx}", "**/*.screen-reader.test.ts"], + // Pilot on the component examples + files: componentTestFiles, rules: { - "no-restricted-properties": [ + "blocknote-tests/component-browser-structure": "error", + }, + }, + { + files: ["packages/*/src/**/*.{ts,tsx}"], + excludeFiles: ["**/*.test.{ts,tsx}"], + rules: { + "no-restricted-imports": [ "error", { - property: "getByTestId", - message: - "Use accessible locators such as getByRole with a name or getByLabel in browser tests.", + patterns: [ + { + group: ["**/*.test", "**/*.test.*"], + message: "Production code must not import test files.", + }, + ], }, ], }, From 59ff20c4fbf79c3fe6d83d366cae5129535dccb4 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Tue, 17 Nov 2026 20:11:53 +0100 Subject: [PATCH 05/14] test: simplify focus capture and screen reader sessions --- .../references/component-testing.md | 2 +- .../src/blocks/Heading/block.browser.test.tsx | 13 ++- .../BasicTextStyleButton.browser.test.tsx | 13 +-- .../ColorStyleButton.browser.test.tsx | 14 ++- .../CreateLinkButton.browser.test.tsx | 13 ++- .../NestBlockButtons.browser.test.tsx | 13 +-- .../TextAlignButton.browser.test.tsx | 13 +-- .../BlockTypeSelect.browser.test.tsx | 14 ++- .../FormattingToolbar.screen-reader.test.ts | 22 ++-- .../src/editor/BlockNoteView.browser.test.tsx | 16 +-- .../BlockNoteView.screen-reader.test.ts | 30 +++--- tests/src/commands/browser/index.ts | 6 +- tests/src/commands/browser/outline.ts | 61 +++++------ .../src/commands/browser/setupScreenReader.ts | 69 ++++++++++++ tests/src/commands/index.ts | 24 ++--- tests/src/commands/node/setupScreenReader.ts | 82 ++++++++++++++ tests/src/commands/transport.ts | 14 ++- tests/src/screen-reader/commands.ts | 7 -- tests/src/screen-reader/screenReader.ts | 101 ------------------ .../vite.config.screen-reader.ts | 5 +- 20 files changed, 263 insertions(+), 269 deletions(-) create mode 100644 tests/src/commands/browser/setupScreenReader.ts create mode 100644 tests/src/commands/node/setupScreenReader.ts delete mode 100644 tests/src/screen-reader/commands.ts delete mode 100644 tests/src/screen-reader/screenReader.ts diff --git a/.claude/skills/testing-skill/references/component-testing.md b/.claude/skills/testing-skill/references/component-testing.md index 2a901d7f6b..2f59e0baa0 100644 --- a/.claude/skills/testing-skill/references/component-testing.md +++ b/.claude/skills/testing-skill/references/component-testing.md @@ -44,7 +44,7 @@ Prefer accessible locators using dictionary labels. Direct focus is valid setup; ## Native screen readers -Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. Register cleanup so the reader stops on failure; consult the command implementations for usage. +Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. `const { getTranscript, pressKey } = await setupScreenReader(locator)` starts a session with automatic cleanup, including on failure. The locator is optional when focus is already established. Use the session's `pressKey` to capture speech, not the ordinary keyboard fixture. This operates the real desktop using VoiceOver/NVDA and GuidePup permissions. Run only as intentional native verification, outside browser CI: diff --git a/packages/core/src/blocks/Heading/block.browser.test.tsx b/packages/core/src/blocks/Heading/block.browser.test.tsx index aae47890d0..821d49d80e 100644 --- a/packages/core/src/blocks/Heading/block.browser.test.tsx +++ b/packages/core/src/blocks/Heading/block.browser.test.tsx @@ -87,8 +87,7 @@ describe("keyboard", () => { page, focusUntil, pressKey, - readFocusOutline, - assertFocusOutline, + captureFocusOutline, }) => { await setupEditor({ initialContent: toggleHeadingDocument, @@ -104,17 +103,17 @@ describe("keyboard", () => { exact: true, }); await expect.element(toggleButton).toBeVisible(); - const unfocusedOutline = readFocusOutline(toggleButton); + const compareFocusOutline = captureFocusOutline(toggleButton); await focusUntil(toggleButton); await expect.element(toggleButton).toHaveFocus(); - await assertFocusOutline(toggleButton, unfocusedOutline); + await compareFocusOutline(toggleButton); await pressKey("Enter"); await expect.element(toggleButton).toHaveFocus(); - await assertFocusOutline(toggleButton, unfocusedOutline); + await compareFocusOutline(toggleButton); await pressKey("Enter"); await expect.element(toggleButton).toHaveFocus(); - await assertFocusOutline(toggleButton, unfocusedOutline); + await compareFocusOutline(toggleButton); await pressKey("Tab"); await expect @@ -122,7 +121,7 @@ describe("keyboard", () => { .toHaveFocus(); await pressKey("Shift+Tab"); await expect.element(toggleButton).toHaveFocus(); - await assertFocusOutline(toggleButton, unfocusedOutline); + await compareFocusOutline(toggleButton); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx index 0c4b084596..66e429fb67 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -197,14 +197,7 @@ describe("BasicTextStyleButton", () => { "shows a keyboard focus ring for %s", async ( style, - { - setupEditor, - selectText, - readFocusOutline, - pressKey, - assertFocusOutline, - page, - }, + { setupEditor, selectText, captureFocusOutline, pressKey, page }, ) => { const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], @@ -217,12 +210,12 @@ describe("BasicTextStyleButton", () => { name: editor.dictionary.formatting_toolbar[style].tooltip, exact: true, }); - const outline = readFocusOutline(button); + const compareFocusOutline = captureFocusOutline(button); await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await assertFocusOutline(button, outline); + await compareFocusOutline(button); }, ); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx index 30c0181fde..42c0a94dc4 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -223,9 +223,8 @@ describe("ColorStyleButton", () => { it("shows a keyboard focus ring on its trigger", async ({ setupEditor, selectText, - readFocusOutline, + captureFocusOutline, pressKey, - assertFocusOutline, page, }) => { const { editor } = await setupEditor({ @@ -239,12 +238,12 @@ describe("ColorStyleButton", () => { name: editor.dictionary.formatting_toolbar.colors.tooltip, exact: true, }); - const outline = readFocusOutline(button); + const compareFocusOutline = captureFocusOutline(button); await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await assertFocusOutline(button, outline); + await compareFocusOutline(button); }); it("chooses a color with the keyboard and returns focus to the editor", async ({ @@ -296,8 +295,7 @@ describe("ColorStyleButton", () => { setupEditor, selectText, pressKey, - readFocusOutline, - assertFocusOutline, + captureFocusOutline, page, }) => { const { editor } = await setupEditor({ @@ -324,12 +322,12 @@ describe("ColorStyleButton", () => { .poll(() => menu.element().contains(document.activeElement)) .toBe(true); const firstItem = menu.getByRole("menuitem").first(); - const outline = readFocusOutline(firstItem); + const compareFocusOutline = captureFocusOutline(firstItem); await pressKey("ArrowDown"); await expect.element(firstItem).toHaveFocus(); - await assertFocusOutline(firstItem, outline); + await compareFocusOutline(firstItem); await pressKey("Escape"); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx index d787b3bdd5..193d3fdef7 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -166,9 +166,8 @@ describe("CreateLinkButton", () => { it("shows a keyboard focus ring on its trigger", async ({ setupEditor, selectText, - readFocusOutline, + captureFocusOutline, pressKey, - assertFocusOutline, page, }) => { const { editor } = await setupEditor({ @@ -183,12 +182,11 @@ describe("CreateLinkButton", () => { exact: true, }); await expect.element(button).toBeVisible(); - const outline = readFocusOutline(button); - + const compareFocusOutline = captureFocusOutline(button); await pressKey("Tab"); + await compareFocusOutline(button); await expect.element(button).toHaveFocus(); - await assertFocusOutline(button, outline); }); // Our Mantine form-popover CSS removes the input border, and there is no @@ -197,7 +195,6 @@ describe("CreateLinkButton", () => { setupEditor, selectText, pressKey, - assertFocusOutline, page, }) => { const { editor } = await setupEditor({ @@ -219,7 +216,9 @@ describe("CreateLinkButton", () => { editor.dictionary.link_toolbar.form.url_placeholder, ); await expect.element(input).toHaveFocus(); - await assertFocusOutline(input); + await expect + .poll(() => getComputedStyle(input.element()).outlineStyle) + .not.toMatch(/^(none|hidden)$/); }); it("opens with Enter and returns focus to its trigger on Escape without editing", async ({ diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx index 86650b80ee..5cccb035f9 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -110,14 +110,7 @@ describe("NestBlockButtons", () => { "activates $direction and returns focus to the editor", async ( { direction, Button }, - { - setupEditor, - selectText, - readFocusOutline, - pressKey, - assertFocusOutline, - page, - }, + { setupEditor, selectText, captureFocusOutline, pressKey, page }, ) => { const { editor } = await setupEditor({ initialContent: @@ -153,12 +146,12 @@ describe("NestBlockButtons", () => { name: editor.dictionary.formatting_toolbar[direction].tooltip, exact: true, }); - const outline = readFocusOutline(button); + const compareFocusOutline = captureFocusOutline(button); await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await assertFocusOutline(button, outline); + await compareFocusOutline(button); await pressKey("Enter"); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx index 82c44f104b..e2c6a74a81 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -185,14 +185,7 @@ describe("TextAlignButton", () => { "shows a keyboard focus ring for %s alignment", async ( alignment, - { - setupEditor, - selectText, - readFocusOutline, - pressKey, - assertFocusOutline, - page, - }, + { setupEditor, selectText, captureFocusOutline, pressKey, page }, ) => { const { editor } = await setupEditor({ initialContent: [{ type: "paragraph", content: "Selected text" }], @@ -206,12 +199,12 @@ describe("TextAlignButton", () => { .tooltip, exact: true, }); - const outline = readFocusOutline(button); + const compareFocusOutline = captureFocusOutline(button); await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await assertFocusOutline(button, outline); + await compareFocusOutline(button); }, ); diff --git a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx index 9d69049cca..dd3e1789de 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -199,9 +199,8 @@ describe("BlockTypeSelect", () => { it("shows a keyboard focus ring on its trigger", async ({ setupEditor, selectText, - readFocusOutline, + captureFocusOutline, pressKey, - assertFocusOutline, page, }) => { const { editor } = await setupEditor({ @@ -215,12 +214,12 @@ describe("BlockTypeSelect", () => { name: editor.dictionary.slash_menu.paragraph.title, exact: true, }); - const outline = readFocusOutline(button); + const compareFocusOutline = captureFocusOutline(button); await pressKey("Tab"); await expect.element(button).toHaveFocus(); - await assertFocusOutline(button, outline); + await compareFocusOutline(button); }); it("dismisses with Escape and restores trigger focus without editing", async ({ @@ -260,8 +259,7 @@ describe("BlockTypeSelect", () => { setupEditor, selectText, pressKey, - readFocusOutline, - assertFocusOutline, + captureFocusOutline, page, }) => { const { editor } = await setupEditor({ @@ -294,7 +292,7 @@ describe("BlockTypeSelect", () => { name: editor.dictionary.slash_menu.heading.title, exact: true, }); - const outline = readFocusOutline(heading); + const compareFocusOutline = captureFocusOutline(heading); await pressKey("ArrowDown"); @@ -303,7 +301,7 @@ describe("BlockTypeSelect", () => { await pressKey("ArrowDown"); await expect.element(heading).toHaveFocus(); - await assertFocusOutline(heading, outline); + await compareFocusOutline(heading); await pressKey("Enter"); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts index 2cceeb03d3..04d371cb62 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts @@ -6,29 +6,18 @@ import { expect } from "vite-plus/test"; // Screen reader announcements do not clearly communicate entering the toolbar. it.skip("announces entering and leaving the formatting toolbar", async ({ setupEditor, - readTranscript, - stopReader, - startReader, - pressKey, + setupScreenReader, page, - onTestFinished, }) => { - onTestFinished(async () => { - try { - const transcript = await readTranscript(); - expect(transcript.length).toBeGreaterThan(0); - expect(transcript).toMatchSnapshot(); - } finally { - await stopReader(); - } - }); const { editor } = await setupEditor({ initialContent: [ { id: "text", type: "paragraph", content: "Selected text" }, ], }); editor.setTextCursorPosition("text", "start"); - await startReader(page.getByRole("textbox").selector); + const { getTranscript, pressKey } = await setupScreenReader( + page.getByRole("textbox"), + ); await pressKey(selectToLineEndKey); await pressKey("Tab"); const toolbar = page.getByRole("toolbar"); @@ -43,4 +32,7 @@ it.skip("announces entering and leaving the formatting toolbar", async ({ await pressKey("Escape"); await expect.element(toolbar).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); + const transcript = await getTranscript(); + expect(transcript.length).toBeGreaterThan(0); + expect(transcript).toMatchSnapshot(); }); diff --git a/packages/react/src/editor/BlockNoteView.browser.test.tsx b/packages/react/src/editor/BlockNoteView.browser.test.tsx index 2fde033e2c..ec687d9906 100644 --- a/packages/react/src/editor/BlockNoteView.browser.test.tsx +++ b/packages/react/src/editor/BlockNoteView.browser.test.tsx @@ -205,8 +205,10 @@ export const defaultSchemaDocument: PartialBlock[] = [ ]; // Keep navigation identical to navigateDefaultSchemaDocumentWithAssertions. -export async function navigateDefaultSchemaDocument() { - await commands.pressKey("Tab"); +export async function navigateDefaultSchemaDocument( + pressKey = commands.pressKey, +) { + await pressKey("Tab"); // Follow the document until its endpoint; an unreachable endpoint times out. const visitedTableCells = new Set(); @@ -218,13 +220,13 @@ export async function navigateDefaultSchemaDocument() { // ArrowDown alone skips columns. Move through cell text and across each // row with ArrowRight, then resume ArrowDown from the final cell. if (tableCell && visitedTableCells.size < 4) { - await commands.pressKey("ArrowRight"); + await pressKey("ArrowRight"); } else { - await commands.pressKey("ArrowDown"); + await pressKey("ArrowDown"); } } while (readDOMSelection().blockId !== "start") { - await commands.pressKey("ArrowUp"); + await pressKey("ArrowUp"); } } @@ -473,12 +475,12 @@ if (!screenReader) { exact: true, }); await expect.element(link).toBeVisible(); - const unfocusedOutline = commands.readFocusOutline(link); + const compareFocusOutline = commands.captureFocusOutline(link); while (document.activeElement !== link.element()) { await commands.pressKey("Tab"); } await expect.element(link).toHaveFocus(); - await commands.assertFocusOutline(link, unfocusedOutline); + await compareFocusOutline(link); return link; } diff --git a/packages/react/src/editor/BlockNoteView.screen-reader.test.ts b/packages/react/src/editor/BlockNoteView.screen-reader.test.ts index de05add4e8..1a0e1d6b69 100644 --- a/packages/react/src/editor/BlockNoteView.screen-reader.test.ts +++ b/packages/react/src/editor/BlockNoteView.screen-reader.test.ts @@ -1,33 +1,27 @@ -import { commands } from "@root/tests/src/utils/context.js"; -import { page } from "vite-plus/test/browser"; -import { afterEach, expect, test } from "vite-plus/test"; +import { expect } from "vite-plus/test"; import { renderTestEditor, navigateDefaultSchemaDocument, defaultSchemaDocument, } from "./BlockNoteView.browser.test.js"; -afterEach(async () => { - try { - const transcript = await commands.readTranscript(); - expect(transcript.length).toBeGreaterThan(0); - expect(transcript).toMatchSnapshot(); - } finally { - await commands.stopReader(); - } -}); - // Navigation announcements omit block types, document structure, and a lot of other markup. -test.skip("default schema: arrow-key document navigation", async () => { +it.skip("default schema: arrow-key document navigation", async ({ + setupScreenReader, + page, +}) => { await renderTestEditor(defaultSchemaDocument); - await commands.startReader( - page.getByRole("button", { name: "Before editor", exact: true }).selector, + const { getTranscript, pressKey } = await setupScreenReader( + page.getByRole("button", { name: "Before editor", exact: true }), ); - await navigateDefaultSchemaDocument(); + await navigateDefaultSchemaDocument(pressKey); + const transcript = await getTranscript(); + expect(transcript.length).toBeGreaterThan(0); + expect(transcript).toMatchSnapshot(); }); // Keyboard whole-block selection is not implemented, so its announcements cannot be tested yet. -test.skip("whole-block selection is announced", async () => { +it.skip("whole-block selection is announced", async () => { // TODO: Once keyboard block selection exists, verify its type and scope are // communicated, and review the transcript before accepting a baseline. // TODO: Text selection, whole-document selection, and non-inline blocks. diff --git a/tests/src/commands/browser/index.ts b/tests/src/commands/browser/index.ts index f723e0215c..796b27ce81 100644 --- a/tests/src/commands/browser/index.ts +++ b/tests/src/commands/browser/index.ts @@ -1,9 +1,5 @@ export { focusUntil } from "./focus.js"; -export { - readFocusOutline, - assertFocusOutline, - type FocusOutline, -} from "./outline.js"; +export { captureFocusOutline } from "./outline.js"; export { runAxe } from "./axe.js"; export { selectText } from "./selectText.js"; export { readAriaSnapshot } from "./ariaSnapshot.js"; diff --git a/tests/src/commands/browser/outline.ts b/tests/src/commands/browser/outline.ts index 0bd596fb0d..4ee2ddceaa 100644 --- a/tests/src/commands/browser/outline.ts +++ b/tests/src/commands/browser/outline.ts @@ -1,21 +1,7 @@ import { expect } from "vite-plus/test"; import type { Locator } from "vite-plus/test/browser"; -export type FocusOutline = { width: number; style: string; color: string }; - -/** - * Reads an element's computed CSS outline without changing focus or asserting. - * Use before keyboard navigation to capture the baseline for {@link assertFocusOutline}; - * use explicit style assertions instead when testing a particular outline value. - * This is synchronous and does not wait for the locator to exist. - * - * @example - * await expect.element(button).toBeVisible(); - * const baseline = readFocusOutline(button); - * await pressKey("Tab"); - * await assertFocusOutline(button, baseline); - */ -export function readFocusOutline(target: Locator): FocusOutline { +function readFocusOutline(target: Locator) { const style = getComputedStyle(target.element()); return { width: Number.parseFloat(style.outlineWidth), @@ -25,38 +11,41 @@ export function readFocusOutline(target: Locator): FocusOutline { } /** - * Asserts `:focus-visible` and a nonzero, non-hidden, nontransparent CSS outline, - * retrying until those conditions hold. With a baseline, also asserts the outline - * changed. Use for a control's keyboard focus indicator after real keyboard input; - * assert focus alone when testing its destination rather than styling. + * Captures an element's unfocused CSS outline and returns a retrying assertion + * that keyboard focus exposes a different, nonzero, non-hidden, nontransparent + * outline and `:focus-visible`. The baseline stays private to the callback. + * Capture before keyboard input; the element must already exist. + * + * The callback defaults to the captured locator, or accepts another locator to + * compare against the same baseline. It can be called repeatedly. * * Does not move focus, measure contrast, check occlusion, or recognize indicators - * implemented only with a border or box-shadow. Omit the baseline when testing - * an input that was autofocused by keyboard activation of a popup. + * implemented only with a border or box-shadow. Assert focus alone when testing + * its destination rather than styling. * * @example - * const baseline = readFocusOutline(button); + * const compareFocusOutline = captureFocusOutline(button); * await pressKey("Tab"); * await expect.element(button).toHaveFocus(); - * await assertFocusOutline(button, baseline); - * - * @example - * await pressKey("Enter"); - * await expect.element(urlInput).toHaveFocus(); - * await assertFocusOutline(urlInput); + * await compareFocusOutline(button); // Or compareFocusOutline() for the same control. */ -export async function assertFocusOutline( +export function captureFocusOutline(target: Locator) { + const unfocusedOutline = readFocusOutline(target); + return async function compareFocusOutline(focusedTarget: Locator = target) { + await assertFocusOutline(focusedTarget, unfocusedOutline); + }; +} + +async function assertFocusOutline( target: Locator, - unfocusedOutline?: FocusOutline, -): Promise { + unfocusedOutline: ReturnType, +) { await expect .poll(() => target.element().matches(":focus-visible")) .toBe(true); - if (unfocusedOutline) { - await expect - .poll(() => readFocusOutline(target)) - .not.toEqual(unfocusedOutline); - } + await expect + .poll(() => readFocusOutline(target)) + .not.toEqual(unfocusedOutline); await expect.poll(() => readFocusOutline(target).width).toBeGreaterThan(0); await expect .poll(() => readFocusOutline(target).style) diff --git a/tests/src/commands/browser/setupScreenReader.ts b/tests/src/commands/browser/setupScreenReader.ts new file mode 100644 index 0000000000..6a42a9e97e --- /dev/null +++ b/tests/src/commands/browser/setupScreenReader.ts @@ -0,0 +1,69 @@ +import type { TestContext } from "vite-plus/test"; +import { commands, type Locator } from "vite-plus/test/browser"; +import type { BrowserCommand } from "vite-plus/test/node"; + +type ReaderTransport = { + [ + Name in keyof typeof import("../node/setupScreenReader.js") + ]: (typeof import("../node/setupScreenReader.js"))[Name] extends BrowserCommand< + infer Args, + infer Result + > + ? (...args: Args) => Promise> + : never; +}; + +// Internal RPC command, not exported as a helper or fixture. Only the session +// below exposes reader interaction, and its lifecycle belongs to this fixture. +const reader = commands as typeof commands & ReaderTransport; + +/** Binds native reader cleanup to the current test; consumed by its fixture. */ +export function createSetupScreenReader( + onFinished: TestContext["onTestFinished"], +) { + /** + * Starts the native screen reader and returns its speech-aware keyboard and + * transcript interface. Cleanup is automatic, including when assertions fail. + * Available only in the native screen-reader runner: this controls the user's + * real desktop reader and foreground browser, not a simulated ARIA tree. + * + * Render first. Supply a locator to focus it during startup, or establish focus + * beforehand and omit it. Use the returned `pressKey` for speech capture; + * the ordinary keyboard fixture does not record announcements. + * + * @example + * const { getTranscript, pressKey } = await setupScreenReader(textbox); + * await pressKey("ArrowDown"); + * const transcript = await getTranscript(); + * expect(transcript.length).toBeGreaterThan(0); + * expect(transcript).toMatchSnapshot(); + */ + async function setupScreenReader(target?: Locator) { + await reader.screenReaderCommand({ + action: "start", + selector: target?.selector, + }); + onFinished(async () => { + await reader.screenReaderCommand({ action: "stop" }); + }); + return { + async getTranscript(this: void) { + const result = await reader.screenReaderCommand({ + action: "getTranscript", + }); + if (result.type !== "transcript") { + throw new Error( + "Screen reader transport did not return a transcript", + ); + } + return result.transcript; + }, + async pressKey(this: void, key: string) { + await reader.screenReaderCommand({ action: "pressKey", key }); + }, + }; + } + return setupScreenReader; +} + +export type SetupScreenReader = ReturnType; diff --git a/tests/src/commands/index.ts b/tests/src/commands/index.ts index 2887f8bae8..cce7d691bb 100644 --- a/tests/src/commands/index.ts +++ b/tests/src/commands/index.ts @@ -2,15 +2,20 @@ import type { TestAPI } from "vite-plus/test"; import * as browserCommands from "./browser/index.js"; import { createSetupEditor, type SetupEditor } from "./browser/setupEditor.js"; +import { + createSetupScreenReader, + type SetupScreenReader, +} from "./browser/setupScreenReader.js"; import { commands as nodeCommands, page } from "./transport.js"; export type CommandContext = Pick< typeof nodeCommands, - keyof typeof import("../screen-reader/commands.js") + keyof typeof import("./node/index.js") > & typeof browserCommands & { page: typeof page; setupEditor: SetupEditor; + setupScreenReader: SetupScreenReader; }; /** Top-level test fixtures; pass this collection to test.extend unchanged. */ @@ -30,27 +35,18 @@ export const commands: Required< restoreTouchEmulation: async ({}, use) => { await use(nodeCommands.restoreTouchEmulation); }, - startReader: async ({}, use) => { - await use(nodeCommands.startReader); - }, - readTranscript: async ({}, use) => { - await use(nodeCommands.readTranscript); - }, - stopReader: async ({}, use) => { - await use(nodeCommands.stopReader); + setupScreenReader: async ({ onTestFinished }, use) => { + await use(createSetupScreenReader(onTestFinished)); }, focusUntil: async ({}, use) => { await use(browserCommands.focusUntil); }, - readFocusOutline: async ({}, use) => { - await use(browserCommands.readFocusOutline); + captureFocusOutline: async ({}, use) => { + await use(browserCommands.captureFocusOutline); }, readAriaSnapshot: async ({}, use) => { await use(browserCommands.readAriaSnapshot); }, - assertFocusOutline: async ({}, use) => { - await use(browserCommands.assertFocusOutline); - }, selectText: async ({}, use) => { await use(browserCommands.selectText); }, diff --git a/tests/src/commands/node/setupScreenReader.ts b/tests/src/commands/node/setupScreenReader.ts new file mode 100644 index 0000000000..37874e815d --- /dev/null +++ b/tests/src/commands/node/setupScreenReader.ts @@ -0,0 +1,82 @@ +import { pressKey } from "./keyboard.js"; +import type { BrowserCommand } from "vite-plus/test/node"; +import type {} from "./positionalMouse.js"; + +type ReaderRequest = + | { action: "start"; selector?: string } + | { action: "pressKey"; key: string } + | { action: "getTranscript" } + | { action: "stop" }; + +type ReaderResponse = + | { type: "complete" } + | { type: "transcript"; transcript: string[] }; + +type CommandContext = Parameters[0]; + +const screenReader = { + async start(context: CommandContext, selector?: string) { + // GuidePup cannot initialize on Linux; load only for an actual native session. + const guidepup = await import("@guidepup/guidepup"); + const reader = guidepup.screenReader; + await reader.start(); + try { + if (process.platform === "darwin") { + await guidepup.macOSActivate("Playwright"); + } else { + await guidepup.windowsActivate( + "chrome.exe", + "Google Chrome for Testing", + ); + } + await context.page.bringToFront(); + const frame = await context.frame(); + if (selector !== undefined) { + await frame.locator(selector).focus(); + } + if (process.platform === "darwin") { + await guidepup.voiceOver.perform( + guidepup.voiceOver.keyboardCommands.moveCursorToKeyboardFocus, + ); + } + await reader.clearSpokenPhraseLog(); + } catch (error) { + await reader.stop(); + throw error; + } + }, + async stop() { + await (await import("@guidepup/guidepup")).screenReader.stop(); + }, + async getTranscript() { + return (await import("@guidepup/guidepup")).screenReader.spokenPhraseLog(); + }, + async pressKey(context: CommandContext, key: string) { + await ( + await import("@guidepup/guidepup") + ).screenReader.capture(() => pressKey(context, key)); + }, +}; + +/** Internal RPC bridge; reader behavior and lifecycle live in the object above. */ +export const screenReaderCommand: BrowserCommand< + [ReaderRequest], + ReaderResponse +> = async (context, request) => { + switch (request.action) { + case "start": + await screenReader.start(context, request.selector); + return { type: "complete" }; + case "pressKey": + await screenReader.pressKey(context, request.key); + return { type: "complete" }; + case "getTranscript": + return { + type: "transcript", + transcript: await screenReader.getTranscript(), + }; + case "stop": + await screenReader.stop(); + return { type: "complete" }; + } +}; diff --git a/tests/src/commands/transport.ts b/tests/src/commands/transport.ts index c281439622..ee624ef9ef 100644 --- a/tests/src/commands/transport.ts +++ b/tests/src/commands/transport.ts @@ -23,6 +23,14 @@ type BrowserCommands = { // Vite+ does not expose the augmentable BrowserCommands interface. Derive the // browser signatures from the implementations, omitting their Node context. -// Reader commands are available only in the native screen-reader configuration. -export const commands = vitestCommands as typeof vitestCommands & - BrowserCommands; +const nodeCommands = vitestCommands as typeof vitestCommands & + BrowserCommands; + +// Expose only shared operations here. Native reader transport stays private to +// setupScreenReader rather than leaking start/stop/transcript methods to tests. +export const commands = { + pressKey: nodeCommands.pressKey, + positionalMouse: nodeCommands.positionalMouse, + imeComposition: nodeCommands.imeComposition, + restoreTouchEmulation: nodeCommands.restoreTouchEmulation, +}; diff --git a/tests/src/screen-reader/commands.ts b/tests/src/screen-reader/commands.ts deleted file mode 100644 index 3e98d52790..0000000000 --- a/tests/src/screen-reader/commands.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from "../commands/node/index.js"; -export { - startReader, - screenReaderPressKey as pressKey, - readTranscript, - stopReader, -} from "./screenReader.js"; diff --git a/tests/src/screen-reader/screenReader.ts b/tests/src/screen-reader/screenReader.ts deleted file mode 100644 index 2651db2f40..0000000000 --- a/tests/src/screen-reader/screenReader.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { pressKey } from "../commands/node/keyboard.js"; -import type { BrowserCommand } from "vite-plus/test/node"; -import type {} from "../commands/node/positionalMouse.js"; - -// Import only on native runs: GuidePup cannot initialize on Linux. -async function reader() { - return (await import("@guidepup/guidepup")).screenReader; -} - -/** - * Starts the native reader, activates the test browser, and focuses the supplied - * selector in the test iframe. Synchronizes VoiceOver's cursor with keyboard - * focus and clears startup speech so the transcript contains only the scenario. - * Available only in the native screen-reader configuration; render first. - * Use only to test actual spoken announcements that browser ARIA/keyboard tests - * cannot prove. This controls the real desktop reader and foreground browser; - * do not use in ordinary Docker browser tests. Register cleanup before starting. - * - * @example - * onTestFinished(async () => { await stopReader(); }); - * await startReader(page.getByRole("textbox").selector); - * await pressKey("ArrowDown"); - * expect((await readTranscript()).length).toBeGreaterThan(0); - */ -export const startReader: BrowserCommand<[selector: string]> = async ( - context, - selector, -) => { - const guidepup = await import("@guidepup/guidepup"); - await guidepup.screenReader.start(); - if (process.platform === "darwin") { - await guidepup.macOSActivate("Playwright"); - } else { - await guidepup.windowsActivate("chrome.exe", "Google Chrome for Testing"); - } - await context.page.bringToFront(); - const frame = await context.frame(); - await frame.locator(selector).focus(); - if (process.platform === "darwin") { - await guidepup.voiceOver.perform( - guidepup.voiceOver.keyboardCommands.moveCursorToKeyboardFocus, - ); - } - await guidepup.screenReader.clearSpokenPhraseLog(); -}; - -/** - * Captures native speech while executing the shared keyboard command, including - * its focus-reconciliation wait. Registered as the top-level {@link pressKey} by the - * native screen-reader configuration, so navigation can be shared with browser - * tests without a separate keyboard helper. - * Use the public {@link pressKey} fixture after {@link startReader}, not this implementation - * directly; use browser tests when no spoken output needs verification. - * - * @example - * await startReader(page.getByRole("textbox").selector); - * await pressKey("Tab"); - * expect((await readTranscript()).length).toBeGreaterThan(0); - */ -export const screenReaderPressKey: BrowserCommand<[key: string]> = async ( - context, - key, -) => { - await (await reader()).capture(() => pressKey(context, key)); -}; - -/** - * Returns the running native reader's spoken phrase log. Assert that it is - * nonempty before comparing it with a Vitest snapshot in the consuming test. - * Reading the log does not stop the reader; cleanup belongs in `finally`. - * Use for real announcement assertions after {@link startReader} and keyboard actions, - * not as a replacement for browser accessibility-tree or focus assertions. - * - * @example - * try { - * const transcript = await readTranscript(); - * expect(transcript.length).toBeGreaterThan(0); - * expect(transcript).toMatchSnapshot(); - * } finally { - * await stopReader(); - * } - */ -export const readTranscript: BrowserCommand<[], string[]> = async () => - (await reader()).spokenPhraseLog(); -/** - * Stops the native reader after a test that started it. Always register cleanup - * before calling {@link startReader}, so assertions failing early do not leave the real - * desktop reader running. Available only in the native screen-reader runner. - * - * @example - * onTestFinished(async () => { - * try { - * const transcript = await readTranscript(); - * expect(transcript.length).toBeGreaterThan(0); - * } finally { - * await stopReader(); - * } - * }); - */ -export const stopReader: BrowserCommand<[]> = async () => - (await reader()).stop(); diff --git a/tests/src/screen-reader/vite.config.screen-reader.ts b/tests/src/screen-reader/vite.config.screen-reader.ts index fdca0d086e..d3b5ac24c1 100644 --- a/tests/src/screen-reader/vite.config.screen-reader.ts +++ b/tests/src/screen-reader/vite.config.screen-reader.ts @@ -1,7 +1,8 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; -import * as commands from "./commands.js"; +import * as commands from "../commands/node/index.js"; +import { screenReaderCommand } from "../commands/node/setupScreenReader.js"; const reader = process.env.BLOCKNOTE_SCREEN_READER; if (reader !== "voiceover" && reader !== "nvda") { @@ -69,7 +70,7 @@ export default defineConfig({ name: reader, }, ], - commands, + commands: { ...commands, screenReaderCommand }, }, }, }); From d4e653467a00a33fe2886adc0be14310b348a458 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 18 Nov 2026 09:08:59 +0100 Subject: [PATCH 06/14] refactor: better selectText result type --- tests/src/commands/browser/selectText.ts | 34 +++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/src/commands/browser/selectText.ts b/tests/src/commands/browser/selectText.ts index 59dcf0ae07..ee47c196d7 100644 --- a/tests/src/commands/browser/selectText.ts +++ b/tests/src/commands/browser/selectText.ts @@ -12,6 +12,12 @@ import { TextSelection } from "@tiptap/pm/state"; * omitting `endBlockId` limits the search to `startBlockId`. Throws for an empty * substring, invalid block range, or missing match so broken setup fails loudly. * + * Returns `collapseToStart()` and `collapseToEnd()` for immediate selection setup. + * They place the cursor at the matched substring's original start/end, even if + * the selection has since moved, and do not focus the editor. They are not + * bookmarks: use them only while the document is unchanged. Calling either after + * a document change throws; call `selectText` again to find a fresh match. + * * @example * const { editor } = await setupEditor({ * initialContent: [{ id: "text", type: "paragraph", content: "Before selected after" }], @@ -22,6 +28,10 @@ import { TextSelection } from "@tiptap/pm/state"; * @example * // Select the occurrence in a particular block, not an earlier duplicate. * selectText(editor, "Repeated text", { startBlockId: "second" }); + * + * @example + * // Put the cursor immediately after the matched text, without focusing. + * selectText(editor, "selected").collapseToEnd(); */ export function selectText( editor: Pick, @@ -31,7 +41,7 @@ export function selectText( if (substring.length === 0) { throw new Error("selectText requires a non-empty substring"); } - editor.transact((tr) => { + const matched = editor.transact((tr) => { let from = 0; let to = tr.doc.content.size; if (range) { @@ -80,5 +90,27 @@ export function selectText( throw new Error(`selectText could not find ${JSON.stringify(substring)}`); } tr.setSelection(TextSelection.create(tr.doc, match.from, match.to)); + return { ...match, doc: tr.doc, selection: tr.selection }; }); + + function collapseTo(position: number) { + editor.transact((tr) => { + if (tr.doc !== matched.doc) { + throw new Error( + "selectText cannot collapse after the document changed; select the text again", + ); + } + tr.setSelection(TextSelection.create(tr.doc, position)); + }); + } + + return { + collapseToStart() { + collapseTo(matched.from); + }, + collapseToEnd() { + collapseTo(matched.to); + }, + selection: matched.selection, + }; } From 3268a82045aacecb878fde330ad47bcb6605fd39 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 18 Nov 2026 09:10:18 +0100 Subject: [PATCH 07/14] docs: slightly stricter rules --- .claude/skills/testing-skill/SKILL.md | 21 ++++++++++++++++++- .../references/component-testing.md | 4 +++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/.claude/skills/testing-skill/SKILL.md b/.claude/skills/testing-skill/SKILL.md index 9ba299c238..616018c38e 100644 --- a/.claude/skills/testing-skill/SKILL.md +++ b/.claude/skills/testing-skill/SKILL.md @@ -18,7 +18,7 @@ Test behavior beside its owner, at the lowest reasonable rung of the test ladder | 5. Mobile-emulated | `end-to-end/mobile/**`, Android browser instance; touch, viewport, emulated IME differences. | | 6. Real device | Only behavior emulation cannot establish; device suite is parked on `mobile/emulator-layer` (PR #3034). | -The ladder guides placement, not a requirement to try every environment. Use a real browser, not jsdom, for clicking, keyboard navigation, focus, or rendered component behavior. Editor/document logic stays in faster Node tests, where `setupEditor` mounts the core editor in jsdom. Rungs 2 and 3 distinguish ownership/location, not strictly runtime cost. +The ladder guides placement, not a requirement to try every environment. Use a real browser for rendered component interactions, actual focus/traversal, and browser-dependent input behavior. Prefer Node/jsdom for editor keyboard shortcut handlers: establish editor state and selection directly, then dispatch a keyboard event, avoiding layout-dependent browser navigation. Editor/document logic also stays in faster Node tests, where `setupEditor` mounts the core editor in jsdom. Rungs 2 and 3 distinguish ownership/location, not strictly runtime cost. Integrations verify boundaries, not repeat dependencies' tests. A parent assumes its children work: test toolbar composition/traversal at the toolbar, button activation at the button, and detailed document operations at their editor commands. @@ -27,6 +27,8 @@ Integrations verify boundaries, not repeat dependencies' tests. A parent assumes - **Cover user-important behavior and applicable categories**, not every branch or state combination. Low-value defensive branches need not be exercised merely for coverage. - **Reported bugs generally warrant regression tests.** Prove regressions red-first against the bug, then green with the fix. Follow TDD for new behavior; modifying existing tests does not require manufacturing another red run. Styling fixes may reasonably lack regression tests when automation is cumbersome or implementation-coupled. - **Use real internal dependencies.** Mock/fake only when necessary, such as external services. Observation-only spies are fine. +- **Use public editor APIs.** Do not reach into `editor._tiptapEditor`. Use `editor.prosemirrorView` when the view is needed; prefer `editor.transact` for current document/selection reads and transactions over `editor.prosemirrorState`. +- **Prefer BlockNote operations over ProseMirror equivalents.** Establish documents with `initialContent`, `insertBlocks`, `updateBlock`, and other BlockNote APIs rather than hand-building internal nodes or mutating transactions when an equivalent exists. Convert blocks to ProseMirror nodes only when the test needs them. - **Distinguish unit from integration by scope.** A function changing block color is a unit contract; clicking a button and checking the editor/UI color change crosses subsystems. - **Arrange → Act → Assert.** Name the outcome, establish the case, exercise the real entry point, and assert its relevant behavior. Repeated act/assert pairs are fine when clearer. Setup APIs must not perform the action the test claims to verify. - **Share understandable conventions.** Prefer `setupEditor` and common mechanics to bespoke setup. Abstract repeated patterns when they improve understanding. Choose inline cases versus `it.for` for readability, not minimum line count. @@ -60,6 +62,23 @@ Use these as patterns, not templates to copy mechanically. For testing a React c Use `const { editor } = await setupEditor({ ...editorOptions })` in either environment. Browser tests receive it from the shared fixture; it renders a view and additionally accepts `skin`, `props`, `children`, and `outside`, returning `rerender` too. Node tests import `test` from `tests/src/fixtures/editor.node.ts` and use the jsdom environment; their helper mounts the core editor without React or skin styles. Both preserve custom-schema types and clean up after the test. For headless logic, use `BlockNoteEditor.create` directly. +`insertBlocks` returns an array of inserted BlockNote blocks. The conversion to a ProseMirror node is `blockToNode`: + +```ts +import { blockToNode } from "@blocknote/core"; + +const [block] = editor.insertBlocks( + [{ type: "paragraph", content: "Inserted text" }], + "existing-block-id", + "after", +); +const node = editor.transact((tr) => + blockToNode(block, tr.doc.type.schema, editor.schema.styleSchema), +); +``` + +For shortcut-handler tests, set up the desired state/selection with editor APIs, then simulate the keyboard event in jsdom. A shared event helper is planned; do not invent a browser navigation journey just to reach the shortcut's starting position. Use a browser when layout, native shortcut handling, or real focus movement is itself the contract. + ## Run Use `vite-plus/test` imports and repository commands: diff --git a/.claude/skills/testing-skill/references/component-testing.md b/.claude/skills/testing-skill/references/component-testing.md index e1659e6002..e44da49d20 100644 --- a/.claude/skills/testing-skill/references/component-testing.md +++ b/.claude/skills/testing-skill/references/component-testing.md @@ -1,6 +1,6 @@ # React component testing -Use a browser when testing clicks, keyboard navigation, focus, or other rendering-dependent behavior. Keep logic that does not need rendering in faster Node tests. +Use a browser for rendered component interactions, actual keyboard traversal/focus, or other rendering-dependent behavior. Test editor keyboard shortcut handlers in Node/jsdom: set state and selection with editor APIs, then dispatch the event. This avoids brittle layout-dependent navigation; use a browser only when browser behavior is the contract. A shared shortcut-event helper is planned. ## Component structure @@ -30,6 +30,8 @@ selectText(editor, "Selected text"); Render the component directly with unrelated default UI disabled, rather than navigating a parent merely to reach it. Use the actual control for the action under test; editor APIs may establish the initial state. +Use BlockNote APIs for that setup instead of equivalent ProseMirror operations. Do not access `editor._tiptapEditor`; use `editor.prosemirrorView` when necessary and prefer `editor.transact` over `editor.prosemirrorState` for reads and transactions. See the [editor setup rules](../SKILL.md#editor-setup) for block-to-node conversion. + Shared rendering handles StrictMode, initial commit, fonts, and cleanup. Wait for later selection-driven UI explicitly. Skin selection defaults to Mantine and loads lazily; loaded CSS remains, so prefer one skin per file. Prefer accessible locators using dictionary labels. Direct focus is valid setup; use real Tab input when traversal is the contract. Wait for observable readiness: a menu can be visible before it receives focus. From 69773361a7e044820c85bc54e2e11cb03b8351fb Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 18 Nov 2026 09:54:46 +0100 Subject: [PATCH 08/14] test: layer editor fixtures by environment --- .../references/component-testing.md | 4 +- tests/docker-run.sh | 1 + tests/src/commands/browser/index.ts | 1 - tests/src/commands/index.ts | 14 +- tests/src/commands/node/compareDocuments.ts | 219 ++++++++++++++++++ tests/src/commands/node/index.ts | 14 +- .../commands/{browser => node}/selectText.ts | 0 .../setupScreenReader.ts | 4 +- .../transport.ts} | 4 +- tests/src/commands/transport.ts | 2 +- .../{node => transport}/imeComposition.ts | 2 +- tests/src/commands/transport/index.ts | 5 + .../commands/{node => transport}/keyboard.ts | 2 +- .../{node => transport}/positionalMouse.ts | 0 .../restoreTouchEmulation.ts | 0 tests/src/fixtures/editor.node.ts | 14 +- tests/src/fixtures/editor.screen-reader.ts | 19 ++ tests/src/fixtures/editor.tsx | 12 +- .../vite.config.screen-reader.ts | 7 +- tests/src/utils/context.ts | 7 +- tests/src/utils/mouse.ts | 2 +- tests/tsconfig.browser.json | 4 +- tests/tsconfig.screen-reader.json | 8 + tests/vite.config.browser.ts | 7 +- tests/vitestSetup.browser-fixtures.ts | 8 + tests/vitestSetup.browser.ts | 8 +- tests/vitestSetup.screen-reader.ts | 7 + tsconfig.json | 1 + 28 files changed, 326 insertions(+), 50 deletions(-) create mode 100644 tests/src/commands/node/compareDocuments.ts rename tests/src/commands/{browser => node}/selectText.ts (100%) rename tests/src/commands/{browser => screen-reader}/setupScreenReader.ts (94%) rename tests/src/commands/{node/setupScreenReader.ts => screen-reader/transport.ts} (95%) rename tests/src/commands/{node => transport}/imeComposition.ts (98%) create mode 100644 tests/src/commands/transport/index.ts rename tests/src/commands/{node => transport}/keyboard.ts (96%) rename tests/src/commands/{node => transport}/positionalMouse.ts (100%) rename tests/src/commands/{node => transport}/restoreTouchEmulation.ts (100%) create mode 100644 tests/src/fixtures/editor.screen-reader.ts create mode 100644 tests/tsconfig.screen-reader.json create mode 100644 tests/vitestSetup.browser-fixtures.ts create mode 100644 tests/vitestSetup.screen-reader.ts diff --git a/.claude/skills/testing-skill/references/component-testing.md b/.claude/skills/testing-skill/references/component-testing.md index e44da49d20..5005a243ee 100644 --- a/.claude/skills/testing-skill/references/component-testing.md +++ b/.claude/skills/testing-skill/references/component-testing.md @@ -17,7 +17,7 @@ Cover relevant categories reasonably, not every possible combination. A child ow ## Setup -Destructure typed helpers from the test context. Find the current listing in [`tests/src/commands/index.ts`](../../../../tests/src/commands/index.ts) and usage documentation beside each implementation. The browser setup supplies the extended global `it`. +Destructure typed helpers from the test context. The [Node fixtures](../../../../tests/src/fixtures/editor.node.ts) provide the baseline editor/document helpers. The [browser fixtures](../../../../tests/src/fixtures/editor.tsx) inherit them, override editor setup with rendering, and add the [browser helpers](../../../../tests/src/commands/index.ts). The browser setup supplies the extended global `it`. Usage documentation lives beside each implementation; Node-only Playwright/CDP transport handlers are registered separately. ```tsx const { editor } = await setupEditor({ @@ -50,7 +50,7 @@ Browser and screen-reader files enforce focused-test, assertion, awaited-poll, f ## Native screen readers -Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. `const { getTranscript, pressKey } = await setupScreenReader(locator)` starts a session with automatic cleanup, including on failure. The locator is optional when focus is already established. Use the session's `pressKey` to capture speech, not the ordinary keyboard fixture. +Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. The native runner installs global `it` from `tests/src/fixtures/editor.screen-reader.ts`; this extends the browser fixtures with `setupScreenReader`, which is not available in ordinary browser tests. The two runners have separate global-type configurations. `const { getTranscript, pressKey } = await setupScreenReader(locator)` starts a session with automatic cleanup, including on failure. The locator is optional when focus is already established. Use the session's `pressKey` to capture speech, not the ordinary keyboard fixture. This operates the real desktop using VoiceOver/NVDA and GuidePup permissions. Run only as intentional native verification, outside browser CI: diff --git a/tests/docker-run.sh b/tests/docker-run.sh index c10eeba65c..83a81d2309 100755 --- a/tests/docker-run.sh +++ b/tests/docker-run.sh @@ -88,6 +88,7 @@ mounts+=( -v "$PWD/tests/public:/work/tests/public" -v "$PWD/tests/vite.config.browser.ts:/work/tests/vite.config.browser.ts" -v "$PWD/tests/vitestSetup.browser.ts:/work/tests/vitestSetup.browser.ts" + -v "$PWD/tests/vitestSetup.browser-fixtures.ts:/work/tests/vitestSetup.browser-fixtures.ts" ) # The suggestion-gallery scenarios import the shared `testDocument` (aliased to # ../shared in vite.config.browser.ts). Only shared/package.json is baked into the diff --git a/tests/src/commands/browser/index.ts b/tests/src/commands/browser/index.ts index 796b27ce81..fa1f1e207f 100644 --- a/tests/src/commands/browser/index.ts +++ b/tests/src/commands/browser/index.ts @@ -1,5 +1,4 @@ export { focusUntil } from "./focus.js"; export { captureFocusOutline } from "./outline.js"; export { runAxe } from "./axe.js"; -export { selectText } from "./selectText.js"; export { readAriaSnapshot } from "./ariaSnapshot.js"; diff --git a/tests/src/commands/index.ts b/tests/src/commands/index.ts index cce7d691bb..ce04ee3799 100644 --- a/tests/src/commands/index.ts +++ b/tests/src/commands/index.ts @@ -2,20 +2,16 @@ import type { TestAPI } from "vite-plus/test"; import * as browserCommands from "./browser/index.js"; import { createSetupEditor, type SetupEditor } from "./browser/setupEditor.js"; -import { - createSetupScreenReader, - type SetupScreenReader, -} from "./browser/setupScreenReader.js"; import { commands as nodeCommands, page } from "./transport.js"; +// Browser-only fixtures extend the baseline in fixtures/editor.node.ts. export type CommandContext = Pick< typeof nodeCommands, - keyof typeof import("./node/index.js") + keyof typeof import("./transport/index.js") > & typeof browserCommands & { page: typeof page; setupEditor: SetupEditor; - setupScreenReader: SetupScreenReader; }; /** Top-level test fixtures; pass this collection to test.extend unchanged. */ @@ -35,9 +31,6 @@ export const commands: Required< restoreTouchEmulation: async ({}, use) => { await use(nodeCommands.restoreTouchEmulation); }, - setupScreenReader: async ({ onTestFinished }, use) => { - await use(createSetupScreenReader(onTestFinished)); - }, focusUntil: async ({}, use) => { await use(browserCommands.focusUntil); }, @@ -47,9 +40,6 @@ export const commands: Required< readAriaSnapshot: async ({}, use) => { await use(browserCommands.readAriaSnapshot); }, - selectText: async ({}, use) => { - await use(browserCommands.selectText); - }, setupEditor: async ({ onTestFinished }, use) => { await use(createSetupEditor(onTestFinished)); }, diff --git a/tests/src/commands/node/compareDocuments.ts b/tests/src/commands/node/compareDocuments.ts new file mode 100644 index 0000000000..b6e272e9a8 --- /dev/null +++ b/tests/src/commands/node/compareDocuments.ts @@ -0,0 +1,219 @@ +/** The structural contract also accepts blocks from custom schemas, unchanged. */ +export type DocumentBlock = { + id: string; + children: readonly DocumentBlock[]; +}; + +export type BlockLocation = { parentId: string | null; index: number }; + +/** JSON Patch operations, with JSON Pointer paths relative to the block. */ +export type FieldChange = + | { op: "add" | "replace"; path: string; value: unknown } + | { op: "remove"; path: string }; + +export type DocumentChange = + | { type: "update"; id: string; changes: FieldChange[] } + | { type: "insert"; block: B; at: BlockLocation } + | { type: "delete"; id: string; at: BlockLocation } + | { type: "move"; id: string; from: BlockLocation; to: BlockLocation }; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function pointerToken(key: string) { + return key.replaceAll("~", "~0").replaceAll("/", "~1"); +} + +/** Diff JSON-shaped data without string normalization or character-level diffs. */ +export function compareValues( + before: unknown, + after: unknown, + path = "", +): FieldChange[] { + if (Object.is(before, after)) { + return []; + } + if (Array.isArray(before) && Array.isArray(after)) { + const changes: FieldChange[] = []; + const commonLength = Math.min(before.length, after.length); + for (let index = 0; index < commonLength; index++) { + changes.push( + ...compareValues(before[index], after[index], `${path}/${index}`), + ); + } + // Descending removals keep these operations valid when applied in order. + for (let index = before.length - 1; index >= after.length; index--) { + changes.push({ op: "remove", path: `${path}/${index}` }); + } + for (let index = commonLength; index < after.length; index++) { + changes.push({ + op: "add", + path: `${path}/${index}`, + value: structuredClone(after[index]), + }); + } + return changes; + } + if (isRecord(before) && isRecord(after)) { + const changes: FieldChange[] = []; + for (const key of Object.keys(before)) { + const childPath = `${path}/${pointerToken(key)}`; + if (!Object.hasOwn(after, key)) { + changes.push({ op: "remove", path: childPath }); + } else { + changes.push(...compareValues(before[key], after[key], childPath)); + } + } + for (const key of Object.keys(after)) { + if (!Object.hasOwn(before, key)) { + changes.push({ + op: "add", + path: `${path}/${pointerToken(key)}`, + value: structuredClone(after[key]), + }); + } + } + return changes; + } + return [{ op: "replace", path, value: structuredClone(after) }]; +} + +function snapshot( + document: readonly B[], +) { + const byId = new Map(); + const siblings = new Map(); + function visit(blocks: readonly B[], parentId: string | null) { + siblings.set( + parentId, + blocks.map((block) => block.id), + ); + blocks.forEach((block, index) => { + if ( + typeof block.id !== "string" || + block.id.length === 0 || + byId.has(block.id) + ) { + throw new Error( + `Document requires unique, nonempty block IDs: ${block.id}`, + ); + } + byId.set(block.id, { block, at: { parentId, index } }); + visit(block.children, block.id); + }); + } + visit(document, null); + return { byId, siblings }; +} + +/** Keep a deterministic longest increasing subsequence; report only the rest. */ +function reordered(before: readonly string[], after: readonly string[]) { + const positions = new Map(before.map((id, index) => [id, index])); + const common = after.filter((id) => positions.has(id)); + const tails: number[] = []; + const ends: number[] = []; + const previous: number[] = []; + common.forEach((id, index) => { + const value = positions.get(id)!; + let low = 0; + let high = tails.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (tails[middle] < value) { + low = middle + 1; + } else { + high = middle; + } + } + previous[index] = low === 0 ? -1 : ends[low - 1]; + tails[low] = value; + ends[low] = index; + }); + const kept = new Set(); + for (let index = ends.at(-1) ?? -1; index !== -1; index = previous[index]) { + kept.add(common[index]); + } + return common.filter((id) => !kept.has(id)); +} + +/** + * Compare final snapshots, not editing activity. Locations refer to the original + * before/after documents, not a sequentially executable global patch. + * + * Insertions/deletions report only roots of newly added/removed subtrees. Insert + * payloads retain the complete, unmodified subtree. Surviving descendants still + * receive moves/updates independently, including when their parent is new/deleted. + * Order: deletes (before preorder), then inserts/moves/updates (after preorder). + * A moved block can also be updated; id/children never appear in field changes. + * Inputs must be JSON-shaped block documents with unique, nonempty IDs. + */ +export function compareDocuments< + B extends { id: string; children: readonly B[] }, +>( + beforeDocument: readonly B[], + afterDocument: readonly B[], +): DocumentChange[] { + const before = snapshot(beforeDocument); + const after = snapshot(afterDocument); + const moved = new Set(); + for (const [parentId, nextOrder] of after.siblings) { + for (const id of reordered( + before.siblings.get(parentId) ?? [], + nextOrder, + )) { + moved.add(id); + } + } + const changes: DocumentChange[] = []; + for (const [id, entry] of before.byId) { + if ( + !after.byId.has(id) && + (entry.at.parentId === null || after.byId.has(entry.at.parentId)) + ) { + changes.push({ type: "delete", id, at: { ...entry.at } }); + } + } + // Walk the typed input for insert payloads, preserving its schema type. + function visit(blocks: readonly B[]) { + for (const block of blocks) { + const next = after.byId.get(block.id)!; + const prev = before.byId.get(block.id); + if (!prev) { + if (next.at.parentId === null || before.byId.has(next.at.parentId)) { + changes.push({ + type: "insert", + block: structuredClone(block), + at: { ...next.at }, + }); + } + } else { + if (prev.at.parentId !== next.at.parentId || moved.has(block.id)) { + changes.push({ + type: "move", + id: block.id, + from: { ...prev.at }, + to: { ...next.at }, + }); + } + const { + id: _beforeId, + children: _beforeChildren, + ...beforeFields + } = prev.block; + const { + id: _afterId, + children: _afterChildren, + ...afterFields + } = block; + const fields = compareValues(beforeFields, afterFields); + if (fields.length) { + changes.push({ type: "update", id: block.id, changes: fields }); + } + } + visit(block.children); + } + } + visit(afterDocument); + return changes; +} diff --git a/tests/src/commands/node/index.ts b/tests/src/commands/node/index.ts index 8e4b246d08..1939bc053b 100644 --- a/tests/src/commands/node/index.ts +++ b/tests/src/commands/node/index.ts @@ -1,5 +1,9 @@ -// Only commands that require Playwright or CDP are registered with Vitest. -export { pressKey } from "./keyboard.js"; -export { positionalMouse } from "./positionalMouse.js"; -export { imeComposition } from "./imeComposition.js"; -export { restoreTouchEmulation } from "./restoreTouchEmulation.js"; +// Baseline helpers run directly in Node/jsdom and in browser tests. +export { compareDocuments } from "./compareDocuments.js"; +export type { + BlockLocation, + DocumentBlock, + DocumentChange, + FieldChange, +} from "./compareDocuments.js"; +export { selectText } from "./selectText.js"; diff --git a/tests/src/commands/browser/selectText.ts b/tests/src/commands/node/selectText.ts similarity index 100% rename from tests/src/commands/browser/selectText.ts rename to tests/src/commands/node/selectText.ts diff --git a/tests/src/commands/browser/setupScreenReader.ts b/tests/src/commands/screen-reader/setupScreenReader.ts similarity index 94% rename from tests/src/commands/browser/setupScreenReader.ts rename to tests/src/commands/screen-reader/setupScreenReader.ts index 6a42a9e97e..c3588a2732 100644 --- a/tests/src/commands/browser/setupScreenReader.ts +++ b/tests/src/commands/screen-reader/setupScreenReader.ts @@ -4,8 +4,8 @@ import type { BrowserCommand } from "vite-plus/test/node"; type ReaderTransport = { [ - Name in keyof typeof import("../node/setupScreenReader.js") - ]: (typeof import("../node/setupScreenReader.js"))[Name] extends BrowserCommand< + Name in keyof typeof import("./transport.js") + ]: (typeof import("./transport.js"))[Name] extends BrowserCommand< infer Args, infer Result > diff --git a/tests/src/commands/node/setupScreenReader.ts b/tests/src/commands/screen-reader/transport.ts similarity index 95% rename from tests/src/commands/node/setupScreenReader.ts rename to tests/src/commands/screen-reader/transport.ts index 37874e815d..395b5c70dd 100644 --- a/tests/src/commands/node/setupScreenReader.ts +++ b/tests/src/commands/screen-reader/transport.ts @@ -1,6 +1,6 @@ -import { pressKey } from "./keyboard.js"; +import { pressKey } from "../transport/keyboard.js"; import type { BrowserCommand } from "vite-plus/test/node"; -import type {} from "./positionalMouse.js"; +import type {} from "../transport/positionalMouse.js"; type ReaderRequest = | { action: "start"; selector?: string } diff --git a/tests/src/commands/transport.ts b/tests/src/commands/transport.ts index ee624ef9ef..044290eed2 100644 --- a/tests/src/commands/transport.ts +++ b/tests/src/commands/transport.ts @@ -24,7 +24,7 @@ type BrowserCommands = { // Vite+ does not expose the augmentable BrowserCommands interface. Derive the // browser signatures from the implementations, omitting their Node context. const nodeCommands = vitestCommands as typeof vitestCommands & - BrowserCommands; + BrowserCommands; // Expose only shared operations here. Native reader transport stays private to // setupScreenReader rather than leaking start/stop/transcript methods to tests. diff --git a/tests/src/commands/node/imeComposition.ts b/tests/src/commands/transport/imeComposition.ts similarity index 98% rename from tests/src/commands/node/imeComposition.ts rename to tests/src/commands/transport/imeComposition.ts index 3bab411554..c19197be2c 100644 --- a/tests/src/commands/node/imeComposition.ts +++ b/tests/src/commands/transport/imeComposition.ts @@ -3,7 +3,7 @@ import type { BrowserCommand } from "vite-plus/test/node"; // eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. import type { userEvent } from "../transport.js"; // eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. -import type { selectText } from "../browser/selectText.js"; +import type { selectText } from "../node/selectText.js"; /** * One step of an emulated IME session. `setComposition` updates the active diff --git a/tests/src/commands/transport/index.ts b/tests/src/commands/transport/index.ts new file mode 100644 index 0000000000..02dd59bba0 --- /dev/null +++ b/tests/src/commands/transport/index.ts @@ -0,0 +1,5 @@ +// Only these Node-only Playwright/CDP handlers are registered with Vitest. +export { pressKey } from "./keyboard.js"; +export { positionalMouse } from "./positionalMouse.js"; +export { imeComposition } from "./imeComposition.js"; +export { restoreTouchEmulation } from "./restoreTouchEmulation.js"; diff --git a/tests/src/commands/node/keyboard.ts b/tests/src/commands/transport/keyboard.ts similarity index 96% rename from tests/src/commands/node/keyboard.ts rename to tests/src/commands/transport/keyboard.ts index 15593b3c49..362d5a239b 100644 --- a/tests/src/commands/node/keyboard.ts +++ b/tests/src/commands/transport/keyboard.ts @@ -3,7 +3,7 @@ import type { BrowserCommand } from "vite-plus/test/node"; // eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. import type { userEvent } from "../transport.js"; // eslint-disable-next-line no-unused-vars -- Type-only import for the JSDoc link. -import type { selectText } from "../browser/selectText.js"; +import type { selectText } from "../node/selectText.js"; declare global { interface Window { diff --git a/tests/src/commands/node/positionalMouse.ts b/tests/src/commands/transport/positionalMouse.ts similarity index 100% rename from tests/src/commands/node/positionalMouse.ts rename to tests/src/commands/transport/positionalMouse.ts diff --git a/tests/src/commands/node/restoreTouchEmulation.ts b/tests/src/commands/transport/restoreTouchEmulation.ts similarity index 100% rename from tests/src/commands/node/restoreTouchEmulation.ts rename to tests/src/commands/transport/restoreTouchEmulation.ts diff --git a/tests/src/fixtures/editor.node.ts b/tests/src/fixtures/editor.node.ts index 6f1f15d87f..609ea0f060 100644 --- a/tests/src/fixtures/editor.node.ts +++ b/tests/src/fixtures/editor.node.ts @@ -1,11 +1,21 @@ -import { test as base } from "vite-plus/test"; +/* eslint-disable no-empty-pattern -- Vitest requires destructured fixture dependencies. */ +import { test as base, type TestAPI } from "vite-plus/test"; +import * as nodeCommands from "../commands/node/index.js"; import { createSetupEditor, type SetupEditor, } from "../commands/node/setupEditor.js"; /** Node fixtures: mounts the core editor in jsdom, without React or skin styles. */ -export const test = base.extend<{ setupEditor: SetupEditor }>({ +export type NodeContext = { setupEditor: SetupEditor } & typeof nodeCommands; + +export const test: TestAPI = base.extend({ + compareDocuments: async ({}, use) => { + await use(nodeCommands.compareDocuments); + }, + selectText: async ({}, use) => { + await use(nodeCommands.selectText); + }, setupEditor: async ({ onTestFinished }, use) => { await use(createSetupEditor(onTestFinished)); }, diff --git a/tests/src/fixtures/editor.screen-reader.ts b/tests/src/fixtures/editor.screen-reader.ts new file mode 100644 index 0000000000..52c321c54a --- /dev/null +++ b/tests/src/fixtures/editor.screen-reader.ts @@ -0,0 +1,19 @@ +import type { TestAPI } from "vite-plus/test"; +import { test as base, type BrowserContext } from "./editor.js"; +import { + createSetupScreenReader, + type SetupScreenReader, +} from "../commands/screen-reader/setupScreenReader.js"; + +/** Native-reader sessions are available only to this browser-fixture extension. */ +export type ScreenReaderContext = BrowserContext & { + setupScreenReader: SetupScreenReader; +}; + +export const test: TestAPI = base.extend<{ + setupScreenReader: SetupScreenReader; +}>({ + setupScreenReader: async ({ onTestFinished }, use) => { + await use(createSetupScreenReader(onTestFinished)); + }, +}); diff --git a/tests/src/fixtures/editor.tsx b/tests/src/fixtures/editor.tsx index 385f899d6a..e4deff827f 100644 --- a/tests/src/fixtures/editor.tsx +++ b/tests/src/fixtures/editor.tsx @@ -1,10 +1,8 @@ -import { test as base } from "vite-plus/test"; +import type { TestAPI } from "vite-plus/test"; +import { test as base, type NodeContext } from "./editor.node.js"; import { commands, type CommandContext } from "../commands/index.js"; -export const test = base.extend(commands); +export type BrowserContext = Omit & CommandContext; -// The browser setup installs this extended API; imported Vitest APIs are not -// extended. tests/tsconfig.browser.json includes the setup for colocated tests. -declare global { - var it: typeof test; -} +export const test: TestAPI = + base.extend(commands); diff --git a/tests/src/screen-reader/vite.config.screen-reader.ts b/tests/src/screen-reader/vite.config.screen-reader.ts index d3b5ac24c1..8e67be5ae4 100644 --- a/tests/src/screen-reader/vite.config.screen-reader.ts +++ b/tests/src/screen-reader/vite.config.screen-reader.ts @@ -1,8 +1,8 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; -import * as commands from "../commands/node/index.js"; -import { screenReaderCommand } from "../commands/node/setupScreenReader.js"; +import * as commands from "../commands/transport/index.js"; +import { screenReaderCommand } from "../commands/screen-reader/transport.js"; const reader = process.env.BLOCKNOTE_SCREEN_READER; if (reader !== "voiceover" && reader !== "nvda") { @@ -37,6 +37,9 @@ export default defineConfig({ name: "screen-reader", setupFiles: [ fileURLToPath(new URL("../../vitestSetup.browser.ts", import.meta.url)), + fileURLToPath( + new URL("../../vitestSetup.screen-reader.ts", import.meta.url), + ), ], include: ["../packages/*/src/**/*.screen-reader.test.ts"], testTimeout: 300_000, diff --git a/tests/src/utils/context.ts b/tests/src/utils/context.ts index c7407a6acd..26a78f571d 100644 --- a/tests/src/utils/context.ts +++ b/tests/src/utils/context.ts @@ -2,10 +2,15 @@ import { server } from "../commands/transport.js"; export { page, server, userEvent } from "../commands/transport.js"; import * as browserCommands from "../commands/browser/index.js"; +import * as baselineCommands from "../commands/node/index.js"; import { commands as nodeCommands } from "../commands/transport.js"; // Compatibility for existing suites; extended tests use top-level fixtures. -export const commands = { ...nodeCommands, ...browserCommands }; +export const commands = { + ...baselineCommands, + ...nodeCommands, + ...browserCommands, +}; /** The browser instance the current test is running in. */ export const browserName = server.browser as "chromium" | "firefox" | "webkit"; diff --git a/tests/src/utils/mouse.ts b/tests/src/utils/mouse.ts index 8733f8dc1c..f50755031c 100644 --- a/tests/src/utils/mouse.ts +++ b/tests/src/utils/mouse.ts @@ -1,7 +1,7 @@ import { commands } from "./context.js"; import { DRAG_HANDLE_SELECTOR } from "./const.js"; import { sleep, waitForSelector } from "./editor.js"; -import type { MouseAction } from "../commands/node/positionalMouse.js"; +import type { MouseAction } from "../commands/transport/positionalMouse.js"; function runMouse(actions: MouseAction[]): Promise { return commands.positionalMouse(...actions); diff --git a/tests/tsconfig.browser.json b/tests/tsconfig.browser.json index 917e1bbe5c..3be3c407a1 100644 --- a/tests/tsconfig.browser.json +++ b/tests/tsconfig.browser.json @@ -25,7 +25,7 @@ "src/utils/**/*.tsx", "src/fixtures/**/*.tsx", "vitestSetup.browser.ts", - "../packages/*/src/**/*.browser.test.*", - "../packages/*/src/**/*.screen-reader.test.ts" + "vitestSetup.browser-fixtures.ts", + "../packages/*/src/**/*.browser.test.*" ] } diff --git a/tests/tsconfig.screen-reader.json b/tests/tsconfig.screen-reader.json new file mode 100644 index 0000000000..d53ae0f51c --- /dev/null +++ b/tests/tsconfig.screen-reader.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.browser.json", + "include": [ + "vitestSetup.browser.ts", + "vitestSetup.screen-reader.ts", + "../packages/*/src/**/*.screen-reader.test.ts" + ] +} diff --git a/tests/vite.config.browser.ts b/tests/vite.config.browser.ts index 5b6b688b70..6dbe5a9b83 100644 --- a/tests/vite.config.browser.ts +++ b/tests/vite.config.browser.ts @@ -3,7 +3,7 @@ import * as fs from "fs"; import * as path from "path"; import { configDefaults, defineConfig, type UserConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; -import * as commands from "./src/commands/node/index.js"; +import * as commands from "./src/commands/transport/index.js"; // For the desktop instances: end-to-end/mobile runs only in the "android" // instance. An instance-level `exclude` replaces the resolved base exclude @@ -120,7 +120,10 @@ export default defineConfig( "../packages/*/src/**/*.screen-reader.test.ts", ], - setupFiles: ["./vitestSetup.browser.ts"], + setupFiles: [ + "./vitestSetup.browser.ts", + "./vitestSetup.browser-fixtures.ts", + ], // Running three browsers concurrently inside one Docker container already // saturates CPU; layering per-browser file parallelism on top causes // 15s test timeouts and even Firefox WS-connect failures. One worker per diff --git a/tests/vitestSetup.browser-fixtures.ts b/tests/vitestSetup.browser-fixtures.ts new file mode 100644 index 0000000000..79e4e8bdda --- /dev/null +++ b/tests/vitestSetup.browser-fixtures.ts @@ -0,0 +1,8 @@ +import { test } from "./src/fixtures/editor.js"; + +// Imported Vitest APIs stay unchanged; only global `it` receives these fixtures. +globalThis.it = test; + +declare global { + var it: typeof test; +} diff --git a/tests/vitestSetup.browser.ts b/tests/vitestSetup.browser.ts index 706ccd01c2..5c4c4ddaf6 100644 --- a/tests/vitestSetup.browser.ts +++ b/tests/vitestSetup.browser.ts @@ -1,13 +1,9 @@ -import type {} from "./src/commands/node/keyboard.js"; +import type {} from "./src/commands/transport/keyboard.js"; import { afterEach, beforeAll, beforeEach } from "vite-plus/test"; import { commands, page } from "./src/utils/context.js"; -import { test } from "./src/fixtures/editor.js"; import { ensureTouchEmulation } from "./src/utils/ensureTouchEmulation.js"; -// Only the global `it` uses these fixtures; imported Vitest APIs stay unchanged. -globalThis.it = test; - // Browser-mode setup. Unlike the jsdom `vitestSetup.ts`, we don't mock // ClipboardEvent/DragEvent/matchMedia here — the real browser provides them. // We only seed the `window.__TEST_OPTIONS` object that examples read from @@ -58,7 +54,7 @@ beforeAll(async () => { // Chromium drops the context's touch emulation after any screenshot captured // beyond the viewport, which on this mobile context is every element // screenshot, and Playwright never re-arms it (microsoft/playwright#42607; -// mechanism and repro in `src/commands/node/restoreTouchEmulation.ts`). Before every +// mechanism and repro in `src/commands/transport/restoreTouchEmulation.ts`). Before every // test on the android instance: re-arm the emulation, then assert it actually // holds — the assert is what catches the deeper failure class where the // *mechanism* breaks (provider contextOptions silently ignored, a vitest diff --git a/tests/vitestSetup.screen-reader.ts b/tests/vitestSetup.screen-reader.ts new file mode 100644 index 0000000000..21a757821b --- /dev/null +++ b/tests/vitestSetup.screen-reader.ts @@ -0,0 +1,7 @@ +import { test } from "./src/fixtures/editor.screen-reader.js"; + +globalThis.it = test; + +declare global { + var it: typeof test; +} diff --git a/tsconfig.json b/tsconfig.json index 8e5af666b1..6c140929e7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "files": [], "references": [ { "path": "./tests/tsconfig.browser.json" }, + { "path": "./tests/tsconfig.screen-reader.json" }, { "path": "./packages/core" }, { "path": "./packages/code-block" }, { "path": "./packages/react" }, From 8564fc34a9707242b243262d868c52ab0fe0838a Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 18 Nov 2026 14:25:52 +0100 Subject: [PATCH 09/14] test: refine document assertions and testing categories --- .../src/blocks/Heading/block.browser.test.tsx | 90 ++-- .../BasicTextStyleButton.browser.test.tsx | 199 +++++--- .../ColorStyleButton.browser.test.tsx | 477 ++++++++++++------ .../CreateLinkButton.browser.test.tsx | 250 +++++---- .../NestBlockButtons.browser.test.tsx | 217 ++++---- .../TextAlignButton.browser.test.tsx | 215 ++++---- ...BasicTextStyleButton.browser.test.tsx.snap | 211 -------- .../BlockTypeSelect.browser.test.tsx | 343 +++++++------ .../FormattingToolbar.browser.test.tsx | 78 +-- .../FormattingToolbar.screen-reader.test.ts | 2 +- .../src/editor/BlockNoteView.browser.test.tsx | 143 +++--- scripts/lint/README.md | 7 +- scripts/lint/component-browser-tests.mjs | 4 +- scripts/lint/component-browser-tests.test.mjs | 30 +- tests/src/commands/browser/environment.ts | 4 + tests/src/commands/browser/index.ts | 3 + tests/src/commands/browser/keyboard.ts | 9 + tests/src/commands/browser/screenshotFull.ts | 61 +++ tests/src/commands/index.ts | 10 +- tests/src/commands/node/setupEditor.ts | 2 - .../vite.config.screen-reader.ts | 1 - tests/src/utils/context.ts | 20 +- tests/src/utils/screenshotFull.ts | 54 +- tests/tsconfig.browser.json | 1 - tests/vite.config.browser.ts | 1 - 25 files changed, 1298 insertions(+), 1134 deletions(-) delete mode 100644 packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap create mode 100644 tests/src/commands/browser/environment.ts create mode 100644 tests/src/commands/browser/keyboard.ts create mode 100644 tests/src/commands/browser/screenshotFull.ts diff --git a/packages/core/src/blocks/Heading/block.browser.test.tsx b/packages/core/src/blocks/Heading/block.browser.test.tsx index 821d49d80e..a0cacc6b66 100644 --- a/packages/core/src/blocks/Heading/block.browser.test.tsx +++ b/packages/core/src/blocks/Heading/block.browser.test.tsx @@ -32,7 +32,7 @@ afterEach(() => { localStorage.removeItem("toggle-read-only-toggle-heading"); }); -describe("behavior", () => { +describe("integration", () => { it("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async ({ setupEditor, page, @@ -68,6 +68,50 @@ describe("behavior", () => { }); }); +describe("aria", () => { + it("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async ({ + setupEditor, + page, + focusUntil, + pressKey, + }) => { + await setupEditor({ + initialContent: toggleHeadingDocument, + props: { editable: false, theme: "light" }, + outside, + }); + page + .getByRole("button", { name: "Before editor", exact: true }) + .element() + .focus(); + await focusUntil( + page.getByRole("button", { + name: "Expand or collapse", + exact: true, + }), + ); + const editor = page.getByRole("textbox"); + await expect.element(editor).toMatchAriaInlineSnapshot(` + - textbox: + - button "Expand or collapse" + - heading "Details" [level=2] + `); + await pressKey("Enter"); + await expect.element(editor).toMatchAriaInlineSnapshot(` + - textbox: + - button "Expand or collapse" [expanded] + - heading "Details" [level=2] + - paragraph: Nested read-only content + `); + await pressKey("Enter"); + await expect.element(editor).toMatchAriaInlineSnapshot(` + - textbox: + - button "Expand or collapse" + - heading "Details" [level=2] + `); + }); +}); + describe("keyboard", () => { // Toggle headings represent interactive blocks in this accessibility vertical slice. // Keyboard access to toggle controls from within an editable block is not implemented. @@ -124,47 +168,3 @@ describe("keyboard", () => { await compareFocusOutline(toggleButton); }); }); - -describe("a11y", () => { - it("read-only toggle heading: Tab reaches the toggle and Enter expands/collapses it", async ({ - setupEditor, - page, - focusUntil, - pressKey, - }) => { - await setupEditor({ - initialContent: toggleHeadingDocument, - props: { editable: false, theme: "light" }, - outside, - }); - page - .getByRole("button", { name: "Before editor", exact: true }) - .element() - .focus(); - await focusUntil( - page.getByRole("button", { - name: "Expand or collapse", - exact: true, - }), - ); - const editor = page.getByRole("textbox"); - await expect.element(editor).toMatchAriaInlineSnapshot(` - - textbox: - - button "Expand or collapse" - - heading "Details" [level=2] - `); - await pressKey("Enter"); - await expect.element(editor).toMatchAriaInlineSnapshot(` - - textbox: - - button "Expand or collapse" [expanded] - - heading "Details" [level=2] - - paragraph: Nested read-only content - `); - await pressKey("Enter"); - await expect.element(editor).toMatchAriaInlineSnapshot(` - - textbox: - - button "Expand or collapse" - - heading "Details" [level=2] - `); - }); -}); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx index 66e429fb67..2dcec23276 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -92,28 +92,47 @@ describe("BasicTextStyleButton", () => { describe("integration", () => { it.for(STYLES)( "toggles %s on and off", - async (basicTextStyle, { setupEditor, selectText, page }) => { + async ( + basicTextStyle, + { setupEditor, selectText, compareDocuments, page }, + ) => { const { editor } = await setupEditor({ initialContent: [ { id: "format", type: "paragraph", content: "Format this text" }, ], - // To test just the button, we don't even need the toolbar - // the button reads the editor context directly + // The button reads editor context directly; no toolbar is needed. props: { formattingToolbar: false }, children: , }); - selectText(editor, "Format this text"); - const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, exact: true, }); for (const state of ["on", "off"] as const) { + const before = editor.document; + await button.click(); - expect(editor.getBlock("format")).toMatchSnapshot(state); + expect(compareDocuments(before, editor.document)).toEqual([ + { + type: "update", + id: "format", + changes: [ + state === "on" + ? { + op: "add", + path: `/content/0/styles/${basicTextStyle}`, + value: true, + } + : { + op: "remove", + path: `/content/0/styles/${basicTextStyle}`, + }, + ], + }, + ]); await expect .element(button) .toHaveAttribute("aria-pressed", String(state === "on")); @@ -123,7 +142,10 @@ describe("BasicTextStyleButton", () => { it.for(STYLES)( "applies %s only to selected text without changing surrounding content", - async (basicTextStyle, { setupEditor, selectText, page }) => { + async ( + basicTextStyle, + { setupEditor, selectText, compareDocuments, page }, + ) => { const { editor } = await setupEditor({ initialContent: [ { @@ -142,6 +164,7 @@ describe("BasicTextStyleButton", () => { children: , }); selectText(editor, "selected"); + const before = editor.document; const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, exact: true, @@ -149,25 +172,43 @@ describe("BasicTextStyleButton", () => { await button.click(); - expect(editor.getBlock("format")?.content).toEqual([ - { type: "text", text: "Before ", styles: { textColor: "red" } }, + expect(compareDocuments(before, editor.document)).toEqual([ { - type: "text", - text: "selected", - // Inline code excludes other formatting styles. - styles: - basicTextStyle === "code" - ? { code: true } - : { textColor: "red", [basicTextStyle]: true }, + type: "update", + id: "format", + changes: [ + { op: "replace", path: "/content/0/text", value: "Before " }, + { + op: "add", + path: "/content/1", + value: { + type: "text", + text: "selected", + // Inline code excludes other formatting styles. + styles: + basicTextStyle === "code" + ? { code: true } + : { textColor: "red", [basicTextStyle]: true }, + }, + }, + { + op: "add", + path: "/content/2", + value: { + type: "text", + text: " after", + styles: { textColor: "red" }, + }, + }, + ], }, - { type: "text", text: " after", styles: { textColor: "red" } }, ]); }, ); it.for(STYLES)( "applies %s to subsequently typed text at a collapsed cursor", - async (basicTextStyle, { setupEditor, page }) => { + async (basicTextStyle, { setupEditor, compareDocuments, page }) => { const { editor } = await setupEditor({ initialContent: [ { id: "format", type: "paragraph", content: "Existing" }, @@ -176,6 +217,7 @@ describe("BasicTextStyleButton", () => { children: , }); editor.setTextCursorPosition("format", "end"); + const before = editor.document; const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, exact: true, @@ -184,14 +226,79 @@ describe("BasicTextStyleButton", () => { await button.click(); await userEvent.keyboard(" typed"); - expect(editor.getBlock("format")?.content).toEqual([ - { type: "text", text: "Existing", styles: {} }, - { type: "text", text: " typed", styles: { [basicTextStyle]: true } }, + expect(compareDocuments(before, editor.document)).toEqual([ + { + type: "update", + id: "format", + changes: [ + { + op: "add", + path: "/content/1", + value: { + type: "text", + text: " typed", + styles: { [basicTextStyle]: true }, + }, + }, + ], + }, ]); }, ); }); + describe("aria", () => { + it("reflects the active style when selection moves between blocks", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + id: "styled", + type: "paragraph", + content: [{ type: "text", text: "Bold", styles: { bold: true } }], + }, + { id: "plain", type: "paragraph", content: "Plain" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { name: "Bold", exact: true }); + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + + selectText(editor, "Plain"); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + selectText(editor, "Bold"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); + }); + + describe("axe", () => { + it("checks all supported style buttons", async ({ + setupEditor, + runAxe, + page, + }) => { + await setupEditor({ + props: { formattingToolbar: false }, + children: ( + + {STYLES.map((style) => ( + + ))} + + ), + }); + + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); + }); + }); + describe("keyboard", () => { it.for(STYLES)( "shows a keyboard focus ring for %s", @@ -245,54 +352,4 @@ describe("BasicTextStyleButton", () => { }, ); }); - - describe("a11y", () => { - it("reflects the active style when selection moves between blocks", async ({ - setupEditor, - selectText, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { - id: "styled", - type: "paragraph", - content: [{ type: "text", text: "Bold", styles: { bold: true } }], - }, - { id: "plain", type: "paragraph", content: "Plain" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { name: "Bold", exact: true }); - selectText(editor, "Bold"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - - selectText(editor, "Plain"); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); - - selectText(editor, "Bold"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - }); - - it("checks all supported style buttons", async ({ - setupEditor, - runAxe, - page, - }) => { - await setupEditor({ - props: { formattingToolbar: false }, - children: ( - - {STYLES.map((style) => ( - - ))} - - ), - }); - - const { violations } = await runAxe(page.getByRole("toolbar")); - expect(violations).toEqual([]); - }); - }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx index 42c0a94dc4..6e0310edca 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -135,209 +135,254 @@ describe("ColorStyleButton", () => { }); describe("integration", () => { - it.for(["textColor", "backgroundColor"] as const)( - "applies %s only to the selected substring", - async (style, { setupEditor, selectText, page }) => { - const { editor } = await setupEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Before selected after" }, - ], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "selected"); - - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.colors.tooltip, - exact: true, - }); - await button.click(); - - await page - .getByRole("menuitem", { - name: editor.dictionary.color_picker.colors.gray, - }) - .nth(style === "textColor" ? 0 : 1) - .click(); - - expect(editor.getBlock("text")?.content).toEqual([ - { type: "text", text: "Before ", styles: {} }, - { type: "text", text: "selected", styles: { [style]: "gray" } }, - { type: "text", text: " after", styles: {} }, - ]); - await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - }, - ); - - it.for(["textColor", "backgroundColor"] as const)( - "resets %s without removing the other color", - async (style, { setupEditor, selectText, page }) => { - const { editor } = await setupEditor({ - initialContent: [ - { - id: "text", - type: "paragraph", - content: [ - { - type: "text", - text: "Selected text", - styles: { textColor: "gray", backgroundColor: "gray" }, - }, - ], - }, - ], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - - await page - .getByRole("button", { - name: editor.dictionary.formatting_toolbar.colors.tooltip, - exact: true, - }) - .click(); - await page - .getByRole("menuitem", { - name: editor.dictionary.color_picker.colors.default, - }) - .nth(style === "textColor" ? 0 : 1) - .click(); - - expect(editor.getBlock("text")?.content).toEqual([ - { - type: "text", - text: "Selected text", - styles: - style === "textColor" - ? { backgroundColor: "gray" } - : { textColor: "gray" }, - }, - ]); - }, - ); - }); - - describe("keyboard", () => { - it("shows a keyboard focus ring on its trigger", async ({ + it("applies textColor only to the selected substring", async ({ setupEditor, selectText, - captureFocusOutline, - pressKey, + compareDocuments, page, }) => { const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], + initialContent: [ + { id: "text", type: "paragraph", content: "Before selected after" }, + ], props: { formattingToolbar: false }, children: , }); - await page.getByRole("textbox").click(); - selectText(editor, "Selected text"); + selectText(editor, "selected"); + const before = editor.document; + const button = page.getByRole("button", { name: editor.dictionary.formatting_toolbar.colors.tooltip, exact: true, }); - const compareFocusOutline = captureFocusOutline(button); + await button.click(); - await pressKey("Tab"); + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .nth(0) + .click(); - await expect.element(button).toHaveFocus(); - await compareFocusOutline(button); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/content/0/text", + "value": "Before ", + }, + { + "op": "add", + "path": "/content/1", + "value": { + "styles": { + "textColor": "gray", + }, + "text": "selected", + "type": "text", + }, + }, + { + "op": "add", + "path": "/content/2", + "value": { + "styles": {}, + "text": " after", + "type": "text", + }, + }, + ], + "id": "text", + "type": "update", + }, + ] + `); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); }); - it("chooses a color with the keyboard and returns focus to the editor", async ({ + it("applies backgroundColor only to the selected substring", async ({ setupEditor, selectText, - pressKey, + compareDocuments, page, }) => { const { editor } = await setupEditor({ initialContent: [ - { id: "text", type: "paragraph", content: "Selected text" }, + { id: "text", type: "paragraph", content: "Before selected after" }, ], props: { formattingToolbar: false }, children: , }); - selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.colors.tooltip, - exact: true, - }); - button.element().focus(); + selectText(editor, "selected"); + const before = editor.document; - await pressKey("Enter"); - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - await expect - .poll(() => menu.element().contains(document.activeElement)) - .toBe(true); - await pressKey("ArrowDown"); - await pressKey("ArrowDown"); - - await expect - .element( - menu - .getByRole("menuitem", { - name: editor.dictionary.color_picker.colors.gray, - }) - .first(), - ) - .toHaveFocus(); - - await pressKey("Enter"); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .nth(1) + .click(); - await expect.element(menu).not.toBeInTheDocument(); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/content/0/text", + "value": "Before ", + }, + { + "op": "add", + "path": "/content/1", + "value": { + "styles": { + "backgroundColor": "gray", + }, + "text": "selected", + "type": "text", + }, + }, + { + "op": "add", + "path": "/content/2", + "value": { + "styles": {}, + "text": " after", + "type": "text", + }, + }, + ], + "id": "text", + "type": "update", + }, + ] + `); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); - expect(editor.getActiveStyles().textColor).toBe("gray"); }); - it("supports opening, navigating, and dismissing its menu without editing the document", async ({ + + it("resets textColor without removing the other color", async ({ setupEditor, selectText, - pressKey, - captureFocusOutline, + compareDocuments, page, }) => { const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], + initialContent: [ + { + id: "text", + type: "paragraph", + content: [ + { + type: "text", + text: "Selected text", + styles: { textColor: "gray", backgroundColor: "gray" }, + }, + ], + }, + ], props: { formattingToolbar: false }, children: , }); selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.colors.tooltip, - exact: true, - }); - const documentBefore = editor.document; - - button.element().focus(); - - await expect.element(button).toHaveFocus(); - - await pressKey("Enter"); + const before = editor.document; - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - await expect - .poll(() => menu.element().contains(document.activeElement)) - .toBe(true); - const firstItem = menu.getByRole("menuitem").first(); - const compareFocusOutline = captureFocusOutline(firstItem); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.default, + }) + .nth(0) + .click(); - await pressKey("ArrowDown"); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "remove", + "path": "/content/0/styles/textColor", + }, + ], + "id": "text", + "type": "update", + }, + ] + `); + }); - await expect.element(firstItem).toHaveFocus(); - await compareFocusOutline(firstItem); + it("resets backgroundColor without removing the other color", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: [ + { + type: "text", + text: "Selected text", + styles: { textColor: "gray", backgroundColor: "gray" }, + }, + ], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const before = editor.document; - await pressKey("Escape"); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + await page + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.default, + }) + .nth(1) + .click(); - await expect.element(menu).not.toBeInTheDocument(); - await expect.element(button).toHaveFocus(); - expect(editor.document).toEqual(documentBefore); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "remove", + "path": "/content/0/styles/backgroundColor", + }, + ], + "id": "text", + "type": "update", + }, + ] + `); }); }); - describe("a11y", () => { + describe("aria", () => { it("exposes the menu trigger's expanded state and relationship", async ({ setupEditor, selectText, @@ -406,7 +451,9 @@ describe("ColorStyleButton", () => { ); expect(after).not.toBe(before); }); + }); + describe("axe", () => { it("checks the color trigger", async ({ setupEditor, runAxe, page }) => { await setupEditor({ props: { formattingToolbar: false }, @@ -482,4 +529,122 @@ describe("ColorStyleButton", () => { } }); }); + + describe("keyboard", () => { + it("shows a keyboard focus ring on its trigger", async ({ + setupEditor, + selectText, + captureFocusOutline, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + const compareFocusOutline = captureFocusOutline(button); + + await pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await compareFocusOutline(button); + }); + + it("chooses a color with the keyboard and returns focus to the editor", async ({ + setupEditor, + selectText, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + button.element().focus(); + + await pressKey("Enter"); + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + await pressKey("ArrowDown"); + await pressKey("ArrowDown"); + + await expect + .element( + menu + .getByRole("menuitem", { + name: editor.dictionary.color_picker.colors.gray, + }) + .first(), + ) + .toHaveFocus(); + + await pressKey("Enter"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + expect(editor.getActiveStyles().textColor).toBe("gray"); + }); + it("supports opening, navigating, and dismissing its menu without editing the document", async ({ + setupEditor, + selectText, + pressKey, + captureFocusOutline, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }); + const documentBefore = editor.document; + + button.element().focus(); + + await expect.element(button).toHaveFocus(); + + await pressKey("Enter"); + + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + const firstItem = menu.getByRole("menuitem").first(); + const compareFocusOutline = captureFocusOutline(firstItem); + + await pressKey("ArrowDown"); + + await expect.element(firstItem).toHaveFocus(); + await compareFocusOutline(firstItem); + + await pressKey("Escape"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect.element(button).toHaveFocus(); + expect(editor.document).toEqual(documentBefore); + }); + }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx index 193d3fdef7..96c4374cc7 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -80,6 +80,7 @@ describe("CreateLinkButton", () => { it("submits a link for the original substring and returns focus to the editor", async ({ setupEditor, selectText, + compareDocuments, pressKey, page, }) => { @@ -95,6 +96,7 @@ describe("CreateLinkButton", () => { children: , }); selectText(editor, "selected text"); + const before = editor.document; await page .getByRole("button", { name: editor.dictionary.formatting_toolbar.link.tooltip, @@ -108,15 +110,45 @@ describe("CreateLinkButton", () => { await input.fill("https://example.com"); await pressKey("Enter"); - expect(editor.getBlock("text")?.content).toEqual([ - { type: "text", text: "Before ", styles: {} }, - { - type: "link", - href: "https://example.com", - content: [{ type: "text", text: "selected text", styles: {} }], - }, - { type: "text", text: " after", styles: {} }, - ]); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/content/0/text", + "value": "Before ", + }, + { + "op": "add", + "path": "/content/1", + "value": { + "content": [ + { + "styles": {}, + "text": "selected text", + "type": "text", + }, + ], + "href": "https://example.com", + "type": "link", + }, + }, + { + "op": "add", + "path": "/content/2", + "value": { + "styles": {}, + "text": " after", + "type": "text", + }, + }, + ], + "id": "text", + "type": "update", + }, + ] + `); await expect.element(input).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); }); @@ -162,6 +194,107 @@ describe("CreateLinkButton", () => { }); }); + describe("aria", () => { + it("exposes the popup's relationship to its named trigger and its URL field", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-haspopup", "dialog"); + await expect.element(button).toHaveAttribute("aria-expanded", "false"); + + await button.click(); + + const dialog = page.getByRole("dialog"); + await expect.element(dialog).toBeVisible(); + await expect.element(button).toHaveAttribute("aria-expanded", "true"); + expect(button.element().getAttribute("aria-controls")).toBe( + dialog.element().id, + ); + expect(dialog.element().getAttribute("aria-labelledby")).toBe( + button.element().id, + ); + await expect + .element( + dialog.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ), + ) + .toHaveFocus(); + }); + }); + + describe("axe", () => { + it("checks the closed trigger", async ({ + setupEditor, + selectText, + runAxe, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + selectText(editor, "Selected text"); + + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }), + ) + .toBeVisible(); + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); + }); + it("opens a link form with no automated accessibility violations", async ({ + setupEditor, + selectText, + runAxe, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.link.tooltip, + exact: true, + }) + .click(); + + await expect + .element( + page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ), + ) + .toBeVisible(); + const { violations } = await runAxe(page.getByRole("dialog")); + expect(violations).toEqual([]); + }); + }); + describe("keyboard", () => { it("shows a keyboard focus ring on its trigger", async ({ setupEditor, @@ -295,103 +428,4 @@ describe("CreateLinkButton", () => { expect(shortcut.defaultPrevented).toBe(false); }); }); - - describe("a11y", () => { - it("exposes the popup's relationship to its named trigger and its URL field", async ({ - setupEditor, - selectText, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.link.tooltip, - exact: true, - }); - await expect.element(button).toHaveAttribute("aria-haspopup", "dialog"); - await expect.element(button).toHaveAttribute("aria-expanded", "false"); - - await button.click(); - - const dialog = page.getByRole("dialog"); - await expect.element(dialog).toBeVisible(); - await expect.element(button).toHaveAttribute("aria-expanded", "true"); - expect(button.element().getAttribute("aria-controls")).toBe( - dialog.element().id, - ); - expect(dialog.element().getAttribute("aria-labelledby")).toBe( - button.element().id, - ); - await expect - .element( - dialog.getByPlaceholder( - editor.dictionary.link_toolbar.form.url_placeholder, - ), - ) - .toHaveFocus(); - }); - - it("checks the closed trigger", async ({ - setupEditor, - selectText, - runAxe, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - props: { formattingToolbar: false }, - children: ( - - - - ), - }); - selectText(editor, "Selected text"); - - await expect - .element( - page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.link.tooltip, - exact: true, - }), - ) - .toBeVisible(); - const { violations } = await runAxe(page.getByRole("toolbar")); - expect(violations).toEqual([]); - }); - it("opens a link form with no automated accessibility violations", async ({ - setupEditor, - selectText, - runAxe, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - - await page - .getByRole("button", { - name: editor.dictionary.formatting_toolbar.link.tooltip, - exact: true, - }) - .click(); - - await expect - .element( - page.getByPlaceholder( - editor.dictionary.link_toolbar.form.url_placeholder, - ), - ) - .toBeVisible(); - const { violations } = await runAxe(page.getByRole("dialog")); - expect(violations).toEqual([]); - }); - }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx index 5cccb035f9..cde92d0690 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -37,6 +37,7 @@ describe("NestBlockButtons", () => { it("moves the selected block under its previous sibling without changing their contents", async ({ setupEditor, selectText, + compareDocuments, page, }) => { const { editor } = await setupEditor({ @@ -49,7 +50,7 @@ describe("NestBlockButtons", () => { children: , }); selectText(editor, "Selected text"); - const [parent, selected, after] = editor.document; + const before = editor.document; await page .getByRole("button", { @@ -58,15 +59,28 @@ describe("NestBlockButtons", () => { }) .click(); - expect(editor.document).toEqual([ - { ...parent, children: [selected] }, - after, - ]); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "from": { + "index": 1, + "parentId": null, + }, + "id": "selected", + "to": { + "index": 0, + "parentId": "parent", + }, + "type": "move", + }, + ] + `); }); it("moves the selected block out of its parent without changing their contents", async ({ setupEditor, selectText, + compareDocuments, page, }) => { const { editor } = await setupEditor({ @@ -85,7 +99,7 @@ describe("NestBlockButtons", () => { children: , }); selectText(editor, "Selected text"); - const [parent, after] = editor.document; + const before = editor.document; await page .getByRole("button", { @@ -94,11 +108,108 @@ describe("NestBlockButtons", () => { }) .click(); - expect(editor.document).toEqual([ - { ...parent, children: [] }, - parent.children[0], - after, - ]); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "from": { + "index": 0, + "parentId": "parent", + }, + "id": "selected", + "to": { + "index": 1, + "parentId": null, + }, + "type": "move", + }, + ] + `); + }); + }); + + describe("aria", () => { + it("only enables nesting when a previous sibling is available", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { type: "paragraph", content: "First block" }, + { type: "paragraph", content: "Second block" }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.nest.tooltip, + exact: true, + }); + selectText(editor, "First block"); + + await expect.element(button).toBeDisabled(); + + selectText(editor, "Second block"); + + await expect.element(button).toBeEnabled(); + }); + + it("only enables unnesting for a nested block", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.unnest.tooltip, + exact: true, + }); + selectText(editor, "Parent"); + await expect.element(button).toBeDisabled(); + + selectText(editor, "Child"); + + await expect.element(button).toBeEnabled(); + }); + }); + + describe("axe", () => { + it("checks enabled and disabled nesting controls", async ({ + setupEditor, + selectText, + runAxe, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + type: "paragraph", + content: "Parent", + children: [{ type: "paragraph", content: "Child" }], + }, + ], + props: { formattingToolbar: false }, + children: ( + + + + + ), + }); + selectText(editor, "Child"); + + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); }); @@ -187,88 +298,4 @@ describe("NestBlockButtons", () => { .toHaveFocus(); }); }); - - describe("a11y", () => { - it("only enables nesting when a previous sibling is available", async ({ - setupEditor, - selectText, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { type: "paragraph", content: "First block" }, - { type: "paragraph", content: "Second block" }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.nest.tooltip, - exact: true, - }); - selectText(editor, "First block"); - - await expect.element(button).toBeDisabled(); - - selectText(editor, "Second block"); - - await expect.element(button).toBeEnabled(); - }); - - it("only enables unnesting for a nested block", async ({ - setupEditor, - selectText, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { - type: "paragraph", - content: "Parent", - children: [{ type: "paragraph", content: "Child" }], - }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.unnest.tooltip, - exact: true, - }); - selectText(editor, "Parent"); - await expect.element(button).toBeDisabled(); - - selectText(editor, "Child"); - - await expect.element(button).toBeEnabled(); - }); - - it("checks enabled and disabled nesting controls", async ({ - setupEditor, - selectText, - runAxe, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { - type: "paragraph", - content: "Parent", - children: [{ type: "paragraph", content: "Child" }], - }, - ], - props: { formattingToolbar: false }, - children: ( - - - - - ), - }); - selectText(editor, "Child"); - - const { violations } = await runAxe(page.getByRole("toolbar")); - expect(violations).toEqual([]); - }); - }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx index e2c6a74a81..f6143a5a73 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -37,7 +37,10 @@ describe("TextAlignButton", () => { describe("integration", () => { it.for(["left", "center", "right", "justify"] as const)( "aligns the selected block %s without changing its text or neighboring blocks", - async (textAlignment, { setupEditor, selectText, page }) => { + async ( + alignment, + { setupEditor, selectText, compareDocuments, page }, + ) => { const { editor } = await setupEditor({ initialContent: [ { id: "before", type: "paragraph", content: "Before" }, @@ -45,19 +48,19 @@ describe("TextAlignButton", () => { id: "selected", type: "paragraph", props: { - textAlignment: textAlignment === "left" ? "center" : "left", + textAlignment: alignment === "left" ? "center" : "left", }, content: "Selected text", }, { id: "after", type: "paragraph", content: "After" }, ], props: { formattingToolbar: false }, - children: , + children: , }); selectText(editor, "Selected text"); const documentBefore = editor.document; const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar[`align_${textAlignment}`] + name: editor.dictionary.formatting_toolbar[`align_${alignment}`] .tooltip, exact: true, }); @@ -65,13 +68,14 @@ describe("TextAlignButton", () => { await button.click(); - expect(editor.document).toEqual([ - documentBefore[0], + expect(compareDocuments(documentBefore, editor.document)).toEqual([ { - ...documentBefore[1], - props: { ...documentBefore[1].props, textAlignment }, + type: "update", + id: "selected", + changes: [ + { op: "replace", path: "/props/textAlignment", value: alignment }, + ], }, - documentBefore[2], ]); await expect.element(button).toHaveAttribute("aria-pressed", "true"); }, @@ -79,6 +83,7 @@ describe("TextAlignButton", () => { it("aligns every selected block without changing an unselected neighbor", async ({ setupEditor, + compareDocuments, page, }) => { const { editor } = await setupEditor({ @@ -100,21 +105,37 @@ describe("TextAlignButton", () => { }) .click(); - expect(editor.document).toEqual([ - { - ...before[0], - props: { ...before[0].props, textAlignment: "center" }, - }, - { - ...before[1], - props: { ...before[1].props, textAlignment: "center" }, - }, - before[2], - ]); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/props/textAlignment", + "value": "center", + }, + ], + "id": "first", + "type": "update", + }, + { + "changes": [ + { + "op": "replace", + "path": "/props/textAlignment", + "value": "center", + }, + ], + "id": "second", + "type": "update", + }, + ] + `); }); it("aligns only the selected table cells", async ({ setupEditor, + compareDocuments, page, }) => { const { editor } = await setupEditor({ @@ -143,10 +164,8 @@ describe("TextAlignButton", () => { }); tr.setSelection(CellSelection.create(tr.doc, cells[0], cells[1])); }); - const tableBefore = editor.getBlock("table"); - if (tableBefore?.type !== "table") { - throw new Error("Expected table fixture"); - } + // The alignment action shares and mutates table-cell props; detach the baseline. + const before = structuredClone(editor.document); await page .getByRole("button", { @@ -155,28 +174,81 @@ describe("TextAlignButton", () => { }) .click(); - expect(editor.getBlock("table")).toEqual({ - ...tableBefore, - content: { - ...tableBefore.content, - rows: tableBefore.content.rows.map((row, index) => - index === 0 - ? { - ...row, - cells: row.cells.map((cell) => { - if (Array.isArray(cell)) { - throw new Error("Expected normalized table cells"); - } - return { - ...cell, - props: { ...cell.props, textAlignment: "center" }, - }; - }), - } - : row, - ), - }, + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/content/rows/0/cells/0/props/textAlignment", + "value": "center", + }, + { + "op": "replace", + "path": "/content/rows/0/cells/1/props/textAlignment", + "value": "center", + }, + ], + "id": "table", + "type": "update", + }, + ] + `); + }); + }); + + describe("aria", () => { + it("updates its pressed state when selection moves between differently aligned blocks", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { type: "paragraph", content: "Left" }, + { + type: "paragraph", + content: "Center", + props: { textAlignment: "center" }, + }, + ], + props: { formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, }); + selectText(editor, "Center"); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + + selectText(editor, "Left"); + + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + }); + }); + + describe("axe", () => { + it("checks all alignment controls, including the selected one", async ({ + setupEditor, + runAxe, + page, + }) => { + await setupEditor({ + props: { formattingToolbar: false }, + children: ( + + {(["left", "center", "right", "justify"] as const).map( + (alignment) => ( + + ), + )} + + ), + }); + + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); }); @@ -236,57 +308,4 @@ describe("TextAlignButton", () => { }, ); }); - - describe("a11y", () => { - it("updates its pressed state when selection moves between differently aligned blocks", async ({ - setupEditor, - selectText, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { type: "paragraph", content: "Left" }, - { - type: "paragraph", - content: "Center", - props: { textAlignment: "center" }, - }, - ], - props: { formattingToolbar: false }, - children: , - }); - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar.align_center.tooltip, - exact: true, - }); - selectText(editor, "Center"); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - - selectText(editor, "Left"); - - await expect.element(button).toHaveAttribute("aria-pressed", "false"); - }); - - it("checks all alignment controls, including the selected one", async ({ - setupEditor, - runAxe, - page, - }) => { - await setupEditor({ - props: { formattingToolbar: false }, - children: ( - - {(["left", "center", "right", "justify"] as const).map( - (alignment) => ( - - ), - )} - - ), - }); - - const { violations } = await runAxe(page.getByRole("toolbar")); - expect(violations).toEqual([]); - }); - }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap b/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap deleted file mode 100644 index 7a50940e3c..0000000000 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/__snapshots__/BasicTextStyleButton.browser.test.tsx.snap +++ /dev/null @@ -1,211 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`BasicTextStyleButton > integration > toggles bold on and off > off 1`] = ` -{ - "children": [], - "content": [ - { - "styles": {}, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles bold on and off > on 1`] = ` -{ - "children": [], - "content": [ - { - "styles": { - "bold": true, - }, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles code on and off > off 1`] = ` -{ - "children": [], - "content": [ - { - "styles": {}, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles code on and off > on 1`] = ` -{ - "children": [], - "content": [ - { - "styles": { - "code": true, - }, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles italic on and off > off 1`] = ` -{ - "children": [], - "content": [ - { - "styles": {}, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles italic on and off > on 1`] = ` -{ - "children": [], - "content": [ - { - "styles": { - "italic": true, - }, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles strike on and off > off 1`] = ` -{ - "children": [], - "content": [ - { - "styles": {}, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles strike on and off > on 1`] = ` -{ - "children": [], - "content": [ - { - "styles": { - "strike": true, - }, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles underline on and off > off 1`] = ` -{ - "children": [], - "content": [ - { - "styles": {}, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; - -exports[`BasicTextStyleButton > integration > toggles underline on and off > on 1`] = ` -{ - "children": [], - "content": [ - { - "styles": { - "underline": true, - }, - "text": "Format this text", - "type": "text", - }, - ], - "id": "format", - "props": { - "backgroundColor": "default", - "textAlignment": "left", - "textColor": "default", - }, - "type": "paragraph", -} -`; diff --git a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx index dd3e1789de..7c71763cfd 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -104,6 +104,7 @@ describe("BlockTypeSelect", () => { it("converts the selected block and updates its label without changing neighboring blocks or text", async ({ setupEditor, selectText, + compareDocuments, page, }) => { const { editor } = await setupEditor({ @@ -131,19 +132,32 @@ describe("BlockTypeSelect", () => { }) .click(); - expect(editor.document).toEqual([ - documentBefore[0], - { - ...documentBefore[1], - type: "heading", - props: { - ...documentBefore[1].props, - level: 1, - isToggleable: false, + expect(compareDocuments(documentBefore, editor.document)) + .toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/type", + "value": "heading", + }, + { + "op": "add", + "path": "/props/level", + "value": 1, + }, + { + "op": "add", + "path": "/props/isToggleable", + "value": false, + }, + ], + "id": "selected", + "type": "update", }, - }, - documentBefore[2], - ]); + ] + `); await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); await expect .element( @@ -157,6 +171,7 @@ describe("BlockTypeSelect", () => { it("converts all selected blocks while leaving an unselected neighbor intact", async ({ setupEditor, + compareDocuments, page, }) => { const { editor } = await setupEditor({ @@ -184,141 +199,56 @@ describe("BlockTypeSelect", () => { }) .click(); - expect(editor.document).toEqual([ - ...before.slice(0, 2).map((block) => ({ - ...block, - type: "heading", - props: { ...block.props, level: 1, isToggleable: false }, - })), - before[2], - ]); - }); - }); - - describe("keyboard", () => { - it("shows a keyboard focus ring on its trigger", async ({ - setupEditor, - selectText, - captureFocusOutline, - pressKey, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - props: { formattingToolbar: false }, - children: , - }); - await page.getByRole("textbox").click(); - selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.slash_menu.paragraph.title, - exact: true, - }); - const compareFocusOutline = captureFocusOutline(button); - - await pressKey("Tab"); - - await expect.element(button).toHaveFocus(); - await compareFocusOutline(button); - }); - - it("dismisses with Escape and restores trigger focus without editing", async ({ - setupEditor, - selectText, - pressKey, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.slash_menu.paragraph.title, - exact: true, - }); - const before = editor.document; - const selection = editor.prosemirrorState.selection.toJSON(); - button.element().focus(); - await pressKey("Enter"); - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - await expect - .poll(() => menu.element().contains(document.activeElement)) - .toBe(true); - - await pressKey("Escape"); - - await expect.element(menu).not.toBeInTheDocument(); - await expect.element(button).toHaveFocus(); - expect(editor.document).toEqual(before); - expect(editor.prosemirrorState.selection.toJSON()).toEqual(selection); - }); - it("opens, navigates, and chooses a block type from the keyboard", async ({ - setupEditor, - selectText, - pressKey, - captureFocusOutline, - page, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { id: "text", type: "paragraph", content: "Selected text" }, - ], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - const button = page.getByRole("button", { - name: editor.dictionary.slash_menu.paragraph.title, - exact: true, - }); - button.element().focus(); - await expect.element(button).toHaveFocus(); - - await pressKey("Enter"); - - const menu = page.getByRole("menu"); - await expect.element(menu).toBeVisible(); - await expect - .poll(() => menu.element().contains(document.activeElement)) - .toBe(true); - const paragraph = menu.getByRole("menuitem", { - name: editor.dictionary.slash_menu.paragraph.title, - exact: true, - }); - const heading = menu.getByRole("menuitem", { - name: editor.dictionary.slash_menu.heading.title, - exact: true, - }); - const compareFocusOutline = captureFocusOutline(heading); - - await pressKey("ArrowDown"); - - await expect.element(paragraph).toHaveFocus(); - - await pressKey("ArrowDown"); - - await expect.element(heading).toHaveFocus(); - await compareFocusOutline(heading); - - await pressKey("Enter"); - - await expect.element(menu).not.toBeInTheDocument(); - await expect - .element( - page.getByRole("button", { - name: editor.dictionary.slash_menu.heading.title, - exact: true, - }), - ) - .toHaveFocus(); - expect(editor.getBlock("text")?.type).toBe("heading"); + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + [ + { + "changes": [ + { + "op": "replace", + "path": "/type", + "value": "heading", + }, + { + "op": "add", + "path": "/props/level", + "value": 1, + }, + { + "op": "add", + "path": "/props/isToggleable", + "value": false, + }, + ], + "id": "first", + "type": "update", + }, + { + "changes": [ + { + "op": "replace", + "path": "/type", + "value": "heading", + }, + { + "op": "add", + "path": "/props/level", + "value": 1, + }, + { + "op": "add", + "path": "/props/isToggleable", + "value": false, + }, + ], + "id": "second", + "type": "update", + }, + ] + `); }); }); - describe("a11y", () => { + describe("aria", () => { it("names the current block type and exposes the popup relationship", async ({ setupEditor, selectText, @@ -377,7 +307,9 @@ describe("BlockTypeSelect", () => { await expect.element(item).toBeVisible(); expect(item.element().getAttribute("aria-checked")).toBe("true"); }); + }); + describe("axe", () => { it("checks the trigger", async ({ setupEditor, selectText, @@ -451,4 +383,127 @@ describe("BlockTypeSelect", () => { ]); }); }); + + describe("keyboard", () => { + it("shows a keyboard focus ring on its trigger", async ({ + setupEditor, + selectText, + captureFocusOutline, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + const compareFocusOutline = captureFocusOutline(button); + + await pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await compareFocusOutline(button); + }); + + it("dismisses with Escape and restores trigger focus without editing", async ({ + setupEditor, + selectText, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + const before = editor.document; + const selection = editor.prosemirrorState.selection.toJSON(); + button.element().focus(); + await pressKey("Enter"); + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + + await pressKey("Escape"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect.element(button).toHaveFocus(); + expect(editor.document).toEqual(before); + expect(editor.prosemirrorState.selection.toJSON()).toEqual(selection); + }); + it("opens, navigates, and chooses a block type from the keyboard", async ({ + setupEditor, + selectText, + pressKey, + captureFocusOutline, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + button.element().focus(); + await expect.element(button).toHaveFocus(); + + await pressKey("Enter"); + + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + await expect + .poll(() => menu.element().contains(document.activeElement)) + .toBe(true); + const paragraph = menu.getByRole("menuitem", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + const heading = menu.getByRole("menuitem", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }); + const compareFocusOutline = captureFocusOutline(heading); + + await pressKey("ArrowDown"); + + await expect.element(paragraph).toHaveFocus(); + + await pressKey("ArrowDown"); + + await expect.element(heading).toHaveFocus(); + await compareFocusOutline(heading); + + await pressKey("Enter"); + + await expect.element(menu).not.toBeInTheDocument(); + await expect + .element( + page.getByRole("button", { + name: editor.dictionary.slash_menu.heading.title, + exact: true, + }), + ) + .toHaveFocus(); + expect(editor.getBlock("text")?.type).toBe("heading"); + }); + }); }); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx index cfd923e13d..bea7861f6d 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx @@ -114,6 +114,46 @@ describe("FormattingToolbar", () => { }); }); + describe("aria", () => { + it("exposes its custom controls as a toolbar", async ({ + setupEditor, + page, + }) => { + await setupEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + + await expect.element(page.getByRole("toolbar")) + .toMatchAriaInlineSnapshot(` + - toolbar: + - button "Custom action" + `); + }); + }); + + describe("axe", () => { + it("has no automated accessibility violations with the default controls", async ({ + setupEditor, + selectText, + page, + runAxe, + }) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + }); + selectText(editor, "Selected text"); + await expect.element(page.getByRole("toolbar")).toBeVisible(); + + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); + }); + }); + describe("keyboard", () => { it("tabs forward through the default controls for Parent and allows leaving", async ({ setupEditor, @@ -513,42 +553,4 @@ describe("FormattingToolbar", () => { expect(toolbar.element().contains(document.activeElement)).toBe(false); }); }); - - describe("a11y", () => { - it("exposes its custom controls as a toolbar", async ({ - setupEditor, - page, - }) => { - await setupEditor({ - props: { formattingToolbar: false }, - children: ( - - - - ), - }); - - await expect.element(page.getByRole("toolbar")) - .toMatchAriaInlineSnapshot(` - - toolbar: - - button "Custom action" - `); - }); - - it("has no automated accessibility violations with the default controls", async ({ - setupEditor, - selectText, - page, - runAxe, - }) => { - const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - }); - selectText(editor, "Selected text"); - await expect.element(page.getByRole("toolbar")).toBeVisible(); - - const { violations } = await runAxe(page.getByRole("toolbar")); - expect(violations).toEqual([]); - }); - }); }); diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts index 04d371cb62..4112128d3f 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts @@ -1,4 +1,3 @@ -import { selectToLineEndKey } from "@root/tests/src/utils/context.js"; import { expect } from "vite-plus/test"; // Record selection → toolbar → Escape → editor. @@ -8,6 +7,7 @@ it.skip("announces entering and leaving the formatting toolbar", async ({ setupEditor, setupScreenReader, page, + selectToLineEndKey, }) => { const { editor } = await setupEditor({ initialContent: [ diff --git a/packages/react/src/editor/BlockNoteView.browser.test.tsx b/packages/react/src/editor/BlockNoteView.browser.test.tsx index f3a111b160..ccd78af11f 100644 --- a/packages/react/src/editor/BlockNoteView.browser.test.tsx +++ b/packages/react/src/editor/BlockNoteView.browser.test.tsx @@ -1,4 +1,3 @@ -import { commands } from "@root/tests/src/utils/context.js"; import { COLORS_DEFAULT, defaultBlockSpecs, @@ -13,7 +12,7 @@ import { type DefaultStyleSchema, type PropSchema, } from "@blocknote/core"; -import { expect, test } from "vite-plus/test"; +import { describe, expect } from "vite-plus/test"; import { page, server } from "vite-plus/test/browser"; import "@blocknote/core/fonts/inter.css"; import { BlockNoteView } from "@blocknote/mantine"; @@ -22,7 +21,6 @@ import { useCreateBlockNote } from "@blocknote/react"; import { render } from "vitest-browser-react"; import { useEffect } from "react"; import { NodeSelection, TextSelection } from "@tiptap/pm/state"; -import { screenshotFull } from "@root/tests/src/utils/screenshotFull.js"; // These keyboard-navigation tests inspect the focus end of the DOM selection. export function readDOMSelection() { @@ -441,31 +439,27 @@ const schemaDocument: PartialBlock[] = [ // Screen-reader tests import the shared helpers and fixtures from this file. // Register these suites only in the regular browser run. if (!screenReader) { - test.describe("keyboard", () => { - async function focusReadOnlyLinkWithAssertions() { - const link = page.getByRole("link", { - name: "Documentation", - exact: true, + describe("aria", () => { + // Numbered list item indices are separate text elements, among other issues. + it.skip("default schema: accessibility tree snapshot", async () => { + await renderTestEditor(schemaDocument); + await expect.element(page.getByRole("textbox")).toMatchAriaSnapshot(); + }); + }); + + describe("axe", () => { + for (const theme of ["light", "dark"] as const) { + // Known issues include the unnamed editor, unlabeled checklist checkboxes, + // insufficient contrast, and undersized targets. + it.skip(`default schema: axe (${theme})`, async ({ runAxe }) => { + await renderTestEditor(schemaDocument, { theme }); + const results = await runAxe(); + expect(results.violations).toEqual([]); }); - await expect.element(link).toBeVisible(); - const compareFocusOutline = commands.captureFocusOutline(link); - for ( - let presses = 0; - document.activeElement !== link.element(); - presses++ - ) { - if (presses >= 10) { - throw new Error( - "Could not focus the Documentation link after 10 Tab presses", - ); - } - await commands.pressKey("Tab"); - } - await expect.element(link).toHaveFocus(); - await compareFocusOutline(link); - return link; } + }); + describe("keyboard", () => { // Firefox skips checkListItem with ArrowDown. // Chromium/WebKit reproduction: expand "Toggle heading", place the caret // immediately before the C in "Completed task", then press ArrowUp. It lands @@ -474,8 +468,9 @@ if (!screenReader) { // Confirmed with clicks and keypresses in Docker. The traversal below reaches // "Completed task" at offset 0 when returning from the final paragraph. // Keep the complete expected route when re-enabling this test. - test.skip("default schema: arrow keys visit every expanded block in order", async ({ + it.skip("default schema: arrow keys visit every expanded block in order", async ({ onTestFinished, + pressKey, }) => { // Expansion is view state, not a document prop. Make the route deterministic // without changing the visual fixtures' default collapsed state. @@ -492,7 +487,7 @@ if (!screenReader) { }); } const editor = await renderTestEditor(defaultSchemaDocument); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(page.getByRole("textbox")).toHaveFocus(); function blockIds(blocks: PartialBlock[]): string[] { @@ -516,7 +511,7 @@ if (!screenReader) { `${key} did not finish the document route after 100 presses; still at block "${expected[index]}"`, ); } - await commands.pressKey(key); + await pressKey(key); const actual = editor.getTextCursorPosition().block.id; expect( @@ -536,9 +531,11 @@ if (!screenReader) { } }); - test("table: ArrowRight and ArrowLeft visit every cell in row order", async () => { + it("table: ArrowRight and ArrowLeft visit every cell in row order", async ({ + pressKey, + }) => { await renderTestEditor(tableNavigationDocument); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(page.getByRole("textbox")).toHaveFocus(); const route = [ { row: 0, column: 0 }, @@ -556,7 +553,7 @@ if (!screenReader) { `${key} did not finish the table route after 100 presses; still at cell ${JSON.stringify(expected[index])}`, ); } - await commands.pressKey(key); + await pressKey(key); const { blockId, tableCell } = readDOMSelection(); expect(blockId, `${key} stays in the table`).toBe("table"); expect( @@ -575,11 +572,11 @@ if (!screenReader) { // After Tab enters the second column, Chromium/WebKit's ArrowDown returns // to column 0. Firefox preserves the column throughout this sequence. - test.skipIf(server.browser !== "firefox")( + it.skipIf(server.browser !== "firefox")( "table: ArrowDown and ArrowUp visit each row without changing column", - async () => { + async ({ pressKey }) => { await renderTestEditor(tableNavigationDocument); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(page.getByRole("textbox")).toHaveFocus(); for (const column of [0, 1]) { expect(readDOMSelection().tableCell).toEqual({ @@ -599,7 +596,7 @@ if (!screenReader) { `${key} did not reach row ${targetRow}, column ${column} after 10 presses`, ); } - await commands.pressKey(key); + await pressKey(key); selection = readDOMSelection(); expect(selection.blockId, `${key} stays in the table`).toBe( "table", @@ -614,14 +611,14 @@ if (!screenReader) { } if (column === 0) { // Set up the second column through the table's keyboard navigation. - await commands.pressKey("Tab"); + await pressKey("Tab"); } } }, ); // The editor has no separate focused state without an editing selection; Escape blurs to the body. - test.skip("editor can receive focus without selecting content", async () => { + it.skip("editor can receive focus without selecting content", async () => { // TODO: Focus the editor as a page element without an editing selection. // Tab/arrows should navigate the page; Enter should enter editing. // Escape currently blurs to body, which does not preserve this entry point. @@ -629,22 +626,22 @@ if (!screenReader) { // Whole-block selection requires Cmd+Click; no keyboard interaction is implemented. No styling // is present to indicate whole-block selection. - test.skip("keyboard selection extends to the entire block", async () => { + it.skip("keyboard selection extends to the entire block", async () => { // TODO: Extend a text selection to its whole block, leaving neighbours out. // Whole-block selection currently requires Cmd+Click; keyboard UX is TBD. }); // TODO: WebKit resets the tab position after Escape blurs the editor, so Tab // focuses "Before editor" instead of "After editor". - test.skipIf(server.browser === "webkit")( + it.skipIf(server.browser === "webkit")( "Escape allows Tab to leave the editor", - async () => { + async ({ pressKey }) => { await renderTestEditor(editorEscapeDocument); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect.element(page.getByRole("textbox")).toHaveFocus(); - await commands.pressKey("Escape"); + await pressKey("Escape"); await expect.element(document.body).toHaveFocus(); - await commands.pressKey("Tab"); + await pressKey("Tab"); await expect .element( page.getByRole("button", { name: "After editor", exact: true }), @@ -656,21 +653,33 @@ if (!screenReader) { // Focused inline links do not yet have a suitable visual focus indicator. // TODO: Fix the focus appearance before enabling. - test.skip("read-only editor: Tab reaches inline links and leaves the editor", async () => { + it.skip("read-only editor: Tab reaches inline links and leaves the editor", async ({ + pressKey, + captureFocusOutline, + focusUntil, + }) => { await renderTestEditor(readOnlyLinkDocument, { editable: false }); - const link = await focusReadOnlyLinkWithAssertions(); - await commands.pressKey("Tab"); + const link = page.getByRole("link", { + name: "Documentation", + exact: true, + }); + await expect.element(link).toBeVisible(); + const compareFocusOutline = captureFocusOutline(link); + await focusUntil(link); + await expect.element(link).toHaveFocus(); + await compareFocusOutline(link); + await pressKey("Tab"); await expect .element( page.getByRole("button", { name: "After editor", exact: true }), ) .toHaveFocus(); - await commands.pressKey("Shift+Tab"); + await pressKey("Shift+Tab"); await expect.element(link).toHaveFocus(); }); // Read-only file/media blocks cannot be selected through the page tab order. - test.skip("read-only editor: Tab selects blocks that expose a formatting toolbar", async () => { + it.skip("read-only editor: Tab selects blocks that expose a formatting toolbar", async () => { // TODO: Open a read-only document containing an image/file block between // ordinary paragraphs. Tab from Before editor to select that block, assert // the block selection and visible indicator, and continue to After editor. @@ -680,33 +689,7 @@ if (!screenReader) { }); }); - test.describe("ARIA", () => { - // Numbered list item indices are separate text elements, among other issues. - test.skip("default schema: accessibility tree snapshot", async () => { - await renderTestEditor(schemaDocument); - await expect.element(page.getByRole("textbox")).toMatchAriaSnapshot(); - }); - }); - - test.describe("axe", () => { - for (const theme of ["light", "dark"] as const) { - // Known issues include the unnamed editor, unlabeled checklist checkboxes, - // insufficient contrast, and undersized targets. - test.skip(`default schema: axe (${theme})`, async ({ annotate }) => { - await renderTestEditor(schemaDocument, { theme }); - const results = await commands.runAxe(); - expect(results.violations).toEqual([]); - for (const result of results.incomplete) { - await annotate( - `axe manual review: ${result.id} — ${result.help}`, - "warning", - ); - } - }); - } - }); - - test.describe("visual", () => { + describe("visual", () => { function applyStyles(css: string) { const style = document.createElement("style"); style.textContent = css; @@ -745,8 +728,10 @@ if (!screenReader) { } } - test.describe("text spacing and resizing", () => { - test("default schema remains readable with text spacing overrides", async () => { + describe("text spacing and resizing", () => { + it("default schema remains readable with text spacing overrides", async ({ + screenshotFull, + }) => { await renderTestEditor(defaultSchemaDocument); await waitForMedia(); // WCAG 1.4.12: override spacing without changing any other style property. @@ -768,7 +753,9 @@ if (!screenReader) { }); }); - test("default schema remains readable at 200% text size", async () => { + it("default schema remains readable at 200% text size", async ({ + screenshotFull, + }) => { await renderTestEditor(defaultSchemaDocument); await waitForMedia(); resizeText(2); diff --git a/scripts/lint/README.md b/scripts/lint/README.md index 4bdd835393..1e5a4b4ed6 100644 --- a/scripts/lint/README.md +++ b/scripts/lint/README.md @@ -9,8 +9,11 @@ only. Older component suites must be migrated before widening that glob. `BasicTextStyleButton` and controller files keep their full names. No import analysis or singularization guesses are used to infer the owner. - Direct child groups are an ordered, unique subset of `unit`, `integration`, - `keyboard`, `a11y`. Missing groups are fine; unknown groups are not. ARIA - assertions and axe scans belong together in `a11y`, not separate groups. + `aria`, `axe`, `keyboard`. Missing groups are fine; unknown groups are not. + `unit` tests the owner's internal behavior; `integration` tests its interactions + across components; `aria` tests ARIA attributes, behaviors, and snapshots; + `axe` tests scan results and violations; `keyboard` tests functionality through + keyboard input. - Tests belong inside those groups. Scenario describes may nest further. - Empty describes, including hooks-only or comments-only placeholders, fail. Emptiness means no syntactic test registration in the describe's subtree, not diff --git a/scripts/lint/component-browser-tests.mjs b/scripts/lint/component-browser-tests.mjs index fd75320df7..67a2a0b936 100644 --- a/scripts/lint/component-browser-tests.mjs +++ b/scripts/lint/component-browser-tests.mjs @@ -1,6 +1,6 @@ import { basename } from "node:path"; -const groups = ["unit", "integration", "keyboard", "a11y"]; +const groups = ["unit", "integration", "aria", "axe", "keyboard"]; const testModules = new Set(["vite-plus/test", "vitest"]); const apis = new Set(["describe", "suite", "it", "test"]); const modifiers = new Set([ @@ -96,7 +96,7 @@ const structure = { owner: 'Use exactly one top-level describe("{{owner}}", () => { ... }).', callback: "Use an inline describe callback with a block body.", group: - "Place each applicable group directly inside the owner, once, in this order: unit, integration, keyboard, a11y. Omit inapplicable groups.", + "Place each applicable group directly inside the owner, once, in this order: unit, integration, aria, axe, keyboard. Omit inapplicable groups.", placement: "Place tests inside an applicable group, not directly in the owner or at file scope.", empty: "Omit empty describe groups; hooks or comments are not tests.", diff --git a/scripts/lint/component-browser-tests.test.mjs b/scripts/lint/component-browser-tests.test.mjs index 200fd99c52..70b7e33e08 100644 --- a/scripts/lint/component-browser-tests.test.mjs +++ b/scripts/lint/component-browser-tests.test.mjs @@ -63,19 +63,26 @@ function owner(content, name = "Button") { void test("accepts all groups in order and any nonempty subset", () => { assert.deepEqual( lint( - owner(["unit", "integration", "keyboard", "a11y"].map(group).join("\n")), + owner( + ["unit", "integration", "aria", "axe", "keyboard"] + .map(group) + .join("\n"), + ), ), [], ); - assert.deepEqual(lint(owner(group("a11y"))), []); - assert.deepEqual(lint(owner(group("unit") + group("a11y"))), []); + assert.deepEqual(lint(owner(group("aria"))), []); + assert.deepEqual(lint(owner(group("unit") + group("axe"))), []); + assert.deepEqual(lint(owner(group("aria") + group("keyboard"))), []); }); -void test("accepts ARIA assertions and axe scans inside the same a11y group", () => { +void test("accepts separate aria and axe groups", () => { assert.deepEqual( lint( - owner(`describe("a11y", () => { + owner(`describe("aria", () => { it("exposes its role", () => { expect(button).toHaveAttribute("role", "button"); }); + }); + describe("axe", () => { it("has no axe violations", async () => { expect((await runAxe()).violations).toEqual([]); }); });`), ), @@ -106,7 +113,7 @@ void test("owner is the full filename stem, not an imported symbol", () => { void test("rejects missing, multiple, or wrongly named owners", () => { for (const code of [ body, - owner(group("unit")) + owner(group("a11y")), + owner(group("unit")) + owner(group("aria")), owner(group("unit"), "Other"), ]) { assert.match(lint(code)[0], /exactly one top-level/); @@ -115,13 +122,14 @@ void test("rejects missing, multiple, or wrongly named owners", () => { void test("rejects out-of-order, duplicate and unknown categories", () => { for (const content of [ - group("a11y") + group("unit"), + group("aria") + group("unit"), group("unit") + group("unit"), - group("a11y") + group("a11y"), + group("aria") + group("aria"), + group("keyboard") + group("aria"), + group("axe") + group("aria"), + group("a11y"), group("behaviour"), group("ARIA"), - group("aria"), - group("axe"), group("visual"), ]) { assert.match(lint(owner(content)).join("\n"), /in this order/); @@ -176,7 +184,7 @@ void test("resolves named import aliases and namespace imports", () => { ); assert.deepEqual( lint(`import * as vt from "vitest"; - vt.describe("Button", () => { vt.describe("a11y", () => { vt.test("works", () => {}); }); });`), + vt.describe("Button", () => { vt.describe("aria", () => { vt.test("works", () => {}); }); });`), [], ); }); diff --git a/tests/src/commands/browser/environment.ts b/tests/src/commands/browser/environment.ts new file mode 100644 index 0000000000..815a90b189 --- /dev/null +++ b/tests/src/commands/browser/environment.ts @@ -0,0 +1,4 @@ +import { server } from "../transport.js"; + +/** The browser instance the current test is running in. */ +export const browserName = server.browser as "chromium" | "firefox" | "webkit"; diff --git a/tests/src/commands/browser/index.ts b/tests/src/commands/browser/index.ts index fa1f1e207f..76651c44fd 100644 --- a/tests/src/commands/browser/index.ts +++ b/tests/src/commands/browser/index.ts @@ -2,3 +2,6 @@ export { focusUntil } from "./focus.js"; export { captureFocusOutline } from "./outline.js"; export { runAxe } from "./axe.js"; export { readAriaSnapshot } from "./ariaSnapshot.js"; +export { MOD, selectToLineEndKey } from "./keyboard.js"; +export { browserName } from "./environment.js"; +export { screenshotFull } from "./screenshotFull.js"; diff --git a/tests/src/commands/browser/keyboard.ts b/tests/src/commands/browser/keyboard.ts new file mode 100644 index 0000000000..52d58c9372 --- /dev/null +++ b/tests/src/commands/browser/keyboard.ts @@ -0,0 +1,9 @@ +import { server } from "../transport.js"; + +/** Platform modifier for `userEvent.keyboard`: Cmd on macOS, Ctrl elsewhere. */ +export const MOD: "Meta" | "Control" = + server.platform === "darwin" ? "Meta" : "Control"; + +/** Platform shortcut for extending the text selection to the end of its line. */ +export const selectToLineEndKey = + server.platform === "darwin" ? "Meta+Shift+ArrowRight" : "Shift+End"; diff --git a/tests/src/commands/browser/screenshotFull.ts b/tests/src/commands/browser/screenshotFull.ts new file mode 100644 index 0000000000..9a5747e1a3 --- /dev/null +++ b/tests/src/commands/browser/screenshotFull.ts @@ -0,0 +1,61 @@ +import { expect } from "vite-plus/test"; +import { page } from "../transport.js"; + +/** + * Screenshots an element that may be taller than the browser window, at full + * resolution. + * + * Grow the tester iframe so it paints the complete element. Vitest 5 handles + * removing the iframe's fit-to-window transform during capture, so this helper + * only manages the capture height and restores the suite's default viewport. + * A fixed height also lets the static-rendering equality test compare renders + * whose content heights differ slightly against the same baseline. + * + * Use for deliberate full-height visual baselines after fonts, media, and layout + * are ready, not as a substitute for state or accessibility assertions. + * + * @example + * it("renders a tall document", async ({ page, screenshotFull }) => { + * await screenshotFull(page.getByRole("textbox").element(), "tall-document"); + * }); + */ +export async function screenshotFull( + element: HTMLElement, + name: string, + options?: { + /** + * Fixed capture height instead of measuring the element. Required when + * two different renders are compared against one baseline (e.g. the + * static-rendering equality test): measured heights differ by a few px + * between renders, and a dimension mismatch fails before pixels are even + * compared. Pass `document.documentElement` as the element then - its box + * is the (grown) iframe viewport, so the dimensions are exact. + */ + height?: number; + comparatorOptions?: { + allowedMismatchedPixelRatio?: number; + allowedMismatchedPixels?: number; + }; + screenshotOptions?: { + scale?: "css" | "device"; + mask?: readonly unknown[]; + }; + }, +) { + const height = + options?.height ?? + Math.max(720, Math.ceil(element.getBoundingClientRect().bottom) + 40); + await page.viewport(1280, height); + try { + await expect.element(element).toMatchScreenshot(name, { + ...(options?.comparatorOptions && { + comparatorOptions: options.comparatorOptions, + }), + ...(options?.screenshotOptions && { + screenshotOptions: options.screenshotOptions, + }), + } as never); + } finally { + await page.viewport(1280, 720); + } +} diff --git a/tests/src/commands/index.ts b/tests/src/commands/index.ts index ce04ee3799..e3482018ad 100644 --- a/tests/src/commands/index.ts +++ b/tests/src/commands/index.ts @@ -2,7 +2,7 @@ import type { TestAPI } from "vite-plus/test"; import * as browserCommands from "./browser/index.js"; import { createSetupEditor, type SetupEditor } from "./browser/setupEditor.js"; -import { commands as nodeCommands, page } from "./transport.js"; +import { commands as nodeCommands, page, userEvent } from "./transport.js"; // Browser-only fixtures extend the baseline in fixtures/editor.node.ts. export type CommandContext = Pick< @@ -11,6 +11,7 @@ export type CommandContext = Pick< > & typeof browserCommands & { page: typeof page; + userEvent: typeof userEvent; setupEditor: SetupEditor; }; @@ -19,6 +20,13 @@ export const commands: Required< Parameters["scoped"]>[0] > = { page, + userEvent, + MOD: browserCommands.MOD, + browserName: browserCommands.browserName, + selectToLineEndKey: browserCommands.selectToLineEndKey, + screenshotFull: async ({}, use) => { + await use(browserCommands.screenshotFull); + }, pressKey: async ({}, use) => { await use(nodeCommands.pressKey); }, diff --git a/tests/src/commands/node/setupEditor.ts b/tests/src/commands/node/setupEditor.ts index 4f3cef63f1..50068bcdab 100644 --- a/tests/src/commands/node/setupEditor.ts +++ b/tests/src/commands/node/setupEditor.ts @@ -58,8 +58,6 @@ export function createSetupEditor(onFinished: TestContext["onTestFinished"]) { * attached to document.body and removed during cleanup. * * @example - * // @vitest-environment jsdom - * import { test as it } from "@root/tests/src/fixtures/editor.node.js"; * * it("updates a block", async ({ setupEditor }) => { * const { editor } = await setupEditor({ diff --git a/tests/src/screen-reader/vite.config.screen-reader.ts b/tests/src/screen-reader/vite.config.screen-reader.ts index 8e67be5ae4..b77e1ee939 100644 --- a/tests/src/screen-reader/vite.config.screen-reader.ts +++ b/tests/src/screen-reader/vite.config.screen-reader.ts @@ -20,7 +20,6 @@ export default defineConfig({ publicDir: fileURLToPath(new URL("../../public", import.meta.url)), resolve: { alias: { - "@root": fileURLToPath(new URL("../../../", import.meta.url)), "@blocknote/core": fileURLToPath( new URL("../../../packages/core/src", import.meta.url), ), diff --git a/tests/src/utils/context.ts b/tests/src/utils/context.ts index 26a78f571d..4180a06e5d 100644 --- a/tests/src/utils/context.ts +++ b/tests/src/utils/context.ts @@ -1,6 +1,9 @@ -import { server } from "../commands/transport.js"; - export { page, server, userEvent } from "../commands/transport.js"; +export { + MOD, + browserName, + selectToLineEndKey, +} from "../commands/browser/index.js"; import * as browserCommands from "../commands/browser/index.js"; import * as baselineCommands from "../commands/node/index.js"; import { commands as nodeCommands } from "../commands/transport.js"; @@ -11,16 +14,3 @@ export const commands = { ...nodeCommands, ...browserCommands, }; - -/** The browser instance the current test is running in. */ -export const browserName = server.browser as "chromium" | "firefox" | "webkit"; - -/** - * Platform modifier for `userEvent.keyboard` (Cmd on macOS, Ctrl elsewhere) — - * the equivalent of Playwright's `ControlOrMeta`. - */ -export const MOD: "Meta" | "Control" = - server.platform === "darwin" ? "Meta" : "Control"; - -export const selectToLineEndKey = - server.platform === "darwin" ? "Meta+Shift+ArrowRight" : "Shift+End"; diff --git a/tests/src/utils/screenshotFull.ts b/tests/src/utils/screenshotFull.ts index 902162d218..b9d557c1b6 100644 --- a/tests/src/utils/screenshotFull.ts +++ b/tests/src/utils/screenshotFull.ts @@ -1,53 +1 @@ -import { page } from "./context.js"; -import { expectElement } from "./editor.js"; - -/** - * Screenshots an element that may be taller than the browser window, at full - * resolution. - * - * Grow the tester iframe so it paints the complete element. Vitest 5 handles - * removing the iframe's fit-to-window transform during capture, so this helper - * only manages the capture height and restores the suite's default viewport. - * A fixed height also lets the static-rendering equality test compare renders - * whose content heights differ slightly against the same baseline. - */ -export async function screenshotFull( - element: HTMLElement, - name: string, - options?: { - /** - * Fixed capture height instead of measuring the element. Required when - * two different renders are compared against one baseline (e.g. the - * static-rendering equality test): measured heights differ by a few px - * between renders, and a dimension mismatch fails before pixels are even - * compared. Pass `document.documentElement` as the element then - its box - * is the (grown) iframe viewport, so the dimensions are exact. - */ - height?: number; - comparatorOptions?: { - allowedMismatchedPixelRatio?: number; - allowedMismatchedPixels?: number; - }; - screenshotOptions?: { - scale?: "css" | "device"; - mask?: readonly unknown[]; - }; - }, -) { - const height = - options?.height ?? - Math.max(720, Math.ceil(element.getBoundingClientRect().bottom) + 40); - await page.viewport(1280, height); - try { - await expectElement(element).toMatchScreenshot(name, { - ...(options?.comparatorOptions && { - comparatorOptions: options.comparatorOptions, - }), - ...(options?.screenshotOptions && { - screenshotOptions: options.screenshotOptions, - }), - } as never); - } finally { - await page.viewport(1280, 720); - } -} +export { screenshotFull } from "../commands/browser/screenshotFull.js"; diff --git a/tests/tsconfig.browser.json b/tests/tsconfig.browser.json index 3be3c407a1..cb62e86c54 100644 --- a/tests/tsconfig.browser.json +++ b/tests/tsconfig.browser.json @@ -11,7 +11,6 @@ "esModuleInterop": true, "types": ["node", "vite-plus/client"], "paths": { - "@root/*": ["../*"], "@shared/*": ["../shared/*"], "@blocknote/mantine": ["./node_modules/@blocknote/mantine"], "@blocknote/react": ["./node_modules/@blocknote/react"], diff --git a/tests/vite.config.browser.ts b/tests/vite.config.browser.ts index 6dbe5a9b83..ed1964b40a 100644 --- a/tests/vite.config.browser.ts +++ b/tests/vite.config.browser.ts @@ -90,7 +90,6 @@ export default defineConfig( // src/examples.d.ts. alias: { ...blockNoteSrcAliases, - "@root": path.resolve(__dirname, ".."), // The shared test-utils package lives at the repo root (not under // packages/), so it isn't picked up by the packages scan above. // All consumers - test code and example apps alike - import it via From 0027dcab83cb205eb7935780e797d13998f19067 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 18 Nov 2026 16:43:41 +0100 Subject: [PATCH 10/14] test: simplify document diffs into readable markup --- .../BasicTextStyleButton.browser.test.tsx | 87 +--- .../ColorStyleButton.browser.test.tsx | 110 +---- .../CreateLinkButton.browser.test.tsx | 42 +- .../NestBlockButtons.browser.test.tsx | 42 +- .../TextAlignButton.browser.test.tsx | 266 +++++++---- .../BlockTypeSelect.browser.test.tsx | 81 +--- tests/src/commands/node/compareDocuments.ts | 420 ++++++++++++------ tests/src/commands/node/index.ts | 7 +- 8 files changed, 535 insertions(+), 520 deletions(-) diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx index 2dcec23276..a5710fa4a5 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -100,7 +100,6 @@ describe("BasicTextStyleButton", () => { initialContent: [ { id: "format", type: "paragraph", content: "Format this text" }, ], - // The button reads editor context directly; no toolbar is needed. props: { formattingToolbar: false }, children: , }); @@ -109,30 +108,18 @@ describe("BasicTextStyleButton", () => { name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, exact: true, }); + const plain = + 'Format this text'; + const styled = `Format this text`; for (const state of ["on", "off"] as const) { const before = editor.document; await button.click(); - expect(compareDocuments(before, editor.document)).toEqual([ - { - type: "update", - id: "format", - changes: [ - state === "on" - ? { - op: "add", - path: `/content/0/styles/${basicTextStyle}`, - value: true, - } - : { - op: "remove", - path: `/content/0/styles/${basicTextStyle}`, - }, - ], - }, - ]); + expect(compareDocuments(before, editor.document)).toEqual( + `BEFORE:\n${state === "on" ? plain : styled}\n\nAFTER:\n${state === "on" ? styled : plain}`, + ); await expect .element(button) .toHaveAttribute("aria-pressed", String(state === "on")); @@ -169,40 +156,18 @@ describe("BasicTextStyleButton", () => { name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, exact: true, }); + const selectedStyles = + basicTextStyle === "code" + ? "code=true" + : `${basicTextStyle}=true textColor="red"`; await button.click(); - expect(compareDocuments(before, editor.document)).toEqual([ - { - type: "update", - id: "format", - changes: [ - { op: "replace", path: "/content/0/text", value: "Before " }, - { - op: "add", - path: "/content/1", - value: { - type: "text", - text: "selected", - // Inline code excludes other formatting styles. - styles: - basicTextStyle === "code" - ? { code: true } - : { textColor: "red", [basicTextStyle]: true }, - }, - }, - { - op: "add", - path: "/content/2", - value: { - type: "text", - text: " after", - styles: { textColor: "red" }, - }, - }, - ], - }, - ]); + expect(compareDocuments(before, editor.document)).toEqual(`BEFORE: +Before selected after + +AFTER: +Before selected after`); }, ); @@ -226,23 +191,11 @@ describe("BasicTextStyleButton", () => { await button.click(); await userEvent.keyboard(" typed"); - expect(compareDocuments(before, editor.document)).toEqual([ - { - type: "update", - id: "format", - changes: [ - { - op: "add", - path: "/content/1", - value: { - type: "text", - text: " typed", - styles: { [basicTextStyle]: true }, - }, - }, - ], - }, - ]); + expect(compareDocuments(before, editor.document)).toEqual(`BEFORE: +Existing + +AFTER: +Existing typed`); }, ); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx index 6e0310edca..da56e321d3 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -165,39 +165,11 @@ describe("ColorStyleButton", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/content/0/text", - "value": "Before ", - }, - { - "op": "add", - "path": "/content/1", - "value": { - "styles": { - "textColor": "gray", - }, - "text": "selected", - "type": "text", - }, - }, - { - "op": "add", - "path": "/content/2", - "value": { - "styles": {}, - "text": " after", - "type": "text", - }, - }, - ], - "id": "text", - "type": "update", - }, - ] + "BEFORE: + Before selected after + + AFTER: + Before selected after" `); await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); @@ -233,39 +205,11 @@ describe("ColorStyleButton", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/content/0/text", - "value": "Before ", - }, - { - "op": "add", - "path": "/content/1", - "value": { - "styles": { - "backgroundColor": "gray", - }, - "text": "selected", - "type": "text", - }, - }, - { - "op": "add", - "path": "/content/2", - "value": { - "styles": {}, - "text": " after", - "type": "text", - }, - }, - ], - "id": "text", - "type": "update", - }, - ] + "BEFORE: + Before selected after + + AFTER: + Before selected after" `); await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); @@ -311,18 +255,11 @@ describe("ColorStyleButton", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "remove", - "path": "/content/0/styles/textColor", - }, - ], - "id": "text", - "type": "update", - }, - ] + "BEFORE: + Selected text + + AFTER: + Selected text" `); }); @@ -366,18 +303,11 @@ describe("ColorStyleButton", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "remove", - "path": "/content/0/styles/backgroundColor", - }, - ], - "id": "text", - "type": "update", - }, - ] + "BEFORE: + Selected text + + AFTER: + Selected text" `); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx index 96c4374cc7..8ef2c86804 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -111,43 +111,11 @@ describe("CreateLinkButton", () => { await pressKey("Enter"); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/content/0/text", - "value": "Before ", - }, - { - "op": "add", - "path": "/content/1", - "value": { - "content": [ - { - "styles": {}, - "text": "selected text", - "type": "text", - }, - ], - "href": "https://example.com", - "type": "link", - }, - }, - { - "op": "add", - "path": "/content/2", - "value": { - "styles": {}, - "text": " after", - "type": "text", - }, - }, - ], - "id": "text", - "type": "update", - }, - ] + "BEFORE: + Before selected text after + + AFTER: + Before selected text after" `); await expect.element(input).not.toBeInTheDocument(); await expect.element(page.getByRole("textbox")).toHaveFocus(); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx index cde92d0690..43e1b1fe90 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -60,20 +60,13 @@ describe("NestBlockButtons", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "from": { - "index": 1, - "parentId": null, - }, - "id": "selected", - "to": { - "index": 0, - "parentId": "parent", - }, - "type": "move", - }, - ] + "BEFORE: + Selected text + + AFTER: + Parent + Selected text + " `); }); @@ -109,20 +102,13 @@ describe("NestBlockButtons", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "from": { - "index": 0, - "parentId": "parent", - }, - "id": "selected", - "to": { - "index": 1, - "parentId": null, - }, - "type": "move", - }, - ] + "BEFORE: + Parent + Selected text + + + AFTER: + Selected text" `); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx index f6143a5a73..2fa5cb1b4a 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -35,51 +35,165 @@ describe("TextAlignButton", () => { }); describe("integration", () => { - it.for(["left", "center", "right", "justify"] as const)( - "aligns the selected block %s without changing its text or neighboring blocks", - async ( - alignment, - { setupEditor, selectText, compareDocuments, page }, - ) => { - const { editor } = await setupEditor({ - initialContent: [ - { id: "before", type: "paragraph", content: "Before" }, - { - id: "selected", - type: "paragraph", - props: { - textAlignment: alignment === "left" ? "center" : "left", - }, - content: "Selected text", - }, - { id: "after", type: "paragraph", content: "After" }, - ], - props: { formattingToolbar: false }, - children: , - }); - selectText(editor, "Selected text"); - const documentBefore = editor.document; - const button = page.getByRole("button", { - name: editor.dictionary.formatting_toolbar[`align_${alignment}`] - .tooltip, - exact: true, - }); - await expect.element(button).toHaveAttribute("aria-pressed", "false"); + it("aligns the selected block left without changing its text or neighboring blocks", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { + id: "selected", + type: "paragraph", + props: { textAlignment: "center" }, + content: "Selected text", + }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const before = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_left.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); - await button.click(); + await button.click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); - expect(compareDocuments(documentBefore, editor.document)).toEqual([ + it("aligns the selected block center without changing its text or neighboring blocks", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, { - type: "update", id: "selected", - changes: [ - { op: "replace", path: "/props/textAlignment", value: alignment }, - ], + type: "paragraph", + props: { textAlignment: "left" }, + content: "Selected text", }, - ]); - await expect.element(button).toHaveAttribute("aria-pressed", "true"); - }, - ); + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const before = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + await button.click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); + + it("aligns the selected block right without changing its text or neighboring blocks", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { + id: "selected", + type: "paragraph", + props: { textAlignment: "left" }, + content: "Selected text", + }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const before = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_right.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + await button.click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); + + it("aligns the selected block justify without changing its text or neighboring blocks", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "before", type: "paragraph", content: "Before" }, + { + id: "selected", + type: "paragraph", + props: { textAlignment: "left" }, + content: "Selected text", + }, + { id: "after", type: "paragraph", content: "After" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const before = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_justify.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + await button.click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + }); it("aligns every selected block without changing an unselected neighbor", async ({ setupEditor, @@ -106,30 +220,13 @@ describe("TextAlignButton", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/props/textAlignment", - "value": "center", - }, - ], - "id": "first", - "type": "update", - }, - { - "changes": [ - { - "op": "replace", - "path": "/props/textAlignment", - "value": "center", - }, - ], - "id": "second", - "type": "update", - }, - ] + "BEFORE: + First + Second + + AFTER: + First + Second" `); }); @@ -175,24 +272,29 @@ describe("TextAlignButton", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/content/rows/0/cells/0/props/textAlignment", - "value": "center", - }, - { - "op": "replace", - "path": "/content/rows/0/cells/1/props/textAlignment", - "value": "center", - }, - ], - "id": "table", - "type": "update", - }, - ] + "BEFORE: + + + First + Second + + + Third + Fourth + +
+ + AFTER: + + + First + Second + + + Third + Fourth + +
" `); }); }); diff --git a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx index 7c71763cfd..d4aa888c21 100644 --- a/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -134,30 +134,12 @@ describe("BlockTypeSelect", () => { expect(compareDocuments(documentBefore, editor.document)) .toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/type", - "value": "heading", - }, - { - "op": "add", - "path": "/props/level", - "value": 1, - }, - { - "op": "add", - "path": "/props/isToggleable", - "value": false, - }, - ], - "id": "selected", - "type": "update", - }, - ] - `); + "BEFORE: + Selected text + + AFTER: + Selected text" + `); await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); await expect .element( @@ -200,50 +182,13 @@ describe("BlockTypeSelect", () => { .click(); expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` - [ - { - "changes": [ - { - "op": "replace", - "path": "/type", - "value": "heading", - }, - { - "op": "add", - "path": "/props/level", - "value": 1, - }, - { - "op": "add", - "path": "/props/isToggleable", - "value": false, - }, - ], - "id": "first", - "type": "update", - }, - { - "changes": [ - { - "op": "replace", - "path": "/type", - "value": "heading", - }, - { - "op": "add", - "path": "/props/level", - "value": 1, - }, - { - "op": "add", - "path": "/props/isToggleable", - "value": false, - }, - ], - "id": "second", - "type": "update", - }, - ] + "BEFORE: + First + Second + + AFTER: + First + Second" `); }); }); diff --git a/tests/src/commands/node/compareDocuments.ts b/tests/src/commands/node/compareDocuments.ts index b6e272e9a8..08cb14f9e7 100644 --- a/tests/src/commands/node/compareDocuments.ts +++ b/tests/src/commands/node/compareDocuments.ts @@ -1,113 +1,170 @@ -/** The structural contract also accepts blocks from custom schemas, unchanged. */ +import { defaultBlockSpecs, type BlockSchema } from "@blocknote/core"; + +const defaultBlockSchema: BlockSchema = Object.fromEntries( + Object.entries(defaultBlockSpecs).map(([type, spec]) => [type, spec.config]), +); + +/** Minimum input contract, including blocks from custom schemas. */ export type DocumentBlock = { id: string; children: readonly DocumentBlock[]; }; -export type BlockLocation = { parentId: string | null; index: number }; - -/** JSON Patch operations, with JSON Pointer paths relative to the block. */ -export type FieldChange = - | { op: "add" | "replace"; path: string; value: unknown } - | { op: "remove"; path: string }; +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} -export type DocumentChange = - | { type: "update"; id: string; changes: FieldChange[] } - | { type: "insert"; block: B; at: BlockLocation } - | { type: "delete"; id: string; at: BlockLocation } - | { type: "move"; id: string; from: BlockLocation; to: BlockLocation }; +function equal(before: unknown, after: unknown): boolean { + if (Object.is(before, after)) { + return true; + } + if (Array.isArray(before) && Array.isArray(after)) { + return ( + before.length === after.length && + before.every((value, index) => equal(value, after[index])) + ); + } + if (record(before) && record(after)) { + return ( + Object.keys(before).length === Object.keys(after).length && + Object.keys(before).every( + (key) => Object.hasOwn(after, key) && equal(before[key], after[key]), + ) + ); + } + return false; +} -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); +function escapeText(value: string) { + return value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">"); } -function pointerToken(key: string) { - return key.replaceAll("~", "~0").replaceAll("/", "~1"); +function attributes(fields: Record) { + return Object.entries(fields) + .map(([key, value]) => ` ${key}=${JSON.stringify(value)}`) + .join(""); } -/** Diff JSON-shaped data without string normalization or character-level diffs. */ -export function compareValues( - before: unknown, - after: unknown, - path = "", -): FieldChange[] { - if (Object.is(before, after)) { - return []; +function inline( + value: unknown, + preserveRuns = false, + counterpart?: unknown, +): string { + if (typeof value === "string") { + return `${escapeText(value)}`; } - if (Array.isArray(before) && Array.isArray(after)) { - const changes: FieldChange[] = []; - const commonLength = Math.min(before.length, after.length); - for (let index = 0; index < commonLength; index++) { - changes.push( - ...compareValues(before[index], after[index], `${path}/${index}`), - ); - } - // Descending removals keep these operations valid when applied in order. - for (let index = before.length - 1; index >= after.length; index--) { - changes.push({ op: "remove", path: `${path}/${index}` }); - } - for (let index = commonLength; index < after.length; index++) { - changes.push({ - op: "add", - path: `${path}/${index}`, - value: structuredClone(after[index]), - }); - } - return changes; - } - if (isRecord(before) && isRecord(after)) { - const changes: FieldChange[] = []; - for (const key of Object.keys(before)) { - const childPath = `${path}/${pointerToken(key)}`; - if (!Object.hasOwn(after, key)) { - changes.push({ op: "remove", path: childPath }); - } else { - changes.push(...compareValues(before[key], after[key], childPath)); - } - } - for (const key of Object.keys(after)) { - if (!Object.hasOwn(before, key)) { - changes.push({ - op: "add", - path: `${path}/${pointerToken(key)}`, - value: structuredClone(after[key]), - }); - } - } - return changes; + if (Array.isArray(value)) { + return value.map((item) => inline(item, preserveRuns)).join(""); } - return [{ op: "replace", path, value: structuredClone(after) }]; + if (!record(value)) { + return escapeText(JSON.stringify(value) ?? "undefined"); + } + const { type, text, styles, content, ...props } = value; + if (type === "text" && typeof text === "string" && record(styles)) { + const fields = { ...styles, ...props }; + return Object.keys(fields).length || preserveRuns || text === "" + ? `${escapeText(text)}` + : escapeText(text); + } + if (type === "tableContent" && Array.isArray(value.rows)) { + const { rows, type: _type, ...metadata } = value; + const otherRows = + record(counterpart) && + counterpart.type === "tableContent" && + Array.isArray(counterpart.rows) && + counterpart.rows.length === rows.length + ? counterpart.rows + : []; + return `\n${rows + .map((row, index) => { + if (!record(row) || !Array.isArray(row.cells)) { + return ` ${escapeText(JSON.stringify(row))}`; + } + const { cells, ...rowProps } = row; + const otherRow = otherRows[index]; + const otherCells = + record(otherRow) && + Array.isArray(otherRow.cells) && + otherRow.cells.length === cells.length + ? otherRow.cells + : []; + return ` \n${cells + .map((cell, cellIndex) => { + if (Array.isArray(cell)) { + return ` ${inline(cell, preserveRuns)}`; + } + if (record(cell)) { + const { content, ...cellProps } = cell; + const otherCell = otherCells[cellIndex]; + if ( + record(cellProps.props) && + record(otherCell) && + record(otherCell.props) + ) { + const otherProps = otherCell.props; + const changedProps = Object.fromEntries( + Object.entries(cellProps.props).filter( + ([key, value]) => + !Object.hasOwn(otherProps, key) || + !equal(value, otherProps[key]), + ), + ); + if (Object.keys(changedProps).length) { + cellProps.props = changedProps; + } else { + delete cellProps.props; + } + } + return ` ${inline(content, preserveRuns)}`; + } + return ` ${escapeText(JSON.stringify(cell))}`; + }) + .join("\n")}\n `; + }) + .join("\n")}\n`; + } + const tag = type === "link" ? "link" : "inline"; + const fields = type === "link" ? props : { type, ...props }; + if (text !== undefined) { + fields.text = text; + } + if (styles !== undefined) { + fields.styles = styles; + } + return content === undefined + ? `<${tag}${attributes(fields)} />` + : `<${tag}${attributes(fields)}>${inline(content, preserveRuns)}`; } -function snapshot( - document: readonly B[], -) { - const byId = new Map(); +function snapshot(blocks: readonly DocumentBlock[]) { + const byId = new Map< + string, + { block: DocumentBlock; parentId: string | null } + >(); const siblings = new Map(); - function visit(blocks: readonly B[], parentId: string | null) { + function visit(children: readonly DocumentBlock[], parentId: string | null) { siblings.set( parentId, - blocks.map((block) => block.id), + children.map((block) => block.id), ); - blocks.forEach((block, index) => { - if ( - typeof block.id !== "string" || - block.id.length === 0 || - byId.has(block.id) - ) { + for (const block of children) { + if (typeof block.id !== "string" || !block.id || byId.has(block.id)) { throw new Error( `Document requires unique, nonempty block IDs: ${block.id}`, ); } - byId.set(block.id, { block, at: { parentId, index } }); + byId.set(block.id, { block, parentId }); visit(block.children, block.id); - }); + } } - visit(document, null); + visit(blocks, null); return { byId, siblings }; } -/** Keep a deterministic longest increasing subsequence; report only the rest. */ +/** Ignore index shifts from insertions/deletions; retain a stable subsequence. */ function reordered(before: readonly string[], after: readonly string[]) { const positions = new Map(before.map((id, index) => [id, index])); const common = after.filter((id) => positions.has(id)); @@ -137,83 +194,162 @@ function reordered(before: readonly string[], after: readonly string[]) { return common.filter((id) => !kept.has(id)); } +function renderDocument( + blocks: readonly DocumentBlock[], + changed: Set, + counterparts: ReturnType["byId"], + blockSchema: BlockSchema, + parentPath: number[] = [], + includeSubtree = false, + preserveRuns = false, +): string[] { + return blocks.flatMap((block, index) => { + const path = [...parentPath, index]; + const { children, content, ...fields } = { content: undefined, ...block }; + const counterpart = counterparts.get(block.id)?.block; + const otherFields: Record = counterpart ?? {}; + const otherProps = record(otherFields.props) ? otherFields.props : {}; + const visibleFields: Record = { ...fields }; + if (record(visibleFields.props)) { + const defaults = + typeof visibleFields.type === "string" + ? blockSchema[visibleFields.type]?.propSchema + : undefined; + const props = Object.fromEntries( + Object.entries(visibleFields.props).filter(([key, value]) => + counterpart + ? !Object.hasOwn(otherProps, key) || !equal(value, otherProps[key]) + : !defaults || + !Object.hasOwn(defaults, key) || + !equal(value, defaults[key].default), + ), + ); + if (Object.keys(props).length) { + visibleFields.props = props; + } else { + delete visibleFields.props; + } + } + const include = includeSubtree || changed.has(block.id); + const nested = renderDocument( + children, + changed, + counterparts, + blockSchema, + path, + include, + preserveRuns, + ); + if (!include && !nested.length) { + return []; + } + const normalizedId = block.id.toLowerCase().replace(/[^a-z0-9-]/g, "-"); + const tag = `block-${normalizedId}`; + // Preserve the original identity if normalization changes it. + delete visibleFields.id; + const originalId = + normalizedId === block.id + ? "" + : ` id="${escapeText(block.id).replaceAll('"', """)}"`; + const indent = " ".repeat(parentPath.length); + const opening = `${indent}<${tag} path="${path.join(".")}"${originalId}${attributes(visibleFields)}`; + const body = + content === undefined + ? "" + : inline(content, preserveRuns, otherFields.content); + if (nested.length) { + return [`${opening}>${body}`, ...nested, `${indent}`]; + } + return [ + content === undefined + ? `${opening}>` + : `${opening}>${body}`, + ]; + }); +} + /** - * Compare final snapshots, not editing activity. Locations refer to the original - * before/after documents, not a sequentially executable global patch. + * Format changed blocks as BEFORE/AFTER markup for document assertions. * - * Insertions/deletions report only roots of newly added/removed subtrees. Insert - * payloads retain the complete, unmodified subtree. Surviving descendants still - * receive moves/updates independently, including when their parent is new/deleted. - * Order: deletes (before preorder), then inserts/moves/updates (after preorder). - * A moved block can also be updated; id/children never appear in field changes. - * Inputs must be JSON-shaped block documents with unique, nonempty IDs. + * Compare final JSON-shaped documents, not editing activity. Unchanged blocks + * are omitted, except containers needed to show nesting and descendants of + * changed blocks. Index paths identify original positions, including moves; + * insertions/deletions alone do not mark shifted siblings as changed. + * Matching block-ID tags identify containers; their `path` attribute records + * position. IDs are normalized for tag names, retaining the original ID as an + * attribute when normalization changes it. + * + * Unchanged block props are omitted. Changed props retain both values, including + * defaults. Inserted/deleted blocks omit schema defaults; pass `blockSchema` for + * custom schemas. Unknown defaults are never guessed. + * Corresponding table cells omit unchanged props when their row/cell counts + * match; structural table edits keep unmatched cell props. Nested block tags + * are indented without reformatting literal content whitespace. + * + * Custom props, styles, inline content, and tables are retained. Text is escaped, + * and otherwise invisible text-run splits are shown with explicit text tags. + * Inputs require unique, nonempty block IDs. Neither input is mutated. + * + * @example + * const before = editor.document; + * await button.click(); + * expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(); */ export function compareDocuments< - B extends { id: string; children: readonly B[] }, + Before extends DocumentBlock, + After extends DocumentBlock, >( - beforeDocument: readonly B[], - afterDocument: readonly B[], -): DocumentChange[] { + beforeDocument: readonly Before[], + afterDocument: readonly After[], + { blockSchema = defaultBlockSchema }: { blockSchema?: BlockSchema } = {}, +): string { const before = snapshot(beforeDocument); const after = snapshot(afterDocument); - const moved = new Set(); + const changed = new Set(); + let preserveRuns = false; for (const [parentId, nextOrder] of after.siblings) { for (const id of reordered( before.siblings.get(parentId) ?? [], nextOrder, )) { - moved.add(id); + changed.add(id); } } - const changes: DocumentChange[] = []; - for (const [id, entry] of before.byId) { + for (const id of before.byId.keys()) { + if (!after.byId.has(id)) { + changed.add(id); + } + } + for (const [id, next] of after.byId) { + const prev = before.byId.get(id); + if (!prev) { + changed.add(id); + continue; + } + const { + children: _beforeChildren, + ...beforeFields + }: Record = prev.block; + const { + children: _afterChildren, + ...afterFields + }: Record = next.block; + if (prev.parentId !== next.parentId || !equal(beforeFields, afterFields)) { + changed.add(id); + } + // Ordinary rendering joins adjacent unstyled runs. Expose their boundaries + // when different content would otherwise produce the same visible markup. + const beforeContent = beforeFields.content; + const afterContent = afterFields.content; if ( - !after.byId.has(id) && - (entry.at.parentId === null || after.byId.has(entry.at.parentId)) + !equal(beforeContent, afterContent) && + inline(beforeContent) === inline(afterContent) ) { - changes.push({ type: "delete", id, at: { ...entry.at } }); + preserveRuns = true; } } - // Walk the typed input for insert payloads, preserving its schema type. - function visit(blocks: readonly B[]) { - for (const block of blocks) { - const next = after.byId.get(block.id)!; - const prev = before.byId.get(block.id); - if (!prev) { - if (next.at.parentId === null || before.byId.has(next.at.parentId)) { - changes.push({ - type: "insert", - block: structuredClone(block), - at: { ...next.at }, - }); - } - } else { - if (prev.at.parentId !== next.at.parentId || moved.has(block.id)) { - changes.push({ - type: "move", - id: block.id, - from: { ...prev.at }, - to: { ...next.at }, - }); - } - const { - id: _beforeId, - children: _beforeChildren, - ...beforeFields - } = prev.block; - const { - id: _afterId, - children: _afterChildren, - ...afterFields - } = block; - const fields = compareValues(beforeFields, afterFields); - if (fields.length) { - changes.push({ type: "update", id: block.id, changes: fields }); - } - } - visit(block.children); - } + if (!changed.size) { + return "(no changes)"; } - visit(afterDocument); - return changes; + return `BEFORE:\n${renderDocument(beforeDocument, changed, after.byId, blockSchema, [], false, preserveRuns).join("\n") || "(none)"}\n\nAFTER:\n${renderDocument(afterDocument, changed, before.byId, blockSchema, [], false, preserveRuns).join("\n") || "(none)"}`; } diff --git a/tests/src/commands/node/index.ts b/tests/src/commands/node/index.ts index 1939bc053b..84103e9f83 100644 --- a/tests/src/commands/node/index.ts +++ b/tests/src/commands/node/index.ts @@ -1,9 +1,4 @@ // Baseline helpers run directly in Node/jsdom and in browser tests. export { compareDocuments } from "./compareDocuments.js"; -export type { - BlockLocation, - DocumentBlock, - DocumentChange, - FieldChange, -} from "./compareDocuments.js"; +export type { DocumentBlock } from "./compareDocuments.js"; export { selectText } from "./selectText.js"; From b436383a6c3e62ed3cd042108a21c2ff48d49eab Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Thu, 19 Nov 2026 10:54:13 +0100 Subject: [PATCH 11/14] test: provide global editor fixtures for each environment --- .claude/skills/testing-skill/SKILL.md | 56 +++++++++-------- .../references/component-testing.md | 61 ++++++++++++------- packages/ariakit/tsconfig.json | 1 + packages/ariakit/vite.config.ts | 2 +- packages/code-block/tsconfig.json | 3 +- packages/code-block/vite.config.ts | 5 +- packages/core/tsconfig.json | 2 +- packages/core/vite.config.ts | 7 ++- packages/diagram-block/tsconfig.json | 1 + packages/diagram-block/vite.config.ts | 5 +- packages/mantine/tsconfig.json | 1 + packages/mantine/vite.config.ts | 2 +- packages/math-block/tsconfig.json | 1 + packages/math-block/vite.config.ts | 5 +- packages/react/tsconfig.json | 2 +- packages/react/vite.config.ts | 5 +- packages/server-util/tsconfig.json | 1 + packages/server-util/vite.config.ts | 5 +- packages/shadcn/tsconfig.json | 1 + packages/shadcn/vite.config.ts | 2 +- packages/xl-ai-server/tsconfig.json | 1 + packages/xl-ai-server/vite.config.ts | 2 +- packages/xl-ai/tsconfig.json | 1 + packages/xl-ai/vite.config.ts | 5 +- packages/xl-docx-exporter/tsconfig.json | 1 + packages/xl-docx-exporter/vite.config.ts | 5 +- packages/xl-email-exporter/tsconfig.json | 1 + packages/xl-email-exporter/vite.config.ts | 5 +- packages/xl-multi-column/tsconfig.json | 1 + packages/xl-multi-column/vite.config.ts | 5 +- packages/xl-odt-exporter/tsconfig.json | 1 + packages/xl-odt-exporter/vite.config.ts | 5 +- packages/xl-pdf-exporter/tsconfig.json | 1 + packages/xl-pdf-exporter/vite.config.ts | 5 +- packages/xl-typst-compiler/tsconfig.json | 3 +- packages/xl-typst-compiler/vite.config.ts | 1 + packages/xl-typst-exporter/tsconfig.json | 1 + packages/xl-typst-exporter/vite.config.ts | 1 + tests/src/commands/node/setupEditor.ts | 25 +++----- tests/src/fixtures/editor.node.ts | 2 +- tests/tsconfig.json | 1 + tests/tsconfig.node.json | 25 ++++++++ tests/vite.config.ts | 2 +- tests/vitestSetup.node-fixtures.ts | 8 +++ tsconfig.json | 1 + 45 files changed, 191 insertions(+), 86 deletions(-) create mode 100644 tests/tsconfig.node.json create mode 100644 tests/vitestSetup.node-fixtures.ts diff --git a/.claude/skills/testing-skill/SKILL.md b/.claude/skills/testing-skill/SKILL.md index 616018c38e..1b1c56fe27 100644 --- a/.claude/skills/testing-skill/SKILL.md +++ b/.claude/skills/testing-skill/SKILL.md @@ -7,20 +7,17 @@ description: Rules and examples for placing, writing, and running unit, integrat ## Decide where to test -Test behavior beside its owner, at the lowest reasonable rung of the test ladder that can reliably prove it works: +Use the lowest rung that can reliably prove the behavior: -| Rung | Environment and location | -| ---------------------------- | ------------------------------------------------------------------------------------------------------- | -| 1. Unit | Node, colocated `packages/*/src/**/*.test.ts`. | -| 2. Browser component | Real DOM/rendering, colocated `*.browser.test.{ts,tsx}`; includes focused component integrations. | -| 3. Cross-package integration | Node, `tests/src/unit`; documents through real pipelines, parsing, and exports. | -| 4. Browser e2e | `tests/src/end-to-end`; broader journeys and complete browser pipelines. | -| 5. Mobile-emulated | `end-to-end/mobile/**`, Android browser instance; touch, viewport, emulated IME differences. | -| 6. Real device | Only behavior emulation cannot establish; device suite is parked on `mobile/emulator-layer` (PR #3034). | +1. Colocated: `.test.ts`, or `.browser.test.ts` when browser APIs are needed. Test behavior owned by one function/component, including its integration with dependencies. +2. Subsystem integration: `/tests/src/integration/` for important cross-package behavior without a single owner, such as HTML conversion or clipboard pipelines. +3. End-to-end: `/tests/src/end-to-end/` for complete journeys across subsystems, including browser and server-side usage. -The ladder guides placement, not a requirement to try every environment. Use a real browser for rendered component interactions, actual focus/traversal, and browser-dependent input behavior. Prefer Node/jsdom for editor keyboard shortcut handlers: establish editor state and selection directly, then dispatch a keyboard event, avoiding layout-dependent browser navigation. Editor/document logic also stays in faster Node tests, where `setupEditor` mounts the core editor in jsdom. Rungs 2 and 3 distinguish ownership/location, not strictly runtime cost. +IMPORTANT: ONLY use `.browser.test.ts` when we are missing APIs in Node (e.g. DOM, window APIs, etc). If it can be tested in Node without touching or having to mock browser APIs, it should be done for speed. We should not be spinning up a browser to test that 2 + 2 = 4. We used to leverage JSDom for simulating part of the browser API within Node, this is now FORBIDDEN for new files, if something touches a browser API, it ought to run in the browser. -Integrations verify boundaries, not repeat dependencies' tests. A parent assumes its children work: test toolbar composition/traversal at the toolbar, button activation at the button, and detailed document operations at their editor commands. +Maxim: we should be testing as low-level in the ladder as we can. Most tests should be colocated (Rung 1); broader integrations (Rung 2) and journeys (Rung 3) should be progressively fewer. E2E tests are a last line of defense, not the first place you add tests to. + +Given that files import each other, there can be overlap and ambiguity to where something should be tested. Generally, we should be writing at least an order of magnitude more unit tests than integration tests. Where, in a parent-child relationship, the child should be testing it's own unit (the code and logic that it actively owns, not imported, or shapes it receives from elsewhere), and the parent should assume all its children's work. The parent should test for concerns that it owns (its unit), and for interactions with external behaviors that it's children cannot verify on it's own (its integration of its children). Integration tests are for verifying boundaries, not duplicating work. ## Rules @@ -39,7 +36,7 @@ Integrations verify boundaries, not repeat dependencies' tests. A parent assumes ## Structure and assertions -Component browser files have one owner-named outer `describe` and applicable groups in this order: `unit`, `integration`, `keyboard`, `a11y`. Reasonably cover each applicable category; omit irrelevant groups. ARIA assertions and axe scans share `a11y`; there is no separate `axe` group. Accessibility belongs alongside normal behavior. +For component file structure, test groups, and accessibility assertions, follow [Component testing](references/component-testing.md). Pure-function tests use a function-named `describe`; give integrated scenarios a separate `describe` when needed. Follow established patterns without inventing unnecessary structure. @@ -49,35 +46,40 @@ Pure-function tests use a function-named `describe`; give integrated scenarios a | Inline snapshot | Small serialized results; prefer inline when readable. Size is a guideline, not a cutoff. | | External snapshot | Large documents, exports, or trees whose output would obscure the test. | +For document mutations, prefer `compareDocuments(before, editor.document)` with inline snapshots. Use `toEqual` when parameterized expectations are clearer. + Screenshots are a last resort for behavior. Prefer state, DOM, or accessibility assertions; do not compare before/after screenshots to prove a click worked. A few deliberate subsystem baselines can guard visual regressions, with awareness of false positives. ## Golden examples -- [BasicTextStyleButton](../../../packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx): component behavior, editor integration, keyboard, a11y (ARIA and axe). -- [FormattingToolbar](../../../packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx): composition and traversal of child controls. +- Child React component test: [BasicTextStyleButton](../../../packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx): component behavior, editor integration, ARIA, axe, and keyboard. +- Parent React component test: [FormattingToolbar](../../../packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx): composition and traversal of child controls. Use these as patterns, not templates to copy mechanically. For testing a React component, read [Component testing](references/component-testing.md). ## Editor setup -Use `const { editor } = await setupEditor({ ...editorOptions })` in either environment. Browser tests receive it from the shared fixture; it renders a view and additionally accepts `skin`, `props`, `children`, and `outside`, returning `rerender` too. Node tests import `test` from `tests/src/fixtures/editor.node.ts` and use the jsdom environment; their helper mounts the core editor without React or skin styles. Both preserve custom-schema types and clean up after the test. For headless logic, use `BlockNoteEditor.create` directly. +Use `const { editor } = await setupEditor({ ...editorOptions })` in either environment. The global `it` supplies correctly typed helpers for the current test environment; do not import `it` or a fixture-specific test function. Browser setup renders a view and additionally accepts `skin`, `props`, `children`, and `outside`, returning `rerender` too. Node setup creates a headless editor without DOM mounting or jsdom. Both preserve custom-schema types and clean up after the test. -`insertBlocks` returns an array of inserted BlockNote blocks. The conversion to a ProseMirror node is `blockToNode`: +The same test works in either environment: ```ts -import { blockToNode } from "@blocknote/core"; - -const [block] = editor.insertBlocks( - [{ type: "paragraph", content: "Inserted text" }], - "existing-block-id", - "after", -); -const node = editor.transact((tr) => - blockToNode(block, tr.doc.type.schema, editor.schema.styleSchema), -); +import { expect } from "vite-plus/test"; + +it("updates a block's background color", async ({ setupEditor }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "paragraph", type: "paragraph", content: "Original text" }, + ], + }); + + editor.updateBlock("paragraph", { props: { backgroundColor: "yellow" } }); + + expect(editor.getBlock("paragraph")?.props.backgroundColor).toBe("yellow"); +}); ``` -For shortcut-handler tests, set up the desired state/selection with editor APIs, then simulate the keyboard event in jsdom. A shared event helper is planned; do not invent a browser navigation journey just to reach the shortcut's starting position. Use a browser when layout, native shortcut handling, or real focus movement is itself the contract. +For shortcut-handler tests, set up the desired state/selection with editor APIs, then simulate the keyboard event in node. Do not invent a browser navigation journey just to reach the shortcut's starting position. Use a browser when layout, native shortcut handling, or real focus movement is itself the contract. ## Run diff --git a/.claude/skills/testing-skill/references/component-testing.md b/.claude/skills/testing-skill/references/component-testing.md index 5005a243ee..498239783b 100644 --- a/.claude/skills/testing-skill/references/component-testing.md +++ b/.claude/skills/testing-skill/references/component-testing.md @@ -1,36 +1,57 @@ # React component testing -Use a browser for rendered component interactions, actual keyboard traversal/focus, or other rendering-dependent behavior. Test editor keyboard shortcut handlers in Node/jsdom: set state and selection with editor APIs, then dispatch the event. This avoids brittle layout-dependent navigation; use a browser only when browser behavior is the contract. A shared shortcut-event helper is planned. +Use a browser for rendered component interactions, keyboard traversal/focus, and browser APIs. Follow the [test-placement rules](../SKILL.md#decide-where-to-test); do not introduce jsdom in new files. ## Component structure -Keep behavior and accessibility in one colocated `.browser.test.{ts,tsx}` file. Use an owner-named outer `describe`, then applicable groups in order: +Keep behavior and accessibility in one colocated `.browser.test.{ts,tsx}` file. Use a component-named outer `describe`, then applicable groups in this order; omit irrelevant groups: -| Group | Assert | -| ------------- | ------------------------------------------------------------------------------------------------------------------------ | -| `unit` | The owner's decisions: visibility, schema support, composition, callbacks. | -| `integration` | Subsystems working together: an actual control updates the editor correctly. | -| `keyboard` | Activation, traversal, dismissal, focus destination, visible focus. | -| `a11y` | Names, roles, relationships, pressed/expanded/checked state; axe scans in relevant states, including open menus/dialogs. | +| Group | Assert | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `unit` | Behavior owned by the component, not its dependencies or how its parent uses it. | +| `integration` | Interactions with other components or subsystems, such as an actual control updating the editor. | +| `aria` | ARIA attributes and behaviors: names, roles, relationships, pressed/expanded/checked state, and accessibility-tree snapshots. | +| `axe` | Automated axe scans and violations in relevant states, including open menus/dialogs. | +| `keyboard` | Functionality through keyboard input: activation, traversal, dismissal, focus destination, and visible focus. | -Cover relevant categories reasonably, not every possible combination. A child owns its interaction and focus indicator; a container owns composition, traversal, and exit. ARIA assertions and axe scans share `a11y`. +Cover relevant categories reasonably, not every possible combination. A child owns its interaction and focus indicator; a container owns composition, traversal, and exit. + +Group tests by their primary contract; do not repeat a scenario merely to populate another group. Keyboard tests can also assert ARIA state or editor changes. An accessibility-tree snapshot recording keyboard traversal belongs in `keyboard`; a standalone ARIA-state snapshot belongs in `aria`. ## Setup -Destructure typed helpers from the test context. The [Node fixtures](../../../../tests/src/fixtures/editor.node.ts) provide the baseline editor/document helpers. The [browser fixtures](../../../../tests/src/fixtures/editor.tsx) inherit them, override editor setup with rendering, and add the [browser helpers](../../../../tests/src/commands/index.ts). The browser setup supplies the extended global `it`. Usage documentation lives beside each implementation; Node-only Playwright/CDP transport handlers are registered separately. +Destructure typed helpers from the extended global `it` context. The [browser fixtures](../../../../tests/src/fixtures/editor.tsx) provide editor setup and interaction helpers; usage documentation lives beside the implementations linked from the [fixture definitions](../../../../tests/src/commands/index.ts). ```tsx -const { editor } = await setupEditor({ - initialContent: [{ type: "paragraph", content: "Selected text" }], - props: { formattingToolbar: false }, - children: , +import { BasicTextStyleButton } from "@blocknote/react"; +import { expect } from "vite-plus/test"; + +it("reflects bold state after activation", async ({ + setupEditor, + selectText, + page, +}) => { + const { editor } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Selected text"); + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar.bold.tooltip, + exact: true, + }); + await expect.element(button).toHaveAttribute("aria-pressed", "false"); + + await button.click(); + + await expect.element(button).toHaveAttribute("aria-pressed", "true"); }); -selectText(editor, "Selected text"); ``` Render the component directly with unrelated default UI disabled, rather than navigating a parent merely to reach it. Use the actual control for the action under test; editor APIs may establish the initial state. -Use BlockNote APIs for that setup instead of equivalent ProseMirror operations. Do not access `editor._tiptapEditor`; use `editor.prosemirrorView` when necessary and prefer `editor.transact` over `editor.prosemirrorState` for reads and transactions. See the [editor setup rules](../SKILL.md#editor-setup) for block-to-node conversion. +Follow the [public-editor-API rules](../SKILL.md#rules) when establishing state. Shared rendering handles StrictMode, initial commit, fonts, and cleanup. Wait for later selection-driven UI explicitly. Skin selection defaults to Mantine and loads lazily; loaded CSS remains, so prefer one skin per file. @@ -38,11 +59,9 @@ Prefer accessible locators using dictionary labels. Direct focus is valid setup; Stop navigation as soon as its target is reached and bound repeated keypresses explicitly; fail with the target and limit rather than waiting for a test timeout. `focusUntil` also detects cycles, stalled focus, and document boundaries. -Browser and screen-reader files enforce focused-test, assertion, awaited-poll, floating-promise, command-import, accessible-locator, and explicit-sleep safeguards. The component examples additionally enforce the scoped structure and timer conventions; do not weaken the shared safeguards when extending those rules. - ## Accessibility assertions -- Assert focus with `toHaveFocus()` and check each owned control's indicator independently. +- Assert focus with `toHaveFocus()`. Check each owned control's indicator independently: capture its unfocused appearance with `const compareFocusOutline = captureFocusOutline(control)`, move focus through keyboard input, then `await compareFocusOutline()`. - Scope accessible-state assertions to the control/popup. Use built-in `toMatchAriaInlineSnapshot` / `toMatchAriaSnapshot` for standalone trees. - For container traversal, an ordered sequence of focused controls' trees can detect skipped controls or changed order. Assert that focus can leave the container without prescribing an unrelated next destination. - Scan closed triggers and open UI as applicable. Assert returned axe `violations`; for known issues, match their precise violation/check shapes with an issue link so additional violations fail. Do not mark a whole axe journey `it.fails`. @@ -50,7 +69,7 @@ Browser and screen-reader files enforce focused-test, assertion, awaited-poll, f ## Native screen readers -Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. The native runner installs global `it` from `tests/src/fixtures/editor.screen-reader.ts`; this extends the browser fixtures with `setupScreenReader`, which is not available in ordinary browser tests. The two runners have separate global-type configurations. `const { getTranscript, pressKey } = await setupScreenReader(locator)` starts a session with automatic cleanup, including on failure. The locator is optional when focus is already established. Use the session's `pressKey` to capture speech, not the ordinary keyboard fixture. +Use colocated `*.screen-reader.test.ts` for real speech/navigation that browser assertions cannot establish. The native runner additionally provides `setupScreenReader`: `const { getTranscript, pressKey } = await setupScreenReader(locator)` starts a session with automatic cleanup, including on failure. The locator is optional when focus is already established. Use the session's `pressKey` to capture speech, not the ordinary keyboard fixture. This operates the real desktop using VoiceOver/NVDA and GuidePup permissions. Run only as intentional native verification, outside browser CI: @@ -64,5 +83,5 @@ Configuration: `tests/src/screen-reader/vite.config.screen-reader.ts`. - Mobile-emulated tests cover mobile-specific behavior, not duplicate desktop contracts. Do not use `screenshotFull` in Android-instance tests: its iframe resize drops touch emulation for subsequent tests. - State the limit when emulation cannot reproduce the OS behavior. Real-device suite is parked on `mobile/emulator-layer` (PR #3034). -- Tall screenshots need `tests/src/utils/screenshotFull.ts`: ordinary iframe screenshots can silently clip below the fold; viewport resizing alone can scale the capture. +- For tall screenshots, inject `screenshotFull` from the browser fixtures (`tests/src/commands/browser/screenshotFull.ts`): ordinary iframe screenshots can silently clip below the fold; viewport resizing alone can scale the capture. - Screenshot baselines are browser/Linux-specific. Update in Docker with `--update=true`. Changes within pixel tolerance may leave a stale baseline; remove the specific baseline first when a fresh capture is required. diff --git a/packages/ariakit/tsconfig.json b/packages/ariakit/tsconfig.json index afade32699..eac94eae3d 100644 --- a/packages/ariakit/tsconfig.json +++ b/packages/ariakit/tsconfig.json @@ -22,6 +22,7 @@ "emitDeclarationOnly": true }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/ariakit/vite.config.ts b/packages/ariakit/vite.config.ts index 3073d00262..15df45749b 100644 --- a/packages/ariakit/vite.config.ts +++ b/packages/ariakit/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: ["../../tests/vitestSetup.node-fixtures.ts"], }, plugins: [react(), webpackStats()], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/code-block/tsconfig.json b/packages/code-block/tsconfig.json index 490084381b..765026a8d5 100644 --- a/packages/code-block/tsconfig.json +++ b/packages/code-block/tsconfig.json @@ -24,5 +24,6 @@ "@shikijs/types": ["../../node_modules/@shikijs/types"] } }, - "include": ["src"] + "include": ["src"], + "exclude": ["src/**/*.test.*"] } diff --git a/packages/code-block/vite.config.ts b/packages/code-block/vite.config.ts index bc4c8e418d..0fe11bd26b 100644 --- a/packages/code-block/vite.config.ts +++ b/packages/code-block/vite.config.ts @@ -29,7 +29,10 @@ export default defineConfig( test: { // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], }, plugins: [webpackStats() as any], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index 94cab86430..b0ea06a9e7 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -23,5 +23,5 @@ "noErrorTruncation": true }, "include": ["src"], - "exclude": ["src/**/*.browser.test.*", "src/**/*.screen-reader.test.ts"] + "exclude": ["src/**/*.test.*"] } diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index 78616f4ca4..3db018e9df 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -27,7 +27,12 @@ export default defineConfig({ // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + // Shared fixtures and colocated tests must use the same core module instance. + alias: { "@blocknote/core": path.resolve(__dirname, "src/") }, + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // `.browser.test` files need a real browser; the tests package's browser // suite runs them. exclude: [ diff --git a/packages/diagram-block/tsconfig.json b/packages/diagram-block/tsconfig.json index 4ce57b0d26..60a08c707a 100644 --- a/packages/diagram-block/tsconfig.json +++ b/packages/diagram-block/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../../shared" diff --git a/packages/diagram-block/vite.config.ts b/packages/diagram-block/vite.config.ts index f64d00cfbe..9c7ad9cc49 100644 --- a/packages/diagram-block/vite.config.ts +++ b/packages/diagram-block/vite.config.ts @@ -28,7 +28,10 @@ export default defineConfig( test: { // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // `.browser.test` files need a real browser; the tests package's // browser suite runs them. exclude: [...configDefaults.exclude, "**/*.browser.test.*"], diff --git a/packages/mantine/tsconfig.json b/packages/mantine/tsconfig.json index afade32699..eac94eae3d 100644 --- a/packages/mantine/tsconfig.json +++ b/packages/mantine/tsconfig.json @@ -22,6 +22,7 @@ "emitDeclarationOnly": true }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/mantine/vite.config.ts b/packages/mantine/vite.config.ts index 7825bcaaca..083307cc49 100644 --- a/packages/mantine/vite.config.ts +++ b/packages/mantine/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: ["../../tests/vitestSetup.node-fixtures.ts"], }, plugins: [react(), webpackStats()], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/math-block/tsconfig.json b/packages/math-block/tsconfig.json index 4ce57b0d26..60a08c707a 100644 --- a/packages/math-block/tsconfig.json +++ b/packages/math-block/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../../shared" diff --git a/packages/math-block/vite.config.ts b/packages/math-block/vite.config.ts index 9ec9a9c1a9..1939483f07 100644 --- a/packages/math-block/vite.config.ts +++ b/packages/math-block/vite.config.ts @@ -28,7 +28,10 @@ export default defineConfig( test: { // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // `.browser.test` files need a real browser; the tests package's // browser suite runs them. exclude: [...configDefaults.exclude, "**/*.browser.test.*"], diff --git a/packages/react/tsconfig.json b/packages/react/tsconfig.json index 850528c0a7..37966d157e 100644 --- a/packages/react/tsconfig.json +++ b/packages/react/tsconfig.json @@ -22,7 +22,7 @@ "emitDeclarationOnly": true }, "include": ["src"], - "exclude": ["src/**/*.browser.test.*", "src/**/*.screen-reader.test.ts"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.ts index 5b94676267..92a31ed230 100644 --- a/packages/react/vite.config.ts +++ b/packages/react/vite.config.ts @@ -31,7 +31,10 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // `.browser.test` files need a real browser; the tests package's // browser suite runs them. exclude: [ diff --git a/packages/server-util/tsconfig.json b/packages/server-util/tsconfig.json index afade32699..eac94eae3d 100644 --- a/packages/server-util/tsconfig.json +++ b/packages/server-util/tsconfig.json @@ -22,6 +22,7 @@ "emitDeclarationOnly": true }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/server-util/vite.config.ts b/packages/server-util/vite.config.ts index 75902c859b..79df16b4cf 100644 --- a/packages/server-util/vite.config.ts +++ b/packages/server-util/vite.config.ts @@ -29,7 +29,10 @@ export default defineConfig( test: { // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], }, plugins: [webpackStats() as any], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/shadcn/tsconfig.json b/packages/shadcn/tsconfig.json index 9f5729de4c..c6865f2348 100644 --- a/packages/shadcn/tsconfig.json +++ b/packages/shadcn/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/shadcn/vite.config.ts b/packages/shadcn/vite.config.ts index dc02662d59..b2cd55ecfd 100644 --- a/packages/shadcn/vite.config.ts +++ b/packages/shadcn/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: ["../../tests/vitestSetup.node-fixtures.ts"], }, plugins: [react(), webpackStats()], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/xl-ai-server/tsconfig.json b/packages/xl-ai-server/tsconfig.json index bb0a0520b1..54eb617b37 100644 --- a/packages/xl-ai-server/tsconfig.json +++ b/packages/xl-ai-server/tsconfig.json @@ -23,6 +23,7 @@ "types": ["node"] }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../xl-ai" diff --git a/packages/xl-ai-server/vite.config.ts b/packages/xl-ai-server/vite.config.ts index 0cfe18edcd..bcc4d0587a 100644 --- a/packages/xl-ai-server/vite.config.ts +++ b/packages/xl-ai-server/vite.config.ts @@ -30,7 +30,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: ["../../tests/vitestSetup.node-fixtures.ts"], }, plugins: [webpackStats()], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/xl-ai/tsconfig.json b/packages/xl-ai/tsconfig.json index 461bda9242..c2caec4d45 100644 --- a/packages/xl-ai/tsconfig.json +++ b/packages/xl-ai/tsconfig.json @@ -26,6 +26,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-ai/vite.config.ts b/packages/xl-ai/vite.config.ts index 6945529772..adc9a81c8a 100644 --- a/packages/xl-ai/vite.config.ts +++ b/packages/xl-ai/vite.config.ts @@ -43,7 +43,10 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // https://vitest.dev/guide/features.html#environment-variables // Only tests need the full environment. Loading it during a build // fingerprints unrelated per-run CI variables and prevents reuse. diff --git a/packages/xl-docx-exporter/tsconfig.json b/packages/xl-docx-exporter/tsconfig.json index fc76d3c948..52ab89d6e1 100644 --- a/packages/xl-docx-exporter/tsconfig.json +++ b/packages/xl-docx-exporter/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-docx-exporter/vite.config.ts b/packages/xl-docx-exporter/vite.config.ts index 8f3cc78f61..275604dc7b 100644 --- a/packages/xl-docx-exporter/vite.config.ts +++ b/packages/xl-docx-exporter/vite.config.ts @@ -29,7 +29,10 @@ export default defineConfig( test: { // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], }, plugins: [webpackStats() as any], // used so that vitest resolves the core package from the sources instead of the built version diff --git a/packages/xl-email-exporter/tsconfig.json b/packages/xl-email-exporter/tsconfig.json index 82d390d93b..ba97197a45 100644 --- a/packages/xl-email-exporter/tsconfig.json +++ b/packages/xl-email-exporter/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-email-exporter/vite.config.ts b/packages/xl-email-exporter/vite.config.ts index 9174ae2bcf..7805fba6cc 100644 --- a/packages/xl-email-exporter/vite.config.ts +++ b/packages/xl-email-exporter/vite.config.ts @@ -29,7 +29,10 @@ export default defineConfig( test: { // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // assetsInclude: [ // "**/*.woff", // "**/*.woff2", diff --git a/packages/xl-multi-column/tsconfig.json b/packages/xl-multi-column/tsconfig.json index 7cfebd971c..b2e5c45159 100644 --- a/packages/xl-multi-column/tsconfig.json +++ b/packages/xl-multi-column/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-multi-column/vite.config.ts b/packages/xl-multi-column/vite.config.ts index 3b86b72c6d..ade4072d0b 100644 --- a/packages/xl-multi-column/vite.config.ts +++ b/packages/xl-multi-column/vite.config.ts @@ -30,7 +30,10 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], // `.browser.test` files need a real browser; the tests package's // browser suite runs them. exclude: [...configDefaults.exclude, "**/*.browser.test.*"], diff --git a/packages/xl-odt-exporter/tsconfig.json b/packages/xl-odt-exporter/tsconfig.json index ed47b01dab..371e9f5790 100644 --- a/packages/xl-odt-exporter/tsconfig.json +++ b/packages/xl-odt-exporter/tsconfig.json @@ -26,6 +26,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-odt-exporter/vite.config.ts b/packages/xl-odt-exporter/vite.config.ts index f885c5ba64..efa164bb1c 100644 --- a/packages/xl-odt-exporter/vite.config.ts +++ b/packages/xl-odt-exporter/vite.config.ts @@ -30,7 +30,10 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], }, plugins: [webpackStats()], // Vite 8 (oxc) rejects JSX namespace tags by default; ODT uses them (e.g. ) diff --git a/packages/xl-pdf-exporter/tsconfig.json b/packages/xl-pdf-exporter/tsconfig.json index a161360880..8e915d8a6a 100644 --- a/packages/xl-pdf-exporter/tsconfig.json +++ b/packages/xl-pdf-exporter/tsconfig.json @@ -26,6 +26,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-pdf-exporter/vite.config.ts b/packages/xl-pdf-exporter/vite.config.ts index 0e3f311f86..a144b6cea2 100644 --- a/packages/xl-pdf-exporter/vite.config.ts +++ b/packages/xl-pdf-exporter/vite.config.ts @@ -35,7 +35,10 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "node", - setupFiles: ["./vitestSetup.ts"], + setupFiles: [ + "./vitestSetup.ts", + "../../tests/vitestSetup.node-fixtures.ts", + ], testTimeout: 15000, // `.browser.test` files need a real browser; the tests package's // browser suite runs them. diff --git a/packages/xl-typst-compiler/tsconfig.json b/packages/xl-typst-compiler/tsconfig.json index 2537882ebf..c3b8af851d 100644 --- a/packages/xl-typst-compiler/tsconfig.json +++ b/packages/xl-typst-compiler/tsconfig.json @@ -21,5 +21,6 @@ "skipLibCheck": true, "emitDeclarationOnly": true }, - "include": ["src"] + "include": ["src"], + "exclude": ["src/**/*.test.*"] } diff --git a/packages/xl-typst-compiler/vite.config.ts b/packages/xl-typst-compiler/vite.config.ts index 80e4a49242..529415dd96 100644 --- a/packages/xl-typst-compiler/vite.config.ts +++ b/packages/xl-typst-compiler/vite.config.ts @@ -49,6 +49,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "node", + setupFiles: ["../../tests/vitestSetup.node-fixtures.ts"], testTimeout: 30000, }, plugins: [webpackStats() as any], diff --git a/packages/xl-typst-exporter/tsconfig.json b/packages/xl-typst-exporter/tsconfig.json index 7008047628..8d983bf1ef 100644 --- a/packages/xl-typst-exporter/tsconfig.json +++ b/packages/xl-typst-exporter/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/**/*.test.*"], "references": [ { "path": "../core" diff --git a/packages/xl-typst-exporter/vite.config.ts b/packages/xl-typst-exporter/vite.config.ts index 0b62cd7cfd..cc328696cc 100644 --- a/packages/xl-typst-exporter/vite.config.ts +++ b/packages/xl-typst-exporter/vite.config.ts @@ -30,6 +30,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "node", + setupFiles: ["../../tests/vitestSetup.node-fixtures.ts"], // `.browser.test` files need a real browser; the tests package's // browser suite runs them. exclude: [...configDefaults.exclude, "**/*.browser.test.*"], diff --git a/tests/src/commands/node/setupEditor.ts b/tests/src/commands/node/setupEditor.ts index 50068bcdab..fe21e95e65 100644 --- a/tests/src/commands/node/setupEditor.ts +++ b/tests/src/commands/node/setupEditor.ts @@ -23,7 +23,7 @@ type DefaultOptions = Omit< "schema" > & { schema?: never }; -/** Binds mounted editor cleanup to the current Node test (not a browser RPC). */ +/** Binds headless editor cleanup to the current Node test (not a browser RPC). */ export function createSetupEditor(onFinished: TestContext["onTestFinished"]) { async function setupWithSchema< B extends BlockSchema, @@ -33,29 +33,23 @@ export function createSetupEditor(onFinished: TestContext["onTestFinished"]) { schema: CustomBlockNoteSchema, options: Partial>, ) { - const rootNode = document.createElement("div"); const editor = BlockNoteEditor.create({ ...options, schema }); - document.body.append(rootNode); onFinished(() => { editor.unmount(); - rootNode.remove(); }); - editor.mount(rootNode); - return { editor, rootNode }; + return { editor }; } /** - * Creates a real editor, mounts its contenteditable into the test environment's - * jsdom document, and unmounts/removes it after the test. Requires Vitest's - * `jsdom` environment; it does not install DOM globals itself. + * Creates a headless editor without accessing a DOM or requiring jsdom. + * Registers the public `unmount` cleanup after the test. This does not + * permanently destroy extensions; BlockNote has no public destroy method. * - * Use for Node tests of editor/document logic. This mounts the core editor, not - * a React view or skin. Use browser setupEditor for component rendering and real - * input/focus behavior, or BlockNoteEditor.create directly for headless logic. + * Use for Node tests of editor/document logic. Use browser setupEditor for + * component rendering and real input/focus behavior. * Accepts the same top-level editor options as the browser setupEditor, * including custom schemas, but no view props, skin, children, or rerender. - * Returns `{ editor, rootNode }`, where `rootNode` is the mounting container - * attached to document.body and removed during cleanup. + * Returns only `{ editor }`; there is no mounting container. * * @example * @@ -75,14 +69,13 @@ export function createSetupEditor(onFinished: TestContext["onTestFinished"]) { options: Partial> & { schema: CustomBlockNoteSchema; }, - ): Promise<{ editor: BlockNoteEditor; rootNode: HTMLDivElement }>; + ): Promise<{ editor: BlockNoteEditor }>; function setupEditor(options?: DefaultOptions): Promise<{ editor: BlockNoteEditor< DefaultBlockSchema, DefaultInlineContentSchema, DefaultStyleSchema >; - rootNode: HTMLDivElement; }>; function setupEditor< B extends BlockSchema, diff --git a/tests/src/fixtures/editor.node.ts b/tests/src/fixtures/editor.node.ts index 609ea0f060..720994b54f 100644 --- a/tests/src/fixtures/editor.node.ts +++ b/tests/src/fixtures/editor.node.ts @@ -6,7 +6,7 @@ import { type SetupEditor, } from "../commands/node/setupEditor.js"; -/** Node fixtures: mounts the core editor in jsdom, without React or skin styles. */ +/** Node fixtures: headless core editors, without a DOM, React, or skin styles. */ export type NodeContext = { setupEditor: SetupEditor } & typeof nodeCommands; export const test: TestAPI = base.extend({ diff --git a/tests/tsconfig.json b/tests/tsconfig.json index e3ce1824b0..53df565974 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -25,6 +25,7 @@ } }, "include": ["src"], + "exclude": ["src/unit/**/*.test.*"], "references": [ { "path": "../packages/core" diff --git a/tests/tsconfig.node.json b/tests/tsconfig.node.json new file mode 100644 index 0000000000..e3b0fcc46a --- /dev/null +++ b/tests/tsconfig.node.json @@ -0,0 +1,25 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "composite": false, + "rootDir": "..", + "sourceMap": false, + "paths": { + "@shared/*": ["../shared/*"], + "@blocknote/core": ["../packages/core/src/index.ts"], + "@blocknote/core/*": ["../packages/core/src/*"] + } + }, + "include": [ + "vitestSetup.node-fixtures.ts", + "src/unit/**/*.test.ts", + "src/unit/**/*.test.tsx", + "../packages/*/src/**/*.test.ts", + "../packages/*/src/**/*.test.tsx", + "../examples/07-collaboration/12-multi-doc-versioning/src/*.test.ts" + ], + "exclude": [ + "../packages/*/src/**/*.browser.test.*", + "../packages/*/src/**/*.screen-reader.test.ts" + ] +} diff --git a/tests/vite.config.ts b/tests/vite.config.ts index 3baa377401..de4b0d0112 100644 --- a/tests/vite.config.ts +++ b/tests/vite.config.ts @@ -36,7 +36,7 @@ export default defineConfig( // Preserve Vitest 4 mock history during the toolchain upgrade. clearMocks: false, environment: "jsdom", - setupFiles: ["./vitestSetup.ts"], + setupFiles: ["./vitestSetup.ts", "./vitestSetup.node-fixtures.ts"], include: [ "./src/unit/**/*.test.ts", "./src/unit/**/*.test.tsx", diff --git a/tests/vitestSetup.node-fixtures.ts b/tests/vitestSetup.node-fixtures.ts new file mode 100644 index 0000000000..cf861da282 --- /dev/null +++ b/tests/vitestSetup.node-fixtures.ts @@ -0,0 +1,8 @@ +import { test } from "./src/fixtures/editor.node.js"; + +// Imported Vitest APIs stay unchanged; only global `it` receives these fixtures. +globalThis.it = test; + +declare global { + var it: typeof test; +} diff --git a/tsconfig.json b/tsconfig.json index 6c140929e7..88f5851afe 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,7 @@ { "files": [], "references": [ + { "path": "./tests/tsconfig.node.json" }, { "path": "./tests/tsconfig.browser.json" }, { "path": "./tests/tsconfig.screen-reader.json" }, { "path": "./packages/core" }, From 9352a82976edf8ee35451fe2617a53226c6e7540 Mon Sep 17 00:00:00 2001 From: Nick Perez Date: Thu, 19 Nov 2026 11:50:11 +0100 Subject: [PATCH 12/14] chore(deps): replace fast-deep-equal with react-fast-compare (#3371) --- packages/core/package.json | 4 ++-- .../src/api/getBlocksChangedByTransaction.ts | 2 +- packages/react/package.json | 2 +- packages/react/src/hooks/useEditorState.ts | 4 ++-- pnpm-lock.yaml | 17 +++++++++++------ 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/packages/core/package.json b/packages/core/package.json index 4808f9dc57..70c262bb30 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -128,14 +128,14 @@ "@tiptap/extension-underline": "^3.31.3", "@tiptap/extensions": "^3.31.3", "@tiptap/pm": "^3.31.3", - "fast-deep-equal": "^3.1.3", "lib0": "1.0.0-rc.36", "prosemirror-highlight": "^0.15.3", "prosemirror-model": "^1.25.11", "prosemirror-state": "^1.4.4", "prosemirror-tables": "^1.8.5", "prosemirror-transform": "^1.12.1", - "prosemirror-view": "^1.42.5" + "prosemirror-view": "^1.42.5", + "react-fast-compare": "^3.2.3" }, "devDependencies": { "cldr-annotations-derived-full": "48.2.0", diff --git a/packages/core/src/api/getBlocksChangedByTransaction.ts b/packages/core/src/api/getBlocksChangedByTransaction.ts index 21f162ee3a..5ebfc5341d 100644 --- a/packages/core/src/api/getBlocksChangedByTransaction.ts +++ b/packages/core/src/api/getBlocksChangedByTransaction.ts @@ -1,5 +1,5 @@ import { combineTransactionSteps } from "./combineTransactionSteps.js"; -import deepEqual from "fast-deep-equal"; +import deepEqual from "react-fast-compare"; import type { Node } from "prosemirror-model"; import type { Transaction } from "prosemirror-state"; import { diff --git a/packages/react/package.json b/packages/react/package.json index e9afc94516..5766c75b12 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -83,8 +83,8 @@ "@tiptap/core": "^3.31.3", "@tiptap/pm": "^3.31.3", "@tiptap/react": "^3.31.3", - "fast-deep-equal": "^3.1.3", "frimousse": "^0.4.0", + "react-fast-compare": "^3.2.3", "use-sync-external-store": "1.6.0" }, "devDependencies": { diff --git a/packages/react/src/hooks/useEditorState.ts b/packages/react/src/hooks/useEditorState.ts index 59817ef8e7..4974ac973d 100644 --- a/packages/react/src/hooks/useEditorState.ts +++ b/packages/react/src/hooks/useEditorState.ts @@ -1,5 +1,5 @@ import type { BlockNoteEditor } from "@blocknote/core"; -import deepEqual from "fast-deep-equal/es6/react.js"; +import deepEqual from "react-fast-compare"; import { useDebugValue, useState } from "react"; import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector"; import { useBlockNoteContext } from "../editor/BlockNoteContext.js"; @@ -36,7 +36,7 @@ export type UseEditorStateOptions< /** * A custom equality function to determine if the editor should re-render. - * @default `deepEqual` from `fast-deep-equal` + * @default `deepEqual` from `react-fast-compare` */ equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4f107a35cf..bf0bcf6595 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5446,9 +5446,6 @@ importers: '@y/y': specifier: 14.0.0-rc.26 version: 14.0.0-rc.26 - fast-deep-equal: - specifier: ^3.1.3 - version: 3.1.3 lib0: specifier: 1.0.0-rc.36 version: 1.0.0-rc.36 @@ -5470,6 +5467,9 @@ importers: prosemirror-view: specifier: ^1.42.5 version: 1.42.5 + react-fast-compare: + specifier: ^3.2.3 + version: 3.2.3 devDependencies: cldr-annotations-derived-full: specifier: 48.2.0 @@ -5762,12 +5762,12 @@ importers: '@tiptap/react': specifier: ^3.31.3 version: 3.31.3(@floating-ui/dom@1.8.0)(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - fast-deep-equal: - specifier: ^3.1.3 - version: 3.1.3 frimousse: specifier: ^0.4.0 version: 0.4.0(react@19.2.5)(typescript@7.0.2) + react-fast-compare: + specifier: ^3.2.3 + version: 3.2.3 use-sync-external-store: specifier: 1.6.0 version: 1.6.0(react@19.2.5) @@ -15117,6 +15117,9 @@ packages: engines: {node: '>=20.0.0'} hasBin: true + react-fast-compare@3.2.3: + resolution: {integrity: sha512-WY9YHI1jjYC5a2lNRfHbeaNVQqiY+mMKWBSw1mPU0FgevlxI6V7izhNYz7Vp5ieFxetuRb6RmihPQxXEzg7oWQ==} + react-github-btn@1.4.0: resolution: {integrity: sha512-lV4FYClAfjWnBfv0iNlJUGhamDgIq6TayD0kPZED6VzHWdpcHmPfsYOZ/CFwLfPv4Zp+F4m8QKTj0oy2HjiGXg==} peerDependencies: @@ -25472,6 +25475,8 @@ snapshots: - supports-color - utf-8-validate + react-fast-compare@3.2.3: {} + react-github-btn@1.4.0(react@19.2.5): dependencies: github-buttons: 2.32.0 From 3e139bfad37cddca5dc98d7b26fa99413a4d2d57 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Thu, 19 Nov 2026 15:09:38 +0100 Subject: [PATCH 13/14] test: reuse react-fast-compare for document comparisons --- pnpm-lock.yaml | 3 ++ tests/package.json | 1 + tests/src/commands/node/compareDocuments.ts | 36 ++++++--------------- 3 files changed, 14 insertions(+), 26 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bf0bcf6595..459146d944 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6779,6 +6779,9 @@ importers: react-dom: specifier: ^19.2.5 version: 19.2.5(react@19.2.5) + react-fast-compare: + specifier: ^3.2.3 + version: 3.2.3 react-icons: specifier: ^5.5.0 version: 5.6.0(react@19.2.5) diff --git a/tests/package.json b/tests/package.json index 26df4820f9..e88e495ccd 100644 --- a/tests/package.json +++ b/tests/package.json @@ -41,6 +41,7 @@ "pdfjs-dist": "^4.10.38", "react": "^19.2.5", "react-dom": "^19.2.5", + "react-fast-compare": "^3.2.3", "react-icons": "^5.5.0", "rimraf": "^5.0.10", "vite-plus": "catalog:", diff --git a/tests/src/commands/node/compareDocuments.ts b/tests/src/commands/node/compareDocuments.ts index 08cb14f9e7..2fc2b527d9 100644 --- a/tests/src/commands/node/compareDocuments.ts +++ b/tests/src/commands/node/compareDocuments.ts @@ -1,4 +1,5 @@ import { defaultBlockSpecs, type BlockSchema } from "@blocknote/core"; +import deepEqual from "react-fast-compare"; const defaultBlockSchema: BlockSchema = Object.fromEntries( Object.entries(defaultBlockSpecs).map(([type, spec]) => [type, spec.config]), @@ -14,27 +15,6 @@ function record(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -function equal(before: unknown, after: unknown): boolean { - if (Object.is(before, after)) { - return true; - } - if (Array.isArray(before) && Array.isArray(after)) { - return ( - before.length === after.length && - before.every((value, index) => equal(value, after[index])) - ); - } - if (record(before) && record(after)) { - return ( - Object.keys(before).length === Object.keys(after).length && - Object.keys(before).every( - (key) => Object.hasOwn(after, key) && equal(before[key], after[key]), - ) - ); - } - return false; -} - function escapeText(value: string) { return value .replaceAll("&", "&") @@ -109,7 +89,7 @@ function inline( Object.entries(cellProps.props).filter( ([key, value]) => !Object.hasOwn(otherProps, key) || - !equal(value, otherProps[key]), + !deepEqual(value, otherProps[key]), ), ); if (Object.keys(changedProps).length) { @@ -218,10 +198,11 @@ function renderDocument( const props = Object.fromEntries( Object.entries(visibleFields.props).filter(([key, value]) => counterpart - ? !Object.hasOwn(otherProps, key) || !equal(value, otherProps[key]) + ? !Object.hasOwn(otherProps, key) || + !deepEqual(value, otherProps[key]) : !defaults || !Object.hasOwn(defaults, key) || - !equal(value, defaults[key].default), + !deepEqual(value, defaults[key].default), ), ); if (Object.keys(props).length) { @@ -334,7 +315,10 @@ export function compareDocuments< children: _afterChildren, ...afterFields }: Record = next.block; - if (prev.parentId !== next.parentId || !equal(beforeFields, afterFields)) { + if ( + prev.parentId !== next.parentId || + !deepEqual(beforeFields, afterFields) + ) { changed.add(id); } // Ordinary rendering joins adjacent unstyled runs. Expose their boundaries @@ -342,7 +326,7 @@ export function compareDocuments< const beforeContent = beforeFields.content; const afterContent = afterFields.content; if ( - !equal(beforeContent, afterContent) && + !deepEqual(beforeContent, afterContent) && inline(beforeContent) === inline(afterContent) ) { preserveRuns = true; From c159865db860c8b1e607d81fb885965a5bde5ffc Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Thu, 19 Nov 2026 15:19:59 +0100 Subject: [PATCH 14/14] test: simplify document comparison rendering --- tests/src/commands/node/compareDocuments.ts | 191 +++++++++++--------- 1 file changed, 107 insertions(+), 84 deletions(-) diff --git a/tests/src/commands/node/compareDocuments.ts b/tests/src/commands/node/compareDocuments.ts index 2fc2b527d9..d7c6f9c3f0 100644 --- a/tests/src/commands/node/compareDocuments.ts +++ b/tests/src/commands/node/compareDocuments.ts @@ -28,6 +28,76 @@ function attributes(fields: Record) { .join(""); } +function changedOwnProps( + props: Record, + counterpart: Record, +) { + return Object.fromEntries( + Object.entries(props).filter( + ([key, value]) => + !Object.hasOwn(counterpart, key) || !deepEqual(value, counterpart[key]), + ), + ); +} + +function renderTable( + value: Record & { rows: unknown[] }, + preserveRuns: boolean, + counterpart?: unknown, +): string { + const { rows, type: _type, ...metadata } = value; + const otherRows = + record(counterpart) && + counterpart.type === "tableContent" && + Array.isArray(counterpart.rows) && + counterpart.rows.length === rows.length + ? counterpart.rows + : []; + return `\n${rows + .map((row, index) => { + if (!record(row) || !Array.isArray(row.cells)) { + return ` ${escapeText(JSON.stringify(row))}`; + } + const { cells, ...rowProps } = row; + const otherRow = otherRows[index]; + const otherCells = + record(otherRow) && + Array.isArray(otherRow.cells) && + otherRow.cells.length === cells.length + ? otherRow.cells + : []; + return ` \n${cells + .map((cell, cellIndex) => { + if (Array.isArray(cell)) { + return ` ${inline(cell, preserveRuns)}`; + } + if (record(cell)) { + const { content, ...cellProps } = cell; + const otherCell = otherCells[cellIndex]; + if ( + record(cellProps.props) && + record(otherCell) && + record(otherCell.props) + ) { + const changedProps = changedOwnProps( + cellProps.props, + otherCell.props, + ); + if (Object.keys(changedProps).length) { + cellProps.props = changedProps; + } else { + delete cellProps.props; + } + } + return ` ${inline(content, preserveRuns)}`; + } + return ` ${escapeText(JSON.stringify(cell))}`; + }) + .join("\n")}\n `; + }) + .join("\n")}\n`; +} + function inline( value: unknown, preserveRuns = false, @@ -50,61 +120,11 @@ function inline( : escapeText(text); } if (type === "tableContent" && Array.isArray(value.rows)) { - const { rows, type: _type, ...metadata } = value; - const otherRows = - record(counterpart) && - counterpart.type === "tableContent" && - Array.isArray(counterpart.rows) && - counterpart.rows.length === rows.length - ? counterpart.rows - : []; - return `\n${rows - .map((row, index) => { - if (!record(row) || !Array.isArray(row.cells)) { - return ` ${escapeText(JSON.stringify(row))}`; - } - const { cells, ...rowProps } = row; - const otherRow = otherRows[index]; - const otherCells = - record(otherRow) && - Array.isArray(otherRow.cells) && - otherRow.cells.length === cells.length - ? otherRow.cells - : []; - return ` \n${cells - .map((cell, cellIndex) => { - if (Array.isArray(cell)) { - return ` ${inline(cell, preserveRuns)}`; - } - if (record(cell)) { - const { content, ...cellProps } = cell; - const otherCell = otherCells[cellIndex]; - if ( - record(cellProps.props) && - record(otherCell) && - record(otherCell.props) - ) { - const otherProps = otherCell.props; - const changedProps = Object.fromEntries( - Object.entries(cellProps.props).filter( - ([key, value]) => - !Object.hasOwn(otherProps, key) || - !deepEqual(value, otherProps[key]), - ), - ); - if (Object.keys(changedProps).length) { - cellProps.props = changedProps; - } else { - delete cellProps.props; - } - } - return ` ${inline(content, preserveRuns)}`; - } - return ` ${escapeText(JSON.stringify(cell))}`; - }) - .join("\n")}\n `; - }) - .join("\n")}\n`; + return renderTable( + { ...value, rows: value.rows }, + preserveRuns, + counterpart, + ); } const tag = type === "link" ? "link" : "inline"; const fields = type === "link" ? props : { type, ...props }; @@ -185,7 +205,27 @@ function renderDocument( ): string[] { return blocks.flatMap((block, index) => { const path = [...parentPath, index]; - const { children, content, ...fields } = { content: undefined, ...block }; + const include = includeSubtree || changed.has(block.id); + const nested = renderDocument( + block.children, + changed, + counterparts, + blockSchema, + path, + include, + preserveRuns, + ); + if (!include && !nested.length) { + return []; + } + const { + children: _children, + content, + ...fields + } = { + content: undefined, + ...block, + }; const counterpart = counterparts.get(block.id)?.block; const otherFields: Record = counterpart ?? {}; const otherProps = record(otherFields.props) ? otherFields.props : {}; @@ -195,35 +235,22 @@ function renderDocument( typeof visibleFields.type === "string" ? blockSchema[visibleFields.type]?.propSchema : undefined; - const props = Object.fromEntries( - Object.entries(visibleFields.props).filter(([key, value]) => - counterpart - ? !Object.hasOwn(otherProps, key) || - !deepEqual(value, otherProps[key]) - : !defaults || - !Object.hasOwn(defaults, key) || - !deepEqual(value, defaults[key].default), - ), - ); + const props = counterpart + ? changedOwnProps(visibleFields.props, otherProps) + : Object.fromEntries( + Object.entries(visibleFields.props).filter( + ([key, value]) => + !defaults || + !Object.hasOwn(defaults, key) || + !deepEqual(value, defaults[key].default), + ), + ); if (Object.keys(props).length) { visibleFields.props = props; } else { delete visibleFields.props; } } - const include = includeSubtree || changed.has(block.id); - const nested = renderDocument( - children, - changed, - counterparts, - blockSchema, - path, - include, - preserveRuns, - ); - if (!include && !nested.length) { - return []; - } const normalizedId = block.id.toLowerCase().replace(/[^a-z0-9-]/g, "-"); const tag = `block-${normalizedId}`; // Preserve the original identity if normalization changes it. @@ -241,11 +268,7 @@ function renderDocument( if (nested.length) { return [`${opening}>${body}`, ...nested, `${indent}`]; } - return [ - content === undefined - ? `${opening}>` - : `${opening}>${body}`, - ]; + return [`${opening}>${body}`]; }); }