Open History to see the last commit
1import { createContext, useContext, useEffect, useLayoutEffect, useState } from "react";
2
3// Activity hides its DOM but not body portals; kept subtrees need a container that hides with them.
4export const PortalContainerContext = createContext<HTMLElement | undefined>(undefined);
5
6export function usePortalContainer(): HTMLElement | undefined {
7 return useContext(PortalContainerContext);
8}
9
10/** Kept views remove the container on release; other callers must sit outside their Activity. */
11export function useOwnPortalContainer(
12 hidden: boolean,
13 lifetime: { hold(release: () => void): unknown } | null,
14): HTMLElement {
15 const [container] = useState(() => {
16 const element = document.createElement("div");
17 element.hidden = true;
18 return element;
19 });
20 useLayoutEffect(() => {
21 if (!container.isConnected) {
22 document.body.append(container);
23 lifetime?.hold(() => container.remove());
24 }
25 container.toggleAttribute("hidden", hidden);
26 // Activity runs cleanup on hide without releasing the view.
27 return () => {
28 container.toggleAttribute("hidden", true);
29 };
30 }, [container, hidden, lifetime]);
31 useEffect(() => {
32 if (lifetime !== null) return;
33 return () => container.remove();
34 }, [container, lifetime]);
35 return container;
36}