diff --git a/docs/content/docs/features/custom-schemas/custom-blocks.mdx b/docs/content/docs/features/custom-schemas/custom-blocks.mdx index 6d2ab2917e..d3668943a4 100644 --- a/docs/content/docs/features/custom-schemas/custom-blocks.mdx +++ b/docs/content/docs/features/custom-schemas/custom-blocks.mdx @@ -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 `
` element. Without it, the child blocks follow the block. diff --git a/docs/content/docs/features/import/html.mdx b/docs/content/docs/features/import/html.mdx index 6fd6baf347..628c26bfec 100644 --- a/docs/content/docs/features/import/html.mdx +++ b/docs/content/docs/features/import/html.mdx @@ -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 `""` 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. diff --git a/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.browser.test.ts b/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.browser.test.ts new file mode 100644 index 0000000000..ffb605810e --- /dev/null +++ b/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.browser.test.ts @@ -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(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"]); + }); +}); diff --git a/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.ts b/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.ts index 2a016cefc9..b74d5477b2 100644 --- a/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.ts +++ b/packages/core/src/api/exporters/html/util/serializeBlocksExternalHTML.ts @@ -194,7 +194,8 @@ 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, @@ -202,11 +203,14 @@ function renderBlockOutput( editor: BlockNoteEditor, 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 }; } @@ -245,8 +249,9 @@ function serializeBlock< orderedListItemBlockTypes: Set, unorderedListItemBlockTypes: Set, nestingLevel: number, + canContinueList: boolean, options?: { document?: Document }, -) { +): boolean { const doc = options?.document ?? document; const BC_NODE = editor.pmSchema.nodes["blockContainer"]; @@ -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; @@ -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 ( @@ -454,6 +479,7 @@ function serializeBlock< ret.contentDOM.append(childFragment); } } + return true; } const serializeBlocksToFragment = < @@ -470,8 +496,9 @@ const serializeBlocksToFragment = < nestingLevel = 0, options?: { document?: Document }, ) => { + let canContinueList = false; for (const block of blocks) { - serializeBlock( + canContinueList = serializeBlock( fragment, editor, block, @@ -479,6 +506,7 @@ const serializeBlocksToFragment = < orderedListItemBlockTypes, unorderedListItemBlockTypes, nestingLevel, + canContinueList, options, ); } diff --git a/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts b/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts index 2b60d7afb7..e5622c8175 100644 --- a/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts +++ b/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts @@ -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", ); diff --git a/packages/core/src/api/parsers/html/parseHTML.ts b/packages/core/src/api/parsers/html/parseHTML.ts index eb302fc06c..d0276eec23 100644 --- a/packages/core/src/api/parsers/html/parseHTML.ts +++ b/packages/core/src/api/parsers/html/parseHTML.ts @@ -75,7 +75,11 @@ export function HTMLToBlocks< BSchema extends BlockSchema, I extends InlineContentSchema, S extends StyleSchema, ->(html: string, pmSchema: Schema): Block[] { +>( + html: string, + pmSchema: Schema, + { fillEmpty = false }: { fillEmpty?: boolean } = {}, +): Block[] { const htmlNode = detachedDoc().createElement("div"); htmlNode.innerHTML = html; // Lift images before list normalization so a nested list after an image @@ -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); diff --git a/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts b/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts index 2765919b15..7a8d7bfaf1 100644 --- a/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts +++ b/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts @@ -2,6 +2,14 @@ import { describe, expect } from "vite-plus/test"; import { markdownToHtml } from "./markdownToHtml.js"; describe("markdownToHtml", () => { + it.each([ + '', + '', + '', + ])("parses a heading immediately after a video: %j", (video) => { + expect(markdownToHtml(`${video}\n## Notes`)).toBe(`${video}

Notes

`); + }); + it("keeps an unmatched backtick run literal", () => { expect(markdownToHtml("``a`")).toBe("

``a`

"); }); diff --git a/packages/core/src/api/parsers/markdown/markdownToHtml.ts b/packages/core/src/api/parsers/markdown/markdownToHtml.ts index babe90c0e0..a599794681 100644 --- a/packages/core/src/api/parsers/markdown/markdownToHtml.ts +++ b/packages/core/src/api/parsers/markdown/markdownToHtml.ts @@ -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 `` 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. */ @@ -808,8 +809,12 @@ const HTML_BLOCK_TAGS = new Set([ "tr", "track", "ul", + "video", ]); +const VIDEO_OPEN_RE = /^ {0,3}|$)/i; +const VIDEO_CLOSE_RE = /<\/video\s*>/i; + function isHtmlBlockStart(line: string): boolean { // `, ``, ``, or ``. - // 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 ). 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; } diff --git a/packages/core/src/api/parsers/markdown/parseMarkdown.ts b/packages/core/src/api/parsers/markdown/parseMarkdown.ts index e1741e214e..b87f60caa4 100644 --- a/packages/core/src/api/parsers/markdown/parseMarkdown.ts +++ b/packages/core/src/api/parsers/markdown/parseMarkdown.ts @@ -20,5 +20,5 @@ export function markdownToBlocks< >(markdown: string, pmSchema: Schema): Block[] { const htmlString = markdownToHTML(markdown); - return HTMLToBlocks(htmlString, pmSchema); + return HTMLToBlocks(htmlString, pmSchema, { fillEmpty: true }); } diff --git a/packages/core/src/blocks/Audio/block.ts b/packages/core/src/blocks/Audio/block.ts index d4bc264027..3b956670f7 100644 --- a/packages/core/src/blocks/Audio/block.ts +++ b/packages/core/src/blocks/Audio/block.ts @@ -5,11 +5,10 @@ import { createBlockSpec, } from "../../schema/index.js"; import { defaultProps, parseDefaultProps } from "../defaultProps.js"; -import { parseFigureElement } from "../File/helpers/parse/parseFigureElement.js"; +import { parseMediaElement } from "../File/helpers/parse/parseMediaElement.js"; import { createFileBlockWrapper } from "../File/helpers/render/createFileBlockWrapper.js"; import { createFigureWithCaption } from "../File/helpers/toExternalHTML/createFigureWithCaption.js"; import { createLinkWithCaption } from "../File/helpers/toExternalHTML/createLinkWithCaption.js"; -import { parseAudioElement } from "./parseAudioElement.js"; export const FILE_AUDIO_ICON_SVG = ''; @@ -50,38 +49,13 @@ export const createAudioBlockConfig = createBlockConfig( export const audioParse = (_config: AudioOptions = {}) => (element: HTMLElement) => { - if (element.tagName === "AUDIO") { - // Ignore if parent figure has already been parsed. - if (element.closest("figure")) { - return undefined; - } - - const { backgroundColor } = parseDefaultProps(element); - - return { - ...parseAudioElement(element as HTMLAudioElement), - backgroundColor, - }; - } - - if (element.tagName === "FIGURE") { - const parsedFigure = parseFigureElement(element, "audio"); - if (!parsedFigure) { - return undefined; - } - - const { targetElement, caption } = parsedFigure; - - const { backgroundColor } = parseDefaultProps(element); - - return { - ...parseAudioElement(targetElement as HTMLAudioElement), - backgroundColor, - caption, - }; + const parsed = parseMediaElement(element, "audio"); + if (!parsed) { + return undefined; } - return undefined; + const { backgroundColor } = parseDefaultProps(element); + return { url: parsed.url, caption: parsed.caption, backgroundColor }; }; export const audioRender = @@ -128,10 +102,9 @@ export const audioToExternalHTML = any >, ) => { - if (!block.props.url) { - return { - dom: document.createElement("audio"), - }; + // The upload placeholder (no URL) is not in the export. + if (!block.props.url?.trim()) { + return null; } let audio; diff --git a/packages/core/src/blocks/File/block.ts b/packages/core/src/blocks/File/block.ts index a3d609add9..00e95c59cc 100644 --- a/packages/core/src/blocks/File/block.ts +++ b/packages/core/src/blocks/File/block.ts @@ -1,8 +1,7 @@ import { createBlockConfig, createBlockSpec } from "../../schema/index.js"; import { defaultProps, parseDefaultProps } from "../defaultProps.js"; -import { parseEmbedElement } from "./helpers/parse/parseEmbedElement.js"; -import { parseFigureElement } from "./helpers/parse/parseFigureElement.js"; import { parseLinkFigure } from "./helpers/parse/parseLinkFigure.js"; +import { parseMediaElement } from "./helpers/parse/parseMediaElement.js"; import { createFileBlockWrapper } from "./helpers/render/createFileBlockWrapper.js"; import { createLinkWithCaption } from "./helpers/toExternalHTML/createLinkWithCaption.js"; @@ -32,45 +31,21 @@ export const createFileBlockConfig = createBlockConfig( ); export const fileParse = () => (element: HTMLElement) => { - if (element.tagName === "EMBED") { - // Ignore if parent figure has already been parsed. - if (element.closest("figure")) { - return undefined; - } - - const { backgroundColor } = parseDefaultProps(element); - - return { - ...parseEmbedElement(element as HTMLEmbedElement), - backgroundColor, - }; - } - if (element.tagName === "FIGURE") { const linkFigure = parseLinkFigure(element); if (linkFigure) { const { backgroundColor } = parseDefaultProps(element); - return { ...linkFigure, backgroundColor }; } + } - const parsedFigure = parseFigureElement(element, "embed"); - if (!parsedFigure) { - return undefined; - } - - const { targetElement, caption } = parsedFigure; - - const { backgroundColor } = parseDefaultProps(element); - - return { - ...parseEmbedElement(targetElement as HTMLEmbedElement), - backgroundColor, - caption, - }; + const parsed = parseMediaElement(element, "embed"); + if (!parsed) { + return undefined; } - return undefined; + const { backgroundColor } = parseDefaultProps(element); + return { url: parsed.url, caption: parsed.caption, backgroundColor }; }; export const createFileBlockSpec = createBlockSpec(createFileBlockConfig, { @@ -82,10 +57,9 @@ export const createFileBlockSpec = createBlockSpec(createFileBlockConfig, { return createFileBlockWrapper(block, editor); }, toExternalHTML(block) { - if (!block.props.url) { - return { - dom: document.createElement("embed"), - }; + // The upload placeholder (no URL) is not in the export. + if (!block.props.url?.trim()) { + return null; } const fileSrcLink = document.createElement("a"); diff --git a/packages/core/src/blocks/File/helpers/parse/parseEmbedElement.ts b/packages/core/src/blocks/File/helpers/parse/parseEmbedElement.ts deleted file mode 100644 index b7a62f5789..0000000000 --- a/packages/core/src/blocks/File/helpers/parse/parseEmbedElement.ts +++ /dev/null @@ -1,5 +0,0 @@ -export const parseEmbedElement = (embedElement: HTMLEmbedElement) => { - const url = embedElement.src || undefined; - - return { url }; -}; diff --git a/packages/core/src/blocks/File/helpers/parse/parseFigureElement.ts b/packages/core/src/blocks/File/helpers/parse/parseFigureElement.ts index 4da64002c9..6d723a8d3b 100644 --- a/packages/core/src/blocks/File/helpers/parse/parseFigureElement.ts +++ b/packages/core/src/blocks/File/helpers/parse/parseFigureElement.ts @@ -1,10 +1,8 @@ -export const parseFigureElement = ( +export function parseFigureElement( figureElement: HTMLElement, - targetTag: string, -) => { - const targetElement = figureElement.querySelector( - targetTag, - ) as HTMLElement | null; + targetTag: Tag, +) { + const targetElement = figureElement.querySelector(targetTag); if (!targetElement) { return undefined; } @@ -13,4 +11,4 @@ export const parseFigureElement = ( const caption = captionElement?.textContent ?? undefined; return { targetElement, caption }; -}; +} diff --git a/packages/core/src/blocks/File/helpers/parse/parseMediaElement.ts b/packages/core/src/blocks/File/helpers/parse/parseMediaElement.ts new file mode 100644 index 0000000000..0d470add4c --- /dev/null +++ b/packages/core/src/blocks/File/helpers/parse/parseMediaElement.ts @@ -0,0 +1,28 @@ +import { parseFigureElement } from "./parseFigureElement.js"; +import { parseMediaUrl } from "./parseMediaUrl.js"; + +export function parseMediaElement< + Tag extends "img" | "video" | "audio" | "embed", +>(element: HTMLElement, tag: Tag) { + const figure = element.localName === "figure" ? element : undefined; + const parsedFigure = figure && parseFigureElement(figure, tag); + let media: HTMLElementTagNameMap[Tag] | null; + if (figure) { + media = parsedFigure?.targetElement ?? null; + } else if (element.localName === tag && !element.closest("figure")) { + media = element as HTMLElementTagNameMap[Tag]; + } else { + return undefined; + } + + if (!media) { + return undefined; + } + + const url = parseMediaUrl(media, figure); + if (!url) { + return undefined; + } + + return { media, url, caption: parsedFigure?.caption }; +} diff --git a/packages/core/src/blocks/File/helpers/parse/parseMediaUrl.ts b/packages/core/src/blocks/File/helpers/parse/parseMediaUrl.ts new file mode 100644 index 0000000000..4c2b0fa106 --- /dev/null +++ b/packages/core/src/blocks/File/helpers/parse/parseMediaUrl.ts @@ -0,0 +1,43 @@ +/** + * Gives the URL of a media element (``, `