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..1b1c56fe27 100644 --- a/.claude/skills/testing-skill/SKILL.md +++ b/.claude/skills/testing-skill/SKILL.md @@ -1,93 +1,98 @@ --- 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 +Use the lowest rung that can reliably prove the behavior: -Six layers, ordered by cost (speed, determinism, machinery), cheapest first. Prefer the first rung where the test can go red: +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. -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. +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. -**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. +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. -Corollaries: +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. -- **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. +## Rules -## Mobile release checklist (manual) +- **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. +- **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. -The device-only behaviors above, checked on real hardware before a release: +## Structure and assertions -- **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. +For component file structure, test groups, and accessibility assertions, follow [Component testing](references/component-testing.md). -## Test File Locations +Pure-function tests use a function-named `describe`; give integrated scenarios a separate `describe` when needed. Follow established patterns without inventing unnecessary structure. -### Unit Tests +| 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. | -`/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. +For document mutations, prefer `compareDocuments(before, editor.document)` with inline snapshots. Use `toEqual` when parameterized expectations are clearer. -`/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. +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. -`/packages/xl-*`: Contain tests for functionality included in a given `xl-*` package. +## Golden examples -### Colocated Browser Unit Tests +- 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. -`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 these as patterns, not templates to copy mechanically. For testing a React component, read [Component testing](references/component-testing.md). -### End-to-End Tests +## Editor setup -`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. +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. -### Colocated Component and Accessibility Tests +The same test works in either environment: -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. +```ts +import { expect } from "vite-plus/test"; -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. +it("updates a block's background color", async ({ setupEditor }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "paragraph", type: "paragraph", content: "Original text" }, + ], + }); -## When & How to Add Tests + editor.updateBlock("paragraph", { props: { backgroundColor: "yellow" } }); -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). + expect(editor.getBlock("paragraph")?.props.backgroundColor).toBe("yellow"); +}); +``` -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. +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. -### End-to-End Tests +## Run -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 cae375be8e..0000000000 --- a/.claude/skills/testing-skill/references/accessibility-tests.md +++ /dev/null @@ -1,79 +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 or arrowing to an item, stop as soon as the target is reached and enforce an explicit maximum number of keypresses. Choose a generous bound for the fixture and fail immediately with the target and limit in the message if it is exhausted; do not rely on the test timeout. The bound is a safety limit, not a fixed navigation sequence or a duplicate list of controls. - -## 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/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. - -Browser and screen-reader files also have lint rules for focused tests, malformed assertions, unhandled promises, direct command-implementation imports, test-ID locators, and explicit sleep APIs (`waitForTimeout`, `.sleep`, and Node timer imports). Readiness waits should use retrying assertions. - -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..498239783b --- /dev/null +++ b/.claude/skills/testing-skill/references/component-testing.md @@ -0,0 +1,87 @@ +# React component testing + +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 a component-named outer `describe`, then applicable groups in this order; omit irrelevant groups: + +| 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. + +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 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 +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"); +}); +``` + +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. + +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. + +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. + +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. + +## Accessibility assertions + +- 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`. +- 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. 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: + +```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). +- 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/.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/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/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/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 f50025bcc5..a0cacc6b66 100644 --- a/packages/core/src/blocks/Heading/block.browser.test.tsx +++ b/packages/core/src/blocks/Heading/block.browser.test.tsx @@ -1,36 +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, - }); - for ( - let presses = 0; - document.activeElement !== toggleButton.element(); - presses++ - ) { - if (presses >= 10) { - throw new Error( - "Could not focus the toggle heading button after 10 Tab presses", - ); - } - await commands.pressKey("Tab"); - } - - return toggleButton; -} +import type { ReactNode } from "react"; +import { expect, describe, vi, beforeEach, afterEach } from "vite-plus/test"; const toggleHeadingDocument: PartialBlock[] = [ { @@ -42,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(() => { @@ -69,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("integration", () => { + 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", @@ -87,36 +68,54 @@ 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, +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, }); - await expect.element(toggleButton).toBeVisible(); - const unfocusedOutline = await commands.readOutline(toggleButton.selector); - - for ( - let presses = 0; - document.activeElement !== toggleButton.element(); - presses++ - ) { - if (presses >= 10) { - throw new Error( - "Could not focus the toggle heading button after 10 Tab presses", - ); - } - await commands.pressKey("Tab"); - } - await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); + 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] + `); + }); +}); - 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. @@ -127,40 +126,45 @@ 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, + captureFocusOutline, + }) => { + 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 compareFocusOutline = captureFocusOutline(toggleButton); + await focusUntil(toggleButton); await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); - await commands.pressKey("Enter"); + await compareFocusOutline(toggleButton); + + await pressKey("Enter"); await expect.element(toggleButton).toHaveFocus(); - await commands.checkFocusOutline(toggleButton.selector, unfocusedOutline); + await compareFocusOutline(toggleButton); + await pressKey("Enter"); + await expect.element(toggleButton).toHaveFocus(); + await compareFocusOutline(toggleButton); - 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); - }); -}); - -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", - ); + await compareFocusOutline(toggleButton); }); }); 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/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/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx new file mode 100644 index 0000000000..a5710fa4a5 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/BasicTextStyleButton.browser.test.tsx @@ -0,0 +1,308 @@ +import { describe, expect } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { + BlockNoteSchema, + createStyleSpec, + 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", () => { + 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, + { setupEditor, selectText, compareDocuments, page }, + ) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "format", type: "paragraph", content: "Format this text" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "Format this text"); + const button = page.getByRole("button", { + 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( + `BEFORE:\n${state === "on" ? plain : styled}\n\nAFTER:\n${state === "on" ? styled : plain}`, + ); + 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, + { setupEditor, selectText, compareDocuments, page }, + ) => { + const { editor } = await setupEditor({ + initialContent: [ + { + id: "format", + type: "paragraph", + content: [ + { + type: "text", + text: "Before selected after", + styles: { textColor: "red" }, + }, + ], + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + const before = editor.document; + const button = page.getByRole("button", { + 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(`BEFORE: +Before selected after + +AFTER: +Before selected after`); + }, + ); + + it.for(STYLES)( + "applies %s to subsequently typed text at a collapsed cursor", + async (basicTextStyle, { setupEditor, compareDocuments, page }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "format", type: "paragraph", content: "Existing" }, + ], + props: { formattingToolbar: false }, + children: , + }); + editor.setTextCursorPosition("format", "end"); + const before = editor.document; + const button = page.getByRole("button", { + name: editor.dictionary.formatting_toolbar[basicTextStyle].tooltip, + exact: true, + }); + + await button.click(); + await userEvent.keyboard(" typed"); + + expect(compareDocuments(before, editor.document)).toEqual(`BEFORE: +Existing + +AFTER: +Existing typed`); + }, + ); + }); + + 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", + async ( + style, + { 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[style].tooltip, + exact: true, + }); + const compareFocusOutline = captureFocusOutline(button); + + await pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await compareFocusOutline(button); + }, + ); + + it.for(["Enter", "Space"])( + "activates with %s and returns focus to the editor", + async (key, { setupEditor, selectText, 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.bold.tooltip, + exact: true, + }); + + await pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + + await pressKey(key); + + 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..da56e321d3 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.browser.test.tsx @@ -0,0 +1,580 @@ +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", () => { + it("only offers text colors when the schema does not support background colors", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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("only offers background colors when text colors are not in the schema", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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 ({ + setupEditor, + page, + }) => { + const { editor } = await setupEditor({ + schema: BlockNoteSchema.create({ + styleSpecs: { bold: defaultStyleSpecs.bold }, + }), + props: { formattingToolbar: false }, + children: , + }); + + 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 ({ + setupEditor, + page, + }) => { + const { editor, rerender } = await setupEditor({ + 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 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("applies textColor only to the selected substring", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Before selected after" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + const before = editor.document; + + 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(0) + .click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Before selected after + + AFTER: + Before selected after" + `); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + + it("applies backgroundColor only to the selected substring", async ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Before selected after" }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected"); + const before = editor.document; + + 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(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Before selected after + + AFTER: + Before selected after" + `); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }); + + it("resets textColor 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 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(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + }); + + 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 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(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + }); + }); + + describe("aria", () => { + it("exposes the menu trigger's expanded state and relationship", 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.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. + it.fails("exposes a color change in the trigger or menu's accessibility tree", async ({ + setupEditor, + selectText, + readAriaSnapshot, + 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, + }); + await button.click(); + const menu = page.getByRole("menu"); + await expect.element(menu).toBeVisible(); + const before = [readAriaSnapshot(button), readAriaSnapshot(menu)].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 = [readAriaSnapshot(button), readAriaSnapshot(menu)].join( + "\n", + ); + expect(after).not.toBe(before); + }); + }); + + describe("axe", () => { + it("checks the color trigger", async ({ setupEditor, runAxe, page }) => { + await setupEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); + + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); + }); + + // 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: ( + + + + ), + }); + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.colors.tooltip, + exact: true, + }) + .click(); + await expect.element(page.getByRole("menu")).toBeVisible(); + + 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: [], + }, + ], + }); + } + }); + }); + + 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 new file mode 100644 index 0000000000..8ef2c86804 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/CreateLinkButton.browser.test.tsx @@ -0,0 +1,399 @@ +import { describe, expect } from "vite-plus/test"; +import { CreateLinkButton } from "./CreateLinkButton.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; + +describe("CreateLinkButton", () => { + describe("unit", () => { + it("requires selected text and responds to editability changes", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor, rerender } = await setupEditor({ + 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, + }); + 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 ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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(); + }); + }); + + describe("integration", () => { + it("submits a link for the original substring and returns focus to the editor", async ({ + setupEditor, + selectText, + compareDocuments, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { + id: "text", + type: "paragraph", + content: "Before selected text after", + }, + ], + props: { formattingToolbar: false }, + children: , + }); + selectText(editor, "selected text"); + const before = editor.document; + 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 pressKey("Enter"); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + Before selected text after + + AFTER: + Before selected text after" + `); + 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 ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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("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, + 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.link.tooltip, + exact: true, + }); + await expect.element(button).toBeVisible(); + const compareFocusOutline = captureFocusOutline(button); + await pressKey("Tab"); + await compareFocusOutline(button); + + await expect.element(button).toHaveFocus(); + }); + + // 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 ({ + 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.formatting_toolbar.link.tooltip, + exact: true, + }); + await expect.element(button).toBeVisible(); + button.element().focus(); + + await pressKey("Enter"); + + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveFocus(); + 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 ({ + 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.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 pressKey("Enter"); + + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveFocus(); + + await 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 ({ + setupEditor, + selectText, + pressKey, + page, + }) => { + const { editor, rerender } = await setupEditor({ + initialContent: [{ type: "paragraph", content: "Selected text" }], + props: { formattingToolbar: false }, + children: , + }); + await page.getByRole("textbox").click(); + selectText(editor, "Selected text"); + + await pressKey("Control+k"); + + const input = page.getByPlaceholder( + editor.dictionary.link_toolbar.form.url_placeholder, + ); + await expect.element(input).toHaveFocus(); + await 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); + }); + }); +}); 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..43e1b1fe90 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/NestBlockButtons.browser.test.tsx @@ -0,0 +1,287 @@ +import { describe, expect } from "vite-plus/test"; +import { NestBlockButton, UnnestBlockButton } from "./NestBlockButtons.js"; +import { FormattingToolbar } from "../FormattingToolbar.js"; + +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 }, { setupEditor, page }) => { + const { editor, rerender } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Text" }, + { id: "divider", type: "divider" }, + ], + props: { editable: false, formattingToolbar: false }, + children: + + ), + }); + await page.getByRole("textbox").click(); + + await pressKey("Tab"); + + await expect + .element(page.getByRole("button", { name: "Next action", exact: true })) + .toHaveFocus(); + }); + }); +}); 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..2fa5cb1b4a --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/TextAlignButton.browser.test.tsx @@ -0,0 +1,413 @@ +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", () => { + describe("unit", () => { + it("hides for read-only content and blocks without alignment, and reappears for text", async ({ + setupEditor, + page, + }) => { + const { editor, rerender } = await setupEditor({ + 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.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("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(); + + 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 center 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_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, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + 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.formatting_toolbar.align_center.tooltip, + exact: true, + }) + .click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + First + Second + + AFTER: + First + Second" + `); + }); + + it("aligns only the selected table cells", async ({ + setupEditor, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + 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])); + }); + // The alignment action shares and mutates table-cell props; detach the baseline. + const before = structuredClone(editor.document); + + await page + .getByRole("button", { + name: editor.dictionary.formatting_toolbar.align_center.tooltip, + exact: true, + }) + .click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + + + First + Second + + + Third + Fourth + +
+ + AFTER: + + + First + Second + + + Third + Fourth + +
" + `); + }); + }); + + 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([]); + }); + }); + + describe("keyboard", () => { + it.for(["left", "center", "right", "justify"] as const)( + "shows a keyboard focus ring for %s alignment", + async ( + alignment, + { 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[`align_${alignment}`] + .tooltip, + exact: true, + }); + const compareFocusOutline = captureFocusOutline(button); + + await pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + await compareFocusOutline(button); + }, + ); + + it.for(["Enter", "Space"])( + "aligns with %s and restores editor focus", + async (key, { setupEditor, selectText, pressKey, page }) => { + const { editor } = await setupEditor({ + 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 pressKey("Tab"); + + await expect.element(button).toHaveFocus(); + + await pressKey(key); + + await expect.element(button).toHaveAttribute("aria-pressed", "true"); + await expect.element(page.getByRole("textbox")).toHaveFocus(); + }, + ); + }); +}); 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..d4aa888c21 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DefaultSelects/BlockTypeSelect.browser.test.tsx @@ -0,0 +1,454 @@ +import { describe, expect } from "vite-plus/test"; +import { FormattingToolbar } from "../FormattingToolbar.js"; +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 ({ + setupEditor, + page, + }) => { + const { editor } = await setupEditor({ + 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, + }); + 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 ({ setupEditor, page }) => { + await setupEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); + + await expect.element(page.getByRole("button")).not.toBeInTheDocument(); + }); + + // 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 ({ + setupEditor, + page, + }) => { + const { editor, rerender } = await setupEditor({ + props: { editable: false, formattingToolbar: false }, + children: , + }); + const button = page.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }); + 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 ({ + setupEditor, + page, + }) => { + const { editor } = await setupEditor({ + 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 ({ + setupEditor, + selectText, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + 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(compareDocuments(documentBefore, editor.document)) + .toMatchInlineSnapshot(` + "BEFORE: + Selected text + + AFTER: + Selected text" + `); + 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 ({ + setupEditor, + compareDocuments, + page, + }) => { + const { editor } = await setupEditor({ + 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, + }) + .click(); + + expect(compareDocuments(before, editor.document)).toMatchInlineSnapshot(` + "BEFORE: + First + Second + + AFTER: + First + Second" + `); + }); + }); + + describe("aria", () => { + it("names the current block type and exposes the popup relationship", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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 ({ + setupEditor, + page, + }) => { + const { editor } = await setupEditor({ + 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 ({ + setupEditor, + selectText, + runAxe, + 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, + }); + await expect.element(button).toBeVisible(); + + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); + }); + + // 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, + 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.slash_menu.paragraph.title, + exact: true, + }) + .click(); + + await expect.element(page.getByRole("menu")).toBeVisible(); + 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: [], + }, + ], + }, + ]); + }); + }); + + 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/DesktopFormattingToolbarController.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx new file mode 100644 index 0000000000..fb08a75f34 --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx @@ -0,0 +1,178 @@ +import { FormattingToolbarExtension } from "@blocknote/core/extensions"; +import { describe, expect } from "vite-plus/test"; +import { DesktopFormattingToolbarController } from "./DesktopFormattingToolbarController.js"; + +describe("DesktopFormattingToolbarController", () => { + describe("unit", () => { + it("mounts its custom toolbar while the extension requests it and unmounts it on dismissal", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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("renders its toolbar into the supplied portal", async ({ + setupEditor, + selectText, + page, + onTestFinished, + }) => { + const portal = document.createElement("div"); + document.body.append(portal); + onTestFinished(() => portal.remove()); + const { editor } = await setupEditor({ + 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); + }); + }); + + describe("integration", () => { + it("does not steal editor focus when the default toolbar appears", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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); + }); + + it("dismisses on an outside click without stealing focus from the outside action", async ({ + setupEditor, + selectText, + page, + }) => { + const { editor } = await setupEditor({ + 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 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); + }); + }); + + 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 87f03a22ac..bea7861f6d 100644 --- a/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/FormattingToolbar.browser.test.tsx @@ -1,565 +1,556 @@ -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, - }); - for ( - let presses = 0; - document.activeElement !== target.element(); - presses++ - ) { - if (presses >= 20) { - throw new Error( - `Could not focus toolbar item "${toolbarItem}" after 20 Tab presses`, - ); - } - 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: 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"); - 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 { FormattingToolbar } from "./FormattingToolbar.js"; + +describe("FormattingToolbar", () => { + describe("unit", () => { + it("allows custom children instead of default controls", async ({ + setupEditor, + 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 setupEditor({ + 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 ({ + setupEditor, + page, + }) => { + const { editor } = await setupEditor({ + 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, - }); - const unfocusedOutline = await commands.readOutline(target.selector); - await commands.pressKey("Tab"); - await expect - .poll(() => toolbar.element().contains(document.activeElement)) - .toBe(true); - for ( - let presses = 0; - document.activeElement !== target.element(); - presses++ - ) { - if (presses >= 20) { - throw new Error( - `Could not focus toolbar item "${toolbarItem}" after 20 Tab presses`, - ); - } - await commands.pressKey("Tab"); - } - await expect.element(target).toHaveFocus(); - await commands.checkFocusOutline(target.selector, unfocusedOutline); - return { toolbar, button: target }; - } - - async function checkToolbarButtonKeyboard(toolbarButton: string) { - await focusToolbarItemWithAssertions(toolbarButton); - await commands.pressKey("Enter"); - await expect.element(page.getByRole("textbox")).toHaveFocus(); - } - - 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]")) - .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, - ); - 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, + describe("integration", () => { + it("preserves the editor selection while keyboard focus moves through the toolbar", async ({ + setupEditor, + selectText, + pressKey, + page, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { type: "paragraph", content: "Before selected text after" }, + ], }); - 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 expect - .element(page.getByRole("button", { name: selectedValue, 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"); - }); + await page.getByRole("textbox").click(); + selectText(editor, "selected text"); + const toolbar = page.getByRole("toolbar"); + const documentBefore = editor.document; + const selectionBefore = editor.prosemirrorState.selection.toJSON(); - test("formatting toolbar: Align text right", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonKeyboard("Align text right"); - }); + await pressKey("Tab"); - test("formatting toolbar: Colors", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarMenuKeyboard("Colors", () => - page.elementLocator( - document.querySelector('[data-test="text-color-gray"]')!, - ), + await expect + .element( + toolbar.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }), + ) + .toHaveFocus(); + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, ); - }); - 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"); - }); + await pressKey("Tab"); - // 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"), - ); - }); - }); - - 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]")) + .element( + toolbar.getByRole("button", { + name: editor.dictionary.formatting_toolbar.bold.tooltip, + exact: true, + }), + ) .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, - ), - ).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", + expect(editor.prosemirrorState.selection.toJSON()).toEqual( + selectionBefore, ); + expect(editor.document).toEqual(documentBefore); }); + }); - 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"); - }); + describe("aria", () => { + it("exposes its custom controls as a toolbar", async ({ + setupEditor, + page, + }) => { + await setupEditor({ + props: { formattingToolbar: false }, + children: ( + + + + ), + }); - test("formatting toolbar: Align text left", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Align text left"); + await expect.element(page.getByRole("toolbar")) + .toMatchAriaInlineSnapshot(` + - toolbar: + - button "Custom action" + `); }); + }); - test("formatting toolbar: Align text center", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Align text center"); - }); + 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(); - test("formatting toolbar: Align text right", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Align text right"); + const { violations } = await runAxe(page.getByRole("toolbar")); + expect(violations).toEqual([]); }); + }); - test("formatting toolbar: Colors", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarMenuAria("Colors", "Colors"); - }); + describe("keyboard", () => { + it("tabs forward through the default controls for Parent and allows leaving", async ({ + setupEditor, + selectText, + focusUntil, + readAriaSnapshot, + page, + }) => { + const { editor } = await setupEditor({ + 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, "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[] = []; - test("formatting toolbar: Nest block", async () => { - await renderTestEditor(toolbarDocument); - await checkToolbarButtonAria("Nest block"); - }); + await focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(readAriaSnapshot(active)); + return false; + }); - test("formatting toolbar: Unnest block", async () => { - await renderTestEditor(nestedToolbarDocument); - await checkToolbarButtonAria("Unnest block"); - }); - }); + 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 ({ + setupEditor, + selectText, + focusUntil, + readAriaSnapshot, + page, + }) => { + const { editor } = await setupEditor({ + 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(); + // Record each control's accessible tree in keyboard focus order, + // so the snapshot detects skipped controls or changes in tab order. + const sequence: string[] = []; - 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"); - } - }); + await focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(readAriaSnapshot(active)); + return false; + }); - // Mantine inserts a focusable div inside the menu, triggering axe aria-required-children violations. - test.skip("formatting toolbar: block type menu axe", async ({ - annotate, + 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 ({ + setupEditor, + selectText, + focusUntil, + readAriaSnapshot, + 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"); - } - }); + const { editor } = await setupEditor({ + 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, "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[] = []; - // 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"); - } - }); + await focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(readAriaSnapshot(active)); + return false; + }); - 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")) { - await annotate(warning, "warning"); - } + 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 ({ + setupEditor, + selectText, + focusUntil, + readAriaSnapshot, + page, + }) => { + const { editor } = await setupEditor({ + 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, + }); + await expect.element(lastControl).toBeVisible(); + lastControl.element().focus(); + // 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 focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(readAriaSnapshot(active)); + 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 ({ + setupEditor, + selectText, + focusUntil, + readAriaSnapshot, + page, + }) => { + const { editor } = await setupEditor({ + 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, + }); + await expect.element(lastControl).toBeVisible(); + lastControl.element().focus(); + // 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 focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(readAriaSnapshot(active)); + return false; + }, "backward"); + + 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); + }); + + it("tabs backward through the default controls for Sibling and allows leaving", async ({ + setupEditor, + selectText, + focusUntil, + readAriaSnapshot, + page, + }) => { + const { editor } = await setupEditor({ + 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(); + // 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 focusUntil(async (active) => { + if (!toolbar.element().contains(active.element())) { + return true; + } + await expect.element(active).toBeEnabled(); + sequence.push(readAriaSnapshot(active)); + return false; + }, "backward"); + + 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/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts b/packages/react/src/components/FormattingToolbar/FormattingToolbar.screen-reader.test.ts index dc778946bf..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,30 +1,38 @@ -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 { 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); - await commands.startReader(page.getByRole("textbox").selector); - const { toolbar } = await focusToolbarItem("Paragraph"); - await commands.pressKey("Escape"); +it.skip("announces entering and leaving the formatting toolbar", async ({ + setupEditor, + setupScreenReader, + page, + selectToLineEndKey, +}) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "text", type: "paragraph", content: "Selected text" }, + ], + }); + editor.setTextCursorPosition("text", "start"); + const { getTranscript, pressKey } = await setupScreenReader( + page.getByRole("textbox"), + ); + await pressKey(selectToLineEndKey); + await pressKey("Tab"); + const toolbar = page.getByRole("toolbar"); + await expect + .element( + toolbar.getByRole("button", { + name: editor.dictionary.slash_menu.paragraph.title, + exact: true, + }), + ) + .toHaveFocus(); + 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/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/packages/react/src/editor/BlockNoteView.browser.test.tsx b/packages/react/src/editor/BlockNoteView.browser.test.tsx index 651cf0b846..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,21 @@ 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() { + 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, @@ -426,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 unfocusedOutline = await commands.readOutline(link.selector); - 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 commands.checkFocusOutline(link.selector, unfocusedOutline); - 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 @@ -459,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. @@ -477,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[] { @@ -501,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( @@ -521,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 }, @@ -531,7 +543,7 @@ if (!screenReader) { { row: 1, column: 0 }, { row: 1, column: 1 }, ]; - expect((await commands.readSelection()).tableCell).toEqual(route[0]); + expect(readDOMSelection().tableCell).toEqual(route[0]); for (const key of ["ArrowRight", "ArrowLeft"] as const) { const expected = key === "ArrowRight" ? route : route.toReversed(); let index = 0; @@ -541,8 +553,8 @@ if (!screenReader) { `${key} did not finish the table route after 100 presses; still at cell ${JSON.stringify(expected[index])}`, ); } - await commands.pressKey(key); - const { blockId, tableCell } = await commands.readSelection(); + await pressKey(key); + const { blockId, tableCell } = readDOMSelection(); expect(blockId, `${key} stays in the table`).toBe("table"); expect( [expected[index], expected[index + 1]], @@ -560,20 +572,20 @@ 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((await commands.readSelection()).tableCell).toEqual({ + expect(readDOMSelection().tableCell).toEqual({ row: 0, column, }); for (const key of ["ArrowDown", "ArrowUp"] as const) { const targetRow = key === "ArrowDown" ? 1 : 0; - let selection = await commands.readSelection(); + let selection = readDOMSelection(); for ( let presses = 0; selection.tableCell?.row !== targetRow; @@ -584,8 +596,8 @@ if (!screenReader) { `${key} did not reach row ${targetRow}, column ${column} after 10 presses`, ); } - await commands.pressKey(key); - selection = await commands.readSelection(); + await pressKey(key); + selection = readDOMSelection(); expect(selection.blockId, `${key} stays in the table`).toBe( "table", ); @@ -599,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. @@ -614,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 }), @@ -641,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. @@ -665,30 +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); - expect( - await commands.readAriaSnapshot(page.getByRole("textbox").selector), - ).toMatchSnapshot("default schema"); - }); - }); - - 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 }); - for (const warning of await commands.checkAxe()) { - await annotate(warning, "warning"); - } - }); - } - }); - - test.describe("visual", () => { + describe("visual", () => { function applyStyles(css: string) { const style = document.createElement("style"); style.textContent = css; @@ -727,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. @@ -750,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/packages/react/src/editor/BlockNoteView.screen-reader.test.ts b/packages/react/src/editor/BlockNoteView.screen-reader.test.ts index 0d6864e567..8f11630b78 100644 --- a/packages/react/src/editor/BlockNoteView.screen-reader.test.ts +++ b/packages/react/src/editor/BlockNoteView.screen-reader.test.ts @@ -1,69 +1,56 @@ -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, defaultSchemaDocument, + readDOMSelection, } 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 commands.pressKey("Tab"); + await pressKey("Tab"); // Allow repeated presses within text, but fail early if navigation gets stuck. const visitedTableCells = new Set(); - for ( - let presses = 0; - (await commands.readSelection()).blockId !== "end"; - presses++ - ) { + for (let presses = 0; readDOMSelection().blockId !== "end"; presses++) { if (presses >= 100) { throw new Error( "Could not reach the final block after 100 arrow-key presses", ); } - const { tableCell } = await commands.readSelection(); + const { tableCell } = readDOMSelection(); if (tableCell) { visitedTableCells.add(`${tableCell.row},${tableCell.column}`); } // 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"); } } - for ( - let presses = 0; - (await commands.readSelection()).blockId !== "start"; - presses++ - ) { + for (let presses = 0; readDOMSelection().blockId !== "start"; presses++) { if (presses >= 100) { throw new Error( "Could not return to the first block after 100 ArrowUp presses", ); } - await commands.pressKey("ArrowUp"); + await pressKey("ArrowUp"); } + 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/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/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/pnpm-lock.yaml b/pnpm-lock.yaml index 4f107a35cf..459146d944 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) @@ -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) @@ -15117,6 +15120,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 +25478,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 diff --git a/scripts/lint/README.md b/scripts/lint/README.md new file mode 100644 index 0000000000..1e5a4b4ed6 --- /dev/null +++ b/scripts/lint/README.md @@ -0,0 +1,39 @@ +# 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`, + `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 + 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..67a2a0b936 --- /dev/null +++ b/scripts/lint/component-browser-tests.mjs @@ -0,0 +1,209 @@ +import { basename } from "node:path"; + +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([ + "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, 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.", + }, + }, + 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..70b7e33e08 --- /dev/null +++ b/scripts/lint/component-browser-tests.test.mjs @@ -0,0 +1,245 @@ +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", "aria", "axe", "keyboard"] + .map(group) + .join("\n"), + ), + ), + [], + ); + 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 separate aria and axe groups", () => { + assert.deepEqual( + lint( + 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([]); }); + });`), + ), + [], + ); +}); + +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("aria")), + 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("aria") + group("unit"), + group("unit") + group("unit"), + group("aria") + group("aria"), + group("keyboard") + group("aria"), + group("axe") + group("aria"), + group("a11y"), + group("behaviour"), + group("ARIA"), + 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..e3482018ad --- /dev/null +++ b/tests/src/commands/index.ts @@ -0,0 +1,68 @@ +/* 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, userEvent } from "./transport.js"; + +// Browser-only fixtures extend the baseline in fixtures/editor.node.ts. +export type CommandContext = Pick< + typeof nodeCommands, + keyof typeof import("./transport/index.js") +> & + typeof browserCommands & { + page: typeof page; + userEvent: typeof userEvent; + setupEditor: SetupEditor; + }; + +/** Top-level test fixtures; pass this collection to test.extend unchanged. */ +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); + }, + positionalMouse: async ({}, use) => { + await use(nodeCommands.positionalMouse); + }, + imeComposition: async ({}, use) => { + await use(nodeCommands.imeComposition); + }, + restoreTouchEmulation: async ({}, use) => { + await use(nodeCommands.restoreTouchEmulation); + }, + focusUntil: async ({}, use) => { + await use(browserCommands.focusUntil); + }, + captureFocusOutline: async ({}, use) => { + await use(browserCommands.captureFocusOutline); + }, + readAriaSnapshot: async ({}, use) => { + await use(browserCommands.readAriaSnapshot); + }, + 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/commands/node/compareDocuments.ts b/tests/src/commands/node/compareDocuments.ts new file mode 100644 index 0000000000..d7c6f9c3f0 --- /dev/null +++ b/tests/src/commands/node/compareDocuments.ts @@ -0,0 +1,362 @@ +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]), +); + +/** Minimum input contract, including blocks from custom schemas. */ +export type DocumentBlock = { + id: string; + children: readonly DocumentBlock[]; +}; + +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function escapeText(value: string) { + return value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">"); +} + +function attributes(fields: Record) { + return Object.entries(fields) + .map(([key, value]) => ` ${key}=${JSON.stringify(value)}`) + .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, + counterpart?: unknown, +): string { + if (typeof value === "string") { + return `${escapeText(value)}`; + } + if (Array.isArray(value)) { + return value.map((item) => inline(item, preserveRuns)).join(""); + } + 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)) { + return renderTable( + { ...value, rows: value.rows }, + preserveRuns, + counterpart, + ); + } + 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(blocks: readonly DocumentBlock[]) { + const byId = new Map< + string, + { block: DocumentBlock; parentId: string | null } + >(); + const siblings = new Map(); + function visit(children: readonly DocumentBlock[], parentId: string | null) { + siblings.set( + parentId, + children.map((block) => 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, parentId }); + visit(block.children, block.id); + } + } + visit(blocks, null); + return { byId, siblings }; +} + +/** 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)); + 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)); +} + +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 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 : {}; + const visibleFields: Record = { ...fields }; + if (record(visibleFields.props)) { + const defaults = + typeof visibleFields.type === "string" + ? blockSchema[visibleFields.type]?.propSchema + : undefined; + 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 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 [`${opening}>${body}`]; + }); +} + +/** + * Format changed blocks as BEFORE/AFTER markup for document assertions. + * + * 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< + Before extends DocumentBlock, + After extends DocumentBlock, +>( + beforeDocument: readonly Before[], + afterDocument: readonly After[], + { blockSchema = defaultBlockSchema }: { blockSchema?: BlockSchema } = {}, +): string { + const before = snapshot(beforeDocument); + const after = snapshot(afterDocument); + const changed = new Set(); + let preserveRuns = false; + for (const [parentId, nextOrder] of after.siblings) { + for (const id of reordered( + before.siblings.get(parentId) ?? [], + nextOrder, + )) { + changed.add(id); + } + } + 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 || + !deepEqual(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 ( + !deepEqual(beforeContent, afterContent) && + inline(beforeContent) === inline(afterContent) + ) { + preserveRuns = true; + } + } + if (!changed.size) { + return "(no 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 new file mode 100644 index 0000000000..84103e9f83 --- /dev/null +++ b/tests/src/commands/node/index.ts @@ -0,0 +1,4 @@ +// Baseline helpers run directly in Node/jsdom and in browser tests. +export { compareDocuments } from "./compareDocuments.js"; +export type { DocumentBlock } from "./compareDocuments.js"; +export { selectText } from "./selectText.js"; diff --git a/tests/src/commands/node/selectText.ts b/tests/src/commands/node/selectText.ts new file mode 100644 index 0000000000..ee47c196d7 --- /dev/null +++ b/tests/src/commands/node/selectText.ts @@ -0,0 +1,116 @@ +import { type BlockNoteEditor, getNodeById } from "@blocknote/core"; +import { TextSelection } from "@tiptap/pm/state"; + +/** + * Selects the first exact substring in document order, including text split across + * different marks, without crossing blocks or non-text inline nodes. Use to set up + * a component's selection-dependent state or formatting action without repeating + * unrelated keyboard navigation. Use real keyboard/pointer input instead when + * selection gestures or keyboard navigation are the behavior under test. + * + * Does not focus the editor. Restrict duplicate text with an inclusive block range; + * 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" }], + * }); + * selectText(editor, "selected"); + * await page.getByRole("button", { name: "Bold", exact: true }).click(); + * + * @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, + substring: string, + range?: { startBlockId: string; endBlockId?: string }, +) { + if (substring.length === 0) { + throw new Error("selectText requires a non-empty substring"); + } + const matched = 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)); + 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, + }; +} diff --git a/tests/src/commands/node/setupEditor.ts b/tests/src/commands/node/setupEditor.ts new file mode 100644 index 0000000000..fe21e95e65 --- /dev/null +++ b/tests/src/commands/node/setupEditor.ts @@ -0,0 +1,99 @@ +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 headless 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 editor = BlockNoteEditor.create({ ...options, schema }); + onFinished(() => { + editor.unmount(); + }); + return { editor }; + } + + /** + * 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. 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 only `{ editor }`; there is no mounting container. + * + * @example + * + * 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 }>; + function setupEditor(options?: DefaultOptions): Promise<{ + editor: BlockNoteEditor< + DefaultBlockSchema, + DefaultInlineContentSchema, + DefaultStyleSchema + >; + }>; + 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/screen-reader/setupScreenReader.ts b/tests/src/commands/screen-reader/setupScreenReader.ts new file mode 100644 index 0000000000..c3588a2732 --- /dev/null +++ b/tests/src/commands/screen-reader/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("./transport.js") + ]: (typeof import("./transport.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/screen-reader/transport.ts b/tests/src/commands/screen-reader/transport.ts new file mode 100644 index 0000000000..395b5c70dd --- /dev/null +++ b/tests/src/commands/screen-reader/transport.ts @@ -0,0 +1,82 @@ +import { pressKey } from "../transport/keyboard.js"; +import type { BrowserCommand } from "vite-plus/test/node"; +import type {} from "../transport/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 new file mode 100644 index 0000000000..044290eed2 --- /dev/null +++ b/tests/src/commands/transport.ts @@ -0,0 +1,36 @@ +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. +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/utils/imeComposition.ts b/tests/src/commands/transport/imeComposition.ts similarity index 69% rename from tests/src/utils/imeComposition.ts rename to tests/src/commands/transport/imeComposition.ts index 6579a10239..c19197be2c 100644 --- a/tests/src/utils/imeComposition.ts +++ b/tests/src/commands/transport/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 "../node/selectText.js"; + /** * One step of an emulated IME session. `setComposition` updates the active * composition (starting one if none is active); `commit` finalizes it with @@ -23,12 +28,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 @@ -37,6 +36,24 @@ export type ImeCompositionCommand = (steps: ImeStep[]) => Promise; * 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/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/transport/keyboard.ts b/tests/src/commands/transport/keyboard.ts new file mode 100644 index 0000000000..362d5a239b --- /dev/null +++ b/tests/src/commands/transport/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 "../node/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/transport/positionalMouse.ts similarity index 63% rename from tests/src/utils/positionalMouse.ts rename to tests/src/commands/transport/positionalMouse.ts index 840a088840..971326e873 100644 --- a/tests/src/utils/positionalMouse.ts +++ b/tests/src/commands/transport/positionalMouse.ts @@ -26,26 +26,27 @@ export type MouseAction = | { 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. + * 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/transport/restoreTouchEmulation.ts similarity index 71% rename from tests/src/utils/restoreTouchEmulation.ts rename to tests/src/commands/transport/restoreTouchEmulation.ts index 47b4844dba..0478debde5 100644 --- a/tests/src/utils/restoreTouchEmulation.ts +++ b/tests/src/commands/transport/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/fixtures/editor.node.ts b/tests/src/fixtures/editor.node.ts new file mode 100644 index 0000000000..720994b54f --- /dev/null +++ b/tests/src/fixtures/editor.node.ts @@ -0,0 +1,22 @@ +/* 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: headless core editors, without a DOM, React, or skin styles. */ +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 new file mode 100644 index 0000000000..e4deff827f --- /dev/null +++ b/tests/src/fixtures/editor.tsx @@ -0,0 +1,8 @@ +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 type BrowserContext = Omit & CommandContext; + +export const test: TestAPI = + base.extend(commands); 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/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..b77e1ee939 100644 --- a/tests/screen-reader/vite.config.screen-reader.ts +++ b/tests/src/screen-reader/vite.config.screen-reader.ts @@ -1,19 +1,8 @@ -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/transport/index.js"; +import { screenReaderCommand } from "../commands/screen-reader/transport.js"; const reader = process.env.BLOCKNOTE_SCREEN_READER; if (reader !== "voiceover" && reader !== "nvda") { @@ -27,19 +16,18 @@ 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)), "@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,10 @@ 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)), + fileURLToPath( + new URL("../../vitestSetup.screen-reader.ts", import.meta.url), + ), ], include: ["../packages/*/src/**/*.screen-reader.test.ts"], testTimeout: 300_000, @@ -81,17 +72,7 @@ export default defineConfig({ name: reader, }, ], - commands: { - readAriaSnapshot, - readOutline, - checkFocusOutline, - readSelection, - checkAxe, - startReader, - pressKey: screenReaderPressKey, - readTranscript, - stopReader, - }, + commands: { ...commands, screenReaderCommand }, }, }, }); 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/context.ts b/tests/src/utils/context.ts index 7c08bca368..4180a06e5d 100644 --- a/tests/src/utils/context.ts +++ b/tests/src/utils/context.ts @@ -1,48 +1,16 @@ -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"; +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"; -// `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 }; - -// 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; +// Compatibility for existing suites; extended tests use top-level fixtures. +export const commands = { + ...baselineCommands, + ...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/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..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 "./positionalMouse.js"; +import type { MouseAction } from "../commands/transport/positionalMouse.js"; function runMouse(actions: MouseAction[]): Promise { return commands.positionalMouse(...actions); 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 3f395e49b7..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"], @@ -23,9 +22,9 @@ "include": [ "src/utils/**/*.ts", "src/utils/**/*.tsx", - "screen-reader/**/*.ts", + "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.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/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 4d18c603d7..ed1964b40a 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/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 @@ -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. @@ -100,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 @@ -130,7 +119,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 @@ -180,17 +172,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/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.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 fd93e2712c..5c4c4ddaf6 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/transport/keyboard.js"; import { afterEach, beforeAll, beforeEach } from "vite-plus/test"; import { commands, page } from "./src/utils/context.js"; @@ -54,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/utils/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.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/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..88f5851afe 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,9 @@ { "files": [], "references": [ + { "path": "./tests/tsconfig.node.json" }, { "path": "./tests/tsconfig.browser.json" }, + { "path": "./tests/tsconfig.screen-reader.json" }, { "path": "./packages/core" }, { "path": "./packages/code-block" }, { "path": "./packages/react" }, diff --git a/vite.config.ts b/vite.config.ts index 070e97bfaf..1351c98f75 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,5 +1,49 @@ 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 }, +]; +const browserTestImportPatterns = [ + { + group: [ + "**/utils/accessibility", + "**/utils/accessibility.*", + "**/utils/keyboard", + "**/utils/keyboard.*", + "**/screen-reader/screenReader", + "**/screen-reader/screenReader.*", + ], + allowTypeImports: true, + message: + "Use the registered commands from tests/src/utils/context.ts instead of importing command implementations.", + }, + { + group: ["timers", "timers/*", "node:timers", "node:timers/*"], + message: testSleepMessage, + }, +]; + export default defineConfig({ staged: { // Format + fast lint (no type-aware) on pre-commit for speed. @@ -15,7 +59,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": { @@ -66,8 +110,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, @@ -99,6 +149,13 @@ export default defineConfig({ "import/no-cycle": "off", }, overrides: [ + { + // Pilot on the component examples + files: componentTestFiles, + rules: { + "blocknote-tests/component-browser-structure": "error", + }, + }, { files: ["packages/*/src/**/*.{ts,tsx}"], excludeFiles: ["**/*.test.{ts,tsx}"], @@ -143,35 +200,12 @@ export default defineConfig({ "no-restricted-imports": [ "error", { - patterns: [ - { - group: [ - "**/utils/accessibility", - "**/utils/accessibility.*", - "**/utils/keyboard", - "**/utils/keyboard.*", - "**/screen-reader/screenReader", - "**/screen-reader/screenReader.*", - ], - allowTypeImports: true, - message: - "Use the registered commands from tests/src/utils/context.ts instead of importing command implementations.", - }, - { - group: ["timers", "timers/*", "node:timers", "node:timers/*"], - message: - "Wait for observable readiness with expect.element or expect.poll instead of sleeping.", - }, - ], + patterns: browserTestImportPatterns, }, ], "no-restricted-properties": [ "error", - { - property: "getByTestId", - message: - "Use accessible locators such as getByRole with a name or getByLabel in browser tests.", - }, + testIdRestriction, { property: "waitForTimeout", message: @@ -185,6 +219,34 @@ export default defineConfig({ ], }, }, + { + files: componentTestFiles, + rules: { + "no-restricted-globals": [ + "error", + { name: "setTimeout", message: testSleepMessage }, + ], + "no-restricted-properties": [ + "error", + ...testSleepProperties, + testIdRestriction, + ], + "no-restricted-imports": [ + "error", + { + // Overrides replace rule options, so retain the shared safeguards. + patterns: [ + ...browserTestImportPatterns, + { + group: ["**/utils/editor.js", "**/utils/editor"], + importNames: ["sleep"], + message: testSleepMessage, + }, + ], + }, + ], + }, + }, { files: [ "**/scripts/**",