1"use client";
2
3import { cva } from "class-variance-authority";
4import {
5 Direction as DirectionPrimitive,
6 Slot as SlotPrimitive,
7} from "radix-ui";
8import * as React from "react";
9import { useComposedRefs } from "@/lib/compose-refs";
10import { cn } from "@/lib/utils";
11import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
12import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
13
14type Direction = "ltr" | "rtl";
15type Orientation = "vertical" | "horizontal";
16type Variant = "default" | "alternate";
17type Status = "completed" | "active" | "pending";
18
19interface DivProps extends React.ComponentProps<"div"> {
20 asChild?: boolean;
21}
22
23type ItemElement = React.ComponentRef<typeof TimelineItem>;
24
25const ROOT_NAME = "Timeline";
26const ITEM_NAME = "TimelineItem";
27const DOT_NAME = "TimelineDot";
28const CONNECTOR_NAME = "TimelineConnector";
29const CONTENT_NAME = "TimelineContent";
30
31function getItemStatus(itemIndex: number, activeIndex?: number): Status {
32 if (activeIndex === undefined) return "pending";
33 if (itemIndex < activeIndex) return "completed";
34 if (itemIndex === activeIndex) return "active";
35 return "pending";
36}
37
38function getSortedEntries(
39 entries: [string, React.RefObject<ItemElement | null>][],
40) {
41 return entries.sort((a, b) => {
42 const elementA = a[1].current;
43 const elementB = b[1].current;
44 if (!elementA || !elementB) return 0;
45 const position = elementA.compareDocumentPosition(elementB);
46 if (position & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
47 if (position & Node.DOCUMENT_POSITION_PRECEDING) return 1;
48 return 0;
49 });
50}
51
52function useStore<T>(selector: (store: Store) => T): T {
53 const store = React.useContext(StoreContext);
54 if (!store) {
55 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
56 }
57
58 const getSnapshot = React.useCallback(
59 () => selector(store),
60 [store, selector],
61 );
62
63 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
64}
65
66interface StoreState {
67 items: Map<string, React.RefObject<ItemElement | null>>;
68}
69
70interface Store {
71 subscribe: (callback: () => void) => () => void;
72 getState: () => StoreState;
73 notify: () => void;
74 onItemRegister: (
75 id: string,
76 ref: React.RefObject<ItemElement | null>,
77 ) => void;
78 onItemUnregister: (id: string) => void;
79 getNextItemStatus: (id: string, activeIndex?: number) => Status | undefined;
80 getItemIndex: (id: string) => number;
81}
82
83const StoreContext = React.createContext<Store | null>(null);
84
85function useStoreContext(consumerName: string) {
86 const context = React.useContext(StoreContext);
87 if (!context) {
88 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
89 }
90 return context;
91}
92
93interface TimelineContextValue {
94 dir: Direction;
95 orientation: Orientation;
96 variant: Variant;
97 activeIndex?: number;
98}
99
100const TimelineContext = React.createContext<TimelineContextValue | null>(null);
101
102function useTimelineContext(consumerName: string) {
103 const context = React.useContext(TimelineContext);
104 if (!context) {
105 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
106 }
107 return context;
108}
109
110const timelineVariants = cva(
111 "relative flex [--timeline-connector-thickness:0.125rem] [--timeline-dot-size:0.875rem]",
112 {
113 variants: {
114 orientation: {
115 vertical: "flex-col",
116 horizontal: "flex-row items-start",
117 },
118 variant: {
119 default: "",
120 alternate: "",
121 },
122 },
123 compoundVariants: [
124 {
125 orientation: "vertical",
126 variant: "default",
127 class: "gap-6",
128 },
129 {
130 orientation: "horizontal",
131 variant: "default",
132 class: "gap-8",
133 },
134 {
135 orientation: "vertical",
136 variant: "alternate",
137 class: "relative w-full gap-3",
138 },
139 {
140 orientation: "horizontal",
141 variant: "alternate",
142 class: "items-center gap-4",
143 },
144 ],
145 defaultVariants: {
146 orientation: "vertical",
147 variant: "default",
148 },
149 },
150);
151
152interface TimelineProps extends DivProps {
153 dir?: Direction;
154 orientation?: Orientation;
155 variant?: Variant;
156 activeIndex?: number;
157}
158
159function Timeline(props: TimelineProps) {
160 const {
161 orientation = "vertical",
162 variant = "default",
163 dir: dirProp,
164 activeIndex,
165 asChild,
166 className,
167 ...rootProps
168 } = props;
169
170 const dir = DirectionPrimitive.useDirection(dirProp);
171
172 const listenersRef = useLazyRef(() => new Set<() => void>());
173 const stateRef = useLazyRef<StoreState>(() => ({
174 items: new Map(),
175 }));
176
177 const store = React.useMemo<Store>(() => {
178 return {
179 subscribe: (cb) => {
180 listenersRef.current.add(cb);
181 return () => listenersRef.current.delete(cb);
182 },
183 getState: () => stateRef.current,
184 notify: () => {
185 for (const cb of listenersRef.current) {
186 cb();
187 }
188 },
189 onItemRegister: (
190 id: string,
191 ref: React.RefObject<ItemElement | null>,
192 ) => {
193 stateRef.current.items.set(id, ref);
194 store.notify();
195 },
196 onItemUnregister: (id: string) => {
197 stateRef.current.items.delete(id);
198 store.notify();
199 },
200 getNextItemStatus: (id: string, activeIndex?: number) => {
201 const entries = Array.from(stateRef.current.items.entries());
202 const sortedEntries = getSortedEntries(entries);
203
204 const currentIndex = sortedEntries.findIndex(([key]) => key === id);
205 if (currentIndex === -1 || currentIndex === sortedEntries.length - 1) {
206 return undefined;
207 }
208
209 const nextItemIndex = currentIndex + 1;
210 return getItemStatus(nextItemIndex, activeIndex);
211 },
212 getItemIndex: (id: string) => {
213 const entries = Array.from(stateRef.current.items.entries());
214 const sortedEntries = getSortedEntries(entries);
215 return sortedEntries.findIndex(([key]) => key === id);
216 },
217 };
218 }, [listenersRef, stateRef]);
219
220 const contextValue = React.useMemo<TimelineContextValue>(
221 () => ({
222 dir,
223 orientation,
224 variant,
225 activeIndex,
226 }),
227 [dir, orientation, variant, activeIndex],
228 );
229
230 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
231
232 return (
233 <StoreContext.Provider value={store}>
234 <TimelineContext.Provider value={contextValue}>
235 <RootPrimitive
236 role="list"
237 aria-orientation={orientation}
238 data-slot="timeline"
239 data-orientation={orientation}
240 data-variant={variant}
241 dir={dir}
242 {...rootProps}
243 className={cn(timelineVariants({ orientation, variant, className }))}
244 />
245 </TimelineContext.Provider>
246 </StoreContext.Provider>
247 );
248}
249
250interface TimelineItemContextValue {
251 id: string;
252 status: Status;
253 isAlternateRight: boolean;
254}
255
256const TimelineItemContext =
257 React.createContext<TimelineItemContextValue | null>(null);
258
259function useTimelineItemContext(consumerName: string) {
260 const context = React.useContext(TimelineItemContext);
261 if (!context) {
262 throw new Error(`\`${consumerName}\` must be used within \`${ITEM_NAME}\``);
263 }
264 return context;
265}
266
267const timelineItemVariants = cva("relative flex", {
268 variants: {
269 orientation: {
270 vertical: "",
271 horizontal: "",
272 },
273 variant: {
274 default: "",
275 alternate: "",
276 },
277 isAlternateRight: {
278 true: "",
279 false: "",
280 },
281 },
282 compoundVariants: [
283 {
284 orientation: "vertical",
285 variant: "default",
286 class: "gap-3 pb-8 last:pb-0",
287 },
288 {
289 orientation: "horizontal",
290 variant: "default",
291 class: "flex-col gap-3",
292 },
293 {
294 orientation: "vertical",
295 variant: "alternate",
296 isAlternateRight: false,
297 class: "w-1/2 gap-3 pr-6 pb-12 last:pb-0",
298 },
299 {
300 orientation: "vertical",
301 variant: "alternate",
302 isAlternateRight: true,
303 class: "ml-auto w-1/2 flex-row-reverse gap-3 pb-12 pl-6 last:pb-0",
304 },
305 {
306 orientation: "horizontal",
307 variant: "alternate",
308 class: "grid min-w-0 grid-rows-[1fr_auto_1fr] gap-3",
309 },
310 ],
311 defaultVariants: {
312 orientation: "vertical",
313 variant: "default",
314 isAlternateRight: false,
315 },
316});
317
318function TimelineItem(props: DivProps) {
319 const { asChild, className, id, ref, ...itemProps } = props;
320
321 const { dir, orientation, variant, activeIndex } =
322 useTimelineContext(ITEM_NAME);
323 const store = useStoreContext(ITEM_NAME);
324
325 const instanceId = React.useId();
326 const itemId = id ?? instanceId;
327 const itemRef = React.useRef<ItemElement | null>(null);
328 const composedRef = useComposedRefs(ref, itemRef);
329
330 const itemIndex = useStore((state) => state.getItemIndex(itemId));
331
332 const status = React.useMemo<Status>(() => {
333 return getItemStatus(itemIndex, activeIndex);
334 }, [activeIndex, itemIndex]);
335
336 useIsomorphicLayoutEffect(() => {
337 store.onItemRegister(itemId, itemRef);
338 return () => {
339 store.onItemUnregister(itemId);
340 };
341 }, [id, store]);
342
343 const isAlternateRight = variant === "alternate" && itemIndex % 2 === 1;
344
345 const itemContextValue = React.useMemo<TimelineItemContextValue>(
346 () => ({ id: itemId, status, isAlternateRight }),
347 [itemId, status, isAlternateRight],
348 );
349
350 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
351
352 return (
353 <TimelineItemContext.Provider value={itemContextValue}>
354 <ItemPrimitive
355 role="listitem"
356 aria-current={status === "active" ? "step" : undefined}
357 data-slot="timeline-item"
358 data-status={status}
359 data-orientation={orientation}
360 data-alternate-right={isAlternateRight ? "" : undefined}
361 id={itemId}
362 dir={dir}
363 {...itemProps}
364 ref={composedRef}
365 className={cn(
366 timelineItemVariants({
367 orientation,
368 variant,
369 isAlternateRight,
370 className,
371 }),
372 )}
373 />
374 </TimelineItemContext.Provider>
375 );
376}
377
378const timelineContentVariants = cva("flex-1", {
379 variants: {
380 orientation: {
381 vertical: "",
382 horizontal: "",
383 },
384 variant: {
385 default: "",
386 alternate: "",
387 },
388 isAlternateRight: {
389 true: "",
390 false: "",
391 },
392 },
393 compoundVariants: [
394 {
395 variant: "alternate",
396 orientation: "vertical",
397 isAlternateRight: false,
398 class: "text-right",
399 },
400 {
401 variant: "alternate",
402 orientation: "horizontal",
403 isAlternateRight: false,
404 class: "row-start-3 pt-2",
405 },
406 {
407 variant: "alternate",
408 orientation: "horizontal",
409 isAlternateRight: true,
410 class: "row-start-1 pb-2",
411 },
412 ],
413 defaultVariants: {
414 orientation: "vertical",
415 variant: "default",
416 isAlternateRight: false,
417 },
418});
419
420function TimelineContent(props: DivProps) {
421 const { asChild, className, ...contentProps } = props;
422
423 const { variant, orientation } = useTimelineContext(CONTENT_NAME);
424 const { status, isAlternateRight } = useTimelineItemContext(CONTENT_NAME);
425
426 const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
427
428 return (
429 <ContentPrimitive
430 data-slot="timeline-content"
431 data-status={status}
432 {...contentProps}
433 className={cn(
434 timelineContentVariants({
435 orientation,
436 variant,
437 isAlternateRight,
438 className,
439 }),
440 )}
441 />
442 );
443}
444
445const timelineDotVariants = cva(
446 "relative z-10 flex size-[var(--timeline-dot-size)] shrink-0 items-center justify-center rounded-full border-2 bg-background",
447 {
448 variants: {
449 status: {
450 completed: "border-primary",
451 active: "border-primary",
452 pending: "border-border",
453 },
454 orientation: {
455 vertical: "",
456 horizontal: "",
457 },
458 variant: {
459 default: "",
460 alternate: "",
461 },
462 isAlternateRight: {
463 true: "",
464 false: "",
465 },
466 },
467 compoundVariants: [
468 {
469 variant: "alternate",
470 orientation: "vertical",
471 isAlternateRight: false,
472 class:
473 "absolute -right-[calc(var(--timeline-dot-size)/2-var(--timeline-connector-thickness)/2)] bg-background",
474 },
475 {
476 variant: "alternate",
477 orientation: "vertical",
478 isAlternateRight: true,
479 class:
480 "absolute -left-[calc(var(--timeline-dot-size)/2-var(--timeline-connector-thickness)/2)] bg-background",
481 },
482 {
483 variant: "alternate",
484 orientation: "horizontal",
485 class: "row-start-2 bg-background",
486 },
487 {
488 variant: "alternate",
489 status: "completed",
490 class: "bg-background",
491 },
492 {
493 variant: "alternate",
494 status: "active",
495 class: "bg-background",
496 },
497 ],
498 defaultVariants: {
499 status: "pending",
500 orientation: "vertical",
501 variant: "default",
502 isAlternateRight: false,
503 },
504 },
505);
506
507function TimelineDot(props: DivProps) {
508 const { asChild, className, ...dotProps } = props;
509
510 const { orientation, variant } = useTimelineContext(DOT_NAME);
511 const { status, isAlternateRight } = useTimelineItemContext(DOT_NAME);
512
513 const DotPrimitive = asChild ? SlotPrimitive.Slot : "div";
514
515 return (
516 <DotPrimitive
517 data-slot="timeline-dot"
518 data-status={status}
519 data-orientation={orientation}
520 {...dotProps}
521 className={cn(
522 timelineDotVariants({
523 status,
524 orientation,
525 variant,
526 isAlternateRight,
527 className,
528 }),
529 )}
530 />
531 );
532}
533
534const timelineConnectorVariants = cva("absolute z-0", {
535 variants: {
536 isCompleted: {
537 true: "bg-primary",
538 false: "bg-border",
539 },
540 orientation: {
541 vertical: "",
542 horizontal: "",
543 },
544 variant: {
545 default: "",
546 alternate: "",
547 },
548 isAlternateRight: {
549 true: "",
550 false: "",
551 },
552 },
553 compoundVariants: [
554 {
555 orientation: "vertical",
556 variant: "default",
557 class:
558 "start-[calc(var(--timeline-dot-size)/2-var(--timeline-connector-thickness)/2)] top-3 h-[calc(100%+0.5rem)] w-[var(--timeline-connector-thickness)]",
559 },
560 {
561 orientation: "horizontal",
562 variant: "default",
563 class:
564 "start-3 top-[calc(var(--timeline-dot-size)/2-var(--timeline-connector-thickness)/2)] h-[var(--timeline-connector-thickness)] w-[calc(100%+0.5rem)]",
565 },
566 {
567 orientation: "vertical",
568 variant: "alternate",
569 isAlternateRight: false,
570 class:
571 "top-2 -right-[calc(var(--timeline-connector-thickness)/2)] h-full w-[var(--timeline-connector-thickness)]",
572 },
573 {
574 orientation: "vertical",
575 variant: "alternate",
576 isAlternateRight: true,
577 class:
578 "top-2 -left-[calc(var(--timeline-connector-thickness)/2)] h-full w-[var(--timeline-connector-thickness)]",
579 },
580 {
581 orientation: "horizontal",
582 variant: "alternate",
583 class:
584 "top-[calc(var(--timeline-dot-size)/2-var(--timeline-connector-thickness)/2)] left-3 row-start-2 h-[var(--timeline-connector-thickness)] w-[calc(100%+0.5rem)]",
585 },
586 ],
587 defaultVariants: {
588 isCompleted: false,
589 orientation: "vertical",
590 variant: "default",
591 isAlternateRight: false,
592 },
593});
594
595interface TimelineConnectorProps extends DivProps {
596 forceMount?: boolean;
597}
598
599function TimelineConnector(props: TimelineConnectorProps) {
600 const { asChild, forceMount, className, ...connectorProps } = props;
601
602 const { orientation, variant, activeIndex } =
603 useTimelineContext(CONNECTOR_NAME);
604 const { id, status, isAlternateRight } =
605 useTimelineItemContext(CONNECTOR_NAME);
606
607 const nextItemStatus = useStore((state) =>
608 state.getNextItemStatus(id, activeIndex),
609 );
610
611 const isLastItem = nextItemStatus === undefined;
612
613 if (!forceMount && isLastItem) return null;
614
615 const isConnectorCompleted =
616 nextItemStatus === "completed" || nextItemStatus === "active";
617
618 const ConnectorPrimitive = asChild ? SlotPrimitive.Slot : "div";
619
620 return (
621 <ConnectorPrimitive
622 aria-hidden="true"
623 data-slot="timeline-connector"
624 data-completed={isConnectorCompleted ? "" : undefined}
625 data-status={status}
626 data-orientation={orientation}
627 {...connectorProps}
628 className={cn(
629 timelineConnectorVariants({
630 isCompleted: isConnectorCompleted,
631 orientation,
632 variant,
633 isAlternateRight,
634 className,
635 }),
636 )}
637 />
638 );
639}
640
641function TimelineHeader(props: DivProps) {
642 const { asChild, className, ...headerProps } = props;
643
644 const HeaderPrimitive = asChild ? SlotPrimitive.Slot : "div";
645
646 return (
647 <HeaderPrimitive
648 data-slot="timeline-header"
649 {...headerProps}
650 className={cn("flex flex-col gap-1", className)}
651 />
652 );
653}
654
655function TimelineTitle(props: DivProps) {
656 const { asChild, className, ...titleProps } = props;
657
658 const TitlePrimitive = asChild ? SlotPrimitive.Slot : "div";
659
660 return (
661 <TitlePrimitive
662 data-slot="timeline-title"
663 {...titleProps}
664 className={cn("font-semibold leading-none", className)}
665 />
666 );
667}
668
669function TimelineDescription(props: DivProps) {
670 const { asChild, className, ...descriptionProps } = props;
671
672 const DescriptionPrimitive = asChild ? SlotPrimitive.Slot : "div";
673
674 return (
675 <DescriptionPrimitive
676 data-slot="timeline-description"
677 {...descriptionProps}
678 className={cn("text-muted-foreground text-sm", className)}
679 />
680 );
681}
682
683interface TimelineTimeProps extends React.ComponentProps<"time"> {
684 asChild?: boolean;
685}
686
687function TimelineTime(props: TimelineTimeProps) {
688 const { asChild, className, ...timeProps } = props;
689
690 const TimePrimitive = asChild ? SlotPrimitive.Slot : "time";
691
692 return (
693 <TimePrimitive
694 data-slot="timeline-time"
695 {...timeProps}
696 className={cn("text-muted-foreground text-xs", className)}
697 />
698 );
699}
700
701export {
702 Timeline,
703 TimelineConnector,
704 TimelineContent,
705 TimelineDescription,
706 TimelineDot,
707 TimelineHeader,
708 TimelineItem,
709 type TimelineProps,
710 TimelineTime,
711 TimelineTitle,
712};
713