-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathNode.tsx
More file actions
230 lines (203 loc) · 7.52 KB
/
Node.tsx
File metadata and controls
230 lines (203 loc) · 7.52 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { View } from 'react-native';
import { useSpatialNavigatorDefaultFocus } from '../context/DefaultFocusContext';
import { ParentIdContext, useParentId } from '../context/ParentIdContext';
import { useSpatialNavigatorParentScroll } from '../context/ParentScrollContext';
import { useSpatialNavigator } from '../context/SpatialNavigatorContext';
import { useUniqueId } from '../hooks/useUniqueId';
import { NodeOrientation } from '../types/orientation';
import { NodeIndexRange } from '@bam.tech/lrud';
import { SpatialNavigationNodeRef } from '../types/SpatialNavigationNodeRef';
import { useIsRootActive } from '../context/IsRootActiveContext';
type NonFocusableNodeState = {
/** Returns whether the root is active or not. An active node is active if one of its children is focused. */
isActive: boolean;
/** Returns whether the root is active or not.
* This is very handy if you want to hide the focus on your page elements when
* the side-menu is focused (since it is a different root navigator) */
isRootActive: boolean;
};
export type FocusableNodeState = NonFocusableNodeState & {
/** Returns whether the root is focused or not. */
isFocused: boolean;
};
type FocusableProps = {
isFocusable: true;
children: (props: FocusableNodeState) => React.ReactElement;
};
type NonFocusableProps = {
isFocusable?: false;
children: React.ReactElement | ((props: NonFocusableNodeState) => React.ReactElement);
};
type DefaultProps = {
onFocus?: () => void;
onBlur?: () => void;
onSelect?: () => void;
onLongSelect?: () => void;
onActive?: () => void;
onInactive?: () => void;
orientation?: NodeOrientation;
/** Use this for grid alignment.
* @see LRUD docs */
alignInGrid?: boolean;
indexRange?: NodeIndexRange;
/**
* This is an additional offset useful only for the scrollview. It adds up to the offsetFromStart of the scrollview.
*/
additionalOffset?: number;
};
type Props = DefaultProps & (FocusableProps | NonFocusableProps);
export type SpatialNavigationNodeDefaultProps = DefaultProps;
const useScrollToNodeIfNeeded = ({
childRef,
additionalOffset,
}: {
childRef: React.RefObject<View | null>;
additionalOffset?: number;
}) => {
const { scrollToNodeIfNeeded } = useSpatialNavigatorParentScroll();
return () => scrollToNodeIfNeeded(childRef, additionalOffset);
};
const useBindRefToChild = () => {
const childRef = useRef<View | null>(null);
const bindRefToChild = (child: React.ReactElement) => {
return React.cloneElement(child, {
// @ts-expect-error @fixme can't find how to type this properly -- new error since react 19
...child.props,
ref: (node: View) => {
// We need the reference for our scroll handling
childRef.current = node;
// @ts-expect-error @fixme This works at runtime but we couldn't find how to type it properly.
// Let's check if a ref was given (not by us)
const { ref } = child;
if (typeof ref === 'function') {
ref(node);
}
if (ref?.current !== undefined) {
ref.current = node;
}
},
});
};
return { bindRefToChild, childRef };
};
export const SpatialNavigationNode = forwardRef<SpatialNavigationNodeRef, Props>(
(
{
onFocus,
onBlur,
onSelect,
onLongSelect = onSelect,
onActive,
onInactive,
orientation = 'vertical',
isFocusable = false,
alignInGrid = false,
indexRange,
children,
additionalOffset = 0,
}: Props,
ref,
) => {
const spatialNavigator = useSpatialNavigator();
const parentId = useParentId();
const isRootActive = useIsRootActive();
const [isFocused, setIsFocused] = useState(false);
const [isActive, setIsActive] = useState(false);
// If parent changes, we have to re-register the Node + all children -> adding the parentId to the nodeId makes the children re-register.
const id = useUniqueId({ prefix: `${parentId}_node_` });
useImperativeHandle(
ref,
() => ({
focus: () => spatialNavigator.grabFocus(id),
}),
[spatialNavigator, id],
);
const { childRef, bindRefToChild } = useBindRefToChild();
const scrollToNodeIfNeeded = useScrollToNodeIfNeeded({
childRef,
additionalOffset,
});
/*
* We don't re-register in LRUD on each render, because LRUD does not allow updating the nodes.
* Therefore, the SpatialNavigator Node callbacks are registered at 1st render but can change (ie. if props change) afterwards.
* Since we want the functions to always be up to date, we use a reference to them.
*/
const currentOnSelect = useRef<() => void>(undefined);
currentOnSelect.current = onSelect;
const currentOnLongSelect = useRef<() => void>(undefined);
currentOnLongSelect.current = onLongSelect;
const currentOnFocus = useRef<() => void>(undefined);
currentOnFocus.current = () => {
onFocus?.();
scrollToNodeIfNeeded();
};
const currentOnBlur = useRef<() => void>(undefined);
currentOnBlur.current = onBlur;
const currentOnActive = useRef<() => void>(undefined);
currentOnActive.current = onActive;
const currentOnInactive = useRef<() => void>(undefined);
currentOnInactive.current = onInactive;
const shouldHaveDefaultFocus = useSpatialNavigatorDefaultFocus();
const accessedPropertiesRef = useRef<Set<keyof FocusableNodeState>>(new Set());
useEffect(() => {
spatialNavigator.registerNode(id, {
parent: parentId,
isFocusable,
onBlur: () => {
currentOnBlur.current?.();
if (accessedPropertiesRef.current.has('isFocused')) {
setIsFocused(false);
}
},
onFocus: () => {
currentOnFocus.current?.();
if (accessedPropertiesRef.current.has('isFocused')) {
setIsFocused(true);
}
},
onSelect: () => currentOnSelect.current?.(),
onLongSelect: () => currentOnLongSelect.current?.(),
orientation,
isIndexAlign: alignInGrid,
indexRange,
onActive: () => {
currentOnActive.current?.();
if (accessedPropertiesRef.current.has('isActive')) {
setIsActive(true);
}
},
onInactive: () => {
currentOnInactive.current?.();
if (accessedPropertiesRef.current.has('isActive')) {
setIsActive(false);
}
},
});
return () => spatialNavigator.unregisterNode(id);
// eslint-disable-next-line react-hooks/exhaustive-deps -- unfortunately, we can't have clean effects with lrud for now
}, [parentId]);
useEffect(() => {
if (shouldHaveDefaultFocus && isFocusable && !spatialNavigator.hasOneNodeFocused()) {
spatialNavigator.handleOrQueueDefaultFocus(id);
}
}, [id, isFocusable, shouldHaveDefaultFocus, spatialNavigator]);
// This proxy allows to track whether a property is used or not
// hence allowing to ignore re-renders for unused pr
const proxyObject = new Proxy(
{ isFocused, isActive, isRootActive },
{
get(target, prop: keyof FocusableNodeState) {
accessedPropertiesRef.current.add(prop);
return target[prop];
},
},
);
return (
<ParentIdContext.Provider value={id}>
{typeof children === 'function' ? bindRefToChild(children(proxyObject)) : children}
</ParentIdContext.Provider>
);
},
);
SpatialNavigationNode.displayName = 'SpatialNavigationNode';