Open History to see the last commit
1import { type ReactNode, useEffect, useState, useSyncExternalStore } from "react";
2import { View } from "react-native";
3
4// RN Modals move native window focus and close the keyboard. Keep composer menus in-window.
5type Entries = ReadonlyMap<number, ReactNode>;
6
7let nextKey = 0;
8
9function allocateKey() {
10 return nextKey++;
11}
12const entries = new Map<number, ReactNode>();
13const listeners = new Set<() => void>();
14let snapshot: Entries = new Map();
15
16function emit() {
17 snapshot = new Map(entries);
18 for (const listener of listeners) {
19 listener();
20 }
21}
22
23function subscribe(listener: () => void) {
24 listeners.add(listener);
25 return () => {
26 listeners.delete(listener);
27 };
28}
29
30function getSnapshot() {
31 return snapshot;
32}
33
34export function OverlayPortal(props: { readonly children: ReactNode }) {
35 const [key] = useState(allocateKey);
36
37 // RN has no createPortal, so projecting into the out-of-tree host has to
38 // happen after commit. No dependency array: re-project after every render so
39 // the host always shows the current content (menus re-render while open —
40 // drill-in, theme).
41 useEffect(() => {
42 entries.set(key, props.children);
43 emit();
44 });
45
46 // Removal is unmount-only: deleting on every re-projection would move the
47 // entry to the end of the map and restack it above overlays opened later.
48 useEffect(
49 () => () => {
50 entries.delete(key);
51 emit();
52 },
53 [key],
54 );
55
56 return null;
57}
58
59export function OverlayPortalHost() {
60 const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
61
62 if (current.size === 0) {
63 return null;
64 }
65 return (
66 <View pointerEvents="box-none" className="absolute inset-0">
67 {[...current.entries()].map(([key, node]) => (
68 <View key={key} pointerEvents="box-none" className="absolute inset-0">
69 {node}
70 </View>
71 ))}
72 </View>
73 );
74}