1"use client";
2
3import { cva, type VariantProps } from "class-variance-authority";
4import { Slot as SlotPrimitive } from "radix-ui";
5import * as React from "react";
6import { useComposedRefs } from "@/lib/compose-refs";
7import { cn } from "@/lib/utils";
8import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
9import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
10import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
11import { Button } from "@/registry/bases/radix/ui/button";
12
13const ROOT_NAME = "SpeedDial";
14const TRIGGER_NAME = "SpeedDialTrigger";
15const CONTENT_NAME = "SpeedDialContent";
16const ITEM_NAME = "SpeedDialItem";
17const ACTION_NAME = "SpeedDialAction";
18const LABEL_NAME = "SpeedDialLabel";
19
20const ACTION_SELECT = "speedDial.actionSelect";
21const INTERACT_OUTSIDE = "speedDial.interactOutside";
22const EVENT_OPTIONS = { bubbles: true, cancelable: true };
23
24const DEFAULT_GAP = 8;
25const DEFAULT_OFFSET = 8;
26const DEFAULT_ITEM_DELAY = 50;
27const DEFAULT_HOVER_CLOSE_DELAY = 100;
28const DEFAULT_ANIMATION_DURATION = 200;
29
30type Side = "top" | "right" | "bottom" | "left";
31type ActivationMode = "click" | "hover";
32
33interface DivProps extends React.ComponentProps<"div"> {
34 asChild?: boolean;
35}
36
37type RootElement = React.ComponentRef<typeof SpeedDial>;
38type ContentElement = React.ComponentRef<typeof SpeedDialContent>;
39type TriggerElement = React.ComponentRef<typeof SpeedDialTrigger>;
40type ActionElement = React.ComponentRef<typeof SpeedDialAction>;
41
42interface InteractOutsideEvent extends CustomEvent {
43 detail: {
44 originalEvent: PointerEvent;
45 };
46}
47
48function getDataState(open: boolean): string {
49 return open ? "open" : "closed";
50}
51
52function getTransformOrigin(side: Side): string {
53 switch (side) {
54 case "top":
55 return "bottom center";
56 case "bottom":
57 return "top center";
58 case "left":
59 return "right center";
60 case "right":
61 return "left center";
62 }
63}
64
65interface StoreState {
66 open: boolean;
67}
68
69interface Store {
70 subscribe: (callback: () => void) => () => void;
71 getState: () => StoreState;
72 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
73 notify: () => void;
74}
75
76const StoreContext = React.createContext<Store | null>(null);
77
78function useStoreContext(consumerName: string) {
79 const context = React.useContext(StoreContext);
80 if (!context) {
81 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
82 }
83 return context;
84}
85
86function useStore<T>(
87 selector: (state: StoreState) => T,
88 ogStore?: Store | null,
89): T {
90 const contextStore = React.useContext(StoreContext);
91
92 const store = ogStore ?? contextStore;
93
94 if (!store) {
95 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
96 }
97
98 const getSnapshot = React.useCallback(
99 () => selector(store.getState()),
100 [store, selector],
101 );
102
103 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
104}
105
106interface NodeData {
107 id: string;
108 ref: React.RefObject<HTMLElement | null>;
109 disabled: boolean;
110}
111
112interface SpeedDialContextValue {
113 onNodeRegister: (node: NodeData) => void;
114 onNodeUnregister: (id: string) => void;
115 getNodes: () => NodeData[];
116 contentId: string;
117 rootRef: React.RefObject<RootElement | null>;
118 triggerRef: React.RefObject<TriggerElement | null>;
119 isPointerInsideReactTreeRef: React.RefObject<boolean>;
120 hoverCloseTimerRef: React.RefObject<number | null>;
121 side: Side;
122 activationMode: ActivationMode;
123 delay: number;
124 disabled: boolean;
125}
126
127const SpeedDialContext = React.createContext<SpeedDialContextValue | null>(
128 null,
129);
130
131function useSpeedDialContext(consumerName: string) {
132 const context = React.useContext(SpeedDialContext);
133 if (!context) {
134 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
135 }
136 return context;
137}
138
139interface SpeedDialProps extends DivProps {
140 open?: boolean;
141 defaultOpen?: boolean;
142 onOpenChange?: (open: boolean) => void;
143 side?: Side;
144 activationMode?: ActivationMode;
145 delay?: number;
146 disabled?: boolean;
147}
148
149function SpeedDial(props: SpeedDialProps) {
150 const {
151 open: openProp,
152 defaultOpen,
153 onOpenChange,
154 onPointerDownCapture: onPointerDownCaptureProp,
155 side = "top",
156 activationMode = "click",
157 delay = 250,
158 asChild,
159 disabled = false,
160 className,
161 ref,
162 ...rootProps
163 } = props;
164
165 const contentId = React.useId();
166
167 const rootRef = React.useRef<RootElement | null>(null);
168 const composedRefs = useComposedRefs(ref, rootRef);
169
170 const triggerRef = React.useRef<TriggerElement | null>(null);
171
172 const nodesRef = React.useRef<Map<string, NodeData>>(new Map());
173 const isPointerInsideReactTreeRef = React.useRef(false);
174 const hoverCloseTimerRef = React.useRef<number | null>(null);
175
176 const listenersRef = useLazyRef(() => new Set<() => void>());
177 const stateRef = useLazyRef<StoreState>(() => ({
178 open: openProp ?? defaultOpen ?? false,
179 }));
180
181 const propsRef = useAsRef({
182 onOpenChange,
183 onPointerDownCapture: onPointerDownCaptureProp,
184 });
185
186 const store = React.useMemo<Store>(() => {
187 return {
188 subscribe: (cb) => {
189 listenersRef.current.add(cb);
190 return () => listenersRef.current.delete(cb);
191 },
192 getState: () => stateRef.current,
193 setState: (key, value) => {
194 if (Object.is(stateRef.current[key], value)) return;
195
196 if (key === "open" && typeof value === "boolean") {
197 stateRef.current.open = value;
198 propsRef.current.onOpenChange?.(value);
199 } else {
200 stateRef.current[key] = value;
201 }
202
203 store.notify();
204 },
205 notify: () => {
206 for (const cb of listenersRef.current) {
207 cb();
208 }
209 },
210 };
211 }, [listenersRef, stateRef, propsRef]);
212
213 const getNodes = React.useCallback(() => {
214 return Array.from(nodesRef.current.values())
215 .filter((node) => node.ref.current)
216 .sort((a, b) => {
217 const elementA = a.ref.current;
218 const elementB = b.ref.current;
219 if (!elementA || !elementB) return 0;
220 const position = elementA.compareDocumentPosition(elementB);
221 if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
222 return -1;
223 }
224 if (position & Node.DOCUMENT_POSITION_PRECEDING) {
225 return 1;
226 }
227 return 0;
228 });
229 }, []);
230
231 const onNodeRegister = React.useCallback((node: NodeData) => {
232 nodesRef.current.set(node.id, node);
233 }, []);
234
235 const onNodeUnregister = React.useCallback((id: string) => {
236 nodesRef.current.delete(id);
237 }, []);
238
239 useIsomorphicLayoutEffect(() => {
240 if (openProp !== undefined) {
241 store.setState("open", openProp);
242 }
243 }, [openProp]);
244
245 const open = useStore((state) => state.open, store);
246
247 const onPointerDownCapture = React.useCallback(
248 (event: React.PointerEvent<RootElement>) => {
249 propsRef.current?.onPointerDownCapture?.(event);
250 if (event.defaultPrevented) return;
251
252 const target = event.target as HTMLElement;
253 const nodes = getNodes();
254 const isInteractiveElement = nodes.some((node) =>
255 node.ref.current?.contains(target),
256 );
257
258 isPointerInsideReactTreeRef.current = isInteractiveElement;
259 },
260 [propsRef, getNodes],
261 );
262
263 const contextValue = React.useMemo<SpeedDialContextValue>(
264 () => ({
265 getNodes,
266 onNodeRegister,
267 onNodeUnregister,
268 contentId,
269 rootRef,
270 triggerRef,
271 isPointerInsideReactTreeRef,
272 hoverCloseTimerRef,
273 side,
274 activationMode,
275 delay,
276 disabled,
277 }),
278 [
279 getNodes,
280 onNodeRegister,
281 onNodeUnregister,
282 contentId,
283 side,
284 activationMode,
285 delay,
286 disabled,
287 ],
288 );
289
290 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
291
292 return (
293 <StoreContext.Provider value={store}>
294 <SpeedDialContext.Provider value={contextValue}>
295 <RootPrimitive
296 data-slot="speed-dial"
297 data-state={getDataState(open)}
298 data-disabled={disabled}
299 {...rootProps}
300 ref={composedRefs}
301 className={cn("relative flex flex-col items-end", className)}
302 onPointerDownCapture={onPointerDownCapture}
303 />
304 </SpeedDialContext.Provider>
305 </StoreContext.Provider>
306 );
307}
308
309function SpeedDialTrigger(props: React.ComponentProps<typeof Button>) {
310 const {
311 onClick: onClickProp,
312 onMouseEnter: onMouseEnterProp,
313 onMouseLeave: onMouseLeaveProp,
314 className,
315 disabled: disabledProp,
316 id,
317 ref,
318 ...triggerProps
319 } = props;
320
321 const store = useStoreContext(TRIGGER_NAME);
322
323 const {
324 onNodeRegister,
325 onNodeUnregister,
326 contentId,
327 hoverCloseTimerRef,
328 triggerRef,
329 activationMode,
330 delay,
331 disabled,
332 } = useSpeedDialContext(TRIGGER_NAME);
333
334 const open = useStore((state) => state.open);
335 const isDisabled = disabledProp || disabled;
336
337 const instanceId = React.useId();
338 const triggerId = id ?? instanceId;
339
340 const composedRef = useComposedRefs(ref, triggerRef);
341 const hoverOpenTimerRef = React.useRef<number | null>(null);
342
343 useIsomorphicLayoutEffect(() => {
344 onNodeRegister({
345 id: triggerId,
346 ref: triggerRef,
347 disabled: isDisabled,
348 });
349
350 return () => {
351 onNodeUnregister(triggerId);
352 };
353 }, [onNodeRegister, onNodeUnregister, triggerId, isDisabled]);
354
355 React.useEffect(() => {
356 return () => {
357 if (hoverOpenTimerRef.current) {
358 window.clearTimeout(hoverOpenTimerRef.current);
359 }
360 if (hoverCloseTimerRef.current) {
361 window.clearTimeout(hoverCloseTimerRef.current);
362 }
363 };
364 }, [hoverCloseTimerRef]);
365
366 const onClick = React.useCallback(
367 (event: React.MouseEvent<TriggerElement>) => {
368 onClickProp?.(event);
369 if (event.defaultPrevented) return;
370
371 if (hoverOpenTimerRef.current) {
372 window.clearTimeout(hoverOpenTimerRef.current);
373 hoverOpenTimerRef.current = null;
374 }
375 if (hoverCloseTimerRef.current) {
376 window.clearTimeout(hoverCloseTimerRef.current);
377 hoverCloseTimerRef.current = null;
378 }
379
380 store.setState("open", !open);
381 },
382 [onClickProp, store, open, hoverCloseTimerRef],
383 );
384
385 const onMouseEnter = React.useCallback(
386 (event: React.MouseEvent<TriggerElement>) => {
387 onMouseEnterProp?.(event);
388 if (event.defaultPrevented || activationMode !== "hover" || isDisabled)
389 return;
390
391 if (hoverCloseTimerRef.current) {
392 window.clearTimeout(hoverCloseTimerRef.current);
393 hoverCloseTimerRef.current = null;
394 }
395
396 if (hoverOpenTimerRef.current) {
397 window.clearTimeout(hoverOpenTimerRef.current);
398 }
399
400 hoverOpenTimerRef.current = window.setTimeout(() => {
401 store.setState("open", true);
402 }, delay);
403 },
404 [
405 onMouseEnterProp,
406 activationMode,
407 isDisabled,
408 store,
409 delay,
410 hoverCloseTimerRef,
411 ],
412 );
413
414 const onMouseLeave = React.useCallback(
415 (event: React.MouseEvent<TriggerElement>) => {
416 onMouseLeaveProp?.(event);
417 if (event.defaultPrevented || activationMode !== "hover" || isDisabled)
418 return;
419
420 if (hoverOpenTimerRef.current) {
421 window.clearTimeout(hoverOpenTimerRef.current);
422 hoverOpenTimerRef.current = null;
423 }
424
425 hoverCloseTimerRef.current = window.setTimeout(() => {
426 store.setState("open", false);
427 }, DEFAULT_HOVER_CLOSE_DELAY);
428 },
429 [onMouseLeaveProp, activationMode, isDisabled, store, hoverCloseTimerRef],
430 );
431
432 return (
433 <Button
434 type="button"
435 role="button"
436 id={triggerId}
437 aria-controls={contentId}
438 aria-expanded={open}
439 aria-haspopup="menu"
440 data-slot="speed-dial-trigger"
441 data-state={getDataState(open)}
442 disabled={isDisabled}
443 size="icon"
444 {...triggerProps}
445 ref={composedRef}
446 className={cn("size-11 rounded-full", className)}
447 onClick={onClick}
448 onMouseEnter={onMouseEnter}
449 onMouseLeave={onMouseLeave}
450 />
451 );
452}
453
454interface SpeedDialItemImplContextValue {
455 delay: number;
456 open: boolean;
457}
458
459const SpeedDialItemImplContext =
460 React.createContext<SpeedDialItemImplContextValue | null>(null);
461
462function useSpeedDialItemImplContext() {
463 return React.useContext(SpeedDialItemImplContext);
464}
465
466interface SpeedDialItemImplProps {
467 delay: number;
468 open: boolean;
469 children: React.ReactNode;
470}
471
472const SpeedDialItemImpl = React.memo(function SpeedDialItemImpl({
473 delay,
474 open,
475 children,
476}: SpeedDialItemImplProps) {
477 const contextValue = React.useMemo<SpeedDialItemImplContextValue>(
478 () => ({ delay, open }),
479 [delay, open],
480 );
481
482 return (
483 <SpeedDialItemImplContext.Provider value={contextValue}>
484 {children}
485 </SpeedDialItemImplContext.Provider>
486 );
487});
488
489const speedDialContentVariants = cva(
490 "absolute z-50 flex gap-[var(--speed-dial-gap)] data-[state=closed]:pointer-events-none",
491 {
492 variants: {
493 side: {
494 top: "flex-col-reverse items-end",
495 bottom: "flex-col items-end",
496 left: "flex-row-reverse items-center",
497 right: "flex-row items-center",
498 },
499 },
500 defaultVariants: {
501 side: "top",
502 },
503 },
504);
505
506interface SpeedDialContentProps
507 extends DivProps,
508 VariantProps<typeof speedDialContentVariants> {
509 offset?: number;
510 gap?: number;
511 forceMount?: boolean;
512 onEscapeKeyDown?: (event: KeyboardEvent) => void;
513 onInteractOutside?: (event: InteractOutsideEvent) => void;
514}
515
516function SpeedDialContent(props: SpeedDialContentProps) {
517 const {
518 offset = DEFAULT_OFFSET,
519 gap = DEFAULT_GAP,
520 forceMount = false,
521 onEscapeKeyDown,
522 onInteractOutside,
523 onMouseEnter: onMouseEnterProp,
524 onMouseLeave: onMouseLeaveProp,
525 asChild,
526 className,
527 children,
528 style,
529 ref,
530 ...contentProps
531 } = props;
532
533 const store = useStoreContext(CONTENT_NAME);
534 const open = useStore((state) => state.open);
535
536 const {
537 contentId,
538 side,
539 getNodes,
540 rootRef,
541 triggerRef,
542 isPointerInsideReactTreeRef,
543 hoverCloseTimerRef,
544 activationMode,
545 } = useSpeedDialContext(CONTENT_NAME);
546
547 const contentRef = React.useRef<ContentElement | null>(null);
548 const composedRef = useComposedRefs(ref, contentRef);
549
550 const propsRef = useAsRef({
551 onMouseEnter: onMouseEnterProp,
552 onMouseLeave: onMouseLeaveProp,
553 onEscapeKeyDown,
554 onInteractOutside,
555 });
556
557 const orientation =
558 side === "top" || side === "bottom" ? "vertical" : "horizontal";
559
560 const transformOrigin = React.useMemo(() => getTransformOrigin(side), [side]);
561
562 const ownerDocument =
563 contentRef.current?.ownerDocument ?? globalThis?.document;
564
565 const mounted = React.useSyncExternalStore(
566 () => () => {},
567 () => true,
568 () => false,
569 );
570
571 const [renderState, setRenderState] = React.useState({
572 shouldRender: false,
573 animating: false,
574 });
575 const [position, setPosition] = React.useState<React.CSSProperties>({});
576
577 const openRafRef = React.useRef<number | null>(null);
578 const unmountTimerRef = React.useRef<number | null>(null);
579
580 React.useEffect(() => {
581 if (open) {
582 if (unmountTimerRef.current) {
583 clearTimeout(unmountTimerRef.current);
584 unmountTimerRef.current = null;
585 }
586
587 setRenderState((prev) => ({ ...prev, shouldRender: true }));
588
589 if (openRafRef.current) cancelAnimationFrame(openRafRef.current);
590 openRafRef.current = requestAnimationFrame(() => {
591 setRenderState((prev) => ({ ...prev, animating: true }));
592 openRafRef.current = null;
593 });
594
595 return () => {
596 if (openRafRef.current) {
597 cancelAnimationFrame(openRafRef.current);
598 openRafRef.current = null;
599 }
600 };
601 } else {
602 setRenderState((prev) => ({ ...prev, animating: false }));
603
604 if (!forceMount) {
605 const childCount = React.Children.count(children);
606 const animationDuration = DEFAULT_ANIMATION_DURATION;
607 const longestDelay = (childCount - 1) * DEFAULT_ITEM_DELAY;
608 const totalDuration = longestDelay + animationDuration;
609
610 unmountTimerRef.current = window.setTimeout(() => {
611 setRenderState((prev) => ({ ...prev, shouldRender: false }));
612 }, totalDuration);
613
614 return () => {
615 if (unmountTimerRef.current) {
616 clearTimeout(unmountTimerRef.current);
617 unmountTimerRef.current = null;
618 }
619 };
620 }
621 }
622 }, [open, forceMount, children]);
623
624 const updatePosition = React.useCallback(() => {
625 if (!triggerRef.current || !open) return;
626
627 const newPosition: React.CSSProperties = {};
628
629 switch (side) {
630 case "top":
631 newPosition.bottom = `calc(100% + ${offset}px)`;
632 newPosition.right = "0";
633 break;
634 case "bottom":
635 newPosition.top = `calc(100% + ${offset}px)`;
636 newPosition.right = "0";
637 break;
638 case "left":
639 newPosition.right = `calc(100% + ${offset}px)`;
640 newPosition.top = "0";
641 break;
642 case "right":
643 newPosition.left = `calc(100% + ${offset}px)`;
644 newPosition.top = "0";
645 break;
646 }
647
648 setPosition((prev) => {
649 const hasChanged = Object.keys(newPosition).some((key) => {
650 const k = key as keyof typeof newPosition;
651 return prev[k] !== newPosition[k];
652 });
653 return hasChanged ? newPosition : prev;
654 });
655 }, [triggerRef, open, side, offset]);
656
657 useIsomorphicLayoutEffect(() => {
658 if (!open) return;
659 updatePosition();
660 }, [open, updatePosition]);
661
662 React.useEffect(() => {
663 if (!open) return;
664
665 const onKeyDown = (event: KeyboardEvent) => {
666 if (event.key === "Escape") {
667 propsRef.current?.onEscapeKeyDown?.(event);
668 if (event.defaultPrevented) return;
669
670 store.setState("open", false);
671 }
672
673 if (event.key === "Tab") {
674 const focusableElements = getNodes()
675 .filter((node) => !node.disabled)
676 .map((node) => node.ref.current);
677
678 if (focusableElements.length === 0) return;
679
680 const firstElement = focusableElements[0];
681 const lastElement = focusableElements[focusableElements.length - 1];
682 const activeElement = ownerDocument.activeElement;
683
684 if (event.shiftKey) {
685 if (activeElement === firstElement) {
686 store.setState("open", false);
687 }
688 } else {
689 if (activeElement === lastElement) {
690 store.setState("open", false);
691 }
692 }
693 }
694 };
695
696 ownerDocument.addEventListener("keydown", onKeyDown);
697 return () => ownerDocument.removeEventListener("keydown", onKeyDown);
698 }, [open, propsRef, ownerDocument, store, getNodes]);
699
700 const onClickRef = React.useRef<() => void>(() => {});
701
702 React.useEffect(() => {
703 if (!open) return;
704
705 isPointerInsideReactTreeRef.current = false;
706
707 const onPointerDown = (event: PointerEvent) => {
708 if (event.target && !isPointerInsideReactTreeRef.current) {
709 const target = event.target as HTMLElement;
710 const isOutside = !rootRef.current?.contains(target);
711
712 function onDismiss() {
713 if (isOutside) {
714 const interactEvent = new CustomEvent(INTERACT_OUTSIDE, {
715 ...EVENT_OPTIONS,
716 detail: { originalEvent: event },
717 }) as InteractOutsideEvent;
718
719 propsRef.current?.onInteractOutside?.(interactEvent);
720 if (interactEvent.defaultPrevented) return;
721 }
722
723 store.setState("open", false);
724 }
725
726 if (event.pointerType === "touch") {
727 ownerDocument.removeEventListener("click", onClickRef.current);
728 onClickRef.current = onDismiss;
729 ownerDocument.addEventListener("click", onClickRef.current, {
730 once: true,
731 });
732 } else {
733 onDismiss();
734 }
735 } else {
736 ownerDocument.removeEventListener("click", onClickRef.current);
737 }
738 isPointerInsideReactTreeRef.current = false;
739 };
740
741 const timerId = window.setTimeout(() => {
742 ownerDocument.addEventListener("pointerdown", onPointerDown);
743 }, 0);
744
745 return () => {
746 window.clearTimeout(timerId);
747 ownerDocument.removeEventListener("pointerdown", onPointerDown);
748 ownerDocument.removeEventListener("click", onClickRef.current);
749 };
750 }, [
751 open,
752 rootRef,
753 isPointerInsideReactTreeRef,
754 propsRef,
755 ownerDocument,
756 store,
757 ]);
758
759 const onMouseEnter = React.useCallback(
760 (event: React.MouseEvent<ContentElement>) => {
761 propsRef.current?.onMouseEnter?.(event);
762 if (event.defaultPrevented || activationMode !== "hover") return;
763
764 if (hoverCloseTimerRef.current) {
765 window.clearTimeout(hoverCloseTimerRef.current);
766 hoverCloseTimerRef.current = null;
767 }
768 },
769 [propsRef, hoverCloseTimerRef, activationMode],
770 );
771
772 const onMouseLeave = React.useCallback(
773 (event: React.MouseEvent<ContentElement>) => {
774 propsRef.current?.onMouseLeave?.(event);
775 if (event.defaultPrevented || activationMode !== "hover") return;
776
777 hoverCloseTimerRef.current = window.setTimeout(() => {
778 store.setState("open", false);
779 }, DEFAULT_HOVER_CLOSE_DELAY);
780 },
781 [propsRef, hoverCloseTimerRef, store, activationMode],
782 );
783
784 const contentStyle = React.useMemo<React.CSSProperties>(
785 () => ({
786 "--speed-dial-gap": `${gap}px`,
787 "--speed-dial-offset": `${offset}px`,
788 "--speed-dial-transform-origin": transformOrigin,
789 ...position,
790 ...style,
791 }),
792 [gap, offset, transformOrigin, position, style],
793 );
794
795 const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
796
797 const shouldMount = forceMount || renderState.shouldRender;
798
799 if (!mounted || !shouldMount) return null;
800
801 return (
802 <ContentPrimitive
803 id={contentId}
804 role="menu"
805 aria-orientation={orientation}
806 data-slot="speed-dial-content"
807 data-state={getDataState(renderState.animating)}
808 data-orientation={orientation}
809 data-side={side}
810 {...contentProps}
811 ref={composedRef}
812 className={cn(speedDialContentVariants({ side, className }))}
813 style={contentStyle}
814 onMouseEnter={onMouseEnter}
815 onMouseLeave={onMouseLeave}
816 >
817 {(() => {
818 const totalChildren = React.Children.count(children);
819 return React.Children.map(children, (child, index) => {
820 if (!React.isValidElement(child)) return child;
821
822 const delay = renderState.animating
823 ? index * DEFAULT_ITEM_DELAY
824 : (totalChildren - index - 1) * DEFAULT_ITEM_DELAY;
825
826 return (
827 <SpeedDialItemImpl
828 key={child.key ?? index}
829 delay={delay}
830 open={renderState.animating}
831 >
832 {child}
833 </SpeedDialItemImpl>
834 );
835 });
836 })()}
837 </ContentPrimitive>
838 );
839}
840
841const speedDialItemVariants = cva(
842 "flex items-center gap-2 transition-all [transition-delay:var(--speed-dial-delay)] [transition-duration:var(--speed-dial-animation-duration)] data-[state=open]:translate-x-0 data-[state=open]:translate-y-0 data-[state=closed]:opacity-0 data-[state=open]:opacity-100",
843 {
844 variants: {
845 side: {
846 top: "justify-end",
847 bottom: "justify-end",
848 left: "flex-row-reverse justify-start",
849 right: "justify-start",
850 },
851 },
852 compoundVariants: [
853 {
854 side: "top",
855 className: "data-[state=closed]:translate-y-2",
856 },
857 {
858 side: "bottom",
859 className: "data-[state=closed]:-translate-y-2",
860 },
861 {
862 side: "left",
863 className: "data-[state=closed]:translate-x-2",
864 },
865 {
866 side: "right",
867 className: "data-[state=closed]:-translate-x-2",
868 },
869 ],
870 defaultVariants: {
871 side: "top",
872 },
873 },
874);
875
876interface SpeedDialItemContextValue {
877 actionId: string;
878 labelId: string;
879}
880
881const SpeedDialItemContext =
882 React.createContext<SpeedDialItemContextValue | null>(null);
883
884function useSpeedDialItemContext(consumerName: string) {
885 const context = React.useContext(SpeedDialItemContext);
886 if (!context) {
887 throw new Error(`\`${consumerName}\` must be used within \`${ITEM_NAME}\``);
888 }
889 return context;
890}
891
892function SpeedDialItem(props: DivProps) {
893 const { asChild, className, style, children, ...itemProps } = props;
894
895 const { side } = useSpeedDialContext(ITEM_NAME);
896 const itemImplContext = useSpeedDialItemImplContext();
897 const delay = itemImplContext?.delay ?? 0;
898 const open = itemImplContext?.open ?? false;
899
900 const actionId = React.useId();
901 const labelId = React.useId();
902
903 const contextValue = React.useMemo<SpeedDialItemContextValue>(
904 () => ({ actionId, labelId }),
905 [actionId, labelId],
906 );
907
908 const itemStyle = React.useMemo<React.CSSProperties>(
909 () => ({
910 "--speed-dial-animation-duration": `${DEFAULT_ANIMATION_DURATION}ms`,
911 "--speed-dial-delay": `${delay}ms`,
912 ...style,
913 }),
914 [delay, style],
915 );
916
917 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
918
919 return (
920 <SpeedDialItemContext.Provider value={contextValue}>
921 <ItemPrimitive
922 role="none"
923 data-slot="speed-dial-item"
924 data-state={getDataState(open)}
925 data-side={side}
926 {...itemProps}
927 className={cn(speedDialItemVariants({ side, className }))}
928 style={itemStyle}
929 >
930 {children}
931 </ItemPrimitive>
932 </SpeedDialItemContext.Provider>
933 );
934}
935
936interface SpeedDialActionProps
937 extends Omit<React.ComponentProps<typeof Button>, "onSelect"> {
938 onSelect?: (event: Event) => void;
939}
940
941function SpeedDialAction(props: SpeedDialActionProps) {
942 const {
943 onSelect,
944 onClick: onClickProp,
945 className,
946 disabled,
947 id,
948 ref,
949 ...actionProps
950 } = props;
951
952 const propsRef = useAsRef({
953 onClick: onClickProp,
954 onSelect,
955 });
956
957 const store = useStoreContext(ACTION_NAME);
958
959 const { onNodeRegister, onNodeUnregister } = useSpeedDialContext(ACTION_NAME);
960 const { actionId: itemActionId, labelId } =
961 useSpeedDialItemContext(ACTION_NAME);
962
963 const actionId = id ?? itemActionId;
964
965 const actionRef = React.useRef<ActionElement | null>(null);
966 const composedRefs = useComposedRefs(ref, actionRef);
967
968 useIsomorphicLayoutEffect(() => {
969 onNodeRegister({
970 id: actionId,
971 ref: actionRef,
972 disabled: !!disabled,
973 });
974
975 return () => {
976 onNodeUnregister(actionId);
977 };
978 }, [onNodeRegister, onNodeUnregister, actionId, disabled]);
979
980 const onClick = React.useCallback(
981 (event: React.MouseEvent<ActionElement>) => {
982 propsRef.current?.onClick?.(event);
983 if (event.defaultPrevented) return;
984
985 const action = actionRef.current;
986 if (!action) return;
987
988 const actionSelectEvent = new CustomEvent(ACTION_SELECT, EVENT_OPTIONS);
989
990 action.addEventListener(
991 ACTION_SELECT,
992 (event) => propsRef.current?.onSelect?.(event),
993 {
994 once: true,
995 },
996 );
997
998 action.dispatchEvent(actionSelectEvent);
999 if (actionSelectEvent.defaultPrevented) return;
1000
1001 store.setState("open", false);
1002 },
1003 [propsRef, store],
1004 );
1005
1006 return (
1007 <Button
1008 type="button"
1009 role="menuitem"
1010 id={actionId}
1011 aria-labelledby={labelId}
1012 data-slot="speed-dial-action"
1013 variant="outline"
1014 size="icon"
1015 disabled={disabled}
1016 ref={composedRefs}
1017 {...actionProps}
1018 className={cn(
1019 "size-11 shrink-0 rounded-full bg-accent shadow-md",
1020 className,
1021 )}
1022 onClick={onClick}
1023 />
1024 );
1025}
1026
1027function SpeedDialLabel({ asChild, className, ...props }: DivProps) {
1028 const { labelId } = useSpeedDialItemContext(LABEL_NAME);
1029
1030 const LabelPrimitive = asChild ? SlotPrimitive.Slot : "div";
1031
1032 return (
1033 <LabelPrimitive
1034 id={labelId}
1035 data-slot="speed-dial-label"
1036 {...props}
1037 className={cn(
1038 "pointer-events-none whitespace-nowrap rounded-md bg-popover px-2 py-1 text-popover-foreground text-sm shadow-md",
1039 className,
1040 )}
1041 />
1042 );
1043}
1044
1045export {
1046 SpeedDial,
1047 SpeedDialAction,
1048 SpeedDialContent,
1049 SpeedDialItem,
1050 SpeedDialLabel,
1051 type SpeedDialProps,
1052 SpeedDialTrigger,
1053};
1054