Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OverlayPortal.tsx

65 lines1.5 KB

1import { type ReactNode, useEffect, useState } 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>;
6type Listener = (entries: Entries) => void;
7​
8let nextKey = 0;
9​
10function allocateKey() {
11 return nextKey++;
13const entries = new Map<number, ReactNode>();
14const listeners = new Set<Listener>();
15​
16function emit() {
17 const snapshot = new Map(entries);
18 for (const listener of listeners) {
19 listener(snapshot);
20 }
22​
23export function OverlayPortal(props: { readonly children: ReactNode }) {
24 const [key] = useState(allocateKey);
25​
26 // Re-project every render so open menus reflect content and theme changes.
27 useEffect(() => {
28 entries.set(key, props.children);
29 emit();
30 });
31​
32 useEffect(
33 () => () => {
34 entries.delete(key);
35 emit();
36 },
37 [key],
38 );
39​
40 return null;
42​
43export function OverlayPortalHost() {
44 const [current, setCurrent] = useState<Entries>(() => new Map());
45​
46 useEffect(() => {
47 listeners.add(setCurrent);
48 return () => {
49 listeners.delete(setCurrent);
50 };
51 }, []);
52​
53 if (current.size === 0) {
54 return null;
55 }
56 return (
57 <View pointerEvents="box-none" className="absolute inset-0">
58 {[...current.entries()].map(([key, node]) => (
59 <View key={key} pointerEvents="box-none" className="absolute inset-0">
60 {node}
61 </View>
62 ))}
63 </View>
64 );