Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions packages/core/src/editor/BlockNoteEditor.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,6 @@ it("reuses complete dictionaries without copying them", () => {
}
});

it("supplies picker strings for dictionaries that omit the picker section", () => {
const { emoji_picker: _picker, ...dictionary } = en;
const editor = BlockNoteEditor.create({
// @ts-expect-error Simulate a dictionary authored before emoji_picker existed.
dictionary,
});
try {
expect(editor.dictionary.emoji_picker).toEqual(en.emoji_picker);
expect(editor.dictionary.slash_menu).toBe(dictionary.slash_menu);
expect(editor.dictionary).toBe(dictionary);
} finally {
editor._tiptapEditor.destroy();
}
});

it("emits destroy once, including listeners registered during extension initialization", () => {
const onDestroy = vi.fn();
const LifecycleExtension = createExtension(({ editor }) => {
Expand Down
3 changes: 0 additions & 3 deletions packages/core/src/editor/BlockNoteEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,6 @@ export class BlockNoteEditor<
super();

this.dictionary = options.dictionary || en;
Comment thread
matthewlipski marked this conversation as resolved.
Resolved
if (this.dictionary.emoji_picker === undefined) {
this.dictionary.emoji_picker = en.emoji_picker;
}
this.settings = {
tables: {
splitCells: options?.tables?.splitCells ?? false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
HistoryExtension,
InlineContentBoundaryEditExtension,
LinkToolbarExtension,
LiveAnnouncerExtension,
LoadingExtension,
NodeSelectionKeyboardExtension,
PlaceholderExtension,
Expand Down Expand Up @@ -174,6 +175,7 @@ export function getDefaultExtensions(
: {}),
}),
LinkToolbarExtension(options),
LiveAnnouncerExtension(),
LoadingExtension(),
NodeSelectionKeyboardExtension(),
PlaceholderExtension(options),
Expand Down
62 changes: 62 additions & 0 deletions packages/core/src/extensions/LiveAnnouncer/LiveAnnouncer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { createExtension } from "../../editor/BlockNoteExtension.js";

/**
* Announces short status messages to screen readers through a polite live
* region, for editor changes that only show visually (e.g. indenting a block
* with Tab).
*
* The region is a visually hidden sibling of the editor's `contenteditable`
* element, so ProseMirror never sees it and it stays near the editor in the
* accessibility tree (e.g. inside the same modal dialog).
*/
export const LiveAnnouncerExtension = createExtension(() => {
let region: HTMLElement | undefined;

return {
key: "liveAnnouncer",
mount({ dom, signal }) {
const liveRegion = dom.ownerDocument.createElement("div");
liveRegion.className = "bn-live-announcer";
liveRegion.setAttribute("role", "status");
liveRegion.setAttribute("aria-live", "polite");
liveRegion.setAttribute("aria-atomic", "true");
// Visually hidden, but still exposed to assistive technologies. Inline
// so it holds without any stylesheet.
Object.assign(liveRegion.style, {
position: "absolute",
width: "1px",
height: "1px",
overflow: "hidden",
clipPath: "inset(50%)",
whiteSpace: "nowrap",
});
// The region has to be in the DOM before its content changes for the
// change to be announced, so it's added up front rather than on demand.
dom.after(liveRegion);
region = liveRegion;

signal.addEventListener(
"abort",
() => {
liveRegion.remove();
if (region === liveRegion) {
region = undefined;
}
},
{ once: true },
);
},
/**
* Announces a message to screen readers. Does nothing while the editor
* isn't mounted.
*/
announce(message: string) {
if (!region) {
return;
}
// Replacing the text node, rather than editing it, makes screen readers
// repeat a message that's identical to the previous one.
region.replaceChildren(region.ownerDocument.createTextNode(message));
},
};
});
1 change: 1 addition & 0 deletions packages/core/src/extensions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export * from "./History/History.js";
export * from "./InlineContentBoundaryEdit/InlineContentBoundaryEdit.js";
export * from "./LinkToolbar/LinkToolbar.js";
export * from "./LinkToolbar/protocols.js";
export * from "./LiveAnnouncer/LiveAnnouncer.js";
export * from "./Loading/Loading.js";
export * from "./NodeSelectionKeyboard/NodeSelectionKeyboard.js";
export * from "./Placeholder/Placeholder.js";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
BlockNoteEditor,
type BlockNoteEditorOptions,
} from "../../../editor/BlockNoteEditor.js";
import { fr } from "../../../i18n/locales/index.js";
import { createBlockSpec } from "../../../schema/index.js";
import { MultipleNodeSelection } from "../../SideMenu/MultipleNodeSelection.js";

Expand Down Expand Up @@ -941,6 +942,185 @@ describe("KeyboardShortcutsExtension Shift-Tab", () => {
});
});

// #2812: indenting with Tab only changed the block visually, so screen reader
// users got no feedback that it worked, or at which level the block ended up.
describe("KeyboardShortcutsExtension Tab announcements", () => {
function createMountedEditor(
cursorId: string,
options: Partial<BlockNoteEditorOptions<any, any, any>> = {},
) {
const wrapper = document.createElement("div");
const mountPoint = document.createElement("div");
wrapper.appendChild(mountPoint);
document.body.appendChild(wrapper);
const editor = BlockNoteEditor.create({
schema,
initialContent: [
{ id: "a", type: "paragraph", content: "Parent" },
{ id: "b", type: "paragraph", content: "Child" },
],
...options,
});
editor.mount(mountPoint);
editor.setTextCursorPosition(cursorId, "start");
return { editor, wrapper };
}

function liveRegion(wrapper: HTMLElement) {
return wrapper.querySelector<HTMLElement>("[aria-live]");
}

function pressTab(editor: BlockNoteEditor<any, any, any>, shiftKey = false) {
keyDown(editor, { key: "Tab", code: "Tab", shiftKey });
}

it("renders a polite live region outside the contenteditable", () => {
const { editor, wrapper } = createMountedEditor("b");
const region = liveRegion(wrapper);

expect(region).not.toBeNull();
expect(region!.getAttribute("aria-live")).toBe("polite");
expect(region!.getAttribute("role")).toBe("status");
expect(editor.domElement!.contains(region)).toBe(false);
expect(region!.textContent).toBe("");

editor._tiptapEditor.destroy();
wrapper.remove();
});

it("announces the new level on Tab and Shift-Tab", () => {
const { editor, wrapper } = createMountedEditor("b");

pressTab(editor);
expect(outline(editor.document)[0].children).toHaveLength(1);
expect(liveRegion(wrapper)!.textContent).toBe("Indented, level 2");

pressTab(editor, true);
expect(editor.document).toHaveLength(2);
expect(liveRegion(wrapper)!.textContent).toBe("Outdented, level 1");

editor._tiptapEditor.destroy();
wrapper.remove();
});

it.each([false, true])(
"does not announce a rejected nesting change (shift: %s)",
(shift) => {
const { editor, wrapper } = createMountedEditor("b");
if (shift) {
editor.nestBlock();
}
const previousDoc = editor.prosemirrorState.doc;
let rejected = false;
editor.onBeforeChange(() => {
rejected = true;
return false;
});

pressTab(editor, shift);

expect(rejected).toBe(true);
expect(editor.prosemirrorState.doc).toBe(previousDoc);
expect(liveRegion(wrapper)!.textContent).toBe("");

editor._tiptapEditor.destroy();
wrapper.remove();
},
);

it("announces the moved blocks' level for a whole-block selection", () => {
const { editor, wrapper } = createMountedEditor("b", {
initialContent: [
{ id: "a", type: "paragraph", content: "Parent" },
{ id: "b", type: "paragraph", content: "First child" },
{ id: "c", type: "paragraph", content: "Second child" },
],
});
editor.transact((tr) => {
const first = getNodeById("b", tr.doc)!;
const last = getNodeById("c", tr.doc)!;
tr.setSelection(
MultipleNodeSelection.create(
tr.doc,
first.posBeforeNode,
last.posBeforeNode + last.node.nodeSize,
),
);
});

pressTab(editor);
expect(editor.document[0].children.map((block) => block.id)).toEqual([
"b",
"c",
]);
expect(liveRegion(wrapper)!.textContent).toBe("Indented, level 2");

pressTab(editor, true);
expect(editor.document.map((block) => block.id)).toEqual(["a", "b", "c"]);
expect(liveRegion(wrapper)!.textContent).toBe("Outdented, level 1");

editor._tiptapEditor.destroy();
wrapper.remove();
});

it("announces nothing when the block can't be indented", () => {
const { editor, wrapper } = createMountedEditor("a");

pressTab(editor);
pressTab(editor, true);

expect(editor.document).toHaveLength(2);
expect(liveRegion(wrapper)!.textContent).toBe("");

editor._tiptapEditor.destroy();
wrapper.remove();
});

it("announces deeper levels", () => {
const { editor, wrapper } = createMountedEditor("c", {
initialContent: [
{
id: "a",
type: "paragraph",
content: "Parent",
children: [
{ id: "b", type: "paragraph", content: "Child" },
{ id: "c", type: "paragraph", content: "Grandchild" },
],
},
],
});

pressTab(editor);
expect(outline(editor.document)[0].children[0].children).toHaveLength(1);
expect(liveRegion(wrapper)!.textContent).toBe("Indented, level 3");

editor._tiptapEditor.destroy();
wrapper.remove();
});

it("uses the editor's dictionary", () => {
const { editor, wrapper } = createMountedEditor("b", { dictionary: fr });

pressTab(editor);
expect(liveRegion(wrapper)!.textContent).toBe("Retrait augmenté, niveau 2");

editor._tiptapEditor.destroy();
wrapper.remove();
});

it("removes the live region when the editor unmounts", () => {
const { editor, wrapper } = createMountedEditor("b");
expect(liveRegion(wrapper)).not.toBeNull();

editor.unmount();
expect(liveRegion(wrapper)).toBeNull();

editor._tiptapEditor.destroy();
wrapper.remove();
});
});

describe("KeyboardShortcutsExtension line breaks", () => {
it("inserts a hard break on Shift-Enter by default", () => {
const editor = createEditor("paragraph");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type ChainedCommands, Extension } from "@tiptap/core";
import { GapCursor } from "@tiptap/pm/gapcursor";
import { Fragment, type Node } from "prosemirror-model";
import { Fragment, type Node, type ResolvedPos } from "prosemirror-model";
import {
NodeSelection,
Selection,
Expand Down Expand Up @@ -32,6 +32,7 @@ import {
getBlockInfoAt,
getBlockInfoFromNode,
getBlockInfoFromSelection,
getBlockInfoNearPos,
getLastDescendantBlockInfo,
getNextBlockInfo,
getParentBlockInfo,
Expand All @@ -42,8 +43,22 @@ import { BlockNoteEditor } from "../../../editor/BlockNoteEditor.js";
import { hasInputRule } from "../../../editor/inputRules.js";
import { FilePanelExtension } from "../../FilePanel/FilePanel.js";
import { FormattingToolbarExtension } from "../../FormattingToolbar/FormattingToolbar.js";
import { LiveAnnouncerExtension } from "../../LiveAnnouncer/LiveAnnouncer.js";
import { MultipleNodeSelection } from "../../SideMenu/MultipleNodeSelection.js";

// How deeply the block at `$pos` is nested, counting top-level blocks as level
// 1. Layout blocks (e.g. columns) aren't block containers, so a block inside
// them stays at the level it visually sits at.
function nestingLevel($pos: ResolvedPos) {
let level = 0;
for (let depth = $pos.depth; depth > 0; depth--) {
if ($pos.node(depth).type.name === "blockContainer") {
level++;
}
}
return level;
}

// Move a block across a layout block boundary, repair its former ancestors, and
// map the caret through any repairs that change the insertion position.
function moveBlockOutAndPlaceCaret(
Expand Down Expand Up @@ -1062,7 +1077,26 @@ export const KeyboardShortcutsExtension = Extension.create<{
// Let the browser navigate into and out of an open toolbar.
return false;
}
return shift ? unnestBlock(editor) : nestBlock(editor);
const previousDoc = editor.prosemirrorState.doc;
const moved = shift ? unnestBlock(editor) : nestBlock(editor);
const state = editor.prosemirrorState;
// Commands can return true even when onBeforeChange rejects the change.
if (moved && state.doc !== previousDoc) {
// The indent is only visible, so tell screen readers about it too
// (#2812).
const { block_nesting } = editor.dictionary;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Whole-block selections start outside the block's own container.
const { block } = getBlockInfoNearPos(state, state.selection.from);
const level = nestingLevel(state.doc.resolve(block.beforePos + 1));
editor
.getExtension(LiveAnnouncerExtension)
?.announce(
shift
? block_nesting.outdented(level)
: block_nesting.indented(level),
);
}
return moved;
}

return {
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/i18n/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ export const ar: Dictionary = {
add_block_button: "تبديل فارغ. انقر لإضافة كتلة.",
toggle_button: "توسيع أو طي",
},
block_nesting: {
indented: (level: number) => `تمت زيادة المسافة البادئة، المستوى ${level}`,
outdented: (level: number) => `تم تقليل المسافة البادئة، المستوى ${level}`,
},
code_block: {
add_source_button_text: "إضافة كود المصدر",
ok_button_text: "موافق",
Expand Down
Loading
Loading