Skip to content

feat(type): optimize parameter type inference for the execute function of the slash menu #524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
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
102 changes: 100 additions & 2 deletions packages/core/src/editor/BlockNoteEditor.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { expect, it } from "vitest";
import { assertType, expect, it } from "vitest";
import { BlockNoteEditor } from "./BlockNoteEditor";
import { getBlockInfoFromPos } from "../api/getBlockInfoFromPos";

import { createBlockSpec } from "../schema/blocks/createSpec";
import { DefaultBlockSchema, defaultBlockSchema, defaultBlockSpecs } from "../blocks/defaultBlocks";
import { BlockSchemaFromSpecs, PartialBlock } from "../schema/blocks/types";
import { getDefaultSlashMenuItems, } from '../extensions/SlashMenu/defaultSlashMenuItems'
import { BaseSlashMenuItem } from "../extensions/SlashMenu/BaseSlashMenuItem";
/**
* @vitest-environment jsdom
*/
Expand All @@ -10,3 +14,97 @@ it("creates an editor", () => {
const blockInfo = getBlockInfoFromPos(editor._tiptapEditor.state.doc, 2);
expect(blockInfo?.contentNode.type.name).toEqual("paragraph");
});

it("support custom block", () => {
const testBlock = createBlockSpec(
{
type: "testBlock",
propSchema: {
content: {
default: "test",
},
},
content: "none",
},
{
render: (block) => {
const div = document.createElement("div");
div.contentEditable = "true";
div.innerHTML = block.props.content;

return {
dom: div,
};
},
}
)

const editor = BlockNoteEditor.create({
blockSpecs: {
...defaultBlockSpecs,
test: testBlock,
},
slashMenuItems: [
...getDefaultSlashMenuItems(),
{
name: "table",
execute: (_editor) => {
assertType<BlockNoteEditor<DefaultBlockSchema & BlockSchemaFromSpecs<{
test: typeof testBlock
}>>>(_editor)

const currentBlock = editor.getTextCursorPosition().block;

// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _errorHelloWorldBlock = {
// @ts-expect-error type should be "testBlock"
type: "test",
props: {
content: "Hello World",
},
} satisfies PartialBlock<BlockSchemaFromSpecs<{
test: typeof testBlock
}>, any, any>

const helloWorldBlock = {
type: "testBlock",
props: {
content: "Hello World",
},
} satisfies PartialBlock<BlockSchemaFromSpecs<{
test: typeof testBlock
}>, any, any>

editor.insertBlocks([helloWorldBlock], currentBlock, "after");
},
},
],
});

assertType<BaseSlashMenuItem<
typeof defaultBlockSchema,
any,
any
>[]>(getDefaultSlashMenuItems(defaultBlockSchema))

assertType<BaseSlashMenuItem<
BlockSchemaFromSpecs<{
test: typeof testBlock
}>,
any,
any
>[]>(getDefaultSlashMenuItems({
test: testBlock['config'],
}))

// @ts-expect-error blockSpecs of editor need to inculde the test block
assertType<BlockNoteEditor>(editor)

assertType<BlockNoteEditor<DefaultBlockSchema & BlockSchemaFromSpecs<{
test: typeof testBlock
}>>>(editor)

const blockInfo = getBlockInfoFromPos(editor._tiptapEditor.state.doc, 2);
expect(blockInfo?.contentNode.type.name).toEqual("paragraph");
})
12 changes: 9 additions & 3 deletions packages/core/src/editor/BlockNoteEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import {
StyleSpecs,
} from "../schema";
import { mergeCSSClasses } from "../util/browser";
import { UnreachableCaseError } from "../util/typescript";
import { NoInfer, UnreachableCaseError } from "../util/typescript";

import { getBlockNoteExtensions } from "./BlockNoteExtensions";
import { TextCursorPosition } from "./cursorPositionTypes";
Expand All @@ -79,11 +79,17 @@ export type BlockNoteEditorOptions<
enableBlockNoteExtensions: boolean;
/**
*
* (couldn't fix any type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771)
* // (couldn't fix any type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771)
*
* @default defaultSlashMenuItems from `./extensions/SlashMenu`
*/
slashMenuItems: BaseSlashMenuItem<any, any, any>[];
slashMenuItems: Array<
BaseSlashMenuItem<
BlockSchemaFromSpecs<NoInfer<BSpecs>>,
any,
any
>
>;

/**
* The HTML element that should be used as the parent element for the editor.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
StyleSchema,
isStyledTextInlineContent,
} from "../../schema";
import { Equal } from "../../util/typescript";
import { imageToolbarPluginKey } from "../ImageToolbar/ImageToolbarPlugin";
import { BaseSlashMenuItem } from "./BaseSlashMenuItem";

Expand Down Expand Up @@ -81,7 +82,7 @@ export const getDefaultSlashMenuItems = <
>(
schema: BSchema = defaultBlockSchema as unknown as BSchema
) => {
const slashMenuItems: BaseSlashMenuItem<BSchema, I, S>[] = [];
const slashMenuItems: BaseSlashMenuItem<Equal<BSchema, BlockSchema> extends true ? any : BSchema, I, S>[] = [];

if ("heading" in schema && "level" in schema.heading.propSchema) {
// Command for creating a level 1 heading
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/schema/blocks/createSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export function getParseRules(
// A function to create custom block for API consumers
// we want to hide the tiptap node from API consumers and provide a simpler API surface instead
export function createBlockSpec<
T extends CustomBlockConfig,
const T extends CustomBlockConfig,
I extends InlineContentSchema,
S extends StyleSchema
>(blockConfig: T, blockImplementation: CustomBlockImplementation<T, I, S>) {
Expand Down
14 changes: 13 additions & 1 deletion packages/core/src/util/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,16 @@ export class UnreachableCaseError extends Error {
constructor(val: never) {
super(`Unreachable case: ${val}`);
}
}
}

/**
* https://stackoverflow.com/questions/56687668/a-way-to-disable-type-argument-inference-in-generics
*
* https://github.com/microsoft/TypeScript/pull/56794
*
* TODO: maybe remove this type after typescript 5.4 is released
*/
export type NoInfer<T> = [T][T extends any ? 0 : never];

export type Equal<Left, Right> =
(<U>() => U extends Left ? 1 : 0) extends (<U>() => U extends Right ? 1 : 0) ? true : false
22 changes: 19 additions & 3 deletions packages/react/src/hooks/useBlockNote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,33 @@ import {
} from "@blocknote/core";
import { DependencyList, useMemo, useRef } from "react";
import { getDefaultReactSlashMenuItems } from "../slashMenuItems/defaultReactSlashMenuItems";
import { ReactSlashMenuItem } from "../slashMenuItems/ReactSlashMenuItem";
import { NoInfer } from "@blocknote/core/src/util/typescript";

type ReactBlockNoteEditorOptions<
BSpecs extends BlockSpecs,
ISpecs extends InlineContentSpecs,
SSpecs extends StyleSpecs
> = Omit<BlockNoteEditorOptions<BSpecs, ISpecs, SSpecs>, 'slashMenuItems'> & {
slashMenuItems: Array<
ReactSlashMenuItem<
BlockSchemaFromSpecs<NoInfer<BSpecs>>,
any,
any
>
>
};

const initEditor = <
BSpecs extends BlockSpecs,
ISpecs extends InlineContentSpecs,
SSpecs extends StyleSpecs
>(
options: Partial<BlockNoteEditorOptions<BSpecs, ISpecs, SSpecs>>
options: Partial<ReactBlockNoteEditorOptions<BSpecs, ISpecs, SSpecs>>
) =>
BlockNoteEditor.create({
slashMenuItems: getDefaultReactSlashMenuItems(
getBlockSchemaFromSpecs(options.blockSpecs || defaultBlockSpecs)
getBlockSchemaFromSpecs(options.blockSpecs as BSpecs || defaultBlockSpecs)
),
...options,
});
Expand All @@ -37,7 +53,7 @@ export const useBlockNote = <
ISpecs extends InlineContentSpecs = typeof defaultInlineContentSpecs,
SSpecs extends StyleSpecs = typeof defaultStyleSpecs
>(
options: Partial<BlockNoteEditorOptions<BSpecs, ISpecs, SSpecs>> = {},
options: Partial<ReactBlockNoteEditorOptions<BSpecs, ISpecs, SSpecs>> = {},
deps: DependencyList = []
) => {
const editorRef =
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/schema/ReactBlockSpec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export function BlockContentWrapper<
// A function to create custom block for API consumers
// we want to hide the tiptap node from API consumers and provide a simpler API surface instead
export function createReactBlockSpec<
T extends CustomBlockConfig,
const T extends CustomBlockConfig,
I extends InlineContentSchema,
S extends StyleSchema
>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ export function getDefaultReactSlashMenuItems<
// the schema type to be automatically inferred if it is defined, or be
// inferred as any if it is not defined. I don't think it's possible to make it
// infer to DefaultBlockSchema if it is not defined.
schema: BSchema = defaultBlockSchema as any as BSchema
): ReactSlashMenuItem<BSchema, I, S>[] {
const slashMenuItems: BaseSlashMenuItem<BSchema, I, S>[] =
schema: BSchema = defaultBlockSchema as unknown as BSchema
): ReactSlashMenuItem<BlockSchema extends BSchema ? any : BSchema, I, S>[] {
const slashMenuItems : BaseSlashMenuItem<BSchema, I, S>[] =
getDefaultSlashMenuItems(schema);

return slashMenuItems.map((item) => ({
Expand Down
57 changes: 43 additions & 14 deletions tests/src/utils/components/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import {
getDefaultReactSlashMenuItems,
useBlockNote,
} from "@blocknote/react";
import { Alert, insertAlert } from "../customblocks/Alert";
import { Button, insertButton } from "../customblocks/Button";
import { Embed, insertEmbed } from "../customblocks/Embed";
import { Image, insertImage } from "../customblocks/Image";
import { Separator, insertSeparator } from "../customblocks/Separator";
import { Alert } from "../customblocks/Alert";
import { Button } from "../customblocks/Button";
import { Embed } from "../customblocks/Embed";
import { Image } from "../customblocks/Image";
import { Separator } from "../customblocks/Separator";
import styles from "./Editor.module.css";

type WindowWithProseMirror = Window & typeof globalThis & { ProseMirror: any };
Expand All @@ -25,21 +25,50 @@ export default function Editor() {
// toc: TableOfContents,
};

const slashMenuItems = [
insertAlert,
insertButton,
insertEmbed,
insertImage,
insertSeparator,
// insertTableOfContents,
];
// const slashMenuItems = [
// insertAlert,
// insertButton,
// insertEmbed,
// insertImage,
// insertSeparator,
// // insertTableOfContents,
// ];

const editor = useBlockNote({
domAttributes: {
editor: { class: styles.editor, "data-test": "editor" },
},
blockSpecs,
slashMenuItems: [...getDefaultReactSlashMenuItems(), ...slashMenuItems],
slashMenuItems: [
...getDefaultReactSlashMenuItems(),
// ...slashMenuItems,
{
name: "Insert Alert",
execute: (editor) => {
editor.insertBlocks(
[
{
type: "alert",
},
],
editor.getTextCursorPosition().block,
"after"
);
},
aliases: [
"alert",
"notification",
"emphasize",
"warning",
"error",
"info",
"success",
],
group: "Media",
icon: <div></div>,
hint: "Insert an alert block to emphasize text",
}
],
});

console.log(editor);
Expand Down
9 changes: 7 additions & 2 deletions tests/src/utils/customblocks/Alert.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BlockSchema, createBlockSpec, defaultProps } from "@blocknote/core";
import { BlockSchemaWithBlock, createBlockSpec, defaultProps } from "@blocknote/core";
import { ReactSlashMenuItem } from "@blocknote/react";
import { RiAlertFill } from "react-icons/ri";
const values = {
Expand Down Expand Up @@ -120,7 +120,12 @@ export const Alert = createBlockSpec(
}
);

export const insertAlert: ReactSlashMenuItem<BlockSchema, any, any> = {

export const insertAlert: ReactSlashMenuItem<
BlockSchemaWithBlock<"alert", typeof Alert.config>,
any,
any
> = {
name: "Insert Alert",
execute: (editor) => {
// editor.topLevelBlocks[0]
Expand Down