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
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ type ReactCustomBlockImplementation = {

`renderFrame?:` A component that draws a frame around the block's content and its child blocks. See [Block Frames](#block-frames).

`toExternalHTML?:` This component is used whenever the block is being exported to HTML for use outside BlockNote, for example when copying it to the clipboard. If it's not defined, BlockNote will just use `render` (and `renderFrame`, if the block has one) for the HTML conversion. Takes the same props as `render`, and two more:
`toExternalHTML?:` This component is used whenever the block is being exported to HTML for use outside BlockNote, for example when copying it to the clipboard. If it's not defined, BlockNote will just use `render` (and `renderFrame`, if the block has one) for the HTML conversion. If the component renders nothing (`null`), the block is left out of the exported HTML. A [layout block](/docs/features/custom-schemas/layout-blocks) is an exception: it is not left out, and exports as an empty element. Takes the same props as `render`, and two more:

- `childrenRef:` A React `ref` that marks where the block's child blocks go, for example inside a `<details>` element. Without it, the child blocks follow the block.

Expand Down
2 changes: 1 addition & 1 deletion docs/content/docs/features/import/html.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ tryParseHTMLToBlocks(html: string): Block[];
const blocksFromHTML = editor.tryParseHTMLToBlocks(html);
```

`returns:` The blocks parsed from the HTML string.
`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 `[]`.

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.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { describe, expect } from "vite-plus/test";

import { BlockNoteSchema } from "../../../../blocks/BlockNoteSchema.js";
import { defaultBlockSpecs } from "../../../../blocks/defaultBlocks.js";
import { createBlockSpec } from "../../../../schema/index.js";

// A block that leaves itself out of the external HTML.
function createOmittedBlock<const Type extends string>(type: Type) {
return createBlockSpec(
{ type, propSchema: {}, content: "none" },
{
render: () => ({ dom: document.createElement("div") }),
toExternalHTML: () => null,
},
)();
}

function parseHTML(html: string) {
const dom = document.createElement("div");
dom.innerHTML = html;
return dom;
}

describe("a block that exports as nothing", () => {
it("keeps the ordered list restart after an omitted image in HTML and Markdown", async ({
setupEditor,
}) => {
const { editor } = await setupEditor({ mountType: false });
const blocks = [
{ type: "numberedListItem", content: "A" },
{ type: "image" },
{ type: "numberedListItem", content: "B", props: { start: 10 } },
{ type: "numberedListItem", content: "C" },
] as const;
const dom = parseHTML(editor.blocksToHTMLLossy([...blocks]));

expect(
Array.from(dom.children, (list) => [
list.tagName,
list.getAttribute("start"),
list.textContent,
]),
).toEqual([
["OL", null, "A"],
["OL", "10", "BC"],
]);

const markdown = editor.blocksToMarkdownLossy([...blocks]);
expect(editor.tryParseMarkdownToBlocks(markdown)).toMatchObject([
{ type: "numberedListItem", content: [{ text: "A" }] },
{
type: "numberedListItem",
props: { start: 10 },
content: [{ text: "B" }],
},
{ type: "numberedListItem", content: [{ text: "C" }] },
]);
});

// The serializer puts a child list of a list item into the item before it.
// The item before a block that is left out is not the item of that block.
it("keeps its child list out of the list item before it", async ({
setupEditor,
}) => {
const { editor } = await setupEditor({
mountType: false,
schema: BlockNoteSchema.create({
blockSpecs: {
...defaultBlockSpecs,
omitted: createOmittedBlock("omitted"),
},
}),
});

const dom = parseHTML(
editor.blocksToHTMLLossy([
{ type: "bulletListItem", content: "A" },
{
type: "omitted",
children: [{ type: "bulletListItem", content: "B" }],
},
]),
);

expect(
Array.from(dom.querySelectorAll("li"), (item) => item.textContent),
).toEqual(["A", "B"]);
expect(dom.querySelector("li li")).toBeNull();
});

// A list item type that is left out made an empty list, and the child list
// had no item to go into.
it("is not an item of a list, and its child list follows", async ({
setupEditor,
}) => {
const { editor } = await setupEditor({
mountType: false,
schema: BlockNoteSchema.create({
blockSpecs: {
...defaultBlockSpecs,
bulletListItem: createOmittedBlock("bulletListItem"),
},
}),
});

const dom = parseHTML(
editor.blocksToHTMLLossy([
{
type: "bulletListItem",
children: [{ type: "numberedListItem", content: "B" }],
},
]),
);

expect(dom.querySelector("ul")).toBeNull();
expect(
Array.from(dom.querySelectorAll("ol > li"), (item) => item.textContent),
).toEqual(["B"]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -194,19 +194,23 @@ type BlockOutput = {
* block's own `toExternalHTML` replaces the default export, frame included.
* By default, a layout block is its frame, with the children in the slot, and
* any other block is `render`'s output, which the caller puts into the
* block's frame (if it draws one).
* block's frame (if it draws one). The output is `null` if the block's
* `toExternalHTML` leaves the block out of the export.
*/
function renderBlockOutput(
blockImplementation: BlockImplementation,
block: any,
editor: BlockNoteEditor<any, any, any>,
isLayoutBlock: boolean,
nestingLevel: number,
): { output: BlockOutput; frame?: { dom: HTMLElement; slot: HTMLElement } } {
): {
output: BlockOutput | null;
frame?: { dom: HTMLElement; slot: HTMLElement };
} {
const external = blockImplementation.toExternalHTML?.call({}, block, editor, {
nestingLevel,
});
if (external) {
if (external !== undefined) {
return { output: external };
}

Expand Down Expand Up @@ -245,8 +249,9 @@ function serializeBlock<
orderedListItemBlockTypes: Set<string>,
unorderedListItemBlockTypes: Set<string>,
nestingLevel: number,
canContinueList: boolean,
options?: { document?: Document },
) {
): boolean {
const doc = options?.document ?? document;
const BC_NODE = editor.pmSchema.nodes["blockContainer"];

Expand Down Expand Up @@ -286,6 +291,26 @@ function serializeBlock<
nestingLevel,
);

if (ret === null) {
// The block leaves itself out of the export. It adds no element and it is
// not an item of a list, so its children go to this place in the output,
// and not into a list item before it.
const childFragment = doc.createDocumentFragment();
serializeBlocksToFragment(
childFragment,
editor,
blockWithDefaults.children,
serializer,
orderedListItemBlockTypes,
unorderedListItemBlockTypes,
nestingLevel + 1,
options,
);
fragment.append(childFragment);
// The block still separates the list runs on either side of it.
return false;
}

const elementFragment = doc.createDocumentFragment();

let rootElement: HTMLElement | undefined;
Expand Down Expand Up @@ -391,7 +416,7 @@ function serializeBlock<
}

if (listType) {
if (fragment.lastChild?.nodeName !== listType) {
if (!canContinueList || fragment.lastChild?.nodeName !== listType) {
const list = doc.createElement(listType);

if (
Expand Down Expand Up @@ -454,6 +479,7 @@ function serializeBlock<
ret.contentDOM.append(childFragment);
}
}
return true;
}

const serializeBlocksToFragment = <
Expand All @@ -470,15 +496,17 @@ const serializeBlocksToFragment = <
nestingLevel = 0,
options?: { document?: Document },
) => {
let canContinueList = false;
for (const block of blocks) {
serializeBlock(
canContinueList = serializeBlock(
fragment,
editor,
block,
serializer,
orderedListItemBlockTypes,
unorderedListItemBlockTypes,
nestingLevel,
canContinueList,
options,
);
}
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/api/exporters/markdown/htmlToMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,10 @@ function serializeUnorderedList(

function serializeOrderedList(el: HTMLElement, ctx: SerializeContext): string {
let result = "";
if (el.previousElementSibling?.tagName.toLowerCase() === "ol") {
// A blank line alone would join these lists and lose the second start.
result = (ctx.inListItem ? "\n" : "") + ctx.indent + "<!-- -->\n\n";
}
const items = Array.from(el.children).filter(
(child) => child.tagName.toLowerCase() === "li",
);
Expand Down
15 changes: 13 additions & 2 deletions packages/core/src/api/parsers/html/parseHTML.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ export function HTMLToBlocks<
BSchema extends BlockSchema,
I extends InlineContentSchema,
S extends StyleSchema,
>(html: string, pmSchema: Schema): Block<BSchema, I, S>[] {
>(
html: string,
pmSchema: Schema,
{ fillEmpty = false }: { fillEmpty?: boolean } = {},
): Block<BSchema, I, S>[] {
const htmlNode = detachedDoc().createElement("div");
htmlNode.innerHTML = html;
// Lift images before list normalization so a nested list after an image
Expand All @@ -91,8 +95,15 @@ export function HTMLToBlocks<
// const doc = pmSchema.nodes["doc"].createAndFill()!;
// and context: doc.resolve(3),

const blockGroup = pmSchema.nodes["blockGroup"];
const parsedNode = parser.parse(htmlNode, {
topNode: pmSchema.nodes["blockGroup"].create(),
topNode: blockGroup.create(),
// After the first `blockGroupChild`, the group allows zero or more
// children instead of one or more. Use that match for an HTML fragment.
topMatch: fillEmpty
? undefined
: (blockGroup.contentMatch.matchType(pmSchema.nodes["blockContainer"]) ??
undefined),
});
const parentNode = normalizeImportedTables(parsedNode);

Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/api/parsers/markdown/markdownToHtml.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import { describe, expect } from "vite-plus/test";
import { markdownToHtml } from "./markdownToHtml.js";

describe("markdownToHtml", () => {
it.each([
'<video src="clip.mp4"></video>',
'<video controls>\n <source src="clip.mp4">\n</video>',
'<video controls>\n\n <source src="clip.mp4">\n</VIDEO>',
])("parses a heading immediately after a video: %j", (video) => {
expect(markdownToHtml(`${video}\n## Notes`)).toBe(`${video}<h2>Notes</h2>`);
});

it("keeps an unmatched backtick run literal", () => {
expect(markdownToHtml("``a`")).toBe("<p>``a`</p>");
});
Expand Down
36 changes: 29 additions & 7 deletions packages/core/src/api/parsers/markdown/markdownToHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,8 @@ type Token =
/**
* HTML block-level tag names (from the CommonMark type-6 list, plus `audio`
* which BlockNote serializes as raw HTML since markdown has no shorthand
* for it). When a line starts with `<` followed by one of these tag names,
* for it, and `video`, so that its `<source>` lines stay in the element).
* When a line starts with `<` followed by one of these tag names,
* the run of non-blank lines is emitted verbatim as raw HTML rather than
* wrapped in a paragraph.
*/
Expand Down Expand Up @@ -808,8 +809,12 @@ const HTML_BLOCK_TAGS = new Set([
"tr",
"track",
"ul",
"video",
]);

const VIDEO_OPEN_RE = /^ {0,3}<video(?=\s|\/?>|$)/i;
const VIDEO_CLOSE_RE = /<\/video\s*>/i;

function isHtmlBlockStart(line: string): boolean {
// <!-- ..., <?..., <![CDATA[..., <!DOCTYPE, etc.
if (/^ {0,3}<(!--|\?|![A-Za-z]|!\[CDATA\[)/.test(line)) {
Expand Down Expand Up @@ -1189,17 +1194,34 @@ function tokenize(markdown: string): Token[] {

// Block-level raw HTML: a line starting with `<tag>` (block-level tag),
// `<!-- ... -->`, `<?...?>`, `<!DOCTYPE ...>`, or `<![CDATA[...]]>`.
// Lines are emitted verbatim until the next blank line.
// Lines are emitted verbatim until the next blank line, or through the
// closing tag for a complete video element (which can contain <source>).
if (isHtmlBlockStart(line)) {
const htmlLines: string[] = [];
while (i < lines.length && lines[i].trim() !== "") {
htmlLines.push(lines[i]);
i++;
let end = i;
if (VIDEO_OPEN_RE.test(line)) {
// Stop looking at a new video so an unclosed tag can't swallow it.
let closingLine = i;
while (
!VIDEO_CLOSE_RE.test(lines[closingLine]) &&
closingLine + 1 < lines.length &&
!VIDEO_OPEN_RE.test(lines[closingLine + 1])
) {
closingLine++;
}
if (VIDEO_CLOSE_RE.test(lines[closingLine])) {
end = closingLine + 1;
}
}
if (end === i) {
while (end < lines.length && lines[end].trim() !== "") {
end++;
}
}
tokens.push({
type: "rawHtml",
content: htmlLines.join("\n"),
content: lines.slice(i, end).join("\n"),
});
i = end;
prevLineWasBlank = false;
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/api/parsers/markdown/parseMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ export function markdownToBlocks<
>(markdown: string, pmSchema: Schema): Block<BSchema, I, S>[] {
const htmlString = markdownToHTML(markdown);

return HTMLToBlocks(htmlString, pmSchema);
return HTMLToBlocks(htmlString, pmSchema, { fillEmpty: true });
}
Loading
Loading