File size: 9,696 Bytes
4995d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/**
 * FeatureTour - Interactive spotlight-based product tour.
 *
 * Highlights specific elements on the page by targeting them via
 * CSS selectors. Displays a tooltip with step information next to
 * each highlighted element. Supports next, back, and skip actions.
 *
 * Steps are provided as an array of { target, title, description, placement }.
 * The target is a CSS selector string pointing to the DOM element to highlight.
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  ChevronRightIcon,
  ChevronLeftIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import PropTypes from "prop-types";

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const TOOLTIP_OFFSET = 12;
const SPOTLIGHT_PADDING = 8;

const TOOLTIP_VARIANTS = {
  hidden: { opacity: 0, y: 8, scale: 0.95 },
  visible: { opacity: 1, y: 0, scale: 1 },
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/**
 * Compute the tooltip position relative to the target rect.
 *
 * @param {DOMRect} targetRect  - Bounding rect of the target element.
 * @param {string}  placement   - One of: top, bottom, left, right.
 * @param {number}  tooltipWidth
 * @returns {{ top: number, left: number }}
 */
function computeTooltipPosition(targetRect, placement, tooltipWidth = 300) {
  const centerX = targetRect.left + targetRect.width / 2 - tooltipWidth / 2;
  const clampedX = Math.max(16, Math.min(centerX, window.innerWidth - tooltipWidth - 16));

  switch (placement) {
    case "top":
      return {
        top: targetRect.top - TOOLTIP_OFFSET - 10,
        left: clampedX,
        transformOrigin: "bottom center",
      };
    case "left":
      return {
        top: targetRect.top + targetRect.height / 2 - 40,
        left: Math.max(16, targetRect.left - tooltipWidth - TOOLTIP_OFFSET),
        transformOrigin: "right center",
      };
    case "right":
      return {
        top: targetRect.top + targetRect.height / 2 - 40,
        left: targetRect.right + TOOLTIP_OFFSET,
        transformOrigin: "left center",
      };
    case "bottom":
    default:
      return {
        top: targetRect.bottom + TOOLTIP_OFFSET,
        left: clampedX,
        transformOrigin: "top center",
      };
  }
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

function FeatureTour({
  steps,
  isOpen,
  onClose,
  onComplete,
  startAt = 0,
}) {
  const [currentStep, setCurrentStep] = useState(startAt);
  const [targetRect, setTargetRect] = useState(null);
  const tooltipRef = useRef(null);

  const step = steps[currentStep];
  const isFirst = currentStep === 0;
  const isLast = currentStep === steps.length - 1;

  // ---------------------------------------------------------------------------
  // Find and measure the target element
  // ---------------------------------------------------------------------------

  useEffect(() => {
    if (!isOpen || !step?.target) {
      setTargetRect(null);
      return;
    }

    function measure() {
      const el = document.querySelector(step.target);
      if (el) {
        const rect = el.getBoundingClientRect();
        setTargetRect({
          top: rect.top - SPOTLIGHT_PADDING,
          left: rect.left - SPOTLIGHT_PADDING,
          width: rect.width + SPOTLIGHT_PADDING * 2,
          height: rect.height + SPOTLIGHT_PADDING * 2,
        });
        el.scrollIntoView({ behavior: "smooth", block: "nearest" });
      } else {
        setTargetRect(null);
      }
    }

    // Measure after a short delay to allow DOM to settle
    const timer = setTimeout(measure, 150);
    window.addEventListener("resize", measure);
    window.addEventListener("scroll", measure, true);

    return () => {
      clearTimeout(timer);
      window.removeEventListener("resize", measure);
      window.removeEventListener("scroll", measure, true);
    };
  }, [isOpen, currentStep, step]);

  // Reset step when opening
  useEffect(() => {
    if (isOpen) {
      setCurrentStep(startAt);
    }
  }, [isOpen, startAt]);

  // ---------------------------------------------------------------------------
  // Handlers
  // ---------------------------------------------------------------------------

  const handleNext = useCallback(() => {
    if (isLast) {
      onComplete?.();
      onClose();
    } else {
      setCurrentStep((prev) => prev + 1);
    }
  }, [isLast, onClose, onComplete]);

  const handlePrev = useCallback(() => {
    if (!isFirst) {
      setCurrentStep((prev) => prev - 1);
    }
  }, [isFirst]);

  const handleSkip = useCallback(() => {
    onClose();
  }, [onClose]);

  // Keyboard navigation
  useEffect(() => {
    if (!isOpen) return;

    function handleKey(e) {
      if (e.key === "Escape") handleSkip();
      if (e.key === "ArrowRight" || e.key === "Enter") handleNext();
      if (e.key === "ArrowLeft") handlePrev();
    }

    document.addEventListener("keydown", handleKey);
    return () => document.removeEventListener("keydown", handleKey);
  }, [isOpen, handleNext, handlePrev, handleSkip]);

  // ---------------------------------------------------------------------------
  // Render
  // ---------------------------------------------------------------------------

  if (!isOpen || !step) return null;

  const placement = step.placement || "bottom";
  const tooltipPos = targetRect
    ? computeTooltipPosition(targetRect, placement)
    : { top: "50%", left: "50%", transform: "translate(-50%, -50%)" };

  const content = (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Dark overlay */}
          <div
            className="fixed inset-0 z-[9997] bg-black/60 transition-opacity duration-300"
            onClick={handleSkip}
            aria-hidden="true"
          />

          {/* Spotlight cutout */}
          {targetRect && (
            <div
              className="tour-spotlight"
              style={{
                top: targetRect.top,
                left: targetRect.left,
                width: targetRect.width,
                height: targetRect.height,
              }}
            />
          )}

          {/* Tooltip */}
          <motion.div
            ref={tooltipRef}
            variants={TOOLTIP_VARIANTS}
            initial="hidden"
            animate="visible"
            exit="hidden"
            transition={{ duration: 0.2 }}
            className="fixed z-[9999] w-[300px] rounded-xl bg-white shadow-float overflow-hidden"
            style={{
              top: tooltipPos.top,
              left: tooltipPos.left,
              transformOrigin: tooltipPos.transformOrigin,
            }}
            role="dialog"
            aria-label={step.title}
          >
            {/* Header */}
            <div className="flex items-center justify-between px-4 py-3 bg-primary-600 text-white">
              <span className="text-xs font-medium opacity-80">
                {currentStep + 1} / {steps.length}
              </span>
              <button
                type="button"
                onClick={handleSkip}
                className="p-1 rounded-md hover:bg-primary-500 transition-colors"
                aria-label="Skip tour"
              >
                <XMarkIcon className="h-4 w-4" />
              </button>
            </div>

            {/* Body */}
            <div className="px-4 py-3">
              <h4 className="text-sm font-semibold text-neutral-900 mb-1">
                {step.title}
              </h4>
              <p className="text-sm text-neutral-600 leading-relaxed">
                {step.description}
              </p>
            </div>

            {/* Footer */}
            <div className="flex items-center justify-between px-4 py-3 border-t border-neutral-100 bg-neutral-50">
              <button
                type="button"
                onClick={handlePrev}
                disabled={isFirst}
                className={[
                  "flex items-center gap-1 text-sm font-medium transition-colors",
                  isFirst
                    ? "text-neutral-300 cursor-not-allowed"
                    : "text-neutral-600 hover:text-neutral-800",
                ].join(" ")}
              >
                <ChevronLeftIcon className="h-4 w-4" />
                Back
              </button>

              <button
                type="button"
                onClick={handleNext}
                className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-primary-600 text-white text-sm font-medium hover:bg-primary-700 transition-colors"
              >
                {isLast ? "Done" : "Next"}
                {!isLast && <ChevronRightIcon className="h-4 w-4" />}
              </button>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );

  return createPortal(content, document.body);
}

FeatureTour.propTypes = {
  steps: PropTypes.arrayOf(
    PropTypes.shape({
      target: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      description: PropTypes.string.isRequired,
      placement: PropTypes.oneOf(["top", "bottom", "left", "right"]),
    }),
  ).isRequired,
  isOpen: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  onComplete: PropTypes.func,
  startAt: PropTypes.number,
};

export default FeatureTour;