Skip to content

Commit 0058edb

Browse files
committed
Properly cancel editing when clicking another "Edit" icon
1 parent ea7b25c commit 0058edb

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/ValueNodeWrapper.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,9 @@ export const ValueNodeWrapper: React.FC<ValueNodeProps> = (props) => {
299299
) : (
300300
showEditButtons && (
301301
<EditButtons
302-
startEdit={canEdit ? () => setCurrentlyEditingElement(pathString) : undefined}
302+
startEdit={
303+
canEdit ? () => setCurrentlyEditingElement(pathString, handleCancel) : undefined
304+
}
303305
handleDelete={canDelete ? handleDelete : undefined}
304306
enableClipboard={enableClipboard}
305307
translate={translate}

src/contexts/TreeStateProvider.tsx

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* dropped on can act on it)
88
*/
99

10-
import React, { createContext, useContext, useState } from 'react'
10+
import React, { createContext, useContext, useRef, useState } from 'react'
1111
import { type CollectionKey } from '../types'
1212

1313
interface CollapseAllState {
@@ -25,7 +25,7 @@ interface TreeStateContext {
2525
setCollapseState: (collapseState: CollapseAllState | null) => void
2626
doesPathMatch: (path: CollectionKey[]) => boolean
2727
currentlyEditingElement: string | null
28-
setCurrentlyEditingElement: React.Dispatch<React.SetStateAction<string | null>>
28+
setCurrentlyEditingElement: (newElement: string | null, cancelOp?: () => void) => void
2929
areChildrenBeingEdited: (pathString: string) => boolean
3030
dragSource: DragSource
3131
setDragSource: (newState: DragSource) => void
@@ -50,6 +50,17 @@ export const TreeStateProvider = ({ children }: { children: React.ReactNode }) =
5050
path: null,
5151
pathString: null,
5252
})
53+
const cancelOp = useRef<(() => void) | null>(null)
54+
55+
const updateCurrentlyEditingElement = (newElement: string | null, newCancel?: () => void) => {
56+
// The "Cancel" allows the UI to reset the element that was previously being
57+
// edited if the user clicks another "Edit" button elsewhere
58+
if (currentlyEditingElement !== null && newElement !== null && cancelOp.current !== null) {
59+
cancelOp.current()
60+
}
61+
setCurrentlyEditingElement(newElement)
62+
cancelOp.current = newCancel ?? null
63+
}
5364

5465
const doesPathMatch = (path: CollectionKey[]) => {
5566
if (collapseState === null) return false
@@ -79,7 +90,7 @@ export const TreeStateProvider = ({ children }: { children: React.ReactNode }) =
7990
doesPathMatch,
8091
// Editing
8192
currentlyEditingElement,
82-
setCurrentlyEditingElement,
93+
setCurrentlyEditingElement: updateCurrentlyEditingElement,
8394
areChildrenBeingEdited,
8495
// Drag-n-drop
8596
dragSource,

0 commit comments

Comments
 (0)