import * as React from "react"; import { useState } from "react"; import ReactCrop, { Crop, centerCrop, makeAspectCrop } from 'react-image-crop'; import { useAssetApi } from '../AppShell/hooks/useAssets'; import DialogModal from "../Templates/DialogModal"; export const AvatarWidget = ({avatar, setAvatar}:{avatar:string, setAvatar : React.Dispatch>}) => { const [crop, setCrop] = useState(); const [image, setImage] = useState(""); const [cropModalOpen, setCropModalOpen] = useState(false); const [cropping, setCropping] = useState(false); const assetsApi = useAssetApi(); const imgRef = React.useRef(null) const onImageChange = (event) => { if (event.target.files && event.target.files[0]) { setImage(URL.createObjectURL(event.target.files[0])); } setCropModalOpen(true); } function onImageLoad(e: React.SyntheticEvent) { const { width, height } = e.currentTarget setCrop(centerAspectCrop(width, height, 1)) } // This is to demonstate how to make and center a % aspect crop // which is a bit trickier so we use some helper functions. function centerAspectCrop( mediaWidth: number, mediaHeight: number, aspect: number, ) { return centerCrop( makeAspectCrop( { unit: 'px', width: mediaWidth / 2, }, aspect, mediaWidth, mediaHeight, ), mediaWidth, mediaHeight, ) } async function renderCrop() { // get the image element const image = imgRef.current; if (crop && image) { const scaleX = image.naturalWidth / image.width const scaleY = image.naturalHeight / image.height // create a canvas element to draw the cropped image const canvas = new OffscreenCanvas( crop.width * scaleX, crop.height * scaleY, ) const ctx = canvas.getContext("2d"); const pixelRatio = window.devicePixelRatio; canvas.width = crop.width * pixelRatio * scaleX; canvas.height = crop.height * pixelRatio * scaleY; if (ctx) { ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); ctx.drawImage( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width * scaleX, crop.height * scaleY ); } const blob = await canvas.convertToBlob(); await resizeBlob(blob); setCropping(false); setImage(""); } } async function resizeBlob(blob) { var img = new Image(); img.src = URL.createObjectURL(blob); await img.decode(); const canvas = new OffscreenCanvas( 400, 400 ) var ctx = canvas.getContext("2d"); ctx?.drawImage(img, 0, 0, 400, 400); const resizedBlob = await canvas.convertToBlob() const asset = await assetsApi.upload(resizedBlob, "test"); setAvatar(asset.id) } return ( <> {!cropping ? :
} { setCropModalOpen(false); setImage(""); }} closeOnClickOutside={false}> setCrop(c)} aspect={1} > ) }