1"use client";
2
3import {
4 Direction as DirectionPrimitive,
5 Slot as SlotPrimitive,
6} from "radix-ui";
7import * as React from "react";
8import * as ReactDOM from "react-dom";
9import { useComposedRefs } from "@/lib/compose-refs";
10import { cn } from "@/lib/utils";
11import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
12import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
13import { Button } from "@/registry/bases/radix/ui/button";
14
15const ROOT_NAME = "ActionBar";
16const GROUP_NAME = "ActionBarGroup";
17const ITEM_NAME = "ActionBarItem";
18const CLOSE_NAME = "ActionBarClose";
19const SEPARATOR_NAME = "ActionBarSeparator";
20const ITEM_SELECT = "actionbar.itemSelect";
21const ENTRY_FOCUS = "actionbarFocusGroup.onEntryFocus";
22const EVENT_OPTIONS = { bubbles: false, cancelable: true };
23
24type Direction = "ltr" | "rtl";
25type Orientation = "horizontal" | "vertical";
26
27interface DivProps extends React.ComponentProps<"div"> {
28 asChild?: boolean;
29}
30
31type RootElement = React.ComponentRef<typeof ActionBar>;
32type ItemElement = React.ComponentRef<typeof ActionBarItem>;
33type CloseElement = React.ComponentRef<typeof ActionBarClose>;
34
35function focusFirst(
36 candidates: React.RefObject<HTMLElement | null>[],
37 preventScroll = false,
38) {
39 const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
40 for (const candidateRef of candidates) {
41 const candidate = candidateRef.current;
42 if (!candidate) continue;
43 if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
44 candidate.focus({ preventScroll });
45 if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
46 }
47}
48
49function wrapArray<T>(array: T[], startIndex: number) {
50 return array.map<T>(
51 (_, index) => array[(startIndex + index) % array.length] as T,
52 );
53}
54
55function getDirectionAwareKey(key: string, dir?: Direction) {
56 if (dir !== "rtl") return key;
57 return key === "ArrowLeft"
58 ? "ArrowRight"
59 : key === "ArrowRight"
60 ? "ArrowLeft"
61 : key;
62}
63
64interface ItemData {
65 id: string;
66 ref: React.RefObject<ItemElement | null>;
67 disabled: boolean;
68}
69
70interface ActionBarContextValue {
71 onOpenChange?: (open: boolean) => void;
72 dir: Direction;
73 orientation: Orientation;
74 loop: boolean;
75}
76
77const ActionBarContext = React.createContext<ActionBarContextValue | null>(
78 null,
79);
80
81function useActionBarContext(consumerName: string) {
82 const context = React.useContext(ActionBarContext);
83 if (!context) {
84 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
85 }
86 return context;
87}
88
89interface FocusContextValue {
90 tabStopId: string | null;
91 onItemFocus: (tabStopId: string) => void;
92 onItemShiftTab: () => void;
93 onFocusableItemAdd: () => void;
94 onFocusableItemRemove: () => void;
95 onItemRegister: (item: ItemData) => void;
96 onItemUnregister: (id: string) => void;
97 getItems: () => ItemData[];
98}
99
100const FocusContext = React.createContext<FocusContextValue | null>(null);
101
102function useFocusContext(consumerName: string) {
103 const context = React.useContext(FocusContext);
104 if (!context) {
105 throw new Error(
106 `\`${consumerName}\` must be used within \`FocusProvider\``,
107 );
108 }
109 return context;
110}
111
112interface ActionBarProps extends DivProps {
113 open?: boolean;
114 onOpenChange?: (open: boolean) => void;
115 onEscapeKeyDown?: (event: KeyboardEvent) => void;
116 align?: "start" | "center" | "end";
117 alignOffset?: number;
118 side?: "top" | "bottom";
119 sideOffset?: number;
120 portalContainer?: Element | DocumentFragment | null;
121 dir?: Direction;
122 orientation?: Orientation;
123 loop?: boolean;
124}
125
126function ActionBar(props: ActionBarProps) {
127 const {
128 open = false,
129 onOpenChange,
130 onEscapeKeyDown,
131 side = "bottom",
132 alignOffset = 0,
133 align = "center",
134 sideOffset = 16,
135 portalContainer: portalContainerProp,
136 dir: dirProp,
137 orientation = "horizontal",
138 loop = true,
139 className,
140 style,
141 ref,
142 asChild,
143 ...rootProps
144 } = props;
145
146 const [mounted, setMounted] = React.useState(false);
147
148 const rootRef = React.useRef<RootElement>(null);
149 const composedRef = useComposedRefs(ref, rootRef);
150
151 const propsRef = useAsRef({
152 onEscapeKeyDown,
153 onOpenChange,
154 });
155
156 const dir = DirectionPrimitive.useDirection(dirProp);
157
158 React.useLayoutEffect(() => {
159 setMounted(true);
160 }, []);
161
162 React.useEffect(() => {
163 if (!open) return;
164
165 const ownerDocument = rootRef.current?.ownerDocument ?? document;
166
167 function onKeyDown(event: KeyboardEvent) {
168 if (event.key === "Escape") {
169 propsRef.current.onEscapeKeyDown?.(event);
170 if (!event.defaultPrevented) {
171 propsRef.current.onOpenChange?.(false);
172 }
173 }
174 }
175
176 ownerDocument.addEventListener("keydown", onKeyDown);
177 return () => ownerDocument.removeEventListener("keydown", onKeyDown);
178 }, [open, propsRef]);
179
180 const contextValue = React.useMemo<ActionBarContextValue>(
181 () => ({
182 onOpenChange,
183 dir,
184 orientation,
185 loop,
186 }),
187 [onOpenChange, dir, orientation, loop],
188 );
189
190 const portalContainer =
191 portalContainerProp ?? (mounted ? globalThis.document?.body : null);
192
193 if (!portalContainer || !open) return null;
194
195 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
196
197 return (
198 <ActionBarContext.Provider value={contextValue}>
199 {ReactDOM.createPortal(
200 <RootPrimitive
201 role="toolbar"
202 aria-orientation={orientation}
203 data-slot="action-bar"
204 data-side={side}
205 data-align={align}
206 data-orientation={orientation}
207 dir={dir}
208 {...rootProps}
209 ref={composedRef}
210 className={cn(
211 "fixed z-50 rounded-lg border bg-card shadow-lg outline-none",
212 "fade-in-0 zoom-in-95 animate-in duration-250 [animation-timing-function:cubic-bezier(0.16,1,0.3,1)]",
213 "data-[side=bottom]:slide-in-from-bottom-4 data-[side=top]:slide-in-from-top-4",
214 "motion-reduce:animate-none motion-reduce:transition-none",
215 orientation === "horizontal"
216 ? "flex flex-row items-center gap-2 px-2 py-1.5"
217 : "flex flex-col items-start gap-2 px-1.5 py-2",
218 className,
219 )}
220 style={{
221 [side]: `${sideOffset}px`,
222 ...(align === "center" && {
223 left: "50%",
224 translate: "-50% 0",
225 }),
226 ...(align === "start" && { left: `${alignOffset}px` }),
227 ...(align === "end" && { right: `${alignOffset}px` }),
228 ...style,
229 }}
230 />,
231 portalContainer,
232 )}
233 </ActionBarContext.Provider>
234 );
235}
236
237function ActionBarSelection(props: DivProps) {
238 const { className, asChild, ...selectionProps } = props;
239
240 const SelectionPrimitive = asChild ? SlotPrimitive.Slot : "div";
241
242 return (
243 <SelectionPrimitive
244 data-slot="action-bar-selection"
245 {...selectionProps}
246 className={cn(
247 "flex items-center gap-1 rounded-sm border px-2 py-1 font-medium text-sm tabular-nums",
248 className,
249 )}
250 />
251 );
252}
253
254function ActionBarGroup(props: DivProps) {
255 const {
256 onBlur: onBlurProp,
257 onFocus: onFocusProp,
258 onMouseDown: onMouseDownProp,
259 className,
260 asChild,
261 ref,
262 ...groupProps
263 } = props;
264
265 const [tabStopId, setTabStopId] = React.useState<string | null>(null);
266 const [isTabbingBackOut, setIsTabbingBackOut] = React.useState(false);
267 const [focusableItemCount, setFocusableItemCount] = React.useState(0);
268
269 const groupRef = React.useRef<HTMLDivElement>(null);
270 const composedRef = useComposedRefs(ref, groupRef);
271 const isClickFocusRef = React.useRef(false);
272 const itemsRef = React.useRef<Map<string, ItemData>>(new Map());
273
274 const { dir, orientation } = useActionBarContext(GROUP_NAME);
275
276 const onItemFocus = React.useCallback((tabStopId: string) => {
277 setTabStopId(tabStopId);
278 }, []);
279
280 const onItemShiftTab = React.useCallback(() => {
281 setIsTabbingBackOut(true);
282 }, []);
283
284 const onFocusableItemAdd = React.useCallback(() => {
285 setFocusableItemCount((prevCount) => prevCount + 1);
286 }, []);
287
288 const onFocusableItemRemove = React.useCallback(() => {
289 setFocusableItemCount((prevCount) => prevCount - 1);
290 }, []);
291
292 const onItemRegister = React.useCallback((item: ItemData) => {
293 itemsRef.current.set(item.id, item);
294 }, []);
295
296 const onItemUnregister = React.useCallback((id: string) => {
297 itemsRef.current.delete(id);
298 }, []);
299
300 const getItems = React.useCallback(() => {
301 return Array.from(itemsRef.current.values())
302 .filter((item) => item.ref.current)
303 .sort((a, b) => {
304 const elementA = a.ref.current;
305 const elementB = b.ref.current;
306 if (!elementA || !elementB) return 0;
307 const position = elementA.compareDocumentPosition(elementB);
308 if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
309 return -1;
310 }
311 if (position & Node.DOCUMENT_POSITION_PRECEDING) {
312 return 1;
313 }
314 return 0;
315 });
316 }, []);
317
318 const onBlur = React.useCallback(
319 (event: React.FocusEvent<HTMLDivElement>) => {
320 onBlurProp?.(event);
321 if (event.defaultPrevented) return;
322
323 setIsTabbingBackOut(false);
324 },
325 [onBlurProp],
326 );
327
328 const onFocus = React.useCallback(
329 (event: React.FocusEvent<HTMLDivElement>) => {
330 onFocusProp?.(event);
331 if (event.defaultPrevented) return;
332
333 const isKeyboardFocus = !isClickFocusRef.current;
334 if (
335 event.target === event.currentTarget &&
336 isKeyboardFocus &&
337 !isTabbingBackOut
338 ) {
339 const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS);
340 event.currentTarget.dispatchEvent(entryFocusEvent);
341
342 if (!entryFocusEvent.defaultPrevented) {
343 const items = Array.from(itemsRef.current.values()).filter(
344 (item) => !item.disabled,
345 );
346 const currentItem = items.find((item) => item.id === tabStopId);
347
348 const candidateItems = [currentItem, ...items].filter(
349 Boolean,
350 ) as ItemData[];
351 const candidateRefs = candidateItems.map((item) => item.ref);
352 focusFirst(candidateRefs, false);
353 }
354 }
355 isClickFocusRef.current = false;
356 },
357 [onFocusProp, isTabbingBackOut, tabStopId],
358 );
359
360 const onMouseDown = React.useCallback(
361 (event: React.MouseEvent<HTMLDivElement>) => {
362 onMouseDownProp?.(event);
363 if (event.defaultPrevented) return;
364
365 isClickFocusRef.current = true;
366 },
367 [onMouseDownProp],
368 );
369
370 const focusContextValue = React.useMemo<FocusContextValue>(
371 () => ({
372 tabStopId,
373 onItemFocus,
374 onItemShiftTab,
375 onFocusableItemAdd,
376 onFocusableItemRemove,
377 onItemRegister,
378 onItemUnregister,
379 getItems,
380 }),
381 [
382 tabStopId,
383 onItemFocus,
384 onItemShiftTab,
385 onFocusableItemAdd,
386 onFocusableItemRemove,
387 onItemRegister,
388 onItemUnregister,
389 getItems,
390 ],
391 );
392
393 const GroupPrimitive = asChild ? SlotPrimitive.Slot : "div";
394
395 return (
396 <FocusContext.Provider value={focusContextValue}>
397 <GroupPrimitive
398 role="group"
399 data-slot="action-bar-group"
400 data-orientation={orientation}
401 dir={dir}
402 tabIndex={isTabbingBackOut || focusableItemCount === 0 ? -1 : 0}
403 {...groupProps}
404 ref={composedRef}
405 className={cn(
406 "flex gap-2 outline-none",
407 orientation === "horizontal"
408 ? "items-center"
409 : "w-full flex-col items-start",
410 className,
411 )}
412 onBlur={onBlur}
413 onFocus={onFocus}
414 onMouseDown={onMouseDown}
415 />
416 </FocusContext.Provider>
417 );
418}
419
420interface ActionBarItemProps
421 extends Omit<React.ComponentProps<typeof Button>, "onSelect"> {
422 onSelect?: (event: Event) => void;
423}
424
425function ActionBarItem(props: ActionBarItemProps) {
426 const {
427 onSelect,
428 onClick: onClickProp,
429 onFocus: onFocusProp,
430 onKeyDown: onKeyDownProp,
431 onMouseDown: onMouseDownProp,
432 className,
433 disabled,
434 ref,
435 ...itemProps
436 } = props;
437
438 const itemRef = React.useRef<ItemElement>(null);
439 const composedRef = useComposedRefs(ref, itemRef);
440 const isMouseClickRef = React.useRef(false);
441
442 const { onOpenChange, dir, orientation, loop } =
443 useActionBarContext(ITEM_NAME);
444 const focusContext = useFocusContext(ITEM_NAME);
445
446 const itemId = React.useId();
447 const isTabStop = focusContext.tabStopId === itemId;
448
449 useIsomorphicLayoutEffect(() => {
450 focusContext.onItemRegister({
451 id: itemId,
452 ref: itemRef,
453 disabled: !!disabled,
454 });
455
456 if (!disabled) {
457 focusContext.onFocusableItemAdd();
458 }
459
460 return () => {
461 focusContext.onItemUnregister(itemId);
462 if (!disabled) {
463 focusContext.onFocusableItemRemove();
464 }
465 };
466 }, [focusContext, itemId, disabled]);
467
468 const onClick = React.useCallback(
469 (event: React.MouseEvent<ItemElement>) => {
470 onClickProp?.(event);
471 if (event.defaultPrevented) return;
472
473 const item = itemRef.current;
474 if (!item) return;
475
476 const itemSelectEvent = new CustomEvent(ITEM_SELECT, {
477 bubbles: true,
478 cancelable: true,
479 });
480
481 item.addEventListener(ITEM_SELECT, (event) => onSelect?.(event), {
482 once: true,
483 });
484
485 item.dispatchEvent(itemSelectEvent);
486
487 if (!itemSelectEvent.defaultPrevented) {
488 onOpenChange?.(false);
489 }
490 },
491 [onClickProp, onOpenChange, onSelect],
492 );
493
494 const onFocus = React.useCallback(
495 (event: React.FocusEvent<ItemElement>) => {
496 onFocusProp?.(event);
497 if (event.defaultPrevented) return;
498
499 focusContext.onItemFocus(itemId);
500 isMouseClickRef.current = false;
501 },
502 [onFocusProp, focusContext, itemId],
503 );
504
505 const onKeyDown = React.useCallback(
506 (event: React.KeyboardEvent<ItemElement>) => {
507 onKeyDownProp?.(event);
508 if (event.defaultPrevented) return;
509
510 if (event.key === "Tab" && event.shiftKey) {
511 focusContext.onItemShiftTab();
512 return;
513 }
514
515 if (event.target !== event.currentTarget) return;
516
517 const key = getDirectionAwareKey(event.key, dir);
518 let focusIntent: "first" | "last" | "prev" | "next" | undefined;
519
520 if (orientation === "horizontal") {
521 if (key === "ArrowLeft") focusIntent = "prev";
522 else if (key === "ArrowRight") focusIntent = "next";
523 else if (key === "Home") focusIntent = "first";
524 else if (key === "End") focusIntent = "last";
525 } else {
526 if (key === "ArrowUp") focusIntent = "prev";
527 else if (key === "ArrowDown") focusIntent = "next";
528 else if (key === "Home") focusIntent = "first";
529 else if (key === "End") focusIntent = "last";
530 }
531
532 if (focusIntent !== undefined) {
533 if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey)
534 return;
535 event.preventDefault();
536
537 const items = focusContext.getItems().filter((item) => !item.disabled);
538 let candidateRefs = items.map((item) => item.ref);
539
540 if (focusIntent === "last") {
541 candidateRefs.reverse();
542 } else if (focusIntent === "prev" || focusIntent === "next") {
543 if (focusIntent === "prev") candidateRefs.reverse();
544 const currentIndex = candidateRefs.findIndex(
545 (ref) => ref.current === event.currentTarget,
546 );
547 candidateRefs = loop
548 ? wrapArray(candidateRefs, currentIndex + 1)
549 : candidateRefs.slice(currentIndex + 1);
550 }
551
552 queueMicrotask(() => focusFirst(candidateRefs));
553 }
554 },
555 [onKeyDownProp, focusContext, dir, orientation, loop],
556 );
557
558 const onMouseDown = React.useCallback(
559 (event: React.MouseEvent<ItemElement>) => {
560 onMouseDownProp?.(event);
561 if (event.defaultPrevented) return;
562
563 isMouseClickRef.current = true;
564
565 if (disabled) {
566 event.preventDefault();
567 } else {
568 focusContext.onItemFocus(itemId);
569 }
570 },
571 [onMouseDownProp, focusContext, itemId, disabled],
572 );
573
574 return (
575 <Button
576 type="button"
577 data-slot="action-bar-item"
578 variant="secondary"
579 size="sm"
580 disabled={disabled}
581 tabIndex={isTabStop ? 0 : -1}
582 {...itemProps}
583 className={cn(orientation === "vertical" && "w-full", className)}
584 ref={composedRef}
585 onClick={onClick}
586 onFocus={onFocus}
587 onKeyDown={onKeyDown}
588 onMouseDown={onMouseDown}
589 />
590 );
591}
592
593interface ActionBarCloseProps extends React.ComponentProps<"button"> {
594 asChild?: boolean;
595}
596
597function ActionBarClose(props: ActionBarCloseProps) {
598 const { asChild, className, onClick, ...closeProps } = props;
599
600 const { onOpenChange } = useActionBarContext(CLOSE_NAME);
601
602 const onCloseClick = React.useCallback(
603 (event: React.MouseEvent<CloseElement>) => {
604 onClick?.(event);
605 if (event.defaultPrevented) return;
606
607 onOpenChange?.(false);
608 },
609 [onOpenChange, onClick],
610 );
611
612 const ClosePrimitive = asChild ? SlotPrimitive.Slot : "button";
613
614 return (
615 <ClosePrimitive
616 type="button"
617 data-slot="action-bar-close"
618 {...closeProps}
619 className={cn(
620 "rounded-xs opacity-70 outline-none hover:opacity-100 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none [&_svg:not([class*='size-'])]:size-3.5 [&_svg]:pointer-events-none [&_svg]:shrink-0",
621 className,
622 )}
623 onClick={onCloseClick}
624 />
625 );
626}
627
628interface ActionBarSeparatorProps extends DivProps {
629 orientation?: Orientation;
630}
631
632function ActionBarSeparator(props: ActionBarSeparatorProps) {
633 const {
634 orientation: orientationProp,
635 asChild,
636 className,
637 ...separatorProps
638 } = props;
639
640 const context = useActionBarContext(SEPARATOR_NAME);
641 const orientation = orientationProp ?? context.orientation;
642
643 const SeparatorPrimitive = asChild ? SlotPrimitive.Slot : "div";
644
645 return (
646 <SeparatorPrimitive
647 role="separator"
648 aria-orientation={orientation}
649 aria-hidden="true"
650 data-slot="action-bar-separator"
651 {...separatorProps}
652 className={cn(
653 "in-data-[slot=action-bar-selection]:ml-0.5 in-data-[slot=action-bar-selection]:h-4 in-data-[slot=action-bar-selection]:w-px bg-border",
654 orientation === "horizontal" ? "h-6 w-px" : "h-px w-full",
655 className,
656 )}
657 />
658 );
659}
660
661export {
662 ActionBar,
663 ActionBarClose,
664 ActionBarGroup,
665 ActionBarItem,
666 type ActionBarProps,
667 ActionBarSelection,
668 ActionBarSeparator,
669};
670