Skip to content

Commit

Permalink
Extract shouldHandleClipboardEvent from Spreadsheet, improve and test
Browse files Browse the repository at this point in the history
Fix util
  • Loading branch information
iddan committed Sep 20, 2021
1 parent f4a6799 commit c3a8a0c
Show file tree
Hide file tree
Showing 4 changed files with 135 additions and 74 deletions.
42 changes: 26 additions & 16 deletions src/Spreadsheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
transformCoordToPoint,
getCellRangeValue,
getCellValue,
shouldHandleClipboardEvent,
} from "./util";
import "./Spreadsheet.css";

Expand Down Expand Up @@ -286,42 +287,51 @@ const Spreadsheet = <CellType extends Types.CellBase>(
[store]
);

const isFocused = React.useCallback(() => {
const root = rootRef.current;
const { activeElement } = document;

return mode === "view" && root
? root === activeElement || root.contains(activeElement)
: false;
}, [rootRef, mode]);

const handleCut = React.useCallback(
(event: ClipboardEvent) => {
if (isFocused()) {
if (
shouldHandleClipboardEvent(
document.activeElement,
rootRef.current,
mode
)
) {
event.preventDefault();
event.stopPropagation();
clip(event);
cut();
}
},
[isFocused, clip, cut]
[mode, clip, cut]
);

const handleCopy = React.useCallback(
(event: ClipboardEvent) => {
if (isFocused()) {
if (
shouldHandleClipboardEvent(
document.activeElement,
rootRef.current,
mode
)
) {
event.preventDefault();
event.stopPropagation();
clip(event);
copy();
}
},
[isFocused, clip, copy]
[mode, clip, copy]
);

const handlePaste = React.useCallback(
async (event: ClipboardEvent) => {
if (mode === "view" && isFocused()) {
(event: ClipboardEvent) => {
if (
shouldHandleClipboardEvent(
document.activeElement,
rootRef.current,
mode
)
) {
event.preventDefault();
event.stopPropagation();
if (event.clipboardData) {
Expand All @@ -330,7 +340,7 @@ const Spreadsheet = <CellType extends Types.CellBase>(
}
}
},
[mode, isFocused, paste]
[mode, paste]
);

const handleKeyDown = React.useCallback(
Expand Down
4 changes: 2 additions & 2 deletions src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@ export function cut(state: Types.StoreState): Partial<Types.StoreState> {
};
}

export async function paste<Cell extends Types.CellBase>(
export function paste<Cell extends Types.CellBase>(
state: Types.StoreState<Cell>,
text: string
): Promise<Partial<Types.StoreState<Cell>> | null> {
): Partial<Types.StoreState<Cell>> | null {
const { active } = state;
if (!active) {
return null;
Expand Down
Loading

0 comments on commit c3a8a0c

Please sign in to comment.