MCPcopy Create free account
hub / github.com/RtlZeroMemory/Rezi / useModalStack

Function useModalStack

packages/core/src/widgets/useModalStack.ts:44–133  ·  view source on GitHub ↗
(ctx: WidgetContext<State>)

Source from the content-addressed store, hash-verified

42}
43
44export function useModalStack<State = void>(ctx: WidgetContext<State>): UseModalStack {
45 const [stack, setStack] = ctx.useState<readonly ModalStackEntry[]>(() => Object.freeze([]));
46
47 const push = ctx.useCallback((id: string, props: Omit<ModalProps, "id">) => {
48 setStack((prev) => {
49 const previousTop = prev[prev.length - 1];
50 const returnFocusTo = props.returnFocusTo ?? previousTop?.focusTarget ?? undefined;
51 const mergedProps =
52 returnFocusTo !== undefined
53 ? Object.freeze({ ...props, returnFocusTo })
54 : Object.freeze({ ...props });
55 const entry: ModalStackEntry = Object.freeze({
56 id,
57 keyVersion: 0,
58 focusTarget: resolveFocusTarget(mergedProps),
59 props: mergedProps,
60 });
61 return Object.freeze([...prev, entry]);
62 });
63 }, []);
64
65 const pop = ctx.useCallback(() => {
66 setStack((prev) => {
67 if (prev.length === 0) return prev;
68 if (prev.length === 1) return Object.freeze([]);
69
70 const remaining = prev.slice(0, -1);
71 const topIndex = remaining.length - 1;
72 const top = remaining[topIndex];
73 if (!top) return Object.freeze(remaining);
74
75 // When revealing the previous modal, bump key so initialFocus is reapplied.
76 const nextTop: ModalStackEntry = Object.freeze({
77 ...top,
78 keyVersion: top.keyVersion + 1,
79 props: Object.freeze({
80 ...top.props,
81 ...(top.focusTarget ? { initialFocus: top.focusTarget } : {}),
82 }),
83 });
84 const next = remaining.slice(0, topIndex).concat(nextTop);
85 return Object.freeze(next);
86 });
87 }, []);
88
89 const clear = ctx.useCallback(() => {
90 setStack((prev) => (prev.length === 0 ? prev : Object.freeze([])));
91 }, []);
92
93 const current = ctx.useCallback(() => {
94 const top = stack[stack.length - 1];
95 return top?.id ?? null;
96 }, [stack]);
97
98 const render = ctx.useCallback(() => {
99 return Object.freeze(
100 stack.map((entry, index) => {
101 const isTop = index === stack.length - 1;

Callers 2

renderFunction · 0.85

Calls 1

resolveFocusTargetFunction · 0.85

Tested by 1

renderFunction · 0.68