Image Cropper
Upload an image, then crop it in a dialog.
import { Div, signal } from "@implementjs/core";
import {
ImageCropper,
ImageCropperCancel,
ImageCropperControls,
ImageCropperCrop,
ImageCropperCropper,
ImageCropperDialog,
ImageCropperPreview,
ImageCropperTrigger,
} from "@/lib/components/ui/image-cropper";
export default function ImageCropperDemo() {
const src = signal("https://github.com/ieedan.png");
return Div(
{ class: "flex justify-center" },
ImageCropper(
{ src },
ImageCropperTrigger(ImageCropperPreview()),
ImageCropperDialog(
ImageCropperCropper(),
ImageCropperControls(ImageCropperCrop(), ImageCropperCancel()),
),
),
);
}Installation
npx jsrepo add @implementjs/ui/image-cropper
It installs @implementjs/lucide at the same time, plus the avatar, button, and dialog components it is built from.
Copy the file below to src/lib/components/ui/image-cropper.ts, along with avatar.ts, button.ts, and dialog.ts (and what they need). It imports cn from @implementjs/cn. Then, on top of @implementjs/core and @implementjs/primitives:
npm install @implementjs/lucide
import { Div, Span, type Child, type ComponentProps, type Readable } from "@implementjs/core";
import { CropIcon, Trash2Icon, UploadIcon } from "@implementjs/lucide";
import {
createComponent,
ImageCropper as ImageCropperPrimitive,
ImageCropperCancel as ImageCropperCancelPrimitive,
ImageCropperContext,
ImageCropperCrop as ImageCropperCropPrimitive,
ImageCropperCropper as ImageCropperCropperPrimitive,
ImageCropperTrigger as ImageCropperTriggerPrimitive,
} from "@implementjs/primitives";
import { cn } from "@implementjs/cn";
import { Avatar, AvatarFallback, AvatarImage } from "./avatar";
import { buttonVariants, type ButtonSize, type ButtonVariant } from "./button";
import { Dialog, DialogContent, DialogTitle } from "./dialog";
export { getFileFromUrl } from "@implementjs/primitives";
export type ImageCropperProps = ComponentProps<typeof ImageCropperPrimitive>;
export type ImageCropperTriggerProps = ComponentProps<typeof ImageCropperTriggerPrimitive>;
export type ImageCropperPreviewProps = ComponentProps<typeof Avatar> & {
/** Draw the picture yourself instead of in a round avatar. It is handed the current `src`. */
child?: (src: Readable<string>) => Child;
};
export type ImageCropperDialogProps = ComponentProps<typeof DialogContent>;
export type ImageCropperCropperProps = ComponentProps<typeof ImageCropperCropperPrimitive>;
export type ImageCropperControlsProps = ComponentProps<typeof Div>;
export type ImageCropperCropProps = ComponentProps<typeof ImageCropperCropPrimitive> & {
variant?: ButtonVariant;
size?: ButtonSize;
};
export type ImageCropperCancelProps = ComponentProps<typeof ImageCropperCancelPrimitive> & {
variant?: ButtonVariant;
size?: ButtonSize;
};
export const ImageCropper = createComponent(function ImageCropper(
props: ImageCropperProps,
...children: Child[]
) {
return ImageCropperPrimitive(props, ...children);
});
export const ImageCropperTrigger = createComponent(function ImageCropperTrigger(
{ class: className, ...props }: ImageCropperTriggerProps,
...children: Child[]
) {
return ImageCropperTriggerPrimitive(
{ ...props, "data-slot": "image-cropper-trigger", class: cn("cursor-pointer", className) },
...children,
);
});
export const ImageCropperPreview = createComponent(function ImageCropperPreview({
child,
class: className,
...props
}: ImageCropperPreviewProps) {
return ImageCropperContext.Use((state) =>
child
? child(state.src)
: Avatar(
{
...props,
"data-slot": "image-cropper-preview",
class: cn("size-20 ring-2 ring-accent ring-offset-2 ring-offset-background", className),
},
AvatarImage({ src: state.src, alt: "" }),
AvatarFallback(
UploadIcon({ class: "size-4", "aria-hidden": true }),
Span({ class: "sr-only" }, "Upload image"),
),
),
);
});
/** The modal the picture is cropped in. It opens when a file is chosen. */
export const ImageCropperDialog = createComponent(function ImageCropperDialog(
{ class: className, ...props }: ImageCropperDialogProps,
...children: Child[]
) {
return ImageCropperContext.Use((state) =>
Dialog(
{ open: state.open },
DialogContent(
{
showCloseButton: false,
...props,
"data-slot": "image-cropper-dialog",
class: cn(
"max-w-full rounded-none border-x-0 sm:max-w-lg sm:rounded-lg sm:border-x",
className,
),
},
DialogTitle({ class: "sr-only" }, "Crop image"),
...children,
),
),
);
});
export const ImageCropperCropper = createComponent(function ImageCropperCropper({
class: className,
...props
}: ImageCropperCropperProps) {
return ImageCropperCropperPrimitive({
...props,
"data-slot": "image-cropper-cropper",
class: cn(
"h-72 w-full rounded-md bg-muted outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
// the dimmed surround is a huge shadow cast by the crop area
"[&>[data-image-cropper-area]]:border-2 [&>[data-image-cropper-area]]:border-white/80 [&>[data-image-cropper-area]]:shadow-[0_0_0_9999px_rgb(0_0_0/0.5)]",
"[&>[data-image-cropper-area][data-shape=round]]:rounded-full",
"cursor-grab active:cursor-grabbing",
className,
),
});
});
export const ImageCropperControls = createComponent(function ImageCropperControls(
{ class: className, ...props }: ImageCropperControlsProps,
...children: Child[]
) {
return Div(
{
...props,
"data-slot": "image-cropper-controls",
class: cn("flex w-full items-center justify-center gap-2", className),
},
...children,
);
});
export const ImageCropperCrop = createComponent(function ImageCropperCrop(
{ class: className, variant = "default", size = "sm", ...props }: ImageCropperCropProps,
...children: Child[]
) {
return ImageCropperCropPrimitive(
{
...props,
"data-slot": "image-cropper-crop",
"data-variant": variant,
"data-size": size,
class: cn(buttonVariants({ variant, size }), className),
},
...(children.length > 0 ? children : [CropIcon({ "aria-hidden": true }), Span("Crop")]),
);
});
export const ImageCropperCancel = createComponent(function ImageCropperCancel(
{ class: className, variant = "outline", size = "sm", ...props }: ImageCropperCancelProps,
...children: Child[]
) {
return ImageCropperCancelPrimitive(
{
...props,
"data-slot": "image-cropper-cancel",
"data-variant": variant,
"data-size": size,
class: cn(buttonVariants({ variant, size }), className),
},
...(children.length > 0 ? children : [Trash2Icon({ "aria-hidden": true }), Span("Cancel")]),
);
});Usage
import { signal } from "@implementjs/core";
import {
ImageCropper,
ImageCropperCancel,
ImageCropperControls,
ImageCropperCrop,
ImageCropperCropper,
ImageCropperDialog,
ImageCropperPreview,
ImageCropperTrigger,
} from "@/lib/components/ui/image-cropper";
const src = signal("");
ImageCropper(
{ src, onCropped: (url) => upload(url) },
ImageCropperTrigger(ImageCropperPreview()),
ImageCropperDialog(
ImageCropperCropper(),
ImageCropperControls(ImageCropperCrop(), ImageCropperCancel()),
),
);
The composition:
ImageCropper
├── ImageCropperTrigger
│ └── ImageCropperPreview
└── ImageCropperDialog
├── ImageCropperCropper
└── ImageCropperControls
├── ImageCropperCrop
└── ImageCropperCancel
src is an object URL; to send it to a server, turn it into a file with getFileFromUrl(src).
Custom preview
Pass child to ImageCropperPreview to draw the picture yourself, and aspect and shape to the cropper to match:
import { Div, Img, signal, Span } from "@implementjs/core";
import {
ImageCropper,
ImageCropperCancel,
ImageCropperControls,
ImageCropperCrop,
ImageCropperCropper,
ImageCropperDialog,
ImageCropperPreview,
ImageCropperTrigger,
} from "@/lib/components/ui/image-cropper";
export default function ImageCropperWideDemo() {
const src = signal("");
return Div(
{ class: "flex justify-center" },
ImageCropper(
{ src },
ImageCropperTrigger(
ImageCropperPreview({
child: (url) =>
Div(
{
class:
"flex aspect-video w-64 items-center justify-center overflow-hidden rounded-md border border-dashed bg-muted text-sm text-muted-foreground",
},
Span(
{ class: url.bind((current) => (current === "" ? "" : "hidden")) },
"Choose a cover image",
),
Img({
src: url.bind((current) => current || undefined),
alt: "Cover",
class: url.bind((current) =>
current === "" ? "hidden" : "size-full object-cover",
),
}),
),
}),
),
ImageCropperDialog(
ImageCropperCropper({ aspect: 16 / 9, shape: "rect" }),
ImageCropperControls(ImageCropperCrop(), ImageCropperCancel()),
),
),
);
}API Reference
Every prop the styling does not consume is forwarded to the Image Cropper primitive, so the tables below are the whole surface.
ImageCropper
The root. It renders no element of its own — only the hidden file input every trigger points at — and holds the picture, the crop, and the open state.
| Prop | Type | Default | Description |
|---|---|---|---|
src | Signal<string> | string | "" | The current image URL. A confirmed crop writes its object URL here; pass a signal to read it. |
onSrcChange | (src: string) => void | — | Runs whenever the image URL changes. |
onCropped | (url: string) => void | — | Runs with the object URL of the cropped image once a crop is confirmed. |
onUnsupportedFile | (file: File) => void | — | Runs when the chosen file is not an image a browser can draw. |
open | Signal<boolean> | boolean | false | Whether the crop dialog is open. It opens itself when a file is chosen; pass a signal to control it. |
onOpenChange | (open: boolean) => void | — | Runs whenever the open state changes. |
id | string | — | Set on the file input, so a trigger's `for` reaches it. |
inputProps | ElementProps<"input"> | — | Props for the hidden file input. |
| Data attribute | Value |
|---|---|
[data-image-cropper-input] | Present, on the file input |
ImageCropperTrigger
A label for the file input. Clicking anything inside it opens the file picker. Renders a Label; extra props are forwarded onto it.
| Data attribute | Value |
|---|---|
[data-image-cropper-trigger] | Present |
ImageCropperCropper
The surface the picture is moved and zoomed on under a fixed crop area. Drag to pan, scroll or pinch to zoom; with focus, arrow keys pan and + / - zoom. It has no size of its own, so give it a width and a height. Renders a Div; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
aspect | number | 1 | Width over height of the area that is kept. |
shape | "round" | "rect" | "round" | Sets data-shape on the surface and the area, so the outline can be styled. The saved image is always a rectangle. |
zoom | Signal<number> | number | 1 | How far in the picture is zoomed. 1 just covers the crop area. |
onZoomChange | (zoom: number) => void | — | Runs whenever the zoom changes. |
minZoom | number | 1 | The lowest zoom. |
maxZoom | number | 3 | The highest zoom. |
alt | string | "" | Alt text for the picture. |
| Data attribute | Value |
|---|---|
[data-image-cropper-cropper] | Present |
[data-image-cropper-area] | Present, on the crop area inside |
[data-shape] | "round" | "rect" |
ImageCropperCrop
Confirms the crop: the picture becomes the root's src and the dialog closes. Renders a crop icon and a label unless you pass children of your own. Renders a Button; extra props are forwarded onto it.
| Data attribute | Value |
|---|---|
[data-image-cropper-crop] | Present |
ImageCropperCancel
Throws the picture away and closes the dialog. Renders a trash icon and a label unless you pass children of your own. Renders a Button; extra props are forwarded onto it.
| Data attribute | Value |
|---|---|
[data-image-cropper-cancel] | Present |
ImageCropperPreview
What the trigger shows: the current src in a round avatar, with an upload icon until there is one. Every Avatar prop is forwarded. Renders a Div; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
child | (src: Readable<string>) => Child | — | Draw the picture yourself instead of in an avatar. It is handed the current src. |
ImageCropperDialog
The modal the picture is cropped in. It opens when a file is chosen and closes on crop or cancel. Every DialogContent prop is forwarded. Renders a Div; extra props are forwarded onto it.
ImageCropperControls
A centred row for the crop and cancel buttons. Renders a Div; extra props are forwarded onto it.