|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useEffect } from "react"; |
| 4 | +import { useRouter } from "next/navigation"; |
| 5 | +import { siteConfig } from "@/lib/siteConfig"; |
| 6 | + |
| 7 | +/** |
| 8 | + * 日记提醒:当天 17:00 起,只要还没有写日记,就用浏览器原生通知反复提醒。 |
| 9 | + * |
| 10 | + * 提醒时刻:17:00、17:20、17:40 …… 固定每 20 分钟一次,直到当天日记被创建。 |
| 11 | + * |
| 12 | + * 设计取舍: |
| 13 | + * 1. 用「轮询当前走到了哪个提醒点」而不是给每个点精确 setTimeout —— |
| 14 | + * 浏览器会节流后台标签页的定时器(切走后最快 1 分钟才跳一次), |
| 15 | + * 精确计时在后台并不可靠;按提醒点去重则节流后既不漏提醒也不重复提醒。 |
| 16 | + * 2. 自带原生 fetch,刻意不用 lib/axios —— 那个实例的响应拦截器在请求失败时 |
| 17 | + * 会 showErrorToast,而后端未启动时的静默探测不该弹错误提示打扰用户。 |
| 18 | + * 3. 只在本地(非静态站)工作:日记数据不上静态站,静态构建下无从判断 |
| 19 | + * 「今天有没有日记」。日记接口不需要登录(personal 布局、DiaryClient |
| 20 | + * 都没有登录门槛),因此这里不做登录态判断,未登录也照常提醒。 |
| 21 | + * 4. 授权按钮用命令式 DOM 创建,而不是 React 状态:Notification.permission |
| 22 | + * 只能在客户端读,写进 state 会造成 SSR 与首帧不一致, |
| 23 | + * 而项目启用的 react-hooks/set-state-in-effect 也不允许在 effect 里同步 setState。 |
| 24 | + */ |
| 25 | + |
| 26 | +/** 起始提醒时刻:17:00 */ |
| 27 | +const START_HOUR = 17; |
| 28 | +/** 提醒间隔:20 分钟 */ |
| 29 | +const INTERVAL_MS = 20 * 60_000; |
| 30 | +/** 轮询间隔:30 秒 */ |
| 31 | +const TICK_MS = 30_000; |
| 32 | +/** localStorage 键前缀,按日期分桶,跨天自动失效 */ |
| 33 | +const STORAGE_PREFIX = "diary-reminder:"; |
| 34 | +/** 点击通知后跳转的日记页 */ |
| 35 | +const DIARY_PATH = "/personal/diary"; |
| 36 | + |
| 37 | +/** 本地时区的 YYYY-MM-DD(toISOString 走 UTC,跨时区会算错日期) */ |
| 38 | +function toDateStr(d: Date): string { |
| 39 | + const pad = (n: number) => String(n).padStart(2, "0"); |
| 40 | + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; |
| 41 | +} |
| 42 | + |
| 43 | +/** 当前时刻已到达的最近一个提醒点;未到 17:00 返回 null */ |
| 44 | +function latestDueSlot(now: Date): Date | null { |
| 45 | + const first = new Date(now); |
| 46 | + first.setHours(START_HOUR, 0, 0, 0); |
| 47 | + if (now.getTime() < first.getTime()) return null; |
| 48 | + |
| 49 | + const k = Math.floor((now.getTime() - first.getTime()) / INTERVAL_MS); |
| 50 | + return new Date(first.getTime() + k * INTERVAL_MS); |
| 51 | +} |
| 52 | + |
| 53 | +/** 读取某天已提醒过的提醒点时间戳 */ |
| 54 | +function readNotified(day: string): number[] { |
| 55 | + try { |
| 56 | + const raw = localStorage.getItem(STORAGE_PREFIX + day); |
| 57 | + const parsed: unknown = raw ? JSON.parse(raw) : []; |
| 58 | + return Array.isArray(parsed) |
| 59 | + ? parsed.filter((v): v is number => typeof v === "number") |
| 60 | + : []; |
| 61 | + } catch { |
| 62 | + return []; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** 记录某天某个提醒点已提醒 */ |
| 67 | +function markNotified(day: string, slotMs: number): void { |
| 68 | + try { |
| 69 | + const list = readNotified(day); |
| 70 | + if (!list.includes(slotMs)) list.push(slotMs); |
| 71 | + localStorage.setItem(STORAGE_PREFIX + day, JSON.stringify(list)); |
| 72 | + } catch { |
| 73 | + /* 隐私模式下 localStorage 可能不可用:忽略,退化为本次会话内去重 */ |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * 静默查询今天是否已有日记。 |
| 79 | + * 异常一律向上抛,由调用方吞掉 —— 探测失败不该有任何可见反馈。 |
| 80 | + */ |
| 81 | +async function hasDiaryToday(day: string): Promise<boolean> { |
| 82 | + const token = localStorage.getItem("token"); |
| 83 | + const res = await fetch(`http://${siteConfig.backUrl}/api/diary`, { |
| 84 | + headers: token ? { Authorization: `Bearer ${token}` } : undefined, |
| 85 | + }); |
| 86 | + if (!res.ok) throw new Error(`HTTP ${res.status}`); |
| 87 | + |
| 88 | + const body = (await res.json()) as { |
| 89 | + code?: number; |
| 90 | + message?: string; |
| 91 | + data?: { recordDate?: string }[]; |
| 92 | + }; |
| 93 | + if (body?.code !== 1) throw new Error(body?.message ?? `code ${body?.code}`); |
| 94 | + |
| 95 | + return (body.data ?? []).some((d) => d?.recordDate === day); |
| 96 | +} |
| 97 | + |
| 98 | +/** |
| 99 | + * 发原生通知,点击跳到日记页。 |
| 100 | + * |
| 101 | + * 跳转回调由调用方用 router.push 提供:本函数挂在通知的 onclick 上, |
| 102 | + * 不是 React 事件处理器,拿不到 router,所以从外面传进来。 |
| 103 | + */ |
| 104 | +function notifyDiaryMissing(openDiary: () => void): void { |
| 105 | + const n = new Notification("今天还没写日记", { |
| 106 | + body: "随手记两句今天的活动吧 —— 点这里打开日记页。", |
| 107 | + icon: "/logo.png", |
| 108 | + // 刻意不设 tag:带相同 tag 的新通知会被 Chrome 静默替换、不再弹出横幅, |
| 109 | + // 而自动提醒的意义正是每 20 分钟都要真正提醒到人(已实测验证过这一点) |
| 110 | + }); |
| 111 | + n.onclick = () => { |
| 112 | + window.focus(); |
| 113 | + n.close(); |
| 114 | + // 读 pathname 是安全的,仅用 href 赋值才会触发 no-location-assign-relative-destination |
| 115 | + if (window.location.pathname !== DIARY_PATH) openDiary(); |
| 116 | + }; |
| 117 | +} |
| 118 | + |
| 119 | +/** |
| 120 | + * 挂载一次性授权按钮。 |
| 121 | + * |
| 122 | + * 浏览器规定 requestPermission 必须由用户手势触发,页面加载时自动请求会被忽略, |
| 123 | + * 所以这里给一个显式入口;授权后按钮自行消失并回调一次,让提醒立刻生效。 |
| 124 | + * 位置取左下角,避开右下角的看板娘与右上角的 toast。 |
| 125 | + */ |
| 126 | +function mountPermissionButton(onGranted: () => void): () => void { |
| 127 | + const btn = document.createElement("button"); |
| 128 | + btn.type = "button"; |
| 129 | + btn.textContent = "🔔 开启日记提醒"; |
| 130 | + btn.style.cssText = |
| 131 | + "position:fixed;left:16px;bottom:16px;z-index:9998;padding:8px 14px;border:none;border-radius:9999px;background:rgba(99,102,241,0.92);backdrop-filter:blur(8px);color:#fff;font-size:12px;font-weight:700;line-height:1.4;cursor:pointer;box-shadow:0 4px 16px rgba(99,102,241,0.35);font-family:system-ui,sans-serif;"; |
| 132 | + |
| 133 | + btn.onclick = () => { |
| 134 | + btn.remove(); |
| 135 | + Notification.requestPermission() |
| 136 | + .then((permission) => { |
| 137 | + if (permission === "granted") onGranted(); |
| 138 | + }) |
| 139 | + .catch(() => { |
| 140 | + /* 授权失败:保持安静,用户可刷新后重试 */ |
| 141 | + }); |
| 142 | + }; |
| 143 | + |
| 144 | + document.body.appendChild(btn); |
| 145 | + return () => btn.remove(); |
| 146 | +} |
| 147 | + |
| 148 | +export default function DiaryReminder() { |
| 149 | + const router = useRouter(); |
| 150 | + |
| 151 | + useEffect(() => { |
| 152 | + const isStatic = process.env.NEXT_PUBLIC_IS_STATIC === "true"; |
| 153 | + if (isStatic) return; |
| 154 | + if (typeof Notification === "undefined") return; |
| 155 | + |
| 156 | + /** 本次会话已处理过的提醒点,避免同一个点反复打接口 */ |
| 157 | + let handledSlot = 0; |
| 158 | + let disposed = false; |
| 159 | + |
| 160 | + const tick = async () => { |
| 161 | + if (disposed) return; |
| 162 | + |
| 163 | + const now = new Date(); |
| 164 | + const slot = latestDueSlot(now); |
| 165 | + if (!slot) return; |
| 166 | + |
| 167 | + const slotMs = slot.getTime(); |
| 168 | + if (slotMs === handledSlot) return; |
| 169 | + |
| 170 | + const day = toDateStr(now); |
| 171 | + |
| 172 | + // 该提醒点今天已经提醒过(含本次会话之前的提醒),不再重复 |
| 173 | + if (readNotified(day).includes(slotMs)) { |
| 174 | + handledSlot = slotMs; |
| 175 | + return; |
| 176 | + } |
| 177 | + |
| 178 | + // 未授权就发不出通知,也不必去探测日记 |
| 179 | + if (Notification.permission !== "granted") return; |
| 180 | + |
| 181 | + handledSlot = slotMs; |
| 182 | + |
| 183 | + try { |
| 184 | + if (await hasDiaryToday(day)) return; |
| 185 | + } catch { |
| 186 | + // 后端不可达 / 响应异常:静默跳过,等下一个提醒点再试 |
| 187 | + return; |
| 188 | + } |
| 189 | + if (disposed) return; |
| 190 | + |
| 191 | + try { |
| 192 | + notifyDiaryMissing(() => router.push(DIARY_PATH)); |
| 193 | + } catch { |
| 194 | + // 通知构造失败(例如系统禁用了通知):不留痕迹 |
| 195 | + return; |
| 196 | + } |
| 197 | + markNotified(day, slotMs); |
| 198 | + }; |
| 199 | + |
| 200 | + void tick(); |
| 201 | + const timer = window.setInterval(() => void tick(), TICK_MS); |
| 202 | + const unmountButton = |
| 203 | + Notification.permission === "default" |
| 204 | + ? mountPermissionButton(() => void tick()) |
| 205 | + : null; |
| 206 | + |
| 207 | + return () => { |
| 208 | + disposed = true; |
| 209 | + window.clearInterval(timer); |
| 210 | + unmountButton?.(); |
| 211 | + }; |
| 212 | + }, [router]); |
| 213 | + |
| 214 | + return null; |
| 215 | +} |
0 commit comments