Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

16.3 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import { ChevronLeftStandardIcon, ChevronRightStandardIcon } from "@/lib/chevron-icons";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
import {
  Cancel01Icon,
  CheckmarkCircle02Icon,
} from "@hugeicons/core-free-icons";
import { Dialog as DialogPrimitive } from "radix-ui";
import { AnimatePresence, motion } from "motion/react";
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import { cssEscape, toRect } from "../lib/dom";
import { fireConfettiFireworks } from "../lib/confetti-fireworks";
import { computeCardPos, padded, pickPlacement } from "../lib/layout";
import { SpotlightOverlay } from "./spotlight-overlay";
import type { Placement, Rect, TourStep } from "../types";

type GuidedTourProps = { open: boolean; onOpenChange: (open: boolean) => void; steps: TourStep[]; onSkip: () => void; onComplete: () => void; celebrate?: boolean };

export function GuidedTour({
  open,
  onOpenChange,
  steps,
  onSkip,
  onComplete,
  celebrate = false,
}: GuidedTourProps) {
  const maskId = `${useId()}-tour-mask`;
  const t = useT();
  const [idx, setIdx] = useState(0);
  const [vw, setVw] = useState(0);
  const [vh, setVh] = useState(0);
  const [targetRect, setTargetRect] = useState<Rect | null>(null);
  const [placement, setPlacement] = useState<Placement>("right");
  const [cardPos, setCardPos] = useState<{ left: number; top: number }>({
    left: 12,
    top: 12,
  });
  const cardRef = useRef<HTMLDivElement>(null);
  const overlayRef = useSurfaceRef<HTMLDivElement>(MODAL_SURFACE);
  const closeLockRef = useRef(false);
  const rafRef = useRef<number | null>(null);
  const lastRectRef = useRef<Rect | null>(null);

  // Rewound during render, or reopening would fire the last step's onEnter before rewinding.
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) setIdx(0);
  }

  const step = steps[idx] ?? null;
  const total = steps.length;
  const isLast = idx === total - 1;

  const spotlightRect = useMemo(() => {
    if (!targetRect || !vw || !vh) return null;
    const pad = step?.target === "navbar" ? 4 : 14;
    return padded(targetRect, pad, vw, vh);
  }, [step?.target, targetRect, vw, vh]);

  // Cleanup so a step is also left on unmount, or onEnter side effects (sidebar pin) leak.
  useEffect(() => {
    if (!open || !step) return;
    void step.onEnter?.();
    return () => {
      void step.onExit?.();
    };
  }, [open, step?.id]); // stays above the target lookup effect below

  useEffect(() => {
    if (!open) return;
    setTargetRect(null);
    closeLockRef.current = false;
    lastRectRef.current = null;
  }, [open]);

  useEffect(() => {
    if (!open) return;
    function onResize() {
      setVw(window.innerWidth);
      setVh(window.innerHeight);
    }
    onResize();
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [open]);

  useEffect(() => {
    if (!open || !step) return;

    const sel = `[data-tour="${cssEscape(step.target)}"]`;
    let el: HTMLElement | null = null;
    let ro: ResizeObserver | null = null;
    let retryTimer = 0;
    let retries = 0;

    let raf = 0;
    let t = 0;

    function isUsableTarget(candidate: HTMLElement): boolean {
      const r = candidate.getBoundingClientRect();
      return r.width >= 6 && r.height >= 6;
    }

    // First visible match: Images and Video share Train targets, and a hidden page stays mounted earlier in the DOM.
    function findTarget(): HTMLElement | null {
      const found = [...document.querySelectorAll(sel)].filter(
        (c): c is HTMLElement => c instanceof HTMLElement,
      );
      return found.find(isUsableTarget) ?? found[0] ?? null;
    }

    function rectChanged(a: Rect | null, b: Rect): boolean {
      if (!a) return true;
      return (
        Math.abs(a.x - b.x) > 0.5 ||
        Math.abs(a.y - b.y) > 0.5 ||
        Math.abs(a.w - b.w) > 0.5 ||
        Math.abs(a.h - b.h) > 0.5
      );
    }

    function read(candidate: HTMLElement) {
      const r = candidate.getBoundingClientRect();
      const next = toRect(r);
      const prev = lastRectRef.current;
      if (rectChanged(prev, next)) {
        lastRectRef.current = next;
        setTargetRect(next);
      }
    }

    function schedule() {
      if (rafRef.current != null) return;
      rafRef.current = window.requestAnimationFrame(() => {
        rafRef.current = null;
        if (el) read(el);
      });
    }

    function attach(candidate: HTMLElement) {
      el = candidate;

      if (step.target !== "navbar") {
        el.scrollIntoView({
          block: "center",
          inline: "center",
          behavior: "smooth",
        });
      }

      raf = window.requestAnimationFrame(() => read(el!));
      t = window.setTimeout(schedule, 240);

      ro = new ResizeObserver(() => schedule());
      ro.observe(el);
      window.addEventListener("scroll", schedule, { capture: true, passive: true });
      window.addEventListener("resize", schedule, { passive: true });
    }

    function tryAttach(): boolean {
      const candidate = findTarget();
      if (!candidate) return false;
      if (!isUsableTarget(candidate)) return false;
      attach(candidate);
      return true;
    }

    if (!tryAttach()) {
      setTargetRect(null);
      retryTimer = window.setInterval(() => {
        retries += 1;
        if (tryAttach() || retries > 40) {
          window.clearInterval(retryTimer);
        }
      }, 50);
    }

    return () => {
      window.cancelAnimationFrame(raf);
      window.clearTimeout(t);
      if (retryTimer) window.clearInterval(retryTimer);
      ro?.disconnect();
      window.removeEventListener("scroll", schedule, true);
      window.removeEventListener("resize", schedule);
      if (rafRef.current != null) {
        window.cancelAnimationFrame(rafRef.current);
        rafRef.current = null;
      }
    };
  }, [open, step?.id]);

  useLayoutEffect(() => {
    if (!open || !spotlightRect || !vw || !vh) return;
    const card = cardRef.current?.getBoundingClientRect();
    if (!card) return;

    const gap = 14;
    const picked = pickPlacement(spotlightRect, { w: card.width, h: card.height }, vw, vh, gap);
    setPlacement(picked);
    setCardPos(
      computeCardPos(
        picked,
        spotlightRect,
        { w: card.width, h: card.height },
        vw,
        vh,
        gap,
      ),
    );
  }, [open, spotlightRect, vw, vh, idx]);

  function requestClose(reason: "skip" | "complete") {
    if (closeLockRef.current) return;
    closeLockRef.current = true;
    if (reason === "skip") {
      onSkip();
    } else {
      if (celebrate) void fireConfettiFireworks();
      onComplete();
    }
    onOpenChange(false);
  }

  return (
    <DialogPrimitive.Root
      open={open}
      onOpenChange={(v) => {
        if (v) onOpenChange(true);
        else requestClose("skip");
      }}
      modal={true}
    >
      <DialogPrimitive.Portal>
        <AnimatePresence>
          {open && (
            <>
              <DialogPrimitive.Overlay asChild>
                <motion.div
                  ref={overlayRef}
                  // The shared slot, so modal checks see the tour.
                  data-slot="dialog-overlay"
                  data-viewport-backdrop={true}
                  className="fixed inset-0 z-50"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.18 }}
                >
                  <SpotlightOverlay rect={spotlightRect} vw={vw} vh={vh} maskId={maskId} />
                  {spotlightRect && (
                    <motion.div
                      className="fixed z-[51] pointer-events-none rounded-2xl ring-1 ring-[rgb(255_255_255_/_calc(0.1*var(--contrast-edge-gain,1)))]"
                      initial={false}
                      animate={{
                        left: spotlightRect.x,
                        top: spotlightRect.y,
                        width: spotlightRect.w,
                        height: spotlightRect.h,
                        boxShadow:
                          "0 0 0 1px rgba(34, 211, 238, 0.12), 0 0 0 6px rgba(16, 185, 129, 0.08), 0 18px 90px rgba(0,0,0,0.55)",
                      }}
                      transition={{ type: "spring", stiffness: 260, damping: 30 }}
                    />
                  )}
                </motion.div>
              </DialogPrimitive.Overlay>

              <DialogPrimitive.Content
                onPointerDownOutside={(e) => e.preventDefault()}
                onInteractOutside={(e) => e.preventDefault()}
                className={cn(
                  "fixed z-[52] outline-none",
                  "w-[min(420px,calc(100vw-1.5rem))]",
                )}
                style={{
                  left: cardPos.left,
                  top: cardPos.top,
                }}
              >
                <motion.div
                  ref={cardRef}
                  initial={{ opacity: 0, scale: 0.985, y: 8 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.99, y: 10 }}
                  transition={{ duration: 0.22, ease: [0.165, 0.84, 0.44, 1] }}
                  className={cn(
                    // Plain rounded, no corner-squircle: at this radius superellipse(2)
                    // hugs the corner about twice as tightly as the arc, which reads as a
                    // boxed-in card rather than a rounded one.
                    "relative overflow-hidden rounded-3xl",
                    "bg-white/95 text-foreground ring-1 ring-[rgb(0_0_0_/_calc(0.1*var(--contrast-edge-gain,1)))] dark:bg-zinc-900/96 dark:text-zinc-100 dark:ring-[rgb(255_255_255_/_calc(0.12*var(--contrast-edge-gain,1)))]",
                    "shadow-[0_30px_120px_rgba(0,0,0,0.35)]",
                  )}
                  style={{
                    fontFamily: "'Figtree Variable', ui-sans-serif, sans-serif",
                  }}
                >
                  <div
                    className={cn(
                      "absolute z-10 size-3 rotate-45 rounded-[3px] bg-white/95 ring-1 ring-[rgb(0_0_0_/_calc(0.1*var(--contrast-edge-gain,1)))] dark:bg-zinc-900/96 dark:ring-[rgb(255_255_255_/_calc(0.12*var(--contrast-edge-gain,1)))]",
                      placement === "right" &&
                        "-left-1 top-1/2 -translate-y-1/2",
                      placement === "left" &&
                        "-right-1 top-1/2 -translate-y-1/2",
                      placement === "bottom" &&
                        "left-1/2 -top-1 -translate-x-1/2",
                      placement === "top" &&
                        "left-1/2 -bottom-1 -translate-x-1/2",
                    )}
                    aria-hidden={true}
                  />
                  {/* Rounded to match the card. A square-cornered rectangle here reads as a
                      second, boxier outline whenever it is not clipped to the card's radius. */}
                  <div className="absolute inset-x-0 top-0 h-20 rounded-t-3xl bg-gradient-to-b from-control-accent/18 via-control-accent/6 to-transparent dark:from-control-accent/24 dark:via-control-accent/12" />
                  <div className="absolute -left-14 -top-16 size-44 rounded-full bg-control-accent/20 blur-2xl dark:bg-control-accent/26" />
                  <div className="absolute -right-14 -bottom-16 size-44 rounded-full bg-cyan-300/18 blur-2xl dark:bg-cyan-300/24" />

                  <div className="relative p-5">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <div className="inline-flex items-center gap-2 rounded-full bg-[rgb(0_0_0_/_calc(0.04*var(--contrast-wash-gain,1)))] px-2.5 py-1 text-ui-10 font-mono text-foreground/60 ring-1 ring-[rgb(0_0_0_/_calc(0.1*var(--contrast-edge-gain,1)))] dark:bg-[rgb(255_255_255_/_calc(0.04*var(--contrast-wash-gain,1)))] dark:text-zinc-200/75 dark:ring-[rgb(255_255_255_/_calc(0.14*var(--contrast-edge-gain,1)))]">
                          {idx + 1}/{total}
                          <span className="size-1 rounded-full bg-control-accent/70" />
                          {t("tour.badge")}
                        </div>
                        <DialogPrimitive.Title
                          className="mt-2 text-ui-18 leading-tight"
                          style={{ fontFamily: "var(--font-serif)" }}
                        >
                          {step?.title ?? t("tour.defaultTitle")}
                        </DialogPrimitive.Title>
                        <DialogPrimitive.Description className="mt-1.5 text-sm leading-relaxed text-foreground/70 dark:text-zinc-200/75">
                          {step?.body ?? t("tour.defaultBody")}
                        </DialogPrimitive.Description>
                      </div>

                      <Button
                        variant="ghost"
                        size="icon-sm"
                        className="text-foreground/60 hover:text-foreground hover:bg-[rgb(0_0_0_/_calc(0.05*var(--contrast-wash-gain,1)))] dark:text-zinc-300/70 dark:hover:text-zinc-100 dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]"
                        onClick={() => requestClose("skip")}
                        aria-label={t("tour.skipTour")}
                      >
                        <HugeiconsIcon icon={Cancel01Icon} className="size-4" />
                      </Button>
                    </div>

                    <div className="mt-5 flex items-center justify-between gap-3">
                      <Button
                        variant="ghost"
                        className="text-foreground/60 hover:text-foreground hover:bg-[rgb(0_0_0_/_calc(0.05*var(--contrast-wash-gain,1)))] dark:text-zinc-300/70 dark:hover:text-zinc-100 dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]"
                        onClick={() => requestClose("skip")}
                      >
                        {t("tour.skip")}
                      </Button>

                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          className="text-foreground hover:text-foreground dark:text-zinc-100"
                          disabled={idx === 0}
                          onClick={() => setIdx((i) => Math.max(0, i - 1))}
                        >
                          <HugeiconsIcon icon={ChevronLeftStandardIcon} className="size-4" />
                          {t("tour.back")}
                        </Button>
                        {isLast ? (
                          <Button
                            variant="dark"
                            className="bg-control-accent text-control-accent-foreground hover:bg-control-accent/90"
                            onClick={() => requestClose("complete")}
                          >
                            <HugeiconsIcon icon={CheckmarkCircle02Icon} className="size-4" />
                            {t("common.done")}
                          </Button>
                        ) : (
                          <Button
                            variant="dark"
                            className="bg-control-accent text-control-accent-foreground hover:bg-control-accent/90"
                            onClick={() => setIdx((i) => Math.min(total - 1, i + 1))}
                          >
                            {t("tour.next")}
                            <HugeiconsIcon icon={ChevronRightStandardIcon} className="size-4" />
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="h-px bg-gradient-to-r from-transparent via-black/10 to-transparent dark:via-white/14" />
                  <div className="px-5 py-3 text-ui-11 text-foreground/55 dark:text-zinc-300/65">
                    {t("tour.tip")}
                  </div>
                </motion.div>
              </DialogPrimitive.Content>
            </>
          )}
        </AnimatePresence>
      </DialogPrimitive.Portal>
    </DialogPrimitive.Root>
  );
}