Blocknote custom slash menu (#4517)

blocknote v12, cleaned up blockschema & specs, added custom slash menu
This commit is contained in:
brendanlaschke
2024-03-20 08:38:05 +01:00
committed by GitHub
parent 35d41e38c8
commit 017b09ba35
11 changed files with 308 additions and 183 deletions

View File

@ -1,11 +1,4 @@
import { ChangeEvent, useRef } from 'react';
import {
BlockFromConfig,
BlockNoteEditor,
InlineContentSchema,
PropSchema,
StyleSchema,
} from '@blocknote/core';
import { createReactBlockSpec } from '@blocknote/react';
import styled from '@emotion/styled';
import { isNonEmptyString } from '@sniptt/guards';
@ -19,31 +12,10 @@ import { AttachmentIcon } from '../files/components/AttachmentIcon';
import { AttachmentType } from '../files/types/Attachment';
import { getFileType } from '../files/utils/getFileType';
import { blockSpecs } from './blockSpecs';
export const filePropSchema = {
// File url
url: {
default: '' as string,
},
name: {
default: '' as string,
},
fileType: {
default: 'Other' as AttachmentType,
},
} satisfies PropSchema;
const StyledFileInput = styled.input`
display: none;
`;
const FileBlockConfig = {
type: 'file' as const,
propSchema: filePropSchema,
content: 'none' as const,
};
const StyledFileLine = styled.div`
align-items: center;
display: flex;
@ -66,75 +38,82 @@ const StyledUploadFileContainer = styled.div`
gap: ${({ theme }) => theme.spacing(2)};
`;
const FileBlockRenderer = ({
block,
editor,
}: {
block: BlockFromConfig<
typeof FileBlockConfig,
InlineContentSchema,
StyleSchema
>;
editor: BlockNoteEditor<typeof blockSpecs, InlineContentSchema, StyleSchema>;
}) => {
const inputFileRef = useRef<HTMLInputElement>(null);
const handleUploadAttachment = async (file: File) => {
if (isUndefinedOrNull(file)) {
return '';
}
const fileUrl = await editor.uploadFile?.(file);
editor.updateBlock(block.id, {
props: {
...block.props,
...{ url: fileUrl, fileType: getFileType(file.name), name: file.name },
export const FileBlock = createReactBlockSpec(
{
type: 'file',
propSchema: {
url: {
default: '' as string,
},
});
};
const handleUploadFileClick = () => {
inputFileRef?.current?.click?.();
};
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
if (isDefined(e.target.files)) handleUploadAttachment?.(e.target.files[0]);
};
if (isNonEmptyString(block.props.url)) {
return (
<AppThemeProvider>
<StyledFileLine>
<AttachmentIcon
attachmentType={block.props.fileType as AttachmentType}
></AttachmentIcon>
<StyledLink href={block.props.url} target="__blank">
{block.props.name}
</StyledLink>
</StyledFileLine>
</AppThemeProvider>
);
}
return (
<AppThemeProvider>
<StyledUploadFileContainer>
<StyledFileInput
ref={inputFileRef}
onChange={handleFileChange}
type="file"
/>
<Button onClick={handleUploadFileClick} title="Upload File"></Button>
</StyledUploadFileContainer>
</AppThemeProvider>
);
};
export const FileBlock = createReactBlockSpec(FileBlockConfig, {
render: (block) => {
return (
<FileBlockRenderer
block={block.block}
editor={block.editor}
></FileBlockRenderer>
);
name: {
default: '' as string,
},
fileType: {
default: 'Other' as AttachmentType,
},
},
content: 'none',
},
});
{
render: ({ block, editor }) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const inputFileRef = useRef<HTMLInputElement>(null);
const handleUploadAttachment = async (file: File) => {
if (isUndefinedOrNull(file)) {
return '';
}
const fileUrl = await editor.uploadFile?.(file);
editor.updateBlock(block.id, {
props: {
...block.props,
...{
url: fileUrl,
fileType: getFileType(file.name),
name: file.name,
},
},
});
};
const handleUploadFileClick = () => {
inputFileRef?.current?.click?.();
};
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
if (isDefined(e.target.files))
handleUploadAttachment?.(e.target.files[0]);
};
if (isNonEmptyString(block.props.url)) {
return (
<AppThemeProvider>
<StyledFileLine>
<AttachmentIcon
attachmentType={block.props.fileType as AttachmentType}
></AttachmentIcon>
<StyledLink href={block.props.url} target="__blank">
{block.props.name}
</StyledLink>
</StyledFileLine>
</AppThemeProvider>
);
}
return (
<AppThemeProvider>
<StyledUploadFileContainer>
<StyledFileInput
ref={inputFileRef}
onChange={handleFileChange}
type="file"
/>
<Button
onClick={handleUploadFileClick}
title="Upload File"
></Button>
</StyledUploadFileContainer>
</AppThemeProvider>
);
},
},
);

View File

@ -1,8 +0,0 @@
import { defaultBlockSpecs } from '@blocknote/core';
import { FileBlock } from './FileBlock';
export const blockSpecs: any = {
...defaultBlockSpecs,
file: FileBlock,
};

View File

@ -1,8 +1,10 @@
import { BlockSchema, defaultBlockSchema } from '@blocknote/core';
import { BlockNoteSchema, defaultBlockSpecs } from '@blocknote/core';
import { FileBlock } from './FileBlock';
export const blockSchema: BlockSchema = {
...defaultBlockSchema,
file: FileBlock.config,
};
export const blockSchema = BlockNoteSchema.create({
blockSpecs: {
...defaultBlockSpecs,
file: FileBlock,
},
});

View File

@ -1,30 +1,45 @@
import {
BlockNoteEditor,
InlineContentSchema,
StyleSchema,
} from '@blocknote/core';
import { getDefaultReactSlashMenuItems } from '@blocknote/react';
import { IconFile } from '@/ui/display/icon';
import {
IconFile,
IconH1,
IconH2,
IconH3,
IconList,
IconListNumbers,
IconPhoto,
IconPilcrow,
IconTable,
} from '@/ui/display/icon';
import { IconComponent } from '@/ui/display/icon/types/IconComponent';
import { SuggestionItem } from '@/ui/input/editor/components/CustomSlashMenu';
import { blockSchema } from './schema';
export const getSlashMenu = () => {
const items = [
...getDefaultReactSlashMenuItems(blockSchema),
const Icons: Record<string, IconComponent> = {
'Heading 1': IconH1,
'Heading 2': IconH2,
'Heading 3': IconH3,
'Numbered List': IconListNumbers,
'Bullet List': IconList,
Paragraph: IconPilcrow,
Table: IconTable,
Image: IconPhoto,
};
export const getSlashMenu = (editor: typeof blockSchema.BlockNoteEditor) => {
const items: SuggestionItem[] = [
...getDefaultReactSlashMenuItems(editor).map((x) => ({
...x,
Icon: Icons[x.title],
})),
{
name: 'File',
title: 'File',
aliases: ['file', 'folder'],
group: 'Media',
icon: <IconFile size={16} />,
hint: 'Insert a file',
execute: (
editor: BlockNoteEditor<
typeof blockSchema,
InlineContentSchema,
StyleSchema
>,
) => {
Icon: IconFile,
onItemClick: () => {
const currentBlock = editor.getTextCursorPosition().block;
editor.insertBlocks(
[
{
@ -34,7 +49,7 @@ export const getSlashMenu = () => {
},
},
],
editor.getTextCursorPosition().block,
currentBlock,
'before',
);
},

View File

@ -1,6 +1,5 @@
import { useCallback, useMemo } from 'react';
import { BlockNoteEditor } from '@blocknote/core';
import { useBlockNote } from '@blocknote/react';
import { ClipboardEvent, useCallback, useMemo } from 'react';
import { useCreateBlockNote } from '@blocknote/react';
import styled from '@emotion/styled';
import { isArray, isNonEmptyString } from '@sniptt/guards';
import { useRecoilCallback, useRecoilState } from 'recoil';
@ -8,6 +7,7 @@ import { Key } from 'ts-key-enum';
import { useDebouncedCallback } from 'use-debounce';
import { v4 } from 'uuid';
import { blockSchema } from '@/activities/blocks/schema';
import { useUpsertActivity } from '@/activities/hooks/useUpsertActivity';
import { activityBodyFamilyState } from '@/activities/states/activityBodyFamilyState';
import { activityTitleHasBeenSetFamilyState } from '@/activities/states/activityTitleHasBeenSetFamilyState';
@ -28,8 +28,6 @@ import { FileFolder, useUploadFileMutation } from '~/generated/graphql';
import { isDefined } from '~/utils/isDefined';
import { isUndefinedOrNull } from '~/utils/isUndefinedOrNull';
import { blockSpecs } from '../blocks/blockSpecs';
import { getSlashMenu } from '../blocks/slashMenu';
import { getFileType } from '../files/utils/getFileType';
import '@blocknote/react/style.css';
@ -121,8 +119,6 @@ export const ActivityBodyEditor = ({
canCreateActivityState(),
);
const slashMenuItems = getSlashMenu();
const [uploadFile] = useUploadFileMutation();
const handleUploadAttachment = async (file: File): Promise<string> => {
@ -216,8 +212,8 @@ export const ActivityBodyEditor = ({
const handleBodyChangeDebounced = useDebouncedCallback(handleBodyChange, 500);
const handleEditorChange = (newEditor: BlockNoteEditor) => {
const newStringifiedBody = JSON.stringify(newEditor.topLevelBlocks) ?? '';
const handleEditorChange = () => {
const newStringifiedBody = JSON.stringify(editor.document) ?? '';
setActivityBody(newStringifiedBody);
@ -238,16 +234,11 @@ export const ActivityBodyEditor = ({
}
}, [activity, activityBody]);
const editor: BlockNoteEditor<typeof blockSpecs> | null = useBlockNote({
const editor = useCreateBlockNote({
initialContent: initialBody,
domAttributes: { editor: { class: 'editor' } },
onEditorContentChange: handleEditorChange,
slashMenuItems,
blockSpecs: blockSpecs,
schema: blockSchema,
uploadFile: handleUploadAttachment,
onEditorReady: (editor: BlockNoteEditor) => {
editor.domElement.addEventListener('paste', handleImagePaste);
},
});
const handleImagePaste = async (event: ClipboardEvent) => {
@ -361,7 +352,7 @@ export const ActivityBodyEditor = ({
const newBlockId = v4();
const newBlock = {
id: newBlockId,
type: 'paragraph',
type: 'paragraph' as const,
content: keyboardEvent.key,
};
editor.insertBlocks([newBlock], blockIdentifier, 'after');
@ -387,6 +378,8 @@ export const ActivityBodyEditor = ({
<BlockEditor
onFocus={handleBlockEditorFocus}
onBlur={handlerBlockEditorBlur}
onPaste={handleImagePaste}
onChange={handleEditorChange}
editor={editor}
/>
</StyledBlockNoteStyledContainer>