/** This file is published under MIT License */ import { useEffect , useState } from 'react' ; import { hasIn } from 'lodash-unified' ; import { Flags } from '../../../shared' ; const q = [ 'query' , 'request' , 'revoke' ] as const ; function checkPermissionApiUsability ( type ? ) { const r = { } ; for ( const v of q ) { r [ v ] = hasIn ( navigator , `permissions.${ v }` ) ; } if ( type ) { return r [ type ] ; } return r as Required < typeof r > ; } export type Permissions = PermissionName | 'camera' | 'clipboard-write' ; export function useQueryNavigatorPermission ( needRequest , name ) { const [ permission , updatePermission ] = useState < PermissionState > ( 'prompt' ) ; useEffect ( ( ) => { if ( ! needRequest || permission !== 'prompt' || Flags . has_no_WebRTC ) return ; let permissionStatus ; const handleChange = function ( this ) { updatePermission ( this . state ) ; } ; if ( checkPermissionApiUsability ( 'query' ) ) { navigator . permissions . query ( { name } ) . then ( ( p ) => { permissionStatus = p ; permissionStatus . addEventListener ( 'change' , handleChange ) ; updatePermission ( permissionStatus . state ) ; } ) . catch ( ( ) => { updatePermission ( 'granted' ) ; } ) ; } else if ( checkPermissionApiUsability ( 'request' ) ) { navigator . permissions . request ( { name } ) . then ( ( p ) => { updatePermission ( p . state ) ; } ) . catch ( ( ) => { updatePermission ( 'granted' ) ; } ) ; } else { updatePermission ( 'granted' ) ; } return ( ) => permissionStatus ?. removeEventListener ( 'change' , handleChange ) ; } , [ name , needRequest , permission ] ) ; return permission ; }