Bluesky app fork with some witchin' additions 馃挮
at 5ee667f307bc459ba53cdaabdad00a0ea1ee6846 68 lines 2.0 kB view raw
1import {useCallback} from 'react' 2import * as MediaLibrary from 'expo-media-library' 3import {msg} from '@lingui/core/macro' 4import {useLingui} from '@lingui/react' 5 6import * as Toast from '#/components/Toast' 7import {IS_NATIVE} from '#/env' 8import {saveImageToMediaLibrary} from './manip' 9 10/** 11 * Same as `saveImageToMediaLibrary`, but also handles permissions and toasts 12 */ 13export function useSaveImageToMediaLibrary() { 14 const {_} = useLingui() 15 const [permissionResponse, requestPermission, getPermission] = 16 MediaLibrary.usePermissions({ 17 granularPermissions: ['photo'], 18 }) 19 return useCallback( 20 async (uri: string) => { 21 if (!IS_NATIVE) { 22 throw new Error('useSaveImageToMediaLibrary is native only') 23 } 24 25 async function save() { 26 try { 27 await saveImageToMediaLibrary({uri}) 28 29 Toast.show(_(msg`Image saved`)) 30 } catch (e: any) { 31 Toast.show(_(msg`Failed to save image: ${String(e)}`), { 32 type: 'error', 33 }) 34 } 35 } 36 37 const permission = permissionResponse ?? (await getPermission()) 38 39 if (permission.granted) { 40 await save() 41 } else { 42 if (permission.canAskAgain) { 43 // request again once 44 const askAgain = await requestPermission() 45 if (askAgain.granted) { 46 await save() 47 } else { 48 // since we've been explicitly denied, show a toast. 49 Toast.show( 50 _( 51 msg`Images cannot be saved unless permission is granted to access your photo library.`, 52 ), 53 {type: 'error'}, 54 ) 55 } 56 } else { 57 Toast.show( 58 _( 59 msg`Permission to access your photo library was denied. Please enable it in your system settings.`, 60 ), 61 {type: 'error'}, 62 ) 63 } 64 } 65 }, 66 [permissionResponse, requestPermission, getPermission, _], 67 ) 68}