-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.tsx
476 lines (435 loc) · 12.4 KB
/
index.tsx
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import * as React from 'react';
import {
View,
Text,
ScrollView as NativeScrollView,
FlatList as NativeFlatList,
FlatListProps,
Pressable,
Platform,
} from 'react-native';
import type {
ComponentProps,
MutableRefObject,
LegacyRef,
ReactNode,
RefObject,
RefCallback,
} from 'react';
const {
createContext,
forwardRef,
useContext,
useMemo,
useRef,
useImperativeHandle,
} = React;
// from react-merge-refs (avoid dependency)
function mergeRefs<T = any>(
refs: Array<MutableRefObject<T> | LegacyRef<T>>
): RefCallback<T> {
return (value) => {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(value);
} else if (ref != null) {
(ref as MutableRefObject<T | null>).current = value;
}
});
};
}
// type Props<Anchors extends readonly string[]> = {
// anchors: Anchors;
// };
type Unpromisify<T> = T extends Promise<infer R> ? R : T;
/**
* The following is taken/edited from `useScrollToTop` from `@react-navigation/native`
*/
type ScrollOptions = { y?: number; animated?: boolean };
type ScrollableView =
| { scrollToTop(): void }
| { scrollTo(options: ScrollOptions): void }
| { scrollToOffset(options: { offset?: number; animated?: boolean }): void }
| { scrollResponderScrollTo(options: ScrollOptions): void };
type ScrollableWrapper =
| { getScrollResponder(): ReactNode }
| { getNode(): ScrollableView }
| ScrollableView;
function getScrollableNode(ref: RefObject<ScrollableWrapper>) {
if (ref.current == null) {
return null;
}
if (typeof ref.current !== 'object' && typeof ref.current !== 'function') {
return null;
}
if (
'scrollTo' in ref.current ||
'scrollToOffset' in ref.current ||
'scrollResponderScrollTo' in ref.current
) {
// This is already a scrollable node.
return ref.current;
} else if ('getScrollResponder' in ref.current) {
// If the view is a wrapper like FlatList, SectionList etc.
// We need to use `getScrollResponder` to get access to the scroll responder
return ref.current.getScrollResponder();
} else if ('getNode' in ref.current) {
// When a `ScrollView` is wraped in `Animated.createAnimatedComponent`
// we need to use `getNode` to get the ref to the actual scrollview.
// Note that `getNode` is deprecated in newer versions of react-native
// this is why we check if we already have a scrollable node above.
return ref.current.getNode();
} else {
return ref.current;
}
}
/**
* End of react-navigation code.
*/
type ScrollToOptions = {
animated?: boolean;
/**
* A number that determines how far from the content you want to scroll.
*
* Default: `-10`, which means it scrolls to 10 pixels before the content.
*/
offset?: number;
/**
* If you're using a `ScrollView` or `FlatList` imported from this library, you can ignore this field.
*/
// horizontal?: boolean;
};
export interface Anchors {}
export type AnchorsRef = {
scrollTo: (
name: Anchor,
options?: ScrollToOptions
) => Promise<{ success: true } | { success: false; message: string }>;
};
/**
* If you need to control a `ScrollView` or `FlatList` from outside of their scope:
*
* ```jsx
* import React from 'react'
* import { useAnchors, ScrollView } from '@nandorojo/anchor'
*
* export default function App() {
* const anchors = useAnchors()
*
* const onPress = () => {
* anchors.current?.scrollTo('list')
* }
*
* return (
* <ScrollView anchors={anchors}>
* <Target name="list" />
* </ScrollView>
* )
* }
* ```
*/
const useAnchors = () => {
const ref = useRef<AnchorsRef>(null);
return ref;
};
// @ts-expect-error
type Anchor = Anchors['anchor'] extends string ? Anchors['anchor'] : string;
// export default function createAnchors() {
type AnchorsContext = {
targetRefs: RefObject<Record<Anchor, View | Text>>;
scrollRef: RefObject<ScrollableWrapper>;
registerTargetRef: (name: Anchor, ref: View | Text) => void;
registerScrollRef: (ref: ScrollableWrapper | null) => void;
horizontal: ComponentProps<typeof NativeScrollView>['horizontal'];
scrollTo: AnchorsRef['scrollTo'];
};
const AnchorsContext = createContext<AnchorsContext>({
targetRefs: {
current: {} as any,
},
scrollRef: {
current: null as any,
},
registerTargetRef: () => {
// no-op
},
registerScrollRef: () => {
// no-op
},
horizontal: false,
scrollTo: () => {
return new Promise((resolve) =>
resolve({
success: false,
message: 'Missing @nandorojo/anchor provider.',
})
);
},
});
const useAnchorsContext = () => useContext(AnchorsContext);
const useCreateAnchorsContext = ({
horizontal,
}: Pick<AnchorsContext, 'horizontal'>): AnchorsContext => {
const targetRefs = useRef<Record<string, View>>({});
const scrollRef = useRef<ScrollableWrapper>();
return useMemo(() => {
return {
targetRefs,
scrollRef: scrollRef as RefObject<ScrollableWrapper>,
registerTargetRef: (target, ref) => {
targetRefs.current = {
...targetRefs.current,
[target]: ref,
};
},
registerScrollRef: (ref) => {
if (ref) {
scrollRef.current = ref;
}
},
horizontal,
scrollTo: (
name: Anchor,
{ animated = true, offset = -10 }: ScrollToOptions = {}
) => {
return new Promise<
{ success: true } | { success: false; message: string }
>((resolve) => {
try {
const node = Platform.select({
default: scrollRef.current,
web:
scrollRef.current &&
// @ts-ignore
scrollRef.current.getInnerViewNode &&
// @ts-ignore
scrollRef.current.getInnerViewNode(),
});
if (!node) {
return resolve({
success: false,
message: 'Scroll ref does not exist. Will not scroll to view.',
});
}
if (!targetRefs.current?.[name]) {
resolve({
success: false,
message:
'Anchor ref ' +
name +
' does not exist. It will not scroll. Please make sure to use the ScrollView provided by @nandorojo/anchors, or use the registerScrollRef function for your own ScrollView.',
});
}
targetRefs.current?.[name].measureLayout(
node,
(left, top) => {
requestAnimationFrame(() => {
const scrollY = top;
const scrollX = left;
const scrollable = getScrollableNode(
scrollRef as RefObject<ScrollableWrapper>
) as ScrollableWrapper;
let scrollTo = horizontal ? scrollX : scrollY;
scrollTo += offset;
scrollTo = Math.max(scrollTo, 0);
const key = horizontal ? 'x' : 'y';
if (!scrollable) {
return resolve({
success: false,
message: 'Scrollable not detected. Will not scroll.',
});
}
try {
if ('scrollTo' in scrollable) {
scrollable.scrollTo({
[key]: scrollTo,
animated,
});
} else if ('scrollToOffset' in scrollable) {
scrollable.scrollToOffset({
offset: scrollTo,
animated,
});
} else if ('scrollResponderScrollTo' in scrollable) {
scrollable.scrollResponderScrollTo({
[key]: scrollTo,
animated,
});
}
} catch (error) {
return resolve({
success: false,
message: 'Failed to scroll for an unknown reason.',
});
}
resolve({ success: true });
});
},
() => {
resolve({
success: false,
message: 'Failed to measure target node.',
});
}
);
} catch (error: any) {
resolve({
success: false,
message: [
'Failed to measure target node.',
error && 'message' in error && error.message,
]
.filter(Boolean)
.join(' '),
});
}
});
},
};
}, [horizontal]);
};
function useRegisterTarget() {
const { registerTargetRef } = useAnchorsContext();
return useMemo(
() => ({
register: (name: Anchor) => {
return (ref: View) => registerTargetRef(name, ref);
},
}),
[registerTargetRef]
);
}
function useScrollTo() {
const { scrollTo } = useAnchorsContext();
return useMemo(
() => ({
scrollTo,
}),
[scrollTo]
);
}
function useRegisterScroller() {
const { registerScrollRef } = useAnchorsContext();
return { registerScrollRef };
}
function AnchorProvider({
children,
horizontal,
anchors,
}: { children: ReactNode; anchors?: RefObject<AnchorsRef> } & Pick<
AnchorsContext,
'horizontal'
>) {
const value = useCreateAnchorsContext({ horizontal });
useImperativeHandle(anchors, () => ({
scrollTo: (...props) => {
return value.scrollTo(...props);
},
}));
return (
<AnchorsContext.Provider value={value}>{children}</AnchorsContext.Provider>
);
}
/**
* Identical to the normal React Native `ScrollView`, except that it allows scrolling to anchor links.
*
* If you use this component, you don't need to use the `AnchorProvider`. It implements it for you.
*/
const ScrollView = forwardRef<
NativeScrollView,
ComponentProps<typeof NativeScrollView> & {
children?: ReactNode;
} & Pick<ComponentProps<typeof AnchorProvider>, 'anchors'>
>(function ScrollView({ horizontal = false, anchors, ...props }, ref) {
return (
<AnchorProvider anchors={anchors} horizontal={horizontal}>
<AnchorsContext.Consumer>
{({ registerScrollRef }) => (
<NativeScrollView
horizontal={horizontal}
{...props}
ref={mergeRefs([registerScrollRef, ref])}
/>
)}
</AnchorsContext.Consumer>
</AnchorProvider>
);
});
/**
* Identical to the normal React Native flatlist, except that it allows scrolling to anchor links.
*
* If you use this component, you don't need to use the `AnchorProvider`.
*
* One important difference: if you want to use the `ref`, pass it to `flatListRef` instead of `ref`.
*/
function FlatList<T = any>({
flatListRef,
horizontal = false,
anchors,
...props
}: FlatListProps<T> & { flatListRef?: RefObject<NativeFlatList> } & Pick<
ComponentProps<typeof AnchorProvider>,
'anchors'
>) {
return (
<AnchorProvider anchors={anchors} horizontal={horizontal}>
<AnchorsContext.Consumer>
{({ registerScrollRef }) => (
<NativeFlatList
{...props}
horizontal={horizontal}
ref={mergeRefs([registerScrollRef, flatListRef || null])}
/>
)}
</AnchorsContext.Consumer>
</AnchorProvider>
);
}
function ScrollTo({
target,
onPress,
options,
onRequestScrollTo,
...props
}: {
children?: ReactNode;
target: Anchor;
options?: ScrollToOptions;
onRequestScrollTo?: (
props: Unpromisify<ReturnType<ReturnType<typeof useScrollTo>['scrollTo']>>
) => void;
} & ComponentProps<typeof Pressable>) {
const { scrollTo } = useScrollTo();
return (
<Pressable
{...props}
onPress={async (e) => {
onPress?.(e);
const result = await scrollTo(target, options);
onRequestScrollTo?.(result);
}}
/>
);
}
const Target = forwardRef<
View,
{ name: Anchor; children?: ReactNode } & ComponentProps<typeof View>
>(function Target({ name, ...props }, ref) {
const { register } = useRegisterTarget();
return <View {...props} ref={mergeRefs([register(name), ref])} />;
});
const AnchorsConsumer = AnchorsContext.Consumer;
export {
AnchorProvider,
ScrollView,
FlatList,
useRegisterTarget,
useScrollTo,
ScrollTo,
Target,
ScrollTo as Anchor,
useRegisterScroller,
useAnchors,
AnchorsConsumer,
};
// }