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
93 changes: 80 additions & 13 deletions docs/content/docs/features/custom-schemas/custom-blocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,22 @@ In addition to the default block types that BlockNote offers, you can also make

## Creating a Custom Block Type

Use the `createReactBlockSpec` function to create a custom block type. This function takes two arguments:
Use the `createReactBlockSpec` function to create a custom block type. This function takes three arguments:

```typescript
function createReactBlockSpec(
blockConfig: CustomBlockConfig,
blockImplementation: ReactCustomBlockImplementation,
);
extensions?: BlockNoteExtension[],
): (options? BlockOptions) => BlockSpec;
```

Let's look at our custom alert block from the demo, and go over each field to explain how it works:
It returns a function that you can call to create an instance of your custom block, or a `BlockSpec`. This `BlockSpec` then gets passed into your [BlockNote schema](/docs/features/custom-schemas#creating-your-own-schema) to add the block to the editor. This function may also take arbitrary options, which you can find out more about [below](/docs/features/custom-schemas/custom-blocks#block-config-options).

Let's look at our custom alert block from the demo, and go over everything we pass to `createReactBlockSpec`:

```typescript
const Alert = createReactBlockSpec(
const createAlert = createReactBlockSpec(
{
type: "alert",
propSchema: {
Expand Down Expand Up @@ -54,8 +57,6 @@ type BlockConfig = {
type: string;
content: "inline" | "none";
readonly propSchema: PropSchema;
isSelectable?: boolean;
hardBreakShortcut?: "shift+enter" | "enter" | "none";
};
```

Expand Down Expand Up @@ -106,12 +107,6 @@ If you do not want the prop to have a default value, you can define it as an obj
Properties](/docs/features/blocks#default-block-properties)._
</Callout>

`isSelectable?:` 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.

`hardBreakShortcut?:` Defines which keyboard shortcut should be used to insert a hard break into the block's inline content. Defaults to `"shift+enter"`.

#### File Block Config

### Block Implementation (`ReactCustomBlockImplementation`)

The Block Implementation defines how the block should be rendered in the editor, and how it should be parsed from and converted to HTML.
Expand All @@ -129,6 +124,15 @@ type ReactCustomBlockImplementation = {
contentRef?: (node: HTMLElement | null) => void;
}>;
parse?: (element: HTMLElement) => PartialBlock["props"] | undefined;
runsBefore?: string[];
meta?: {
hardBreakShortcut?: "shift+enter" | "enter" | "none";
selectable?: boolean;
fileBlockAccept?: string[];
code?: boolean;
defining?: boolean;
isolating?: boolean;
};
};
```

Expand All @@ -152,6 +156,69 @@ type ReactCustomBlockImplementation = {

- `element`: The HTML element that's being parsed.

`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.

`meta?:` An object for setting various generic properties of the block.

- `hardBreakShortcut?:` Defines which keyboard shortcut should be used to insert a hard break into the block's inline content. Defaults to `"shift+enter"`.

- `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.

- `fileBlockAccept?:` For custom file blocks, this specifies which MIME types are accepted when uploading a file. All file blocks should specify this property, and should use a [`FileBlockWrapper`](https://github.com/TypeCellOS/BlockNote/blob/main/packages/react/src/blocks/File/helpers/render/FileBlockWrapper.tsx)/[`ResizableFileBlockWrapper`](https://github.com/TypeCellOS/BlockNote/blob/main/packages/react/src/blocks/File/helpers/render/ResizableFileBlockWrapper.tsx) component in their `render` functions (see next subsection).

- `code?:` Whether this block contains [code](https://prosemirror.net/docs/ref/#model.NodeSpec.code).

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

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

### Block Extensions

While the example on this page doesn't use it, `createReactBlockSpec` takes a third, optional argument `extensions`. This is for adding editor `extensions` that are specific to the block, which you can find out more about [here](/docs/features/extensions).

Block extensions are typically things like e.g. adding keyboard shortcuts to change the current block type to a custom block. For a table of contents block, an extension could also add a ProseMirror plugin to scan for headings to put in the ToC.

### Block Config Options

In some cases, you may want to have a customizable block config. For example, you may want to be able to have a code block with syntax highlighting for either web or embedded code, or a heading block with a flexible number of heading levels. You can use the same API for this use case, with some minor changes:

```typescript
// Arbitrary options that your block can take, e.g. number of heading levels or
// available code syntax highlight languages.
type CustomBlockConfigOptions = {
...
}

const createCustomBlock = createReactBlockSpec(
createBlockConfig((options: CustomBlockConfigOptions) => ({
type: "customBlock"
propSchema: ...,
content: ...,
})),
(options: CustomBlockConfigOptions) => ({
render: ...,
...
})
)

const options: CustomBlockConfigOptions = {
...
};

const schema = BlockNoteSchema.create().extend({
blockSpecs: {
// Creates an instance of the custom block and adds it to the schema.
customBlock: createCustomBlock(options),
},
});
```

You can see that instead of passing plain objects for the config and implementation, we instead pass functions. These take the block options as an argument, and return the config and implementation objects respectively. Additionally, the function for creating the config is wrapped in a `createBlockConfig` function.

Also notice that for the example on this page, we create a new Alert block instance by simply calling `createAlert()` with no arguments. When a custom block takes options though, you can pass them in when creating an instance, as shown above.

To see a full example of block options being used, check out the [built-in heading block](https://github.com/TypeCellOS/BlockNote/blob/main/packages/core/src/blocks/Heading/block.ts).

## Adding Custom Blocks to the Editor

Finally, create a BlockNoteSchema using the definition of your custom blocks:
Expand All @@ -163,7 +230,7 @@ const schema = BlockNoteSchema.create({
...defaultBlockSpecs,

// Add your own custom blocks:
alert: Alert,
alert: createAlert(),
},
});
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ Use the `createReactInlineContentSpec` function to create a custom inline conten
function createReactInlineContentSpec(
blockConfig: CustomInlineContentConfig,
blockImplementation: ReactInlineContentImplementation,
);
): InlineContentSpec;
```

Let's look at our custom mentions tag from the demo, and go over each field to explain how it works:
It returns an instance of your custom inline content, or an `InlineContentSpec`. This `InlineContentSpec` then gets passed into your [BlockNote schema](/docs/features/custom-schemas#creating-your-own-schema) to add the inline content to the editor.

Let's look at our custom mentions tag from the demo, and go over everything we pass to `createReactInlineContentSpec`:

```typescript
const Mention = createReactInlineContentSpec(
Expand Down Expand Up @@ -59,8 +61,7 @@ type CustomInlineContentConfig = {
`content:` `styled` if your custom inline content should contain [`StyledText`](/docs/foundations/document-structure#inline-content-objects), `none` if not.

<Callout type="info">
_In the mentions demo, we want each mention to be a single, non-editable
element, so we set `content` to `"none"`._
_In the mentions demo, we want each mention to be a single, non-editable element, so we set `content` to `"none"`._
</Callout>

`propSchema:` The `PropSchema` specifies the props that the inline content supports. Inline content props (properties) are data stored with your inline content in the document, and can be used to customize its appearance or behavior.
Expand Down Expand Up @@ -95,8 +96,7 @@ If you do not want the prop to have a default value, you can define it as an obj
- `values?:` Specifies an array of values that the prop can take, for example, to limit the value to a list of pre-defined strings. If `values` is not defined, BlockNote assumes the prop can be any value of `PrimitiveType`.

<Callout type="info">
_In the mentions demo, we add a `user` prop for the user that's being
mentioned._
_In the mentions demo, we add a `user` prop for the user that's being mentioned._
</Callout>

### Inline Content Implementation (`ReactCustomInlineContentImplementation`)
Expand All @@ -110,9 +110,18 @@ type ReactCustomInlineContentImplementation = {
};
render: React.FC<{
inlineContent: InlineContent;
editor: BlockNoteEditor;
contentRef?: (node: HTMLElement | null) => void;
}>;
toExternalHTML?: React.FC<{
inlineContent: InlineContent;
editor: BlockNoteEditor;
contentRef?: (node: HTMLElement | null) => void;
draggable?: boolean;
}>;
parse?: (element: HTMLElement) => PartialInlineContent["props"] | undefined;
meta?: {
draggable?: boolean;
};
};
```

Expand All @@ -124,11 +133,20 @@ type ReactCustomInlineContentImplementation = {

- `draggable:` Specifies whether the inline content can be dragged within the editor. If set to `true`, the inline content will be draggable. Defaults to `false` if not specified. If this is true, you should add `data-drag-handle` to the DOM element that should function as the drag handle.

`toExternalHTML?:` This component is used whenever the inline content 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`.

<Callout type="info">
_Note that your component passed to `toExternalHTML` is rendered and serialized in a separate React root, which means you can't use hooks that rely on React Contexts._
</Callout>

`parse?:` The `parse` function defines how to parse HTML content into your inline content, for example when pasting contents from the clipboard. If the element should be parsed into your custom inline content, 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.

`meta?.draggable?:` Whether the inline content should be draggable.

<Callout type="info">
_Note that since inline content is, by definition, inline, your component
should also return an HTML inline element._
_Note that since inline content is, by definition, inline, your component should also return an HTML inline element._
</Callout>

## Adding Custom Inline Content to the Editor
Expand Down
23 changes: 18 additions & 5 deletions docs/content/docs/features/custom-schemas/custom-styles.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ Use the `createReactStyleSpec` function to create a custom style type. This func
function createReactStyleSpec(
styleConfig: CustomStyleConfig,
styleImplementation: ReactStyleImplementation,
);
): StyleSpec;
```

Let's look at our custom font style from the demo, and go over each field to explain how it works:
It returns an instance of your custom inline content, or a `StyleSpec`. This `StyleSpec` then gets passed into your [BlockNote schema](/docs/features/custom-schemas#creating-your-own-schema) to add the style to the editor.

Let's look at our custom font style from the demo, and go over everything we pass to `createReactStyleSpec`:

```typescript
export const Font = createReactStyleSpec(
Expand Down Expand Up @@ -67,6 +69,11 @@ type ReactCustomStyleImplementation = {
value?: string;
contentRef: (node: HTMLElement | null) => void;
}>;
toExternalHTML?: React.FC<{
value?: string;
contentRef: (node: HTMLElement | null) => void;
}>;
parse?: (element: HTMLElement) => string | true | undefined;
};
```

Expand All @@ -76,12 +83,18 @@ type ReactCustomStyleImplementation = {

- `contentRef:` A React `ref` to mark the editable element.

`toExternalHTML?:` This component is used whenever the style 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`.

<Callout type="info">
_Note that in contrast to Custom Blocks and Inline Content, the `render`
function of Custom Styles cannot access React Context or other state. They
should be plain React functions analogous to the example._
_Note that your component passed to `toExternalHTML` is rendered and
serialized in a separate React root, which means you can't use hooks that rely
on React Contexts._
</Callout>

`parse?:` The `parse` function defines how to parse HTML content into your style, for example when pasting contents from the clipboard. If the element should be parsed into your custom style, you return a `string` or `true`. If the `propSchema` is `"string"`, you should likewise return a string value, or `true` otherwise. Returning `undefined` will not parse the style from the HTML element. Takes a single argument:

- `element`: The HTML element that's being parsed.

## Adding Custom Style to the Editor

Finally, create a BlockNoteSchema using the definition of your custom style:
Expand Down
59 changes: 48 additions & 11 deletions docs/content/docs/features/custom-schemas/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -28,35 +28,72 @@ Text Styles are properties that can be applied to a piece of text, such as bold,

## Creating your own schema

Once you have defined your custom blocks (see the links above), inline content or styles, you can create a schema and pass this to the initialization of the editor.
Once you have defined your custom blocks (see the links above), inline content or styles, you can create a schema and pass this to the initialization of the editor. There are two ways to create a new schema.

### Extending an existing schema

You can call `BlockNoteSchema.extend` to add custom blocks, inline content, or styles to an existing schema. While this works for any existing schema, it's most common to use this to extend the default schema.

```typescript
// Creates an instance of the default schema when nothing is passed to
// `BlockNoteSchema.create`.
const schema = BlockNoteSchema.create()
// Adds custom blocks, inline content, or styles to the default schema.
.extend({
blockSpecs: {
// Add your own custom blocks:
customBlock: CustomBlock,
...
},
inlineContentSpecs: {
// Add your own custom inline content:
customInlineContent: CustomInlineContent,
...
},
styleSpecs: {
// Add your own custom styles:
customStyle: CustomStyle,
...
},
});
```

### Creating a schema from scratch

Passing custom blocks, inline content, or styles directly into `BlockNoteSchema.create` will produce a new schema with only the things you pass. This can be useful if you only need a few basic things from the default schema, and intend to implement everything else yourself.

```typescript
const schema = BlockNoteSchema.create({
blockSpecs: {
// enable the default blocks if desired
...defaultBlockSpecs,
// Add only the default paragraph block:
paragraph: defaultBlockSpecs.paragraph,

// Add your own custom blocks:
// customBlock: CustomBlock,
customBlock: CustomBlock,
...
},
inlineContentSpecs: {
// enable the default inline content if desired
...defaultInlineContentSpecs,
// Add only the default text inline content:
text: defaultInlineContentSpecs.text,

// Add your own custom inline content:
// customInlineContent: CustomInlineContent,
customInlineContent: CustomInlineContent,
...
},
styleSpecs: {
// enable the default styles if desired
...defaultStyleSpecs,
// Add only the default bold style:
bold: defaultStyleSpecs.bold,

// Add your own custom styles:
// customStyle: CustomStyle
customStyle: CustomStyle,
...
},
});
```

You can then pass this to the instantiation of your BlockNoteEditor (`BlockNoteEditor.create` or `useCreateBlockNote`):
## Using your own schema

Once you've created an instance of your schema using `BlockNoteSchema.create` or `BlockNoteSchema.extend`, you can pass it to the `schema` option of your BlockNoteEditor (`BlockNoteEditor.create` or `useCreateBlockNote`):

```typescript
const editor = useCreateBlockNote({
Expand Down
Loading
Loading