All components
Image Cropper
Crop selection over an image with drag-to-move, eight resize handles, an optional locked aspect ratio, arrow-key nudging, and a rule-of-thirds grid while dragging.
measuring…
1234567891011121314151617181920import { useState } from "react";import { ImageCropper } from "#components/ui/base-ui/image-cropper.tsx";
export function Example() { const [crop, setCrop] = useState({ x: 0, y: 0, width: 0, height: 0 }); return ( // Base UI has no cropper, so Root owns the crop rect: it measures the // viewport, handles pointer drag (move + 8 handles), arrow-key nudging // (Shift = 10px, Alt + arrows resize) and a locked aspect ratio. Parts // compose through render. <ImageCropper.Root aspectRatio={16 / 9} onCropChange={(d) => setCrop(d.crop)}> <ImageCropper.Viewport> <ImageCropper.Image src="/photo.jpg" /> <ImageCropper.Selection /> </ImageCropper.Viewport> </ImageCropper.Root> );}
// imperative: <ImageCropper.Context>{(api) => <button onClick={api.reset}>Reset</button>}</ImageCropper.Context>Fixed aspect ratio
`aspectRatio={1}` locks the selection to a square; corner and edge handles keep the ratio and stay inside the image.
measuring…
123456<ImageCropper.Root aspectRatio={1}> <ImageCropper.Viewport> <ImageCropper.Image src="/photo.jpg" /> <ImageCropper.Selection /> </ImageCropper.Viewport></ImageCropper.Root>Circle crop
`cropShape="circle"` rounds the selection for avatar crops; the crop rect is still the bounding box.
measuring…
123456<ImageCropper.Root cropShape="circle" aspectRatio={1}> <ImageCropper.Viewport> <ImageCropper.Image src="/avatar.jpg" /> <ImageCropper.Selection /> </ImageCropper.Viewport></ImageCropper.Root>Install
1npx stylexblocks add image-cropperSource
components/ui/base-ui/image-cropper.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711import * as stylex from "@stylexjs/stylex";import { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState,} from "react";import { mergeProps } from "@base-ui/react/merge-props";import { useRender } from "@base-ui/react/use-render";import { defineSlotRecipe, resolveSlotStyles, type StyleOverrideProps,} from "#lib/recipe-props.ts";import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'import { colors } from '@stylexblocks/ui/tokens/colors.stylex.ts'import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'import { radii } from '@stylexblocks/ui/tokens/radii.stylex.ts'import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
const imageCropperRoot = stylex.create({ base: { display: 'flex', flexDirection: 'column', gap: spacing._3, width: '100%', position: 'relative', },})
// Same surface as the file-upload dropzone: page background, panel radius,// 1px border. The image fills it; the crop selection lives on top.const imageCropperViewport = stylex.create({ base: { position: 'relative', overflow: 'hidden', touchAction: 'none', userSelect: 'none', width: '100%', backgroundColor: semanticColors.bgMuted, borderRadius: semanticRadii.panel, borderWidth: '1px', borderStyle: 'solid', borderColor: semanticColors.border, },})
const imageCropperImage = stylex.create({ base: { display: 'block', width: '100%', height: 'auto', maxWidth: '100%', pointerEvents: 'none', userSelect: 'none', },})
// The selection dims everything outside it with a huge spread shadow and// draws a light frame that reads on any photo, in both color schemes.const imageCropperSelection = stylex.create({ base: { position: 'absolute', boxSizing: 'border-box', cursor: { default: 'move', ':is([data-disabled])': 'default', }, touchAction: 'none', borderWidth: '1px', borderStyle: 'solid', borderColor: colors.whiteAlpha700, borderRadius: { default: 0, ':is([data-shape="circle"])': radii.full, }, boxShadow: `0 0 0 9999px ${colors.blackAlpha600}`, outlineWidth: { default: null, ':focus-visible': '2px', }, outlineOffset: { default: null, ':focus-visible': '0px', }, outlineStyle: { default: null, ':focus-visible': 'solid', }, outlineColor: { default: null, ':focus-visible': colorPalette.focusRing, }, },})
// Edge handles are invisible hit strips (the engine sizes them along the// edge); corner handles are visible square knobs.const imageCropperHandle = stylex.create({ base: { position: 'absolute', boxSizing: 'border-box', zIndex: 1, touchAction: 'none', width: { default: null, ':is([data-position="e"], [data-position="w"])': spacing._3, ':is([data-position="ne"], [data-position="se"], [data-position="sw"], [data-position="nw"])': spacing._3, }, height: { default: null, ':is([data-position="n"], [data-position="s"])': spacing._3, ':is([data-position="ne"], [data-position="se"], [data-position="sw"], [data-position="nw"])': spacing._3, }, backgroundColor: { default: 'transparent', ':is([data-position="ne"], [data-position="se"], [data-position="sw"], [data-position="nw"])': colors.white, }, borderWidth: { default: 0, ':is([data-position="ne"], [data-position="se"], [data-position="sw"], [data-position="nw"])': '1px', }, borderStyle: 'solid', borderColor: colorPalette.solid, borderRadius: radii.xs, display: { default: null, ':is([data-disabled])': 'none', }, },})
// Rule-of-thirds lines: one element per axis spanning the middle third,// bordered on both sides. Hidden until the selection is dragged or panned.const imageCropperGrid = stylex.create({ base: { position: 'absolute', pointerEvents: 'none', borderStyle: 'solid', borderColor: colors.whiteAlpha600, borderBlockWidth: { default: 0, ':is([data-axis="horizontal"])': '1px', }, borderInlineWidth: { default: 0, ':is([data-axis="vertical"])': '1px', }, opacity: { default: 0, ':is([data-dragging], [data-panning])': 1, }, transitionProperty: 'opacity', transitionDuration: durations.fast, },})
const imageCropperRecipe = defineSlotRecipe({ slots: { root: { styles: imageCropperRoot }, viewport: { styles: imageCropperViewport }, image: { styles: imageCropperImage }, selection: { styles: imageCropperSelection }, handle: { styles: imageCropperHandle }, grid: { styles: imageCropperGrid }, }, defaultVariants: {},});
type Slot = keyof typeof imageCropperRecipe.slots;
export type ImageCropperHandlePosition = "n" | "e" | "s" | "w" | "ne" | "se" | "sw" | "nw";
/** A crop rectangle in viewport pixels (same shape Ark reports). */export interface ImageCropperRect { x: number; y: number; width: number; height: number;}
export interface ImageCropperCropChangeDetails { crop: ImageCropperRect;}
interface Size { width: number; height: number;}
const handles: ImageCropperHandlePosition[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
// Where each handle sits on the selection (mirrors Ark's inline placement).const handlePlacement: Record<ImageCropperHandlePosition, React.CSSProperties> = { n: { top: 0, left: "50%", width: "96%", translate: "-50% -50%", cursor: "n-resize" }, s: { bottom: 0, left: "50%", width: "96%", translate: "-50% 50%", cursor: "s-resize" }, e: { right: 0, top: "50%", height: "96%", translate: "50% -50%", cursor: "e-resize" }, w: { left: 0, top: "50%", height: "96%", translate: "-50% -50%", cursor: "w-resize" }, ne: { top: 0, right: 0, translate: "50% -50%", cursor: "ne-resize" }, nw: { top: 0, left: 0, translate: "-50% -50%", cursor: "nw-resize" }, se: { bottom: 0, right: 0, translate: "50% 50%", cursor: "se-resize" }, sw: { bottom: 0, left: 0, translate: "-50% 50%", cursor: "sw-resize" },};
const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);
const round = (rect: ImageCropperRect): ImageCropperRect => ({ x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height),});
/** Centered crop covering 80% of the viewport, respecting the aspect ratio. */function defaultCrop(bounds: Size, ratio: number | undefined): ImageCropperRect { let width = bounds.width * 0.8; let height = bounds.height * 0.8; if (ratio) { if (width / height > ratio) width = height * ratio; else height = width / ratio; } return { x: (bounds.width - width) / 2, y: (bounds.height - height) / 2, width, height, };}
function moveCrop(start: ImageCropperRect, dx: number, dy: number, bounds: Size) { return { ...start, x: clamp(start.x + dx, 0, bounds.width - start.width), y: clamp(start.y + dy, 0, bounds.height - start.height), };}
/** * Resize from a handle: the opposite edge (or corner) stays anchored, an * axis the handle doesn't touch stays centered, and with an aspect ratio * the free axis follows the dragged one. Always stays inside `bounds`. */function resizeCrop( start: ImageCropperRect, position: ImageCropperHandlePosition, dx: number, dy: number, bounds: Size, ratio: number | undefined, min: Size,): ImageCropperRect { const sx = position.includes("e") ? 1 : position.includes("w") ? -1 : 0; const sy = position.includes("s") ? 1 : position.includes("n") ? -1 : 0; const ax = sx > 0 ? start.x : sx < 0 ? start.x + start.width : start.x + start.width / 2; const ay = sy > 0 ? start.y : sy < 0 ? start.y + start.height : start.y + start.height / 2; const maxW = sx > 0 ? bounds.width - ax : sx < 0 ? ax : 2 * Math.min(ax, bounds.width - ax); const maxH = sy > 0 ? bounds.height - ay : sy < 0 ? ay : 2 * Math.min(ay, bounds.height - ay); let width = sx ? start.width + sx * dx : start.width; let height = sy ? start.height + sy * dy : start.height; if (ratio) { if (!sy) height = width / ratio; else if (!sx) width = height * ratio; else if (width / height > ratio) height = width / ratio; else width = height * ratio; const upper = Math.min(maxW, maxH * ratio); width = clamp(width, Math.min(Math.max(min.width, min.height * ratio), upper), upper); height = width / ratio; } else { width = clamp(width, Math.min(min.width, maxW), maxW); height = clamp(height, Math.min(min.height, maxH), maxH); } return { x: sx > 0 ? ax : sx < 0 ? ax - width : ax - width / 2, y: sy > 0 ? ay : sy < 0 ? ay - height : ay - height / 2, width, height, };}
interface DragState { pointerId: number; origin: { x: number; y: number }; start: ImageCropperRect; handle: ImageCropperHandlePosition | null;}
export interface ImageCropperContextValue { /** Current crop in viewport pixels (rounded); null until measured. */ crop: ImageCropperRect | null; dragging: boolean; setCrop: (crop: ImageCropperRect) => void; reset: () => void;}
interface InternalContext extends ImageCropperContextValue { ids: { root: string; viewport: string; selection: string }; rawCrop: ImageCropperRect | null; cropShape: "rectangle" | "circle"; viewportRef: (node: HTMLDivElement | null) => void; startDrag: (event: React.PointerEvent, handle: ImageCropperHandlePosition | null) => void; nudge: (event: React.KeyboardEvent) => void;}
const CropperContext = createContext<InternalContext | null>(null);
function useCropper() { const ctx = useContext(CropperContext); if (!ctx) throw new Error("ImageCropper parts must be rendered inside <ImageCropper.Root>"); return ctx;}
function slotProps(slot: Slot, palette: StyleOverrideProps["palette"], style: StyleOverrideProps["style"]) { return stylex.props(palette, ...resolveSlotStyles(imageCropperRecipe.slots[slot], {}), style);}
type PartProps<T extends keyof React.JSX.IntrinsicElements> = Omit< useRender.ComponentProps<T>, "style"> & StyleOverrideProps;
export interface ImageCropperRootProps extends PartProps<"div"> { /** Width / height ratio to lock the selection to (e.g. `1`, `16 / 9`). */ aspectRatio?: number; /** Initial crop in viewport pixels; defaults to a centered 80% box. */ initialCrop?: ImageCropperRect; minWidth?: number; minHeight?: number; /** Arrow-key step in px; Shift uses `nudgeStepShift`. */ nudgeStep?: number; nudgeStepShift?: number; cropShape?: "rectangle" | "circle"; onCropChange?: (details: ImageCropperCropChangeDetails) => void;}
/** * ImageCropper — Base UI ships no cropper, so Root owns the crop state: it * measures the viewport, keeps the selection inside it, and drives pointer * drag (move + eight resize handles), keyboard nudging (arrows, Shift for * bigger steps, Alt+arrows to resize) and an optional locked aspect ratio. * Parts compose through `render`. */function Root(props: ImageCropperRootProps) { const { aspectRatio, initialCrop, minWidth = 40, minHeight = 40, nudgeStep = 1, nudgeStepShift = 10, cropShape = "rectangle", onCropChange, render, palette, style, ...rest } = props; const ratio = cropShape === "circle" ? (aspectRatio ?? 1) : aspectRatio; const id = useId(); const ids = useMemo( () => ({ root: `${id}-root`, viewport: `${id}-viewport`, selection: `${id}-selection` }), [id], ); const [bounds, setBounds] = useState<Size | null>(null); const [crop, setCropState] = useState<ImageCropperRect | null>(null); const [dragging, setDragging] = useState(false); const dragRef = useRef<DragState | null>(null); const cropRef = useRef(crop); cropRef.current = crop; const boundsRef = useRef(bounds); boundsRef.current = bounds; const onCropChangeRef = useRef(onCropChange); onCropChangeRef.current = onCropChange;
const commit = useCallback((next: ImageCropperRect) => { setCropState(next); onCropChangeRef.current?.({ crop: round(next) }); }, []);
// Measure the viewport; place the first crop, then scale it on resize. const observerRef = useRef<ResizeObserver | null>(null); const viewportRef = useCallback((node: HTMLDivElement | null) => { observerRef.current?.disconnect(); observerRef.current = null; if (!node) return; const observer = new ResizeObserver(() => { const next = { width: node.clientWidth, height: node.clientHeight }; if (!next.width || !next.height) return; setBounds(next); }); observer.observe(node); observerRef.current = observer; }, []);
const lastBounds = useRef<Size | null>(null); useEffect(() => { if (!bounds) return; const prev = lastBounds.current; lastBounds.current = bounds; const current = cropRef.current; if (!current || !prev) { commit(initialCrop ?? defaultCrop(bounds, ratio)); return; } if (prev.width === bounds.width && prev.height === bounds.height) return; const kx = bounds.width / prev.width; const ky = bounds.height / prev.height; commit({ x: current.x * kx, y: current.y * ky, width: current.width * kx, height: current.height * ky, }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [bounds]);
// Re-fit when the aspect ratio prop changes. useEffect(() => { const current = cropRef.current; const b = boundsRef.current; if (!current || !b || !ratio) return; if (Math.abs(current.width / current.height - ratio) < 0.001) return; const fitted = resizeCrop(current, "se", 0, 0, b, ratio, { width: minWidth, height: minHeight }); commit(fitted); // eslint-disable-next-line react-hooks/exhaustive-deps }, [ratio]);
const startDrag = useCallback( (event: React.PointerEvent, handle: ImageCropperHandlePosition | null) => { if (event.pointerType === "mouse" && event.button !== 0) return; const start = cropRef.current; if (!start || dragRef.current) return; event.preventDefault(); event.stopPropagation(); (document.getElementById(ids.selection) as HTMLElement | null)?.focus({ preventScroll: true }); dragRef.current = { pointerId: event.pointerId, origin: { x: event.clientX, y: event.clientY }, start, handle, }; setDragging(true); const onMove = (e: PointerEvent) => { const drag = dragRef.current; const b = boundsRef.current; if (!drag || !b || e.pointerId !== drag.pointerId) return; const dx = e.clientX - drag.origin.x; const dy = e.clientY - drag.origin.y; commit( drag.handle ? resizeCrop(drag.start, drag.handle, dx, dy, b, ratio, { width: minWidth, height: minHeight, }) : moveCrop(drag.start, dx, dy, b), ); }; const onUp = (e: PointerEvent) => { if (dragRef.current && e.pointerId !== dragRef.current.pointerId) return; dragRef.current = null; setDragging(false); window.removeEventListener("pointermove", onMove); window.removeEventListener("pointerup", onUp); window.removeEventListener("pointercancel", onUp); }; window.addEventListener("pointermove", onMove); window.addEventListener("pointerup", onUp); window.addEventListener("pointercancel", onUp); }, [commit, ids.selection, minHeight, minWidth, ratio], );
const nudge = useCallback( (event: React.KeyboardEvent) => { const current = cropRef.current; const b = boundsRef.current; if (!current || !b) return; const step = event.shiftKey ? nudgeStepShift : nudgeStep; const delta: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step], }; const d = delta[event.key]; if (!d) return; event.preventDefault(); if (event.altKey) { // Alt + arrows resize from the end edges (like Ark). const handle = d[0] !== 0 ? "e" : "s"; commit( resizeCrop(current, handle, d[0], d[1], b, ratio, { width: minWidth, height: minHeight, }), ); return; } commit(moveCrop(current, d[0], d[1], b)); }, [commit, minHeight, minWidth, nudgeStep, nudgeStepShift, ratio], );
const ctx = useMemo<InternalContext>( () => ({ crop: crop ? round(crop) : null, rawCrop: crop, dragging, ids, cropShape, viewportRef, startDrag, nudge, setCrop: (next) => { const b = boundsRef.current; if (!b) return; const width = clamp(next.width, Math.min(minWidth, b.width), b.width); const height = clamp(next.height, Math.min(minHeight, b.height), b.height); commit({ width, height, x: clamp(next.x, 0, b.width - width), y: clamp(next.y, 0, b.height - height), }); }, reset: () => { const b = boundsRef.current; if (b) commit(initialCrop ?? defaultCrop(b, ratio)); }, }), [commit, crop, cropShape, dragging, ids, initialCrop, minHeight, minWidth, nudge, ratio, startDrag, viewportRef], );
const element = useRender({ defaultTagName: "div", render, props: mergeProps<"div">( { ...slotProps("root", palette, style), id: ids.root, role: "group", "aria-label": "Image cropper", "data-shape": cropShape, "data-dragging": dragging ? "" : undefined, } as React.ComponentProps<"div">, rest, ), }); return <CropperContext.Provider value={ctx}>{element}</CropperContext.Provider>;}Root.displayName = "ImageCropperRoot";
function Viewport(props: PartProps<"div">) { const { render, palette, style, ...rest } = props; const ctx = useCropper(); return useRender({ defaultTagName: "div", render, ref: ctx.viewportRef, props: mergeProps<"div">( { ...slotProps("viewport", palette, style), id: ctx.ids.viewport, role: "presentation" }, rest, ), });}Viewport.displayName = "ImageCropperViewport";
function Image(props: PartProps<"img">) { const { render, palette, style, ...rest } = props; return useRender({ defaultTagName: "img", render, props: mergeProps<"img">( { ...slotProps("image", palette, style), alt: "", draggable: false, "aria-hidden": true, }, rest, ), });}Image.displayName = "ImageCropperImage";
function Handle(props: PartProps<"div"> & { position: ImageCropperHandlePosition }) { const { position, render, palette, style, ...rest } = props; const ctx = useCropper(); const sx = slotProps("handle", palette, style); return useRender({ defaultTagName: "div", render, props: mergeProps<"div">( { ...sx, style: { ...sx.style, position: "absolute", ...handlePlacement[position] }, "aria-hidden": true, role: "presentation", "data-position": position, onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => ctx.startDrag(event, position), } as React.ComponentProps<"div">, rest, ), });}Handle.displayName = "ImageCropperHandle";
function Grid(props: PartProps<"div"> & { axis: "horizontal" | "vertical" }) { const { axis, render, palette, style, ...rest } = props; const ctx = useCropper(); const sx = slotProps("grid", palette, style); return useRender({ defaultTagName: "div", render, props: mergeProps<"div">( { ...sx, style: { ...sx.style, inset: axis === "horizontal" ? "33.33% 0" : "0 33.33%" }, "aria-hidden": true, "data-axis": axis, "data-dragging": ctx.dragging ? "" : undefined, } as React.ComponentProps<"div">, rest, ), });}Grid.displayName = "ImageCropperGrid";
/** * Selection — the focusable crop rectangle (a 2D slider for assistive * tech). Without children it renders the eight handles and the * rule-of-thirds grid. */function Selection(props: PartProps<"div">) { const { render, palette, style, children, ...rest } = props; const ctx = useCropper(); const crop = ctx.rawCrop; const sx = slotProps("selection", palette, style); const rounded = ctx.crop; return useRender({ defaultTagName: "div", render, props: mergeProps<"div">( { ...sx, style: { ...sx.style, position: "absolute", left: crop?.x ?? 0, top: crop?.y ?? 0, width: crop?.width ?? 0, height: crop?.height ?? 0, visibility: crop ? undefined : "hidden", }, id: ctx.ids.selection, tabIndex: 0, role: "slider", "aria-label": `Crop ${ctx.cropShape === "circle" ? "circle" : "rectangle"}`, "aria-roledescription": "2D slider", "aria-valuemin": 0, "aria-valuenow": rounded?.x ?? 0, "aria-valuetext": rounded ? `x ${rounded.x}, y ${rounded.y}, ${rounded.width} by ${rounded.height} pixels` : undefined, "aria-description": "Use arrow keys to move the crop, Shift for bigger steps. Hold Alt with arrow keys to resize.", "data-shape": ctx.cropShape, "data-dragging": ctx.dragging ? "" : undefined, "data-measured": crop ? "" : undefined, onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => ctx.startDrag(event, null), onKeyDown: ctx.nudge, children: children ?? ( <> {handles.map((position) => ( <Handle key={position} position={position} /> ))} <Grid axis="horizontal" /> <Grid axis="vertical" /> </> ), } as React.ComponentProps<"div">, rest, ), });}Selection.displayName = "ImageCropperSelection";
/** Read the crop state the way Ark exposes its machine context. */function Context({ children }: { children: (ctx: ImageCropperContextValue) => React.ReactNode }) { const { crop, dragging, setCrop, reset } = useCropper(); return children({ crop, dragging, setCrop, reset });}
export const ImageCropper = { Root, Viewport, Image, Selection, Handle, Grid, Context, handles,};