Skip to content

Commit 79a64a5

Browse files
committed
Provide callback prop for onBlur
1 parent 4bb000b commit 79a64a5

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/Spreadsheet.tsx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
getCellRangeValue,
3737
getCellValue,
3838
shouldHandleClipboardEvent,
39+
isFocusedWithin,
3940
} from "./util";
4041
import reducer, { INITIAL_STATE, hasKeyDownHandler } from "./reducer";
4142
import context from "./context";
@@ -105,6 +106,8 @@ export type Props<CellType extends Types.CellBase> = {
105106
onSelect?: (selected: Point.Point[]) => void;
106107
/** Callback called when Spreadsheet's active cell changes. */
107108
onActivate?: (active: Point.Point) => void;
109+
/** Callback called when the Spreadsheet loses focus */
110+
onBlur?: () => void;
108111
onCellCommit?: (
109112
prevCell: null | CellType,
110113
nextCell: null | CellType,
@@ -137,6 +140,7 @@ const Spreadsheet = <CellType extends Types.CellBase>(
137140
onModeChange = () => {},
138141
onSelect = () => {},
139142
onActivate = () => {},
143+
onBlur = () => {},
140144
onCellCommit = () => {},
141145
} = props;
142146
const initialState = React.useMemo(
@@ -223,15 +227,24 @@ const Spreadsheet = <CellType extends Types.CellBase>(
223227
onSelect(points);
224228
}
225229

226-
if (state.active !== prevState.active && state.active) {
227-
onActivate(state.active);
230+
if (state.active !== prevState.active) {
231+
if (state.active) {
232+
onActivate(state.active);
233+
} else {
234+
const root = rootRef.current;
235+
if (root && isFocusedWithin(root) && document.activeElement) {
236+
(document.activeElement as HTMLElement).blur();
237+
}
238+
onBlur();
239+
}
228240
}
229241

230242
prevStateRef.current = state;
231243
}, [
232244
props.data,
233245
state,
234246
onActivate,
247+
onBlur,
235248
onCellCommit,
236249
onChange,
237250
onModeChange,
@@ -330,7 +343,7 @@ const Spreadsheet = <CellType extends Types.CellBase>(
330343
(event) => {
331344
const { currentTarget } = event;
332345
setTimeout(() => {
333-
if (!currentTarget.matches(":focus-within")) {
346+
if (!isFocusedWithin(currentTarget)) {
334347
blur();
335348
}
336349
}, 0);

0 commit comments

Comments
 (0)