forked from TypeCellOS/BlockNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSelectedBlocks.ts
More file actions
43 lines (37 loc) · 1.13 KB
/
useSelectedBlocks.ts
File metadata and controls
43 lines (37 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import {
Block,
BlockNoteEditor,
BlockSchema,
InlineContentSchema,
StyleSchema,
} from "@blocknote/core";
import { useState } from "react";
import { useBlockNoteContext } from "../editor/BlockNoteContext.js";
import { useEditorContentOrSelectionChange } from "./useEditorContentOrSelectionChange.js";
export function useSelectedBlocks<
BSchema extends BlockSchema,
ISchema extends InlineContentSchema,
SSchema extends StyleSchema
>(editor?: BlockNoteEditor<BSchema, ISchema, SSchema>) {
const editorContext = useBlockNoteContext<BSchema, ISchema, SSchema>();
if (!editor) {
editor = editorContext?.editor;
}
if (!editor) {
throw new Error(
"'editor' is required, either from BlockNoteContext or as a function argument"
);
}
const e = editor;
const [selectedBlocks, setSelectedBlocks] = useState<
Block<BSchema, ISchema, SSchema>[]
>(() => e.getSelection()?.blocks || [e.getTextCursorPosition().block]);
useEditorContentOrSelectionChange(
() =>
setSelectedBlocks(
e.getSelection()?.blocks || [e.getTextCursorPosition().block]
),
e
);
return selectedBlocks;
}