---
title: "ImagePreview"
description: "A full-window image viewer with zoom, rotation, and swipe paging."
category: Data
status: beta
since: 0.9.2
tags: [image, zoom, gesture, lightbox]
syncStatus: reviewed
verified: true
---

## Usage

### Basic
`origin` returns each image's thumbnail, so the preview grows out of it and shrinks back into it on closing; zoom with the wheel, a trackpad, or two fingers, swipe sideways to page, and drag up or down to close.
::::TuffDemoWrapper{demo="ImagePreviewBasicDemo" code-lang="vue"}
---
code: |
  <script setup lang="ts">
  import { ref } from 'vue'

  const images = [
    { url: '/shots/search.jpg', thumbnail: '/shots/search-s.jpg', name: 'File search', width: 1668, height: 1080 },
    { url: '/photos/fjord.jpg', thumbnail: '/photos/fjord-s.jpg', name: 'Fjord panorama', width: 3000, height: 1000 },
    { url: '/photos/alley.jpg', thumbnail: '/photos/alley-s.jpg', name: 'Brick alley', width: 1200, height: 1800 },
  ]

  const open = ref(false)
  const index = ref(0)
  const grid = ref<HTMLElement | null>(null)

  // Image i flies out of thumbnail i, and back into it on closing
  function thumbOf(i: number) {
    return grid.value?.children[i] ?? null
  }

  function show(at: number, event: MouseEvent) {
    // WebKit does not focus a clicked button; focused first, it gets the focus back on close
    ;(event.currentTarget as HTMLElement).focus()
    index.value = at
    open.value = true
  }
  </script>

  <template>
    <div ref="grid">
      <button v-for="(image, i) in images" :key="image.url" type="button" @click="show(i, $event)">
        <img :src="image.thumbnail" alt="">
      </button>
    </div>

    <TxImagePreview
      v-model:open="open"
      v-model:index="index"
      :images="images"
      :origin="thumbOf"
    />
  </template>
---
::::

### Actions and the Long-Press Menu
`actions` chooses the toolbar's and the menu's actions and their order, and calling `preventDefault()` in the `action` event leaves one to the host; with `contextMenu` set to `false`, a long press or a right-click no longer opens the menu.

```vue
<script setup lang="ts">
import type { ImagePreviewActionEvent } from '@talex-touch/tuffex/image-preview'

function onAction(event: ImagePreviewActionEvent) {
  // The host saves into its own album instead; the preview leaves it alone
  if (event.action === 'download') {
    event.preventDefault()
    saveToAlbum(event.item.url)
  }
}
</script>

<template>
  <TxImagePreview
    v-model:open="open"
    :images="images"
    :actions="['rotate', 'copy', 'download']"
    @action="onAction"
  />
</template>
```

### Materials and the Strip
`indicator` picks a strip of thumbnails, dots, or nothing, `maskSurface` / `controlSurface` pick the materials behind the image and under the controls, and `bounce` sets how far pages, jumps, and the flight overshoot.
::::TuffDemoWrapper{demo="ImagePreviewOptionsDemo" code-lang="vue"}
---
code: |
  <template>
    <TxImagePreview
      v-model:open="open"
      v-model:index="index"
      :images="images"
      :origin="thumbOf"
      indicator="dots"
      mask-surface="blur"
      control-surface="glass"
      :bounce="0.45"
    />
  </template>
---
::::

### Single Image
With one image there is no counter, no page buttons, and no strip, and the image gets more of the screen.

```vue
<template>
  <button type="button" @click="open = true">
    <img :src="cover" alt="Cover">
  </button>
  <TxImagePreview v-model:open="open" :images="[cover]" />
</template>
```

### Opening from Code
`show(index)` opens at the given image, and `close()` closes without emitting `close`.

```vue
<script setup lang="ts">
import type { TxImagePreviewInstance } from '@talex-touch/tuffex/image-preview'
import { ref } from 'vue'

const preview = ref<TxImagePreviewInstance | null>(null)
</script>

<template>
  <TxButton @click="preview?.show(2)">View the third</TxButton>
  <TxImagePreview ref="preview" :images="images" />
</template>
```

### Best Practices

- Pass `origin` and `width` / `height`: the image grows out of its thumbnail and back into it, and its placeholder takes its shape before it loads.
- Pass a `thumbnail` when you have one: the strip uses it, and otherwise loads the full image in every cell.
- Pass URLs that already failed as thumbnails to `failed`; the preview shows its failure placeholder without requesting them again.
- The presets need three.js (an optional peer). With three installed, they work from every entry point. Without it, importing `image-preview` directly logs `is not exported` warnings at build time (the build still succeeds), and at run time the placeholder falls back to `skeleton`; importing from the package entry point fails the whole page, a problem that predates this change.
- Focus the trigger before opening: WebKit does not focus a clicked button, and focus can only return to an element that had it.
- On non-English surfaces, override every text prop and all five formatters: the buttons are icons, and these names are what screen readers announce.

## API Reference

### Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `open` | `boolean` | `false` | Whether the preview is open; use with `v-model:open`. |
| `index` | `number` | `0` | The current image; use with `v-model:index`. Clamped to the list. |
| `images` | `ImagePreviewSource[]` | `[]` | URLs, or objects with a name, a size, and a thumbnail; the preview closes when the list empties. |
| `items` | `ImagePreviewSource[]` | — | Images or custom content; wins over `images` when given. For custom content with `svg` / `raw` and no `url`, copy and save work on the text: copy yields `copyText` (the markup itself by default) and save writes an `.svg` file; share stays unavailable. |
| `origin` | `(index: number) => ImagePreviewOrigin \| null \| undefined` | - | Where image `index` sits on the page, asked on opening and again on closing for the image shown then. |
| `transition` | `'zoom' \| 'fade'` | `'zoom'` | How the preview opens and closes; `zoom` fades instead without an `origin`, with the thumbnail out of view, with an image not ready in time, or with reduced motion. |
| `maxScale` | `number` | `4` | The largest zoom against the image's own pixels, so `1` is 100%; never below the whole image's fit. |
| `failed` | `ReadonlySet<string> \| string[]` | - | URLs the host already saw fail; shown as the failure placeholder and never requested. |
| `loadingEffect` | `'sweep-gradient' \| 'pixels-organic' \| 'pixels-mechanic' \| 'skeleton' \| 'none'` | `'sweep-gradient'` | What shows in a picture's place while it loads: one of the three [TxImageGeneration](/docs/dev/components/image-generation) presets, the `skeleton` shimmer, or `none`. Only a picture that is loading plays it. The presets need three.js; see below. |
| `actions` | `ImagePreviewAction[]` | `['rotate', 'copy', 'share', 'download']` | The toolbar's and the menu's actions, in this order; share shows only where the browser can share. |
| `contextMenu` | `boolean` | `true` | A long press on the image, a right-click, or the context-menu key opens a menu of the actions. |
| `indicator` | `'thumbnails' \| 'dots' \| 'none'` | `'thumbnails'` | The strip along the bottom: thumbnails, dots, or nothing; hidden with a single image. |
| `minimap` | `boolean` | `true` | While an image is zoomed in, the whole of it in the bottom-right corner with the part on screen framed; a press or a drag on it moves there. |
| `bounce` | `number` | `0.2` | How far a page turn, a jump, the menu, and the flight out of the thumbnail overshoot; `0` for none, `0.9` at most. |
| `maskSurface` | `BaseSurfaceMode` | `'refraction'` | The [TxBaseSurface](/docs/dev/components/base-surface) material behind the image. |
| `maskColor` | `string` | `'rgb(10, 10, 12)'` | The colour of that material. |
| `maskOpacity` | `number` | `0.35` | The opacity of that colour, `0`–`1`. |
| `maskBlur` | `number` | `12` | How far it blurs the page behind it (px). |
| `controlSurface` | `BaseSurfaceMode` | `'blur'` | The material of the buttons, the toolbar, the dots, the status, and the menu. |
| `controlColor` | `string` | `'rgb(64, 64, 70)'` | The colour of that material. |
| `controlOpacity` | `number` | `0.6` | The opacity of that colour, `0`–`1`. |
| `controlBlur` | `number` | `16` | How far it blurs what is behind it (px). |
| `label` | `string` | `'Image preview'` | The dialog's accessible name, joined to the current image's `name` by `labelFormatter`. |
| `closeLabel` | `string` | `'Close'` | Accessible name of the close button. |
| `previousLabel` | `string` | `'Previous image'` | Accessible name of the previous button. |
| `nextLabel` | `string` | `'Next image'` | Accessible name of the next button. |
| `zoomInLabel` | `string` | `'Zoom in'` | Accessible name of the zoom-in button. |
| `zoomOutLabel` | `string` | `'Zoom out'` | Accessible name of the zoom-out button. |
| `zoomLabel` | `string` | `'Zoom'` | Accessible name of the menu the zoom readout opens; joined after the readout by `readoutLabelFormatter`, it names the readout too. |
| `resetLabel` | `string` | `'Fit to screen'` | The zoom menu's first item, which shows the whole image again. |
| `rotateLabel` | `string` | `'Rotate'` | The rotate action's name. |
| `copyLabel` | `string` | `'Copy image'` | The copy action's name. |
| `shareLabel` | `string` | `'Share'` | The share action's name. |
| `downloadLabel` | `string` | `'Download'` | The download action's name. |
| `menuLabel` | `string` | `'Image actions'` | Accessible name of the menu. |
| `indicatorLabel` | `string` | `'Images'` | Accessible name of the strip. |
| `copiedText` | `string` | `'Image copied'` | Said once the image is on the clipboard. |
| `linkCopiedText` | `string` | `'Link copied'` | Said when only the image's link went onto the clipboard. |
| `copyFailedText` | `string` | `'Could not copy the image'` | Said when copying fails. |
| `failedText` | `string` | `'This image could not be loaded'` | Text in the placeholder of an image that failed to load. |
| `counterFormatter` | `(current: number, total: number) => string` | `` (c, t) => `${c} / ${t}` `` | The position count in the top bar; hidden with a single image. |
| `scaleFormatter` | `(scale: number) => string` | `` (s) => `${Math.round(s * 100)}%` `` | The zoom readout and the zooms in its menu, with `scale` against the image's own pixels. |
| `indicatorItemFormatter` | `(current: number, total: number, name?: string) => string` | `` (c, t, name) => name ? `${name}, ${c} of ${t}` : `Image ${c} of ${t}` `` | The accessible name of each thumbnail or dot in the strip. |
| `labelFormatter` | `(label: string, name: string) => string` | `` (label, name) => `${label}: ${name}` `` | The dialog's accessible name while the current image has a `name`. |
| `readoutLabelFormatter` | `(readout: string, label: string) => string` | `` (readout, label) => `${readout}, ${label}` `` | The zoom readout's accessible name, from the readout and `zoomLabel`. |

### Events

| Event | Payload | Description |
|------|---------|-------------|
| `update:open` | `(open: boolean)` | Fires when the preview opens or closes. |
| `update:index` | `(index: number)` | Fires when the current image changes; on a swipe, once the new image is halfway in. |
| `close` | `()` | Fires when the person closes it: the close button, Escape, the backdrop, or dragging the image away; never when the host does. |
| `error` | `(url: string, index: number)` | Fires once per URL when an image fails to load; the neighbours on either side preload too. |
| `action` | `(event: ImagePreviewActionEvent)` | Fires when an action is chosen, before the preview carries it out; after `preventDefault()` the host carries it out itself. |

### Slots

| Slot | Description |
|------|------|
| `default` | Custom content for each image, used when `item` is not given. Receives `{ item, index, scale, turns, view, stage }`. |
| `item` | Custom content for each image; takes precedence over `default` and receives the same props. |
| `thumbnail` | Replaces each thumbnail in the bottom strip. Receives `{ item, index, current }`. |
| `minimap` | Replaces the minimap in the lower-right corner. Receives `{ item, index, turns, view, stage }`. |
| `loading` | Replaces the default loading placeholder. Receives `{ item, index }` and renders in the picture's place, at the placeholder's size. |

### Exposed Methods

| Name | Type | Description |
|------|------|-------------|
| `show` | `(index?: number) => void` | Opens the preview, optionally at a given image. |
| `close` | `() => void` | Closes the preview without emitting `close`. |
| `next` / `prev` | `() => void` | Turns to the next / previous image; does nothing at either end. |
| `zoomIn` / `zoomOut` | `() => void` | Zooms in / out by √2 about the centre of the view. |
| `reset` | `() => void` | Shows the whole image again. |
| `rotate` | `(direction?: 1 \| -1) => void` | Turns the image a quarter clockwise (the default) or back, whatever `actions` holds, without emitting `action`. |

### Types

#### ImagePreviewItem

`ImagePreviewSource` is `string | ImagePreviewItem`; a string is the image URL.

| Field | Type | Default | Description |
|------|------|---------|-------------|
| `url` | `string` | required | The image URL, which also keys its loading state: a new URL loads afresh. Custom content may omit it. |
| `type` | `'image' \| 'custom'` | `'image'` | Set to `'custom'` for custom content. |
| `name` | `string` | - | Shown in the top bar and after the dialog's name; also the alt text when `alt` is absent. |
| `alt` | `string` | - | The image's alt text. |
| `width` / `height` | `number` | - | The image's own size; the placeholder takes its shape before it loads. |
| `thumbnail` | `string` | - | A smaller copy for the strip; `url` stands in without one. |
| `component` | `Component` | - | The component rendered for custom content; it receives `item` and `payload` props. |
| `payload` | `unknown` | - | Data passed to `component` as `payload`. |
| `raw` | `string` | - | Trusted HTML or SVG markup; sanitize untrusted markup first. |
| `svg` | `string` | - | Trusted SVG markup, rendered without fetching an external image. |
| `copyText` | `string` | - | Clipboard text for custom content without a `url`; without it, the `svg` or `raw` markup is copied as text. |

#### ImagePreviewOrigin

`ImagePreviewOrigin` is `Element | ImagePreviewOriginRect`. From an element, the preview reads its own `<img>`, or the first inside it: the box, the corners, `object-fit`, and whatever its ancestors clip off. The element hides while the image flies, and its loaded pixels stand in until the full image arrives. From a rect, only the box and the corners are used.

| Field | Type | Default | Description |
|------|------|---------|-------------|
| `x` / `y` | `number` | required | The top-left corner in viewport pixels. |
| `width` / `height` | `number` | required | The size in pixels. |
| `radius` | `number` | `0` | The corner radius in pixels. |

#### ImagePreviewActionEvent

`ImagePreviewAction` is `'rotate' | 'copy' | 'share' | 'download'`.

| Field | Type | Description |
|------|------|-------------|
| `action` | `ImagePreviewAction` | The action chosen. |
| `index` | `number` | The current image's index. |
| `item` | `ImagePreviewItem` | The current image, with a string source turned into an item. |
| `preventDefault` | `() => void` | Skips the preview's own handling. |
| `defaultPrevented` | `boolean` | Whether `preventDefault()` was called. |

## Overview

- Opening, closing, and loading: with an `origin`, the image grows out of the thumbnail's crop and corners, overshoots a little, and settles; on closing it straightens and shrinks back into place, and a flight turns round where it is when the preview opens or closes again midway. Closed in the middle of a page turn, the image more than half in view goes home, and the neighbour slides back as it fades with the backdrop, so the index stays where it was. Before an image loads, its place is held at `width` / `height`, or else at the shape of the last image looked at, and the `loadingEffect` effect appears only after 150 ms, and with reduced motion it holds still on one frame; a failed image shows a placeholder with `failedText`, and the same URL is not requested again.
- Mouse and trackpad: the wheel zooms about the pointer, and a pinch or ⌘/Ctrl + wheel zooms under the fingers, Safari's pinch gestures included. A click or a double-click on the image zooms to the detail about the pointer, and another goes back; zoomed in, a drag or a two-finger scroll pans, coasts on after release, and resists like a rubber band past the edges; at fit, a sideways drag or swipe turns the page and a vertical drag pulls the image away to close. A right-click on the image opens the action menu, and Shift + right-click still gets the browser's own.
- Touch: two fingers pinch about their midpoint, and lifting one carries on as a one-finger drag without a jump; a double tap zooms in or back, and a tap hides or shows the controls. A 480 ms long press opens the action menu above the finger, with a light vibration where the browser supports one.
- Keyboard: `+` / `-` zoom, `0` shows the whole image, ← / → page, and while zoomed the arrows pan; `R` / `Shift + R` rotate, ⌘/Ctrl + C copies, and the context-menu key or Shift + F10 opens the menu, where ↑ / ↓ / Home / End move and Escape or Tab close it. Escape first undoes a gesture under way, then closes; Tab cycles within the dialog, and closing returns focus to the element that had it.
- The zoom menu: a press on the toolbar's readout opens a menu above it. Its first item, `resetLabel`, shows the whole image again, and after it come those of 25%, 50%, 100%, 200% and on up to 1600% that are larger than the whole image and no larger than `maxScale`; the current zoom is checked, and choosing one zooms there about the middle of the view. The menu is a `role="menu"` named by `zoomLabel`, its items `menuitemradio`; it opens with focus on the checked item, ↑ / ↓ / Home / End move, Escape or Tab close it and return to the readout, and a press anywhere off it only closes it. While the image has no size yet, or its whole is as far as it zooms, the readout is `aria-disabled` and opens nothing.
- Actions: rotate turns a quarter at a time and fits the image again, and a page turn straightens it. Copy puts the image on the clipboard as a PNG, or only its link when the image's server does not allow CORS; share sends a web image as its link and a `data:` / `blob:` image as a file; download saves a same-origin, `data:`, or `blob:` image under its name and opens a cross-origin one in a new tab. A failed image offers no actions, and the outcome is said in a `role="status"` region.
- The strip: among thumbnails the current one opens out to its own shape, and the dots shrink at an end with more beyond it. The strip follows the page, a click jumps, a drag across it scrubs through, and only the current item is a Tab stop. The dialog has `role="dialog"` and `aria-modal="true"`, named by `labelFormatter` from `label` and the current image's `name`; the top bar's name and count are an `aria-live` region, and at either end the page button is `aria-disabled` rather than disabled, so focus never drops to `body`.
- The minimap: zoomed in, the whole image sits in the bottom-right corner with the part on screen framed and the rest dimmed, in step with every pan and zoom. A press outside the frame glides there, a drag on the frame carries the view along, and Escape during the drag goes back to where it began without closing the preview; the wheel over it zooms about the middle of the view. It answers only to the pointer and is hidden from assistive technology, since the arrow keys pan; it fades out as the view heads back to the whole image, when the page turns, and when the image is rotated.

## Technologies

- Motion: zooms and bounces settle on a spring with damping ratio 1 and a 0.35 s response, pages on a 0.4 s one and the flight out of the thumbnail on a 0.36 s one, both damped at `1 - bounce`, while the flight home never overshoots; the strip's and the menu's easing curves come from `bounce` too. A released drag glides on at the pointer's speed, and with `prefers-reduced-motion: reduce` everything lands at once. `will-change` is set only while something moves, so a zoomed image re-rasterises at its new scale when it stops and stays sharp.
- Appearance: the backdrop and the controls are TxBaseSurface in `fake` mode. The preview teleports to `body`, takes its layer from the shared z-index manager, and is always dark. At 640px wide or less, or 480px tall or less, the image fills the screen under floating controls, the toolbar keeps only the actions, and the page buttons move to the bottom, or give way to a strip; buttons are 44px and keep clear of the safe areas. The on-demand style plugin loads TxBaseSurface's styles along with it; when importing styles by hand, also import `style.css` from `base-surface`, `flow-light`, and `glass-surface`.
- Source: `packages/tuffex/packages/components/src/image-preview/`.

<TuffDocSourceLink />
