Repository navigation
Expand file tree
/
Copy pathrich-plugin-elements.tsx
More file actions
285 lines (283 loc) · 8.36 KB
/
Copy pathrich-plugin-elements.tsx
File metadata and controls
285 lines (283 loc) · 8.36 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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { bilingualLocale } from "@doca/i18n";
import {
createContext,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { Editor, Element, Transforms, type RangeRef } from "slate";
import { HistoryEditor } from "slate-history";
import { ReactEditor, useReadOnly } from "slate-react";
import {
createAtomicInlineExtension,
type CustomElement,
type RichTextEditorHandle,
} from "@smartdoca/slate";
import {
isPluginElementPayload,
type PluginElementPayload,
} from "@smartdoca/plugin-contracts";
import { pluginElementCodec } from "@core/modules/documents/codecs/rich-runtime.js";
import { webPluginRegistry } from "@web/plugins/registry.js";
import { useI18n } from "@web/shared/i18n.js";
import {
ElementBoundary,
ElementContent,
ElementPlaceholder,
PluginElementDialog,
pluginElementState,
usePluginElements,
type ElementDialogSession,
} from "./plugin-elements.js";
import { PackagePlus, Settings2 } from "lucide-react";
const ElementSession = createContext<{
documentId: string;
edit(id: string): void;
} | null>(null);
function RichElementContent({ element }: { element: CustomElement }) {
usePluginElements("rich_text");
const session = useContext(ElementSession),
readOnly = useReadOnly();
const { locale, t } = useI18n();
const payload = element.payload;
const type =
typeof (payload as any)?.type === "string"
? (payload as any).type
: undefined;
const provider = type ? webPluginRegistry.elements.get(type) : undefined;
const state = useMemo(
() => pluginElementState(payload, provider, "rich_text"),
[payload, provider],
);
const abort = useMemo(
() => new AbortController(),
[session?.documentId, element.id, provider],
);
useEffect(() => () => abort.abort(), [abort]);
return (
<span className="plugin-element-inline" data-plugin-element={type}>
<ElementBoundary
key={`${type}:${(payload as any)?.dataVersion}:${webPluginRegistry.elements.snapshot()}`}
type={type}
>
{state === "ready" ? (
<ElementContent
provider={provider!}
payload={payload as unknown as PluginElementPayload}
context={{
documentId: session?.documentId ?? "",
format: "rich_text",
locale: bilingualLocale(locale),
readOnly,
signal: abort.signal,
}}
/>
) : (
<ElementPlaceholder
type={type}
reason={state === "invalid" ? "invalid" : "unsupported"}
/>
)}
</ElementBoundary>
{!readOnly && session && (
<button
type="button"
className="plugin-element-configure"
title={t("editor.element.edit")}
aria-label={t("editor.element.edit")}
onMouseDown={(event) => event.preventDefault()}
onClick={() => session.edit(element.id)}
>
<Settings2 size={13} />
</button>
)}
</span>
);
}
export const pluginElementPlugin = createAtomicInlineExtension({
...pluginElementCodec,
decode: (data, identity) =>
pluginElementCodec.decode(data, identity) as CustomElement,
render: (element) => <RichElementContent element={element} />,
}).plugin;
export function RichPluginElements({
documentId,
handle,
editable,
children,
}: {
documentId: string;
handle: RichTextEditorHandle | null;
editable: boolean;
children: (insert: React.ReactNode) => React.ReactNode;
}) {
const { t } = useI18n();
const providers = usePluginElements("rich_text");
const [session, setSession] = useState<ElementDialogSession | null>(null);
const [range, setRange] = useState<RangeRef | null>(null);
const active = useRef({ documentId, handle, editable });
active.current = { documentId, handle, editable };
const close = () => {
range?.unref();
setRange(null);
setSession(null);
};
useEffect(() => {
if (!editable) close();
}, [editable]);
useEffect(() => {
close();
}, [documentId, handle]);
useEffect(
() => () => {
range?.unref();
},
[range],
);
const live = () => {
if (
!handle ||
!editable ||
!active.current.editable ||
active.current.handle !== handle ||
active.current.documentId !== documentId ||
ReactEditor.isReadOnly(handle.editor)
)
throw Error("Editor unavailable");
return handle.editor;
};
const edit = (id: string) => {
const editor = live();
const find = () =>
[
...Editor.nodes(editor, {
at: [],
match: (node) =>
Element.isElement(node) &&
node.type === "custom:plugin-element" &&
node.id === id,
voids: true,
}),
][0];
const found = find();
if (!found) return;
const payload = (found[0] as CustomElement).payload;
const current = isPluginElementPayload(payload) ? payload : null;
setSession({
type:
typeof (payload as any)?.type === "string"
? (payload as any).type
: "unsupported",
unsupported:
pluginElementState(
payload,
current ? webPluginRegistry.elements.get(current.type) : undefined,
"rich_text",
) !== "ready",
initialData: current?.data,
commit(next) {
live();
const target = find();
if (!target) throw Error("Element removed");
// Do not overwrite a concurrently changed config with the stale form.
if (
JSON.stringify((target[0] as CustomElement).payload) !==
JSON.stringify(payload)
)
throw Error("Element changed");
if (
!current ||
next.dataVersion !== current.dataVersion ||
next.type !== current.type
)
throw Error("Unsupported element version");
HistoryEditor.withNewBatch(editor as HistoryEditor, () =>
Transforms.setNodes(
editor,
{ payload: next, label: next.text },
{ at: target[1], voids: true },
),
);
},
remove() {
live();
const target = find();
if (!target) throw Error("Element removed");
if (
JSON.stringify((target[0] as CustomElement).payload) !==
JSON.stringify(payload)
)
throw Error("Element changed");
HistoryEditor.withNewBatch(editor as HistoryEditor, () =>
Transforms.removeNodes(editor, { at: target[1], voids: true }),
);
},
});
};
const insert = providers.length ? (
<button
type="button"
disabled={!handle || !editable}
title={t("editor.element.insert")}
aria-label={t("editor.element.insert")}
onMouseDown={(event) => {
event.preventDefault();
if (handle?.editor.selection) {
range?.unref();
setRange(
Editor.rangeRef(handle.editor, handle.editor.selection, {
affinity: "inward",
}),
);
}
}}
onClick={() => {
const insertionRange =
range ??
(handle?.editor.selection
? Editor.rangeRef(handle.editor, handle.editor.selection, {
affinity: "inward",
})
: null);
if (!insertionRange?.current) return;
if (insertionRange !== range) setRange(insertionRange);
setSession({
commit(payload) {
const editor = live();
if (!insertionRange.current)
throw Error("Insertion position removed");
ReactEditor.focus(editor);
HistoryEditor.withNewBatch(editor as HistoryEditor, () => {
Transforms.select(editor, insertionRange.current!);
Transforms.insertNodes(editor, {
type: "custom:plugin-element",
id: crypto.randomUUID(),
payload,
label: payload.text,
children: [{ text: "" }],
});
Transforms.move(editor);
});
},
});
}}
>
<PackagePlus size={17} />
</button>
) : null;
return (
<ElementSession.Provider value={{ documentId, edit }}>
{children(insert)}
{session && editable && (
<PluginElementDialog
documentId={documentId}
format="rich_text"
session={session}
close={close}
/>
)}
</ElementSession.Provider>
);
}