-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtour.tsx
More file actions
211 lines (186 loc) · 6.15 KB
/
Copy pathtour.tsx
File metadata and controls
211 lines (186 loc) · 6.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"use client"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter } from "@/components/ui/card"
import { cn } from "@/lib/utils"
import { FloatingArrow, FloatingOverlay, arrow, autoPlacement, autoUpdate, offset, shift, useFloating } from "@floating-ui/react"
import { Slot } from "@radix-ui/react-slot"
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"
export interface TourStep {
target: string
step: React.ReactNode
}
interface UseTourProps {
steps: TourStep[]
onFinish?: () => void
isOpen?: boolean
onClose?: () => void
}
export function useTour(props: UseTourProps) {
const [currentStepIndex, setCurrentStepIndex] = useState<number | null>(props.isOpen ? 0 : null)
const arrowRef = useRef(null)
const { elements, refs, floatingStyles, context } = useFloating({
middleware: [offset(10), shift(), autoPlacement(), arrow({ element: arrowRef })],
whileElementsMounted: autoUpdate,
})
const isEnabled = currentStepIndex !== null
const currentStep = isEnabled ? props.steps[currentStepIndex] : undefined
const target = currentStep?.target
useEffect(() => {
if (props.isOpen) {
setCurrentStepIndex(0)
} else {
setCurrentStepIndex(null)
}
}, [props.isOpen])
const start = useCallback(() => {
setCurrentStepIndex(0)
}, [])
const end = useCallback(() => {
setCurrentStepIndex(null)
props.onClose?.()
}, [props.onClose])
useEffect(() => {
if (!isEnabled || !target) return
const targetElement = document.querySelector(`.${target}`)
if (targetElement instanceof HTMLElement) {
refs.setReference(targetElement)
try {
targetElement.scrollIntoView({ behavior: "smooth", block: "center" })
} catch (error) {
console.warn("Failed to scroll to target element:", error)
}
} else {
console.warn(`Tour target not found: ${target}`)
end()
}
const listener = (event: KeyboardEvent) => {
if (event.key === "Escape") end()
}
document.addEventListener("keydown", listener)
return () => {
document.removeEventListener("keydown", listener)
}
}, [end, refs, target, isEnabled])
const nextStep = useCallback(() => {
if (currentStepIndex !== null && currentStepIndex < props.steps.length - 1) {
setCurrentStepIndex(currentStepIndex + 1)
} else {
end()
props.onFinish?.()
}
}, [currentStepIndex, props.steps.length, end, props.onFinish])
const prevStep = useCallback(() => {
if (currentStepIndex !== null && currentStepIndex > 0) {
setCurrentStepIndex(currentStepIndex - 1)
}
}, [currentStepIndex])
return {
arrowRef,
context,
currentStep,
currentStepIndex: currentStepIndex ?? 0,
currentTarget: elements.reference,
end,
floatingProps: { ref: refs.setFloating, style: floatingStyles },
isEnabled,
isLastStep: currentStepIndex === (props.steps.length ?? 0) - 1,
nextStep,
prevStep,
refs,
start,
steps: props.steps,
}
}
export function TourTrigger({
asChild,
...props
}: { children: React.ReactNode; asChild?: boolean } & React.ComponentProps<"button">) {
const tour = useTourContext()
const Comp = asChild ? Slot : "button"
return (
<Comp
{...props}
onClick={(event) => {
if (!event.defaultPrevented) tour?.start()
}}
/>
)
}
const TourContext = createContext<ReturnType<typeof useTour> | null>(null)
export function Tour({ children, steps, onFinish, isOpen, onClose }: { children: React.ReactNode } & UseTourProps) {
const tour = useTour(useMemo(() => ({ steps, onFinish, isOpen, onClose }), [steps, onFinish, isOpen, onClose]))
return <TourContext.Provider value={tour}>{children}</TourContext.Provider>
}
export function useTourContext() {
const tour = useContext(TourContext)
if (!tour) throw new Error("useTourContext must be used within a Tour component")
return tour
}
export function TourOverlay() {
const tour = useTourContext()
if (!tour.isEnabled) return null
const rect = tour.currentTarget?.getBoundingClientRect()
return (
<FloatingOverlay className="z-9997" onClick={tour.end} lockScroll={false}>
<div
className="absolute bg-transparent rounded"
style={{
top: (rect?.top ?? 0) - 4,
left: (rect?.left ?? 0) - 4,
width: (rect?.width ?? 0) + 8,
height: (rect?.height ?? 0) + 8,
boxShadow: "0 0 0 9999px rgba(0, 0, 0, 0.7)",
}}
/>
</FloatingOverlay>
)
}
export function TourArrow({ className }: { className?: string }) {
const tour = useTourContext()
return (
<FloatingArrow
ref={tour.arrowRef}
context={tour.context}
className={cn("fill-popover [&>path:first-of-type]:stroke-border [&>path:last-of-type]:stroke-border", className)}
/>
)
}
export function TourContent({ children, className }: { children: React.ReactNode; className?: string }) {
const tour = useTourContext()
if (!tour.isEnabled) return null
return (
<Card className={cn("max-w-sm z-9998", className)} {...tour.floatingProps}>
{children}
</Card>
)
}
export function TourStep({ className }: { className?: string }) {
const tour = useTourContext()
if (!tour.currentStep) return null
return <CardContent className={cn("p-4", className)}>{tour.currentStep.step}</CardContent>
}
export function TourFooter() {
const tour = useTourContext()
return (
<CardFooter className="flex items-center justify-between p-3">
<div className="flex-1">
<Button size="sm" variant="secondary" onClick={tour.prevStep} disabled={tour.currentStepIndex === 0}>
Previous
</Button>
</div>
<div className="flex flex-1 justify-center gap-1">
{tour.steps.map(({ target }, index) => (
<div
key={`${target}-${index}`}
className={`w-2 h-2 rounded-full ${index === tour.currentStepIndex ? "bg-primary" : "bg-muted"}`}
/>
))}
</div>
<div className="flex-1 flex justify-end">
<Button size="sm" onClick={tour.nextStep}>
{tour.isLastStep ? "Finish" : "Next"}
</Button>
</div>
</CardFooter>
)
}