Skip to content
Open
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
24 changes: 24 additions & 0 deletions docs/content/docs/features/custom-schemas/custom-blocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ type ReactCustomBlockImplementation = {
childrenRef: (node: HTMLElement | null) => void;
context: { nestingLevel: number };
}>;
postProcessHTML?(context: HTMLExportContext): undefined;
parse?: (element: HTMLElement) => PartialBlock["props"] | undefined;
parseContent?: (options: {
el: HTMLElement;
Expand Down Expand Up @@ -201,6 +202,8 @@ type ReactCustomBlockImplementation = {
on React Contexts._
</Callout>

`postProcessHTML?:` A synchronous DOM callback for changes that need the assembled document, rather than one block's render output. It is available on both `createBlockSpec` and `createReactBlockSpec`. See [Post-processing Exported HTML](#post-processing-exported-html).

`parse?:` The `parse` function defines how to parse HTML content into your block, for example when pasting contents from the clipboard. If the element should be parsed into your custom block, you return the props that the block should be given. Otherwise, return `undefined`. Takes a single argument:

- `element`: The HTML element that's being parsed.
Expand Down Expand Up @@ -398,3 +401,24 @@ When the user moves the alert, its title and its body move together.
set. See [Layout Blocks and Block
Frames](/docs/features/custom-schemas/layout-blocks#layout-blocks-and-block-frames)._
</Callout>

## Post-processing Exported HTML

Add `postProcessHTML` alongside `render` or `toExternalHTML` to adjust a block's HTML after the whole document has been rendered. This is useful when the result depends on other blocks, such as numbering list items.

The callback runs once for each block type present in the export, for both `blocksToFullHTML` and `blocksToHTMLLossy`. It receives:

- `root`: the whole exported document's DOM, which you can search with `querySelectorAll`.
- `blockOutputs`: a map from blocks of this type to their rendered output. Use `elements` to access their HTML elements, or `nodes` to include text and comments too.

```ts
postProcessHTML({ blockOutputs }) {
for (const { elements } of blockOutputs.values()) {
for (const element of elements) {
element.setAttribute("data-exported", "true");
}
}
}
```

Keep the callback synchronous and only change the exported DOM, not block data or editor state. For relationships between blocks, use DOM siblings and parents rather than map order. Since the two export methods can produce different HTML, only change elements that match the structure you need.
161 changes: 6 additions & 155 deletions packages/core/src/api/exporters/html/internalHTMLSerializer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { DOMSerializer, Schema } from "prosemirror-model";

import { PartialBlock } from "../../../blocks/defaultBlocks.js";
import { EMPTY_CELL_WIDTH } from "../../../blocks/index.js";
import type { BlockNoteEditor } from "../../../editor/BlockNoteEditor.js";
import {
BlockSchema,
Expand All @@ -10,131 +9,9 @@ import {
} from "../../../schema/index.js";
import { serializeBlocksInternalHTML } from "./util/serializeBlocksInternalHTML.js";

// This is normally handled using decorations in the
// `NumberedListIndexingDecorationPlugin`. This does not run when exporting, so
// we have to add the necessary HTML attributes ourselves.
const addIndexToNumberedListItems = (element: HTMLElement) => {
const numberedListItems = element.querySelectorAll(
'[data-content-type="numberedListItem"]',
);
numberedListItems.forEach((numberedListItem) => {
const prevNumberedListItem = numberedListItem
.closest(".bn-block-outer")
?.previousElementSibling?.querySelector(
'[data-content-type="numberedListItem"]',
);

if (!prevNumberedListItem) {
numberedListItem.setAttribute(
"data-index",
numberedListItem.getAttribute("data-start") || "1",
);
} else {
const prevNumberedListItemIndex =
prevNumberedListItem.getAttribute("data-index");
numberedListItem.setAttribute(
"data-index",
(parseInt(prevNumberedListItemIndex || "0") + 1).toString(),
);
}
});

return element;
};

// Makes the checkboxes in check list items read-only, as the HTML should be
// static and therefore read-only when rendered.
const makeCheckListItemsReadOnly = (element: HTMLElement) => {
const checkboxes: NodeListOf<HTMLInputElement> = element.querySelectorAll(
'[data-content-type="checkListItem"] input',
);
checkboxes.forEach((checkbox) => {
checkbox.disabled = true;
});

return element;
};

// Forces toggle blocks (toggle headings, toggle list items) to be expanded.
// This is because event listeners for the toggle button are lost when
// serializing HTML elements to a string, so the button no longer works if the
// HTML string is rendered out.
const forceToggleBlocksShow = (element: HTMLElement) => {
const closedToggleButtons = element.querySelectorAll(
'.bn-toggle-button[aria-expanded="false"]',
);
closedToggleButtons.forEach((toggleButton) => {
toggleButton.setAttribute("aria-expanded", "true");
});

return element;
};

// Adds minimum cell widths, which would normally be done by the
// `columnResizing` extension. This extension doesn't run when exporting to
// HTML, so we have to add this manually.
const addTableMinCellWidths = (element: HTMLElement) => {
const tables = element.querySelectorAll('[data-content-type="table"] table');
tables.forEach((table) => {
table.setAttribute(
"style",
`--default-cell-min-width: ${EMPTY_CELL_WIDTH}px;`,
);
table.setAttribute("data-show-children", "true");
});

return element;
};

// Adds table wrapping elements, which would normally be done by the
// `columnResizing` extension. This extension doesn't run when exporting to
// HTML, so we have to add this manually. This adds the correct padding to
// tables.
const addTableWrappers = (element: HTMLElement) => {
const tables = element.querySelectorAll('[data-content-type="table"] table');
tables.forEach((table) => {
const tableWrapper = document.createElement("div");
tableWrapper.className = "tableWrapper";
const tableWrapperInner = document.createElement("div");
tableWrapperInner.className = "tableWrapper-inner";

tableWrapper.appendChild(tableWrapperInner);
table.parentElement?.appendChild(tableWrapper);
tableWrapper.appendChild(table);
});

return element;
};

// Adds trailing breaks to blocks with empty inline content. This is normally
// done by ProseMirror, but only when rendering an actual editor. Without them,
// empty inline content has a height of 0.
const addTrailingBreakToEmptyInlineContent = (element: HTMLElement) => {
const emptyInlineContent = element.querySelectorAll(
".bn-inline-content:empty",
);
emptyInlineContent.forEach((inlineContent) => {
// We actually use a `span` instead of a `br` to avoid potential false
// positives when parsing.
const trailingBreak = document.createElement("span");
trailingBreak.className = "ProseMirror-trailingBreak";
trailingBreak.setAttribute("style", "display: inline-block;");

inlineContent.appendChild(trailingBreak);
});

return element;
};

// Used to serialize BlockNote blocks and ProseMirror nodes to HTML without
// losing data. Blocks are exported using the `toInternalHTML` method in their
// `blockSpec`.
//
// The HTML created by this serializer is the same as what's rendered by the
// editor to the DOM. This means that it retains the same structure as the
// editor, including the `blockGroup` and `blockContainer` wrappers. This also
// means that it can be converted back to the original blocks without any data
// loss.
// Serializes to the editor's HTML structure, retaining blockGroup and
// blockContainer wrappers so the document can be parsed back without data loss.
// Block-owned post-processing is part of the shared serialization pipeline.
export const createInternalHTMLSerializer = <
BSchema extends BlockSchema,
I extends InlineContentSchema,
Expand All @@ -145,38 +22,12 @@ export const createInternalHTMLSerializer = <
) => {
const serializer = DOMSerializer.fromSchema(schema);

// Set of transforms to run on the output HTML element after serializing
// blocks. These are used to add HTML elements, attributes, or class names
// which would normally be done by extensions and plugins. Since these don't
// run when converting blocks to HTML, tranforms are used to mock their
// functionality so that the rendered HTML looks identical to that of a live
// editor.
const transforms: ((element: HTMLElement) => HTMLElement)[] = [
addIndexToNumberedListItems,
makeCheckListItemsReadOnly,
forceToggleBlocksShow,
addTableMinCellWidths,
addTableWrappers,
addTrailingBreakToEmptyInlineContent,
];

return {
serializeBlocks: (
blocks: PartialBlock<BSchema, I, S>[],
options: { document?: Document },
) => {
let element = serializeBlocksInternalHTML(
editor,
blocks,
serializer,
options,
);

for (const transform of transforms) {
element = transform(element);
}

return element.outerHTML;
},
) =>
serializeBlocksInternalHTML(editor, blocks, serializer, options)
.outerHTML,
};
};
Loading
Loading