# Window

Draggable retro window with a striped title bar, close button and optional status bar. Drags snap to --pixel.

Source: https://www.ui95.dev/ui/window

## Examples

```tsx
import { useState } from "react"

import { Window } from "@/components/retro/window"
import { Button } from "@/components/ui/button"

import type { ShowcaseDemo } from "../types"

const START = { x: 16, y: 16 }
const WINDOW_WIDTH = "w-80"

function Desk({ children }: { children: React.ReactNode }) {
  return <div className="relative h-72 w-full overflow-hidden bg-desktop">{children}</div>
}

function ClosableWindow() {
  const [isOpen, setIsOpen] = useState(true)

  return (
    <Desk>
      {isOpen ? (
        <Window
          title="Notes.txt"
          defaultPosition={START}
          className={WINDOW_WIDTH}
          statusBar={<span>Ln 1, Col 1</span>}
          onClose={() => setIsOpen(false)}
        >
          <p className="p-3 text-xl">Buy floppies. Defrag on Sunday.</p>
        </Window>
      ) : (
        <Button size="sm" className="absolute top-4 left-4" onClick={() => setIsOpen(true)}>
          Reopen
        </Button>
      )}
    </Desk>
  )
}

function FullControlsWindow() {
  const [isMinimized, setIsMinimized] = useState(false)

  return (
    <Desk>
      {isMinimized ? (
        <Button size="sm" className="absolute top-4 left-4" onClick={() => setIsMinimized(false)}>
          Restore
        </Button>
      ) : (
        <Window
          title="Explorer"
          defaultPosition={START}
          className={WINDOW_WIDTH}
          onMinimize={() => setIsMinimized(true)}
          onClose={() => setIsMinimized(true)}
        >
          <p className="p-3 text-xl">Maximize is disabled here.</p>
        </Window>
      )}
    </Desk>
  )
}

export const demo: ShowcaseDemo = {
  span: "full",
  variants: [
    { label: "active, close, status bar", render: () => <ClosableWindow /> },
    { label: "minimize, maximize, close", render: () => <FullControlsWindow /> },
    {
      label: "inactive",
      render: () => (
        <Desk>
          <Window title="Clock" isActive={false} defaultPosition={START} className={WINDOW_WIDTH}>
            <p className="p-3 font-pixel text-[24px] leading-none">12:00</p>
          </Window>
        </Desk>
      ),
    },
    {
      label: "page variant, scrolling body",
      render: () => (
        <Desk>
          <Window title="Readme.txt" variant="page" defaultPosition={START} className={`h-52 ${WINDOW_WIDTH}`}>
            <div className="flex flex-col gap-2 p-3 text-xl">
              {Array.from({ length: 8 }, (_, index) => (
                <p key={index}>Line {index + 1}. Long files scroll inside the window.</p>
              ))}
            </div>
          </Window>
        </Desk>
      ),
    },
    {
      label: "bare",
      render: () => (
        <Desk>
          <Window title="About" defaultPosition={START} className={WINDOW_WIDTH}>
            <p className="p-3 text-xl">UI95 v0.0.1</p>
          </Window>
        </Desk>
      ),
    },
  ],
}
```

## Installation

```bash
npx shadcn@latest add https://www.ui95.dev/r/window.json
```

Run it in a Radix shadcn project that already has the UI95 theme.

Dependencies:

```bash
npm install cn
```

Add these items first:

- [button](https://www.ui95.dev/ui/button)
- [pixel-glyphs](https://www.ui95.dev/ui/pixel-glyphs)
- [scroll-area](https://www.ui95.dev/ui/scroll-area)

`components/retro/window.tsx`

```tsx
"use client"

import { cn } from "cn"
import * as React from "react"

import { Button } from "@/components/ui/button"
import { CloseGlyph, MaximizeGlyph, MinimizeGlyph } from "@/components/ui/pixel-glyphs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { type Point, useWindowDrag } from "@/hooks/use-window-drag"

type WindowVariant = "card" | "page"

const VARIANT_SURFACES: Record<WindowVariant, { body: string; inactiveTitlebar: string }> = {
  card: { body: "bg-card text-card-foreground dark:bg-(--ink-1)", inactiveTitlebar: "bg-card text-card-foreground" },
  page: { body: "bg-background text-foreground", inactiveTitlebar: "bg-background text-foreground" },
}

type WindowProps = Omit<React.ComponentProps<"section">, "title"> & {
  title: string
  variant?: WindowVariant
  titleIcon?: React.ReactNode
  defaultPosition?: Point
  isActive?: boolean
  statusBar?: React.ReactNode
  onMinimize?: () => void
  onMaximize?: () => void
  onClose?: () => void
  onActivate?: () => void
}

const ORIGIN: Point = { x: 0, y: 0 }

function stopPointerPropagation(event: React.PointerEvent) {
  event.stopPropagation()
}

function TitleBarButton({
  label,
  onClick,
  children,
}: {
  label: string
  onClick?: () => void
  children: React.ReactNode
}) {
  return (
    <Button
      variant="ghost"
      size="icon-xs"
      aria-label={label}
      className="text-current"
      disabled={onClick === undefined}
      onPointerDown={stopPointerPropagation}
      onClick={onClick}
    >
      {children}
    </Button>
  )
}

function Window({
  title,
  variant = "card",
  titleIcon,
  defaultPosition,
  isActive = true,
  statusBar,
  onMinimize,
  onMaximize,
  onClose,
  onActivate,
  className,
  style,
  children,

  ...props
}: WindowProps) {
  const isDraggable = defaultPosition !== undefined
  const { position, isDragging, startDrag } = useWindowDrag(defaultPosition ?? ORIGIN)
  const hasFullControls = onMinimize !== undefined || onMaximize !== undefined

  return (
    <section
      aria-label={title}
      data-slot="window"
      data-variant={variant}
      data-active={isActive}
      data-dragging={isDragging}
      className={cn(
        "flex flex-col pixel-border border-border dither-shadow bevel-frame",
        VARIANT_SURFACES[variant].body,
        isDraggable ? "absolute" : "relative",
        className
      )}
      style={isDraggable ? { left: position.x, top: position.y, ...style } : style}
      onPointerDownCapture={onActivate}
      {...props}
    >
      <header
        data-slot="window-titlebar"
        onPointerDown={isDraggable ? startDrag : undefined}
        className={cn(
          "flex h-8 shrink-0 items-center gap-3 border-b-(length:--pixel) border-border pr-1 pl-3 font-pixel text-[16px] leading-none uppercase select-none",
          isActive
            ? "bg-titlebar text-titlebar-foreground"
            : VARIANT_SURFACES[variant].inactiveTitlebar,
          isDraggable && "cursor-grab touch-none",
          isDragging && "cursor-grabbing",
        )}
      >
        {titleIcon}
        <h2 className="truncate">{title}</h2>
        <span aria-hidden="true" className="h-4 min-w-6 flex-1 stripes" />
        {hasFullControls && (
          <TitleBarButton label={`Minimize ${title}`} onClick={onMinimize}>
            <MinimizeGlyph />
          </TitleBarButton>
        )}
        {hasFullControls && (
          <TitleBarButton label={`Maximize ${title}`} onClick={onMaximize}>
            <MaximizeGlyph />
          </TitleBarButton>
        )}
        {(hasFullControls || onClose) && (
          <TitleBarButton label={`Close ${title}`} onClick={onClose}>
            <CloseGlyph />
          </TitleBarButton>
        )}
      </header>
      <ScrollArea
        data-slot="window-body"
        className="min-h-0 flex-1 [&>[data-slot=scroll-area-viewport]>div]:relative [&>[data-slot=scroll-area-viewport]>div]:min-h-full"
      >
        {children}
      </ScrollArea>
      {statusBar && (
        <footer
          data-slot="window-statusbar"
          className="flex h-7 shrink-0 items-center gap-2 border-t-(length:--pixel) border-border px-2 text-lg leading-none"
        >
          {statusBar}
        </footer>
      )}
    </section>
  )
}

export { Window, type WindowProps, type WindowVariant }
```

`hooks/use-window-drag.ts`

```tsx
"use client"

import {
  type PointerEvent as ReactPointerEvent,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react"

export type Point = {
  x: number
  y: number
}

export type WindowDrag = {
  position: Point
  isDragging: boolean
  startDrag: (event: ReactPointerEvent<HTMLElement>) => void
}

const DEFAULT_PIXEL = 2

function readPixel(): number {
  const raw = getComputedStyle(document.documentElement).getPropertyValue("--pixel")
  const pixel = Number.parseFloat(raw)
  return Number.isFinite(pixel) && pixel > 0 ? pixel : DEFAULT_PIXEL
}

function snapToPixel(value: number, pixel: number): number {
  return Math.round(value / pixel) * pixel
}

export function useWindowDrag(initialPosition: Point): WindowDrag {
  const [position, setPosition] = useState(initialPosition)
  const [isDragging, setIsDragging] = useState(false)
  const positionRef = useRef(initialPosition)
  const stopRef = useRef<(() => void) | null>(null)

  useEffect(() => () => stopRef.current?.(), [])

  const startDrag = useCallback((event: ReactPointerEvent<HTMLElement>) => {
    if (event.button !== 0) {
      return
    }
    event.preventDefault()
    stopRef.current?.()
    const pixel = readPixel()
    const windowElement = event.currentTarget.closest<HTMLElement>("[data-slot='window']") ?? event.currentTarget
    const scale = windowElement.offsetWidth > 0 ? windowElement.getBoundingClientRect().width / windowElement.offsetWidth : 1
    const origin = { x: event.clientX, y: event.clientY, position: positionRef.current }

    function trackPointer(moveEvent: PointerEvent) {
      const next = {
        x: snapToPixel(origin.position.x + (moveEvent.clientX - origin.x) / scale, pixel),
        y: snapToPixel(origin.position.y + (moveEvent.clientY - origin.y) / scale, pixel),
      }
      positionRef.current = next
      setPosition(next)
    }

    function stop() {
      window.removeEventListener("pointermove", trackPointer)
      window.removeEventListener("pointerup", drop)
      window.removeEventListener("pointercancel", drop)
      stopRef.current = null
    }

    function drop() {
      stop()
      setIsDragging(false)
    }

    window.addEventListener("pointermove", trackPointer)
    window.addEventListener("pointerup", drop)
    window.addEventListener("pointercancel", drop)
    stopRef.current = stop
    setIsDragging(true)
  }, [])

  return { position, isDragging, startDrag }
}
```

## API reference

### Window

| Prop | Type | Default |
| --- | --- | --- |
| `title` * | `string` | - |
| `variant` | `WindowVariant` | `"card"` |
| `titleIcon` | `React.ReactNode` | - |
| `defaultPosition` | `Point` | - |
| `isActive` | `boolean` | `true` |
| `statusBar` | `React.ReactNode` | - |
| `onMinimize` | `(() => void)` | - |
| `onMaximize` | `(() => void)` | - |
| `onClose` | `(() => void)` | - |
| `onActivate` | `(() => void)` | - |

## Sounds

- `drag.pickup`
- `drag.drop`
- `drag.friction`
