File size: 11,377 Bytes
793e953
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
 * PushNotificationToggle - 推送通知开关组件
 *
 * 显示当前推送订阅状态,提供订阅/取消订阅的切换按钮。
 * 可在设置页面或任意位置嵌入使用。
 *
 * 交互流程:
 * 1. 检查浏览器支持 → 不支持则显示提示
 * 2. 检查通知权限 → 未授权则引导用户授权
 * 3. 检查当前订阅状态 → 显示对应按钮
 * 4. 点击按钮 → 执行订阅/取消订阅 + 后端同步
 */

import React, { useState, useEffect, useCallback } from 'react'
import { useTranslation } from '../i18n'
import {
  isPushSupported,
  getNotificationPermission,
  requestNotificationPermission,
  subscribeToPush,
  unsubscribeFromPush,
  getPushSubscription,
  registerSubscriptionWithBackend,
  unregisterSubscriptionFromBackend,
} from '../utils/pushNotifications'

// ================================================================
// 状态枚举
// ================================================================

type SubscriptionStatus =
  | 'unsupported'   // 浏览器不支持 Push
  | 'loading'       // 正在检查/执行操作
  | 'denied'        // 通知权限被拒绝
  | 'unsubscribed'  // 未订阅
  | 'subscribed'    // 已订阅

// ================================================================
// PushNotificationToggle 组件
// ================================================================

export default function PushNotificationToggle() {
  const { t } = useTranslation()
  const [status, setStatus] = useState<SubscriptionStatus>('loading')
  const [error, setError] = useState<string | null>(null)
  const [subscriptionEndpoint, setSubscriptionEndpoint] =
    useState<string | null>(null)

  // ----------------------------------------------------------
  // 初始化:检查当前状态
  // ----------------------------------------------------------

  useEffect(() => {
    checkStatus()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const checkStatus = useCallback(async () => {
    setError(null)

    // 1. 检查浏览器支持
    if (!isPushSupported()) {
      setStatus('unsupported')
      return
    }

    // 2. 检查通知权限
    const permission = getNotificationPermission()
    if (permission === 'denied') {
      setStatus('denied')
      return
    }

    // 3. 检查当前订阅
    setStatus('loading')
    try {
      const sub = await getPushSubscription()
      if (sub) {
        setSubscriptionEndpoint(sub.endpoint || null)
        setStatus('subscribed')
      } else {
        setSubscriptionEndpoint(null)
        setStatus('unsubscribed')
      }
    } catch {
      setSubscriptionEndpoint(null)
      setStatus('unsubscribed')
    }
  }, [])

  // ----------------------------------------------------------
  // 开启通知
  // ----------------------------------------------------------

  const handleEnable = useCallback(async () => {
    setError(null)
    setStatus('loading')

    try {
      console.log('[PushToggle] 开始开启推送通知...')

      // 先请求通知权限(如果尚未授予)
      let permission = getNotificationPermission()
      if (permission !== 'granted') {
        permission = await requestNotificationPermission()
      }

      if (permission !== 'granted') {
        console.warn('[PushToggle] 通知权限未授予')
        setStatus('denied')
        setError(t('components.push.permissionNotGranted'))
        return
      }

      // 订阅 Push(调用浏览器 PushManager.subscribe)
      console.log('[PushToggle] 调用 subscribeToPush...')
      const subscription = await subscribeToPush()
      console.log('[PushToggle] 浏览器订阅成功:', subscription.endpoint)

      // 立刻更新 UI 状态为已订阅(不等后端同步完成)
      setSubscriptionEndpoint(subscription.endpoint || null)
      setStatus('subscribed')
      console.log('[PushToggle] UI 已切换为已订阅状态')

      // 后台同步到后端(不阻塞 UI)
      try {
        console.log('[PushToggle] 同步订阅到后端...')
        await registerSubscriptionWithBackend(subscription)
        console.log('[PushToggle] 后端订阅注册成功')
      } catch (backendErr) {
        console.warn('[PushToggle] 后端同步失败(浏览器订阅已生效):', backendErr)
        setError(t('components.push.backendSyncFailed'))
      }
    } catch (err) {
      console.error('[PushToggle] 开启失败:', err)
      const message =
        err instanceof Error ? err.message : t('components.push.enableFailed')
      setError(message)
      // 回退到检查当前实际订阅状态
      await checkStatus()
    }
  }, [checkStatus])

  // ----------------------------------------------------------
  // 关闭通知
  // ----------------------------------------------------------

  const handleDisable = useCallback(async () => {
    setError(null)
    setStatus('loading')

    try {
      // 获取当前端点用于后端取消注册
      const sub = await getPushSubscription()
      const endpoint = sub?.endpoint || subscriptionEndpoint

      // 取消浏览器 Push 订阅
      await unsubscribeFromPush()

      // 从后端取消注册
      if (endpoint) {
        try {
          await unregisterSubscriptionFromBackend(endpoint)
        } catch {
          // 后端取消失败不影响前端状态
          console.warn('[PushToggle] 后端取消订阅失败,已在前端取消')
        }
      }

      setSubscriptionEndpoint(null)
      setStatus('unsubscribed')
    } catch (err) {
      const message =
        err instanceof Error ? err.message : t('components.push.disableFailed')
      setError(message)
      await checkStatus()
    }
  }, [subscriptionEndpoint, checkStatus])

  // ----------------------------------------------------------
  // 渲染:不支持
  // ----------------------------------------------------------

  if (status === 'unsupported') {
    return (
      <div className="card p-4">
        <div className="flex items-start gap-3">
          <div className="shrink-0 mt-0.5">
            <svg
              className="w-5 h-5 text-surface-400"
              fill="none"
              stroke="currentColor"
              strokeWidth={2}
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"
              />
            </svg>
          </div>
          <div>
            <p className="text-sm font-medium text-gray-700">{t('components.push.notSupported')}</p>
            <p className="text-xs text-surface-400 mt-0.5">
              {t('components.push.browserNotSupported')}
            </p>
          </div>
        </div>
      </div>
    )
  }

  // ----------------------------------------------------------
  // 渲染:加载中
  // ----------------------------------------------------------

  if (status === 'loading') {
    return (
      <div className="card p-4">
        <div className="flex items-center gap-3">
          <div className="w-5 h-5 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin" />
          <p className="text-sm text-surface-400">{t('components.push.checking')}</p>
        </div>
      </div>
    )
  }

  // ----------------------------------------------------------
  // 渲染:权限被拒绝
  // ----------------------------------------------------------

  if (status === 'denied') {
    return (
      <div className="card p-4">
        <div className="flex items-start gap-3">
          <div className="shrink-0 mt-0.5">
            <svg
              className="w-5 h-5 text-amber-500"
              fill="none"
              stroke="currentColor"
              strokeWidth={2}
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-gray-700">
              {t('components.push.permissionDenied')}
            </p>
            <p className="text-xs text-surface-400 mt-0.5">
              {t('components.push.permissionDeniedHint')}
            </p>
          </div>
        </div>
      </div>
    )
  }

  // ----------------------------------------------------------
  // 渲染:已订阅 / 未订阅
  // ----------------------------------------------------------

  return (
    <div className="card p-4">
      {/* 标题行 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          {/* 状态图标 */}
          {status === 'subscribed' ? (
            <div className="w-5 h-5 rounded-full bg-emerald-100 flex items-center justify-center">
              <svg
                className="w-3 h-3 text-emerald-600"
                fill="none"
                stroke="currentColor"
                strokeWidth={3}
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
          ) : (
            <div className="w-5 h-5 rounded-full bg-surface-100 flex items-center justify-center">
              <svg
                className="w-3 h-3 text-surface-400"
                fill="none"
                stroke="currentColor"
                strokeWidth={2}
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"
                />
              </svg>
            </div>
          )}

          {/* 状态文字 */}
          <div>
            <p className="text-sm font-medium text-gray-700">
              {status === 'subscribed' ? t('components.push.enabled') : t('components.push.disabled')}
            </p>
            <p className="text-xs text-surface-400 mt-0.5">
              {status === 'subscribed'
                ? t('components.push.enabledDesc')
                : t('components.push.disabledDesc')}
            </p>
          </div>
        </div>

        {/* 切换按钮 */}
        {status === 'subscribed' ? (
          <button
            type="button"
            onClick={handleDisable}
            className="btn-danger text-xs px-3 py-1.5"
          >
            {t('components.push.disableButton')}
          </button>
        ) : (
          <button
            type="button"
            onClick={handleEnable}
            className="btn-primary text-xs px-3 py-1.5"
          >
            {t('components.push.enableButton')}
          </button>
        )}
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="mt-3 px-3 py-2 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-xs text-red-600">{error}</p>
        </div>
      )}
    </div>
  )
}