# Device Morph
*URL: https://www.grettech.com/components/device-morph*

One frame that morphs between desktop, tablet and phone. Show a screenshot per device, or live content that reflows with container queries.

- Smooth morph between browser, tablet and phone frames
- Screenshots, per-device screenshots or live children
- Children reflow with container queries (@container)
- Optional autoplay that only runs on screen, pauses on hover and stops once a device is picked

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/device-morph
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/device-morph-demo`

**Dependencies:** npm: clsx, tailwind-merge, lucide-react

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge lucide-react
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/device-morph.tsx`
```tsx
"use client"

import { cn } from "@/lib/utils"
import { Monitor, Smartphone, Tablet } from "lucide-react"
import * as React from "react"

export type Device = "desktop" | "tablet" | "phone"

export interface DeviceMorphProps extends Omit<
  React.HTMLAttributes<HTMLDivElement>,
  "children"
> {
  /** One screenshot for every device… */
  src?: string
  /** …or one per device (falls back to src) */
  sources?: Partial<Record<Device, string>>
  alt?: string
  /** Live content instead of screenshots; use container queries to reflow */
  children?: React.ReactNode
  device?: Device
  defaultDevice?: Device
  onDeviceChange?: (device: Device) => void
  /** Cycles through the devices while on screen and not hovered */
  autoPlay?: boolean
  /** ms per device when autoPlay is on */
  interval?: number
  showControls?: boolean
  /** Text in the desktop address bar */
  url?: string
  /** Component used for images, e.g. next/image's Image */
  imageAs?: React.ElementType
}

const DEVICES: Device[] = ["desktop", "tablet", "phone"]

/**
 * Frame sizes in % of a 16:10 stage. Tablet is 3:4 and phone 9:19.5 at 96%
 * of the stage height: 0.96 × 0.625 × ratio.
 */
const FRAMES: Record<Device, { w: string; h: string; radius: string }> = {
  desktop: { w: "100%", h: "100%", radius: "12px" },
  tablet: { w: "45%", h: "96%", radius: "26px" },
  phone: { w: "27.7%", h: "96%", radius: "34px" },
}

const ICONS = { desktop: Monitor, tablet: Tablet, phone: Smartphone }
const LABELS = { desktop: "Desktop", tablet: "Tablet", phone: "Phone" }

export const DeviceMorph = React.forwardRef<HTMLDivElement, DeviceMorphProps>(
  (
    {
      src,
      sources,
      alt = "",
      children,
      device: controlledDevice,
      defaultDevice = "desktop",
      onDeviceChange,
      autoPlay = false,
      interval = 3500,
      showControls = true,
      url = "yourwebsite.com",
      imageAs: ImageTag = "img",
      className,
      ...props
    },
    ref
  ) => {
    const [internalDevice, setInternalDevice] = React.useState(defaultDevice)
    const device = controlledDevice ?? internalDevice
    const setDevice = React.useCallback(
      (next: Device) => {
        setInternalDevice(next)
        onDeviceChange?.(next)
      },
      [onDeviceChange]
    )

    const stageRef = React.useRef<HTMLDivElement>(null)
    const paused = React.useRef(false)
    // A device picked by the visitor ends autoplay for good
    const stopped = React.useRef(false)
    const pick = (next: Device) => {
      stopped.current = true
      setDevice(next)
    }
    React.useEffect(() => {
      if (!autoPlay || controlledDevice) return
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
      let inView = false
      const io = new IntersectionObserver(
        ([entry]) => (inView = entry.isIntersecting),
        { threshold: 0.5 }
      )
      if (stageRef.current) io.observe(stageRef.current)
      const timer = setInterval(() => {
        if (!inView || paused.current || stopped.current) return
        setInternalDevice((d) => DEVICES[(DEVICES.indexOf(d) + 1) % 3])
      }, interval)
      return () => {
        clearInterval(timer)
        io.disconnect()
      }
    }, [autoPlay, controlledDevice, interval])

    const frame = FRAMES[device]
    const isDesktop = device === "desktop"

    // Live children reflow at every width the frame passes through, which
    // flickers between layouts. So they fade out, the frame morphs (its size
    // transition waits for the fade), and they fade back in at the final size.
    const live = children != null
    const contentRef = React.useRef<HTMLDivElement>(null)
    const lastDevice = React.useRef(device)
    React.useEffect(() => {
      if (lastDevice.current === device) return
      lastDevice.current = device
      const content = contentRef.current
      if (
        !content?.animate ||
        window.matchMedia("(prefers-reduced-motion: reduce)").matches
      )
        return
      const animation = content.animate(
        [
          { opacity: 1 },
          { opacity: 0, offset: 0.12 },
          { opacity: 0, offset: 0.86 },
          { opacity: 1 },
        ],
        { duration: 950, easing: "ease-out" }
      )
      return () => animation.cancel()
    }, [device])
    const imageFor = (d: Device) => sources?.[d] ?? src

    // Arrow keys move between the options, like native radios
    const onKeyDown = (e: React.KeyboardEvent) => {
      const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[
        e.key
      ]
      if (!step) return
      e.preventDefault()
      const next = DEVICES[(DEVICES.indexOf(device) + step + 3) % 3]
      pick(next)
      e.currentTarget
        .querySelector<HTMLElement>(`[data-device="${next}"]`)
        ?.focus()
    }

    return (
      <div
        ref={ref}
        className={cn(
          "flex w-full min-w-72 flex-col items-center gap-4",
          className
        )}
        onPointerEnter={() => (paused.current = true)}
        onPointerLeave={() => (paused.current = false)}
        onFocus={() => (paused.current = true)}
        onBlur={() => (paused.current = false)}
        {...props}
      >
        <div
          ref={stageRef}
          className="relative flex aspect-[16/10] w-full items-center justify-center"
        >
          {/* Centred with translate rather than flexbox: resizing then never
              moves its layout position, so it isn't counted as layout shift */}
          <div
            className={cn(
              "absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden bg-neutral-900 shadow-[0_30px_80px_-40px_rgba(0,0,0,0.6)] transition-[width,height,border-radius,padding] duration-700 ease-[cubic-bezier(0.65,0,0.35,1)] motion-reduce:transition-none dark:bg-neutral-800",
              isDesktop ? "p-0 ring-1 ring-black/10" : "p-[7px]",
              live && "delay-[120ms]"
            )}
            style={{
              width: frame.w,
              height: frame.h,
              borderRadius: frame.radius,
            }}
          >
            {/* Browser bar, collapsed on tablet and phone */}
            <div
              aria-hidden="true"
              className={cn(
                "flex shrink-0 items-center gap-1.5 overflow-hidden bg-neutral-100 px-3 transition-[height,opacity] duration-500 motion-reduce:transition-none dark:bg-neutral-900",
                isDesktop ? "h-7 opacity-100" : "h-0 opacity-0",
                live && "delay-[120ms]"
              )}
            >
              <span className="size-2 rounded-full bg-[#FF5F57]" />
              <span className="size-2 rounded-full bg-[#FEBC2E]" />
              <span className="size-2 rounded-full bg-[#28C840]" />
              <span className="ml-3 truncate rounded bg-white px-3 py-0.5 font-mono text-[10px] text-neutral-500 dark:bg-neutral-800">
                {url}
              </span>
            </div>

            <div
              className="@container relative min-h-0 flex-1 overflow-hidden bg-background transition-[border-radius] duration-700 motion-reduce:transition-none"
              style={{
                borderRadius: isDesktop
                  ? "0 0 12px 12px"
                  : `calc(${frame.radius} - 7px)`,
              }}
            >
              {live ? (
                <div ref={contentRef} className="size-full">
                  {children}
                </div>
              ) : (
                // Each distinct screenshot once; the current device's shows
                [...new Set(DEVICES.map(imageFor))].map((source) =>
                  source ? (
                    <ImageTag
                      key={source}
                      src={source}
                      alt={source === imageFor(device) ? alt : ""}
                      loading="lazy"
                      className={cn(
                        "absolute inset-0 h-full w-full object-cover object-top transition-opacity duration-500",
                        source === imageFor(device)
                          ? "opacity-100"
                          : "opacity-0"
                      )}
                    />
                  ) : null
                )
              )}

              {/* Phone status pill */}
              <span
                aria-hidden="true"
                className={cn(
                  "pointer-events-none absolute top-1.5 left-1/2 h-3.5 w-[34%] -translate-x-1/2 rounded-full bg-neutral-900 transition-opacity duration-300",
                  device === "phone" ? "opacity-100 delay-500" : "opacity-0"
                )}
              />
            </div>
          </div>
        </div>

        {showControls && (
          <div
            role="radiogroup"
            aria-label="Device"
            onKeyDown={onKeyDown}
            className="inline-flex gap-1 rounded-full border bg-muted p-1"
          >
            {DEVICES.map((d) => {
              const Icon = ICONS[d]
              const active = d === device
              return (
                <button
                  key={d}
                  type="button"
                  role="radio"
                  aria-checked={active}
                  aria-label={LABELS[d]}
                  tabIndex={active ? 0 : -1}
                  data-device={d}
                  onClick={() => pick(d)}
                  className={cn(
                    "flex size-8 items-center justify-center rounded-full transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
                    active
                      ? "bg-background text-foreground shadow-sm"
                      : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  <Icon aria-hidden="true" className="size-4" />
                </button>
              )
            })}
          </div>
        )}
      </div>
    )
  }
)
DeviceMorph.displayName = "DeviceMorph"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `children` | `React.ReactNode` | - | No | Live content instead of screenshots. The screen is a container, so @md: and other container-query classes reflow it. |
| `src` | `string` | - | No | One screenshot for every device. |
| `sources` | `Partial<Record<"desktop" \| "tablet" \| "phone", string>>` | - | No | A screenshot per device; missing devices fall back to src. |
| `alt` | `string` | `""` | No | Alt text for the screenshot. |
| `device` | `"desktop" \| "tablet" \| "phone"` | - | No | Controlled device. |
| `defaultDevice` | `"desktop" \| "tablet" \| "phone"` | `"desktop"` | No | Device shown first. |
| `onDeviceChange` | `(device: Device) => void` | - | No | Called when the device changes. |
| `autoPlay` | `boolean` | `false` | No | Cycles through the devices while on screen and not hovered or focused. Stops once the visitor picks a device, and never runs with reduced motion. |
| `interval` | `number` | `3500` | No | Milliseconds per device when autoPlay is on. |
| `showControls` | `boolean` | `true` | No | Shows the device switcher. |
| `url` | `string` | `"yourwebsite.com"` | No | Text in the desktop address bar. |
| `imageAs` | `React.ElementType` | `"img"` | No | Component used for screenshots, e.g. next/image's Image. It receives src, alt, loading and className. |
| `className` | `string` | - | No | Extra classes for the root element. |
| `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | No | Any other attributes, passed to the root element. |

## Usage
```tsx
"use client"

import { DeviceMorph } from "@/components/ui/device-morph"

/** A tiny landing page that reflows with container queries */
function MiniSite() {
  return (
    <div className="flex h-full flex-col gap-[6cqw] p-[5cqw] text-neutral-900 @md:gap-[3cqw] dark:text-neutral-100">
      <div className="flex items-center justify-between">
        <span className="text-[4.5cqw] font-semibold @md:text-[1.8cqw]">
          Northwind
        </span>
        <span className="hidden gap-[2cqw] text-[1.4cqw] text-neutral-500 @md:flex">
          <span>Product</span>
          <span>Pricing</span>
          <span>Contact</span>
        </span>
        <span className="flex flex-col gap-[1cqw] @md:hidden">
          <span className="h-[0.8cqw] w-[6cqw] rounded bg-current" />
          <span className="h-[0.8cqw] w-[6cqw] rounded bg-current" />
        </span>
      </div>
      <div className="grid gap-[5cqw] @md:grid-cols-2 @md:items-center @md:gap-[4cqw]">
        <div>
          <p className="text-[8cqw] leading-tight font-semibold tracking-tight @md:text-[4cqw]">
            Coffee, roasted for you.
          </p>
          <p className="mt-[2cqw] text-[3.6cqw] text-neutral-500 @md:mt-[1cqw] @md:text-[1.5cqw]">
            Small batches, shipped the day they are roasted.
          </p>
          <span className="mt-[4cqw] inline-block rounded-full bg-neutral-900 px-[5cqw] py-[2cqw] text-[3.4cqw] text-white @md:mt-[2cqw] @md:px-[2.5cqw] @md:py-[1cqw] @md:text-[1.4cqw] dark:bg-white dark:text-neutral-900">
            Shop beans
          </span>
        </div>
        <div className="aspect-[4/3] rounded-[3cqw] bg-linear-to-br from-amber-300 via-orange-400 to-rose-500 @md:rounded-[1.5cqw]" />
      </div>
      <div className="grid grid-cols-2 gap-[3cqw] @md:grid-cols-4 @md:gap-[1.5cqw]">
        {["Light", "Medium", "Dark", "Decaf"].map((roast) => (
          <div
            key={roast}
            className="rounded-[2cqw] border p-[3cqw] text-[3.2cqw] @md:rounded-[1cqw] @md:p-[1.5cqw] @md:text-[1.3cqw]"
          >
            {roast}
          </div>
        ))}
      </div>
    </div>
  )
}

export default function DeviceMorphDemo() {
  return (
    <div className="w-full max-w-3xl p-4">
      <DeviceMorph url="northwind.coffee" autoPlay>
        <MiniSite />
      </DeviceMorph>
    </div>
  )
}

```
