Files
hats-app/app/(dashboard)/profile/components/ChangeAvatar.tsx
T
Ichsan Kurniawan 5cbded392a Add server API helper, logging & misc updates
Introduce a reusable serverApiCall helper and file-based logger (lib/server-api.ts, lib/logger.ts) to centralize backend requests, attach session auth, and capture request/response/error logs. Update server actions to use the new helper (updateProfileAction, changeAvatarAction) and ensure profile revalidation. Add client-side avatar upload size limit (5MB) and normalize avatar base64 payload. Add new OpenGraph/Twitter images, bump app version to v1.1.1, and add a v1.1.1 entry in release notes. Update default API/IMG env URLs and metadataBase fallback, fix minor release-notes link capitalization, and adjust a debug console.log in admin user page.
2026-02-09 14:48:03 +07:00

254 lines
13 KiB
TypeScript

'use client'
import { ChangeEvent, FC, Fragment, lazy, Suspense, useCallback, useState } from 'react';
import Image from 'next/image';
import Cropper from 'react-easy-crop';
import { Range } from 'react-range';
import { getOrientation } from 'get-orientation/browser';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Icons } from '@/components/Icons';
import { getCroppedImg, getRotatedImage } from '@/lib/canvasUtils';
import { blobToBase64, randomIntFromInterval, readFile } from '@/lib/helper';
import useAxiosAuth from '@/lib/axios/useAxiosAuth';
import PageLoading from '@/components/loader/PageLoading';
import { toast } from 'sonner';
import FallbackAvatar from '@/components/loader/FallbackAvatar';
const ViewAvatar = lazy(() => import('@/components/ViewAvatar'));
type Props = {
nik: string
existAvatar?: string
};
const ORIENTATION_TO_ANGLE: any = {
'3': 180,
'6': 90,
'8': -90,
}
const ChangeAvatar: FC<Props> = ({ nik, existAvatar }) => {
const [isFullLoading, setIsFullLoading] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [showFormDialog, setShowFormDialog] = useState(false)
const [imageSrc, setImageSrc] = useState<any>(null)
const [crop, setCrop] = useState({ x: 0, y: 0 })
const [rotation, setRotation] = useState(0)
const [zoom, setZoom] = useState(1)
const [croppedAreaPixels, setCroppedAreaPixels] = useState(null)
const [croppedImage, setCroppedImage] = useState<any>(null)
const [values, setValues] = useState([1])
const [values2, setValues2] = useState([0])
const router = useRouter()
const axios = useAxiosAuth()
const onCropComplete = useCallback((croppedArea: any, croppedAreaPixels: any) => {
setCroppedAreaPixels(croppedAreaPixels)
}, [])
const showCroppedImage = useCallback(async () => {
try {
const croppedImage = await getCroppedImg(
imageSrc,
croppedAreaPixels,
rotation
)
console.log('donee', croppedImage)
setCroppedImage(croppedImage)
} catch (e) {
console.error(e)
}
}, [imageSrc, croppedAreaPixels, rotation])
// eslint-disable-next-line
const onClose = useCallback(() => {
setCroppedImage(null)
}, [])
const onFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const file = e.target.files[0]
if (file.name.includes('.HEIC') || file.name.includes('.heic')) {
setIsFullLoading(true)
const heic2any = (await import('heic2any')).default;
heic2any({
blob: file,
quality: file.size > 5000000 ? 0.05 : file.size > 4000000 ? 0.09 : file.size > 3000000 ? 0.1 : file.size > 2000000 ? 0.2 : 0.4,
toType: 'image/jpeg'
}).then(async (blob: any) => {
let imageDataUrl = await blobToBase64(blob)
const orientation = await getOrientation(file)
const rotation = ORIENTATION_TO_ANGLE[orientation]
if (rotation) {
imageDataUrl = await getRotatedImage(imageDataUrl, rotation)
}
setIsFullLoading(false)
setImageSrc(imageDataUrl)
}).catch((err) => {
toast.error('Failed upload photo', { description: err.message })
setIsFullLoading(false)
})
} else {
if (file.size > 5000000) {
toast.error('Failed upload photo', { description: 'File size too large, maximum 5MB' })
return
}
let imageDataUrl = await readFile(file)
// apply rotation if needed
const orientation = await getOrientation(file)
const rotation = ORIENTATION_TO_ANGLE[orientation]
if (rotation) {
imageDataUrl = await getRotatedImage(imageDataUrl, rotation)
}
setImageSrc(imageDataUrl)
}
}
}
const handleSavePhoto = async () => {
try {
setIsLoading(true)
await axios.post('/user/change-avatar', { nik, avatar: croppedImage?.base64 ? croppedImage.base64?.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '') : '' })
toast.success('Avatar changed successfully.')
handleCloseDialog()
router.refresh()
} catch (error: any) {
toast.error(`Failed to change avatar`, {
description: `(${error?.response?.data?.code || error?.response?.status || '-'}) ${error?.response?.data?.message || error?.response?.statusText || error?.message}`
})
setIsLoading(false)
}
}
const handleCloseDialog = () => {
setIsLoading(false)
setShowFormDialog(false)
setImageSrc(null)
setCrop({ x: 0, y: 0 })
setRotation(0)
setZoom(1)
setCroppedAreaPixels(null)
setCroppedImage(null)
setValues([1])
setValues2([0])
}
return (
<>
<div className='flex flex-col sm:flex-row items-center sm:space-x-6 xl:space-x-8 space-y-5 sm:space-y-0 pt-6'>
<Suspense fallback={<FallbackAvatar className='w-[120px] h-[120px] md:w-40 md:h-40' />}>
<ViewAvatar avatar={existAvatar!} className='w-[120px] h-[120px] md:w-40 md:h-40 duration-300' />
</Suspense>
<div className='flex flex-col items-center sm:items-start space-y-3'>
<p className='w-full xl:w-5/12 text-center sm:text-left text-sm'>Personalize your account with photos. Your profile photo will appear on apps and devices that use your Supper Apps account.</p>
<Dialog open={showFormDialog} onOpenChange={setShowFormDialog}>
<DialogTrigger asChild>
<Button variant='outline' className='w-full sm:w-max'>Change Photo</Button>
</DialogTrigger>
<DialogContent className=" overflow-y-auto max-h-[95vh]">
<DialogHeader>
<DialogTitle className="dark:text-white">Change profile photo</DialogTitle>
<DialogDescription>
Personalize your account with photos
</DialogDescription>
</DialogHeader>
{imageSrc ?
<Fragment>
<div className='w-full h-64 relative'>
<Cropper image={imageSrc} crop={crop} rotation={rotation} zoom={zoom} aspect={1 / 1}
onCropChange={setCrop}
onRotationChange={setRotation}
onCropComplete={onCropComplete}
onZoomChange={setZoom}
/>
</div>
<div className=''>
<div className=''>
<label>Zoom {zoom?.toFixed(1)}x</label>
<Range step={0.1} min={1} max={3} values={values} onChange={(values) => { setValues(values); setZoom(values[0]) }}
renderTrack={({ props, children }) => (
<div {...props} key={randomIntFromInterval(0, 100)} className="w-full h-3 pr-2 my-4 bg-gray-200 rounded-md" >
{children}
</div>
)}
renderThumb={({ props }) => (
<div {...props} key={randomIntFromInterval(100, 200)}
className="w-5 h-5 transform bg-his rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-his"
/>
)}
/>
</div>
<div>
<label>Rotation {rotation}°</label>
<Range step={1} min={0} max={360} values={values2} onChange={(values) => { setValues2(values); setRotation(values[0]) }}
renderTrack={({ props, children }) => (
<div {...props} key={randomIntFromInterval(200, 300)} className="w-full h-3 pr-2 my-4 bg-gray-200 rounded-md" >
{children}
</div>
)}
renderThumb={({ props }) => (
<div {...props} key={randomIntFromInterval(300, 400)}
className="w-5 h-5 transform bg-his rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-his"
/>
)}
/>
</div>
<div className='flex items-center justify-center mt-5'>
<Button onClick={showCroppedImage} variant='secondary' >
<i className="ti ti-eye text-lg mr-2"></i>
Preview
</Button>
</div>
{croppedImage &&
<div className='flex items-center justify-center flex-col mt-5'>
<Image alt='cropped-image' height={0} width={0} quality={100} src={croppedImage.base64} className='w-10/12 mx-auto rounded-xl border-2 border-slate-400 dark:border-slate-500' />
</div>
}
</div>
</Fragment>
:
<div className='flex flex-col justify-center items-center'>
{existAvatar ?
<Image src={`${process.env.BASE_URL_IMG}/${existAvatar}`} alt="avatar" width={120} height={120} className="rounded-full border dark:border-zinc-800 object-cover" />
:
<Image alt='avatar' height={0} width={0} sizes='50vw' quality={75} src='/assets/no-avatar.jpg' className='w-[120px] h-[120px] rounded-full border dark:border-zinc-800 object-cover' />
}
<label htmlFor='foto' className='text-his mt-4 font-medium cursor-pointer hover:underline hover:text-his/50 duration-300'>Change profile photo</label>
<input id='foto' type="file" onChange={onFileChange} accept="image/*,.heic" className='hidden' />
</div>
}
<DialogFooter>
<Button variant="outline" type="button" onClick={handleCloseDialog} disabled={isLoading} >
Cancel
</Button>
{croppedImage &&
<Button type="submit" disabled={isLoading} onClick={handleSavePhoto}>
{isLoading && (
<Icons.spinner className="mr-1 h-4 w-4 animate-spin" />
)}
Save
</Button>
}
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
{isFullLoading &&
<PageLoading className='bg-opacity-40 dark:bg-opacity-20 z-999' title='Uploading photo..' />
}
</>
);
}
export default ChangeAvatar;