-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcanvas_editor_hook.ts
More file actions
357 lines (321 loc) · 9.68 KB
/
canvas_editor_hook.ts
File metadata and controls
357 lines (321 loc) · 9.68 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import type { CanonizerOptions, CanvasEditorMode } from 'openchemlib';
import {
Canonizer,
CanvasEditor,
Molecule,
Reaction,
ReactionEncoder,
SmilesParser,
} from 'openchemlib';
import type { RefObject } from 'react';
import { useEffect, useLayoutEffect, useRef } from 'react';
export interface CanvasEditorOnChangeMoleculeGetIdcodeOptions {
/**
* Used to initialize the canonizer.
*/
canonizerOptions?: CanonizerOptions;
/**
* If keepPositionAndScale==false, then coordinate encoding will be relative
* (i.e. scale and absolute positions get lost during the encoding).
* Otherwise, the encoding retains scale and absolute positions.
* @default false
*/
keepPositionAndScale?: boolean;
}
export interface CanvasEditorOnChangeMolecule {
/**
* Returns the molecule encoded as an idcode (with coordinates).
*/
getIdcode: (options?: CanvasEditorOnChangeMoleculeGetIdcodeOptions) => string;
/**
* Returns the molecule encoded as a molfile V2000.
*/
getMolfile: () => string;
/**
* Returns the molecule encoded as a molfile V3000.
*/
getMolfileV3: () => string;
/**
* Returns the molecule encoded as a SMILES.
*/
getSmiles: () => string;
/**
* Returns a copy of the current molecule.
*/
getMolecule: () => Molecule;
}
export interface CanvasEditorOnChangeReaction {
/**
* Returns the reaction encoded as an idcode (with coordinates).
*/
getIdcode: () => string;
/**
* Returns the reaction encoded as a RXNFile V2000.
*/
getRxn: () => string;
/**
* Returns the reaction encoded as a RXNFile V3000.
*/
getRxnV3: () => string;
/**
* Returns the reaction encoded as a SMILES.
*/
getSmiles: () => string;
}
export type CanvasEditorInputFormat = 'idcode' | 'molfile' | 'smiles';
export interface UseCanvasEditorBaseOptions {
/**
* Mode used to initialise the editor.
*
* Changing this will force the editor to be reinitialised and lose its
* internal state.
*/
initialMode?: CanvasEditorMode;
/**
* A read-only editor can be used to render structures or reactions.
*
* Changing this will force the editor to be reinitialised and lose its
* internal state.
* @default false
*/
readOnly?: boolean;
/**
* Format of the input value.
* 'molfile' supports both V2000 and V3000.
* For reactions encoded as RXN, use 'molfile'.
* @default 'idcode'
*/
inputFormat?: CanvasEditorInputFormat;
/**
* Input value to initialise the structure.
*
* Changing this value will have the effect of replacing the structure being edited,
* but this should not be done continuously in reaction to the `onChange` event
* like you would with a controlled component.
* The editor manages its state internally, and replacing the structure will
* reset the coordinates and likely move the structure everytime it is changed.
* @default ''
*/
inputValue?: string;
/**
* Whether the edited structure is a fragment or regular structure.
* @default false
*/
fragment?: boolean;
}
export type OnChangeMoleculeCallback = (
event: CanvasEditorOnChangeMolecule,
) => void;
export interface UseCanvasEditorMoleculeOptions
extends UseCanvasEditorBaseOptions {
initialMode?: 'molecule';
/**
* Callback which is called whenever the molecule is changed by a user action
* in the editor.
*
* The event methods available in the callback should be called synchronously,
* otherwise they might reflect a future state of the editor.
*/
onChange?: OnChangeMoleculeCallback;
}
export type OnChangeReactionCallback = (
event: CanvasEditorOnChangeReaction,
) => void;
export interface UseCanvasEditorReactionOptions
extends UseCanvasEditorBaseOptions {
initialMode: 'reaction';
/**
* Callback which is called whenever the reaction is changed by a user action
* in the editor.
*
* The event methods available in the callback should be called synchronously,
* otherwise they might reflect a future state of the editor.
*/
onChange?: OnChangeReactionCallback;
}
type OnChangeCallback = OnChangeMoleculeCallback | OnChangeReactionCallback;
/**
* Initialize a CanvasEditor and return a ref to the DOM element on which it
* will be attached.
* @param options - Editor options
* @returns The element ref.
*/
export function useCanvasEditor(
options: UseCanvasEditorMoleculeOptions | UseCanvasEditorReactionOptions = {},
) {
const {
initialMode = 'molecule',
readOnly = false,
inputFormat = 'idcode',
inputValue = '',
fragment = false,
onChange,
} = options;
const elementRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<CanvasEditor | null>(null);
useInitialiseEditor(elementRef, editorRef, readOnly, initialMode);
useOnChangeListeners(editorRef, onChange);
useUpdateStructure(editorRef, inputFormat, inputValue);
useUpdateFragment(editorRef, fragment);
return { elementRef };
}
function useInitialiseEditor(
elementRef: RefObject<HTMLDivElement | null>,
editorRef: RefObject<CanvasEditor | null>,
readOnly: boolean,
initialMode: CanvasEditorMode,
): void {
useLayoutEffect(() => {
if (!elementRef.current) {
return;
}
elementRef.current.innerHTML = '';
const editor = new CanvasEditor(elementRef.current, {
readOnly,
initialMode,
});
editorRef.current = editor;
return () => {
editor.removeOnChangeListener();
editor.destroy();
};
}, [editorRef, elementRef, readOnly, initialMode]);
}
function useOnChangeListeners(
editorRef: RefObject<CanvasEditor | null>,
onChange: OnChangeCallback | undefined,
) {
const callbacksRef = useRef<{ onChange: typeof onChange }>({
onChange,
});
// Register the main change handler.
useEffect(() => {
const editor = editorRef.current;
if (!editor || editor.isDestroyed) return;
const moleculeChangeApi = getMoleculeChangeApi(editor);
const reactionChangeApi = getReactionChangeApi(editor);
editor.setOnChangeListener((event) => {
if (
event.isUserEvent &&
event.type === 'molecule' &&
callbacksRef.current.onChange
) {
const currentMode = editor.getMode();
if (currentMode === 'molecule') {
// @ts-expect-error Cannot be safe as onChange type depends on the mode.
callbacksRef.current.onChange(moleculeChangeApi);
} else {
// @ts-expect-error Cannot be safe as onChange type depends on the mode.
callbacksRef.current.onChange(reactionChangeApi);
}
}
});
return () => {
if (!editor.isDestroyed) {
editor.removeOnChangeListener();
}
};
}, [editorRef]);
// Update user callbacks.
useEffect(() => {
callbacksRef.current.onChange = onChange;
}, [onChange]);
}
function getMoleculeChangeApi(
editor: CanvasEditor,
): CanvasEditorOnChangeMolecule {
return {
getIdcode(options: CanvasEditorOnChangeMoleculeGetIdcodeOptions = {}) {
const { canonizerOptions, keepPositionAndScale = false } = options;
const canonizer = new Canonizer(editor.getMolecule(), canonizerOptions);
const idCode = canonizer.getIDCode();
const coordinates = canonizer.getEncodedCoordinates(keepPositionAndScale);
return `${idCode} ${coordinates}`;
},
getMolfile() {
return editor.getMolecule().toMolfile();
},
getMolfileV3() {
return editor.getMolecule().toMolfileV3();
},
getSmiles() {
return editor.getMolecule().toIsomericSmiles();
},
getMolecule() {
return editor.getMolecule().getCompactCopy();
},
};
}
function getReactionChangeApi(
editor: CanvasEditor,
): CanvasEditorOnChangeReaction {
return {
getIdcode() {
return ReactionEncoder.encode(editor.getReaction()) ?? '';
},
getRxn(programName?: string) {
return editor.getReaction().toRxn({ programName });
},
getRxnV3(programName?: string) {
return editor.getReaction().toRxnV3({ programName });
},
getSmiles() {
return editor.getReaction().toSmiles();
},
};
}
function useUpdateStructure(
editorRef: RefObject<CanvasEditor | null>,
inputFormat: CanvasEditorInputFormat,
inputValue: string,
): void {
useEffect(() => {
const editor = editorRef.current;
if (!editor || editor.isDestroyed) return;
const currentMode = editor.getMode();
if (inputFormat === 'idcode') {
if (currentMode === 'molecule') {
editor.setMolecule(Molecule.fromIDCode(inputValue));
} else {
const reaction =
ReactionEncoder.decode(inputValue) ?? Reaction.create();
editor.setReaction(reaction);
}
} else if (inputFormat === 'molfile') {
if (currentMode === 'molecule') {
editor.setMolecule(Molecule.fromMolfile(inputValue));
} else {
editor.setReaction(Reaction.fromRxn(inputValue));
}
} else if (inputFormat === 'smiles') {
if (currentMode === 'molecule') {
editor.setMolecule(Molecule.fromSmiles(inputValue));
} else {
editor.setReaction(
new SmilesParser({ singleDotSeparator: true }).parseReaction(
inputValue,
),
);
}
}
}, [editorRef, inputFormat, inputValue]);
}
function useUpdateFragment(
editorRef: RefObject<CanvasEditor | null>,
fragment: boolean,
): void {
useEffect(() => {
const editor = editorRef.current;
if (!editor || editor.isDestroyed) return;
const currentMode = editor.getMode();
if (currentMode === 'molecule') {
const molecule = editor.getMolecule();
molecule.setFragment(fragment);
editor.setMolecule(molecule);
} else {
const reaction = editor.getReaction();
reaction.setFragment(fragment);
editor.setReaction(reaction);
}
}, [editorRef, fragment]);
}