-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLexicalAutoEmbedPlugin.tsx.txt
240 lines (222 loc) · 6.56 KB
/
LexicalAutoEmbedPlugin.tsx.txt
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {
CommandListenerPriority,
LexicalNode,
MutationListener,
} from 'lexical';
import {$isLinkNode, AutoLinkNode, LinkNode} from '@lexical/link';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {
LexicalNodeMenuPlugin,
MenuOption,
MenuRenderFn,
} from '@lexical/react/LexicalNodeMenuPlugin';
import {mergeRegister} from '@lexical/utils';
import {
$getNodeByKey,
$getSelection,
COMMAND_PRIORITY_EDITOR,
COMMAND_PRIORITY_LOW,
createCommand,
LexicalCommand,
LexicalEditor,
NodeKey,
TextNode,
} from 'lexical';
import {useCallback, useEffect, useMemo, useState} from 'react';
import * as React from 'react';
export type EmbedMatchResult<TEmbedMatchResult = unknown> = {
url: string;
id: string;
data?: TEmbedMatchResult;
};
export interface EmbedConfig<
TEmbedMatchResultData = unknown,
TEmbedMatchResult = EmbedMatchResult<TEmbedMatchResultData>,
> {
// Used to identify this config e.g. youtube, tweet, google-maps.
type: string;
// Determine if a given URL is a match and return url data.
parseUrl: (
text: string,
) => Promise<TEmbedMatchResult | null> | TEmbedMatchResult | null;
// Create the Lexical embed node from the url data.
insertNode: (editor: LexicalEditor, result: TEmbedMatchResult) => void;
}
export const URL_MATCHER =
/((https?:\/\/(www\.)?)|(www\.))[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/;
export const INSERT_EMBED_COMMAND: LexicalCommand<EmbedConfig['type']> =
createCommand('INSERT_EMBED_COMMAND');
export class AutoEmbedOption extends MenuOption {
title: string;
onSelect: (targetNode: LexicalNode | null) => void;
constructor(
title: string,
options: {
onSelect: (targetNode: LexicalNode | null) => void;
},
) {
super(title);
this.title = title;
this.onSelect = options.onSelect.bind(this);
}
}
type LexicalAutoEmbedPluginProps<TEmbedConfig extends EmbedConfig> = {
embedConfigs: Array<TEmbedConfig>;
onOpenEmbedModalForConfig: (embedConfig: TEmbedConfig) => void;
getMenuOptions: (
activeEmbedConfig: TEmbedConfig,
embedFn: () => void,
dismissFn: () => void,
) => Array<AutoEmbedOption>;
menuRenderFn: MenuRenderFn<AutoEmbedOption>;
menuCommandPriority?: CommandListenerPriority;
};
export function LexicalAutoEmbedPlugin<TEmbedConfig extends EmbedConfig>({
embedConfigs,
onOpenEmbedModalForConfig,
getMenuOptions,
menuRenderFn,
menuCommandPriority = COMMAND_PRIORITY_LOW,
}: LexicalAutoEmbedPluginProps<TEmbedConfig>): JSX.Element | null {
const [editor] = useLexicalComposerContext();
const [nodeKey, setNodeKey] = useState<NodeKey | null>(null);
const [activeEmbedConfig, setActiveEmbedConfig] =
useState<TEmbedConfig | null>(null);
const reset = useCallback(() => {
setNodeKey(null);
setActiveEmbedConfig(null);
}, []);
const checkIfLinkNodeIsEmbeddable = useCallback(
async (key: NodeKey) => {
const url = editor.getEditorState().read(function () {
const linkNode = $getNodeByKey(key);
if ($isLinkNode(linkNode)) {
return linkNode.getURL();
}
});
if (url === undefined) {
return;
}
for (const embedConfig of embedConfigs) {
const urlMatch = await Promise.resolve(embedConfig.parseUrl(url));
if (urlMatch != null) {
setActiveEmbedConfig(embedConfig);
setNodeKey(key);
}
}
},
[editor, embedConfigs],
);
useEffect(() => {
const listener: MutationListener = (
nodeMutations,
{updateTags, dirtyLeaves},
) => {
for (const [key, mutation] of nodeMutations) {
if (
mutation === 'created' &&
updateTags.has('paste') &&
dirtyLeaves.size <= 3
) {
checkIfLinkNodeIsEmbeddable(key);
} else if (key === nodeKey) {
reset();
}
}
};
return mergeRegister(
...[LinkNode, AutoLinkNode].map((Klass) =>
editor.registerMutationListener(Klass, (...args) => listener(...args), {
skipInitialization: true,
}),
),
);
}, [checkIfLinkNodeIsEmbeddable, editor, embedConfigs, nodeKey, reset]);
useEffect(() => {
return editor.registerCommand(
INSERT_EMBED_COMMAND,
(embedConfigType: TEmbedConfig['type']) => {
const embedConfig = embedConfigs.find(
({type}) => type === embedConfigType,
);
if (embedConfig) {
onOpenEmbedModalForConfig(embedConfig);
return true;
}
return false;
},
COMMAND_PRIORITY_EDITOR,
);
}, [editor, embedConfigs, onOpenEmbedModalForConfig]);
const embedLinkViaActiveEmbedConfig = useCallback(
async function () {
if (activeEmbedConfig != null && nodeKey != null) {
const linkNode = editor.getEditorState().read(() => {
const node = $getNodeByKey(nodeKey);
if ($isLinkNode(node)) {
return node;
}
return null;
});
if ($isLinkNode(linkNode)) {
const result = await Promise.resolve(
activeEmbedConfig.parseUrl(linkNode.__url),
);
if (result != null) {
editor.update(() => {
if (!$getSelection()) {
linkNode.selectEnd();
}
activeEmbedConfig.insertNode(editor, result);
if (linkNode.isAttached()) {
linkNode.remove();
}
});
}
}
}
},
[activeEmbedConfig, editor, nodeKey],
);
const options = useMemo(() => {
return activeEmbedConfig != null && nodeKey != null
? getMenuOptions(activeEmbedConfig, embedLinkViaActiveEmbedConfig, reset)
: [];
}, [
activeEmbedConfig,
embedLinkViaActiveEmbedConfig,
getMenuOptions,
nodeKey,
reset,
]);
const onSelectOption = useCallback(
(
selectedOption: AutoEmbedOption,
targetNode: TextNode | null,
closeMenu: () => void,
) => {
editor.update(() => {
selectedOption.onSelect(targetNode);
closeMenu();
});
},
[editor],
);
return nodeKey != null ? (
<LexicalNodeMenuPlugin<AutoEmbedOption>
nodeKey={nodeKey}
onClose={reset}
onSelectOption={onSelectOption}
options={options}
menuRenderFn={menuRenderFn}
commandPriority={menuCommandPriority}
/>
) : null;
}