Open History to see the last commit
1import { type ReactNode, useEffect, 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;
11
12function allocateKey() {
13 return nextKey++;
14}
15const entries = new Map<number, ReactNode>();
16const listeners = new Set<Listener>();
17
18function emit() {
19 const snapshot = new Map(entries);
20 for (const listener of listeners) {
21 listener(snapshot);
22 }
23}
24
25export function OverlayPortal(props: { readonly children: ReactNode }) {
26 const [key] = useState(allocateKey);
27
28 // No dependency array: re-project after every render so the host always
29 // shows the current content (menus re-render while open — drill-in, theme).
30 useEffect(() => {
31 entries.set(key, props.children);
32 emit();
33 });
34
35 useEffect(
36 () => () => {
37 entries.delete(key);
38 emit();
39 },
40 [key],
41 );
42
43 return null;
44}
45
46export function OverlayPortalHost() {
47 const [current, setCurrent] = useState<Entries>(() => new Map());
48
49 useEffect(() => {
50 listeners.add(setCurrent);
51 return () => {
52 listeners.delete(setCurrent);
53 };
54 }, []);
55
56 if (current.size === 0) {
57 return null;
58 }
59 return (
60 <View pointerEvents="box-none" className="absolute inset-0">
61 {[...current.entries()].map(([key, node]) => (
62 <View key={key} pointerEvents="box-none" className="absolute inset-0">
63 {node}
64 </View>
65 ))}
66 </View>
67 );
68}