@@ -12,6 +12,8 @@ import propTypes from 'prop-types';
12
12
* @prop {HTMLElement } attachedElement - Which element the DoodleCanvas should cover.
13
13
* @prop {Array<import('../types/api').DoodleLine> } lines - An array of lines that compose this doodle.
14
14
* @prop {Function } setLines - A function to set the lines
15
+ * @prop {Function } onUndo - a function called when undo key commands pressed
16
+ * @prop {Function } onRedo - a function called when redo key commands pressed
15
17
*/
16
18
17
19
/**
@@ -27,6 +29,8 @@ const DoodleCanvas = ({
27
29
attachedElement,
28
30
lines,
29
31
setLines,
32
+ onUndo,
33
+ onRedo,
30
34
} ) => {
31
35
const [ isDrawing , setIsDrawing ] = useState ( false ) ;
32
36
const [ everActive , setEverActive ] = useState ( false ) ;
@@ -35,6 +39,27 @@ const DoodleCanvas = ({
35
39
setEverActive ( true ) ;
36
40
}
37
41
42
+ useEffect ( ( ) => {
43
+ const KEY_UNDO = 90 ; // Code for "Z" key
44
+ const KEY_REDO = 89 ; // Code for "Y" key
45
+ if ( ! active ) {
46
+ return ( ) => { } ;
47
+ }
48
+ const listener = e => {
49
+ const key = e . charCode || e . keyCode ;
50
+ if ( e . ctrlKey ) {
51
+ if ( key === KEY_UNDO ) {
52
+ onUndo ( ) ;
53
+ } else if ( key === KEY_REDO ) {
54
+ onRedo ( ) ;
55
+ }
56
+ }
57
+ } ;
58
+ document . addEventListener ( 'keydown' , listener ) ;
59
+ return ( ) => {
60
+ document . removeEventListener ( 'keydown' , listener ) ;
61
+ } ;
62
+ } , [ active , onUndo , onRedo ] ) ;
38
63
useEffect ( ( ) => {
39
64
if ( lines . length === 0 ) {
40
65
return ( ) => { } ;
@@ -50,7 +75,7 @@ const DoodleCanvas = ({
50
75
return ( ) => {
51
76
window . removeEventListener ( 'beforeunload' , warn ) ;
52
77
} ;
53
- } , [ lines ] ) ;
78
+ } , [ lines . length ] ) ;
54
79
55
80
const handleMouseDown = e => {
56
81
setIsDrawing ( true ) ;
@@ -137,6 +162,8 @@ DoodleCanvas.propTypes = {
137
162
lines : propTypes . array . isRequired ,
138
163
setLines : propTypes . func . isRequired ,
139
164
attachedElement : propTypes . any . isRequired ,
165
+ onUndo : propTypes . func . isRequired ,
166
+ onRedo : propTypes . func . isRequired ,
140
167
} ;
141
168
142
169
export { DoodleCanvas } ;
0 commit comments