85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
import useExamEditorStore from '@/stores/examEditor';
|
|
import ExamEditorStore from '@/stores/examEditor/types';
|
|
import { useCallback, useState } from 'react';
|
|
|
|
interface Props {
|
|
sectionId: number;
|
|
editing?: boolean;
|
|
setEditing?: React.Dispatch<React.SetStateAction<boolean>>;
|
|
onSave?: () => void;
|
|
onDiscard?: () => void;
|
|
onDelete?: () => void;
|
|
onPractice?: () => void;
|
|
onEdit?: () => void;
|
|
}
|
|
|
|
const useSectionEdit = ({
|
|
sectionId,
|
|
editing: externalEditing = false,
|
|
setEditing: externalSetEditing,
|
|
onSave,
|
|
onDiscard,
|
|
onDelete,
|
|
onPractice,
|
|
onEdit
|
|
}: Props) => {
|
|
const { dispatch } = useExamEditorStore();
|
|
const [internalEditing, setInternalEditing] = useState<boolean>(externalEditing);
|
|
const editing = externalSetEditing !== undefined ? externalEditing : internalEditing;
|
|
const setEditing = externalSetEditing !== undefined ? externalSetEditing : setInternalEditing;
|
|
|
|
|
|
const updateRoot = useCallback((updates: Partial<ExamEditorStore>) => {
|
|
dispatch({ type: 'UPDATE_ROOT', payload: { updates } });
|
|
}, [dispatch]);
|
|
|
|
const handleEdit = useCallback(() => {
|
|
setEditing(!editing);
|
|
if (onEdit) {
|
|
onEdit();
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [sectionId, editing, setEditing, updateRoot]);
|
|
|
|
const handleSave = useCallback(() => {
|
|
if (onSave) {
|
|
onSave();
|
|
} else {
|
|
setEditing(false);
|
|
}
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [setEditing, updateRoot, onSave, sectionId]);
|
|
|
|
const handleDiscard = useCallback(() => {
|
|
setEditing(false);
|
|
onDiscard?.();
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [setEditing, updateRoot, onDiscard, sectionId]);
|
|
|
|
const handleDelete = useCallback(() => {
|
|
setEditing(!editing);
|
|
onDelete?.();
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [setEditing, editing, updateRoot, onDelete, sectionId]);
|
|
|
|
const handlePractice = useCallback(() => {
|
|
onPractice?.();
|
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [setEditing, editing, updateRoot, onPractice, sectionId]);
|
|
|
|
return {
|
|
editing,
|
|
setEditing,
|
|
handleEdit,
|
|
handleSave,
|
|
handleDiscard,
|
|
handleDelete,
|
|
handlePractice,
|
|
};
|
|
};
|
|
|
|
export default useSectionEdit;
|