diff --git a/packages/core/src/api/parsers/html/parseHTML.ts b/packages/core/src/api/parsers/html/parseHTML.ts
index cfe1a49ba3..f21302780e 100644
--- a/packages/core/src/api/parsers/html/parseHTML.ts
+++ b/packages/core/src/api/parsers/html/parseHTML.ts
@@ -7,10 +7,12 @@ import {
} from "../../../schema/index.js";
import { Block } from "../../../blocks/defaultBlocks.js";
+import { detachedDoc } from "../../../util/detachedDoc.js";
import { EMPTY_BLOCK_PLACEHOLDER } from "../../exporters/html/util/serializeBlocksExternalHTML.js";
import { nodeToBlock } from "../../nodeConversions/nodeToBlock.js";
import { nestedListsToBlockNoteStructure } from "./util/nestedLists.js";
import { preprocessHTMLWhitespace } from "./util/normalizeWhitespace.js";
+import { moveImagesOutOfText } from "./util/imagesInText.js";
/**
* Removes the placeholder character that the external HTML exporter inserts
@@ -74,7 +76,16 @@ export function HTMLToBlocks<
I extends InlineContentSchema,
S extends StyleSchema,
>(html: string, pmSchema: Schema): Block[] {
- const htmlNode = nestedListsToBlockNoteStructure(html);
+ const htmlNode = detachedDoc().createElement("div");
+ htmlNode.innerHTML = html;
+ // The images move out of the text before the list steps. An image in the
+ // paragraph of a list item is then a block for these steps, and a nested
+ // list after it stays in the list item. Without the image block, the parse
+ // drops each image, and the text around it must stay one block.
+ if (pmSchema.nodes["image"]) {
+ moveImagesOutOfText(htmlNode);
+ }
+ nestedListsToBlockNoteStructure(htmlNode);
preprocessHTMLWhitespace(htmlNode);
const parser = DOMParser.fromSchema(pmSchema);
diff --git a/packages/core/src/api/parsers/html/util/imagesInText.ts b/packages/core/src/api/parsers/html/util/imagesInText.ts
new file mode 100644
index 0000000000..0bc8af4144
--- /dev/null
+++ b/packages/core/src/api/parsers/html/util/imagesInText.ts
@@ -0,0 +1,99 @@
+import { isAllowedUri } from "../../../../extensions/tiptap-extensions/Link/link.js";
+import { detachedDoc } from "../../../../util/detachedDoc.js";
+
+// The elements with text that split around an image.
+const TEXT_BLOCKS = "p, blockquote, h1, h2, h3, h4, h5, h6";
+
+// Removes the line breaks and the white space that are next to the image on
+// one side: they have no meaning at the edge of a block.
+function trimNextTo(image: Element, side: "previousSibling" | "nextSibling") {
+ for (let node = image[side]; node; node = image[side]) {
+ if (node.nodeName !== "BR") {
+ // Only a text node (type 3) can have white space.
+ if (node.nodeType !== 3) {
+ return;
+ }
+ const text = node.nodeValue ?? "";
+ node.nodeValue =
+ side === "nextSibling" ? text.trimStart() : text.trimEnd();
+ if (node.nodeValue) {
+ return;
+ }
+ }
+ node.remove();
+ }
+}
+
+// Moves the nodes that are before `node` in its parent to the end of `to`.
+function moveNodesBefore(node: ChildNode, to: ParentNode) {
+ const from = node.parentNode;
+ while (from?.firstChild && from.firstChild !== node) {
+ to.append(from.firstChild);
+ }
+}
+
+/**
+ * Moves each image out of the text that holds it. An image is a block, and
+ * ProseMirror drops a block that is in the text of a block.
+ *
+ * A paragraph, a quote and a heading split around the image, and the parts
+ * keep the attributes of the element. A table cell cannot hold a block, thus
+ * a link replaces the image there, if the URL of the image can be a link.
+ */
+export function moveImagesOutOfText(root: HTMLElement) {
+ // The nodes of an element that are complete wait here until the end. In
+ // jsdom, the time to put a node before another node grows with the number
+ // of nodes before it. Thus a block that splits must be near the start.
+ const complete = new Map();
+ for (const image of root.querySelectorAll("img")) {
+ // BlockNote's own HTML stays as it is: custom inline content can hold an
+ // image, and a block of the full HTML has only one content element. The
+ // summary of a toggle and the caption of a figure are text: an image
+ // cannot go out of them.
+ if (
+ image.closest(
+ "[data-inline-content-type], [data-content-type], summary, figcaption",
+ )
+ ) {
+ continue;
+ }
+ if (image.closest("td, th")) {
+ // Not each URL can be a link (for example `file:` and `data:`). Such an
+ // image stays, and the parse of the cell drops it.
+ if (image.src && isAllowedUri(image.src)) {
+ const link = detachedDoc().createElement("a");
+ link.href = image.src;
+ link.textContent = image.alt || image.src;
+ image.replaceWith(link);
+ }
+ continue;
+ }
+ // Splits the parent of the image until no text block holds the image: a
+ // copy of the parent takes the content before the image.
+ let holder: ParentNode | null = null;
+ while (image.parentElement?.closest(TEXT_BLOCKS)) {
+ const parent = image.parentElement;
+ trimNextTo(image, "previousSibling");
+ trimNextTo(image, "nextSibling");
+ const before = detachedDoc().importNode(parent, false);
+ moveNodesBefore(image, before);
+ parent.before(before, image);
+ holder = parent.parentNode;
+ // A part without text is not a block. Its other content stays.
+ for (const part of [before, parent]) {
+ if (!part.textContent?.trim()) {
+ part.replaceWith(...part.childNodes);
+ }
+ }
+ }
+ if (holder) {
+ const nodes =
+ complete.get(holder) ?? detachedDoc().createDocumentFragment();
+ complete.set(holder, nodes);
+ moveNodesBefore(image, nodes);
+ }
+ }
+ for (const [holder, nodes] of complete) {
+ holder.prepend(nodes);
+ }
+}
diff --git a/packages/core/src/api/parsers/html/util/nestedLists.test.ts b/packages/core/src/api/parsers/html/util/nestedLists.test.ts
index 6ee15c077d..06ec91eeb1 100644
--- a/packages/core/src/api/parsers/html/util/nestedLists.test.ts
+++ b/packages/core/src/api/parsers/html/util/nestedLists.test.ts
@@ -1,9 +1,17 @@
import { afterEach, describe, expect, it } from "vite-plus/test";
+import { detachedDoc } from "../../../../util/detachedDoc.js";
import { nestedListsToBlockNoteStructure } from "./nestedLists.js";
+// Makes the element for the HTML as `HTMLToBlocks` does, and runs the steps.
+function parse(html: string) {
+ const element = detachedDoc().createElement("div");
+ element.innerHTML = html;
+ nestedListsToBlockNoteStructure(element);
+ return element;
+}
+
async function testHTML(html: string) {
- const htmlNode = nestedListsToBlockNoteStructure(html);
- expect(htmlNode.innerHTML).toMatchSnapshot();
+ expect(parse(html).innerHTML).toMatchSnapshot();
}
describe("Lift nested lists", () => {
@@ -192,7 +200,7 @@ describe("content after a nested list", () => {
}
};
- const htmlNode = nestedListsToBlockNoteStructure(
+ const htmlNode = parse(
`
Item
Nested item
`,
);
diff --git a/packages/core/src/api/parsers/html/util/nestedLists.ts b/packages/core/src/api/parsers/html/util/nestedLists.ts
index 7b3f967c42..7e97c842cf 100644
--- a/packages/core/src/api/parsers/html/util/nestedLists.ts
+++ b/packages/core/src/api/parsers/html/util/nestedLists.ts
@@ -185,10 +185,11 @@ function createGroups(element: HTMLElement) {
});
}
-export function nestedListsToBlockNoteStructure(html: string) {
- const element = detachedDoc().createElement("div");
- element.innerHTML = html;
+/**
+ * Changes the lists in `element` with the two steps above. The element is the
+ * one that `HTMLToBlocks` makes in `detachedDoc()` for the HTML.
+ */
+export function nestedListsToBlockNoteStructure(element: HTMLElement) {
liftNestedListsToParent(element);
createGroups(element);
- return element;
}
diff --git a/packages/core/src/util/detachedDoc.test.ts b/packages/core/src/util/detachedDoc.test.ts
index 6a852b1e40..2bf76e03d6 100644
--- a/packages/core/src/util/detachedDoc.test.ts
+++ b/packages/core/src/util/detachedDoc.test.ts
@@ -1,6 +1,9 @@
import { DOMParser } from "prosemirror-model";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { HTMLToBlocks } from "../api/parsers/html/parseHTML.js";
+import { BlockNoteSchema } from "../blocks/BlockNoteSchema.js";
+import { defaultBlockSpecs } from "../blocks/defaultBlocks.js";
import { BlockNoteEditor } from "../editor/BlockNoteEditor.js";
describe("the parse rules with HTML that is in the active document", () => {
@@ -49,3 +52,51 @@ describe("the parse rules with HTML that is in the active document", () => {
]);
});
});
+
+describe("the parse of an HTML string", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // The string is from outside. In an element of the active document, its
+ // images load and its event handlers run before the parse reads them.
+ it("makes no element in the active document", () => {
+ const editor = BlockNoteEditor.create();
+ const createElement = vi.spyOn(document, "createElement");
+
+ const blocks = HTMLToBlocks(
+ `
Text more
` +
+ `
Item
Nested
`,
+ editor.pmSchema,
+ );
+
+ expect(createElement).not.toHaveBeenCalled();
+ expect(blocks.map((block) => block.type)).toEqual([
+ "paragraph",
+ "image",
+ "paragraph",
+ "bulletListItem",
+ ]);
+ });
+
+ // A schema without the image block drops an image in the parse. The text
+ // around the image must then stay one block.
+ it("does not split a paragraph at an image if the schema has no image block", () => {
+ const editor = BlockNoteEditor.create({
+ schema: BlockNoteSchema.create({
+ blockSpecs: { paragraph: defaultBlockSpecs.paragraph },
+ }),
+ });
+
+ const blocks = HTMLToBlocks(
+ `
We arrived at the harbor before dusk. The boats were in.
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // The parts of the paragraph keep its alignment and its colors.
+ {
+ testCase: {
+ name: "inlineImageInStyledParagraph",
+ content: `
Before and after
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image on its own line in a paragraph. The line breaks and the spaces
+ // next to the image have no meaning at the edge of a block: they are removed.
+ {
+ testCase: {
+ name: "lineBreakNextToInlineImage",
+ content: `
Some text More text
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // Paragraphs with and without an image, at the top and in a `
`. The
+ // blocks keep their order.
+ {
+ testCase: {
+ name: "inlineImagesBetweenParagraphs",
+ content: `
First second
+
No image here
+
+
Third fourth
+
No image here also
+
Fifth sixth
+
+
The end
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // Text with a style before the image: the text before the image keeps its
+ // order.
+ {
+ testCase: {
+ name: "inlineImageAfterStyledText",
+ content: `
Open the menu and look: Then close it.
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // A paragraph with an image and a video, and no text. No part has text, so
+ // there is no paragraph, but the video stays.
+ {
+ testCase: {
+ name: "imageAndVideoInParagraph",
+ content: `
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in the paragraph of a list item, as GitHub writes it (the image
+ // is in a link). The image and the text after it become children of the
+ // list item.
+ {
+ testCase: {
+ name: "inlineImageInListItemParagraph",
+ content: `
+
+
Open the menu and select a block
+
+
+
Close the menu
+
+
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in the paragraph of a list item that has a nested list. The
+ // image, the text after it and the nested list are children of the list
+ // item, in this order, and the numbered list continues.
+ {
+ testCase: {
+ name: "inlineImageInListItemParagraphWithNestedList",
+ content: `
+
+
Step one done
+
+
sub a
+
sub b
+
+
+
Step two
+
Step three
+`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in a quote, as a markdown renderer writes it. The quote splits
+ // around the image.
+ {
+ testCase: {
+ name: "inlineImageInQuote",
+ content: `
As the picture shows the result is good.
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in a heading (a logo next to a title). The heading splits around
+ // the image. There is no text before the image, so there is no heading
+ // before it.
+ {
+ testCase: {
+ name: "inlineImageInHeading",
+ content: `
Project
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image without a URL in a table cell: there is no link, and the cell
+ // does not get the alt text.
+ {
+ testCase: {
+ name: "imageWithoutUrlInTableCell",
+ content: `
+
+
Before after
+
+
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // A heading with an image and only a space after it, as Word writes it. A
+ // part with only white space is not a block: there is no empty heading.
+ {
+ testCase: {
+ name: "imageAndSpaceInHeading",
+ content: `
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // Each heading level splits around an image.
+ {
+ testCase: {
+ name: "inlineImageInHeadingLevels",
+ content: `
Level three
+
Level four
+
Level five
+
Level six
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in the summary of a toggle. The summary is the text of the
+ // toggle, and a toggle cannot split: the step does not change the summary.
+ // The image is dropped, and the words next to it stay apart.
+ {
+ testCase: {
+ name: "inlineImageInToggleSummary",
+ content: `
Step one
The details
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in the caption of a figure. The caption is text, and the step
+ // does not change it: the image is dropped, and the words next to it stay
+ // apart.
+ {
+ testCase: {
+ name: "inlineImageInFigureCaption",
+ content: `
The harbor at dusk
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // Images in table cells, as GitHub writes them (each image is in a link). A
+ // table cell cannot hold a block, so the image becomes a link with its alt
+ // text.
+ {
+ testCase: {
+ name: "inlineImageInTableCell",
+ content: `
+
+
+
Light
+
Dark
+
+
+
+
+
+
+
+
+
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in custom inline content (a mention with an avatar), as the HTML
+ // export of BlockNote writes it. The image is a part of the inline content:
+ // the paragraph does not split, and the table cell gets no link.
+ {
+ testCase: {
+ name: "imageInCustomInlineContent",
+ content: `
Ask @Matthew for help
+
+
+
Owner: @Matthew
+
+
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // The same in the full HTML of BlockNote. A block of the full HTML has one
+ // content element: a split would lose the text after the image.
+ {
+ testCase: {
+ name: "imageInCustomInlineContentFullHTML",
+ content: `
Ask @Matthew for help
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // An image in the content element of a block of the full HTML. BlockNote
+ // does not write this, but the text after the image must not be lost: the
+ // block does not split, and ProseMirror makes the image a child.
+ {
+ testCase: {
+ name: "inlineImageInFullHTMLBlock",
+ content: `
Before after
`,
+ },
+ executeTest: testParseHTML,
+ },
+ // Images in table cells with different URLs. A web URL becomes a link, with
+ // the alt text or the URL as its text, also in a header cell. A `file:` URL
+ // (a table from Word) and a `data:` URL cannot be a link: the image is
+ // dropped, and the cell does not get the URL as text.
+ {
+ testCase: {
+ name: "imageUrlsInTableCell",
+ content: `
+
+
+
The URL of the image
+
+
+
+
A web URL, with alt text
+
+
+
+
A web URL, without alt text
+
+
+
Before after
+
A file URL
+
+
+
+
A data URL
+
+
`,
+ },
+ executeTest: testParseHTML,
+ },
{
testCase: {
name: "fakeImageCaption",
@@ -2213,7 +2471,8 @@ Final paragraph with [a link](https://example.com).`,
},
executeTest: testParseMarkdown,
},
- // Inline image within text (should be handled)
+ // An image in the text of a paragraph. An image is a block, so the paragraph
+ // splits around the image.
{
testCase: {
name: "inlineImage",
@@ -2221,6 +2480,66 @@ Final paragraph with [a link](https://example.com).`,
},
executeTest: testParseMarkdown,
},
+ // An image on its own line in a paragraph. The line breaks next to the
+ // image are removed.
+ {
+ testCase: {
+ name: "lineBreakNextToInlineImage",
+ content: `Some text
+
+More text`,
+ },
+ executeTest: testParseMarkdown,
+ },
+ // An image in the text of a list item: the image and the text after it
+ // become children of the list item.
+ {
+ testCase: {
+ name: "inlineImageInListItem",
+ content: `- Item  text after`,
+ },
+ executeTest: testParseMarkdown,
+ },
+ // A nested list after an image in a list item. The image and the nested
+ // list are children of the list item, and the numbered list continues.
+ {
+ testCase: {
+ name: "inlineImageInListItemWithNestedList",
+ content: `1. Step one 
+ - sub a
+ - sub b
+2. Step two`,
+ },
+ executeTest: testParseMarkdown,
+ },
+ // An image in a quote: the quote splits around the image.
+ {
+ testCase: {
+ name: "inlineImageInQuote",
+ content: `> Quote  text after`,
+ },
+ executeTest: testParseMarkdown,
+ },
+ // An image in a heading: the heading splits around the image. Text before
+ // and after the image gives two headings.
+ {
+ testCase: {
+ name: "inlineImageInHeading",
+ content: `## Heading  text after`,
+ },
+ executeTest: testParseMarkdown,
+ },
+ // Images in table cells, with text and alone. A table cell cannot hold a
+ // block, so the image becomes a link with its alt text.
+ {
+ testCase: {
+ name: "inlineImageInTableCell",
+ content: `| Step | Result |
+| --- | --- |
+| Open the menu  |  |`,
+ },
+ executeTest: testParseMarkdown,
+ },
// Code block immediately after heading
{
testCase: {