Skip to content

Commit

Permalink
Run active edit action synchronously
Browse files Browse the repository at this point in the history
  • Loading branch information
joel-jeremy committed Jan 3, 2024
1 parent ec6a309 commit 1e53dd4
Showing 1 changed file with 21 additions and 29 deletions.
50 changes: 21 additions & 29 deletions packages/desktop-client/src/hooks/useSingleActiveEditForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import React, {
} from 'react';

import usePrevious from './usePrevious';
import useStableCallback from './useStableCallback';

type ActiveEditCleanup = () => void;
type ActiveEditAction = () => void | ActiveEditCleanup;
Expand All @@ -19,7 +18,9 @@ type SingleActiveEditFormContextValue = {
onRequestActiveEdit: (
field: string,
action?: ActiveEditAction,
clearActiveEditDelayMs?: number,
options?: {
clearActiveEditDelayMs?: number;
},
) => void;
onClearActiveEdit: (delayMs?: number) => void;
};
Expand All @@ -39,21 +40,14 @@ export function SingleActiveEditFormProvider({
}: SingleActiveEditFormProviderProps) {
const [editingField, setEditingField] = useState(null);
const prevEditingField = usePrevious(editingField);
const actionRef = useRef<ActiveEditAction>(null);
const cleanupRef = useRef<ActiveEditCleanup | void>(null);

useEffect(() => {
if (prevEditingField != null && prevEditingField !== editingField) {
runCleanup();
} else if (prevEditingField == null && editingField !== null) {
runAction();
}
}, [editingField]);

const runAction = () => {
cleanupRef.current = actionRef.current?.();
};

const runCleanup = () => {
const editCleanup = cleanupRef.current;
if (typeof editCleanup === 'function') {
Expand All @@ -66,27 +60,25 @@ export function SingleActiveEditFormProvider({
setTimeout(() => setEditingField(null), delayMs);
};

const onRequestActiveEdit = useStableCallback(
(
field: string,
action: ActiveEditAction,
options: {
clearActiveEditDelayMs?: number;
},
) => {
if (editingField === field) {
// Already active.
return;
}

if (editingField) {
onClearActiveEdit(options?.clearActiveEditDelayMs);
} else {
actionRef.current = action;
setEditingField(field);
}
const onRequestActiveEdit = (
field: string,
action: ActiveEditAction,
options: {
clearActiveEditDelayMs?: number;
},
);
) => {
if (editingField === field) {
// Already active.
return;
}

if (editingField) {
onClearActiveEdit(options?.clearActiveEditDelayMs);
} else {
cleanupRef.current = action?.();
setEditingField(field);
}
};

return (
<SingleActiveEditFormContext.Provider
Expand Down

0 comments on commit 1e53dd4

Please sign in to comment.