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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
|
import { IReactionDisposer, action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { observer } from 'mobx-react';
import { OverlayView } from '../../OverlayView';
import { DocumentIconContainer } from '../../nodes/DocumentIcon';
import React, { FormEvent } from 'react';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { FieldType, ObjectField } from '../../../../fields/ObjectField';
import { Doc } from '../../../../fields/Doc';
import { DocumentView } from '../../nodes/DocumentView';
import DOMPurify from 'dompurify';
/**
* The SchemaCellField renders text in schema cells while the user is editing, and updates the
* contents of the field based on user input. It handles some cell-side logic for equations, such
* as how equations are broken up within the text.
*
* The current implementation parses innerHTML to create spans based on the text in the cell.
* A more robust/safer approach would directly add elements in the react structure, but this
* has been challenging to implement.
*/
export interface SchemaCellFieldProps {
Doc: Doc;
contents: FieldType | undefined;
fieldContents?: FieldViewProps;
editing?: boolean;
oneLine?: boolean;
fieldKey: string;
// eslint-disable-next-line no-use-before-define
refSelectModeInfo: { enabled: boolean; currEditing: SchemaCellField | undefined };
highlightCells?: (text: string) => void;
GetValue(): string | undefined;
SetValue(value: string, shiftDown?: boolean, enterKey?: boolean): boolean;
getCells: (text: string) => HTMLDivElement[] | [];
}
@observer
export class SchemaCellField extends ObservableReactComponent<SchemaCellFieldProps> {
private _disposers: { [name: string]: IReactionDisposer } = {};
private _inputref: HTMLDivElement | null = null;
private _unrenderedContent: string = '';
_overlayDisposer?: () => void;
@observable _editing: boolean = false;
@observable _displayedContent = '';
@observable _inCellSelectMode: boolean = false;
@observable _dependencyMessageShown: boolean = false;
constructor(props: SchemaCellFieldProps) {
super(props);
makeObservable(this);
setTimeout(() => {
this._unrenderedContent = this._props.GetValue() ?? '';
this.setContent(this._unrenderedContent);
}); //must be moved to end of batch or else other docs aren't loaded, so render as d-1 in function
}
get docIndex(){return DocumentView.getDocViewIndex(this._props.Doc);} // prettier-ignore
get selfRefPattern() {
return `d${this.docIndex}.${this._props.fieldKey}`;
}
@computed get lastCharBeforeCursor() {
const pos = this.cursorPosition;
const content = this._unrenderedContent;
const text = this._unrenderedContent.substring(0, pos ?? content.length);
for (let i = text.length - 1; i > 0; --i) {
if (text.charCodeAt(i) !== 160 && text.charCodeAt(i) !== 32) {
return text[i];
}
}
return null;
}
@computed get refSelectConditionMet() {
const char = this.lastCharBeforeCursor;
return char === '+' || char === '*' || char === '/' || char === '%' || char === '=';
}
componentDidMount(): void {
this._unrenderedContent = this._props.GetValue() ?? '';
this.setContent(this._unrenderedContent, true);
this._disposers.editing = reaction(
() => this._editing,
editing => {
if (editing) {
this.setContent((this._unrenderedContent = this._props.GetValue() ?? ''));
this.setupRefSelect(this.refSelectConditionMet);
} else {
this._overlayDisposer?.();
this._overlayDisposer = undefined;
this._props.highlightCells?.('');
this.setupRefSelect(false);
}
},
{ fireImmediately: true }
);
this._disposers.fieldUpdate = reaction(
() => this._props.GetValue(),
fieldVal => {
this._unrenderedContent = fieldVal ?? '';
this._editing && this.finalizeEdit(false, false, false);
}
);
}
componentDidUpdate(prevProps: Readonly<SchemaCellFieldProps>) {
super.componentDidUpdate(prevProps);
if (this._editing && this._props.editing === false) {
this.finalizeEdit(false, true, false);
} else
runInAction(() => {
if (this._props.editing !== undefined) this._editing = this._props.editing;
});
}
_unmounted = false;
componentWillUnmount(): void {
this._unmounted = true;
this._overlayDisposer?.();
Object.values(this._disposers).forEach(disposer => disposer?.());
this.finalizeEdit(false, true, false);
}
generateSpan = (text: string, cell: HTMLDivElement | undefined) => {
const selfRef = text === this.selfRefPattern;
return `<span style="text-decoration: ${selfRef ? 'underline' : 'none'}; text-decoration-color: red; color: ${selfRef ? 'gray' : cell?.style.borderTop.replace('2px solid', '')}">${text}</span>`;
};
makeSpans = (content: string) => {
let chunkedText = content;
const pattern = /(this|d(\d+))\.(\w+)/g;
const matches: string[] = [];
let match: RegExpExecArray | null;
const cells: Map<string, HTMLDivElement> = new Map();
while ((match = pattern.exec(content)) !== null) {
const cell = this._props.getCells(match[0]);
if (cell.length) {
matches.push(match[0]);
cells.set(match[0], cell[0]);
}
}
matches.forEach(m => {
chunkedText = chunkedText.replace(m, this.generateSpan(m, cells.get(m)));
});
return chunkedText;
};
/**
* Sets the rendered content of the cell to save user inputs.
* @param content the content to set
* @param restoreCursorPos whether the cursor should be set back to where it was rather than the 0th index; should usually be true
*/
@action
setContent = (content: string, restoreCursorPos?: boolean) => {
const pos = this.cursorPosition;
this._displayedContent = DOMPurify.sanitize(this.makeSpans(content));
restoreCursorPos && setTimeout(() => this.setCursorPosition(pos));
};
//Called from schemaview when a cell is selected to add a reference to the equation
/**
* Inserts text at the given index.
* @param text The text to append.
* @param atPos he index at which to insert the text. If empty, defaults to end.
*/
@action
insertText = (text: string, atPos?: boolean) => {
const content = this._unrenderedContent;
const cursorPos = this.cursorPosition;
const robustPos = cursorPos ?? content.length;
const newText = atPos ? content.slice(0, robustPos) + text + content.slice(cursorPos ?? content.length) : this._unrenderedContent.concat(text);
this.onChange(undefined, newText);
setTimeout(() => this.setCursorPosition(robustPos + text.length));
};
@action
setIsFocused = (value: boolean) => {
const wasFocused = this._editing;
this._editing = value;
this._editing && setTimeout(() => this._inputref?.focus());
return wasFocused !== this._editing;
};
/**
* Gets the cursor's position index within the text being edited.
*/
get cursorPosition() {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0 || !this._inputref) return null;
const range = selection.getRangeAt(0);
const adjRange = range.cloneRange();
adjRange.selectNodeContents(this._inputref);
adjRange.setEnd(range.startContainer, range.startOffset);
return adjRange.toString().length;
}
setCursorPosition = (position: number | null) => {
const selection = window.getSelection();
if (!selection || position === null || !this._inputref) return;
const range = document.createRange();
range.setStart(this._inputref, 0);
range.collapse(true);
let currentPos = 0;
const setRange = (nodes: NodeList) => {
for (let i = 0; i < nodes.length; ++i) {
const node = nodes[i];
if (node.nodeType === Node.TEXT_NODE) {
if (!node.textContent) return;
const nextPos = currentPos + node.textContent.length;
if (position <= nextPos) {
range.setStart(node, position - currentPos);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
return true;
}
currentPos = nextPos;
} else if (node.nodeType === Node.ELEMENT_NODE && setRange(node.childNodes)) return true;
}
return false;
};
setRange(this._inputref.childNodes);
};
//This function checks if a visual update (eg. coloring a cell reference) should be made. It's meant to
//save on processing upkeep vs. constantly rerendering, but I think the savings are minimal for now
shouldUpdate = (prevVal: string, currVal: string) => {
if (this._props.getCells(currVal).length !== this._props.getCells(prevVal).length) return true;
};
onChange = (e: FormEvent<HTMLDivElement> | undefined, newText?: string) => {
const prevVal = this._unrenderedContent;
const targVal = newText ?? e!.currentTarget.innerText; // TODO: bang
if (!(targVal.startsWith(':=') || targVal.startsWith('='))) {
this._overlayDisposer?.();
this._overlayDisposer = undefined;
} else if (!this._overlayDisposer) {
this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
}
this._unrenderedContent = targVal;
this._props.highlightCells?.(targVal);
if (this.shouldUpdate(prevVal, targVal)) this.setContent(targVal, true);
this.setupRefSelect(this.refSelectConditionMet);
};
setupRefSelect = (enabled: boolean) => {
const properties = this._props.refSelectModeInfo;
properties.enabled = enabled;
properties.currEditing = enabled ? this : undefined;
};
@action
onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
switch (e.key) {
case 'Tab':
e.stopPropagation();
this.finalizeEdit(e.shiftKey, false, false);
break;
case 'Backspace':
e.stopPropagation();
break;
case 'Enter':
e.stopPropagation();
!e.ctrlKey && this.finalizeEdit(e.shiftKey, false, true);
break;
case 'Escape':
e.stopPropagation();
this._editing = false;
break;
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight': // prettier-ignore
e.stopPropagation();
setTimeout(() => this.setupRefSelect(this.refSelectConditionMet));
break;
case ' ':
{
e.stopPropagation();
const cursorPos = this.cursorPosition !== null ? this.cursorPosition + 1 : 0;
setTimeout(() => {
this.setContent(this._unrenderedContent);
setTimeout(() => this.setCursorPosition(cursorPos));
});
}
break;
case 'Shift':
case 'Alt':
case 'Meta':
case 'Control':
case ':':
default:
break;
}
};
@action
onClick = (e?: React.MouseEvent) => {
if (this._props.editing !== false) {
e?.nativeEvent.stopPropagation();
this._editing = true;
}
};
@action
finalizeEdit = (shiftDown: boolean, lostFocus: boolean, enterKey: boolean) => {
if (this._unmounted) {
return;
}
if (this._unrenderedContent.replace(this.selfRefPattern, '') !== this._unrenderedContent) {
if (this._dependencyMessageShown) {
this._dependencyMessageShown = false;
} else alert(`Circular dependency detected. Please update the field at ${this.selfRefPattern}.`);
this._dependencyMessageShown = true;
return;
}
this.setContent(this._unrenderedContent);
if (!this._props.SetValue(this._unrenderedContent, shiftDown, enterKey) && !lostFocus) {
setTimeout(action(() => (this._editing = true)));
}
this._editing = false;
};
staticDisplay = () => {
return <span className="editableView-static">{this._props.fieldContents ? <FieldView {...this._props.fieldContents} /> : ''}</span>;
};
setRef = (r: HTMLDivElement | null) => (this._inputref = r);
renderEditor = () => {
return (
<div
contentEditable
className="schemaField-editing"
ref={this.setRef}
style={{ minHeight: `min(100%, ${(this._props.GetValue()?.split('\n').length || 1) * 15})`, minWidth: 20 }}
onBlur={() => (this._props.refSelectModeInfo.enabled ? setTimeout(() => this.setIsFocused(true), 1000) : this.finalizeEdit(false, true, false))}
onInput={this.onChange}
onKeyDown={this.onKeyDown}
onPointerDown={e => {
e.stopPropagation();
setTimeout(() => this.setupRefSelect(this.refSelectConditionMet), 0);
}} //timeout callback ensures that refSelectMode is properly set
onClick={e => e.stopPropagation}
onPointerUp={e => e.stopPropagation}
onPointerMove={e => {
e.stopPropagation();
e.preventDefault();
}}
dangerouslySetInnerHTML={{ __html: this._displayedContent }}></div>
);
};
onFocus = () => {
if (this._inputref?.innerText.startsWith('=') || this._inputref?.innerText.startsWith(':=')) {
this._overlayDisposer?.();
this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
this._props.highlightCells?.(this._unrenderedContent);
this.setContent(this._unrenderedContent);
setTimeout(() => this.setCursorPosition(this._unrenderedContent.length));
}
};
onBlur = action(() => {
this._editing = false;
});
render() {
const gval = this._props.GetValue()?.replace(/\n/g, '\\r\\n');
if (this._editing && gval !== undefined) {
return (
<div
className={`editableView-container-editing${this._props.oneLine ? '-oneLine' : ''}`} //
onFocus={this.onFocus}
onBlur={this.onBlur}>
{this.renderEditor()}
</div>
);
} else
return this._props.contents instanceof ObjectField ? null : (
<div
className={`editableView-container-editing${this._props.oneLine ? '-oneLine' : ''}`}
onFocus={this.onFocus}
onBlur={this.onBlur}
style={{
minHeight: '10px',
whiteSpace: this._props.oneLine ? 'nowrap' : 'pre-line',
width: '100%',
}}
onClick={this.onClick}>
{this.staticDisplay()}
</div>
);
}
}
|