Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
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", () => {
// 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({
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({
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 @@ -286,6 +290,25 @@ 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);
return;
}

const elementFragment = doc.createDocumentFragment();

let rootElement: HTMLElement | undefined;
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/api/parsers/markdown/markdownToHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,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 @@ -786,6 +787,7 @@ const HTML_BLOCK_TAGS = new Set([
"tr",
"track",
"ul",
"video",
]);

function isHtmlBlockStart(line: string): boolean {
Expand Down
20 changes: 15 additions & 5 deletions packages/core/src/blocks/Audio/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,16 @@ export const audioParse =
return undefined;
}

// An audio without a URL gives no block.
const audio = parseAudioElement(element as HTMLAudioElement);
if (!audio.url) {
return undefined;
}

const { backgroundColor } = parseDefaultProps(element);

return {
...parseAudioElement(element as HTMLAudioElement),
...audio,
backgroundColor,
};
}
Expand All @@ -72,10 +78,15 @@ export const audioParse =

const { targetElement, caption } = parsedFigure;

const audio = parseAudioElement(targetElement as HTMLAudioElement);
if (!audio.url) {
return undefined;
}

const { backgroundColor } = parseDefaultProps(element);

return {
...parseAudioElement(targetElement as HTMLAudioElement),
...audio,
backgroundColor,
caption,
};
Expand Down Expand Up @@ -128,10 +139,9 @@ export const audioToExternalHTML =
any
>,
) => {
// The upload placeholder (no URL) is not in the export.
if (!block.props.url) {
return {
dom: document.createElement("audio"),
};
return null;
}

let audio;
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/blocks/Audio/parseAudioElement.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { parseMediaUrl } from "../File/helpers/parse/parseMediaUrl.js";

export const parseAudioElement = (audioElement: HTMLAudioElement) => {
const url = audioElement.src || undefined;
const url = parseMediaUrl(audioElement);

return { url };
};
20 changes: 15 additions & 5 deletions packages/core/src/blocks/File/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,16 @@ export const fileParse = () => (element: HTMLElement) => {
return undefined;
}

// A file without a URL gives no block.
const embed = parseEmbedElement(element as HTMLEmbedElement);
if (!embed.url) {
return undefined;
}

const { backgroundColor } = parseDefaultProps(element);

return {
...parseEmbedElement(element as HTMLEmbedElement),
...embed,
backgroundColor,
};
}
Expand All @@ -53,10 +59,15 @@ export const fileParse = () => (element: HTMLElement) => {

const { targetElement, caption } = parsedFigure;

const embed = parseEmbedElement(targetElement as HTMLEmbedElement);
if (!embed.url) {
return undefined;
}

const { backgroundColor } = parseDefaultProps(element);

return {
...parseEmbedElement(targetElement as HTMLEmbedElement),
...embed,
backgroundColor,
caption,
};
Expand All @@ -74,10 +85,9 @@ export const createFileBlockSpec = createBlockSpec(createFileBlockConfig, {
return createFileBlockWrapper(block, editor);
},
toExternalHTML(block) {
// The upload placeholder (no URL) is not in the export.
if (!block.props.url) {
return {
dom: document.createElement("embed"),
};
return null;
}

const fileSrcLink = document.createElement("a");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { parseMediaUrl } from "./parseMediaUrl.js";

export const parseEmbedElement = (embedElement: HTMLEmbedElement) => {
const url = embedElement.src || undefined;
const url = parseMediaUrl(embedElement);

return { url };
};
33 changes: 33 additions & 0 deletions packages/core/src/blocks/File/helpers/parse/parseMediaUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Gives the URL of a media element (`<img>`, `<video>`, `<audio>` or
* `<embed>`), or `undefined` if it has none. The parse gives no block for a
* media element without a URL.
*/
export function parseMediaUrl(
element:
| HTMLImageElement
| HTMLVideoElement
| HTMLAudioElement
| HTMLEmbedElement,
): string | undefined {
// BlockNote's own HTML has the URL in `data-url`, on the figure of the
// element or on the element. The generic parse of the props reads that
// attribute after the parse of the block, so it has priority here too.
const dataUrl =
element.closest("figure")?.getAttribute("data-url") ??
element.getAttribute("data-url");
if (dataUrl !== null) {
return dataUrl.trim() ? dataUrl : undefined;
}

// A `<video>` or an `<audio>` can have its URL in a `<source>` child.
for (const source of [element, ...element.querySelectorAll("source")]) {
// The attribute tells if there is a URL: in the active document, the
// `src` property of an empty `src` attribute is the URL of the page.
if (source.getAttribute("src")?.trim()) {
return source.src;
}
}

return undefined;
}
20 changes: 15 additions & 5 deletions packages/core/src/blocks/Image/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,16 @@ export const imageParse =
return undefined;
}

// An image without a URL gives no block.
const image = parseImageElement(element as HTMLImageElement);
if (!image.url) {
return undefined;
}

const { backgroundColor } = parseDefaultProps(element);

return {
...parseImageElement(element as HTMLImageElement),
...image,
backgroundColor,
};
}
Expand All @@ -78,10 +84,15 @@ export const imageParse =

const { targetElement, caption } = parsedFigure;

const image = parseImageElement(targetElement as HTMLImageElement);
if (!image.url) {
return undefined;
}

const { backgroundColor } = parseDefaultProps(element);

return {
...parseImageElement(targetElement as HTMLImageElement),
...image,
backgroundColor,
caption,
};
Expand Down Expand Up @@ -146,10 +157,9 @@ export const imageToExternalHTML =
any
>,
) => {
// The upload placeholder (no URL) is not in the export.
if (!block.props.url) {
return {
dom: document.createElement("img"),
};
return null;
}

let image;
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/blocks/Image/parseImageElement.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { parseMediaUrl } from "../File/helpers/parse/parseMediaUrl.js";

export const parseImageElement = (imageElement: HTMLImageElement) => {
const url = imageElement.src || undefined;
const url = parseMediaUrl(imageElement);
const previewWidth = imageElement.width || undefined;
const name = imageElement.alt || undefined;

Expand Down
Loading
Loading