-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
AztecInputState.js
105 lines (92 loc) · 2.48 KB
/
AztecInputState.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* External dependencies
*/
import TextInputState from 'react-native/Libraries/Components/TextInput/TextInputState';
/** @typedef {import('@wordpress/element').RefObject} RefObject */
const focusChangeListeners = [];
let currentFocusedElement = null;
/**
* Adds a listener that will be called in the following cases:
*
* - An Aztec view is being focused and all were previously unfocused.
* - An Aztec view is being unfocused and none will be focused.
*
* Note that this listener won't be called when switching focus between Aztec views.
*
* @param {Function} listener
*/
export const addFocusChangeListener = ( listener ) => {
focusChangeListeners.push( listener );
};
/**
* Removes a listener from the focus change listeners list.
*
* @param {Function} listener
*/
export const removeFocusChangeListener = ( listener ) => {
const itemIndex = focusChangeListeners.indexOf( listener );
if ( itemIndex !== -1 ) {
focusChangeListeners.splice( itemIndex, 1 );
}
};
const notifyListeners = ( { isFocused } ) => {
focusChangeListeners.forEach( ( listener ) => {
listener( { isFocused } );
} );
};
/**
* Determines if any Aztec view is focused.
*
* @return {boolean} True if focused.
*/
export const isFocused = () => {
return currentFocusedElement !== null;
};
/**
* Returns the current focused element.
*
* @return {RefObject} Ref of the current focused element or `null` otherwise.
*/
export const getCurrentFocusedElement = () => {
return currentFocusedElement;
};
/**
* Notifies that an Aztec view is being focused or unfocused.
*/
export const notifyInputChange = () => {
const focusedInput = TextInputState.currentlyFocusedInput();
const hasAnyFocusedInput = focusedInput !== null;
if ( hasAnyFocusedInput ) {
if ( ! currentFocusedElement ) {
notifyListeners( { isFocused: true } );
}
currentFocusedElement = focusedInput;
} else if ( currentFocusedElement ) {
notifyListeners( { isFocused: false } );
currentFocusedElement = null;
}
};
/**
* Focuses the specified element.
*
* @param {RefObject} element Element to be focused.
*/
export const focus = ( element ) => {
TextInputState.focusTextInput( element );
};
/**
* Unfocuses the specified element.
*
* @param {RefObject} element Element to be unfocused.
*/
export const blur = ( element ) => {
TextInputState.blurTextInput( element );
};
/**
* Unfocuses the current focused element.
*/
export const blurCurrentFocusedElement = () => {
if ( isFocused() ) {
blur( getCurrentFocusedElement() );
}
};