import { useCallback, useContext, useId, useLayoutEffect, useState, type HTMLAttributes } from "react"; import { ActivityIndicator } from "./ActivityIndicator.js"; import { LoadingContext } from "./LoadingContext.js"; import { cn } from "./cn.js"; export interface LoadingRegionProps extends HTMLAttributes { loading: boolean; label: string; /** Collect nested initial-content loads into this surface's single indicator. */ aggregate?: boolean; } /** Keeps content mounted. Failures/unmounts release each nested pending lease. */ export function LoadingRegion({ loading, label, aggregate = false, children, className, ...props }: LoadingRegionProps) { const parent = useContext(LoadingContext); const id = useId(); const [pending, setPending] = useState>(() => new Set()); const report = useCallback((key: string, busy: boolean) => { setPending(previous => { if (previous.has(key) === busy) return previous; const next = new Set(previous); if (busy) next.add(key); else next.delete(key); return next; }); }, []); useLayoutEffect(() => { parent?.(id, loading); return () => parent?.(id, false); }, [parent, id, loading]); const busy = loading || (aggregate && !parent && pending.size > 0); const content =
{children} {busy && !parent ?
: null}
; return aggregate && !parent ? {content} : content; }