Open History to see the last commit
1import { type ReactNode, useEffect, useRef, useState } from "react";
2import { View } from "react-native";
3
4// AndroidAnchoredMenu projects its dropdown here instead of into an RN Modal: a Modal is a
5// separate native window, so presenting one moves window focus and closes the soft keyboard —
6// which matters for menus anchored to the keyboard-sticky composer pills.
7type Entries = ReadonlyMap<number, ReactNode>;
8type Listener = (entries: Entries) => void;
9
10let nextKey = 0;
11const entries = new Map<number, ReactNode>();
12const listeners = new Set<Listener>();
13
14function emit() {
15 const snapshot = new Map(entries);
16 for (const listener of listeners) {
17 listener(snapshot);
18 }
19}
20
21export function OverlayPortal(props: { readonly children: ReactNode }) {
22 const keyRef = useRef<number | null>(null);
23 keyRef.current ??= nextKey++;
24 const key = keyRef.current;
25
26 // No dependency array: re-project after every render so the host always
27 // shows the current content (menus re-render while open — drill-in, theme).
28 useEffect(() => {
29 entries.set(key, props.children);
30 emit();
31 });
32
33 useEffect(
34 () => () => {
35 entries.delete(key);
36 emit();
37 },
38 [key],
39 );
40
41 return null;
42}
43
44export function OverlayPortalHost() {
45 const [current, setCurrent] = useState<Entries>(() => new Map());
46
47 useEffect(() => {
48 listeners.add(setCurrent);
49 return () => {
50 listeners.delete(setCurrent);
51 };
52 }, []);
53
54 if (current.size === 0) {
55 return null;
56 }
57 return (
58 <View pointerEvents="box-none" className="absolute inset-0">
59 {[...current.entries()].map(([key, node]) => (
60 <View key={key} pointerEvents="box-none" className="absolute inset-0">
61 {node}
62 </View>
63 ))}
64 </View>
65 );
66}