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…
1234567891011121314151617181920212223import { useState } from "react";import { ImageCropper } from "#components/ui/ui-sdk/image-cropper.tsx";
export function Example() { const [crop, setCrop] = useState(null); return ( // UI SDK's ImageCropper: drag to move, drag a handle to resize, arrow // keys on the selection or a focused handle (Shift = 10x), +/- zoom, // R rotates, Escape cancels a drag. The crop is in the image's own // pixels (with rotation/flips), ready for cropImage from @ui-sdk/react/image. <ImageCropper.Root aspectRatio={16 / 9} onCropChange={(d) => setCrop(d.crop)}> <ImageCropper.Viewport> <ImageCropper.Image src="/photo.jpg" alt="Your photo" /> <ImageCropper.Selection /> </ImageCropper.Viewport> </ImageCropper.Root> );}
// custom parts: handles go BESIDE the selection, inside the viewport:// <ImageCropper.Selection><ImageCropper.Grid axis="horizontal" /></ImageCropper.Selection>// {ImageCropper.handles.map((p) => <ImageCropper.Handle key={p} position={p} />)}// 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/ui-sdk/image-cropper.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444import * as stylex from "@stylexjs/stylex";import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState,} from "react";import { createImageCropperController, ImageCropper as UiSdkImageCropper, ImageCropperHandle, ImageCropperImage, ImageCropperSelection, ImageCropperViewport, type ImageCrop, type ImageCropperController, type ImageCropperCropChangeReason, type ImageCropperHandlePosition, type ImageCropperState,} from "@ui-sdk/react/image-cropper";import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";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: {},});
export type { ImageCropperHandlePosition };
/** The crop in the image's own pixels, with its rotation and flips. */export type ImageCropperRect = Required<ImageCrop>;
export interface ImageCropperCropChangeDetails { crop: ImageCropperRect; reason: ImageCropperCropChangeReason;}
const handles: ImageCropperHandlePosition[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
const corner = ':is([data-position="ne"], [data-position="se"], [data-position="sw"], [data-position="nw"])';
// What differs from Ark's layout. UI SDK places the image absolutely once it// loads, so the viewport takes the image's ratio from the variable UI SDK// sets. Handles sit BESIDE the selection, positioned at the point on its edge// or corner, so they're centered on it with a translate; edge handles get a// fixed-length hit strip (Ark sizes them to the edge's length) — the width/// height maps restate the recipe's corner sizes, since a property-level map// replaces the recipe's whole map. Handles are focusable sliders in UI SDK,// so they get the selection's focus ring.const chrome = stylex.create({ viewport: { aspectRatio: "var(--image-cropper-aspect-ratio)" }, handle: { translate: "-50% -50%", width: { default: null, ':is([data-position="n"], [data-position="s"])': spacing._10, ':is([data-position="e"], [data-position="w"])': spacing._3, [corner]: spacing._3, }, height: { default: null, ':is([data-position="e"], [data-position="w"])': spacing._10, ':is([data-position="n"], [data-position="s"])': spacing._3, [corner]: spacing._3, }, outlineWidth: { default: null, ":focus-visible": "2px" }, outlineOffset: { default: null, ":focus-visible": "1px" }, outlineStyle: { default: null, ":focus-visible": "solid" }, outlineColor: { default: null, ":focus-visible": colorPalette.focusRing }, },});
const gridInset = { horizontal: "33.33% 0", vertical: "0 33.33%" } as const;
const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
export interface ImageCropperContextValue { /** Current crop in image pixels; null until the image loads. */ crop: ImageCropperRect | null; dragging: boolean; zoom: number; setCrop: (crop: ImageCrop) => void; reset: () => void; rotate: (direction?: 1 | -1) => void; flip: (direction?: "horizontal" | "vertical") => void;}
interface InternalContext { controller: ImageCropperController; setImageSrc: (src: string | undefined) => void; initial: React.RefObject<ImageCropperRect | null>;}
const CropperContext = createContext<InternalContext | null>(null);const StateContext = createContext<ImageCropperState | null>(null);
const { withProvider, withContext } = createSlotRecipeContext(imageCropperRecipe);
const StyledRoot = withProvider(UiSdkImageCropper, "root", "ImageCropperRoot");
type UiSdkRootProps = React.ComponentProps<typeof UiSdkImageCropper>;
export interface ImageCropperRootProps extends Omit< UiSdkRootProps, "style" | "className" | "children" | "onCropChange" | "defaultCrop" | "shape" >, StyleOverrideProps { /** Initial crop in image pixels; defaults to a centered box 4/5 as large as the ratio allows. */ initialCrop?: ImageCrop; cropShape?: "rectangle" | "circle"; onCropChange?: (details: ImageCropperCropChangeDetails) => void; children?: React.ReactNode;}
/** * ImageCropper — on UI SDK's ImageCropper: pointer drag (move + resize * handles), arrow keys on the selection or a handle (Shift = 10×), +/- to * zoom, R to rotate, Escape to cancel a drag, and an optional locked aspect * ratio. The crop is in the image's own pixels, ready for `cropImage`. * `Image` may carry the `src` (lifted to the root) or the root may take it. */function Root(props: ImageCropperRootProps) { const { src, initialCrop, cropShape = "rectangle", aspectRatio, onCropChange, controller: own, children, ...rest } = props; const [fallback] = useState(createImageCropperController); const controller = own ?? fallback; const [imageSrc, setImageSrc] = useState<string | undefined>(undefined); const initial = useRef<ImageCropperRect | null>(null); const [ctx] = useState<InternalContext>(() => ({ controller, setImageSrc, initial })); return ( <CropperContext.Provider value={ctx}> <StyledRoot aria-label="Image cropper" {...rest} src={src ?? imageSrc} shape={cropShape} aspectRatio={cropShape === "circle" ? (aspectRatio ?? 1) : aspectRatio} defaultCrop={initialCrop} controller={controller} onCropChange={(crop, details) => { if (details.reason === "image-load") initial.current = crop; onCropChange?.({ crop, reason: details.reason }); }} > {(state: ImageCropperState) => ( <StateContext.Provider value={state}>{children}</StateContext.Provider> )} </StyledRoot> </CropperContext.Provider> );}Root.displayName = "ImageCropperRoot";
const Viewport = withContext( ImageCropperViewport, (v) => [...resolveSlotStyles(imageCropperRecipe.slots.viewport, v), chrome.viewport], "ImageCropperViewport",);
const StyledImage = withContext(ImageCropperImage, "image", "ImageCropperImage");
/** The image. A `src` here is lifted to the root, which loads and measures it. */function Image(props: React.ComponentProps<typeof StyledImage>) { const { src, alt = "", ...rest } = props; const ctx = useContext(CropperContext); useIsomorphicLayoutEffect(() => { if (typeof src === "string") ctx?.setImageSrc(src); }, [src]); // Passing `src` through keeps it in the server render, before the lift. return <StyledImage alt={alt} {...(typeof src === "string" ? { src } : {})} {...rest} />;}Image.displayName = "ImageCropperImage";
const StyledHandle = withContext( ImageCropperHandle, (v) => [...resolveSlotStyles(imageCropperRecipe.slots.handle, v), chrome.handle], "ImageCropperHandle",);
/** Resizes from one edge or corner. Goes BESIDE the Selection, in the Viewport. */const Handle = StyledHandle;
/** * Rule-of-thirds lines for one axis: render one per axis inside the * Selection. A plain element, not UI SDK's ImageCropperGrid — that part is * a single full-size grid, and only one instance per cropper receives the * live `data-dragging` attribute, so two axis lines can't both be one. The * dragging state comes from the root's state instead. */function Grid( props: Omit<PartProps<"div", ImageCropperState | null>, "style"> & StyleOverrideProps & { axis: "horizontal" | "vertical" },) { const { axis, palette, style, render, ...rest } = props; const state = useContext(StateContext); const sx = stylex.props( palette, ...resolveSlotStyles(imageCropperRecipe.slots.grid, {}), style, ); return renderElement( "div", mergeProps( { ...sx, style: { ...sx.style, inset: gridInset[axis] }, "aria-hidden": true, "data-slot": "image-cropper-grid", "data-axis": axis, "data-dragging": state?.dragging ? "" : undefined, }, rest, ), render, state, );}Grid.displayName = "ImageCropperGrid";
const StyledSelection = withContext(ImageCropperSelection, "selection", "ImageCropperSelection");
/** * Selection — the focusable crop rectangle (a slider). Without children it * renders the rule-of-thirds grid inside and the eight handles beside it * (UI SDK keeps handles out of the slider, for assistive tech). With your own * children, place the Handles next to the Selection yourself. */function Selection(props: React.ComponentProps<typeof StyledSelection>) { const { children, ...rest } = props; if (children !== undefined) return <StyledSelection {...rest}>{children}</StyledSelection>; return ( <> <StyledSelection {...rest}> <Grid axis="horizontal" /> <Grid axis="vertical" /> </StyledSelection> {handles.map((position) => ( <Handle key={position} position={position} /> ))} </> );}Selection.displayName = "ImageCropperSelection";
/** Read the crop state the way Ark exposes its machine context. */function Context({ children }: { children: (ctx: ImageCropperContextValue) => React.ReactNode }) { const state = useContext(StateContext); const internal = useContext(CropperContext); if (!state || !internal) { throw new Error("ImageCropper parts must be rendered inside <ImageCropper.Root>"); } const { controller, initial } = internal; return children({ crop: state.crop, dragging: state.dragging, zoom: state.zoom, setCrop: (crop) => controller.setCrop(crop), reset: () => { if (initial.current) controller.setCrop(initial.current); }, rotate: (direction) => controller.rotate(direction), flip: (direction) => controller.flip(direction), });}
export const ImageCropper = { Root, Viewport, Image, Selection, Handle, Grid, Context, handles,};