Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import {useCallback} from 'react'import * as MediaLibrary from 'expo-media-library/legacy'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'
import * as Toast from '#/components/Toast'import {IS_NATIVE} from '#/env'import {saveImageToMediaLibrary} from './manip'
/** * Same as `saveImageToMediaLibrary`, but also handles permissions and toasts */export function useSaveImageToMediaLibrary() { const {_} = useLingui() const [, requestPermission, getPermission] = MediaLibrary.usePermissions({ granularPermissions: ['photo'], /* * Don't query the permission on mount. Every image embed in the feed * mounts this hook, so the eager query cost a native call and a * re-render per post. The save handler fetches it on demand instead. */ get: false, }) return useCallback( async (uri: string) => { if (!IS_NATIVE) { throw new Error('useSaveImageToMediaLibrary is native only') }
async function save() { try { await saveImageToMediaLibrary({uri})
Toast.show(_(msg`Image saved`)) } catch (e: any) { Toast.show(_(msg`Failed to save image: ${String(e)}`), { type: 'error', }) } }
/* * Always ask the OS instead of reusing the hook's cached response. The * lightbox keeps this hook mounted for the whole session, so a cached * denial would outlive the user granting access in system settings. */ const permission = await getPermission()
if (permission.granted) { await save() } else { if (permission.canAskAgain) { // request again once const askAgain = await requestPermission() if (askAgain.granted) { await save() } else { // since we've been explicitly denied, show a toast. Toast.show( _( msg`Images cannot be saved unless permission is granted to access your photo library.`, ), {type: 'error'}, ) } } else { Toast.show( _( msg`Permission to access your photo library was denied. Please enable it in your system settings.`, ), {type: 'error'}, ) } } }, [requestPermission, getPermission, _], )}