推送通知:Web Push(网页 / PWA)+ 桌面原生通知
页面 / PWA 关闭、或桌面窗口非前台时,收到文件、消息、传输完成 / 失败以系统通知提醒。
判定统一为「页面打开走应用内提示,否则系统通知」,三端各自落地;网页端的判定直接复用
Hub.SendTo 的投递结果,零额外状态。
- Web Push(VAPID,账号无关):服务端 internal/push.Sender 在事件未经 SSE 投递到目标
设备时(即该设备页面已关)发推送,文案按订阅 locale 在服务端渲染(中简 / 中繁 / 英)、
404 / 410 自动清理死订阅;新增 push_subscriptions 表(含 locale,主键为 endpoint 的
SHA-256 以幂等 upsert)+ /api/push/{vapid-key, subscribe POST/DELETE} 端点
- 事件挂接:transfer:incoming / message(离线返 202,文本随推送送达)/ transfer:state
DONE|FAILED,均未投递才推
- 配置 CDROP_VAPID_PUBLIC_KEY / CDROP_VAPID_PRIVATE_KEY(半对即拒启动,都空则推送惰性
关闭)+ just vapid-keygen 生成工具(cmd/vapidgen)
- 前端:service worker 加 push / notificationclick(仍不拦截 /api 与导航);net/push.ts
订阅管理 + push store slice + 设置页「推送通知」面板(仅浏览器 / PWA);登录后 resyncPush
把既有订阅重新登记到当前用户,换用户 / endpoint 轮换 / 切换语言皆自愈
- 桌面原生通知:platform/notify_{darwin,windows,other}.go + notify_darwin.m,仅窗口非
前台时弹原生通知(macOS UNUserNotificationCenter,未签名时安全空操作、待签名后显示;
Windows go-toast 即用);app.go ShowNotification 绑定,前端 notifyNativeIfBackground
复用 hub 事件分发 + 客户端本地化
- 文档:README / .env.example / compose 模板补 CDROP_VAPID_* 配置
注:sqlc v1.31.1 对 query 文件里的多字节字符会错位偏移、生成损坏 SQL,故 query 注释保持纯
ASCII(文件内留有警示)。
This commit is contained in:
@@ -60,3 +60,43 @@ self.addEventListener("fetch", (event) =>
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ---- Web Push --------------------------------------------------------------
|
||||
// Fires only when this device's page is closed (an open page got the event over
|
||||
// SSE and showed an in-app toast instead). The payload is the JSON the server's
|
||||
// push.Sender already localized: { type, title, body, tag, url }. The SW just
|
||||
// displays it — no /api access, no app logic.
|
||||
self.addEventListener("push", (event) =>
|
||||
{
|
||||
let data = {};
|
||||
try { data = event.data ? event.data.json() : {}; }
|
||||
catch (_e) { data = {}; }
|
||||
|
||||
const title = data.title || "cdrop";
|
||||
const options = {
|
||||
body: data.body || "",
|
||||
tag: data.tag || undefined, // same tag replaces a stale notification in place
|
||||
icon: "/icon-192.png",
|
||||
badge: "/icon-192.png",
|
||||
data: { url: data.url || "/" },
|
||||
};
|
||||
event.waitUntil(self.registration.showNotification(title, options));
|
||||
});
|
||||
|
||||
// Clicking a notification focuses an existing window if one is open, else opens
|
||||
// the app at the notification's target URL.
|
||||
self.addEventListener("notificationclick", (event) =>
|
||||
{
|
||||
event.notification.close();
|
||||
const target = (event.notification.data && event.notification.data.url) || "/";
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) =>
|
||||
{
|
||||
for (const c of clients)
|
||||
{
|
||||
if ("focus" in c) { return c.focus(); }
|
||||
}
|
||||
return self.clients.openWindow ? self.clients.openWindow(target) : undefined;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { connectSSE, type SseEvent } from "../../net/sse";
|
||||
import { useAppStore, type DeviceInfo, type TransferRecord } from "../../store";
|
||||
import { apiFetch } from "../../net/api";
|
||||
import { notifyNativeIfBackground } from "../../net/desktop";
|
||||
import { t } from "../../i18n";
|
||||
import { p2pHandleSignal, p2pCleanup } from "./p2p";
|
||||
import { rememberIncoming, handleRelayReady, cleanupTransfer } from "./transfer";
|
||||
import { applyRemoteClipboard } from "../clipboard/clipboard";
|
||||
@@ -156,6 +158,8 @@ function handleIncomingMessage(data: unknown): void
|
||||
text: p.text,
|
||||
sentAt: typeof p.sent_at === "number" ? p.sent_at : Math.floor(Date.now() / 1000),
|
||||
});
|
||||
// 桌面端窗口在后台时弹原生通知(标题=发送方设备名,正文=消息)。
|
||||
notifyNativeIfBackground(p.from, p.text);
|
||||
}
|
||||
|
||||
function handleClipboardUpdate(data: unknown): void
|
||||
@@ -256,6 +260,12 @@ async function handleIncoming(data: unknown): Promise<void>
|
||||
};
|
||||
useAppStore.getState().upsertTransfer(rec);
|
||||
|
||||
// 桌面端窗口在后台时弹原生通知「收到文件」(前台时由传输卡片呈现)。
|
||||
notifyNativeIfBackground(
|
||||
t("notify.incoming.title"),
|
||||
t("notify.incoming.body", { sender: s.sender_name, file: s.file_name }),
|
||||
);
|
||||
|
||||
// brief §2 写明 "> 100 MB 二次确认",但 MVP 没有该 UI,且 auto_accept=false
|
||||
// 时跳过 rememberIncoming + /accept 会让 sender 等不到任何 ICE 候选 → 30s
|
||||
// 后 fallback 到 relay → ring buffer 64 MiB 写满 → 整个传输死锁。所以这里
|
||||
@@ -297,6 +307,14 @@ function handleState(data: unknown): void
|
||||
store.upsertTransfer({ ...cur, mode: p.mode });
|
||||
}
|
||||
store.completeTransfer(p.session_id, p.state);
|
||||
// 桌面端窗口在后台时,对完成 / 失败弹原生通知(取消不提醒,与推送事件选择一致)。
|
||||
if (p.state === "DONE" || p.state === "FAILED")
|
||||
{
|
||||
notifyNativeIfBackground(
|
||||
t(p.state === "DONE" ? "notify.transfer.doneTitle" : "notify.transfer.failedTitle"),
|
||||
cur?.fileName ?? "",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (cur)
|
||||
|
||||
@@ -117,6 +117,20 @@ export const enUS: Partial<TranslationDict> = {
|
||||
"settings.offline": "Offline",
|
||||
"settings.lastSeen": "Last seen {{time}}",
|
||||
"settings.lastSeenNever": "Never connected",
|
||||
"settings.push.title": "Push notifications",
|
||||
"settings.push.hint": "When this page is closed, new files, messages, and transfer results arrive as system notifications; while it's open, you'll see in-app alerts instead.",
|
||||
"settings.push.enable": "Enable push",
|
||||
"settings.push.enabled": "Enabled",
|
||||
"settings.push.disable": "Turn off",
|
||||
"settings.push.deniedHint": "Notifications are blocked by the browser. Allow them in this site's settings, then try again.",
|
||||
"settings.push.denied": "Notification permission denied",
|
||||
"settings.push.enableOk": "Push notifications enabled",
|
||||
"settings.push.disableOk": "Push notifications turned off",
|
||||
"settings.push.failed": "Couldn't enable push. Please try again.",
|
||||
"notify.incoming.title": "Incoming file",
|
||||
"notify.incoming.body": "{{sender}} is sending {{file}}",
|
||||
"notify.transfer.doneTitle": "Transfer complete",
|
||||
"notify.transfer.failedTitle": "Transfer failed",
|
||||
"settings.account.title": "Account",
|
||||
"settings.account.signOut": "Sign out",
|
||||
"settings.desktop.title": "Desktop",
|
||||
|
||||
@@ -114,6 +114,20 @@ export const zhCN = {
|
||||
"settings.offline": "离线",
|
||||
"settings.lastSeen": "上次活跃 {{time}}",
|
||||
"settings.lastSeenNever": "尚未上线",
|
||||
"settings.push.title": "推送通知",
|
||||
"settings.push.hint": "页面关闭时,新文件、消息和传输结果会以系统通知提醒;页面打开时仍走应用内提示。",
|
||||
"settings.push.enable": "启用推送",
|
||||
"settings.push.enabled": "已启用",
|
||||
"settings.push.disable": "关闭推送",
|
||||
"settings.push.deniedHint": "通知权限已被浏览器拒绝,请在浏览器的站点设置中允许后重试。",
|
||||
"settings.push.denied": "通知权限被拒绝",
|
||||
"settings.push.enableOk": "已启用推送通知",
|
||||
"settings.push.disableOk": "已关闭推送通知",
|
||||
"settings.push.failed": "启用推送失败,请重试",
|
||||
"notify.incoming.title": "收到文件",
|
||||
"notify.incoming.body": "{{sender}} 发来 {{file}}",
|
||||
"notify.transfer.doneTitle": "传输完成",
|
||||
"notify.transfer.failedTitle": "传输失败",
|
||||
"settings.account.title": "账号",
|
||||
"settings.account.signOut": "退出登录",
|
||||
"settings.desktop.title": "桌面",
|
||||
|
||||
@@ -118,6 +118,20 @@ export const zhTW: Partial<TranslationDict> = {
|
||||
"settings.offline": "離線",
|
||||
"settings.lastSeen": "上次活躍 {{time}}",
|
||||
"settings.lastSeenNever": "尚未上線",
|
||||
"settings.push.title": "推播通知",
|
||||
"settings.push.hint": "頁面關閉時,新檔案、訊息與傳輸結果會以系統通知提醒;頁面開啟時仍走應用內提示。",
|
||||
"settings.push.enable": "啟用推播",
|
||||
"settings.push.enabled": "已啟用",
|
||||
"settings.push.disable": "關閉推播",
|
||||
"settings.push.deniedHint": "通知權限已被瀏覽器拒絕,請在瀏覽器的網站設定中允許後重試。",
|
||||
"settings.push.denied": "通知權限被拒絕",
|
||||
"settings.push.enableOk": "已啟用推播通知",
|
||||
"settings.push.disableOk": "已關閉推播通知",
|
||||
"settings.push.failed": "啟用推播失敗,請重試",
|
||||
"notify.incoming.title": "收到檔案",
|
||||
"notify.incoming.body": "{{sender}} 傳來 {{file}}",
|
||||
"notify.transfer.doneTitle": "傳輸完成",
|
||||
"notify.transfer.failedTitle": "傳輸失敗",
|
||||
"settings.account.title": "帳號",
|
||||
"settings.account.signOut": "登出",
|
||||
"settings.desktop.title": "桌面",
|
||||
|
||||
@@ -43,6 +43,9 @@ interface DesktopBridge
|
||||
SaveDownload: (name: string, data: string) => Promise<string>;
|
||||
ChooseDownloadDir: (title: string) => Promise<string>;
|
||||
EffectiveDownloadDir: () => Promise<string>;
|
||||
// 弹原生系统通知(macOS UNUserNotificationCenter / Windows toast)。标题、正文
|
||||
// 已由前端本地化。
|
||||
ShowNotification: (title: string, body: string) => Promise<void>;
|
||||
}
|
||||
|
||||
// 桌面剪贴板自动同步开关,默认开;由设置页通过 setClipboardSyncEnabled 调整。
|
||||
@@ -137,6 +140,21 @@ export async function ensureDeviceName(): Promise<void>
|
||||
catch { /* 保留为空,回退到 /setup 手动命名 */ }
|
||||
}
|
||||
|
||||
// notifyNativeIfBackground:桌面端窗口非前台时,弹一条原生系统通知。窗口在前台
|
||||
// (可见且聚焦)时为 no-op——此刻应用内 UI 已呈现该事件,符合「页面打开用应用内
|
||||
// 提示,否则系统通知」。浏览器里 isDesktop()=false,始终 no-op(Web 的后台通知走
|
||||
// 服务端 Web Push)。title / body 须由调用方先用 t() 本地化。
|
||||
export function notifyNativeIfBackground(title: string, body: string): void
|
||||
{
|
||||
const app = bridge();
|
||||
if (!isDesktop() || !app) { return; }
|
||||
const foreground = typeof document !== "undefined"
|
||||
&& document.visibilityState === "visible"
|
||||
&& document.hasFocus();
|
||||
if (foreground) { return; }
|
||||
void app.ShowNotification(title, body).catch(() => { /* 通知失败不影响主流程 */ });
|
||||
}
|
||||
|
||||
// initDesktopMenuBridge 把 Go 菜单栏发来的事件接到前端(如「设置」→ 路由跳转)。
|
||||
// 仅桌面端生效;浏览器里 isDesktop()=false 直接返回,对 Web 零影响。
|
||||
export function initDesktopMenuBridge(onSettings: () => void): void
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { apiFetch } from "./api";
|
||||
import { isDesktop } from "./desktop";
|
||||
import { getLocale } from "../i18n";
|
||||
import { useAppStore } from "../store";
|
||||
|
||||
// Web Push 订阅管理。仅浏览器 / PWA——桌面壳走原生通知,不在此列。
|
||||
//
|
||||
// 分工:「页面打开→应用内 toast,页面关闭→系统通知」的判定在服务端(Hub.SendTo
|
||||
// 投递失败即推 Web Push,见后端 internal/push)。前端这里只做三件事:把本设备的
|
||||
// 推送端点登记到服务端(按设备名定位收件设备)、开关订阅、登录后重新登记。
|
||||
|
||||
interface VapidKeyResp
|
||||
{
|
||||
enabled: boolean;
|
||||
public_key: string;
|
||||
}
|
||||
|
||||
export interface PushState
|
||||
{
|
||||
supported: boolean;
|
||||
permission: NotificationPermission; // "default" | "granted" | "denied"
|
||||
subscribed: boolean; // 浏览器已持有 pushManager 订阅
|
||||
}
|
||||
|
||||
// pushSupported:需 SW + PushManager + Notification 三者俱全、非桌面壳、且为 prod
|
||||
// 构建(SW 仅在 prod 注册,见 main.tsx;dev 下无 SW,serviceWorker.ready 永不
|
||||
// resolve)。任一不满足即视为不支持,设置页隐藏入口。
|
||||
export function pushSupported(): boolean
|
||||
{
|
||||
return import.meta.env.PROD
|
||||
&& !isDesktop()
|
||||
&& typeof navigator !== "undefined"
|
||||
&& "serviceWorker" in navigator
|
||||
&& typeof window !== "undefined"
|
||||
&& "PushManager" in window
|
||||
&& "Notification" in window;
|
||||
}
|
||||
|
||||
function permissionNow(): NotificationPermission
|
||||
{
|
||||
return typeof Notification !== "undefined" ? Notification.permission : "default";
|
||||
}
|
||||
|
||||
async function registration(): Promise<ServiceWorkerRegistration | null>
|
||||
{
|
||||
if (!pushSupported()) { return null; }
|
||||
try { return await navigator.serviceWorker.ready; }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
async function existingSubscription(): Promise<PushSubscription | null>
|
||||
{
|
||||
const reg = await registration();
|
||||
if (!reg) { return null; }
|
||||
try { return await reg.pushManager.getSubscription(); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
// currentPushState:供设置页初始化展示当前订阅 / 权限状态。
|
||||
export async function currentPushState(): Promise<PushState>
|
||||
{
|
||||
if (!pushSupported())
|
||||
{
|
||||
return { supported: false, permission: "default", subscribed: false };
|
||||
}
|
||||
const sub = await existingSubscription();
|
||||
return { supported: true, permission: permissionNow(), subscribed: sub !== null };
|
||||
}
|
||||
|
||||
async function fetchVapidKey(): Promise<VapidKeyResp | null>
|
||||
{
|
||||
try
|
||||
{
|
||||
const r = await apiFetch("/api/push/vapid-key");
|
||||
if (!r.ok) { return null; }
|
||||
return await r.json() as VapidKeyResp;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
// postSubscription:把浏览器订阅 + 当前 locale 登记到服务端(apiFetch 带上
|
||||
// X-Device-Name,服务端按设备名归属)。服务端以 endpoint 的哈希为主键 upsert,
|
||||
// 故重复登记 / 换用户 / locale 变更都幂等覆盖。
|
||||
async function postSubscription(sub: PushSubscription): Promise<boolean>
|
||||
{
|
||||
const json = sub.toJSON();
|
||||
if (!json.endpoint || !json.keys?.p256dh || !json.keys?.auth) { return false; }
|
||||
try
|
||||
{
|
||||
const r = await apiFetch("/api/push/subscribe", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
endpoint: json.endpoint,
|
||||
keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },
|
||||
locale: getLocale(),
|
||||
}),
|
||||
});
|
||||
return r.ok;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
async function deleteServerSubscription(endpoint: string): Promise<void>
|
||||
{
|
||||
try
|
||||
{
|
||||
await apiFetch("/api/push/subscribe", {
|
||||
method: "DELETE",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ endpoint }),
|
||||
});
|
||||
}
|
||||
catch { /* ignore:服务端订阅清理失败只是体验降级 */ }
|
||||
}
|
||||
|
||||
// enablePush:用户在设置里开启。请求通知权限 → 创建(或复用)浏览器订阅 → 登记
|
||||
// 服务端。返回最终状态;权限被拒 / 服务端未配置 VAPID / 订阅失败时 subscribed=false。
|
||||
export async function enablePush(): Promise<PushState>
|
||||
{
|
||||
if (!pushSupported())
|
||||
{
|
||||
return { supported: false, permission: "default", subscribed: false };
|
||||
}
|
||||
|
||||
let perm = permissionNow();
|
||||
if (perm === "default")
|
||||
{
|
||||
try { perm = await Notification.requestPermission(); }
|
||||
catch { perm = permissionNow(); }
|
||||
}
|
||||
useAppStore.getState().setPushPermission(perm);
|
||||
if (perm !== "granted")
|
||||
{
|
||||
return { supported: true, permission: perm, subscribed: false };
|
||||
}
|
||||
|
||||
const vapid = await fetchVapidKey();
|
||||
if (!vapid?.enabled || !vapid.public_key)
|
||||
{
|
||||
return { supported: true, permission: perm, subscribed: false };
|
||||
}
|
||||
|
||||
const reg = await registration();
|
||||
if (!reg) { return { supported: true, permission: perm, subscribed: false }; }
|
||||
|
||||
let sub = await reg.pushManager.getSubscription();
|
||||
if (!sub)
|
||||
{
|
||||
try
|
||||
{
|
||||
sub = await reg.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(vapid.public_key),
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
return { supported: true, permission: perm, subscribed: false };
|
||||
}
|
||||
}
|
||||
|
||||
const ok = await postSubscription(sub);
|
||||
useAppStore.getState().setPushSubscribed(ok);
|
||||
return { supported: true, permission: perm, subscribed: ok };
|
||||
}
|
||||
|
||||
// disablePush:用户在设置里关闭。删服务端 + 退订浏览器,使再次登录的 resyncPush
|
||||
// 不会自动恢复(浏览器无订阅即视为用户不想要)。
|
||||
export async function disablePush(): Promise<PushState>
|
||||
{
|
||||
const sub = await existingSubscription();
|
||||
if (sub)
|
||||
{
|
||||
await deleteServerSubscription(sub.endpoint);
|
||||
try { await sub.unsubscribe(); }
|
||||
catch { /* ignore */ }
|
||||
}
|
||||
useAppStore.getState().setPushSubscribed(false);
|
||||
return { supported: pushSupported(), permission: permissionNow(), subscribed: false };
|
||||
}
|
||||
|
||||
// resyncPush:登录后(root effect 内)调用。若浏览器已有订阅且权限在握,把它重新
|
||||
// 登记到当前用户名下——让「同一浏览器换用户登录」「endpoint 轮换」「切换 locale」
|
||||
// 自愈,且无需再弹权限。无订阅则不动(用户从未开启推送)。fire-and-forget。
|
||||
export async function resyncPush(): Promise<void>
|
||||
{
|
||||
if (!pushSupported() || permissionNow() !== "granted") { return; }
|
||||
const sub = await existingSubscription();
|
||||
if (!sub) { return; }
|
||||
const ok = await postSubscription(sub);
|
||||
useAppStore.getState().setPushSubscribed(ok);
|
||||
}
|
||||
|
||||
// urlBase64ToUint8Array:把 VAPID base64url 公钥转成 applicationServerKey 需要的
|
||||
// 字节数组(标准 Web Push 样板)。
|
||||
function urlBase64ToUint8Array(base64: string): Uint8Array<ArrayBuffer>
|
||||
{
|
||||
const padding = "=".repeat((4 - (base64.length % 4)) % 4);
|
||||
const b64 = (base64 + padding).replace(/-/g, "+").replace(/_/g, "/");
|
||||
const raw = atob(b64);
|
||||
// Back the view with a concrete ArrayBuffer (not ArrayBufferLike) so it
|
||||
// satisfies BufferSource for applicationServerKey under TS 5.7 strict typing.
|
||||
const out = new Uint8Array(new ArrayBuffer(raw.length));
|
||||
for (let i = 0; i < raw.length; i += 1) { out[i] = raw.charCodeAt(i); }
|
||||
return out;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { logout } from "../features/auth/auth";
|
||||
import { uploadClipboard } from "../features/clipboard/clipboard";
|
||||
import { onNativeClipboard } from "../net/desktop";
|
||||
import { startHub } from "../features/transfer/hub";
|
||||
import { resyncPush } from "../net/push";
|
||||
import { refreshICEServers, stopICEServerRefresh } from "../features/transfer/iceServers";
|
||||
import { t, type Locale } from "../i18n";
|
||||
import { Callout, IconButton, Tooltip } from "../ui/primitives";
|
||||
@@ -47,6 +48,9 @@ function RootLayout()
|
||||
startHub(ctrl.signal);
|
||||
// 预取 Cloudflare TURN 凭据(或 STUN 回退),首次 WebRTC 同步可用。
|
||||
void refreshICEServers();
|
||||
// 已开启推送的浏览器:登录后把订阅重新登记到当前用户名下(自愈换用户 /
|
||||
// endpoint 轮换 / locale 变更);未开启或桌面端为 no-op。
|
||||
void resyncPush();
|
||||
// 桌面:本机复制 → 上传云端(复用 uploadClipboard 链路;浏览器里为 no-op)。
|
||||
// 上传失败静默——不打断用户,下次复制再试。
|
||||
const offNativeClipboard = onNativeClipboard((text) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Anchor,
|
||||
Container,
|
||||
@@ -8,11 +8,18 @@ import {
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { createFileRoute, Link, redirect, useNavigate } from "@tanstack/react-router";
|
||||
import { LogOut, Trash2 } from "lucide-react";
|
||||
import { Bell, LogOut, Trash2 } from "lucide-react";
|
||||
import { logout, syncWebDeviceName } from "../features/auth/auth";
|
||||
import { DesktopSettings } from "../features/desktop/DesktopSettings";
|
||||
import { isDesktop, persistDesktopDeviceName } from "../net/desktop";
|
||||
import { apiFetch } from "../net/api";
|
||||
import {
|
||||
currentPushState,
|
||||
disablePush,
|
||||
enablePush,
|
||||
pushSupported,
|
||||
type PushState,
|
||||
} from "../net/push";
|
||||
import { useAppStore, type DeviceInfo } from "../store";
|
||||
import { t } from "../i18n";
|
||||
import { formatRelative, isAsciiDeviceName } from "../utils/format";
|
||||
@@ -236,6 +243,8 @@ function SettingsPage()
|
||||
|
||||
{isDesktop() && <DesktopSettings />}
|
||||
|
||||
{pushSupported() && <PushPanel />}
|
||||
|
||||
<Panel title={t("settings.peers.title")}>
|
||||
{peerDevices.length === 0 ? (
|
||||
<Text size="sm" c="dimmed">{t("settings.peers.empty")}</Text>
|
||||
@@ -279,6 +288,89 @@ function SettingsPage()
|
||||
);
|
||||
}
|
||||
|
||||
// PushPanel:浏览器 / PWA 的 Web Push 开关。仅 pushSupported() 为真时渲染(桌面壳
|
||||
// 与 dev 均为 false——桌面走原生通知、dev 无 SW)。订阅权威态在浏览器 pushManager,
|
||||
// 挂载时用 currentPushState 读取一次。
|
||||
function PushPanel()
|
||||
{
|
||||
const [ state, setState ] = useState<PushState | null>(null);
|
||||
const [ busy, setBusy ] = useState(false);
|
||||
|
||||
useEffect(() =>
|
||||
{
|
||||
let alive = true;
|
||||
void currentPushState().then((s) => { if (alive) { setState(s); } });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const handleEnable = async () =>
|
||||
{
|
||||
setBusy(true);
|
||||
try
|
||||
{
|
||||
const s = await enablePush();
|
||||
setState(s);
|
||||
if (s.subscribed) { toast.ok(t("settings.push.enableOk")); }
|
||||
else if (s.permission === "denied") { toast.warn(t("settings.push.denied")); }
|
||||
else { toast.error(t("settings.push.failed")); }
|
||||
}
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
const handleDisable = async () =>
|
||||
{
|
||||
setBusy(true);
|
||||
try
|
||||
{
|
||||
const s = await disablePush();
|
||||
setState(s);
|
||||
toast.ok(t("settings.push.disableOk"));
|
||||
}
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
const subscribed = state?.subscribed ?? false;
|
||||
const denied = state?.permission === "denied";
|
||||
|
||||
return (
|
||||
<Panel title={t("settings.push.title")}>
|
||||
<Stack gap="sm">
|
||||
<Text size="sm" c="dimmed">{t("settings.push.hint")}</Text>
|
||||
{denied && !subscribed && (
|
||||
<Text size="sm" style={{ color: "var(--state-error)" }}>
|
||||
{t("settings.push.deniedHint")}
|
||||
</Text>
|
||||
)}
|
||||
<Group>
|
||||
{subscribed ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={<Bell size={14} />}
|
||||
loading={busy}
|
||||
onClick={handleDisable}
|
||||
>
|
||||
{t("settings.push.disable")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
leftIcon={<Bell size={14} />}
|
||||
loading={busy}
|
||||
disabled={denied}
|
||||
onClick={handleEnable}
|
||||
>
|
||||
{t("settings.push.enable")}
|
||||
</Button>
|
||||
)}
|
||||
{subscribed && (
|
||||
<Badge tone="online">{t("settings.push.enabled")}</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Stack>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function PeerRow(props: { device: DeviceInfo; removing: boolean; onRemove: () => void })
|
||||
{
|
||||
const { device, removing, onRemove } = props;
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createClipboardSlice } from "./slices/clipboard";
|
||||
import { createUiSlice } from "./slices/ui";
|
||||
import { createThemeSlice } from "./slices/theme";
|
||||
import { createLocaleSlice } from "./slices/locale";
|
||||
import { createPushSlice } from "./slices/push";
|
||||
|
||||
export const useAppStore = create<AppState>()((...a) =>
|
||||
({
|
||||
@@ -19,6 +20,7 @@ export const useAppStore = create<AppState>()((...a) =>
|
||||
...createUiSlice(...a),
|
||||
...createThemeSlice(...a),
|
||||
...createLocaleSlice(...a),
|
||||
...createPushSlice(...a),
|
||||
}));
|
||||
|
||||
// 重新导出所有 type 与 helper,保证现有 `from "./store"` import 仍可解析。
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { StateCreator } from "zustand";
|
||||
import type { AppState } from "../types";
|
||||
|
||||
export type PushSlice = Pick<
|
||||
AppState,
|
||||
"pushPermission" | "pushSubscribed" | "setPushPermission" | "setPushSubscribed"
|
||||
>;
|
||||
|
||||
function initialPermission(): NotificationPermission
|
||||
{
|
||||
return typeof Notification !== "undefined" ? Notification.permission : "default";
|
||||
}
|
||||
|
||||
// Web Push 的 UI 状态。订阅的权威来源是浏览器 pushManager(currentPushState 据此
|
||||
// 读出),这里只是为设置页提供响应式镜像,避免每次都 await 异步查询。
|
||||
export const createPushSlice: StateCreator<AppState, [], [], PushSlice> = (set) =>
|
||||
({
|
||||
pushPermission: initialPermission(),
|
||||
pushSubscribed: false,
|
||||
|
||||
setPushPermission: (p) => { set({ pushPermission: p }); },
|
||||
setPushSubscribed: (b) => { set({ pushSubscribed: b }); },
|
||||
});
|
||||
@@ -166,4 +166,12 @@ export interface AppState
|
||||
// ---- locale slice ----
|
||||
locale: Locale;
|
||||
setLocale: (l: Locale) => void;
|
||||
|
||||
// ---- push slice ----
|
||||
// Web Push 的响应式镜像(权威态在浏览器 pushManager)。仅浏览器 / PWA 有意义,
|
||||
// 桌面壳走原生通知不读这两项。
|
||||
pushPermission: NotificationPermission;
|
||||
pushSubscribed: boolean;
|
||||
setPushPermission: (p: NotificationPermission) => void;
|
||||
setPushSubscribed: (b: boolean) => void;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user