UNPKG

1.85 kBPlain TextView Raw
1import { PermissionExpiration, PermissionMap, PermissionStatus } from './Permissions.types';
2
3export function coalesceStatuses(permissions: PermissionMap): PermissionStatus {
4 const statuses = Object.keys(permissions).map(type => permissions[type].status);
5 statuses.sort((status1, status2) => _getStatusWeight(status1) - _getStatusWeight(status2));
6 // We choose the "heaviest" status with the most implications
7 return statuses[statuses.length - 1];
8}
9
10function _getStatusWeight(status: PermissionStatus): number {
11 // In terms of weight, we treat UNDETERMINED > DENIED > GRANTED since UNDETERMINED requires the
12 // most amount of further handling (prompting for permission and then checking that permission)
13 // and GRANTED requires the least
14 switch (status) {
15 case PermissionStatus.GRANTED:
16 return 0;
17 case PermissionStatus.DENIED:
18 return 1;
19 case PermissionStatus.UNDETERMINED:
20 return 2;
21 default:
22 return 100;
23 }
24}
25
26export function coalesceExpirations(permissions: PermissionMap): PermissionExpiration {
27 const maxExpiration = 9007199254740991; // Number.MAX_SAFE_INTEGER
28 const expirations = Object.keys(permissions).map(type => permissions[type].expires);
29 expirations.sort(
30 (e1, e2) =>
31 (e1 == null || e1 === 'never' ? maxExpiration : e1) -
32 (e2 == null || e2 === 'never' ? maxExpiration : e2)
33 );
34 // We choose the earliest expiration
35 return expirations[0];
36}
37
38export function coalesceCanAskAgain(permissions: PermissionMap): boolean {
39 return Object.keys(permissions).reduce<boolean>(
40 (canAskAgain, type) => canAskAgain && permissions[type].canAskAgain,
41 true
42 );
43}
44
45export function coalesceGranted(permissions: PermissionMap): boolean {
46 return Object.keys(permissions).reduce<boolean>(
47 (granted, type) => granted && permissions[type].granted,
48 true
49 );
50}