Skip to content

Commit b18522b

Browse files
committed
Refine source-less media import and export
1 parent 323fb0d commit b18522b

39 files changed

Lines changed: 392 additions & 686 deletions

‎docs/content/docs/features/import/html.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ tryParseHTMLToBlocks(html: string): Block[];
2626
const blocksFromHTML = editor.tryParseHTMLToBlocks(html);
2727
```
2828

29-
`returns:` The blocks parsed from the HTML string.
29+
`returns:` The blocks parsed from the HTML string. If the input produces no blocks, the result is an empty array (`[]`). For example, both `""` and `"<video></video>"` return `[]`.
3030

3131
Tries to create `Block` objects out of any HTML block-level elements, and `InlineContent` objects from any HTML inline elements, though not all HTML tags are recognized. If BlockNote doesn't recognize an element's tag, it will parse it as a paragraph or plain text.
3232

‎packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.browser.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,41 @@ function parseHTML(html: string) {
2222
}
2323

2424
describe("a block that exports as nothing", () => {
25+
it("keeps the ordered list restart after an omitted image in HTML and Markdown", async ({
26+
setupEditor,
27+
}) => {
28+
const { editor } = await setupEditor({ mountType: false });
29+
const blocks = [
30+
{ type: "numberedListItem", content: "A" },
31+
{ type: "image" },
32+
{ type: "numberedListItem", content: "B", props: { start: 10 } },
33+
{ type: "numberedListItem", content: "C" },
34+
] as const;
35+
const dom = parseHTML(editor.blocksToHTMLLossy([...blocks]));
36+
37+
expect(
38+
Array.from(dom.children, (list) => [
39+
list.tagName,
40+
list.getAttribute("start"),
41+
list.textContent,
42+
]),
43+
).toEqual([
44+
["OL", null, "A"],
45+
["OL", "10", "BC"],
46+
]);
47+
48+
const markdown = editor.blocksToMarkdownLossy([...blocks]);
49+
expect(editor.tryParseMarkdownToBlocks(markdown)).toMatchObject([
50+
{ type: "numberedListItem", content: [{ text: "A" }] },
51+
{
52+
type: "numberedListItem",
53+
props: { start: 10 },
54+
content: [{ text: "B" }],
55+
},
56+
{ type: "numberedListItem", content: [{ text: "C" }] },
57+
]);
58+
});
59+
2560
// The serializer puts a child list of a list item into the item before it.
2661
// The item before a block that is left out is not the item of that block.
2762
it("keeps its child list out of the list item before it", async ({

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,9 @@ function serializeBlock<
249249
orderedListItemBlockTypes: Set<string>,
250250
unorderedListItemBlockTypes: Set<string>,
251251
nestingLevel: number,
252+
canContinueList: boolean,
252253
options?: { document?: Document },
253-
) {
254+
): boolean {
254255
const doc = options?.document ?? document;
255256
const BC_NODE = editor.pmSchema.nodes["blockContainer"];
256257

@@ -306,7 +307,8 @@ function serializeBlock<
306307
options,
307308
);
308309
fragment.append(childFragment);
309-
return;
310+
// The block still separates the list runs on either side of it.
311+
return false;
310312
}
311313

312314
const elementFragment = doc.createDocumentFragment();
@@ -414,7 +416,7 @@ function serializeBlock<
414416
}
415417

416418
if (listType) {
417-
if (fragment.lastChild?.nodeName !== listType) {
419+
if (!canContinueList || fragment.lastChild?.nodeName !== listType) {
418420
const list = doc.createElement(listType);
419421

420422
if (
@@ -477,6 +479,7 @@ function serializeBlock<
477479
ret.contentDOM.append(childFragment);
478480
}
479481
}
482+
return true;
480483
}
481484

482485
const serializeBlocksToFragment = <
@@ -493,15 +496,17 @@ const serializeBlocksToFragment = <
493496
nestingLevel = 0,
494497
options?: { document?: Document },
495498
) => {
499+
let canContinueList = false;
496500
for (const block of blocks) {
497-
serializeBlock(
501+
canContinueList = serializeBlock(
498502
fragment,
499503
editor,
500504
block,
501505
serializer,
502506
orderedListItemBlockTypes,
503507
unorderedListItemBlockTypes,
504508
nestingLevel,
509+
canContinueList,
505510
options,
506511
);
507512
}

‎packages/core/src/api/exporters/markdown/htmlToMarkdown.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,10 @@ function serializeUnorderedList(
276276

277277
function serializeOrderedList(el: HTMLElement, ctx: SerializeContext): string {
278278
let result = "";
279+
if (el.previousElementSibling?.tagName.toLowerCase() === "ol") {
280+
// A blank line alone would join these lists and lose the second start.
281+
result = (ctx.inListItem ? "\n" : "") + ctx.indent + "<!-- -->\n\n";
282+
}
279283
const items = Array.from(el.children).filter(
280284
(child) => child.tagName.toLowerCase() === "li",
281285
);

‎packages/core/src/api/parsers/html/parseHTML.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,11 @@ export function HTMLToBlocks<
7575
BSchema extends BlockSchema,
7676
I extends InlineContentSchema,
7777
S extends StyleSchema,
78-
>(html: string, pmSchema: Schema): Block<BSchema, I, S>[] {
78+
>(
79+
html: string,
80+
pmSchema: Schema,
81+
{ fillEmpty = false }: { fillEmpty?: boolean } = {},
82+
): Block<BSchema, I, S>[] {
7983
const htmlNode = detachedDoc().createElement("div");
8084
htmlNode.innerHTML = html;
8185
// Lift images before list normalization so a nested list after an image
@@ -91,8 +95,15 @@ export function HTMLToBlocks<
9195
// const doc = pmSchema.nodes["doc"].createAndFill()!;
9296
// and context: doc.resolve(3),
9397

98+
const blockGroup = pmSchema.nodes["blockGroup"];
9499
const parsedNode = parser.parse(htmlNode, {
95-
topNode: pmSchema.nodes["blockGroup"].create(),
100+
topNode: blockGroup.create(),
101+
// After the first `blockGroupChild`, the group allows zero or more
102+
// children instead of one or more. Use that match for an HTML fragment.
103+
topMatch: fillEmpty
104+
? undefined
105+
: (blockGroup.contentMatch.matchType(pmSchema.nodes["blockContainer"]) ??
106+
undefined),
96107
});
97108
const parentNode = normalizeImportedTables(parsedNode);
98109

‎packages/core/src/api/parsers/markdown/markdownToHtml.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@ import { describe, expect } from "vite-plus/test";
22
import { markdownToHtml } from "./markdownToHtml.js";
33

44
describe("markdownToHtml", () => {
5+
it.each([
6+
'<video src="clip.mp4"></video>',
7+
'<video controls>\n <source src="clip.mp4">\n</video>',
8+
'<video controls>\n\n <source src="clip.mp4">\n</VIDEO>',
9+
])("parses a heading immediately after a video: %j", (video) => {
10+
expect(markdownToHtml(`${video}\n## Notes`)).toBe(`${video}<h2>Notes</h2>`);
11+
});
12+
513
it("keeps an unmatched backtick run literal", () => {
614
expect(markdownToHtml("``a`")).toBe("<p>``a`</p>");
715
});

‎packages/core/src/api/parsers/markdown/markdownToHtml.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,9 @@ const HTML_BLOCK_TAGS = new Set([
812812
"video",
813813
]);
814814

815+
const VIDEO_OPEN_RE = /^ {0,3}<video(?=\s|\/?>|$)/i;
816+
const VIDEO_CLOSE_RE = /<\/video\s*>/i;
817+
815818
function isHtmlBlockStart(line: string): boolean {
816819
// <!-- ..., <?..., <![CDATA[..., <!DOCTYPE, etc.
817820
if (/^ {0,3}<(!--|\?|![A-Za-z]|!\[CDATA\[)/.test(line)) {
@@ -1191,17 +1194,34 @@ function tokenize(markdown: string): Token[] {
11911194

11921195
// Block-level raw HTML: a line starting with `<tag>` (block-level tag),
11931196
// `<!-- ... -->`, `<?...?>`, `<!DOCTYPE ...>`, or `<![CDATA[...]]>`.
1194-
// Lines are emitted verbatim until the next blank line.
1197+
// Lines are emitted verbatim until the next blank line, or through the
1198+
// closing tag for a complete video element (which can contain <source>).
11951199
if (isHtmlBlockStart(line)) {
1196-
const htmlLines: string[] = [];
1197-
while (i < lines.length && lines[i].trim() !== "") {
1198-
htmlLines.push(lines[i]);
1199-
i++;
1200+
let end = i;
1201+
if (VIDEO_OPEN_RE.test(line)) {
1202+
// Stop looking at a new video so an unclosed tag can't swallow it.
1203+
let closingLine = i;
1204+
while (
1205+
!VIDEO_CLOSE_RE.test(lines[closingLine]) &&
1206+
closingLine + 1 < lines.length &&
1207+
!VIDEO_OPEN_RE.test(lines[closingLine + 1])
1208+
) {
1209+
closingLine++;
1210+
}
1211+
if (VIDEO_CLOSE_RE.test(lines[closingLine])) {
1212+
end = closingLine + 1;
1213+
}
1214+
}
1215+
if (end === i) {
1216+
while (end < lines.length && lines[end].trim() !== "") {
1217+
end++;
1218+
}
12001219
}
12011220
tokens.push({
12021221
type: "rawHtml",
1203-
content: htmlLines.join("\n"),
1222+
content: lines.slice(i, end).join("\n"),
12041223
});
1224+
i = end;
12051225
prevLineWasBlank = false;
12061226
continue;
12071227
}

‎packages/core/src/api/parsers/markdown/parseMarkdown.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,5 @@ export function markdownToBlocks<
2020
>(markdown: string, pmSchema: Schema): Block<BSchema, I, S>[] {
2121
const htmlString = markdownToHTML(markdown);
2222

23-
return HTMLToBlocks(htmlString, pmSchema);
23+
return HTMLToBlocks(htmlString, pmSchema, { fillEmpty: true });
2424
}

‎packages/core/src/blocks/Audio/block.ts‎

Lines changed: 7 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,10 @@ import {
55
createBlockSpec,
66
} from "../../schema/index.js";
77
import { defaultProps, parseDefaultProps } from "../defaultProps.js";
8-
import { parseFigureElement } from "../File/helpers/parse/parseFigureElement.js";
8+
import { parseMediaElement } from "../File/helpers/parse/parseMediaElement.js";
99
import { createFileBlockWrapper } from "../File/helpers/render/createFileBlockWrapper.js";
1010
import { createFigureWithCaption } from "../File/helpers/toExternalHTML/createFigureWithCaption.js";
1111
import { createLinkWithCaption } from "../File/helpers/toExternalHTML/createLinkWithCaption.js";
12-
import { parseAudioElement } from "./parseAudioElement.js";
1312

1413
export const FILE_AUDIO_ICON_SVG =
1514
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 16.0001H5.88889L11.1834 20.3319C11.2727 20.405 11.3846 20.4449 11.5 20.4449C11.7761 20.4449 12 20.2211 12 19.9449V4.05519C12 3.93977 11.9601 3.8279 11.887 3.73857C11.7121 3.52485 11.3971 3.49335 11.1834 3.66821L5.88889 8.00007H2C1.44772 8.00007 1 8.44778 1 9.00007V15.0001C1 15.5524 1.44772 16.0001 2 16.0001ZM23 12C23 15.292 21.5539 18.2463 19.2622 20.2622L17.8445 18.8444C19.7758 17.1937 21 14.7398 21 12C21 9.26016 19.7758 6.80629 17.8445 5.15557L19.2622 3.73779C21.5539 5.75368 23 8.70795 23 12ZM18 12C18 10.0883 17.106 8.38548 15.7133 7.28673L14.2842 8.71584C15.3213 9.43855 16 10.64 16 12C16 13.36 15.3213 14.5614 14.2842 15.2841L15.7133 16.7132C17.106 15.6145 18 13.9116 18 12Z"></path></svg>';
@@ -50,49 +49,13 @@ export const createAudioBlockConfig = createBlockConfig(
5049
export const audioParse =
5150
(_config: AudioOptions = {}) =>
5251
(element: HTMLElement) => {
53-
if (element.tagName === "AUDIO") {
54-
// Ignore if parent figure has already been parsed.
55-
if (element.closest("figure")) {
56-
return undefined;
57-
}
58-
59-
// An audio without a URL gives no block.
60-
const audio = parseAudioElement(element as HTMLAudioElement);
61-
if (!audio.url) {
62-
return undefined;
63-
}
64-
65-
const { backgroundColor } = parseDefaultProps(element);
66-
67-
return {
68-
...audio,
69-
backgroundColor,
70-
};
71-
}
72-
73-
if (element.tagName === "FIGURE") {
74-
const parsedFigure = parseFigureElement(element, "audio");
75-
if (!parsedFigure) {
76-
return undefined;
77-
}
78-
79-
const { targetElement, caption } = parsedFigure;
80-
81-
const audio = parseAudioElement(targetElement as HTMLAudioElement);
82-
if (!audio.url) {
83-
return undefined;
84-
}
85-
86-
const { backgroundColor } = parseDefaultProps(element);
87-
88-
return {
89-
...audio,
90-
backgroundColor,
91-
caption,
92-
};
52+
const parsed = parseMediaElement(element, "audio");
53+
if (!parsed) {
54+
return undefined;
9355
}
9456

95-
return undefined;
57+
const { backgroundColor } = parseDefaultProps(element);
58+
return { url: parsed.url, caption: parsed.caption, backgroundColor };
9659
};
9760

9861
export const audioRender =
@@ -140,7 +103,7 @@ export const audioToExternalHTML =
140103
>,
141104
) => {
142105
// The upload placeholder (no URL) is not in the export.
143-
if (!block.props.url) {
106+
if (!block.props.url?.trim()) {
144107
return null;
145108
}
146109

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import { parseMediaUrl } from "../File/helpers/parse/parseMediaUrl.js";
2-
31
export const parseAudioElement = (audioElement: HTMLAudioElement) => {
4-
const url = parseMediaUrl(audioElement);
2+
const url = audioElement.src || undefined;
53

64
return { url };
75
};

0 commit comments

Comments
 (0)