1"use client";
2
3import { Slot as SlotPrimitive } from "radix-ui";
4import * as React from "react";
5import { cn } from "@/lib/utils";
6import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
7import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
8import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
9
10interface DivProps extends React.ComponentProps<"div"> {
11 asChild?: boolean;
12}
13
14function getDataState(swapped: boolean) {
15 return swapped ? "on" : "off";
16}
17
18interface StoreState {
19 swapped: boolean;
20}
21
22interface Store {
23 subscribe: (callback: () => void) => () => void;
24 getState: () => StoreState;
25 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
26 notify: () => void;
27}
28
29const StoreContext = React.createContext<Store | null>(null);
30
31function useStore<T>(
32 selector: (state: StoreState) => T,
33 ogStore?: Store | null,
34): T {
35 const contextStore = React.useContext(StoreContext);
36
37 const store = ogStore ?? contextStore;
38
39 if (!store) {
40 throw new Error(`\`useStore\` must be used within \`Swap\``);
41 }
42
43 const getSnapshot = React.useCallback(
44 () => selector(store.getState()),
45 [store, selector],
46 );
47
48 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
49}
50
51interface SwapProps extends DivProps {
52 swapped?: boolean;
53 defaultSwapped?: boolean;
54 onSwappedChange?: (swapped: boolean) => void;
55 activationMode?: "click" | "hover";
56 animation?: "fade" | "rotate" | "flip" | "scale";
57 disabled?: boolean;
58}
59
60function Swap(props: SwapProps) {
61 const {
62 swapped: swappedProp,
63 defaultSwapped,
64 onSwappedChange,
65 activationMode = "click",
66 animation = "fade",
67 disabled,
68 asChild,
69 className,
70 onClick: onClickProp,
71 onMouseEnter: onMouseEnterProp,
72 onMouseLeave: onMouseLeaveProp,
73 onKeyDown: onKeyDownProp,
74 ...rootProps
75 } = props;
76
77 const listenersRef = useLazyRef(() => new Set<() => void>());
78 const stateRef = useLazyRef<StoreState>(() => ({
79 swapped: swappedProp ?? defaultSwapped ?? false,
80 }));
81
82 const propsRef = useAsRef({
83 activationMode,
84 animation,
85 disabled,
86 onSwappedChange,
87 onClick: onClickProp,
88 onMouseEnter: onMouseEnterProp,
89 onMouseLeave: onMouseLeaveProp,
90 onKeyDown: onKeyDownProp,
91 });
92
93 const isClickMode = activationMode === "click";
94
95 const store = React.useMemo<Store>(() => {
96 return {
97 subscribe: (cb) => {
98 listenersRef.current.add(cb);
99 return () => listenersRef.current.delete(cb);
100 },
101 getState: () => stateRef.current,
102 setState: (key, value) => {
103 if (Object.is(stateRef.current[key], value)) return;
104
105 if (key === "swapped" && typeof value === "boolean") {
106 stateRef.current.swapped = value;
107 propsRef.current.onSwappedChange?.(value);
108 } else {
109 stateRef.current[key] = value;
110 }
111
112 store.notify();
113 },
114 notify: () => {
115 for (const cb of listenersRef.current) {
116 cb();
117 }
118 },
119 };
120 }, [listenersRef, stateRef, propsRef]);
121
122 const swapped = useStore((state) => state.swapped, store);
123
124 useIsomorphicLayoutEffect(() => {
125 if (swappedProp !== undefined) {
126 store.setState("swapped", swappedProp);
127 }
128 }, [swappedProp]);
129
130 const onToggle = React.useCallback(() => {
131 if (propsRef.current.disabled) return;
132
133 store.setState("swapped", !store.getState().swapped);
134 }, [store, propsRef]);
135
136 const onClick = React.useCallback(
137 (event: React.MouseEvent<HTMLDivElement>) => {
138 propsRef.current.onClick?.(event);
139 if (event.defaultPrevented || propsRef.current.activationMode !== "click")
140 return;
141
142 onToggle();
143 },
144 [propsRef, onToggle],
145 );
146
147 const onMouseEnter = React.useCallback(
148 (event: React.MouseEvent<HTMLDivElement>) => {
149 propsRef.current.onMouseEnter?.(event);
150 if (
151 event.defaultPrevented ||
152 activationMode !== "hover" ||
153 propsRef.current.disabled
154 )
155 return;
156
157 store.setState("swapped", true);
158 },
159 [propsRef, activationMode, store],
160 );
161
162 const onMouseLeave = React.useCallback(
163 (event: React.MouseEvent<HTMLDivElement>) => {
164 propsRef.current.onMouseLeave?.(event);
165 if (
166 event.defaultPrevented ||
167 activationMode !== "hover" ||
168 propsRef.current.disabled
169 )
170 return;
171
172 store.setState("swapped", false);
173 },
174 [propsRef, activationMode, store],
175 );
176
177 const onKeyDown = React.useCallback(
178 (event: React.KeyboardEvent<HTMLDivElement>) => {
179 propsRef.current.onKeyDown?.(event);
180 if (
181 event.defaultPrevented ||
182 propsRef.current.activationMode !== "click" ||
183 propsRef.current.disabled
184 )
185 return;
186
187 if (event.key === "Enter" || event.key === " ") {
188 event.preventDefault();
189 onToggle();
190 }
191 },
192 [propsRef, onToggle],
193 );
194
195 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
196
197 return (
198 <StoreContext.Provider value={store}>
199 <RootPrimitive
200 role={isClickMode ? "button" : undefined}
201 aria-pressed={isClickMode ? swapped : undefined}
202 aria-disabled={disabled}
203 data-slot="swap"
204 data-animation={animation}
205 data-state={getDataState(swapped)}
206 data-disabled={disabled ? "" : undefined}
207 tabIndex={isClickMode && !disabled ? 0 : undefined}
208 {...rootProps}
209 className={cn(
210 "relative inline-flex cursor-pointer select-none items-center justify-center data-disabled:cursor-not-allowed data-disabled:opacity-50",
211 className,
212 )}
213 onClick={onClick}
214 onMouseEnter={onMouseEnter}
215 onMouseLeave={onMouseLeave}
216 onKeyDown={onKeyDown}
217 />
218 </StoreContext.Provider>
219 );
220}
221
222function SwapOn(props: DivProps) {
223 const { asChild, className, ...onProps } = props;
224
225 const swapped = useStore((state) => state.swapped);
226
227 const OnPrimitive = asChild ? SlotPrimitive.Slot : "div";
228
229 return (
230 <OnPrimitive
231 data-slot="swap-on"
232 data-state={getDataState(swapped)}
233 {...onProps}
234 className={cn(
235 "transition-all duration-300 data-[state=off]:absolute data-[state=off]:opacity-0 data-[state=on]:opacity-100 motion-reduce:transition-none",
236 "[*[data-animation=rotate]_&]:data-[state=off]:rotate-180 [*[data-animation=rotate]_&]:data-[state=on]:rotate-0 motion-reduce:[*[data-animation=rotate]_&]:data-[state=off]:rotate-0",
237 "[*[data-animation=flip]_&]:data-[state=off]:transform-[rotateY(180deg)] [*[data-animation=flip]_&]:data-[state=on]:transform-[rotateY(0deg)] motion-reduce:[*[data-animation=flip]_&]:data-[state=off]:transform-[rotateY(0deg)]",
238 "[*[data-animation=scale]_&]:data-[state=off]:scale-0 [*[data-animation=scale]_&]:data-[state=on]:scale-100 motion-reduce:[*[data-animation=scale]_&]:data-[state=off]:scale-100",
239 className,
240 )}
241 />
242 );
243}
244
245function SwapOff(props: DivProps) {
246 const { asChild, className, ...offProps } = props;
247
248 const swapped = useStore((state) => state.swapped);
249
250 const OffPrimitive = asChild ? SlotPrimitive.Slot : "div";
251
252 return (
253 <OffPrimitive
254 data-slot="swap-off"
255 data-state={getDataState(swapped)}
256 {...offProps}
257 className={cn(
258 "transition-all duration-300 data-[state=on]:absolute data-[state=off]:opacity-100 data-[state=on]:opacity-0 motion-reduce:transition-none",
259 "[*[data-animation=rotate]_&]:data-[state=off]:rotate-0 [*[data-animation=rotate]_&]:data-[state=on]:rotate-180 motion-reduce:[*[data-animation=rotate]_&]:data-[state=on]:rotate-0",
260 "[*[data-animation=flip]_&]:data-[state=off]:transform-[rotateY(0deg)] [*[data-animation=flip]_&]:data-[state=on]:transform-[rotateY(180deg)] motion-reduce:[*[data-animation=flip]_&]:data-[state=on]:transform-[rotateY(0deg)]",
261 "[*[data-animation=scale]_&]:data-[state=off]:scale-100 [*[data-animation=scale]_&]:data-[state=on]:scale-0 motion-reduce:[*[data-animation=scale]_&]:data-[state=on]:scale-100",
262 className,
263 )}
264 />
265 );
266}
267
268export { Swap, SwapOff, SwapOn, type SwapProps, useStore as useSwap };
269