Files
dashboards/apps/business/src/components/ImageCropper.tsx
T
Alireza HassaniandCursor e2950fa20e Add store installments module with calculator and public API docs.
Business dashboard can manage credit methods and preview plans; cropper and module flags support the new flow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 23:17:51 +03:30

231 lines
6.9 KiB
TypeScript

import { useCallback, useEffect, useState } from 'react'
import Cropper, { type Area } from 'react-easy-crop'
import { ImagePlus, X } from 'lucide-react'
import { getCroppedImage } from '../utils/cropImage'
import { useT } from '../i18n/useT'
import styles from './ImageCropper.module.css'
interface ImageCropperProps {
value: string | null
onChange: (value: string | null) => void
/** Crop aspect ratio. Defaults to square (1). */
aspect?: number
/**
* Output format. When omitted, follows the uploaded file
* (PNG stays PNG with transparent padding; other images become JPEG with white padding).
*/
outputFormat?: 'jpeg' | 'png'
/** Fill color for JPEG and for crop areas outside the image. */
fillColor?: string
/** Minimum zoom. Values below 1 shrink the image inside the crop frame. */
minZoom?: number
maxZoom?: number
accept?: string
uploadLabel?: string
hint?: string
changeLabel?: string
/** Smaller upload/preview frame for narrow grid columns. */
compact?: boolean
}
function isPngSource(file: File): boolean {
return (
file.type === 'image/png' ||
file.name.toLowerCase().endsWith('.png')
)
}
function isPngDataUrl(src: string): boolean {
return /^data:image\/png/i.test(src)
}
export function ImageCropper({
value,
onChange,
aspect = 1,
outputFormat,
fillColor,
minZoom = 0.4,
maxZoom = 3,
accept = 'image/*',
uploadLabel,
hint,
changeLabel,
compact = false,
}: ImageCropperProps) {
const t = useT()
const resolvedUploadLabel = uploadLabel ?? t('products.form.thumbnailUpload')
const resolvedHint = hint ?? t('products.form.thumbnailHint')
const resolvedChangeLabel = changeLabel ?? t('products.form.thumbnailChange')
const [imageSrc, setImageSrc] = useState<string | null>(null)
const [sourceIsPng, setSourceIsPng] = useState(false)
const [crop, setCrop] = useState({ x: 0, y: 0 })
const [zoom, setZoom] = useState(1)
const [croppedArea, setCroppedArea] = useState<Area | null>(null)
const resolvedFormat: 'jpeg' | 'png' =
outputFormat ?? (sourceIsPng ? 'png' : 'jpeg')
const resolvedFillColor =
fillColor ?? (resolvedFormat === 'jpeg' ? '#ffffff' : undefined)
const useTransparentPad = resolvedFormat === 'png' && !resolvedFillColor
useEffect(() => {
setCrop({ x: 0, y: 0 })
setZoom(1)
setCroppedArea(null)
}, [aspect])
const onCropComplete = useCallback((_: Area, pixels: Area) => {
setCroppedArea(pixels)
}, [])
function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file) return
const png = isPngSource(file)
setSourceIsPng(png)
const reader = new FileReader()
reader.onload = () => {
setImageSrc(reader.result as string)
setCrop({ x: 0, y: 0 })
setZoom(1)
setCroppedArea(null)
}
reader.readAsDataURL(file)
e.target.value = ''
}
async function applyCrop() {
if (!imageSrc || !croppedArea) return
const format: 'jpeg' | 'png' =
outputFormat ?? (isPngDataUrl(imageSrc) || sourceIsPng ? 'png' : 'jpeg')
const fill = fillColor ?? (format === 'jpeg' ? '#ffffff' : undefined)
const cropped = await getCroppedImage(imageSrc, croppedArea, format, fill)
onChange(cropped)
setImageSrc(null)
setZoom(1)
setCrop({ x: 0, y: 0 })
}
function cancelCrop() {
setImageSrc(null)
setZoom(1)
setCrop({ x: 0, y: 0 })
}
function removeThumbnail() {
onChange(null)
}
const isPortrait = aspect < 1
const maxHeight = isPortrait ? 'min(360px, 42vh)' : 'min(280px, 36vh)'
const frameStyle: React.CSSProperties = compact
? {
aspectRatio: String(aspect),
width: '100%',
height: 'auto',
minHeight: 0,
}
: {
aspectRatio: String(aspect),
width: `min(100%, calc(${maxHeight} * ${aspect}))`,
height: 'auto',
maxHeight,
minHeight: 0,
marginInline: 'auto',
alignSelf: 'center',
}
const cropSurfaceStyle: React.CSSProperties = useTransparentPad
? { ...frameStyle }
: { ...frameStyle, background: resolvedFillColor ?? '#1e293b' }
return (
<div className={`${styles.wrapper} ${compact ? styles.compact : ''}`}>
{value && !imageSrc && (
<div className={styles.preview} style={frameStyle}>
<img src={value} alt={resolvedUploadLabel} className={styles.previewImg} />
<button
type="button"
className={styles.removeBtn}
onClick={removeThumbnail}
aria-label={t('products.form.thumbnailRemove')}
>
<X size={16} />
</button>
</div>
)}
{!value && !imageSrc && (
<label className={styles.uploadZone} style={frameStyle}>
<ImagePlus size={compact ? 20 : 28} />
<span>{resolvedUploadLabel}</span>
<span className={styles.hint}>{resolvedHint}</span>
<input type="file" accept={accept} onChange={handleFile} hidden />
</label>
)}
{imageSrc && (
<div className={styles.cropPanel}>
<div
className={`${styles.cropArea} ${useTransparentPad ? styles.cropAreaTransparent : ''}`}
style={cropSurfaceStyle}
>
<Cropper
key={String(aspect)}
image={imageSrc}
crop={crop}
zoom={zoom}
minZoom={minZoom}
maxZoom={maxZoom}
aspect={aspect}
onCropChange={setCrop}
onZoomChange={setZoom}
onCropComplete={onCropComplete}
restrictPosition={minZoom >= 1}
style={{
containerStyle: useTransparentPad
? { background: 'transparent' }
: { background: resolvedFillColor ?? '#1e293b' },
}}
/>
</div>
<div className={styles.cropControls}>
<label className={styles.zoomLabel}>
{t('products.form.zoom')}
<input
type="range"
min={minZoom}
max={maxZoom}
step={0.05}
value={zoom}
onChange={(e) => setZoom(Number(e.target.value))}
/>
</label>
<div className={styles.cropActions}>
<button type="button" className={styles.cancelBtn} onClick={cancelCrop}>
{t('products.form.cancel')}
</button>
<button
type="button"
className={styles.applyBtn}
onClick={() => void applyCrop()}
disabled={!croppedArea}
>
{t('products.form.applyCrop')}
</button>
</div>
</div>
</div>
)}
{value && !imageSrc && (
<label className={styles.changeBtn}>
{resolvedChangeLabel}
<input type="file" accept={accept} onChange={handleFile} hidden />
</label>
)}
</div>
)
}