Files
rowy/src/components/fields/_BasicCell/BasicCellContextMenuActions.tsx

75 lines
2.3 KiB
TypeScript
Raw Normal View History

import _find from "lodash/find";
2022-02-02 16:44:57 +11:00
import Cut from "@mui/icons-material/ContentCut";
import CopyCells from "@src/assets/icons/CopyCells";
2022-02-02 16:44:57 +11:00
import Paste from "@mui/icons-material/ContentPaste";
import { useProjectContext } from "@src/contexts/ProjectContext";
2022-02-02 18:07:52 +07:00
import { useSnackbar } from "notistack";
import { SelectedCell } from "@src/atoms/ContextMenu";
2022-02-02 18:07:52 +07:00
export interface IContextMenuActions {
label: string;
icon: React.ReactNode;
onClick: () => void;
}
export default function BasicContextMenuActions(
selectedCell: SelectedCell,
reset: () => void | Promise<void>
): IContextMenuActions[] {
const { tableState, deleteCell, updateCell } = useProjectContext();
2022-02-02 18:07:52 +07:00
const { enqueueSnackbar } = useSnackbar();
const columns = tableState?.columns;
const rows = tableState?.rows;
const selectedRowIndex = selectedCell.rowIndex as number;
const selectedColIndex = selectedCell?.colIndex;
const selectedCol = _find(columns, { index: selectedColIndex });
const selectedRow = rows?.[selectedRowIndex];
2022-02-02 20:56:52 +07:00
const cell = selectedRow?.[selectedCol.key];
2022-02-02 20:56:52 +07:00
const handleClose = async () => await reset?.();
2022-02-02 20:56:52 +07:00
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(JSON.stringify(cell));
2022-02-02 18:07:52 +07:00
enqueueSnackbar("Copied to clipboard", { variant: "success" });
2022-02-02 20:56:52 +07:00
} catch (error) {
2022-02-04 08:38:08 +07:00
enqueueSnackbar(`Failed to copy:${error}`, { variant: "error" });
2022-02-02 20:56:52 +07:00
}
handleClose();
};
2022-02-04 08:38:08 +07:00
const handleCut = async () => {
try {
await navigator.clipboard.writeText(JSON.stringify(cell));
if (typeof cell !== "undefined")
deleteCell?.(selectedRow?.ref, selectedCol?.key);
} catch (error) {
enqueueSnackbar(`Failed to cut: ${error}`, { variant: "error" });
}
handleClose();
};
2022-02-02 20:56:52 +07:00
const handlePaste = async () => {
try {
const text = await navigator.clipboard.readText();
const paste = await JSON.parse(text);
updateCell?.(selectedRow?.ref, selectedCol.key, paste);
} catch (error) {
2022-02-04 08:38:08 +07:00
enqueueSnackbar(`Failed to paste: ${error}`, { variant: "error" });
2022-02-02 20:56:52 +07:00
}
handleClose();
};
2022-02-02 18:07:52 +07:00
const contextMenuActions = [
{ label: "Cut", icon: <Cut />, onClick: handleCut },
{ label: "Copy", icon: <CopyCells />, onClick: handleCopy },
{ label: "Paste", icon: <Paste />, onClick: handlePaste },
];
2022-02-02 18:07:52 +07:00
return contextMenuActions;
}