-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathSuperDocEditor.tsx
More file actions
278 lines (250 loc) · 9 KB
/
SuperDocEditor.tsx
File metadata and controls
278 lines (250 loc) · 9 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
import {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState,
type CSSProperties,
type ForwardedRef,
} from 'react';
import { useStableId, useMemoByValue } from './utils';
import type {
CallbackProps,
DocumentMode,
SuperDocEditorProps,
SuperDocInstance,
SuperDocRef,
SuperDocReadyEvent,
SuperDocEditorCreateEvent,
SuperDocEditorUpdateEvent,
SuperDocTransactionEvent,
SuperDocContentErrorEvent,
SuperDocExceptionEvent,
} from './types';
/**
* SuperDocEditor - React wrapper component for SuperDoc
*
* Provides a component-based API with proper lifecycle management
* and React Strict Mode compatibility. Container divs are always
* rendered (hidden until initialized) so SuperDoc can mount into
* them on the first client-side effect.
*/
function SuperDocEditorInner(props: SuperDocEditorProps, ref: ForwardedRef<SuperDocRef>) {
const [hasError, setHasError] = useState(false);
// Destructure React-specific props and key rebuild triggers
const {
// React-specific
id,
renderLoading,
hideToolbar = false,
contained = false,
className,
style,
// Callbacks (stored in ref to avoid triggering rebuilds)
onReady,
onEditorCreate,
onEditorDestroy,
onEditorUpdate,
onTransaction,
onContentError,
onException,
// Key props that trigger rebuild when changed
document: documentProp,
user: userProp,
users: usersProp,
modules,
// All other props passed through
...restProps
} = props;
// Apply defaults
const documentMode = props.documentMode ?? 'editing';
const role = props.role ?? 'editor';
// `user` and `users` are memoized by value so inline literals don't
// trigger a rebuild. `modules` stays on reference identity — it can
// carry functions and live objects (e.g. `collaboration.provider`)
// that a consumer may intentionally swap. See SD-2635.
const user = useMemoByValue(userProp);
const users = useMemoByValue(usersProp);
const instanceRef = useRef<SuperDocInstance | null>(null);
const toolbarContainerRef = useRef<HTMLDivElement | null>(null);
// Generate stable IDs (useStableId returns the same value across re-renders)
const generatedId = useStableId();
const baseId = id ?? `superdoc${generatedId}`;
const containerId = baseId;
const toolbarId = `${baseId}-toolbar`;
const [isLoading, setIsLoading] = useState(true);
// Store callbacks in refs to avoid triggering effect on callback changes
const callbacksRef = useRef<CallbackProps>({
onReady,
onEditorCreate,
onEditorDestroy,
onEditorUpdate,
onTransaction,
onContentError,
onException,
});
// Update callback refs when props change
useEffect(() => {
callbacksRef.current = {
onReady,
onEditorCreate,
onEditorDestroy,
onEditorUpdate,
onTransaction,
onContentError,
onException,
};
}, [onReady, onEditorCreate, onEditorDestroy, onEditorUpdate, onTransaction, onContentError, onException]);
// Queue mode changes that happen during init
const pendingModeRef = useRef<DocumentMode | null>(null);
const isInitializingRef = useRef(false);
// Track documentMode changes and apply imperatively
const prevDocumentModeRef = useRef(documentMode);
useEffect(() => {
if (prevDocumentModeRef.current !== documentMode) {
if (instanceRef.current) {
// Instance exists, apply immediately
instanceRef.current.setDocumentMode(documentMode);
} else if (isInitializingRef.current) {
// Instance is initializing, queue the mode change
pendingModeRef.current = documentMode;
}
}
prevDocumentModeRef.current = documentMode;
}, [documentMode]);
// Expose ref methods - simplified API with just getInstance()
useImperativeHandle(
ref,
() => ({
getInstance: () => instanceRef.current,
}),
[],
);
// Main effect: create and destroy SuperDoc instance
useEffect(() => {
// Reset states when document changes
setIsLoading(true);
setHasError(false);
isInitializingRef.current = true;
let destroyed = false;
let instance: SuperDocInstance | null = null;
const initSuperDoc = async () => {
try {
// Dynamic import for SSR safety
const modulePath = 'superdoc';
const superdocModule = await import(/* @vite-ignore */ modulePath);
const SuperDoc = superdocModule.SuperDoc as new (config: Record<string, unknown>) => SuperDocInstance;
// Check if we were destroyed while loading
if (destroyed) return;
// Build configuration - pass through all props
const superdocConfig = {
...restProps,
selector: `#${CSS.escape(containerId)}`,
// Use internal toolbar container unless hideToolbar is true
...(!hideToolbar && toolbarContainerRef.current ? { toolbar: `#${CSS.escape(toolbarId)}` } : {}),
documentMode,
role,
contained,
...(documentProp != null ? { document: documentProp } : {}),
...(user ? { user } : {}),
...(users ? { users } : {}),
...(modules ? { modules } : {}),
// Wire up callbacks with lifecycle guards
onReady: (event: SuperDocReadyEvent) => {
if (!destroyed) {
setIsLoading(false);
isInitializingRef.current = false;
// Apply any pending mode changes
if (pendingModeRef.current && pendingModeRef.current !== documentMode) {
event.superdoc.setDocumentMode(pendingModeRef.current);
pendingModeRef.current = null;
}
callbacksRef.current.onReady?.(event);
}
},
onEditorCreate: (event: SuperDocEditorCreateEvent) => {
if (!destroyed) {
callbacksRef.current.onEditorCreate?.(event);
}
},
onEditorDestroy: () => {
if (!destroyed) {
callbacksRef.current.onEditorDestroy?.();
}
},
onEditorUpdate: (event: SuperDocEditorUpdateEvent) => {
if (!destroyed) {
callbacksRef.current.onEditorUpdate?.(event);
}
},
onTransaction: (event: SuperDocTransactionEvent) => {
if (!destroyed) {
callbacksRef.current.onTransaction?.(event);
}
},
onContentError: (event: SuperDocContentErrorEvent) => {
if (!destroyed) {
callbacksRef.current.onContentError?.(event);
}
},
onException: (event: SuperDocExceptionEvent) => {
if (!destroyed) {
callbacksRef.current.onException?.(event);
}
},
};
instance = new SuperDoc(superdocConfig) as SuperDocInstance;
instanceRef.current = instance;
} catch (error) {
if (!destroyed) {
isInitializingRef.current = false;
setIsLoading(false);
setHasError(true);
console.error('[SuperDocEditor] Failed to initialize SuperDoc:', error);
callbacksRef.current.onException?.({ error: error as Error });
}
}
};
initSuperDoc();
// Cleanup function
return () => {
isInitializingRef.current = false;
pendingModeRef.current = null;
if (instance) {
instance.destroy();
instanceRef.current = null;
}
destroyed = true;
};
// Only these props trigger a full rebuild. Other props (rulers, etc.) are
// initial values — use getInstance() methods to change them at runtime.
// restProps is intentionally excluded to avoid rebuilds on every render.
// documentMode is handled separately via setDocumentMode() for efficiency.
}, [documentProp, user, users, modules, role, hideToolbar, contained, containerId, toolbarId]);
const wrapperClassName = ['superdoc-wrapper', className].filter(Boolean).join(' ');
const hideWhenLoading: CSSProperties | undefined = isLoading ? { display: 'none' } : undefined;
const wrapperStyle: CSSProperties = {
...style,
...(contained && { display: 'flex', flexDirection: 'column' as const }),
};
return (
<div className={wrapperClassName} style={wrapperStyle}>
{!hideToolbar && (
<div ref={toolbarContainerRef} id={toolbarId} className='superdoc-toolbar-container' style={hideWhenLoading} />
)}
<div
id={containerId}
className='superdoc-editor-container'
style={{ ...hideWhenLoading, ...(contained && { flex: 1, minHeight: 0 }) }}
/>
{isLoading && !hasError && renderLoading && <div className='superdoc-loading-container'>{renderLoading()}</div>}
{hasError && <div className='superdoc-error-container'>Failed to load editor. Check console for details.</div>}
</div>
);
}
/**
* SuperDocEditor component with forwardRef - Initializes SuperDoc instance and handles cleanup.
*/
export const SuperDocEditor = forwardRef<SuperDocRef, SuperDocEditorProps>(SuperDocEditorInner);
SuperDocEditor.displayName = 'SuperDocEditor';
export default SuperDocEditor;