Skip to content

[URH-62] usePermission 신규 #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/hooks/usePermission.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// const useHooks = ({}: UseHooksProps): UseHooksReturns ⇒ {}

import { useEffect, useState } from 'react';
import { validators } from '../utils';

interface UsePermissionProps {
permission: Permission; // 정의된 타입과 문자열 타입 모두 허용
}

interface UsePermissionReturns {
status: PermissionState;
}

type PermissionState = 'granted' | 'prompt' | 'denied' | 'notSupported';

/**
* 사용자의 권한 상태를 확인하고 추적하는 커스텀 훅.
*
* @param {object} props permission {Permission}: 확인하려는 권한의 이름.
*
* @returns {object}
* - `status`: 현재 권한의 상태. ‘granted’, ‘prompt’, ‘denied’, ‘notSupported’
*
* @description
* - 이 훅은 주어진 권한에 대한 상태를 확인하고, 권한 상태가 변경될 때마다 업데이트합니다.
*/
const usePermission = ({
permission,
}: UsePermissionProps): UsePermissionReturns => {
const [status, setStatus] = useState<PermissionState>('prompt');

useEffect(() => {
if (!validators.isClient() || !navigator.permissions) {
console.warn('The Permissions API is not supported.');
return;
}

navigator.permissions
.query({
name: permission as PermissionName,
})
.then((permissionStatus) => {
setStatus(permissionStatus.state);

permissionStatus.onchange = () => {
setStatus(permissionStatus.state);
};
})
.catch(() => {
setStatus('notSupported');
});
}, [permission]);

return { status };
};

// eslint-disable-next-line @typescript-eslint/ban-types
type Permission = PredefinedPermissionName | (string & {});

// Firefox, Chromium, WebKit
type PredefinedPermissionName =
| 'accessibility-events'
| 'accelerometer'
| 'ambient-light-sensor'
| 'background-fetch'
| 'background-sync'
| 'bluetooth'
| 'camera'
| 'captured-surface-control'
| 'clipboard-read'
| 'clipboard-write'
| 'display-capture'
| 'fullscreen'
| 'geolocation'
| 'gyroscope'
| 'idle-detection'
| 'keyboard-lock'
| 'local-fonts'
| 'magnetometer'
| 'microphone'
| 'midi'
| 'nfc'
| 'notifications'
| 'payment-handler'
| 'periodic-background-sync'
| 'persistent-storage'
| 'pointer-lock'
| 'push'
| 'screen-wake-lock'
| 'speaker-selection'
| 'storage-access'
| 'system-wake-lock'
| 'top-level-storage-access'
| 'window-management';

export default usePermission;
Loading