[English README](./README.md)

<!-- This file is generated by `pnpm readme:package`. Edit packages/react-webcam/pkg-docs/README.en.md and packages/react-webcam/pkg-docs/README.ko.md instead. -->

# @cp949/react-webcam

React 18/19를 지원하는 웹캠 컴포넌트 라이브러리입니다.

- Controlled / Uncontrolled 상태 소유권을 지원합니다.
- `WebcamHandle` ref로 snapshot, 옵션 변경, playback pause/resume을 제어할 수 있습니다.
- `onStateChange`로 권한 거부, autoplay 차단, 장치 unavailable 같은 런타임 상태를 다룰 수 있습니다.

자세한 저장소 운영 방법과 개발 명령은 루트 README에서 다룹니다.

## 설치

```bash
npm install @cp949/react-webcam
```

**React 18과 19를 지원합니다.** React 17 이하는 지원하지 않습니다.

```bash
npm install react@^18 react-dom@^18
# 또는
npm install react@^19 react-dom@^19
```

## 브라우저 호환성 목표

pack된 라이브러리 산출물과 소비자 번들은 Chrome Desktop 75를 호환성 목표로 삼는다.
Chrome 75에서 직접 실행한 기록을 뜻하지 않는다. 카메라 접근에는 HTTPS 또는
localhost, 사용자 권한, 사용 가능한 장치가 필요하다. 저장소의 Next/MUI 데모는
별도 소비자이며 이 호환성 목표에 포함하지 않는다.

Playwright의 CDP 제약으로 Chrome 75/76 자동화가 불가능하므로 자동화 검증의
실제 하한은 Chrome 83이다. 이 검증은 CI가 아닌 릴리스 전 로컬 수동 스크립트로 실행한다.

## 기본 사용법

```tsx
import { Webcam } from "@cp949/react-webcam";

export function CameraView() {
  return (
    <div style={{ width: 640, height: "auto" }}>
      <Webcam
        webcamOptions={{ aspectRatio: 16 / 9 }}
        controls={{ flip: true, cameraDirection: true }}
      />
    </div>
  );
}
```

`fitMode`로 부모 컨테이너에 맞추는 경우:

```tsx
<div style={{ width: 640, height: 480 }}>
  <Webcam fitMode='cover' webcamOptions={{ audioEnabled: true }} />
</div>
```

## Props

`Webcam`은 아래 표의 props 외에 `ref`로 `WebcamHandle`도 받을 수 있습니다(자세한
내용은 뒤의 ref handle 절 참고).

| Prop                    | 타입                                                                                                  | 기본값        | 설명                                                                                                                                                                                                     |
| ----------------------- | ----------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `style`                 | `React.CSSProperties`                                                                                 | —             | 루트 엘리먼트에 적용할 인라인 스타일입니다.                                                                                                                                                              |
| `className`             | `string`                                                                                              | —             | 루트 엘리먼트에 적용할 클래스명입니다.                                                                                                                                                                   |
| `children`              | `React.ReactNode`                                                                                     | —             | 루트 엘리먼트 내부, 비디오 위에 렌더링됩니다.                                                                                                                                                            |
| `disabled`              | `boolean`                                                                                             | `false`       | 카메라 요청 없이 컴포넌트를 비활성 상태로 유지합니다(뒤의 비활성 상태 절 참고).                                                                                                                          |
| `disabledFallback`      | `React.ReactNode`                                                                                     | —             | `disabled`일 때 기본 placeholder 대신 렌더링할 커스텀 UI입니다.                                                                                                                                          |
| `autoRecover`           | `boolean`                                                                                             | `false`       | `track-ended` 오류 뒤 탭이 다시 보일 때 스트림을 한 번 다시 요청합니다(뒤의 커스텀 오류 fallback 절 참고).                                                                                               |
| `errorFallback`         | `React.ReactNode \| ((detail: WebcamErrorDetail, helpers: { retry: () => void }) => React.ReactNode)` | —             | `denied` / `unavailable` / `unsupported` / `insecure` / `error` 상태의 커스텀 UI입니다. `playback-error`는 포함하지 않습니다.                                                                            |
| `onStateChange`         | `(state: WebcamDetail) => void`                                                                       | —             | `WebcamDetail`이 바뀔 때마다 호출됩니다(뒤의 상태 변화 감지 절 참고).                                                                                                                                    |
| `onFrameReadyChange`    | `(ready: boolean) => void`                                                                            | —             | 디코딩된 프레임을 쓸 수 있는지가 바뀔 때 호출됩니다(뒤의 상태 변화 감지 절 참고).                                                                                                                        |
| `fitMode`               | `"unset" \| "fill" \| "cover" \| "contain"`                                                           | `"unset"`     | `webcamOptions.aspectRatio`가 없을 때 비디오를 박스에 맞추는 방식입니다.                                                                                                                                 |
| `flipped`               | `boolean`                                                                                             | —             | Controlled 모드의 좌우 반전 값입니다. `onFlippedChange`와 함께 사용하여 부모가 상태를 갱신합니다(뒤의 `flipped` 절 참고).                                                                                |
| `onFlippedChange`       | `(value: boolean) => void`                                                                            | —             | `flipped`와 함께 사용합니다. 반전 변경이 요청될 때 호출됩니다.                                                                                                                                           |
| `defaultFlipped`        | `boolean`                                                                                             | `false`       | Uncontrolled 모드의 초기 반전 상태입니다. 마운트 시 한 번만 적용됩니다.                                                                                                                                  |
| `webcamOptions`         | `WebcamOptions`                                                                                       | —             | Controlled 모드의 카메라 옵션(`facingMode`, `aspectRatio`, `audioEnabled`, `deviceId`, `size` 등)입니다. `onWebcamOptionsChange`와 함께 사용하여 부모가 상태를 갱신합니다(뒤의 `webcamOptions` 절 참고). |
| `onWebcamOptionsChange` | `(options: WebcamOptions) => void`                                                                    | —             | `webcamOptions`와 함께 사용합니다. 옵션 변경이 요청될 때 호출됩니다.                                                                                                                                     |
| `defaultWebcamOptions`  | `WebcamOptions`                                                                                       | —             | Uncontrolled 모드의 초기 카메라 옵션입니다. 마운트 시 한 번만 적용됩니다.                                                                                                                                |
| `controls`              | `WebcamControls`                                                                                      | `{}`          | 표시할 내장 컨트롤 버튼을 고릅니다: `flip`, `cameraDirection`, `aspectRatio`, `snapshot`. 각 항목의 기본값은 `false`입니다.                                                                              |
| `onSnapshot`            | `(canvas: HTMLCanvasElement) => void`                                                                 | —             | 내장 스냅샷 버튼을 누를 때 캡처한 프레임(원본 해상도)을 받습니다. `controls.snapshot`이 필요합니다.                                                                                                      |
| `debug`                 | `WebcamDebug`                                                                                         | `{}`          | 표시할 디버그 오버레이를 고릅니다: `videoSize`(비디오 요소 크기), `constraints`(현재 적용된 `MediaStreamConstraints`). 각 항목의 기본값은 `false`입니다.                                                 |
| `icons`                 | `WebcamIcons`                                                                                         | 내장 아이콘   | 내장 버튼의 아이콘을 교체합니다: `flip`, `cameraDirection`, `aspectRatio`, `snapshot` (아래 "아이콘 교체" 참고).                                                                                         |
| `labels`                | `WebcamLabels`                                                                                        | 한국어 기본값 | 내장 버튼 라벨을 부분적으로 덮어씁니다(뒤의 라벨과 로컬라이제이션 절 참고).                                                                                                                              |

내장 스냅샷 버튼은 디코딩된 프레임이 준비된 뒤에 표시됩니다. `onFrameReadyChange`와 같은
기준입니다. 비디오 트랙이 `muted`인 동안에는 사라졌다가 `unmute` 뒤에 돌아옵니다.
다른 내장 버튼(`flip`, `cameraDirection`, `aspectRatio`)은 영상 크기가 확인되면 바로 표시되고
트랙이 `muted`인 동안에도 유지됩니다.

### 3.0.0 마이그레이션

`visible*` prop 6개를 객체 2개로 바꿨습니다. 사용처를 모두 고치세요.

| 2.x                            | 3.0                                    |
| ------------------------------ | -------------------------------------- |
| `visibleFlipButton`            | `controls={{ flip: true }}`            |
| `visibleCameraDirectionButton` | `controls={{ cameraDirection: true }}` |
| `visibleAspectRatioButton`     | `controls={{ aspectRatio: true }}`     |
| `visibleSnapshotButton`        | `controls={{ snapshot: true }}`        |
| `visibleVideoSizeDebug`        | `debug={{ videoSize: true }}`          |
| `visibleConstraintsDebug`      | `debug={{ constraints: true }}`        |

- `onSnapshot`은 최상위 prop으로 유지합니다. `controls.snapshot`이 필요합니다.
- 타입 `WebcamControls`, `WebcamDebug`를 export합니다.

## 비활성 상태 - `disabled`

웹캠을 마운트한 채로 유지하되, 아직 카메라 접근을 요청하면 안 되는 경우
`disabled`를 사용할 수 있습니다.

`disabled={true}`이면:

- `getUserMedia()`를 호출하지 않습니다.
- 컴포넌트는 기존 `idle` 흐름에 머뭅니다.
- 기본으로 텍스트 없는 soft gradient + 카메라 아이콘 placeholder를 렌더링합니다.

다시 `disabled={false}`가 되면 웹캠은 일반적인 요청 흐름으로 복귀합니다.

### 기본 placeholder

```tsx
<Webcam disabled />
```

### 커스텀 비활성 fallback

`disabledFallback`을 전달하면 기본 placeholder를 완전히 대체할 수 있습니다.

```tsx
<Webcam
  disabled
  disabledFallback={
    <div
      style={{
        position: "absolute",
        inset: 0,
        display: "grid",
        placeItems: "center",
        background: "#111",
        color: "#fff",
      }}
    >
      Camera is disabled
    </div>
  }
/>
```

### 커스텀 에러 fallback

`errorFallback`을 전달하면 권한 거부, 카메라 없음, 브라우저 미지원 같은 오류
상태에서 커스텀 UI를 렌더링할 수 있습니다. 함수로 전달하면 현재
`WebcamDetail`을 받아 오류 원인별 메시지를 분기할 수 있습니다. 두 번째 인자의
`retry()`는 같은 옵션으로 카메라를 다시 요청합니다.

```tsx
<Webcam
  errorFallback={(detail, { retry }) => (
    <div>
      {detail.errorCode === "device-not-found"
        ? "연결된 카메라가 없습니다."
        : "카메라를 시작할 수 없습니다."}
      <button onClick={retry}>다시 시도</button>
    </div>
  )}
/>
```

권한을 거부한 뒤에는 브라우저가 권한 프롬프트를 다시 띄우지 않을 수 있습니다.
이 경우 사용자가 브라우저 설정에서 허용하기 전까지 `retry()`는 같은 오류로 실패합니다.

`playback-error`는 스트림이 살아 있는 재생 오류이므로 `errorFallback` 대상이 아닙니다.

일부 모바일 브라우저는 탭이 백그라운드에 있는 동안 카메라 트랙을 종료해
`track-ended` 오류가 됩니다. `autoRecover`를 켜면 탭이 다시 보일 때 스트림을
다시 요청합니다. 탭이 보일 때마다 최대 한 번만 요청하며, 권한 거부 같은 다른
오류는 무시합니다.

```tsx
<Webcam autoRecover />
```

### 비활성 상태 토글

```tsx
import { useState } from "react";
import { Webcam } from "@cp949/react-webcam";

export function DisabledExample() {
  const [disabled, setDisabled] = useState(true);

  return (
    <>
      <button type='button' onClick={() => setDisabled((prev) => !prev)}>
        웹캠 토글
      </button>

      <div style={{ width: 640, height: "auto" }}>
        <Webcam disabled={disabled} />
      </div>
    </>
  );
}
```

## 기존 video 요소 연결

`useWebcam`은 앱이 소유한 video 요소의 카메라 요청과 재생을 관리한다.
UI를 만들지 않으며 기존 `transform`, `objectFit` 스타일을 보존한다.
video의 `muted`, `playsInline`은 호출자가 설정한다.
요소가 앱 소유이므로 훅은 두 속성을 바꾸지 않는다.

```tsx
import { useState } from "react";
import { useWebcam } from "@cp949/react-webcam";

export function CameraSource() {
  const [videoElement, setVideoElement] = useState<HTMLVideoElement | null>(null);
  const camera = useWebcam({
    videoElement,
    webcamOptions: { facingMode: "user", size: { width: 1280 } },
  });

  return (
    <>
      <video ref={setVideoElement} muted playsInline />
      <output>{camera.isFrameReady ? "프레임 준비 완료" : camera.detail.phase}</output>
      <button onClick={camera.retry}>카메라 다시 시도</button>
      <button onClick={camera.resumePlayback}>재생 다시 시도</button>
    </>
  );
}
```

- `videoElement`에는 기존 `HTMLVideoElement`, `null`, `undefined`를 넘긴다.
  요소 연결·교체가 렌더링을 일으키도록 state나 callback ref를 사용한다.
  카메라 크기를 명시하면 `display: none`인 video도 사용할 수 있다.
- `webcamOptions`는 `Webcam`과 같은 옵션이다. `disabled`는 요청을 막고 기존
  스트림을 종료한다. 요소가 없을 때도 요청하지 않는다.
- `detail.phase === "live"`는 스트림을 얻었다는 뜻이다. `play()` 성공이나
  프레임 도착을 보장하지 않는다. 얼굴 인식을 시작할 때는 `isFrameReady`를 확인한다.
  현재 스트림에 연결된 video의 `readyState >= 2` (`HAVE_CURRENT_DATA`), 양수인
  영상 너비·높이, `live` 상태, `muted`가 아닌 비디오 트랙을 모두 요구한다.
  다른 앱이 카메라를 가져가거나 페이지가 백그라운드로 가면 `ended` 없이 트랙이
  `muted`가 된다. 이때 `phase`는 `live`로 남고 `isFrameReady`는 트랙이 `unmute`될
  때까지 `false`가 된다. 일시 정지한 영상에도 사용 가능한 프레임이 남을 수 있으므로
  이 값이 프레임의 계속된 갱신을 뜻하지는 않는다.
- `retry()`는 기존 스트림을 종료하고 같은 옵션으로 새로 요청한다. 권한 요청 실패나
  `track-ended` 뒤에도 사용할 수 있다. 브라우저 권한 제한을 우회하지 않으며
  `disabled` 중에는 요청하지 않는다.
- `pausePlayback()`은 영상 재생만 멈춘다. `resumePlayback()`은 재생을 다시
  시도하고 실패를 `detail`의 `playback-error`로 전달한다.
- `autoRecover: true`이면 `track-ended` 오류 뒤 탭이 다시 보일 때 `retry()`를
  호출한다. 탭이 보일 때마다 최대 한 번만 동작하고, 다른 오류는 무시하며,
  `disabled` 중에는 아무것도 하지 않는다. 기본값은 `false`다.
- 훅은 스트림을 연결하자마자 `play()`를 호출한다. 브라우저 autoplay 정책이 이
  호출을 거부하면(예: `muted` 누락) `detail.phase`가 `playback-error`가 되고
  `isFrameReady`는 `false`로 남는다. 요소를 넘기기 전에 `muted`와 `playsInline`을
  설정한다. iOS Safari는 `playsInline`이 없으면 인라인 재생하지 않는다.
  재생이 실패한 뒤에는 사용자 조작 안에서 `resumePlayback()`을 호출한다.
  이 프로젝트 자동화 컨테이너의 Chrome 83은 `muted` 없는 재생도 막지 않아
  이 실패를 재현하지 못한다.
- 요소 교체·언마운트 때 소유한 트랙을 종료하고 video에서 해당 스트림을 분리한다.
  같은 video의 `srcObject`나 카메라 스트림을 다른 제어 코드에서 동시에 관리하지 않는다.

## 카메라 에러 분류

### 2.0.0 마이그레이션

`SecurityError`의 분류가 `insecure-context` / `insecure`에서
`security-error` / `error`로 바뀐다. 모든 `SecurityError`를 HTTPS 문제로
안내하던 분기를 수정한다. 실제 보안 컨텍스트 문제는 계속
`insecure-context` / `insecure`로 보고한다.

`WebcamErrorCode`에 `security-error`, `policy-blocked`가 추가된다.
모든 코드를 나열하는 switch나 안내 문장 맵에 두 값을 반영한다.
확인된 정책 차단은 `policy-blocked` / `denied`다. 원인이 확인되지 않은
`NotAllowedError`는 기존 `permission-denied` / `denied` 분류를 유지한다.

- `insecure-context`: 보안 컨텍스트 밖에서 실행 중이다. HTTP에서 `mediaDevices`가
  없어지는 경우도 구분하도록 API 지원 여부보다 먼저 검사한다.
- `policy-blocked` (`denied` 상태): 브라우저의 정책 검사 API로 요청한 카메라나
  마이크의 차단을 확인했다. `permissionsPolicy`와 구형 `featurePolicy`를 지원한다.
- `permission-denied`: 정책 차단이 확인되지 않은 `NotAllowedError` 또는
  `PermissionDeniedError`다. 모든 브라우저에 정책 검사 API가 있지는 않으므로
  사용자가 거부 버튼을 눌렀다고 단정하지 않는다.
- `security-error` (`error` 상태): 문서의 미디어 사용이 비활성화되어 브라우저가
  `SecurityError`를 반환했다. HTTP 문제로 분류하지 않는다.

### 에러 코드별 원인과 조치

`detail.errorCode`는 `denied`, `unavailable`, `unsupported`, `insecure`, `error` 상태에 항상 있습니다.
코드로 복구할 수 없는 원인은 소비자가 안내 문구를 직접 보여 줘야 합니다.

| errorCode                 | phase         | 원인                                                                                           | 소비자 조치                                                                                                 |
| ------------------------- | ------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `permission-denied`       | `denied`      | `NotAllowedError` 또는 `PermissionDeniedError`. 정책 차단은 확인되지 않았습니다.               | 브라우저 사이트 설정에서 허용하도록 안내합니다. 허용 전에는 `retry()`가 같은 오류입니다.                    |
| `policy-blocked`          | `denied`      | Permissions-Policy 또는 iframe `allow` 속성이 요청한 카메라·마이크를 막습니다.                 | 호스트 페이지의 헤더나 iframe에 `allow="camera; microphone"`을 설정합니다.                                  |
| `security-error`          | `error`       | 문서의 미디어 사용이 비활성화되어 브라우저가 `SecurityError`를 반환했습니다.                   | 문서 정책과 iframe 설정을 확인합니다. HTTPS 안내를 보이지 않습니다.                                         |
| `device-not-found`        | `unavailable` | 요청한 입력 장치가 없습니다(`NotFoundError`).                                                  | 카메라 연결을 안내하고 연결 뒤 `retry()`를 호출합니다.                                                      |
| `device-in-use`           | `unavailable` | 다른 앱이나 탭이 장치를 점유하거나 하드웨어가 시작에 실패했습니다(`NotReadableError`).         | 다른 앱을 종료하도록 안내하고 `retry()`를 호출합니다.                                                       |
| `constraints-unsatisfied` | `error`       | 장치가 제약을 만족하지 못합니다(`OverconstrainedError`). 예: 없는 `deviceId`를 `exact`로 지정. | `deviceSelectionStrategy: "ideal"`을 쓰거나 해상도·`deviceId` 제약을 완화합니다.                            |
| `unsupported-browser`     | `unsupported` | `navigator.mediaDevices` 또는 `getUserMedia`가 없습니다.                                       | 지원 브라우저로 안내합니다. `retry()`로 복구할 수 없습니다.                                                 |
| `insecure-context`        | `insecure`    | HTTP 같은 보안 컨텍스트 밖에서 실행 중입니다.                                                  | HTTPS 또는 `localhost`로 제공합니다.                                                                        |
| `aborted`                 | `error`       | 브라우저가 요청을 중단했습니다(`AbortError`).                                                  | `retry()`를 호출합니다.                                                                                     |
| `track-ended`             | `error`       | 영상 트랙이 예기치 않게 종료되었습니다. 예: 카메라 분리.                                       | `retry()`를 호출하거나 `autoRecover`를 켭니다. 마이크 트랙 종료는 이 코드가 아니라 `audioEnded`로 알립니다. |
| `unknown`                 | `error`       | 위 분류에 없는 예외입니다.                                                                     | `detail.error`의 `name`과 `message`를 로그로 남기고 `retry()`를 제공합니다.                                 |

## 상태 변화 감지 - `onStateChange`

`onStateChange`는 `WebcamDetail`이 변경될 때마다 호출됩니다. `pausePlayback()`은 `WebcamDetail`을 변경하지 않으므로 `onStateChange`를 발생시키지 않습니다. `resumePlayback()`은 성공 시 보통 현재 상태를 유지하거나 `playback-error`를 해제하고, 실패 시 `playback-error`를 발생시킬 수 있습니다.

```tsx
import { Webcam, type WebcamDetail } from "@cp949/react-webcam";

export function CameraView() {
  function handleStateChange(detail: WebcamDetail) {
    switch (detail.phase) {
      case "live":
        console.log("스트림 시작:", detail.mediaStream);
        break;
      case "playback-error":
        console.warn("재생 차단:", detail.error);
        break;
      case "denied":
        console.warn("카메라 권한이 거부되었습니다.");
        break;
      case "unavailable":
        console.warn("카메라를 찾을 수 없거나 사용 중입니다.");
        break;
      case "insecure":
        console.error("HTTPS 환경에서만 카메라를 사용할 수 있습니다.");
        break;
      case "unsupported":
        console.error("이 브라우저는 카메라를 지원하지 않습니다.");
        break;
      case "error":
        if (detail.errorCode === "track-ended") {
          console.warn("카메라 트랙이 종료되었습니다. 재시작을 안내하세요.");
        } else {
          console.error("오류:", detail.errorCode, detail.error);
        }
        break;
    }
  }

  return (
    <div style={{ width: 640, height: "auto" }}>
      <Webcam webcamOptions={{ aspectRatio: 16 / 9 }} onStateChange={handleStateChange} />
    </div>
  );
}
```

오디오 트랙만 종료되면(예: 마이크를 뽑음) `phase`는 `live`로 유지되고 영상은 계속 재생된다.
`detail.audioEnded`가 `true`가 된다. 비디오 트랙이 종료되면 기존처럼 `track-ended` 오류로 전환된다.

### 촬영 UI 열기 - `onFrameReadyChange`

`live`는 디코딩된 프레임이 도착했다는 뜻이 아닙니다. 촬영 UI는 `detail.phase` 대신
`onFrameReadyChange`로 엽니다.

- `true`: phase가 `live`이고 `readyState >= 2`이며 영상 크기가 양수이고 비디오 트랙이 `muted`가 아닙니다.
- 처음 값은 `false`이며, 이 값으로는 호출하지 않습니다.
- 스트림 교체(`retry`, 옵션 변경), `disabled`, 트랙 `mute`, 오류 phase로 바뀌어 직전 값이 `true`였다면 `false`로 호출합니다. 언마운트 시에는 호출하지 않습니다.
- `pausePlayback()`은 값을 `true`로 유지합니다. 일시 정지한 프레임도 캡처할 수 있습니다.
- `ref.current.isFrameReady()`는 호출 시점의 현재 값을 반환합니다.
- 언마운트 뒤에는 캐시한 핸들의 `isFrameReady()`가 `false`를 반환합니다.

```tsx
import { useRef, useState } from "react";
import { Webcam, type WebcamHandle } from "@cp949/react-webcam";

export function CaptureView() {
  const webcamRef = useRef<WebcamHandle>(null);
  const [ready, setReady] = useState(false);

  return (
    <div style={{ width: 640, height: "auto" }}>
      <Webcam ref={webcamRef} onFrameReadyChange={setReady} />
      <button type='button' disabled={!ready} onClick={() => webcamRef.current?.snapshotToCanvas()}>
        스냅샷 찍기
      </button>
    </div>
  );
}
```

### 상태 흐름

```text
idle -> requesting -> live
               -> denied
               -> unavailable
               -> unsupported
               -> insecure
               -> error

live -> playback-error
playback-error -> live
live -> error
live -> requesting -> live   (webcamOptions 변경 시 자동 재시작)
```

`WebcamDetail`은 `phase`를 기준으로 분기하는 discriminated union입니다.

```ts
function handleDetail(detail: WebcamDetail) {
  if (detail.phase === "live") {
    console.log(detail.mediaStream);
    console.log(detail.constraints);
  } else if (detail.phase === "playback-error") {
    console.warn("재생 실패:", detail.error);
    console.log(detail.mediaStream);
  } else if (detail.phase === "denied") {
    console.warn(detail.errorCode);
    console.warn(detail.error);
  } else if (detail.phase === "error") {
    console.error(detail.errorCode, detail.error);
  } else if (detail.phase === "insecure") {
    console.error(detail.errorCode);
  }
}
```

## ref handle - `WebcamHandle`

`ref` prop으로 `WebcamHandle`을 받아 스냅샷 캡처, 디바이스 조회, 옵션 변경을 명령형으로 제어할 수 있습니다.

```tsx
import { useRef } from "react";
import { Webcam, type WebcamHandle } from "@cp949/react-webcam";

export function CameraWithSnapshot() {
  const webcamRef = useRef<WebcamHandle>(null);

  function handleSnapshot() {
    const canvas = webcamRef.current?.snapshotToCanvas();
    if (!canvas) return;

    const imageDataUrl = canvas.toDataURL("image/png");
    console.log(imageDataUrl);

    canvas.toBlob(
      (blob) => {
        if (blob) {
          // upload(blob);
        }
      },
      "image/jpeg",
      0.9,
    );
  }

  return (
    <div>
      <div style={{ width: 640, height: "auto" }}>
        <Webcam ref={webcamRef} webcamOptions={{ aspectRatio: 16 / 9 }} />
      </div>
      <button type='button' onClick={handleSnapshot}>
        스냅샷 찍기
      </button>
    </div>
  );
}
```

### `WebcamHandle` API

| 메서드                       | 설명                                                                       |
| ---------------------------- | -------------------------------------------------------------------------- |
| `snapshotToCanvas(options?)` | 현재 프레임을 `HTMLCanvasElement`로 반환. 준비 전이면 `null`               |
| `isFrameReady()`             | 지금 프레임을 캡처할 수 있는지 반환. `onFrameReadyChange`가 다루는 현재 값 |
| `getDetail()`                | 현재 `WebcamDetail`을 반환. `onStateChange`로 받는 값과 같다               |
| `getVideoElement()`          | 렌더된 `HTMLVideoElement`를 반환. 없으면 `null` (읽기 전용으로 사용)       |
| `getPlayingVideoDeviceId()`  | 재생 중인 비디오 트랙의 디바이스 ID                                        |
| `getPlayingAudioDeviceId()`  | 재생 중인 오디오 트랙의 디바이스 ID                                        |
| `setFlipped(value)`          | 좌우 반전 상태 변경                                                        |
| `setWebcamOptions(updater)`  | 카메라 옵션 갱신                                                           |
| `pausePlayback()`            | video 재생을 일시 정지한다. 카메라 스트림은 유지된다                       |
| `resumePlayback()`           | 일시 정지된 video 재생을 재개한다                                          |
| `retry()`                    | 같은 옵션으로 카메라 스트림을 다시 요청한다                                |

> `pausePlayback()`과 `resumePlayback()`은 `video.pause()` / `video.play()`만 호출합니다. 카메라 하드웨어를 끄거나 `MediaStreamTrack`을 stop하지 않습니다. 카메라 LED는 계속 켜져 있으며, track-ended 이벤트 감지도 계속 작동합니다. `pausePlayback()`은 `onStateChange`를 발생시키지 않지만, `resumePlayback()`은 실패 시 `playback-error`를 publish할 수 있습니다.

> `getVideoElement()`는 `<video>`를 읽기 용도(`drawImage`, `videoWidth`, 이벤트 구독)로만 노출합니다.
> `srcObject`, `style.transform`, `style.objectFit`을 바꾸거나 `play()` / `pause()`를 직접 호출하지 마세요.
> 재생 제어는 `pausePlayback()` / `resumePlayback()`을 사용합니다.
> 첫 크기 측정 전, `disabled`일 때, 언마운트 뒤에는 `null`을 반환합니다.
> `retry`와 옵션 변경 중에는 같은 요소를 유지하지만 `disabled`를 해제하면 요소가 다시 만들어질 수 있으므로,
> 결과를 저장하지 말고 필요할 때마다 호출하세요.
> `MediaStream`은 handle에서 노출하지 않습니다. `onStateChange`의 `detail.mediaStream`으로 읽으세요.

### `snapshotToCanvas(options)` 옵션

| 옵션                 | 타입                                            | 기본값              | 설명                                                                                        |
| -------------------- | ----------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------- |
| `imageSmoothEnabled` | `boolean`                                       | `true`              | 대상 캔버스의 `imageSmoothingEnabled`를 설정합니다.                                         |
| `canvas`             | `HTMLCanvasElement`                             | 새 캔버스           | 새로 만들지 않고 이 캔버스에 그립니다. `width`와 `height`는 결과 크기로 바뀝니다.           |
| `sizeConstraints`    | `{ maxWidth: number } \| { maxHeight: number }` | 원본 해상도         | 비율을 유지하며 축소합니다. 한도보다 작은 프레임은 확대하지 않습니다.                       |
| `flipped`            | `boolean`                                       | 현재 `flipped` 상태 | 결과 이미지의 좌우 반전을 덮어씁니다. 생략하면 미리보기와 같은 방향입니다.                  |
| `aspectRatio`        | `number`                                        | 원본 프레임 비율    | 프레임 가운데를 이 비율(너비/높이)로 잘라 냅니다. `0` 이하, `NaN`, `Infinity`는 무시합니다. |

처리 순서는 크롭(`aspectRatio`), 축소(`sizeConstraints`, 잘라 낸 크기에 적용), 반전입니다.
재사용하는 `canvas`는 결과 크기로 바뀝니다.

내장 스냅샷 버튼은 옵션 없이 `snapshotToCanvas()`를 호출하므로 현재 `flipped` 상태를 따르고
원본 해상도를 유지합니다.

## 디바이스 목록 조회

사용 가능한 장치 목록은 `Webcam` 컴포넌트에서 제공하지 않습니다.
라이브러리가 제공하는 유틸리티로 조회하며, 사용 방법은 다음과 같습니다.

```tsx
import {
  listAudioInputDevices,
  listMediaDevices,
  listVideoInputDevices,
} from "@cp949/react-webcam";

const allDevices: MediaDeviceInfo[] = await listMediaDevices();
const cameras: MediaDeviceInfo[] = await listVideoInputDevices();
const microphones: MediaDeviceInfo[] = await listAudioInputDevices();
```

반환 타입은 브라우저 기본 `MediaDeviceInfo[]`입니다.

목록의 첫 번째 디바이스를 `Webcam`에 전달하려면 `deviceId`를 `webcamOptions`에 넣습니다.

```tsx
const selectedDeviceId = allDevices[0]?.deviceId;

<Webcam webcamOptions={{ deviceId: selectedDeviceId }} />;
```

### `useMediaDevices`로 디바이스 변경 따라가기

`useMediaDevices(kind?)`는 마운트 뒤에 디바이스 목록을 불러오고, USB 카메라를 꽂거나 뽑을 때처럼
`devicechange` 이벤트가 발생할 때마다 목록을 갱신합니다.

```tsx
import { useMediaDevices } from "@cp949/react-webcam";

function CameraPicker({ onSelect }: { onSelect: (deviceId: string) => void }) {
  const { devices, labelsAvailable, error, refresh } = useMediaDevices("videoinput");

  if (error) return <p>카메라 목록을 불러오지 못했습니다: {error.message}</p>;

  return (
    <select onChange={(e) => onSelect(e.target.value)} onFocus={() => void refresh()}>
      {devices.map((device, index) => (
        <option key={device.deviceId} value={device.deviceId}>
          {labelsAvailable ? device.label : `카메라 ${index + 1}`}
        </option>
      ))}
    </select>
  );
}
```

| 필드              | 설명                                                                     |
| ----------------- | ------------------------------------------------------------------------ |
| `devices`         | 마지막으로 불러온 디바이스 목록. 첫 조회 전에는 빈 배열입니다.           |
| `labelsAvailable` | 디바이스가 있고 모두 `label`이 있으면 `true`입니다.                      |
| `error`           | 마지막 조회 오류. 없으면 `undefined`입니다. 훅은 예외를 던지지 않습니다. |
| `refresh()`       | 목록을 다시 불러옵니다. 권한 허용 뒤 label을 얻을 때 호출합니다.         |

카메라·마이크 권한을 허용하기 전에는 브라우저가 `label`을 빈 문자열로 반환합니다.
`labelsAvailable`이 `false`이면 `카메라 1` 같은 대체 이름을 보여 주세요.

## 레시피

### QR 스캔: 프레임이 준비되면 시작

`isFrameReady`가 `true`가 된 뒤에 프레임 콜백 루프를 시작한다.
`live`만으로는 프레임 도착을 보장하지 않으므로 `detail.phase`로 시작 시점을 정하지 않는다.
`decode`는 앱이 고른다. `BarcodeDetector` 또는 QR 디코딩 라이브러리를 감싼다.
`decode`와 `onResult`는 안정된 참조로 넘긴다. 참조가 바뀌면 루프가 다시 시작된다.
`requestVideoFrameCallback`을 지원하지 않는 브라우저는 `requestAnimationFrame`으로 바꾼다.

```tsx
import { useEffect, useState } from "react";
import { useWebcam } from "@cp949/react-webcam";

export function QrScanner({
  decode,
  onResult,
}: {
  decode: (video: HTMLVideoElement) => Promise<string | null>;
  onResult: (text: string) => void;
}) {
  const [video, setVideo] = useState<HTMLVideoElement | null>(null);
  const { isFrameReady } = useWebcam({
    videoElement: video,
    webcamOptions: { facingMode: "environment" },
  });

  useEffect(() => {
    if (!video || !isFrameReady) return;
    let canceled = false;
    let handle = 0;

    const scan = async () => {
      const text = await decode(video).catch(() => null);
      if (canceled) return;
      if (text) {
        onResult(text);
        return;
      }
      handle = video.requestVideoFrameCallback(scan);
    };

    handle = video.requestVideoFrameCallback(scan);
    return () => {
      canceled = true;
      video.cancelVideoFrameCallback(handle);
    };
  }, [video, isFrameReady, decode, onResult]);

  return <video ref={setVideo} muted playsInline />;
}
```

### 권한 거부 안내 화면과 `retry`

`denied` 상태에서는 `permission-denied`와 `policy-blocked`가 모두 해당한다.
권한을 거부한 뒤에는 브라우저가 프롬프트를 다시 띄우지 않을 수 있다.
사용자가 브라우저 설정에서 허용하기 전까지 `retry()`는 같은 오류로 실패한다.
안내 문구는 이 점을 전제로 쓴다. 코드별 조치는 "에러 코드별 원인과 조치" 표를 따른다.

```tsx
<Webcam
  errorFallback={(detail, { retry }) =>
    detail.phase === "denied" ? (
      <div>
        <p>카메라 권한이 필요합니다. 주소창의 카메라 아이콘에서 허용해 주세요.</p>
        <button onClick={retry}>허용했습니다. 다시 시도</button>
      </div>
    ) : (
      <div>
        <p>카메라를 시작할 수 없습니다. ({detail.errorCode})</p>
        <button onClick={retry}>다시 시도</button>
      </div>
    )
  }
/>
```

### 스냅샷을 `Blob`으로 업로드

`onSnapshot`이 받는 캔버스에서 `canvas.toBlob`을 직접 호출한다.
`toBlob`은 실패하면 `null`을 넘기므로 `Promise`로 감싸 오류로 바꾼다.
`/api/snapshots`는 예시 경로다. 앱의 업로드 주소로 바꾼다.

```tsx
function toBlob(canvas: HTMLCanvasElement, type: string, quality: number) {
  return new Promise<Blob>((resolve, reject) => {
    canvas.toBlob(
      (blob) => (blob ? resolve(blob) : reject(new Error("toBlob 실패"))),
      type,
      quality,
    );
  });
}

async function uploadSnapshot(canvas: HTMLCanvasElement) {
  const body = new FormData();
  body.append("file", await toBlob(canvas, "image/jpeg", 0.9), "snapshot.jpg");
  const response = await fetch("/api/snapshots", { method: "POST", body });
  if (!response.ok) throw new Error(`업로드 실패: ${response.status}`);
}

<Webcam
  controls={{ snapshot: true }}
  onSnapshot={(canvas) => {
    uploadSnapshot(canvas).catch(console.error);
  }}
/>;
```

### 거울 미리보기, 정방향 저장

거울 미리보기가 쓰기 편하지만, 저장한 이미지의 글자나 문서는 정방향이어야 합니다.
`flipped: false`를 넘기면 미리보기는 반전한 채로 정방향 이미지를 저장합니다.

```tsx
const webcamRef = useRef<WebcamHandle>(null);

<Webcam ref={webcamRef} defaultFlipped />;

function capture() {
  // 미리보기는 반전 상태를 유지하고, 저장 캔버스는 반전하지 않는다.
  return webcamRef.current?.snapshotToCanvas({ flipped: false });
}
```

## 스타일링

### CSS 변수

패키지는 스타일시트를 배포하지 않습니다. 색은 인라인 스타일이며 현재 값을
기본값으로 둔 CSS 변수를 읽습니다. 변수를 지정하기 전에는 아무것도 바뀌지
않습니다. `Webcam` 또는 상위 요소에 지정합니다.

```tsx
<div style={{ "--webcam-bg": "#000", "--webcam-accent": "#e91e63" } as React.CSSProperties}>
  <Webcam controls={{ snapshot: true }} />
</div>
```

| 변수                     | 기본값    | 적용 대상                               |
| ------------------------ | --------- | --------------------------------------- |
| `--webcam-bg`            | `#1e1e1e` | 루트와 video 배경                       |
| `--webcam-disabled-bg`   | `#f7f8fa` | `disabled`일 때 루트와 placeholder 배경 |
| `--webcam-accent`        | `#1976d2` | 호버 시 스냅샷 버튼 색                  |
| `--webcam-flip-active`   | `#ff7600` | 반전 켜짐일 때 미러 버튼 색             |
| `--webcam-rear-active`   | `#ff7600` | 후면일 때 카메라 방향 버튼 색           |
| `--webcam-menu-bg`       | `#fff`    | 팝업 메뉴 배경                          |
| `--webcam-menu-fg`       | `#000`    | 팝업 메뉴 항목 글자색                   |
| `--webcam-menu-hover-bg` | `#f5f5f5` | 호버 시 팝업 메뉴 항목 배경             |
| `--webcam-menu-z-index`  | `1300`    | 팝업 메뉴 `z-index`                     |

변수 이름은 공개 API입니다. 이름을 바꾸면 breaking change입니다. 버튼 오버레이
같은 다른 색은 바꿀 수 없습니다. `style` prop으로 지정한 속성은 변수보다
우선합니다.

### 클래스 이름

내장 요소를 직접 만든 CSS로 고칠 때는 아래 클래스 이름을 씁니다. 이 이름은
공개 API이며 이름을 바꾸면 breaking change입니다.

| 클래스                                                                                      | 요소                                           |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `Webcam-root`                                                                               | 루트 `div`. 전달한 `className`이 함께 붙습니다 |
| `Webcam-video`                                                                              | `video` 요소                                   |
| `Webcam-optionBtn`                                                                          | 미러, 전면/후면, 크기 비율 버튼의 래퍼         |
| `FlipButton-root`, `FacingModeButton-root`, `AspectRatioButton-root`, `SnapshotButton-root` | 각 내장 버튼의 래퍼                            |
| `x_btn`                                                                                     | 각 내장 버튼 래퍼 안의 `button`                |

색과 레이아웃은 인라인 스타일이므로 클래스 규칙은 `!important` 없이는 이깁니다.
색은 위의 CSS 변수를 우선 쓰세요. 루트의 `x_fullHeight`, `x_fixedHeight` 같은
상태 표시 클래스는 내부용이며 바뀔 수 있습니다.

## 라벨과 로컬라이제이션

내장 버튼 라벨의 기본값은 한국어입니다. 영어 UI는 `WEBCAM_LABELS_EN` 프리셋을
`labels`에 전달하면 됩니다.

```tsx
import { Webcam, WEBCAM_LABELS_EN } from "@cp949/react-webcam";

<Webcam
  controls={{ flip: true, cameraDirection: true, aspectRatio: true, snapshot: true }}
  labels={WEBCAM_LABELS_EN}
/>;
```

서비스 문구에 맞추려면 `labels`에 바꿀 항목만 전달합니다.

```tsx
<Webcam controls={{ flip: true }} labels={{ ...WEBCAM_LABELS_EN, flip: "셀피 보기" }} />
```

내장 스냅샷 버튼을 눌렀을 때 캡처한 프레임을 받으려면 `onSnapshot`을 전달합니다.
캔버스는 비디오 원본 해상도입니다.

```tsx
<Webcam
  controls={{ snapshot: true }}
  onSnapshot={(canvas) => {
    canvas.toBlob((blob) => blob && upload(blob), "image/jpeg", 0.9);
  }}
/>
```

## 아이콘 교체

`icons`에 React 노드를 전달하면 내장 버튼의 아이콘을 바꿉니다. 지정하지 않은 항목은
기본 아이콘을 유지합니다. `title`과 `aria-label`은 계속 `labels`를 따릅니다.

```tsx
import { Webcam } from "@cp949/react-webcam";

<Webcam
  controls={{ flip: true, cameraDirection: true, aspectRatio: true, snapshot: true }}
  icons={{
    flip: <MirrorIcon />,
    cameraDirection: <SwitchCameraIcon />,
    aspectRatio: <CropIcon />,
    snapshot: <ShutterIcon />,
  }}
/>;
```

- 전달한 노드는 버튼 안에 그대로 렌더링합니다. 크기는 직접 지정합니다.
- 기본 크기는 `flip`, `cameraDirection`, `aspectRatio`가 `1.2rem`, `snapshot`이 `2rem`입니다.
- 선과 채움에 `currentColor`를 쓰면 버튼 색과 `--webcam-*` 변수를 따릅니다.
- 아이콘은 상태에 따라 바뀌지 않습니다. 예를 들어 `flip`은 반전 여부와 관계없이 같은 노드를 보여 줍니다.

## 상태 소유권 - Controlled / Uncontrolled

`flipped`와 `webcamOptions`는 React의 표준 Controlled/Uncontrolled 패턴을 따릅니다.

### `flipped` 소유권

| 사용 방법                     | 동작                                                                                   |
| ----------------------------- | -------------------------------------------------------------------------------------- |
| `flipped` + `onFlippedChange` | Controlled 모드. 버튼/ref 변경 시 `onFlippedChange`만 호출하고 내부 상태는 바꾸지 않음 |
| `flipped`                     | 변경 콜백 없는 Controlled 모드. 버튼/ref 변경 요청이 반영되지 않음                     |
| `defaultFlipped`              | Uncontrolled 모드. 마운트 시 초기값 지정, 이후 내부 상태를 라이브러리가 관리           |
| 둘 다 미지정                  | Uncontrolled 모드, 초기값 `false`                                                      |

```tsx
import { useState } from "react";
import { Webcam } from "@cp949/react-webcam";

export function FlipOwnershipExample() {
  const [flipped, setFlipped] = useState(false);

  return (
    <>
      <Webcam flipped={flipped} onFlippedChange={setFlipped} controls={{ flip: true }} />

      <Webcam defaultFlipped controls={{ flip: true }} />
    </>
  );
}
```

첫 번째 `Webcam`은 상위 컴포넌트가 반전 상태를 소유하는 Controlled 모드 예제이고, 두 번째 `Webcam`은 초기값만 넘기고 이후 상태를 내부에서 관리하는 Uncontrolled 모드 예제입니다.

### `webcamOptions` 소유권

| 사용 방법                                 | 동작                                                           |
| ----------------------------------------- | -------------------------------------------------------------- |
| `webcamOptions` + `onWebcamOptionsChange` | Controlled 모드                                                |
| `webcamOptions`                           | 변경 콜백 없는 Controlled 모드. 내부 변경 요청이 반영되지 않음 |
| `defaultWebcamOptions`                    | Uncontrolled 모드                                              |
| 둘 다 미지정                              | Uncontrolled 모드, 기본값 사용                                 |

```tsx
import { useState } from "react";
import { Webcam, type WebcamOptions } from "@cp949/react-webcam";

export function WebcamOptionsOwnershipExample() {
  const [options, setOptions] = useState<WebcamOptions>({
    facingMode: "user",
    aspectRatio: 16 / 9,
  });

  return (
    <>
      <Webcam
        webcamOptions={options}
        onWebcamOptionsChange={setOptions}
        controls={{ cameraDirection: true, aspectRatio: true }}
      />

      <Webcam
        defaultWebcamOptions={{ facingMode: "environment", aspectRatio: 4 / 3 }}
        controls={{ cameraDirection: true, aspectRatio: true }}
      />
    </>
  );
}
```

첫 번째는 카메라 방향과 비율 변경 결과를 상위 상태에 반영하는 Controlled 모드 예제이고, 두 번째는 초기 옵션만 지정한 뒤 내부 상태에 맡기는 Uncontrolled 모드 예제입니다.

## 런타임 제약

- 브라우저 환경에서만 동작합니다.
- 카메라 접근은 HTTPS 또는 `localhost` 보안 컨텍스트가 필요합니다.
- 실제 장치가 없거나 다른 앱이 장치를 점유 중이면 `unavailable` 상태가 될 수 있습니다.
- 브라우저 autoplay 정책에 의해 `video.play()`가 차단되면 `playback-error` 상태가 됩니다. 이 경우 카메라 스트림은 살아 있으며, 사용자 인터랙션 후 `resumePlayback()`을 호출해 `live`로 복구할 수 있습니다.

## 학습용 데모 앱

`apps/demo`는 패키지 README를 대체하는 문서가 아니라, 실제 동작을 실험하고 검증하는 학습용 앱입니다.

- Basic Usage
- Common Controls
- Controlled State
- Device Selection
- Pause / Resume
- Ref Handle
- State Inspector
- Recipes
