Skip to content

Commit ce806b1

Browse files
authored
Layout blocks and block frames (preview) (#3059)
* refactor(core): simplify the BlockInfo API into the single vocabulary for block plumbing Replaces the BlockInfo union's isBlockContainer/childContainer/blockContent shape with block/content/children, and annotates it with the facts callers kept re-deriving by hand: contentStart/contentEnd, childrenStart/ childrenEnd, contentKind (read off the spec config stored on the node), and isContentEmpty. The +1/-1 position arithmetic around content edges, tables and child ranges moves into blockEdgePos/blockEdgeSelection/ tableContentCaretPos and the ChildrenInfo fields. The six producers collapse to four named by the input you already have: getBlockInfoFromNode, getBlockInfoAt, getBlockInfoNearPos, getBlockInfoFromSelection. Block navigation (parent/prev/next/last- descendant) joins them here instead of living beside the merge command. All block manipulation (insert/move/nest/replace/split/update, selections, clipboard, serialization, conversions, keyboard shortcuts) is rewired onto the new vocabulary. insertBlocks gains "first-child"/"last-child" placements resolved through getInsertionPos, shared with the move commands so "can this block go here?" has one schema-driven answer; hand-written nodes are checked against their declared content kind when the schema is built (checkNodeMatchesConfig). * refactor(core): consolidate BlockInfo shape and insertion helpers Resolve block shape directly, validate wrapper structure at the BlockInfo boundary, and convert content from the established content kind. Move insertion resolution into BlockInfo and use node bounds for last-descendant navigation, updating callers and regression coverage. * feat(container-blocks): unify containers, owned children, and frames Build container ownership and editing on the BlockInfo helpers. Keep repair policy centralized, use the existing NodeView lifecycle for JS and React frames, and expose shared helpers through the core entrypoint. * test(container-blocks): cover editing, frames, repair, and serialization * docs(container-blocks): document the API and add panel and callout examples * refactor(core): simplify container UI and block DOM lookup * refactor(container-blocks): simplify rendering, editing, and exports * fix(core): normalize container parsing and export * fix(tests): streamline Docker build inputs and cache invalidation * fix(container-blocks): simplify editing and support plain text * refactor(container-blocks): simplify implementation and examples * fix(core): complete frame lifecycle and preserve split children * fix: address container block review feedback * fix(core): unwrap a dissolving container in place (#3104) * test(core): add behaviour tests for the built-in toggle blocks Tests for the toggle heading and the toggle list item, covering the toggle bugs under BLO-1018 and the rest of their editing behaviour. Every test runs for both blocks. The expected behaviour is Notion's (compared on 2026-09-29), with one exception: a toggle heading turned into a regular heading keeps its children nested. Tests for behaviour that BlockNote does not have yet use `it.fails`, so they fail once it is implemented and must then be changed to `it`: - Enter at the end of an open toggle's title adds a first child (BLO-929) - Enter mid-title moves the rest of the title into a first child (BLO-949) - Enter on an empty last child adds another child - Backspace at the start of the first child merges into the title (fixed by #3124) - the toggle stays open when its last child is removed or moved out - Enter in an empty toggle heading makes a regular heading - Mod-Alt-2 and the slash menu turn a toggle heading into a regular heading (BLO-959) - ArrowDown moves out of an open, empty toggle (BLO-956) - a block dropped into an open, empty toggle becomes its child (BLO-956) Keyboard and open-state tests are browser unit tests next to the toggle code. Drag and drop, the side menu and the placeholder need the full editor view, so they are end-to-end tests. * refactor(core): draw the built-in toggles with renderFrame The toggle heading and the toggle list item now draw their chevron and "Add block" button with `renderFrame` (`createToggleFrame`), instead of wrapping their content with `createToggleWrapper`. `render` draws only the heading or paragraph. - The toggle logic goes from about 200 to about 100 lines: the frame's `update` hook replaces an editor-wide `onChange` listener per toggle, and `ignoreMutation`, `destroy` and the listener clean-up go away. - A heading that is not toggleable gets no frame. - ArrowDown now moves the caret out of an open, empty toggle (BLO-956): the "Add block" button no longer sits inside the content element. - The frame keeps the `bn-toggle-wrapper` class and `data-show-children`, so existing CSS and the internal HTML export still find it. A frame moves `.bn-block-content` one level down, and `Block.css` selects it as a direct child of `.bn-block` in many places. Heading sizes and the block colours that also apply to a block's children therefore get a second selector for the toggle frame. The chevron rotation now applies only to a toggle's own chevron, so a closed toggle nested in an open one keeps its chevron. `createToggleWrapper` and the React `ToggleWrapper` stay, because custom blocks use them. * feat(core)!: split keyboard behaviour from container structure Blocks declare how the keyboard treats them with a `keyboard` option on their implementation (Enter, Shift-Enter, reset, empty-child Enter, outdenting), instead of deriving it from a `children` config. A container is marked with `container: true`; `children` only restricts its child types or count, and defaults to `{ allow: "blocks" }` for every block. - List items and toggles declare their Enter behaviour as settings; the per-block list Enter handlers and the unused ListItemKeyboardShortcuts file are removed. - Enter at the start of a non-empty block inserts an empty block above, so the block keeps its id, props and children (#550). - Toggles: Enter on an open toggle goes into its children, a closed toggle keeps them; the chevron has an accessible name and `aria-expanded`, which also drives the CSS (replaces `data-show-children`). - A toggle heading turned into a regular heading by the shortcut, the markdown rule or the slash menu stops being a toggle. - Backspace after a block whose own content is not rich text (a code block) merges into its last child block. - Removes `createToggleWrapper`, the React `ToggleWrapper` and the toggleable-blocks example; `meta.hardBreakShortcut` is deprecated. * feat(exporters): let block mappings place their children A block mapping is a plain function (the exporter places the block's children) or `{ withChildren }`, which receives the rendered children and places them itself. A container with a plain mapping throws. * fix(core): apply block colors to the children of framed blocks The block's element (`.bn-block`) carries its text and background color, set by the block container's node view and the internal HTML serializer. The color rules in Block.css no longer look for the content as a direct child, so they work when a frame puts the content at any depth, and the toggle specific copies go away. * test(server-util): update the full HTML snapshot for block color attributes * fix: address review findings on keyboard settings and toggles - Restore the toggle heading size and weight rules, which the block color change dropped, and test that a toggle heading looks like a heading. - Keep a keyboard setting's default when a keyboard function returns it as `undefined`, instead of crashing Backspace. - Resolve a block's keyboard settings against the document of the command that asks. - Tests: cover Shift-Enter on plain blocks with `keyboard` settings, remove the per-exporter "unmapped block" tests (core tests the error) and a duplicate Enter test, and update stale comments and names. * docs(core): note that ignoreFrameChromeMutations needs tests or removal * feat(core): drop a block into a toggle (BLO-956) A block dragged onto a toggle's title, chevron or "Add block" button becomes its first child, as in Notion. The drop cursor shows the place and the toggle is highlighted like a selected block. - `meta.dropsIntoChildren` marks a block that takes drops this way. - The drop cursor finds the target and a `handleDrop` plugin drops the blocks where the cursor shows them. - Drag-and-drop events on frame chrome now reach ProseMirror. - A toggle stays open when its last child is removed or moved out. * fix(core): keep a block's id on Backspace below an alike empty block (#550) Backspace at the start of a block below an empty block with the same type and props moves the block up into its place: it keeps its id, props and children. Below an empty block of another type, the text still moves into that block, which keeps its id, type and props (Notion, #3124). Delete at the end of the empty block does the same. Also: the placeholder extension sets its editor class through ProseMirror's `attributes` prop instead of on `view.dom`. ProseMirror flushed the outside change 20ms later, which could outlive the editor in tests ("document is not defined"). * fix(core): drop as usual when the drop target is gone `handleDrop` used the target from the last `dragover`. If the target was removed in the meantime (e.g. by a collaborator), it threw halfway through the move. It now looks up the target first and lets ProseMirror drop the blocks when it is gone. The drop also clears the highlight. * test: update block spec snapshot for meta.dropsIntoChildren * fix: one source for the block types that the menus offer (BLO-990, BLO-1236) The block type select filtered a fixed item list by prop names and types. With `allowToggleHeadings: false` it showed no headings at all, and with `levels` it still showed every heading level. `getDefaultBlockTypeItems(editor)` (core) now returns the block types that the schema supports, with their props: headings for the configured levels, toggle headings only when the heading has `isToggleable`. The slash menu and the block type select both use it, each in its own order. Breaking: `blockTypeSelectItems(dict)` is now `blockTypeSelectItems(editor)`. * refactor(core): rename the keyboard option to experimental_keyboard The block implementation option for keyboard settings is now `experimental_keyboard`. The API is still under discussion and may change. The resolved settings on a schema spec stay at `keyboard`, and the declared option is no longer kept on the spec. * Simplify nestBlock's slice, restrict children.min to allow lists, drop isContainerConfig - nestBlock: `sinkItem` opens its slice into the previous sibling and its block group only, never into the group's last child. Tab after a column list (or any container node) now nests the block instead of throwing. `insert` follows the open depth; the step is applied with `tr.step` again, since the schema cannot refuse it. - `children.min` is only valid with an `allow` list. `{ allow: "blocks" }` cannot carry it; the type and `validateChildrenConfigs` enforce this. `min: 0` lets a container be empty. - Remove `isContainerConfig`: it was a plain property check. - Docs: trim the typst section on blocks that place their children; describe `insertBlocks` placements for all blocks; document the `children.min` rule. - Cleanups: the mergeBlocks test asserts that children are lifted and the comment names `createChainableState`; `nodeToBlock` loop variable; `contentKind` doc; the Exporter's container check. * Keyboard, children and drag fixes from the second review round - Columns: Enter in an empty column block adds another block (`emptyChildEnter: "stay"`), as in Notion. Other containers keep the default, where an empty last block leaves the container. - Split: the children of a split block follow the text after the caret into the new block again, as on `main`. The new keyboard setting `splitKeepsChildren` keeps them on the block. It defaults to `true` when Enter goes into the children, and closed toggles set it. - `children.exclude` names the container types a container of any blocks does not hold. Columns exclude column lists, as on `main`. The content expression is built when the editor builds its ProseMirror schema, from the complete block specs. - A block's `meta` is resolved once per spec (`resolveBlockMeta`), like its keyboard settings. `draggable` defaults to `false` for a named-only container, which can only live in its parent. - Multi-column drop: dropping blocks onto a target they hold does nothing, instead of throwing `Block with ID ... not found` (a CI flake). - Tests: Backspace at the start of a column's first block keeps the caret; column children; a browser test for the drop flake. - Docs: keyboard settings, `children.exclude`, `meta.draggable`; no column example on the container page. * Frame slot parsing, frames out of external HTML, one data-* attribute rule - A framed block's internal HTML marks its slot (`data-frame-slot-todo`), and the `blockContainer` parse rule reads only that element. Chrome a frame draws outside the slot no longer parses back as a paragraph. TODO: containers mark the same region with `data-children-of`; use one marker once container boxes move into `renderFrame`. - External HTML leaves out `renderFrame`: a frame is editor chrome. A block that wants a wrapper returns one from `toExternalHTML`, with `childrenDOM` for its children. - The test schema's callout always draws its chrome (no `this.renderType` branch), and the framed alert draws the same chrome, so the format-conversion tests cover both. - One implementation of the props to `data-*` attribute rule (`propsToDataAttributes`, `setDataAttributes`, `applyDataAttributes`), used by blocks, inline content, tables, containers and the React specs. No output changes. - Remove `isControl` from the side menu: it made the handle depend on whether a container's chrome is an element or padding. * Containers draw only renderFrame; render never returns a frame (#3182) - A container (`container: true`) declares only `renderFrame`; `render` is not permitted (`validateRenderHooks`). Its frame root carries the block's attributes. - `render` returns only the block's content. Both HTML serializers call `renderFrame` themselves (`renderFrameDOM`). - A block exports its frame unless it has its own `toExternalHTML`, which replaces the content and the frame. The spec has `toExternalHTML` only when the author wrote one. - External HTML treats containers like regular blocks: no `data-node-type`, `data-id` or slot marker; props stay as `data-*`. Columns get `parse` functions, so they still round-trip. A container's children are kept when its own export places them nowhere. - One slot marker (`data-frame-slot`) and finder (`findFrameSlot`). A frame's `dom` is an `HTMLElement`. `renderFrame`'s context no longer has `blockContentDOMAttributes`. - React: frames take `slotRef`; `toExternalHTML` gets `childrenRef` (like core's `childrenDOM`); a container renders through `FrameNodeView`. - `createBlockSpecFromTiptapNode` drops the unused `container`, `children` and `placeable` options. - Main's doc comment for `render`'s `update` hook is restored. * Frame views: one node view path for vanilla and React frames (#3184) One FrameView type for vanilla and React frames; BlockContainer's node view rebuilt from main's; whoever draws a frame stamps it; shared chrome rules (drag-and-drop and clipboard events go to ProseMirror); getBlockElementForNode for BlockPopover; containers never reuse another block's frame. * Workaround: measure a React container by its frame root A React container's node view `dom` is TipTap's wrapper, which has `display: contents` and so no box. nodeDOM boxes, coordsAtPos at the container's edges, posToDOMRect, the drop cursor, the selection box and scrolling measured 0,0,0,0. This is a workaround: the wrapper's getBoundingClientRect and getClientRects measure the frame's root instead. Other measurements of the wrapper (offsetTop, observers, scrollIntoView on it) stay wrong. The correct fix makes the frame's root the node view `dom` (FIXME in code). * test(exporters): rely on the shared test document for child placement The shared test document has a column list, and every exporter maps `column` and `columnList` with `{ withChildren }`. Its snapshot tests already check that each exporter gives a block's children to the mapping and does not place them after the block again. An exporter decides this only from the mapping (`placesChildren`), so a custom container or a titled block takes the same path. Remove the custom-block tests that each exporter repeated, and say so in `shared/testDocument.ts`. * fix(multi-column): throw when the drop target column is not in its column list The drop target comes from the column list, so it is one of its columns. If findIndex misses it, the new column would go to an incorrect position without an error. From #3116. * fix(core): drag previews of containers; dragged blocks keep their parent - The drag preview copies each dragged block's DOM (`nodeDOM`) into a copy of the element that holds them, without `display: contents`. Before, it found the blocks by assuming two DOM levels per block, so a React container (or a frame whose root is its slot) got an empty preview, and a block in a React container a preview without a box. - `dragStart` puts the type of the dragged blocks' parent in the drag data, and every editor parses the blocks into it. Before, a block that only its parent can hold (a `namedOnly` container, e.g. a step) was wrapped in a new copy of the parent, in the same editor and in others. - Tests: drag previews of a React container and of a block in it, and moving a `namedOnly` container in its list and to another editor. The drag helper is split into `startBlockDrag` and `dropDraggedBlock`. * fix(core): clearer block config errors; reject an unnamed namedOnly block - The errors of `validateChildrenConfigs` use the words of the docs, not internals ("container node", "the same wrapper"), and start with "Invalid config for block", because not all are about `children`. - A `namedOnly` block that no `children.allow` list names is now an error at schema creation. Before, the schema accepted it, but the editor could not insert it anywhere. * feat(examples): container block examples; children.dissolve (#3140) Tabs and stepper examples on the renderFrame container API. Adds children.dissolve for containers with an allow list (tab sets and steppers keep empty tabs and steps). The core drag fixes found by these examples are in container-blocks/unified (9414458). * refactor!: rename container blocks to layout blocks (`layoutOnly`) The block config flag `container: true` is now `layoutOnly: true`, and "container block" is "layout block" in the API, errors, docs, examples and tests. A layout block has no content of its own, only child blocks. "Container" also named the `blockContainer` node (the node of every other block, stored in documents), and suggested any block that holds blocks, like a titled callout. - Exports: `isContainerNode` -> `isLayoutNode`, `fixContainer` -> `fixLayoutBlock`, `isEmptyContainerChild` -> `isEmptyLayoutChild`, `getAncestorContainers` -> `getAncestorLayoutBlocks`, `applyContainerAttributes` -> `applyLayoutBlockAttributes`, `stampContainerFrame` -> `stampLayoutFrame`; `removeAndInsertBlocks` option `fixContainers` -> `fixLayoutBlocks`. - CSS class `bn-container-node-view` -> `bn-frame-node-view` (it is on every React frame). - Docs page `container-blocks` -> `layout-blocks`; example `09-container-block` -> `09-layout-block`. - Kept: `blockContainer` (stored in documents) and the `childContainer` node group (any node holding a block's children), explained in `children.ts`. The ProseMirror schema and all serialized output are unchanged. * docs(examples): streamline the alert and panel examples Replace the callout example with "Alert Block with Title and Body". It is the minimal Alert example plus a body: the same code, except for renderFrame, experimental_keyboard and the title row. The layout block docs build on it. The panel example gets a neutral look. The alert examples link to each other, and the minimal alert example loses its slash menu tags. * small fix to stepper design * docs: explain block frames in Custom Blocks; layoutOnly is a boolean Custom Blocks gets a Block Frames section, built on the Alert with a title and a body. Layout Blocks starts with what a layout block is, compares it with a block with a frame, and links to the Tabs and Stepper examples, which are now on the docs site. layoutOnly is now a boolean. `true` still needs content: "none". * fix: review findings for layout blocks - removeBlocks repairs only the layout blocks that directly hold the removed block. A block nested under a regular block in a column no longer collapses the column list (regression vs main). - updateBlock keeps the block id when it rebuilds the block. - children.min must be a whole number that is 0 or more. - Docs: exporting layout blocks ({ withChildren }), and a layout block's renderFrame must not return null. - Examples: the layout examples' slash items move to a "Layout" group (no second "Basic blocks" group), the stepper README is correct again, and the tabs and stepper examples are by yousefed. * docs: layout blocks are a preview; simplify the comparison table Layout Blocks starts with a preview note that asks for feedback. The table with block frames now says which hooks are mandatory, and links to all layout block examples. --------- Co-authored-by: YousefED
1 parent abf741c commit ce806b1

402 files changed

Lines changed: 20266 additions & 4586 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.dockerignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
# these entries just stop the heavy/irrelevant trees from bloating the context.
66
**/node_modules
77
**/dist
8+
**/.next
89
**/types
910
**/.vite
1011
**/.vite-plus

‎docs/content/docs/features/custom-schemas/custom-blocks.mdx‎

Lines changed: 147 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ type BlockConfig = {
5656
type: string;
5757
content: "inline" | "plain" | "none";
5858
readonly propSchema: PropSchema;
59+
layoutOnly?: boolean;
60+
children?:
61+
| { allow?: "blocks"; exclude?: string[] }
62+
| { allow: string[]; min?: number; dissolve?: boolean };
63+
placeable?: "anywhere" | "namedOnly";
5964
};
6065
```
6166

@@ -110,6 +115,15 @@ If you do not want the prop to have a default value, you can define it as an obj
110115
Properties](/docs/features/blocks#default-block-properties)._
111116
</Callout>
112117

118+
<Callout type="info">
119+
_Every block can have child blocks, indented below it. You do not declare
120+
them in the config. To draw a frame around a block and its child blocks, see
121+
[Block Frames](#block-frames). `layoutOnly`, `children` and `placeable` are
122+
only for layout blocks. A layout block only holds and arranges other blocks,
123+
but has no content of its own, for example a panel or a tab set. See [Layout
124+
Blocks](/docs/features/custom-schemas/layout-blocks)._
125+
</Callout>
126+
113127
### Block Implementation (`ReactCustomBlockImplementation`)
114128

115129
The Block Implementation defines how the block should be rendered in the editor, and how it should be parsed from and converted to HTML.
@@ -121,25 +135,44 @@ type ReactCustomBlockImplementation = {
121135
editor: BlockNoteEditor;
122136
contentRef?: (node: HTMLElement | null) => void;
123137
}>;
138+
renderFrame?: React.FC<{
139+
block: Block;
140+
editor: BlockNoteEditor;
141+
slotRef: (node: HTMLElement | null) => void;
142+
}>;
124143
toExternalHTML?: React.FC<{
125144
block: Block;
126145
editor: BlockNoteEditor;
127146
contentRef?: (node: HTMLElement | null) => void;
128-
contest: { nestingLevel: number };
147+
childrenRef: (node: HTMLElement | null) => void;
148+
context: { nestingLevel: number };
129149
}>;
130150
parse?: (element: HTMLElement) => PartialBlock["props"] | undefined;
131151
parseContent?: (options: {
132152
el: HTMLElement;
133153
schema: Schema;
134154
}) => Fragment | undefined;
135155
runsBefore?: string[];
156+
experimental_keyboard?:
157+
| KeyboardSettings
158+
| ((block: Block) => KeyboardSettings);
159+
// KeyboardSettings: {
160+
// enter?: "split" | "into-children" | "line-break";
161+
// shiftEnter?: "line-break" | "same-as-enter";
162+
// splitKeepsType?: boolean;
163+
// splitKeepsChildren?: boolean;
164+
// resetsTo?: { type: string; props?: Record<string, unknown> };
165+
// emptyEnterResets?: boolean;
166+
// emptyChildEnter?: "outdent" | "exit-at-end" | "stay";
167+
// childrenCanOutdent?: boolean;
168+
// }
136169
meta?: {
137-
hardBreakShortcut?: "shift+enter" | "enter" | "none";
138170
selectable?: boolean;
139171
fileBlockAccept?: string[];
140172
code?: boolean;
141173
defining?: boolean;
142174
isolating?: boolean;
175+
draggable?: boolean;
143176
highlight?: (block: Block) => string | undefined;
144177
};
145178
};
@@ -153,9 +186,14 @@ type ReactCustomBlockImplementation = {
153186

154187
- `contentRef:` A React `ref` you can use to mark which element in your block is editable. This is only available if your block config contains `content: "inline"` or `content: "plain"`.
155188

156-
`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` for the HTML conversion. Takes the same props as `render` and an additional `context` prop, which is. an object with the following attributes:
189+
`renderFrame?:` A component that draws a frame around the block's content and its child blocks. See [Block Frames](#block-frames).
190+
191+
`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:
192+
193+
- `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.
157194

158-
- `nestingLevel`: How deep the block being exported in nested inside other blocks. 0 means it's at the top level of the document.
195+
- `context:` An object with the following attributes:
196+
- `nestingLevel`: How deep the block being exported is nested inside other blocks. 0 means it's at the top level of the document.
159197

160198
<Callout type="info">
161199
_Note that your component passed to `toExternalHTML` is rendered and
@@ -171,9 +209,27 @@ type ReactCustomBlockImplementation = {
171209

172210
`runsBefore?:` If this block has parsing or extensions that need to be given priority over any other blocks, you can pass their `type`s in an array here.
173211

174-
`meta?:` An object for setting various generic properties of the block.
212+
`experimental_keyboard?:` How the keyboard treats the block and its children. This API is experimental and may change. Give only the settings that differ from the defaults. To make settings depend on the block's props, give a function that gets the block and returns them instead.
213+
214+
- `enter?:` What Enter does in the block's content. `"split"` (default) splits the block, moving the text after the caret into a new block below. `"into-children"` moves it into a new first child instead. `"line-break"` inserts a line break, and makes Shift-Enter do the same. For `content: "plain"` blocks (which can't hold hard break nodes), a line break is a literal newline (`"\n"`).
215+
216+
- `shiftEnter?:` What Shift-Enter does in the block's content: `"line-break"` (default) or `"same-as-enter"`.
217+
218+
- `splitKeepsType?:` Whether the block created by splitting this one with Enter has the same type, as in lists. Defaults to `false`.
219+
220+
- `splitKeepsChildren?:` Whether the block's children stay with it when Enter splits it. Otherwise they follow the text after the caret into the new block, as for nested blocks, so the new block takes the block's place above them. Defaults to `true` when `enter` is `"into-children"` (the children are the block's body), otherwise `false`; a closed toggle sets it to keep its hidden children.
221+
222+
- `resetsTo?:` What the block turns into when it's reset, keeping its content and children. Backspace at the start of the block always resets it. A `type`, and `props` to merge into the block's props. Defaults to `{ type: "paragraph" }`.
223+
224+
- `emptyEnterResets?:` Whether Enter in the empty block resets it too, as when an empty list item turns into a paragraph. Defaults to `false`.
225+
226+
- `emptyChildEnter?:` What Enter does in an empty child of this block. `"outdent"` (default) outdents any empty child. `"exit-at-end"` (default for layout blocks) moves an empty last child out to after the block, and adds a new child after any other empty child. `"stay"` always adds a new child after it.
175227

176-
- `hardBreakShortcut?:` Defines which keyboard shortcut should be used to insert a hard break into the block's inline content. Defaults to `"shift+enter"`. For `content: "plain"` blocks (which can't hold hard break nodes), the shortcut inserts a literal newline (`"\n"`) instead.
228+
- `childrenCanOutdent?:` Whether the block's children can be outdented out of it with Shift-Tab, or by Enter or Backspace in an empty or nested child. Defaults to `true`, or `false` for layout blocks, whose children can never be outdented.
229+
230+
When settings meet, Enter at the start of non-empty content always inserts an empty block above it, and resetting an empty block comes before `enter: "into-children"`.
231+
232+
`meta?:` An object for setting various generic properties of the block.
177233

178234
- `selectable?:` Can be set to false in order to make the block non-selectable, both using the mouse and keyboard. This also helps with being able to select non-editable content within the block. Should only be set to false when `content` is `none` and defaults to true.
179235

@@ -185,6 +241,8 @@ type ReactCustomBlockImplementation = {
185241

186242
- `isolating?:` Whether this block is [isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating).
187243

244+
- `draggable?:` Whether the block gets a side menu drag handle. Defaults to `true`, or `false` for a layout block that can only be placed inside a specific parent (`placeable: "namedOnly"`).
245+
188246
- `highlight?:` A callback that returns the language the block's text should be syntax-highlighted as (or `undefined` for no highlighting). Highlighting only takes effect when the [syntax highlighting extension](/docs/features/blocks/code-blocks#syntax-highlighting) is added to the editor.
189247

190248
### Block Extensions
@@ -257,3 +315,86 @@ You can then instantiate your editor with this custom schema, as explained on th
257315
Now you know how to create a custom block and add it to your editor. However, users don't have a way of creating instances of it to their documents.
258316

259317
To fix this, it's recommended to implement a [command to insert your custom in the Slash Menu](/docs/react/components/suggestion-menus#changing-slash-menu-items), and [an item for it in the Block Type Select](/docs/react/components/formatting-toolbar)
318+
319+
## Block Frames
320+
321+
A block can have child blocks. By default, BlockNote shows the child blocks indented below the block. Use `renderFrame` to draw one frame around the block's content and its child blocks, for example one background for both.
322+
323+
In the demo below, we give the Alert block from the demo above a title and a body. The alert's text is its title, and its child blocks are its body. The frame gives the title and the body the background color of the alert type:
324+
325+
<Example name="custom-schema/alert-block-with-title-and-body" />
326+
327+
The block config does not change. A block with content (`content: "inline"` or `"plain"`) can always have child blocks, so you do not declare them. We add `renderFrame` and `experimental_keyboard` to the block implementation:
328+
329+
```tsx
330+
export const createAlert = createReactBlockSpec(
331+
{
332+
type: "alert",
333+
propSchema: {
334+
type: {
335+
default: "warning",
336+
values: ["warning", "error", "info", "success"],
337+
},
338+
},
339+
content: "inline",
340+
},
341+
{
342+
experimental_keyboard: {
343+
enter: "into-children",
344+
childrenCanOutdent: false,
345+
emptyChildEnter: "exit-at-end",
346+
},
347+
// Draws the title row, the same as in the Alert demo.
348+
render: (props) => {
349+
...
350+
},
351+
renderFrame: (props) => (
352+
<div className="alert-frame" data-alert-type={props.block.props.type}>
353+
<div ref={props.slotRef} />
354+
</div>
355+
),
356+
},
357+
);
358+
```
359+
360+
`render:` Draws only the block's content, here the alert's title row. It does not change when you add a frame.
361+
362+
`renderFrame:` A React component that draws the frame. It takes three React props:
363+
364+
- `block:` The block. Use its props to change the frame, for example to show the color of the alert type.
365+
366+
- `editor:` The BlockNote editor instance that the block is in.
367+
368+
- `slotRef:` A React `ref`. Attach it to the element that holds the block's content and its child blocks. You can add other elements around this element, for example icons or buttons. Set `contentEditable={false}` on them.
369+
370+
To show the block without a frame, return `null`. For example, you can use a prop to turn the frame on and off.
371+
372+
`experimental_keyboard:` Without these settings, the child blocks behave like all other nested blocks. Here, they keep the body in the alert:
373+
374+
- `enter: "into-children"`: Enter in the title adds a block at the start of the body.
375+
- `childrenCanOutdent: false`: Shift-Tab does not move blocks out of the alert.
376+
- `emptyChildEnter: "exit-at-end"`: Enter in an empty last block of the body moves that block out of the alert.
377+
378+
See [`experimental_keyboard`](#block-implementation-reactcustomblockimplementation) above for all settings.
379+
380+
Use `content` for the title and `children` for the body:
381+
382+
```typescript
383+
{
384+
type: "alert",
385+
content: "Before you start",
386+
children: [
387+
{ type: "paragraph", content: "Make sure you have an account." },
388+
],
389+
}
390+
```
391+
392+
When the user moves the alert, its title and its body move together.
393+
394+
<Callout type="info">
395+
_A block with a frame is different from a [layout
396+
block](/docs/features/custom-schemas/layout-blocks). A layout block has no
397+
content of its own. It only holds child blocks, for example a panel or a tab
398+
set. See [Layout Blocks and Block
399+
Frames](/docs/features/custom-schemas/layout-blocks#layout-blocks-and-block-frames)._
400+
</Callout>

0 commit comments

Comments
 (0)