-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsvg_editor.tsx
More file actions
326 lines (281 loc) · 9.18 KB
/
svg_editor.tsx
File metadata and controls
326 lines (281 loc) · 9.18 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
import type { Molecule } from 'openchemlib';
import type {
FormEvent,
KeyboardEvent as ReactKeyboardEvent,
MouseEvent,
} from 'react';
import { useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { useRefUpToDate } from '../../hooks/use_ref_up_to_date.js';
import { useCSS } from '../../styling/use_css.ts';
import type { BaseEditorProps } from '../types.js';
import {
isCleanEvent,
isQuickNumberingEvent,
} from './editor/events_predicate.js';
import {
getNextCustomLabel,
getPreviousCustomLabel,
moleculeCustomLabels,
splitCustomLabels,
} from './editor/quick_numbering.js';
import type { State } from './editor/reducer.js';
import { stateReducer } from './editor/reducer.js';
import { useHighlight } from './editor/use_highlight.js';
import { atomLabelEditCss, greekLetters, primes } from './svg_editor.css.ts';
import type { SvgRendererProps } from './svg_renderer.js';
import { SvgRenderer } from './svg_renderer.js';
export interface SvgEditorProps
extends SvgRendererProps,
BaseEditorProps<Molecule> {}
const initialState: State = { mode: 'view' };
/**
* A component that renders an SVG editor for a given molecule.
* Under the hood it uses the SvgRenderer component to display the molecule and catch interactions.
* @param props - The props for the SvgEditor component.
* @returns JSX.Element
*/
export function SvgEditor(props: SvgEditorProps) {
const {
molecule,
onChange,
atomHighlightStrategy = 'editor-state',
atomHighlight: atomHighlightProp,
...svgProps
} = props;
const [state, dispatch] = useReducer(stateReducer, initialState);
const { atomHighlight, setAtomHighlight, atomsHighlight } = useHighlight({
atomHighlight: atomHighlightProp,
atomHighlightStrategy,
});
const [lastInputLabel, setLastInputLabel] = useState('');
const atomRef = useRefUpToDate(atomHighlight);
const onChangeRef = useRefUpToDate(onChange);
const lastInputLabelRef = useRefUpToDate(lastInputLabel);
useEffect(() => {
if (state.mode !== 'view') return;
function onClean(event: KeyboardEvent) {
if (!isCleanEvent(event)) return;
if (atomRef.current === -1) return;
event.preventDefault();
const atomId = atomRef.current;
const newMolecule = molecule.getCompactCopy();
const rawLabel = molecule.getAtomCustomLabel(atomId);
if (rawLabel) {
const label = rawLabel.replaceAll(']', '');
const previousLabel = getPreviousCustomLabel(label);
if (previousLabel) {
setLastInputLabel(previousLabel);
}
}
newMolecule.setAtomCustomLabel(atomId, null);
onChangeRef.current(newMolecule);
}
function onQuickNumbering(event: KeyboardEvent) {
if (!isQuickNumberingEvent(event)) return;
if (atomRef.current === -1) return;
event.preventDefault(); // numbering shortcut may be used in browser shortcuts
const atomId = atomRef.current;
const lastInputLabel = lastInputLabelRef.current;
const newMolecule = molecule.getCompactCopy();
const existingLabels = splitCustomLabels(
moleculeCustomLabels(newMolecule),
);
const nextLabel = getNextCustomLabel(lastInputLabel, existingLabels);
newMolecule.setAtomCustomLabel(atomId, `]${nextLabel}`);
setLastInputLabel(nextLabel);
onChangeRef.current(newMolecule);
}
document.addEventListener('keydown', onClean);
document.addEventListener('keydown', onQuickNumbering);
return () => {
document.removeEventListener('keydown', onClean);
document.removeEventListener('keydown', onQuickNumbering);
};
}, [state, molecule, atomRef, onChangeRef, lastInputLabelRef]);
function onAtomClick(atomId: number, event: MouseEvent<SVGElement>) {
props.onAtomClick?.(atomId, event);
if (event.defaultPrevented) return;
dispatch({ type: 'startEdit', atomId, event });
}
function onAtomEnter(atomId: number, event: MouseEvent<SVGElement>) {
props.onAtomEnter?.(atomId, event);
if (event.defaultPrevented) return;
setAtomHighlight(atomId);
}
function onAtomLeave(atomId: number, event: MouseEvent<SVGElement>) {
props.onAtomLeave?.(atomId, event);
if (event.defaultPrevented) return;
setAtomHighlight(-1);
}
const defaultAtomLabel = useMemo(() => {
if (state.mode !== 'atom-label-edit') return '';
const label = molecule.getAtomCustomLabel(state.atomId) ?? '';
return label.replaceAll(']', '');
}, [state, molecule]);
function onAtomLabelSubmit(newLabel: string) {
if (state.mode !== 'atom-label-edit') return;
newLabel = newLabel.replaceAll(']', '');
const newMolecule = molecule.getCompactCopy();
if (newLabel) {
newMolecule.setAtomCustomLabel(state.atomId, `]${newLabel}`);
setLastInputLabel(newLabel);
} else {
newMolecule.setAtomCustomLabel(state.atomId, null);
}
onChange(newMolecule);
dispatch({ type: 'stopEdit' });
}
return (
<div style={{ position: 'relative' }}>
<SvgRenderer
{...svgProps}
molecule={molecule}
atomHighlight={atomsHighlight}
onAtomEnter={onAtomEnter}
onAtomLeave={onAtomLeave}
onAtomClick={onAtomClick}
/>
{state.mode === 'atom-label-edit' && (
<AtomLabelEditForm
key={defaultAtomLabel}
defaultValue={defaultAtomLabel}
formCoords={state.formCoords}
onSubmit={onAtomLabelSubmit}
onCancel={() => dispatch({ type: 'stopEdit' })}
/>
)}
</div>
);
}
interface AtomLabelEditFormProps {
defaultValue: string;
formCoords: { x: number; y: number };
onSubmit: (value: string) => void;
onCancel: () => void;
}
function AtomLabelEditForm(props: AtomLabelEditFormProps) {
const { defaultValue, formCoords, onSubmit, onCancel } = props;
function onFormSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
event.stopPropagation();
const formData = new FormData(event.currentTarget);
const value = formData.get('label') as string;
onSubmit(value);
}
function onKeyDown(event: ReactKeyboardEvent<HTMLFormElement>) {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopPropagation();
onCancel();
}
function onCancelClick(event: MouseEvent<HTMLButtonElement>) {
event.preventDefault();
event.stopPropagation();
onCancel();
}
const formRef = useRef<HTMLFormElement>(null);
const onCancelRef = useRef(onCancel);
useEffect(() => {
onCancelRef.current = onCancel;
});
useEffect(() => {
function onClickOutside(event: PointerEvent) {
const form = formRef.current;
if (!form) return;
if (form === event.currentTarget) return;
if (form.contains(event.target as HTMLElement)) return;
onCancelRef.current();
}
// It seems mounting the form is fast enough to catch the click event that
// triggered the edit mode.
// To avoid this we delay the binding of the event
// handler to the next event loop iteration.
const timeoutId = setTimeout(
() => document.addEventListener('click', onClickOutside),
0,
);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('click', onClickOutside);
};
}, []);
function onShortcut(event: MouseEvent<HTMLButtonElement>) {
event.preventDefault();
event.stopPropagation();
if (!formRef.current) return;
const form = formRef.current;
const input = form.querySelector('input[type="text"]') as HTMLInputElement;
if (!input) return;
const value = event.currentTarget.textContent.trim();
input.setRangeText(
value,
input.selectionStart ?? 0,
input.selectionEnd ?? input.value.length,
'end',
);
input.focus();
}
useCSS(atomLabelEditCss);
return (
<form
ref={formRef}
onSubmit={onFormSubmit}
onKeyDown={onKeyDown}
className="react-ocl react-ocl-atom-label-edit"
style={{ top: formCoords.y, left: formCoords.x }}
>
<input
className="react-ocl"
style={{ gridArea: 'input' }}
type="text"
name="label"
defaultValue={defaultValue}
size={5}
autoFocus
ref={autoSelectText}
/>
<button
className="react-ocl"
style={{ gridArea: 'submit' }}
type="submit"
aria-label="Submit"
>
✔️
</button>
<button
className="react-ocl"
style={{ gridArea: 'cancel' }}
type="button"
aria-label="Cancel"
onClick={onCancelClick}
>
❌
</button>
{Object.entries(greekLetters).map(([charName, greekChar]) => (
<button
className="react-ocl"
key={charName}
type="submit"
style={{ gridArea: charName }}
onClick={onShortcut}
>
{greekChar}
</button>
))}
{Object.entries(primes).map(([primeName, primeChar]) => (
<button
className="react-ocl"
key={primeName}
type="submit"
style={{ gridArea: primeName }}
onClick={onShortcut}
>
{primeChar}
</button>
))}
</form>
);
}
function autoSelectText(node: HTMLInputElement | null) {
node?.select();
}