Skip to content

Commit 496334a

Browse files
committed
feat(core): add accessible semantics to list items
Supersedes the runtime list ownership plugin approach proposed in #3223, while retaining its meta.listItem opt-in. Uses existing BlockContainer wrappers for list semantics and keeps numbered-list indexing independent.
1 parent 6dcb18a commit 496334a

29 files changed

Lines changed: 1698 additions & 42 deletions

File tree

Lines changed: 288 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,288 @@
1+
// @vitest-environment node
2+
import { DOMSerializer, Schema } from "prosemirror-model";
3+
import { describe, expect, it, vi } from "vite-plus/test";
4+
5+
import type { PartialBlock } from "../../../../blocks/defaultBlocks.js";
6+
import type { BlockNoteEditor } from "../../../../editor/BlockNoteEditor.js";
7+
import type {
8+
InlineContentSchema,
9+
StyleSchema,
10+
} from "../../../../schema/index.js";
11+
import { serializeBlocksInternalHTML } from "./serializeBlocksInternalHTML.js";
12+
13+
type FixtureSchema = Record<
14+
string,
15+
{ type: string; content: "none"; propSchema: { start: { default: number } } }
16+
>;
17+
type FixtureBlock = PartialBlock<
18+
FixtureSchema,
19+
InlineContentSchema,
20+
StyleSchema
21+
>;
22+
23+
// These tests exercise sibling traversal and attribute placement, not browser
24+
// rendering or parsing. Real HTML round trips and the accessibility tree need
25+
// the browser suite; this deliberately supplies no global document/jsdom.
26+
class ElementAdapter {
27+
attributes = new Map<string, string>();
28+
children: ElementAdapter[] = [];
29+
30+
constructor(readonly name: string) {}
31+
32+
setAttribute(name: string, value: string) {
33+
this.attributes.set(name, value);
34+
}
35+
36+
getAttribute(name: string) {
37+
return this.attributes.get(name) ?? null;
38+
}
39+
40+
appendChild(child: ElementAdapter) {
41+
if (child.name === "fragment") {
42+
this.children.push(...child.children);
43+
} else {
44+
this.children.push(child);
45+
}
46+
}
47+
48+
append(child: ElementAdapter) {
49+
this.appendChild(child);
50+
}
51+
}
52+
53+
vi.mock("../../../../schema/blocks/frame.js", () => ({
54+
markFrameSlot: vi.fn(),
55+
renderFrameDOM: (_editor: unknown, block: { type: string; id?: string }) => {
56+
if (block.type !== "layout" && block.type !== "framed") {
57+
return undefined;
58+
}
59+
const dom = new ElementAdapter(block.type);
60+
const slot = new ElementAdapter("slot");
61+
dom.setAttribute("data-id", block.id ?? "");
62+
dom.appendChild(slot);
63+
return { dom, slot };
64+
},
65+
}));
66+
67+
vi.mock("../../../../pm-nodes/BlockContainer.js", () => ({
68+
setBlockColorAttributes: vi.fn(),
69+
}));
70+
71+
const listTypes = [
72+
"bulletListItem",
73+
"numberedListItem",
74+
"checkListItem",
75+
"toggleListItem",
76+
"custom",
77+
"framed",
78+
];
79+
80+
function fixture(
81+
types = ["paragraph", "unmarked", "layout", ...listTypes],
82+
serializeInternalHTML = serializeBlocksInternalHTML,
83+
) {
84+
const schema = new Schema({
85+
nodes: {
86+
doc: { content: "blockGroup" },
87+
text: {},
88+
blockGroup: {
89+
content: "blockContainer*",
90+
toDOM: () => {
91+
const dom = new ElementAdapter("group");
92+
return {
93+
dom: dom as unknown as HTMLElement,
94+
contentDOM: dom as unknown as HTMLElement,
95+
};
96+
},
97+
},
98+
blockContainer: {
99+
attrs: { id: { default: null } },
100+
toDOM: (node) => {
101+
const dom = new ElementAdapter("outer");
102+
const contentDOM = new ElementAdapter("inner");
103+
contentDOM.setAttribute("data-id", node.attrs.id);
104+
dom.appendChild(contentDOM);
105+
return {
106+
dom: dom as unknown as HTMLElement,
107+
contentDOM: contentDOM as unknown as HTMLElement,
108+
};
109+
},
110+
},
111+
...Object.fromEntries(
112+
types.map((type) => [
113+
type,
114+
{
115+
group:
116+
type === "layout" ? "childContainer bnBlock" : "blockContent",
117+
},
118+
]),
119+
),
120+
},
121+
});
122+
const editor = {
123+
pmSchema: schema,
124+
schema: {
125+
blockSchema: Object.fromEntries(
126+
types.map((type) => [type, { propSchema: {} }]),
127+
),
128+
},
129+
blockImplementations: Object.fromEntries(
130+
types.map((type) => [
131+
type,
132+
{
133+
implementation: {
134+
meta: { listItem: listTypes.includes(type) },
135+
render: () => ({ dom: new ElementAdapter("content") }),
136+
},
137+
},
138+
]),
139+
),
140+
} as unknown as BlockNoteEditor<
141+
FixtureSchema,
142+
InlineContentSchema,
143+
StyleSchema
144+
>;
145+
const document = {
146+
createDocumentFragment: () => new ElementAdapter("fragment"),
147+
} as unknown as Document;
148+
return function serialize(blocks: FixtureBlock[]) {
149+
return serializeInternalHTML(
150+
editor,
151+
blocks,
152+
DOMSerializer.fromSchema(schema),
153+
{ document },
154+
) as unknown as ElementAdapter;
155+
};
156+
}
157+
158+
function inner(outer: ElementAdapter) {
159+
return outer.children[0];
160+
}
161+
162+
function expectRun(outers: ElementAdapter[]) {
163+
expect(outers[0].getAttribute("role")).toBe("list");
164+
const items = outers.map(inner);
165+
for (const item of items) {
166+
expect(item.getAttribute("role")).toBe("listitem");
167+
expect(item.getAttribute("id")).toMatch(/^[A-Za-z][\w-]+$/);
168+
}
169+
expect(outers[0].getAttribute("aria-owns")).toBe(
170+
items.length === 1
171+
? null
172+
: items
173+
.slice(1)
174+
.map((item) => item.getAttribute("id"))
175+
.join(" "),
176+
);
177+
for (const outer of outers.slice(1)) {
178+
expect(outer.getAttribute("role")).toBeNull();
179+
expect(outer.getAttribute("aria-owns")).toBeNull();
180+
}
181+
}
182+
183+
describe("static internal HTML list relationships", () => {
184+
it("keeps combined exports from independent module contexts uniquely owned", async () => {
185+
async function isolatedExport() {
186+
vi.resetModules();
187+
const { serializeBlocksInternalHTML } =
188+
await import("./serializeBlocksInternalHTML.js");
189+
return fixture(
190+
undefined,
191+
serializeBlocksInternalHTML,
192+
)([
193+
{ type: "bulletListItem", id: "same-a" },
194+
{ type: "bulletListItem", id: "same-b" },
195+
]);
196+
}
197+
198+
const first = await isolatedExport();
199+
const second = await isolatedExport();
200+
expectRun(first.children);
201+
expectRun(second.children);
202+
const combined = [...first.children, ...second.children];
203+
const ids = combined.map((outer) => inner(outer).getAttribute("id"));
204+
expect(new Set(ids).size).toBe(combined.length);
205+
for (const outer of combined) {
206+
for (const id of outer.getAttribute("aria-owns")?.split(" ") ?? []) {
207+
expect(ids.filter((target) => target === id)).toHaveLength(1);
208+
}
209+
}
210+
});
211+
212+
it("groups exact consecutive types; numbered restarts do not split runs", () => {
213+
const result = fixture()([
214+
{ type: "paragraph" },
215+
{ type: "bulletListItem" },
216+
{ type: "bulletListItem" },
217+
{ type: "numberedListItem" },
218+
{ type: "numberedListItem", props: { start: 7 } },
219+
{ type: "bulletListItem" },
220+
{ type: "unmarked" },
221+
{ type: "bulletListItem" },
222+
]);
223+
expectRun(result.children.slice(1, 3));
224+
expectRun(result.children.slice(3, 5));
225+
expectRun(result.children.slice(5, 6));
226+
expectRun(result.children.slice(7, 8));
227+
expect(inner(result.children[0]).getAttribute("role")).toBeNull();
228+
expect(result.children[6].getAttribute("role")).toBeNull();
229+
expect(inner(result.children[6]).getAttribute("role")).toBeNull();
230+
});
231+
232+
it.each(listTypes)(
233+
"supports %s without a numbered-list schema dependency",
234+
(type) => {
235+
const result = fixture([type])([{ type }, { type }]);
236+
expectRun(result.children);
237+
},
238+
);
239+
240+
it("keeps nested and framed content inside its item and layout parents separate", () => {
241+
const result = fixture()([
242+
{
243+
type: "bulletListItem",
244+
children: [
245+
{ type: "paragraph", id: "nested-text" },
246+
{ type: "bulletListItem" },
247+
{ type: "bulletListItem" },
248+
],
249+
},
250+
{ type: "bulletListItem" },
251+
{
252+
type: "layout",
253+
children: [{ type: "bulletListItem" }, { type: "bulletListItem" }],
254+
},
255+
{ type: "layout", children: [{ type: "bulletListItem" }] },
256+
{ type: "framed", children: [{ type: "bulletListItem" }] },
257+
]);
258+
expectRun(result.children.slice(0, 2));
259+
const nested = inner(result.children[0]).children[1];
260+
expect(inner(nested.children[0]).getAttribute("data-id")).toBe(
261+
"nested-text",
262+
);
263+
expectRun(nested.children.slice(1));
264+
expectRun(result.children[2].children[0].children);
265+
expectRun(result.children[3].children[0].children);
266+
expectRun(result.children.slice(4));
267+
const frame = inner(result.children[4]).children[0];
268+
expectRun(frame.children[0].children[1].children);
269+
});
270+
271+
it("uses unique serialization IDs even for missing, duplicate, and unsafe block IDs", () => {
272+
const serialize = fixture();
273+
const blocks: FixtureBlock[] = [
274+
{ type: "bulletListItem", id: 'unsafe " < & /' },
275+
{ type: "bulletListItem", id: 'unsafe " < & /' },
276+
{ type: "bulletListItem" },
277+
];
278+
const first = serialize(blocks);
279+
const second = serialize(blocks);
280+
expectRun(first.children);
281+
expectRun(second.children);
282+
const ids = [...first.children, ...second.children].map((outer) =>
283+
inner(outer).getAttribute("id"),
284+
);
285+
expect(new Set(ids).size).toBe(6);
286+
expect(inner(first.children[0]).getAttribute("data-id")).toBe(blocks[0].id);
287+
});
288+
});

‎packages/core/src/api/exporters/html/util/serializeBlocksInternalHTML.ts‎

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { DOMSerializer, Fragment, Node } from "prosemirror-model";
2+
import { uuidv4 } from "lib0/random";
23

34
import { PartialBlock } from "../../../../blocks/defaultBlocks.js";
45
import type { BlockNoteEditor } from "../../../../editor/BlockNoteEditor.js";
@@ -20,6 +21,36 @@ import {
2021
markFrameSlot,
2122
renderFrameDOM,
2223
} from "../../../../schema/blocks/frame.js";
24+
25+
type SerializedListItem = {
26+
outer: HTMLElement;
27+
inner: HTMLElement;
28+
id: string;
29+
};
30+
31+
// Keep the representation here: the first outer wrapper owns a list, whose
32+
// natural first child and explicitly owned later children encompass whole items.
33+
function addListAttributes(items: SerializedListItem[]) {
34+
if (items.length === 0) {
35+
return;
36+
}
37+
for (const item of items) {
38+
item.inner.setAttribute("role", "listitem");
39+
item.inner.setAttribute("id", item.id);
40+
}
41+
const owner = items[0].outer;
42+
owner.setAttribute("role", "list");
43+
if (items.length > 1) {
44+
owner.setAttribute(
45+
"aria-owns",
46+
items
47+
.slice(1)
48+
.map((item) => item.id)
49+
.join(" "),
50+
);
51+
}
52+
}
53+
2354
export function serializeInlineContentInternalHTML<
2455
BSchema extends BlockSchema,
2556
I extends InlineContentSchema,
@@ -172,7 +203,7 @@ function serializeBlock<
172203
if (children.length > 0) {
173204
frame.slot.append(serializeBlocks(editor, children, serializer, options));
174205
}
175-
return frame.dom;
206+
return { dom: frame.dom, listItemDOM: undefined };
176207
}
177208

178209
// Every block but a layout block declares `render` (`validateRenderHooks`).
@@ -234,7 +265,7 @@ function serializeBlock<
234265
serializeBlocksInternalHTML(editor, children, serializer, options),
235266
);
236267
}
237-
return bc.dom;
268+
return { dom: bc.dom, listItemDOM: bc.contentDOM };
238269
}
239270

240271
function serializeBlocks<
@@ -249,11 +280,39 @@ function serializeBlocks<
249280
) {
250281
const doc = options?.document ?? document;
251282
const fragment = doc.createDocumentFragment();
283+
// Separate from document IDs and the mounted editor's namespace. Random
284+
// scopes let exports from independent workers/page loads share a document.
285+
const scope = uuidv4();
286+
let runType: string | undefined;
287+
let run: SerializedListItem[] = [];
252288

253-
for (const block of blocks) {
254-
const blockDOM = serializeBlock(editor, block, serializer, options);
255-
fragment.appendChild(blockDOM);
289+
for (const [index, block] of blocks.entries()) {
290+
const { dom, listItemDOM } = serializeBlock(
291+
editor,
292+
block,
293+
serializer,
294+
options,
295+
);
296+
const type = block.type;
297+
const listItem =
298+
listItemDOM &&
299+
type !== undefined &&
300+
editor.blockImplementations[type].implementation.meta?.listItem === true;
301+
if (!listItem || type !== runType) {
302+
addListAttributes(run);
303+
run = [];
304+
runType = listItem ? type : undefined;
305+
}
306+
if (listItem && listItemDOM) {
307+
run.push({
308+
outer: dom,
309+
inner: listItemDOM,
310+
id: `bn-html-list-${scope}-${index}`,
311+
});
312+
}
313+
fragment.appendChild(dom);
256314
}
315+
addListAttributes(run);
257316

258317
return fragment;
259318
}

0 commit comments

Comments
 (0)