> ## Documentation Index
> Fetch the complete documentation index at: https://docs.thunderphone.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Headless Hook

> 使用 useThunderPhone React Hook 建立完全自訂的語音使用者介面

`useThunderPhone` Hook 可讓你完整掌控使用者介面，同時由 ThunderPhone 管理語音工作階段、音訊路由和連線狀態。當你想要完全自訂的 UI——自行設計按鈕、版面配置、動畫和品牌風格——並由 ThunderPhone 在幕後處理一切時，請使用它。

## 何時使用無介面 Hook

預先建置的 `ThunderPhoneWidget` 元件可涵蓋大多數使用情境，但在你需要以下功能時，請使用無介面 Hook：

* 完全自訂的通話 UI，以符合你的應用程式設計系統
* 由即時音訊音量驅動的音訊反應式視覺化效果（波形、光球、脈衝指示器）
* 自訂通話流程，例如通話前表單、通話後問卷，或與語音並列的內嵌聊天
* 整合至既有元件函式庫（Material UI、Chakra、Radix 等）

***

## 安裝

```bash theme={null}
npm install @thunderphone/widget
```

<Note>
  無介面 Hook **不**需要匯入 `@thunderphone/widget/style.css`，因為你會自行提供 UI。不過，你仍必須安裝相同的 `@thunderphone/widget` 套件。
</Note>

***

## 基本用法

```tsx theme={null}
import { useThunderPhone } from '@thunderphone/widget'

function CustomCallButton() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })

  const handleClick = () => {
    if (phone.state === 'connected') {
      phone.disconnect()
    } else {
      phone.connect()
    }
  }

  return (
    <>
      <button onClick={handleClick} disabled={phone.state === 'connecting'}>
        {phone.state === 'connecting'
          ? 'Connecting...'
          : phone.state === 'connected'
            ? 'End call'
            : 'Start call'}
      </button>
      {phone.audio}
    </>
  )
}
```

<Warning>
  **你必須在元件樹的某處呈現 `phone.audio`。** 它是管理底層音訊連線的隱形 React 元件。若省略它，將不會播放任何音訊，工作階段也無法運作。
</Warning>

***

## 選項

透過 `UseThunderPhoneOptions` 將以下選項傳遞給 `useThunderPhone`：

| 選項               | 類型                  | 必填 | 預設值                                 | 說明                                                               |
| ---------------- | ------------------- | -- | ----------------------------------- | ---------------------------------------------------------------- |
| `publishableKey` | `string`            | 是  | --                                  | 可公開 API 金鑰（`pk_live_...`）。系統會根據金鑰的小工具設定自動判定智慧體。                  |
| `apiBase`        | `string`            | 否  | `'https://api.thunderphone.com/v1'` | 覆寫 API 基礎 URL。                                                   |
| `language`       | `string`            | 否  | --                                  | 每個工作階段的語言覆寫——語言代碼或地區設定，例如 `en`、`es` 或 `fr-FR`。未設定時，會套用智慧體已設定的語言。 |
| `voice`          | `string`            | 否  | --                                  | 每個工作階段的語音覆寫——語音名稱，例如 `maria`。未設定時，會套用智慧體已設定的語音。                  |
| `context`        | `string`            | 否  | --                                  | 傳遞給智慧體的每個工作階段之事實性頁面或網站背景資訊。伺服器端會截斷至 12,000 個字元。                  |
| `onConnect`      | `() => void`        | 否  | --                                  | 語音工作階段連線時呼叫。                                                     |
| `onDisconnect`   | `() => void`        | 否  | --                                  | 工作階段結束時呼叫。                                                       |
| `onError`        | `(error) => void`   | 否  | --                                  | 發生錯誤時呼叫。錯誤具有 `error`（代碼）和 `message` 欄位。                          |
| `ringtone`       | `boolean \| string` | 否  | `false`                             | 連線時播放鈴聲。`true` 使用預設鈴聲，或使用 URL 字串指定自訂音訊。                          |

<Note>
  此 Hook 為無介面：它**不**接受 `ThunderPhoneWidget` 的外觀屬性（`theme`、`primaryColor`、`title`、`position`、`className`）。傳遞這些屬性會造成 TypeScript 錯誤——呈現方式完全由你自行建置。
</Note>

***

## 回傳值

此 Hook 會回傳一個 `UseThunderPhoneReturn` 物件：

| 屬性              | 類型                                                                   | 說明                                                                                                                                                                       |
| --------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `state`         | `'idle' \| 'connecting' \| 'connected' \| 'disconnected' \| 'error'` | 目前的連線狀態。                                                                                                                                                                 |
| `connect`       | `() => void`                                                         | 開始語音工作階段。                                                                                                                                                                |
| `disconnect`    | `() => void`                                                         | 結束目前的工作階段。                                                                                                                                                               |
| `toggleMute`    | `() => void`                                                         | 切換麥克風靜音開關。                                                                                                                                                               |
| `isMuted`       | `boolean`                                                            | 麥克風目前是否已靜音。                                                                                                                                                              |
| `error`         | `string \| undefined`                                                | 狀態為 `'error'` 時的錯誤訊息。                                                                                                                                                    |
| `agentName`     | `string \| undefined`                                                | 已連線智慧體的顯示名稱。                                                                                                                                                             |
| `audioLevel`    | `number`                                                             | **已淘汰——一律為 `0`。** 為維持向下相容而保留的靜態預留欄位；永遠不會更新。請改讀取 `audioLevelRef.current`。                                                                                                 |
| `audioLevelRef` | `React.RefObject<number>`                                            | 包含即時音訊音量（0--1）的可變 ref——取智慧體語音與訪客麥克風中較大的音量——會在每個動畫影格更新，且不受 React 渲染週期影響。若要實現流暢、無卡頓的動畫，請在 `requestAnimationFrame` 迴圈中讀取 `audioLevelRef.current`；若需要在 React 狀態中取得該值，則可定期取樣。 |
| `audio`         | `ReactNode`                                                          | 處理音訊連線的不可見元素——**必須渲染**。                                                                                                                                                  |

***

## 音訊反應式 UI

`audioLevelRef` ref 可讓你取得影格速率的音訊音量，而不會觸發 React 重新渲染，因此非常適合用於驅動流暢的波形視覺效果、脈動光球，或任何與對話連動的動畫。音量會反映較大聲的一方：語音智慧體的聲音或訪客的麥克風。

### 波形範例

```tsx theme={null}
import { useRef, useEffect } from 'react'
import { useThunderPhone } from '@thunderphone/widget'

function WaveformCall() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })
  const canvasRef = useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    if (phone.state !== 'connected') return
    const canvas = canvasRef.current
    if (!canvas) return
    const ctx = canvas.getContext('2d')!

    let animId: number
    const draw = () => {
      const level = phone.audioLevelRef.current ?? 0
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // Draw bars that react to audio level
      const barCount = 24
      const barWidth = canvas.width / barCount
      for (let i = 0; i < barCount; i++) {
        const distance = Math.abs(i - barCount / 2) / (barCount / 2)
        const height = level * canvas.height * (1 - distance * 0.6)
        const y = (canvas.height - height) / 2
        ctx.fillStyle = '#0ea5e9'
        ctx.fillRect(i * barWidth + 1, y, barWidth - 2, height)
      }

      animId = requestAnimationFrame(draw)
    }
    animId = requestAnimationFrame(draw)
    return () => cancelAnimationFrame(animId)
  }, [phone.state, phone.audioLevelRef])

  return (
    <div>
      {phone.state === 'connected' && (
        <canvas ref={canvasRef} width={240} height={80} />
      )}
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connected' ? 'End call' : 'Start call'}
      </button>
      {phone.audio}
    </div>
  )
}
```

### 脈動光球範例

```tsx theme={null}
import { useRef, useEffect } from 'react'
import { useThunderPhone } from '@thunderphone/widget'

function PulsingOrb() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })
  const orbRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (phone.state !== 'connected') return
    let animId: number
    const animate = () => {
      const level = phone.audioLevelRef.current ?? 0
      if (orbRef.current) {
        const scale = 1 + level * 0.5
        orbRef.current.style.transform = `scale(${scale})`
        orbRef.current.style.opacity = `${0.6 + level * 0.4}`
      }
      animId = requestAnimationFrame(animate)
    }
    animId = requestAnimationFrame(animate)
    return () => cancelAnimationFrame(animId)
  }, [phone.state, phone.audioLevelRef])

  return (
    <div style={{ textAlign: 'center' }}>
      <div
        ref={orbRef}
        style={{
          width: 80,
          height: 80,
          borderRadius: '50%',
          background: '#0ea5e9',
          margin: '20px auto',
          transition: 'transform 0.05s ease-out',
        }}
      />
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connected' ? 'End call' : 'Call'}
      </button>
      {phone.audio}
    </div>
  )
}
```

### 說話指示器範例

對於會隨音量變化的 React 渲染 UI——例如以閾值為基礎的「說話中」標記——請定期讀取 `audioLevelRef.current`，並將結果儲存在 state 中：

```tsx theme={null}
import { useEffect, useState } from 'react'
import { useThunderPhone } from '@thunderphone/widget'

function SpeakingBadge() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })
  const [speaking, setSpeaking] = useState(false)

  useEffect(() => {
    if (phone.state !== 'connected') {
      setSpeaking(false)
      return
    }
    const interval = setInterval(() => {
      setSpeaking((phone.audioLevelRef.current ?? 0) > 0.1)
    }, 100)
    return () => clearInterval(interval)
  }, [phone.state, phone.audioLevelRef])

  return (
    <div>
      {phone.state === 'connected' && (
        <span>{speaking ? 'Speaking' : 'Listening'}</span>
      )}
      <button onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}>
        {phone.state === 'connected' ? 'End call' : 'Start call'}
      </button>
      {phone.audio}
    </div>
  )
}
```

<Warning>
  務必從 `audioLevelRef.current` 讀取音量。回傳物件中的 `audioLevel` 數值<strong>已淘汰且永遠為 `0`</strong>——任何依據它建立的邏輯都會在無提示的情況下讀取到零。
</Warning>

***

## 狀態機

`state` 屬性遵循以下生命週期：

```
idle --> connecting --> connected --> disconnected --> idle (after 1.5s)
                  \
                   --> error (stays until connect() is called again)
```

| 狀態             | 說明                                                                        |
| -------------- | ------------------------------------------------------------------------- |
| `idle`         | 沒有進行中的工作階段。可呼叫 `connect()`。                                               |
| `connecting`   | 正在建立工作階段。在此狀態期間停用通話按鈕。                                                    |
| `connected`    | 語音工作階段進行中。使用者正在與智慧體交談。                                                    |
| `disconnected` | 工作階段已正常結束。1.5 秒後會自動轉回 `idle`。                                             |
| `error`        | 發生錯誤。請查看 `phone.error` 取得訊息。此狀態**不會**自行清除——再次呼叫 `connect()` 會開始新的嘗試並重設錯誤。 |

***

## 範例

### 使用靜音控制

```tsx theme={null}
import { useThunderPhone } from '@thunderphone/widget'

function CallWithMute() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })

  return (
    <div>
      {phone.state === 'connected' && (
        <div>
          <p>Talking to {phone.agentName ?? 'Agent'}</p>
          <button onClick={phone.toggleMute}>
            {phone.isMuted ? 'Unmute' : 'Mute'}
          </button>
          <button onClick={phone.disconnect}>End call</button>
        </div>
      )}

      {phone.state !== 'connected' && (
        <button
          onClick={phone.connect}
          disabled={phone.state === 'connecting'}
        >
          {phone.state === 'connecting' ? 'Connecting...' : 'Call support'}
        </button>
      )}

      {phone.state === 'error' && (
        <p style={{ color: 'red' }}>{phone.error}</p>
      )}

      {phone.audio}
    </div>
  )
}
```

### 使用鈴聲

在連線時播放響鈴聲，模擬電話通話：

```tsx theme={null}
import { useThunderPhone } from '@thunderphone/widget'

function PhoneCallButton() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
    ringtone: true, // or a custom URL: 'https://example.com/ringtone.mp3'
  })

  return (
    <>
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connecting'
          ? 'Ringing...'
          : phone.state === 'connected'
            ? 'Hang up'
            : 'Call'}
      </button>
      {phone.audio}
    </>
  )
}
```

鈴聲會在 `connecting` 狀態期間循環播放，並在智慧體接通時淡出。傳入 `true` 可使用內建預設鈴聲，或傳入 URL 字串以使用你自己的音訊檔案。

### 使用事件回呼

```tsx theme={null}
import { useThunderPhone } from '@thunderphone/widget'

function TrackedCallButton() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
    onConnect: () => {
      analytics.track('call_started')
    },
    onDisconnect: () => {
      analytics.track('call_ended')
    },
    onError: (error) => {
      analytics.track('call_error', { code: error.error, message: error.message })
    },
  })

  return (
    <>
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connected' ? 'Hang up' : 'Talk to AI'}
      </button>
      {phone.audio}
    </>
  )
}
```

### 完全自訂 UI

```tsx theme={null}
import { useThunderPhone } from '@thunderphone/widget'

function FullCustomUI() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })

  return (
    <div className="call-panel">
      <div className="call-status">
        {phone.state === 'idle' && <span>Ready</span>}
        {phone.state === 'connecting' && <span className="pulse">Connecting...</span>}
        {phone.state === 'connected' && (
          <span>On call with {phone.agentName}</span>
        )}
        {phone.state === 'error' && <span className="error">{phone.error}</span>}
      </div>

      <div className="call-controls">
        {phone.state === 'connected' ? (
          <>
            <button className="mute-btn" onClick={phone.toggleMute}>
              {phone.isMuted ? 'Unmute' : 'Mute'}
            </button>
            <button className="end-btn" onClick={phone.disconnect}>
              End
            </button>
          </>
        ) : (
          <button
            className="start-btn"
            onClick={phone.connect}
            disabled={phone.state === 'connecting'}
          >
            Start call
          </button>
        )}
      </div>

      {/* Required -- handles audio under the hood */}
      {phone.audio}
    </div>
  )
}
```

***

## 提示

<AccordionGroup>
  <Accordion title="一律渲染 phone.audio">
    `phone.audio` 元素不可見，但不可或缺。將其放在 JSX 的任何位置——它不會渲染可見的 DOM，但會在內部管理 WebRTC 音訊連線。
  </Accordion>

  <Accordion title="連線期間停用按鈕">
    `connecting` 狀態可能持續 1 至 3 秒。在此狀態期間停用通話按鈕，以避免重複嘗試連線。
  </Accordion>

  <Accordion title="妥善處理錯誤狀態">
    當狀態為 `error` 時，向使用者顯示 `phone.error`，並保持通話按鈕啟用。此 Hook 不會自行離開 `error` 狀態——再次呼叫 `connect()` 會開始新的嘗試，並清除先前的錯誤。
  </Accordion>

  <Accordion title="使用回呼處理副作用">
    `onConnect`、`onDisconnect` 和 `onError` 回呼非常適合用於分析、記錄，或觸發其他應用程式邏輯，無須輪詢狀態。
  </Accordion>

  <Accordion title="從 audioLevelRef 讀取音訊音量">
    `audioLevelRef` 是唯一的即時音訊音量來源。若要實現波形等流暢動畫，請在 `requestAnimationFrame` 內讀取 `audioLevelRef.current`（讀取 ref 不會造成重新渲染）；或者依固定間隔取樣，並將結果儲存在 state 中，供 React 渲染的 UI 使用。`audioLevel` 數值已淘汰，且一律為 `0`——請勿依此建立邏輯。
  </Accordion>
</AccordionGroup>
