-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathSpreadsheet.tsx
573 lines (531 loc) · 17 KB
/
Spreadsheet.tsx
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import * as React from "react";
import classNames from "classnames";
import * as Types from "./types";
import * as Actions from "./actions";
import * as Matrix from "./matrix";
import * as Point from "./point";
import { Selection } from "./selection";
import reducer, { INITIAL_STATE, hasKeyDownHandler } from "./reducer";
import context from "./context";
import { Model, createFormulaParser } from "./engine";
import {
range,
readTextFromClipboard,
writeTextToClipboard,
calculateSpreadsheetSize,
getCSV,
shouldHandleClipboardEvent,
isFocusedWithin,
} from "./util";
import DefaultTable from "./Table";
import DefaultRow from "./Row";
import DefaultHeaderRow from "./HeaderRow";
import DefaultCornerIndicator, {
enhance as enhanceCornerIndicator,
} from "./CornerIndicator";
import DefaultColumnIndicator, {
enhance as enhanceColumnIndicator,
} from "./ColumnIndicator";
import DefaultRowIndicator, {
enhance as enhanceRowIndicator,
} from "./RowIndicator";
import { Cell as DefaultCell, enhance as enhanceCell } from "./Cell";
import DefaultDataViewer from "./DataViewer";
import DefaultDataEditor from "./DataEditor";
import ActiveCell from "./ActiveCell";
import Selected from "./Selected";
import Copied from "./Copied";
import "./Spreadsheet.css";
/** The Spreadsheet component props */
export type Props<CellType extends Types.CellBase> = {
/** The spreadsheet's data */
data: Matrix.Matrix<CellType>;
/** Class name to be added to the spreadsheet's root element */
className?: string;
/**
* Use dark colors that complement dark mode
* @defaultValue `false`
*/
darkMode?: boolean;
/**
* Function used to create the formula parser (instance of
* "fast-formula-parser") used by the Spreadsheet by getting the spreadsheet's
* data.
* @defaultValue function which creates a formula parser bound to the
* Spreadsheet's data.
* @see `createFormulaParser`
* @see https://www.npmjs.com/package/fast-formula-parser
*/
createFormulaParser?: Types.CreateFormulaParser;
/**
* Labels to use in column indicators.
* @defaultValue alphabetical labels.
*/
columnLabels?: string[];
/**
* Labels to use in row indicators.
* @defaultValue row index labels.
*/
rowLabels?: string[];
/**
* If set to true, hides the row indicators of the spreadsheet.
* @defaultValue `false`.
*/
hideRowIndicators?: boolean;
/**
* If set to true, hides the column indicators of the spreadsheet.
* @defaultValue `false`.
*/
hideColumnIndicators?: boolean;
/** The selected cells in the worksheet. */
selected?: Selection;
// Custom Components
/** Component rendered above each column. */
ColumnIndicator?: Types.ColumnIndicatorComponent;
/** Component rendered in the corner of row and column indicators. */
CornerIndicator?: Types.CornerIndicatorComponent;
/** Component rendered next to each row. */
RowIndicator?: Types.RowIndicatorComponent;
/** The Spreadsheet's table component. */
Table?: Types.TableComponent;
/** The Spreadsheet's row component. */
Row?: Types.RowComponent;
/** The spreadsheet's header row component */
HeaderRow?: Types.HeaderRowComponent;
/** The Spreadsheet's cell component. */
Cell?: Types.CellComponent<CellType>;
/** Component rendered for cells in view mode. */
DataViewer?: Types.DataViewerComponent<CellType>;
/** Component rendered for cells in edit mode. */
DataEditor?: Types.DataEditorComponent<CellType>;
// Handlers
/** Callback called on key down inside the spreadsheet. */
onKeyDown?: (event: React.KeyboardEvent) => void;
/** Callback called when the Spreadsheet's data changes. */
onChange?: (data: Matrix.Matrix<CellType>) => void;
/** Callback called when the Spreadsheet's edit mode changes. */
onModeChange?: (mode: Types.Mode) => void;
/** Callback called when the Spreadsheet's selection changes. */
onSelect?: (selected: Selection) => void;
/** Callback called when Spreadsheet's active cell changes. */
onActivate?: (active: Point.Point) => void;
/** Callback called when the Spreadsheet loses focus */
onBlur?: () => void;
onCellCommit?: (
prevCell: null | CellType,
nextCell: null | CellType,
coords: null | Point.Point
) => void;
/** Callback called when the Spreadsheet's evaluated data changes. */
onEvaluatedDataChange?: (data: Matrix.Matrix<CellType>) => void;
};
/**
* The Spreadsheet component
*/
const Spreadsheet = <CellType extends Types.CellBase>(
props: Props<CellType>
): React.ReactElement => {
const {
className,
darkMode,
columnLabels,
rowLabels,
hideColumnIndicators,
hideRowIndicators,
onKeyDown,
Table = DefaultTable,
Row = DefaultRow,
HeaderRow = DefaultHeaderRow,
DataEditor = DefaultDataEditor,
DataViewer = DefaultDataViewer,
onChange = () => {},
onModeChange = () => {},
onSelect = () => {},
onActivate = () => {},
onBlur = () => {},
onCellCommit = () => {},
onEvaluatedDataChange = () => {},
} = props;
type State = Types.StoreState<CellType>;
const initialState = React.useMemo(() => {
const createParser = (props.createFormulaParser ||
createFormulaParser) as Types.CreateFormulaParser;
const model = new Model(createParser, props.data);
return {
...INITIAL_STATE,
model,
selected: props.selected || INITIAL_STATE.selected,
} as State;
}, [props.createFormulaParser, props.data, props.selected]);
const reducerElements = React.useReducer(
reducer as unknown as React.Reducer<State, Actions.Action>,
initialState
);
const [state, dispatch] = reducerElements;
const size = React.useMemo(() => {
return calculateSpreadsheetSize(state.model.data, rowLabels, columnLabels);
}, [state.model.data, rowLabels, columnLabels]);
const mode = state.mode;
const rootRef = React.useRef<HTMLDivElement>(null);
const copy = React.useCallback(() => dispatch(Actions.copy()), [dispatch]);
const cut = React.useCallback(() => dispatch(Actions.cut()), [dispatch]);
const paste = React.useCallback(
(data: string) => dispatch(Actions.paste(data)),
[dispatch]
);
const onKeyDownAction = React.useCallback(
(event: React.KeyboardEvent) => dispatch(Actions.keyDown(event)),
[dispatch]
);
const onKeyPress = React.useCallback(
(event: React.KeyboardEvent) => dispatch(Actions.keyPress(event)),
[dispatch]
);
const onDragStart = React.useCallback(
() => dispatch(Actions.dragStart()),
[dispatch]
);
const onDragEnd = React.useCallback(
() => dispatch(Actions.dragEnd()),
[dispatch]
);
const setData = React.useCallback(
(data: Matrix.Matrix<CellType>) => dispatch(Actions.setData(data)),
[dispatch]
);
const setCreateFormulaParser = React.useCallback(
(createFormulaParser: Types.CreateFormulaParser) =>
dispatch(Actions.setCreateFormulaParser(createFormulaParser)),
[dispatch]
);
const blur = React.useCallback(() => dispatch(Actions.blur()), [dispatch]);
const setSelection = React.useCallback(
(selection: Selection) => dispatch(Actions.setSelection(selection)),
[dispatch]
);
// Track active
const prevActiveRef = React.useRef<Point.Point | null>(state.active);
React.useEffect(() => {
if (state.active !== prevActiveRef.current) {
if (state.active) {
onActivate(state.active);
} else {
const root = rootRef.current;
if (root && isFocusedWithin(root) && document.activeElement) {
(document.activeElement as HTMLElement).blur();
}
onBlur();
}
}
prevActiveRef.current = state.active;
}, [onActivate, onBlur, state.active]);
// Listen to data changes
const currentModelDataRef = React.useRef<Matrix.Matrix<CellType>>(
state.model.data
);
React.useEffect(() => {
currentModelDataRef.current = state.model.data;
}, [state.model.data]);
React.useEffect(() => {
onChange(currentModelDataRef.current);
}, [state.lastUpdateDate, onChange]);
const prevEvaluatedDataRef = React.useRef<Matrix.Matrix<CellType>>(
state.model.evaluatedData
);
React.useEffect(() => {
if (state?.model?.evaluatedData !== prevEvaluatedDataRef?.current) {
onEvaluatedDataChange(state?.model?.evaluatedData);
}
prevEvaluatedDataRef.current = state.model.evaluatedData;
}, [state?.model?.evaluatedData, onEvaluatedDataChange]);
// Listen to selection changes
const prevSelectedRef = React.useRef<Selection>(state.selected);
React.useEffect(() => {
if (!state.selected.equals(prevSelectedRef.current)) {
// Call on select only if the selection change internal
if (!props.selected || !state.selected.equals(props.selected)) {
onSelect(state.selected);
}
}
prevSelectedRef.current = state.selected;
}, [state.selected, onSelect, props.selected]);
// Listen to mode changes
const prevModeRef = React.useRef<Types.Mode>(state.mode);
React.useEffect(() => {
if (state.mode !== prevModeRef.current) {
onModeChange(state.mode);
}
prevModeRef.current = state.mode;
}, [state.mode, onModeChange]);
// Listen to last commit changes
const prevLastCommitRef = React.useRef<null | Types.CellChange[]>(
state.lastCommit
);
React.useEffect(() => {
if (state.lastCommit && state.lastCommit !== prevLastCommitRef.current) {
for (const change of state.lastCommit) {
onCellCommit(change.prevCell, change.nextCell, state.lastChanged);
}
}
}, [onCellCommit, state.lastChanged, state.lastCommit]);
// Update selection when props.selected changes
const prevSelectedPropRef = React.useRef<Selection | undefined>(
props.selected
);
React.useEffect(() => {
if (
props.selected &&
prevSelectedPropRef.current &&
!props.selected.equals(prevSelectedPropRef.current)
) {
setSelection(props.selected);
}
prevSelectedPropRef.current = props.selected;
}, [props.selected, setSelection]);
// Update data when props.data changes
const prevDataPropRef = React.useRef<Matrix.Matrix<CellType> | undefined>(
props.data
);
React.useEffect(() => {
if (props.data !== prevDataPropRef.current) {
setData(props.data);
}
prevDataPropRef.current = props.data;
}, [props.data, setData]);
// Update createFormulaParser when props.createFormulaParser changes
const prevCreateFormulaParserPropRef = React.useRef<
Types.CreateFormulaParser | undefined
>(props.createFormulaParser);
React.useEffect(() => {
if (
props.createFormulaParser !== prevCreateFormulaParserPropRef.current &&
props.createFormulaParser
)
setCreateFormulaParser(props.createFormulaParser);
prevCreateFormulaParserPropRef.current = props.createFormulaParser;
}, [props.createFormulaParser, setCreateFormulaParser]);
const writeDataToClipboard = React.useCallback(
(event: ClipboardEvent): void => {
const { model, selected } = state;
const { data } = model;
const range = selected.toRange(data);
if (range) {
const selectedData = Matrix.slice(range.start, range.end, data);
const csv = getCSV(selectedData);
writeTextToClipboard(event, csv);
}
},
[state]
);
const handleCut = React.useCallback(
(event: ClipboardEvent) => {
if (shouldHandleClipboardEvent(rootRef.current, mode)) {
event.preventDefault();
event.stopPropagation();
writeDataToClipboard(event);
cut();
}
},
[mode, writeDataToClipboard, cut]
);
const handleCopy = React.useCallback(
(event: ClipboardEvent) => {
if (shouldHandleClipboardEvent(rootRef.current, mode)) {
event.preventDefault();
event.stopPropagation();
writeDataToClipboard(event);
copy();
}
},
[mode, writeDataToClipboard, copy]
);
const handlePaste = React.useCallback(
(event: ClipboardEvent) => {
if (shouldHandleClipboardEvent(rootRef.current, mode)) {
event.preventDefault();
event.stopPropagation();
if (event.clipboardData) {
const text = readTextFromClipboard(event);
paste(text);
}
}
},
[mode, paste]
);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent) => {
event.persist();
if (onKeyDown) {
onKeyDown(event);
}
// Do not use event in case preventDefault() was called inside onKeyDown
if (!event.defaultPrevented) {
// Only disable default behavior if an handler exist
if (hasKeyDownHandler(state, event)) {
event.nativeEvent.preventDefault();
}
onKeyDownAction(event);
}
},
[state, onKeyDown, onKeyDownAction]
);
const handleMouseUp = React.useCallback(() => {
onDragEnd();
document.removeEventListener("mouseup", handleMouseUp);
}, [onDragEnd]);
const handleMouseMove = React.useCallback(
(event: React.MouseEvent) => {
if (!state.dragging && event.buttons === 1) {
onDragStart();
document.addEventListener("mouseup", handleMouseUp);
}
},
[state, onDragStart, handleMouseUp]
);
const handleBlur = React.useCallback(
(event: React.FocusEvent<HTMLDivElement>) => {
/**
* Focus left self, Not triggered when swapping focus between children
* @see https://reactjs.org/docs/events.html#detecting-focus-entering-and-leaving
*/
if (!event.currentTarget.contains(event.relatedTarget as Node)) {
blur();
}
},
[blur]
);
const Cell = React.useMemo(() => {
// @ts-ignore
return enhanceCell(props.Cell || DefaultCell);
}, [props.Cell]);
const CornerIndicator = React.useMemo(
() =>
enhanceCornerIndicator(props.CornerIndicator || DefaultCornerIndicator),
[props.CornerIndicator]
);
const RowIndicator = React.useMemo(
() => enhanceRowIndicator(props.RowIndicator || DefaultRowIndicator),
[props.RowIndicator]
);
const ColumnIndicator = React.useMemo(
() =>
enhanceColumnIndicator(props.ColumnIndicator || DefaultColumnIndicator),
[props.ColumnIndicator]
);
React.useEffect(() => {
document.addEventListener("cut", handleCut);
document.addEventListener("copy", handleCopy);
document.addEventListener("paste", handlePaste);
return () => {
document.removeEventListener("cut", handleCut);
document.removeEventListener("copy", handleCopy);
document.removeEventListener("paste", handlePaste);
};
}, [handleCut, handleCopy, handlePaste]);
const tableNode = React.useMemo(
() => (
<Table columns={size.columns} hideColumnIndicators={hideColumnIndicators}>
<HeaderRow>
{!hideRowIndicators && !hideColumnIndicators && <CornerIndicator />}
{!hideColumnIndicators &&
range(size.columns).map((columnNumber) =>
columnLabels ? (
<ColumnIndicator
key={columnNumber}
column={columnNumber}
label={
columnNumber in columnLabels
? columnLabels[columnNumber]
: null
}
/>
) : (
<ColumnIndicator key={columnNumber} column={columnNumber} />
)
)}
</HeaderRow>
{range(size.rows).map((rowNumber) => (
<Row key={rowNumber} row={rowNumber}>
{!hideRowIndicators &&
(rowLabels ? (
<RowIndicator
key={rowNumber}
row={rowNumber}
label={rowNumber in rowLabels ? rowLabels[rowNumber] : null}
/>
) : (
<RowIndicator key={rowNumber} row={rowNumber} />
))}
{range(size.columns).map((columnNumber) => (
<Cell
key={columnNumber}
row={rowNumber}
column={columnNumber}
// @ts-ignore
DataViewer={DataViewer}
/>
))}
</Row>
))}
</Table>
),
[
Table,
size.rows,
size.columns,
hideColumnIndicators,
Row,
HeaderRow,
hideRowIndicators,
CornerIndicator,
columnLabels,
ColumnIndicator,
rowLabels,
RowIndicator,
Cell,
DataViewer,
]
);
const activeCellNode = React.useMemo(
() => (
<ActiveCell
// @ts-ignore
DataEditor={DataEditor}
/>
),
[DataEditor]
);
const rootNode = React.useMemo(
() => (
<div
ref={rootRef}
className={classNames("Spreadsheet", className, {
"Spreadsheet--dark-mode": darkMode,
})}
onKeyPress={onKeyPress}
onKeyDown={handleKeyDown}
onMouseMove={handleMouseMove}
onBlur={handleBlur}
>
{tableNode}
{activeCellNode}
<Selected />
<Copied />
</div>
),
[
className,
darkMode,
onKeyPress,
handleKeyDown,
handleMouseMove,
handleBlur,
tableNode,
activeCellNode,
]
);
return (
<context.Provider value={reducerElements}>{rootNode}</context.Provider>
);
};
export default Spreadsheet;