import { useEffect , useState } from 'react' ; import { isPlatform } from '@ionic/react' ; import { CameraPhoto , CameraResultType , CameraSource , Capacitor , FilesystemDirectory } from "@capacitor/core" ; import { useCamera } from '@ionic/react-hooks/camera' ; import { useFilesystem , base64FromPath } from '@ionic/react-hooks/filesystem' ; import { useStorage } from '@ionic/react-hooks/storage' ; import { defineCustomElements } from '@ionic/pwa-elements/loader' ; import { Photo } from "../interface/Photo" ; defineCustomElements ( window ) ; const PHOTO_STORAGE = "photos" ; export function usePhotoGallery ( ) { const [ photos , setPhotos ] = useState < Photo [ ] > ( [ ] ) ; const { getPhoto } = useCamera ( ) ; const { getUri , readFile , writeFile } = useFilesystem ( ) ; const { get , set } = useStorage ( ) ; const takePhoto = async ( ) => { const cameraPhoto = await getPhoto ( { resultType : CameraResultType . Uri , source : CameraSource . Camera , quality : 100 } ) ; const fileName = new Date ( ) . getTime ( ) + '.jpeg' ; const savedFileImage = await savePicture ( cameraPhoto , fileName ) ; const newPhotos = [ savedFileImage , ... photos ] ; setPhotos ( newPhotos ) ; set ( PHOTO_STORAGE , isPlatform ( 'hybrid' ) ? JSON . stringify ( newPhotos ) : JSON . stringify ( newPhotos . map ( p => { const photoCopy = { ... p } ; delete photoCopy . base64 ; return photoCopy ; } ) ) ) ; } ; const savePicture = async ( photo , fileName ) => { let base64Data ; if ( isPlatform ( 'hybrid' ) ) { const file = await readFile ( { path : photo . path ! } ) ; base64Data = file . data ; } else { base64Data = await base64FromPath ( photo . webPath ! ) ; } await writeFile ( { path : fileName , data : base64Data , directory : FilesystemDirectory . Data } ) ; return getPhotoFile ( photo , fileName ) ; } ; const getPhotoFile = async ( cameraPhoto , fileName ) : Promise < Photo > => { if ( isPlatform ( 'hybrid' ) ) { const fileUri = await getUri ( { directory : FilesystemDirectory . Data , path : fileName } ) ; return { filepath : fileUri . uri , webviewPath : Capacitor . convertFileSrc ( fileUri . uri ) , } ; } else { return { filepath : fileName , webviewPath : cameraPhoto . webPath } ; } } ; return { takePhoto , photos } ; }