Image Compare for Astro
Astro before-and-after pictures with a pointer and keyboard divider.
Installation
bunx --bun shadcn@latest add @gnostic/image-comparenpx shadcn@latest add @gnostic/image-comparepnpm dlx shadcn@latest add @gnostic/image-compareComplete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/coreCopy the files
src/components/ui/image-compare/image-compare-handle.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import GripVerticalIcon from "@lucide/astro/icons/grip-vertical"
/**
* Pointer drag surface and divider between the two pictures.
* Div attributes such as `class` pass through.
* The default slot replaces the grip icon.
* Keyboard input stays on the range control in `ImageCompare`.
*/
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="image-compare-handle"
aria-hidden="true"
class={cn(
"pointer-events-auto absolute inset-y-0 left-(--image-compare-position,50%) z-30 flex w-8 -translate-x-1/2 cursor-grab touch-none items-center justify-center",
"group-data-[dragging=true]/image-compare:cursor-grabbing",
className,
)}
{...props}
>
<span
class="block w-1 h-full bg-background absolute inset-0 mx-auto"
aria-hidden="true"
data-slot="image-compare-handle-line"
/>
<span
class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-background px-0.5 py-2 [&_svg:not([class*='size-'])]:size-4"
title="Slide to compare images"
>
<slot>
<GripVerticalIcon class="text-foreground/72 group-hover/image-compare:text-foreground" />
</slot>
</span>
</div>
src/components/ui/image-compare/image-compare-image.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { ImageCompareImageProps } from "./types.ts"
/** Image attributes pass through. `src`, `alt`, and `clip` come from `ImageCompareImageProps`. */
type Props = Omit<HTMLAttributes<"img">, "src" | "alt"> & ImageCompareImageProps
const {
class: className,
src,
alt,
width,
height,
clip = false,
draggable = false,
...props
} = Astro.props
/**
* An imported picture carries its own pixel size.
* A plain address uses the 16:9 fallback unless the caller sets a size.
* `draggable` is the string "true" or "false". A boolean false would omit the attribute.
*/
const resolvedSrc = typeof src === "string" ? src : src.src
const resolvedWidth = width ?? (typeof src === "string" ? 1200 : src.width)
const resolvedHeight = height ?? (typeof src === "string" ? 675 : src.height)
const imageDraggable =
draggable === true || draggable === "true" ? "true" : "false"
---
<img
data-slot="image-compare-image"
data-clip={clip ? "true" : undefined}
src={resolvedSrc}
alt={alt}
width={resolvedWidth}
height={resolvedHeight}
draggable={imageDraggable}
class={cn(
"pointer-events-none absolute inset-0 size-full object-cover",
clip ? "image-compare-clip z-10" : "z-0",
className,
)}
{...props}
/>
<style>
/* Reveal the left portion. The root sets --image-compare-position. */
.image-compare-clip {
clip-path: inset(0 calc(100% - var(--image-compare-position, 50%)) 0 0);
}
</style>
src/components/ui/image-compare/image-compare.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { ImageCompareProps } from "./types.ts"
/**
* Comparison frame.
* Place two `ImageCompareImage` parts and one `ImageCompareHandle` in the slot.
* Div attributes pass through. `defaultValue` and `label` come from `ImageCompareProps`.
*/
type Props = HTMLAttributes<"div"> & ImageCompareProps
const {
class: className,
defaultValue = 50,
label = "Amount of the clipped image shown",
style,
...props
} = Astro.props
/**
* Keep the divider inside the frame.
* A non-numeric value falls back to the center.
*/
const position = Number.isFinite(defaultValue)
? Math.min(100, Math.max(0, defaultValue))
: 50
/** String form so a value of 0 stays on the range control. */
const positionValue = String(position)
const positionStyle = `--image-compare-position:${positionValue}%`
const mergedStyle =
typeof style === "string"
? `${style};${positionStyle}`
: { ...style, "--image-compare-position": `${positionValue}%` }
---
<div
data-slot="image-compare"
data-dragging="false"
style={mergedStyle}
class={cn(
"group/image-compare relative block aspect-video w-full touch-pan-y overflow-hidden rounded-2xl bg-background select-none",
className,
)}
{...props}
>
<slot />
<input
data-slot="image-compare-input"
type="range"
min={0}
max={100}
step={0.01}
value={positionValue}
aria-label={label}
class="pointer-events-none sr-only"
/>
</div>
<script>
import { type ImageCompareController, create } from "./image-compare.ts"
const controllers: ImageCompareController[] = []
const initialize = () => controllers.push(...create())
initialize()
document.addEventListener("astro:page-load", initialize)
document.addEventListener("astro:before-swap", () => {
for (const controller of controllers) controller.destroy()
controllers.length = 0
})
</script>
src/components/ui/image-compare/image-compare.ts
import {
clearRootBinding,
getPart,
getRootBinding,
getRoots,
hasRootBinding,
on,
setRootBinding,
} from '@data-slot/core'
const ROOT_SLOT = 'image-compare'
export interface ImageCompareController {
destroy(): void
updatePosition(): void
startDrag(event: PointerEvent): void
endDrag(event: PointerEvent): void
moveDrag(event: PointerEvent): void
}
/** Bind each unbound comparison in the scope, as other data-slot controls do. */
export function create(scope: ParentNode = document): ImageCompareController[] {
return getRoots<HTMLElement>(scope, ROOT_SLOT)
.filter((root) => !hasRootBinding(root, ROOT_SLOT))
.map(createImageCompare)
}
/** Bind one comparison. Pointer input starts only on its own handle. */
export function createImageCompare(root: HTMLElement): ImageCompareController {
const existing = getRootBinding<ImageCompareController>(root, ROOT_SLOT)
if (existing) return existing
const input = getPart<HTMLInputElement>(root, 'image-compare-input')
const handle = getPart<HTMLElement>(root, 'image-compare-handle')
if (!input || !handle)
throw new Error('ImageCompare requires an input and a handle.')
let destroyed = false
let pointerId: number | null = null
let startX = 0
let startValue = 50
const updatePosition = () => {
if (destroyed) return
const parsed = Number(input.value)
const value = Number.isFinite(parsed)
? Math.min(100, Math.max(0, parsed))
: 50
input.value = String(value)
root.style.setProperty('--image-compare-position', `${value}%`)
}
const resetDrag = () => {
const id = pointerId
pointerId = null
root.dataset.dragging = 'false'
if (id !== null && handle.hasPointerCapture(id))
handle.releasePointerCapture(id)
}
const startDrag = (event: PointerEvent) => {
if (
destroyed ||
event.defaultPrevented ||
event.button !== 0 ||
!event.isPrimary ||
pointerId !== null
)
return
// Keep a click or a press off-center on the handle from moving the image.
startX = event.clientX
startValue = Number(input.value)
pointerId = event.pointerId
handle.setPointerCapture(pointerId)
root.dataset.dragging = 'true'
event.preventDefault()
input.focus({ preventScroll: true })
}
const endDrag = (event: PointerEvent) => {
if (event.pointerId === pointerId) resetDrag()
}
const moveDrag = (event: PointerEvent) => {
if (
destroyed ||
event.pointerId !== pointerId ||
root.clientWidth === 0
)
return
const delta = ((event.clientX - startX) / root.clientWidth) * 100
const value = Math.min(
100,
Math.max(0, Math.round((startValue + delta) * 100) / 100),
)
if (value === Number(input.value)) return
input.value = String(value)
input.dispatchEvent(new Event('input', { bubbles: true }))
}
const cleanups = [
on(input, 'input', updatePosition),
on(handle, 'pointerdown', startDrag),
on(handle, 'pointermove', moveDrag),
on(handle, 'pointerup', endDrag),
on(handle, 'pointercancel', endDrag),
on(handle, 'lostpointercapture', endDrag),
]
root.dataset.dragging = 'false'
updatePosition()
const controller: ImageCompareController = {
updatePosition,
startDrag,
endDrag,
moveDrag,
destroy() {
if (destroyed) return
destroyed = true
for (const cleanup of cleanups) cleanup()
resetDrag()
clearRootBinding(root, ROOT_SLOT, controller)
},
}
return setRootBinding(root, ROOT_SLOT, controller)
}
src/components/ui/image-compare/index.ts
export { default as ImageCompareHandle } from './image-compare-handle.astro'
export { default as ImageCompareImage } from './image-compare-image.astro'
export { default as ImageCompare } from './image-compare.astro'
export type { ImageCompareImageProps, ImageCompareProps } from './types.ts'
src/components/ui/image-compare/types.ts
import type { ImageMetadata } from 'astro'
/**
* Props for the comparison frame.
* Div attributes such as `class` and `id` pass through.
* Put both pictures and the handle in the default slot.
*/
export interface ImageCompareProps {
/**
* Divider position at first render, from 0 to 100.
* `0` hides the clipped picture. `100` covers the frame with it.
* @default 50
*/
defaultValue?: number
/**
* Accessible name for the range control.
* @default "Amount of the clipped image shown"
*/
label?: string
}
/**
* Props for one picture in a comparison.
* Image attributes such as `class`, `width`, `height`, and `loading` pass through.
*/
export interface ImageCompareImageProps {
/**
* Picture file or address.
*/
src: ImageMetadata | string
/**
* Text alternative for this picture.
*/
alt: string
/**
* Show only the part of this picture to the left of the divider.
* Set this on one picture. Leave it unset on the picture that fills the frame.
* @default false
*/
clip?: boolean
}
Usage
---
import {
ImageCompareHandle,
ImageCompareImage,
ImageCompare,
} from "@/components/ui/image-compare"
---
<ImageCompare>
<ImageCompareImage src={daylight} alt="Town in daylight" />
<ImageCompareImage src={sunset} alt="Town at sunset" clip />
<ImageCompareHandle />
</ImageCompare>
Composition
Put the full picture first. Set clip on the picture that shows to the left of the divider. Place ImageCompareHandle after the pictures. Corner labels are normal elements in the same slot.
ImageCompare
├── ImageCompareImage
├── ImageCompareImage clip
└── ImageCompareHandle
The handle slot replaces the grip icon. The divider does not take keyboard focus. The range control on ImageCompare does.
API Reference
ImageCompareProps
defaultValue?number
Divider position at first render, from 0 to 100. `0` hides the clipped picture. `100` covers the frame with it.
number50label?string
Accessible name for the range control.
string"Amount of the clipped image shown"Div attributes such as class and id pass through.
ImageCompareImageProps
srcImageMetadata | string
Picture file or address.
ImageMetadata | stringaltstring
Text alternative for this picture.
stringclip?boolean
Show only the part of this picture to the left of the divider. Set this on one picture. Leave it unset on the picture that fills the frame.
booleanfalseImage attributes such as class, width, height, and loading pass through.
ImageCompareHandle
ImageCompareHandle accepts div attributes such as class. Put a custom icon in its default slot.
Read the installed source for the component source.
When to use Image Compare
Use Image Compare for two pictures of the same subject. Drag the handle, or focus the control and use the arrow keys. Set defaultValue when the comparison should start away from the center.
Keyboard and behavior
Tab reaches the range control. Arrow keys move the divider. Drag the handle to move it with a pointer. Clicking the pictures or pressing the handle without moving it does not change the position. The control name comes from label. Give each picture its own alt text.
Theme and layout
The frame uses a 16:9 ratio. Pass another aspect-* class to change it. The divider and grip use the background color. Check both pictures in light and dark mode.

