dsh-sitmax 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,1536 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-sitmax",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ // dsh-sitmax client plugin: anti-sedentary running-track HUD.
8
+ // - shell.overlay: top-center stadium running track with a small runner moving
9
+ // along it as the 15-minute cycle progresses + the sitting time in the middle.
10
+ // - Reminder popup every 30 minutes of sitting with break mode, snooze and
11
+ // stats; desktop notification + chime when enabled.
12
+ // - Keyboard/mouse activity detection: auto-pause when idle, resume on return,
13
+ // count as a break when away longer than the break duration.
14
+ // - Two settings sections: configuration (persisted to localStorage) and a
15
+ // 7-day daily sitting report.
16
+ const React = require('react')
17
+
18
+ const CSS = '\n.maxm-badge{position:fixed;top:6px;left:50%;transform:translateX(-50%);z-index:4000;display:flex;flex-direction:row;align-items:center;gap:8px;cursor:grab;pointer-events:auto;user-select:none}\n.maxm-badge::before,.maxm-badge::after{content:"";position:absolute;top:0;bottom:0;width:44px;z-index:1}\n.maxm-badge::before{left:-42px}\n.maxm-badge::after{right:-42px}\n.maxm-svg{width:118px;height:auto;display:none;filter:drop-shadow(0 1px 5px rgba(0,0,0,.35))}\n.maxm-badge:hover .maxm-svg{display:block}\n.maxm-badge:not(:hover) .maxm-act-btn{display:none}\n.maxm-mini{width:30px;height:30px;display:block;flex:none}\n.maxm-badge:hover .maxm-mini{display:none}\n.maxm-mini-track{fill:none;stroke:var(--dsw-alias-label-primary,#e8e8ea);opacity:.25;stroke-width:4}\n.maxm-mini-fill{fill:none;stroke:url(#maxmSandMini);stroke-width:4;stroke-linecap:round;transform:rotate(-90deg);transform-origin:center;transition:stroke-dashoffset 1s linear}\n.maxm-break .maxm-mini-track{stroke:var(--dsw-alias-state-success-primary,#2ecc71);opacity:.5}\n.maxm-overdue .maxm-mini-track{stroke:var(--dsw-alias-state-warn-primary,#f5a623);opacity:.5}\n.maxm-offduty .maxm-mini{opacity:.45}\n.maxm-glow .maxm-svg{filter:drop-shadow(0 0 10px rgba(251,191,36,.55))}\n.maxm-act-btn{position:absolute;top:50%;margin-top:-13.5px;z-index:2;width:27px;height:27px;border-radius:50%;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.08);color:var(--dsw-alias-label-secondary,#b8b8c0);font-size:12px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;flex:none;font-family:inherit;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);transition:background .2s,color .2s,transform .1s}\n.maxm-act-btn.maxm-act-left{left:-35px}\n.maxm-act-btn.maxm-act-right{right:-35px}\n.maxm-act-btn:hover{background:rgba(255,255,255,.2);color:var(--dsw-alias-label-primary,#fff)}\n.maxm-act-btn:active{transform:scale(.92)}\n.maxm-time-text{fill:var(--dsw-alias-label-secondary,#c9c9d1);font-size:11px;font-weight:600;font-family:inherit;text-anchor:middle;letter-spacing:.03em;font-variant-numeric:tabular-nums;pointer-events:none}\n.maxm-overdue .maxm-time-text{fill:var(--dsw-alias-state-warn-primary,#f5a623)}\n.maxm-break .maxm-time-text{fill:var(--dsw-alias-state-success-primary,#2ecc71)}\n.maxm-offduty .maxm-time-text{fill:var(--dsw-alias-label-secondary,#9aa0ab)}\n.maxm-track{fill:none;stroke:var(--dsw-alias-label-primary,#e8e8ea);opacity:.22;stroke-width:8;stroke-linecap:round;stroke-linejoin:round}\n.maxm-lane{fill:none;stroke:var(--dsw-alias-label-primary,#e8e8ea);opacity:.13;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round}\n.maxm-break .maxm-track{stroke:var(--dsw-alias-state-success-primary,#2ecc71);opacity:.5}\n.maxm-overdue .maxm-track{stroke:var(--dsw-alias-state-warn-primary,#f5a623);opacity:.5}\n.maxm-fill{fill:none;stroke:url(#maxmSand);stroke-width:8;stroke-linecap:round;stroke-linejoin:round;transition:stroke-dashoffset 1s linear}\n.maxm-head{transition:transform 1s linear}\n.maxm-runner{filter:drop-shadow(0 0 2px rgba(10,11,14,.85));animation:maxmBob .55s ease-in-out infinite alternate}\n@keyframes maxmBob{from{transform:scale(1.6) translateY(0)}to{transform:scale(1.6) translateY(-1.1px)}}\n.maxm-r-head{fill:var(--dsw-alias-label-primary,#f0f0f2)}\n.maxm-r-body,.maxm-r-arm,.maxm-r-leg{stroke:var(--dsw-alias-label-primary,#f0f0f2);stroke-width:1.7;stroke-linecap:round;fill:none}\n.maxm-modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);z-index:5000;width:320px;padding:18px 18px 16px;border-radius:22px;background:var(--dsw-alias-bg-overlay,rgba(30,32,38,.84));border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));backdrop-filter:blur(24px) saturate(160%);-webkit-backdrop-filter:blur(24px) saturate(160%);box-shadow:0 24px 70px rgba(0,0,0,.45),inset 0 1px 0 rgba(255,255,255,.14);color:var(--dsw-alias-label-primary,#eee);pointer-events:auto;animation:maxmPop .28s cubic-bezier(.2,1.4,.4,1)}\n@keyframes maxmPop{from{opacity:0;transform:translate(-50%,-46%) scale(.92)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}\n.maxm-m-title{font-size:16px;font-weight:700;margin-bottom:8px}\n.maxm-m-break-title{color:var(--dsw-alias-state-success-primary,#2ecc71)}\n.maxm-m-body{font-size:13px;line-height:1.65;color:var(--dsw-alias-label-secondary,#b8b8c0);margin-bottom:8px}\n.maxm-m-stats{font-size:11px;color:var(--dsw-alias-label-secondary,#8f8f98);margin-bottom:12px;opacity:.9}\n.maxm-m-count{font-size:34px;font-weight:800;font-variant-numeric:tabular-nums;color:var(--dsw-alias-state-success-primary,#2ecc71);margin-bottom:10px;letter-spacing:.04em}\n.maxm-m-tips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}\n.maxm-m-tips span{font-size:12px;padding:3px 8px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.12));color:var(--dsw-alias-label-secondary,#b8b8c0)}\n.maxm-m-actions{display:flex;flex-direction:column;gap:8px}\n.maxm-btn{width:100%;padding:9px 12px;border-radius:10px;border:none;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit}\n.maxm-btn-primary{background:var(--dsw-alias-brand-primary,#4f8cff);color:#fff}\n.maxm-btn-ghost{background:transparent;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.2));color:var(--dsw-alias-label-primary,#eee)}\n.maxm-page{display:flex;flex-direction:column;gap:10px;padding:4px 2px;max-width:480px}\n.maxm-page-title{font-size:17px;font-weight:700;color:var(--dsw-alias-label-primary,#eee)}\n.maxm-page-sub{font-size:12px;color:var(--dsw-alias-label-secondary,#a6a6ad);margin-top:-6px;margin-bottom:4px}\n.maxm-set-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08))}\n.maxm-set-lab{display:flex;flex-direction:column;gap:2px;font-size:13px;color:var(--dsw-alias-label-primary,#eee);cursor:pointer}\n.maxm-set-hint{font-size:11px;color:var(--dsw-alias-label-secondary,#8f8f98)}\n.maxm-set-num{width:76px;padding:6px 8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.04));color:var(--dsw-alias-label-primary,#eee);font-size:13px;text-align:center}\n.maxm-set-check{width:18px;height:18px;accent-color:var(--dsw-alias-brand-primary,#4f8cff);cursor:pointer}\n.maxm-set-actions{display:flex;flex-direction:column;gap:8px;margin-top:6px}\n.maxm-set-flash{font-size:12px;color:var(--dsw-alias-state-success-primary,#2ecc71)}\n.maxm-page-sep{height:1px;background:var(--dsw-alias-border-l1,rgba(255,255,255,.08));margin:6px 0}\n.maxm-today{display:flex;gap:8px;flex-wrap:wrap;margin:2px 0 8px}\n.maxm-today span{padding:6px 10px;border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.05));border:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08));font-size:12px;color:var(--dsw-alias-label-primary,#eee)}\n.maxm-bar-row{display:flex;align-items:center;gap:8px;padding:4px 0}\n.maxm-bar-lab{width:52px;font-size:12px;color:var(--dsw-alias-label-secondary,#a6a6ad);flex:none}\n.maxm-bar-track{flex:1;height:12px;border-radius:6px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.05));overflow:hidden}\n.maxm-bar-fill{height:100%;border-radius:6px;background:linear-gradient(90deg,#fbbf24,#b45309);min-width:2px;transition:width .5s}\n.maxm-bar-val{width:132px;font-size:11px;color:var(--dsw-alias-label-secondary,#a6a6ad);text-align:right;flex:none}\n.maxm-vtab{display:inline-flex;border:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.12));border-radius:8px;overflow:hidden;align-self:flex-start}\n.maxm-vtab button{border:none;background:transparent;color:var(--dsw-alias-label-secondary,#a6a6ad);padding:5px 14px;font-size:12px;cursor:pointer;font-family:inherit}\n.maxm-vtab .maxm-vtab-on{background:var(--dsw-alias-brand-primary,#4f8cff);color:#fff}\n.maxm-cal-head{display:flex;align-items:center;gap:8px;margin-bottom:2px}\n.maxm-cal-title{font-size:14px;font-weight:700;color:var(--dsw-alias-label-primary,#eee);min-width:96px;text-align:center}\n.maxm-cal-nav{border:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.12));background:transparent;color:var(--dsw-alias-label-secondary,#a6a6ad);border-radius:6px;padding:3px 10px;cursor:pointer;font-size:13px;line-height:1.4}\n.maxm-cal-todaybtn{margin-left:auto;font-size:11px;color:var(--dsw-alias-brand-primary,#4f8cff);background:transparent;border:none;cursor:pointer}\n.maxm-cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:4px}\n.maxm-cal-dow{font-size:10px;color:var(--dsw-alias-label-secondary,#8f8f98);text-align:center;padding:2px 0}\n.maxm-cal-cell{min-height:54px;border-radius:8px;border:1px solid transparent;padding:3px 4px;cursor:pointer;display:flex;flex-direction:column;gap:1px}\n.maxm-cal-cell:hover{border-color:var(--dsw-alias-border-l2,rgba(255,255,255,.25))}\n.maxm-cal-day{font-size:11px;color:var(--dsw-alias-label-primary,#e8e8ea);line-height:1.15}\n.maxm-cal-time{font-size:10px;color:var(--dsw-alias-label-secondary,#c9c9d1);line-height:1.15;font-variant-numeric:tabular-nums}\n.maxm-cal-sub{font-size:9px;color:var(--dsw-alias-label-secondary,#8f8f98);line-height:1.15}\n.maxm-cal-empty{background:transparent;cursor:default}\n.maxm-cal-future{opacity:.35;cursor:default}\n.maxm-cal-today{border-color:var(--dsw-alias-brand-primary,#4f8cff)}\n.maxm-cal-sel{border-color:var(--dsw-alias-state-warn-primary,#f5a623);box-shadow:0 0 0 1px var(--dsw-alias-state-warn-primary,rgba(245,166,35,.4))}\n.maxm-cal-detail{margin-top:8px;padding:10px 12px;border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.04));border:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08))}\n.maxm-cards{display:grid;grid-template-columns:repeat(2,1fr);gap:8px}\n.maxm-card{display:flex;flex-direction:column;gap:3px;padding:9px 11px;border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.05));border:1px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08))}\n.maxm-card-v{font-size:16px;font-weight:800;color:var(--dsw-alias-label-primary,#eee);font-variant-numeric:tabular-nums}\n.maxm-card-k{font-size:11px;color:var(--dsw-alias-label-secondary,#8f8f98)}\n.maxm-evs{margin-top:8px;display:flex;flex-direction:column}\n.maxm-evrow{display:flex;gap:8px;font-size:11px;padding:2px 0;color:var(--dsw-alias-label-secondary,#a6a6ad)}\n.maxm-evtime{flex:none;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary,#c9c9d1)}\n.maxm-duty{display:none;margin-top:2px}\n.maxm-badge:hover .maxm-duty{display:block}\n.maxm-offduty .maxm-duty{display:block}\n.maxm-duty-btn{font-size:10px;line-height:1.7;border:none;background:rgba(255,255,255,.07);color:var(--dsw-alias-label-secondary,#a6a6ad);border-radius:6px;padding:0 8px;cursor:pointer;font-family:inherit;letter-spacing:.05em}\n.maxm-duty-btn:hover{color:var(--dsw-alias-label-primary,#eee);background:rgba(255,255,255,.14)}\n.maxm-offduty .maxm-svg{opacity:.4}\n.maxm-offduty .maxm-head{opacity:0}\n.maxm-pv-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.65);z-index:6000;display:flex;align-items:center;justify-content:center;padding:20px}\n.maxm-pv-box{position:relative;max-width:min(780px,96vw);max-height:96vh;overflow:auto;border-radius:12px;box-shadow:0 20px 60px rgba(0,0,0,.5)}\n.maxm-pv-img{width:100%;display:block;image-rendering:auto}\n.maxm-pv-close{position:absolute;top:8px;right:8px;width:28px;height:28px;border-radius:50%;border:none;background:rgba(20,22,27,.85);color:#fff;font-size:14px;cursor:pointer;line-height:1}\n.maxm-cal-day-we{color:var(--dsw-alias-state-warn-primary,#f5a623)}\n.maxm-cal-day-ho{color:var(--dsw-alias-state-error-primary,#d64545)}\n.maxm-cal-tag{font-size:8px;margin-left:3px;padding:0 3px;border-radius:3px;background:rgba(220,68,68,.22);color:var(--dsw-alias-state-error-primary,#ff9b9b);line-height:1.5;vertical-align:top}'
19
+
20
+ const DEFAULTS = { cycleMin: 15, remindMin: 30, breakMin: 5, snoozeMin: 5, idleMin: 3, notif: true, sound: true, workH: 9, workM: 0 }
21
+ const CFG_KEY = 'dsh.sitmax.cfg.v1'
22
+ const HIST_KEY = 'dsh.sitmax.hist.v1'
23
+ const STATE_KEY = 'dsh.sitmax.state.v1'
24
+ const EVENTS_KEY = 'dsh.sitmax.events.v1'
25
+
26
+ function loadCfg() {
27
+ const c = {}
28
+ for (const k in DEFAULTS) c[k] = DEFAULTS[k]
29
+ try {
30
+ const raw = localStorage.getItem(CFG_KEY)
31
+ if (raw) {
32
+ const p = JSON.parse(raw)
33
+ for (const k in DEFAULTS) if (typeof p[k] === typeof DEFAULTS[k]) c[k] = p[k]
34
+ }
35
+ } catch (e) { }
36
+ // Core behaviors are always on (no toggles): idle auto-pause, global idle
37
+ // detection, daily auto-start, workday-only timing, away-counts-as-break.
38
+ c.idlePause = true
39
+ c.globalIdle = true
40
+ c.autoStart = true
41
+ c.workdays = true
42
+ c.autoBreak = true
43
+ return c
44
+ }
45
+
46
+ function loadHist() {
47
+ try {
48
+ const raw = localStorage.getItem(HIST_KEY)
49
+ if (raw) return JSON.parse(raw)
50
+ } catch (e) { }
51
+ return {}
52
+ }
53
+
54
+ function dateKey(ts) {
55
+ const d = new Date(ts)
56
+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
57
+ }
58
+
59
+ function fmt(ms) {
60
+ const s = Math.max(0, Math.floor(ms / 1000))
61
+ return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0')
62
+ }
63
+
64
+ /** Exact duration for event text, e.g. "4 分 32 秒" (rounding a 4m32s absence up to
65
+ * "5 分钟" made users think a break should have been credited). */
66
+ function fmtSpan(ms) {
67
+ const s = Math.max(0, Math.round(ms / 1000))
68
+ const m = Math.floor(s / 60)
69
+ const r = s % 60
70
+ if (m === 0) return r + ' 秒'
71
+ if (r === 0) return m + ' 分钟'
72
+ return m + ' 分 ' + r + ' 秒'
73
+ }
74
+
75
+ function fmtHm(ms) {
76
+ const m = Math.round(ms / 60000)
77
+ if (m < 60) return m + ' 分钟'
78
+ return Math.floor(m / 60) + ' 小时 ' + (m % 60) + ' 分'
79
+ }
80
+
81
+ // Stadium running-track path (viewBox 0 0 150 62): two straights joined by
82
+ // semicircle ends. The progress stroke reveals along it and the runner travels
83
+ // on it with getPointAtLength.
84
+ const TRACK = 'M 38,13 H 112 A 20,20 0 0 1 112,53 H 38 A 20,20 0 0 1 38,13 Z'
85
+ // Inner lane divider, so the ring reads as a running track rather than a pill.
86
+ const TRACK_INNER = 'M 42,17 H 108 A 16,16 0 0 1 108,49 H 42 A 16,16 0 0 1 42,17 Z'
87
+
88
+ exports.name = 'dsh-sitmax-client'
89
+ exports.inject = ['slots']
90
+ exports.apply = function apply(ctx) {
91
+ ctx.effect(() => {
92
+ const old = document.getElementById('dsh-sitmax-css')
93
+ if (old) old.remove()
94
+ const el = document.createElement('style')
95
+ el.id = 'dsh-sitmax-css'
96
+ el.textContent = CSS
97
+ document.head.appendChild(el)
98
+ return () => { el.remove() }
99
+ })
100
+
101
+ const CFG = loadCfg()
102
+ const HIST = loadHist()
103
+
104
+ const persistCfg = () => { try { localStorage.setItem(CFG_KEY, JSON.stringify(CFG)) } catch (e) { } }
105
+ const persistHist = () => { try { localStorage.setItem(HIST_KEY, JSON.stringify(HIST)) } catch (e) { } }
106
+
107
+ // Event log: every reminder / break / pause / reset with its cause and
108
+ // timestamp, shown in the report so the numbers are always explainable.
109
+ let EVENTS = []
110
+ try {
111
+ const rawEv = localStorage.getItem(EVENTS_KEY)
112
+ if (rawEv) EVENTS = JSON.parse(rawEv) || []
113
+ } catch (e) { }
114
+ function logEvent(type, note) {
115
+ try {
116
+ EVENTS.unshift({ t: Date.now(), type, note })
117
+ if (EVENTS.length > 300) EVENTS.length = 300
118
+ localStorage.setItem(EVENTS_KEY, JSON.stringify(EVENTS))
119
+ } catch (e) { }
120
+ }
121
+
122
+ // Chinese statutory holiday calendar: 'YYYY-MM-DD' → { holiday, name }.
123
+ // holiday=false entries are make-up workdays (调休上班). Loaded from the
124
+ // host route (which fetches timor.tech) and cached in localStorage.
125
+ const HOLIDAYS = {}
126
+ const HOLIDAYS_KEY = 'dsh.sitmax.holidays.v1'
127
+ try {
128
+ const rawH = localStorage.getItem(HOLIDAYS_KEY)
129
+ if (rawH) {
130
+ const p = JSON.parse(rawH)
131
+ if (p && p.map && typeof p.map === 'object') Object.assign(HOLIDAYS, p.map)
132
+ }
133
+ } catch (e) { }
134
+
135
+ function isWorkday(key) {
136
+ const d = new Date(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)))
137
+ const dow = d.getDay()
138
+ const h = HOLIDAYS[key]
139
+ if (h && typeof h.holiday === 'boolean') return !h.holiday
140
+ return dow !== 0 && dow !== 6
141
+ }
142
+
143
+ async function loadHolidays() {
144
+ // Throttle: at most one fetch per 5 minutes (apply + poll may both fire
145
+ // shortly after load), and log only when the calendar actually grows.
146
+ if (Date.now() - S.lastHolidayFetch < 300000) return
147
+ S.lastHolidayFetch = Date.now()
148
+ try {
149
+ const year = new Date().getFullYear()
150
+ const res = await fetch('/api/dsh-sitmax/holidays?year=' + year)
151
+ if (!res.ok) return
152
+ const j = await res.json()
153
+ if (j && j.ok && j.map && typeof j.map === 'object') {
154
+ let added = 0
155
+ for (const k of Object.keys(j.map)) {
156
+ if (!(k in HOLIDAYS)) { HOLIDAYS[k] = j.map[k]; added++ }
157
+ }
158
+ try { localStorage.setItem(HOLIDAYS_KEY, JSON.stringify({ year, map: j.map })) } catch (e) { }
159
+ if (added > 0) {
160
+ if (typeof S !== 'undefined' && S.mode === 'offduty') S.nextAutoAt = nextAutoStart(Date.now())
161
+ logEvent('holidays-loaded', '已加载 ' + year + ' 年节假日安排(新增 ' + added + ' 天标记)')
162
+ }
163
+ }
164
+ } catch (e) { }
165
+ }
166
+
167
+ function dayBucket(ts) {
168
+ const k = dateKey(ts)
169
+ if (!HIST[k] || typeof HIST[k] !== 'object') HIST[k] = { sitMs: 0, breaks: 0, cycles: 0, reminders: 0 }
170
+ return HIST[k]
171
+ }
172
+
173
+ // Reconciled daily sitting total: the durable per-tick accumulation vs the
174
+ // sum of recorded continuous stretches — the larger one wins, so 累计在座
175
+ // can never fall below 最长连续.
176
+ function daySitMs(b) {
177
+ if (!b) return 0
178
+ let m = typeof b.sitMs === 'number' ? b.sitMs : 0
179
+ if (Array.isArray(b.stretches)) {
180
+ let s = 0
181
+ for (let i = 0; i < b.stretches.length; i++) s += b.stretches[i]
182
+ if (s > m) m = s
183
+ }
184
+ return m
185
+ }
186
+
187
+ function mins(v, lo, hi) {
188
+ const n = Math.round(Number(v))
189
+ if (!isFinite(n)) return lo
190
+ return Math.min(hi, Math.max(lo, n))
191
+ }
192
+
193
+ // Chime: generate a small WAV in memory (no assets, no network).
194
+ let hardUri = null
195
+ let softUri = null
196
+ function chimeUriFor(soft) {
197
+ try {
198
+ const sr = 22050
199
+ const dur = soft ? 0.35 : 0.6
200
+ const n = Math.floor(sr * dur)
201
+ const data = new Int16Array(n)
202
+ const f1 = soft ? 523 : 659
203
+ const f2 = soft ? 784 : 988
204
+ for (let i = 0; i < n; i++) {
205
+ const t = i / sr
206
+ const env = Math.min(1, (n - i) / (sr * 0.15))
207
+ data[i] = Math.round(Math.max(-1, Math.min(1, (Math.sin(2 * Math.PI * f1 * t) + 0.5 * Math.sin(2 * Math.PI * f2 * t)) * 0.28 * env)) * 0x7fff)
208
+ }
209
+ const buf = new ArrayBuffer(44 + n * 2)
210
+ const dv = new DataView(buf)
211
+ const ws = (o, s) => { for (let i = 0; i < s.length; i++) dv.setUint8(o + i, s.charCodeAt(i)) }
212
+ ws(0, 'RIFF'); dv.setUint32(4, 36 + n * 2, true); ws(8, 'WAVE'); ws(12, 'fmt ')
213
+ dv.setUint32(16, 16, true); dv.setUint16(20, 1, true); dv.setUint16(22, 1, true)
214
+ dv.setUint32(24, sr, true); dv.setUint32(28, sr * 2, true); dv.setUint16(32, 2, true); dv.setUint16(34, 16, true)
215
+ ws(36, 'data'); dv.setUint32(40, n * 2, true)
216
+ new Int16Array(buf, 44).set(data)
217
+ const bytes = new Uint8Array(buf)
218
+ let bin = ''
219
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i])
220
+ return 'data:audio/wav;base64,' + window.btoa(bin)
221
+ } catch (e) { return null }
222
+ }
223
+
224
+ function beep(soft) {
225
+ if (!CFG.sound) return
226
+ try {
227
+ const uri = soft ? (softUri = softUri || chimeUriFor(true)) : (hardUri = hardUri || chimeUriFor(false))
228
+ if (!uri) return
229
+ const a = new Audio(uri)
230
+ const p = a.play()
231
+ if (p && typeof p.catch === 'function') p.catch(() => {})
232
+ } catch (e) { }
233
+ }
234
+
235
+ function notify(title, body) {
236
+ if (!CFG.notif) return 'off'
237
+ try {
238
+ if (typeof Notification === 'undefined') return 'unsupported'
239
+ if (Notification.permission !== 'granted') return 'no-permission'
240
+ const n = new Notification(title, { body: body })
241
+ n.onclick = () => { try { window.focus() } catch (e) { } }
242
+ return 'sent'
243
+ } catch (e) { return 'error' }
244
+ }
245
+
246
+ const S = {
247
+ mode: 'sitting',
248
+ pauseKind: '',
249
+ skipBreakCredit: false,
250
+ sitAnchor: Date.now(),
251
+ stretchStart: Date.now(),
252
+ nextRemindAt: Date.now() + CFG.remindMin * 60000,
253
+ pauseStart: 0,
254
+ breakUntil: 0,
255
+ frozenPhase: 0,
256
+ prevPhase: 0,
257
+ glowUntil: 0,
258
+ showModal: false,
259
+ total: 0,
260
+ pathEl: null,
261
+ lastActivity: Date.now(),
262
+ lastTick: Date.now(),
263
+ lastNotifAt: 0,
264
+ histDirty: 0,
265
+ globalIdleMs: null,
266
+ globalSupported: false,
267
+ globalSampleAt: 0,
268
+ lastPeakEndedAt: 0,
269
+ nextAutoAt: 0,
270
+ dayKey: dateKey(Date.now()),
271
+ lastHolidayFetch: 0,
272
+ everGlobal: false,
273
+ stats: { popups: 0, breaks: 0, cycles: 0 },
274
+ }
275
+
276
+ // Persist the sitting-clock anchor too, so a quick page refresh keeps the
277
+ // "已坐" clock, the sand-flow phase and the reminder countdown running.
278
+ function persistState() {
279
+ try {
280
+ localStorage.setItem(STATE_KEY, JSON.stringify({
281
+ mode: S.mode,
282
+ anchor: S.sitAnchor,
283
+ stretchStart: S.stretchStart,
284
+ nextRemindAt: S.nextRemindAt,
285
+ breakUntil: S.breakUntil,
286
+ stats: { popups: S.stats.popups, breaks: S.stats.breaks, cycles: S.stats.cycles },
287
+ savedAt: Date.now(),
288
+ }))
289
+ } catch (e) { }
290
+ }
291
+ function flush() { persistHist(); persistState() }
292
+
293
+ // Continuous-sitting stretches: each stretch is recorded when it ends so
294
+ // the report can show the longest single sitting session, distinct from
295
+ // the daily accumulated total.
296
+ function recordStretch(endTs) {
297
+ const dur = endTs - S.stretchStart
298
+ if (dur >= 60000) {
299
+ const b = dayBucket(endTs)
300
+ if (!Array.isArray(b.stretches)) b.stretches = []
301
+ b.stretches.push(dur)
302
+ if (b.stretches.length > 100) b.stretches.shift()
303
+ if (!b.maxStretch || dur > b.maxStretch) b.maxStretch = dur
304
+ }
305
+ }
306
+
307
+ // ---- single-driver protection: with several DSH tabs open, only ONE tab
308
+ // ticks the clock, writes state and fires reminders, so a stale tab can
309
+ // never overwrite the live clock or double-count sitting time. The other
310
+ // tabs stay read-only ("follower"). Election is deterministic: the tab
311
+ // with the smallest random id becomes the driver. ----
312
+ const TAB_ID = Math.random().toString(36).slice(2, 10)
313
+ let role = 'unknown' // 'leader' | 'follower' | 'unknown'
314
+ let leaderId = null
315
+ let lastHeartbeat = Date.now()
316
+ let candidates = [TAB_ID]
317
+ let roleListener = null
318
+ const bc = typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel('dsh-sitmax') : null
319
+
320
+ function setRole(r) {
321
+ role = r
322
+ if (roleListener !== null) roleListener(r)
323
+ }
324
+ function hello() {
325
+ if (bc === null) { setRole('leader'); return }
326
+ candidates = [TAB_ID]
327
+ setRole('unknown')
328
+ bc.postMessage({ type: 'hello', id: TAB_ID })
329
+ setTimeout(() => {
330
+ if (role !== 'unknown') return
331
+ const ids = Array.from(candidates).sort()
332
+ if (ids[0] === TAB_ID) {
333
+ setRole('leader')
334
+ bc.postMessage({ type: 'leader', id: TAB_ID })
335
+ bc.postMessage({ type: 'heartbeat', id: TAB_ID })
336
+ } else {
337
+ leaderId = ids[0]
338
+ lastHeartbeat = Date.now()
339
+ setRole('follower')
340
+ bc.postMessage({ type: 'hello', id: TAB_ID })
341
+ }
342
+ }, 400)
343
+ }
344
+ if (bc !== null) {
345
+ bc.onmessage = (ev) => {
346
+ const m = ev.data || {}
347
+ if (m.type === 'hello') {
348
+ if (!candidates.includes(m.id)) candidates.push(m.id)
349
+ if (role === 'leader') bc.postMessage({ type: 'leader', id: TAB_ID })
350
+ } else if (m.type === 'leader') {
351
+ if (m.id !== TAB_ID) {
352
+ leaderId = m.id
353
+ lastHeartbeat = Date.now()
354
+ setRole('follower')
355
+ } else {
356
+ setRole('leader')
357
+ }
358
+ } else if (m.type === 'heartbeat' && m.id === leaderId) {
359
+ lastHeartbeat = Date.now()
360
+ } else if (m.type === 'bye' && m.id === leaderId) {
361
+ leaderId = null
362
+ hello()
363
+ }
364
+ }
365
+ }
366
+ hello()
367
+ ctx.effect(() => {
368
+ const keeper = setInterval(() => {
369
+ if (bc === null) return
370
+ if (role === 'leader') {
371
+ bc.postMessage({ type: 'heartbeat', id: TAB_ID })
372
+ } else if (leaderId !== null && Date.now() - lastHeartbeat > 15000) {
373
+ hello()
374
+ }
375
+ }, 5000)
376
+ const bye = () => { if (bc !== null && role === 'leader') { try { bc.postMessage({ type: 'bye', id: TAB_ID }) } catch (e) { } } }
377
+ window.addEventListener('beforeunload', bye)
378
+ return () => {
379
+ clearInterval(keeper)
380
+ window.removeEventListener('beforeunload', bye)
381
+ if (bc !== null) { try { bc.close() } catch (e) { } }
382
+ }
383
+ })
384
+
385
+ const cycleMs = () => CFG.cycleMin * 60000
386
+ const remindMs = () => CFG.remindMin * 60000
387
+ const breakMs = () => CFG.breakMin * 60000
388
+
389
+ // Next occurrence of the configured daily auto-start time (HH:MM), skipping
390
+ // weekends and statutory holidays when workday-only mode is on.
391
+ function nextAutoStart(now) {
392
+ for (let i = 0; i < 16; i++) {
393
+ const t = new Date(now + i * 86400000)
394
+ const at = new Date(t.getFullYear(), t.getMonth(), t.getDate(), CFG.workH, CFG.workM, 0, 0).getTime()
395
+ if (at <= now) continue
396
+ if (!CFG.workdays || isWorkday(dateKey(at))) return at
397
+ }
398
+ return now + 86400000
399
+ }
400
+
401
+ function currentPhase(now) {
402
+ if (S.mode !== 'sitting') return S.frozenPhase
403
+ const c = cycleMs()
404
+ return (((now - S.sitAnchor) % c) + c) % c / c
405
+ }
406
+
407
+ // Restore the pre-refresh sitting clock: a quick refresh (≤90s gap) keeps
408
+ // the "已坐" timer, sand phase and reminder countdown running, and the
409
+ // refresh gap is still counted as sitting time in the daily report.
410
+ try {
411
+ const raw = localStorage.getItem(STATE_KEY)
412
+ if (raw) {
413
+ const st = JSON.parse(raw)
414
+ const now = Date.now()
415
+ if (st && typeof st.mode === 'string' && st.mode === 'offduty') {
416
+ // Off-duty survives any gap: it stays stopped until the user clicks
417
+ // "start overtime" or the daily auto-start time arrives.
418
+ S.mode = 'offduty'
419
+ S.frozenPhase = 0
420
+ S.showModal = false
421
+ S.nextAutoAt = nextAutoStart(now)
422
+ if (st.stats && typeof st.stats === 'object') {
423
+ S.stats.popups = Number(st.stats.popups) || 0
424
+ S.stats.breaks = Number(st.stats.breaks) || 0
425
+ S.stats.cycles = Number(st.stats.cycles) || 0
426
+ }
427
+ } else if (st && typeof st.savedAt === 'number' && typeof st.anchor === 'number'
428
+ && now - st.savedAt >= 0 && now - st.savedAt <= 90000
429
+ && (st.mode === 'sitting' || st.mode === 'break')) {
430
+ S.sitAnchor = st.anchor
431
+ S.stretchStart = typeof st.stretchStart === 'number' ? st.stretchStart : st.anchor
432
+ if (st.mode === 'break' && typeof st.breakUntil === 'number' && st.breakUntil > now) {
433
+ S.mode = 'break'
434
+ S.breakUntil = st.breakUntil
435
+ } else {
436
+ S.mode = 'sitting'
437
+ S.nextRemindAt = typeof st.nextRemindAt === 'number' && st.nextRemindAt > now ? st.nextRemindAt : now + remindMs()
438
+ dayBucket(now).sitMs += now - st.savedAt
439
+ }
440
+ if (st.stats && typeof st.stats === 'object') {
441
+ S.stats.popups = Number(st.stats.popups) || 0
442
+ S.stats.breaks = Number(st.stats.breaks) || 0
443
+ S.stats.cycles = Number(st.stats.cycles) || 0
444
+ }
445
+ S.lastTick = now
446
+ persistHist()
447
+ logEvent('restore', '刷新后恢复计时(继续之前的「已坐」时钟)')
448
+ }
449
+ }
450
+ } catch (e) { }
451
+
452
+ // Load the statutory-holiday calendar once at startup (and every 12h from
453
+ // the leader poll below).
454
+ loadHolidays()
455
+
456
+ // Idle detection: auto-pause when away, resume on return; a long absence
457
+ // counts as a completed break (auto-reset).
458
+ function resumeFromAway(now) {
459
+ const away = now - S.pauseStart
460
+ if (CFG.autoBreak && away >= breakMs() && !S.skipBreakCredit) {
461
+ recordStretch(S.pauseStart)
462
+ S.stretchStart = now
463
+ S.stats.breaks++
464
+ dayBucket(now).breaks++
465
+ S.mode = 'sitting'
466
+ S.sitAnchor = now
467
+ S.nextRemindAt = now + remindMs()
468
+ S.frozenPhase = 0
469
+ S.prevPhase = 0
470
+ S.pauseKind = ''
471
+ S.showModal = false
472
+ flush()
473
+ logEvent('away-reset', '离开 ' + fmtSpan(away) + '(≥ 休息时长 ' + CFG.breakMin + ' 分钟),算完成一次休息并重置计时')
474
+ } else {
475
+ S.sitAnchor += away
476
+ S.nextRemindAt += away
477
+ S.mode = 'sitting'
478
+ S.prevPhase = currentPhase(now)
479
+ S.pauseKind = ''
480
+ logEvent('resume', '回来继续计时(扣掉离开的 ' + fmtSpan(away) + ',未到休息时长 ' + CFG.breakMin + ' 分钟)')
481
+ }
482
+ S.skipBreakCredit = false
483
+ S.lastTick = now
484
+ }
485
+
486
+ function onActivity() {
487
+ if (role !== 'leader') return
488
+ const now = Date.now()
489
+ S.lastActivity = now
490
+ if (S.mode !== 'paused' || S.pauseKind !== 'auto') return
491
+ resumeFromAway(now)
492
+ }
493
+
494
+ ctx.effect(() => {
495
+ const evs = ['keydown', 'mousedown', 'pointerdown', 'wheel', 'touchstart']
496
+ for (let i = 0; i < evs.length; i++) document.addEventListener(evs[i], onActivity, { passive: true })
497
+ const save = () => flush()
498
+ window.addEventListener('beforeunload', save)
499
+ document.addEventListener('visibilitychange', save)
500
+ return () => {
501
+ for (let i = 0; i < evs.length; i++) document.removeEventListener(evs[i], onActivity)
502
+ window.removeEventListener('beforeunload', save)
503
+ document.removeEventListener('visibilitychange', save)
504
+ }
505
+ })
506
+
507
+ // Poll the host route for the Windows-wide idle sample (GetLastInputInfo).
508
+ // While it answers, the SYSTEM-wide idle decides "away"; the page-local
509
+ // events above stay as the fallback when the route is unavailable.
510
+ ctx.effect(() => {
511
+ let stopped = false
512
+ let timer = null
513
+ async function poll() {
514
+ if (role !== 'leader') {
515
+ if (!stopped) timer = setTimeout(poll, 2000)
516
+ return
517
+ }
518
+ const nowTs = Date.now()
519
+ if (nowTs - S.lastHolidayFetch > 12 * 3600000) {
520
+ S.lastHolidayFetch = nowTs
521
+ loadHolidays()
522
+ }
523
+ try {
524
+ const res = await fetch('/api/dsh-sitmax/idle', { cache: 'no-store' })
525
+ if (res.ok) {
526
+ const j = await res.json()
527
+ if (j && typeof j.idleMs === 'number' && !stopped) {
528
+ const prevGlobal = S.globalSupported
529
+ S.globalIdleMs = j.idleMs
530
+ S.globalSupported = j.supported === true
531
+ S.globalSampleAt = Date.now()
532
+ if (S.globalSupported && !S.everGlobal) S.everGlobal = true
533
+ if (prevGlobal && !S.globalSupported) {
534
+ logEvent('global-lost', '全局检测连接断开:自动暂停已临时关闭,避免误判「离开」')
535
+ }
536
+ // Retroactive away correction: the host kept sampling while this
537
+ // tab was throttled or frozen (locked workstation), so this page
538
+ // missed the whole away stretch. When such a stretch ended, remove
539
+ // the overlapping part from the sitting clock now.
540
+ if (typeof j.idlePeakEndedAt === 'number' && typeof j.idlePeak === 'number'
541
+ && j.idlePeakEndedAt > S.lastPeakEndedAt) {
542
+ S.lastPeakEndedAt = j.idlePeakEndedAt
543
+ const end = j.idlePeakEndedAt
544
+ const start = end - (typeof j.idlePeakLast === 'number' ? j.idlePeakLast : j.idlePeak)
545
+ const overlap = Math.max(0, end - Math.max(S.sitAnchor, start))
546
+ if (overlap >= CFG.idleMin * 60000) {
547
+ if (S.mode === 'sitting') {
548
+ if (CFG.autoBreak && overlap >= breakMs()) {
549
+ recordStretch(start)
550
+ S.stretchStart = Date.now()
551
+ S.stats.breaks++
552
+ dayBucket(Date.now()).breaks++
553
+ S.mode = 'sitting'
554
+ S.sitAnchor = Date.now()
555
+ S.nextRemindAt = Date.now() + remindMs()
556
+ S.frozenPhase = 0
557
+ S.prevPhase = 0
558
+ S.showModal = false
559
+ persistHist()
560
+ logEvent('retro-reset', '锁屏/冻结期间离开约 ' + Math.round(overlap / 60000) + ' 分钟,已按完成休息重置')
561
+ } else {
562
+ S.sitAnchor += overlap
563
+ S.nextRemindAt += overlap
564
+ logEvent('retro-correct', '锁屏/冻结期间离开约 ' + Math.round(overlap / 60000) + ' 分钟,已从计时中扣除')
565
+ }
566
+ S.lastTick = Date.now()
567
+ }
568
+ }
569
+ }
570
+ }
571
+ }
572
+ } catch (err) {
573
+ // route not registered yet; keep polling
574
+ }
575
+ if (!stopped) timer = setTimeout(poll, 2000)
576
+ }
577
+ timer = setTimeout(poll, 300)
578
+ return () => { stopped = true; clearTimeout(timer) }
579
+ })
580
+
581
+ // HUD position: null = default top-center. Drag anywhere and it is remembered;
582
+ // double-click resets to the default.
583
+ const HUD_POS_KEY = 'dsh.sitmax.pos.v1'
584
+ let hudPos = (() => {
585
+ try {
586
+ const raw = localStorage.getItem(HUD_POS_KEY)
587
+ if (raw !== null) {
588
+ const parsed = JSON.parse(raw)
589
+ if (parsed !== null && typeof parsed === 'object' && Number.isFinite(parsed.x) && Number.isFinite(parsed.y)) {
590
+ return { x: parsed.x, y: parsed.y }
591
+ }
592
+ }
593
+ } catch (err) { /* ignore */ }
594
+ return null
595
+ })()
596
+ let hudDrag = null
597
+ let suppressHudClick = false
598
+
599
+ function MAXWidget() {
600
+ const [v, setV] = React.useState(() => derive(Date.now()))
601
+
602
+ function derive(now) {
603
+ const tickGap = now - S.lastTick
604
+ // Global idle (Windows-wide) wins when available; page events are the
605
+ // fallback. Extrapolate the last sample forward to "now"; tolerate up
606
+ // to 120s of staleness so a throttled tab still detects absence from a
607
+ // slightly older sample instead of giving up.
608
+ const pageIdle = now - S.lastActivity
609
+ let globalIdle = null
610
+ if (S.globalSupported && S.globalIdleMs !== null) {
611
+ const staleness = now - S.globalSampleAt
612
+ if (staleness <= 120000) {
613
+ globalIdle = S.globalIdleMs + Math.max(0, staleness)
614
+ }
615
+ }
616
+ if (S.mode === 'sitting') {
617
+ // When the system reports the user active (fresh global idle), a long
618
+ // tick gap means browser throttling, not absence: count wall-clock
619
+ // time so throttled tabs never undercount sitting.
620
+ let delta = Math.min(tickGap, 5000)
621
+ if (globalIdle !== null && globalIdle < 60000 && tickGap <= 600000) delta = tickGap
622
+ if (delta > 0) dayBucket(now).sitMs += delta
623
+ }
624
+ S.lastTick = now
625
+ if (now - S.histDirty > 15000) { S.histDirty = now; flush() }
626
+
627
+ const globalActive = CFG.globalIdle && globalIdle !== null
628
+
629
+ // "Present" means the user touched the system within the last minute —
630
+ // reminders must never fire while nobody is there.
631
+ const userPresent = (globalIdle !== null ? globalIdle : pageIdle) < 60000
632
+
633
+ // Wake-from-stall backstop: when the tab froze (locked workstation /
634
+ // energy saver) and no fresh global sample exists, conservatively treat
635
+ // the stalled time as NOT sitting — the clock must never count phantom
636
+ // sitting time.
637
+ if (S.mode === 'sitting' && tickGap > 30000 && globalIdle === null) {
638
+ const skip = tickGap - 30000
639
+ S.sitAnchor += skip
640
+ S.nextRemindAt += skip
641
+ S.stretchStart += skip
642
+ if (skip >= 120000) logEvent('stall-skip', '心跳中断约 ' + Math.round(tickGap / 60000) + ' 分钟,该时段未计入久坐')
643
+ }
644
+
645
+ // Auto-pause requires trustworthy idle data. Skip it when: the tab just
646
+ // woke from a stall (a frozen/throttled page would otherwise turn its
647
+ // ancient last-input time into a phantom "away" stretch), or the global
648
+ // connection was lost after having worked (degraded page-only detection
649
+ // misfires when the user works in other apps).
650
+ // Auto-pause requires trustworthy idle data. The stall guard (tickGap)
651
+ // only applies to the page-fallback path: a fresh-enough global sample
652
+ // is valid even across throttled ticks.
653
+ const autoPauseAllowed = CFG.idlePause && (globalActive || !S.everGlobal) && (globalActive || tickGap < 30000)
654
+ if (autoPauseAllowed && S.mode === 'sitting') {
655
+ const away = globalActive ? globalIdle : pageIdle
656
+ if (away > CFG.idleMin * 60000) {
657
+ S.mode = 'paused'
658
+ S.pauseKind = 'auto'
659
+ S.frozenPhase = currentPhase(now)
660
+ // Freeze the clock at the moment input stopped, not at the moment
661
+ // this tick noticed it.
662
+ S.pauseStart = globalActive ? now - globalIdle : S.lastActivity
663
+ const pausedAt = new Date(S.pauseStart)
664
+ logEvent('pause', '无输入超过 ' + CFG.idleMin + ' 分钟,自动暂停(从 ' + String(pausedAt.getHours()).padStart(2, '0') + ':' + String(pausedAt.getMinutes()).padStart(2, '0') + ' 起算)')
665
+ }
666
+ }
667
+ // The user touched something anywhere in Windows (another app counts):
668
+ // resume even when this page saw no event of its own.
669
+ if (S.mode === 'paused' && S.pauseKind === 'auto' && globalActive && globalIdle < 2000) {
670
+ resumeFromAway(now)
671
+ }
672
+
673
+ const p = currentPhase(now)
674
+ let showModal = S.showModal
675
+ if (S.mode === 'sitting' && now >= S.nextRemindAt && !showModal && userPresent) {
676
+ showModal = true
677
+ S.showModal = true
678
+ S.stats.popups++
679
+ dayBucket(now).reminders++
680
+ S.lastNotifAt = now
681
+ const nr = notify('⏰ 该起来走走了', '已经连续坐满 ' + CFG.remindMin + ' 分钟啦,起来接杯水、伸个懒腰吧~')
682
+ if (nr !== 'sent') logEvent('notif-skip', '桌面通知未发送(' + nr + ')')
683
+ beep(false)
684
+ flush()
685
+ logEvent('remind', '到点提醒 · 已连续坐 ' + CFG.remindMin + ' 分钟')
686
+ }
687
+ if (S.mode === 'sitting' && showModal && now >= S.nextRemindAt && now - S.lastNotifAt > 300000 && userPresent) {
688
+ S.lastNotifAt = now
689
+ notify('⏰ 还在坐着吗?', '起来活动一下,眼睛看看远处~')
690
+ beep(false)
691
+ }
692
+ if (S.mode === 'break' && now >= S.breakUntil) {
693
+ S.mode = 'sitting'
694
+ S.sitAnchor = now
695
+ S.stretchStart = now
696
+ S.nextRemindAt = now + remindMs()
697
+ S.frozenPhase = 0
698
+ S.prevPhase = 0
699
+ S.showModal = false
700
+ showModal = false
701
+ // The break itself counts as absence: if the user is still away when
702
+ // the countdown ends, pause (without charging another break) and wait
703
+ // for their return instead of instantly flagging "no input".
704
+ if (globalIdle !== null && globalIdle > CFG.idleMin * 60000) {
705
+ S.mode = 'paused'
706
+ S.pauseKind = 'auto'
707
+ S.pauseStart = now
708
+ S.skipBreakCredit = true
709
+ logEvent('pause', '休息结束但你尚未回来,暂停等待你回来')
710
+ } else {
711
+ S.skipBreakCredit = false
712
+ }
713
+ notify('✅ 休息结束', '欢迎回来,新一轮计时开始~')
714
+ beep(true)
715
+ logEvent('break-end', '休息倒计时结束,重新开始计时')
716
+ }
717
+ // Day rollover: on a non-workday (with workday-only mode on), a session
718
+ // that ran past midnight automatically goes off-duty.
719
+ const dk = dateKey(now)
720
+ if (dk !== S.dayKey) {
721
+ S.dayKey = dk
722
+ if (CFG.workdays && S.mode === 'sitting' && !isWorkday(dk)) {
723
+ recordStretch(now)
724
+ S.stretchStart = now
725
+ S.mode = 'offduty'
726
+ S.showModal = false
727
+ S.frozenPhase = 0
728
+ S.nextAutoAt = nextAutoStart(now)
729
+ flush()
730
+ logEvent('auto-offduty', '进入周末/节假日,自动停止计时(点「开始加班」可继续)')
731
+ }
732
+ }
733
+ if (S.mode === 'offduty' && CFG.autoStart && (!CFG.workdays || isWorkday(dk)) && now >= S.nextAutoAt) {
734
+ S.mode = 'sitting'
735
+ S.sitAnchor = now
736
+ S.stretchStart = now
737
+ S.nextRemindAt = now + remindMs()
738
+ S.prevPhase = 0
739
+ S.frozenPhase = 0
740
+ S.lastTick = now
741
+ flush()
742
+ logEvent('auto-start', '到上班时间(' + String(CFG.workH).padStart(2, '0') + ':' + String(CFG.workM).padStart(2, '0') + '),自动恢复计时')
743
+ }
744
+ if (S.mode === 'sitting') {
745
+ if (S.prevPhase > 0.6 && p < 0.4) {
746
+ S.stats.cycles++
747
+ dayBucket(now).cycles++
748
+ S.glowUntil = now + 2600
749
+ }
750
+ S.prevPhase = p
751
+ }
752
+ const overdue = S.mode === 'sitting' && now >= S.nextRemindAt
753
+ let notifOk = false
754
+ try { notifOk = CFG.notif && typeof Notification !== 'undefined' && Notification.permission === 'granted' } catch (e) { }
755
+ return {
756
+ now, p, mode: S.mode, pauseKind: S.pauseKind,
757
+ modal: showModal, overdue, glow: now < S.glowUntil, notifOk,
758
+ sitMs: S.mode === 'sitting' ? now - S.sitAnchor : 0,
759
+ remainMs: Math.max(0, S.nextRemindAt - now),
760
+ breakMs: S.mode === 'break' ? Math.max(0, S.breakUntil - now) : 0,
761
+ remindMin: CFG.remindMin,
762
+ stats: { popups: S.stats.popups, breaks: S.stats.breaks, cycles: S.stats.cycles },
763
+ }
764
+ }
765
+
766
+ const [tabRole, setTabRole] = React.useState(role)
767
+ React.useEffect(() => {
768
+ roleListener = setTabRole
769
+ setTabRole(role)
770
+ return () => { roleListener = null }
771
+ }, [])
772
+ React.useEffect(() => {
773
+ if (tabRole !== 'leader') return
774
+ const t = setInterval(() => setV(derive(Date.now())), 1000)
775
+ return () => clearInterval(t)
776
+ }, [tabRole])
777
+
778
+ const togglePause = () => {
779
+ if (tabRole !== 'leader') return
780
+ if (S.mode === 'offduty') return
781
+ const now = Date.now()
782
+ markActive(now)
783
+ if (S.mode === 'sitting') {
784
+ S.mode = 'paused'
785
+ S.pauseKind = 'manual'
786
+ S.frozenPhase = currentPhase(now)
787
+ S.pauseStart = now
788
+ } else if (S.mode === 'paused') {
789
+ const dt = now - S.pauseStart
790
+ S.sitAnchor += dt
791
+ S.nextRemindAt += dt
792
+ S.mode = 'sitting'
793
+ S.pauseKind = ''
794
+ S.prevPhase = currentPhase(now)
795
+ }
796
+ setV(derive(now))
797
+ }
798
+
799
+ const ackBreak = () => {
800
+ const now = Date.now()
801
+ recordStretch(now)
802
+ S.stretchStart = now
803
+ S.skipBreakCredit = false
804
+ S.mode = 'break'
805
+ S.frozenPhase = currentPhase(now)
806
+ S.breakUntil = now + breakMs()
807
+ S.stats.breaks++
808
+ dayBucket(now).breaks++
809
+ flush()
810
+ logEvent('break-start', '点击「起来了」开始 ' + CFG.breakMin + ' 分钟休息')
811
+ setV(derive(now))
812
+ }
813
+
814
+ const endBreak = () => {
815
+ const now = Date.now()
816
+ S.mode = 'sitting'
817
+ S.sitAnchor = now
818
+ S.stretchStart = now
819
+ S.skipBreakCredit = false
820
+ S.nextRemindAt = now + remindMs()
821
+ S.frozenPhase = 0
822
+ S.prevPhase = 0
823
+ S.showModal = false
824
+ logEvent('break-end', '点击「我回来了」提前结束休息')
825
+ setV(derive(now))
826
+ }
827
+
828
+ const snooze = () => {
829
+ const now = Date.now()
830
+ S.nextRemindAt = now + CFG.snoozeMin * 60000
831
+ S.showModal = false
832
+ logEvent('snooze', '点击「再坐一会儿」暂缓 ' + CFG.snoozeMin + ' 分钟')
833
+ setV(derive(now))
834
+ }
835
+
836
+ const goOffDuty = () => {
837
+ if (tabRole !== 'leader') return
838
+ const now = Date.now()
839
+ markActive(now)
840
+ // Off-duty ends the sitting session: bank the stretch, then reset the
841
+ // clock so the next session starts from 0:00.
842
+ recordStretch(S.pauseKind === 'auto' ? S.pauseStart : now)
843
+ S.stretchStart = now
844
+ S.sitAnchor = now
845
+ S.nextRemindAt = now + remindMs()
846
+ S.mode = 'offduty'
847
+ S.pauseKind = ''
848
+ S.showModal = false
849
+ S.frozenPhase = 0
850
+ S.prevPhase = 0
851
+ S.nextAutoAt = nextAutoStart(now)
852
+ flush()
853
+ logEvent('offduty', '点击「下班」,停止计时并重置已坐时间')
854
+ setV(derive(now))
855
+ }
856
+
857
+ // A user click is fresh activity: clear the idle samples so the very
858
+ // next tick cannot misjudge "away" from a pre-click stale sample.
859
+ const markActive = (now) => {
860
+ S.lastActivity = now
861
+ S.globalIdleMs = 0
862
+ S.globalSampleAt = now
863
+ }
864
+
865
+ const startOvertime = () => {
866
+ if (tabRole !== 'leader') return
867
+ const now = Date.now()
868
+ markActive(now)
869
+ S.mode = 'sitting'
870
+ S.sitAnchor = now
871
+ S.stretchStart = now
872
+ S.nextRemindAt = now + remindMs()
873
+ S.prevPhase = 0
874
+ S.frozenPhase = 0
875
+ S.lastTick = now
876
+ flush()
877
+ logEvent('overtime', '点击「开始加班」,恢复计时')
878
+ setV(derive(now))
879
+ }
880
+
881
+ // Status line under the letters (inside the glass capsule): time while
882
+ // sitting, countdown while resting, one word otherwise.
883
+ let statusText = tabRole !== 'leader' ? '只读' : '已坐 ' + fmt(v.sitMs)
884
+ if (tabRole === 'leader') {
885
+ if (v.mode === 'break') statusText = '休息 ' + fmt(v.breakMs)
886
+ if (v.mode === 'paused') statusText = v.pauseKind === 'auto' ? '暂停' : '已暂停'
887
+ if (v.mode === 'offduty') statusText = CFG.workdays && !isWorkday(dateKey(Date.now())) ? '周末' : '已下班'
888
+ }
889
+
890
+ let pt = { x: -20, y: -20 }
891
+ if (S.total > 0 && S.pathEl) {
892
+ const q = S.pathEl.getPointAtLength(S.total * Math.min(1, Math.max(0, v.p)))
893
+ pt = { x: q.x, y: q.y }
894
+ }
895
+
896
+ const badgeClass = 'maxm-badge' + (v.glow ? ' maxm-glow' : '') + (v.mode === 'break' ? ' maxm-break' : '') + (v.overdue ? ' maxm-overdue' : '') + (v.mode === 'offduty' ? ' maxm-offduty' : '')
897
+
898
+ // Collapsed mini ring geometry (viewBox 40x40, circle r=15 starting at top).
899
+ const miniR = 15
900
+ const miniC = 2 * Math.PI * miniR
901
+ const miniP = Math.min(1, Math.max(0, v.p))
902
+ const miniAngle = -Math.PI / 2 + miniP * 2 * Math.PI
903
+ const miniDot = { x: 20 + miniR * Math.cos(miniAngle), y: 20 + miniR * Math.sin(miniAngle) }
904
+ const miniRunner = React.createElement('g', { style: { transform: 'translate(' + miniDot.x + 'px, ' + miniDot.y + 'px) scale(0.62)' } },
905
+ React.createElement('circle', { className: 'maxm-r-head', cx: '0', cy: '-6.6', r: '2.2' }),
906
+ React.createElement('line', { className: 'maxm-r-body', x1: '0', y1: '-4.4', x2: '0', y2: '1.2' }),
907
+ React.createElement('line', { className: 'maxm-r-arm', x1: '0', y1: '-3.2', x2: '-3.3', y2: '-1' }),
908
+ React.createElement('line', { className: 'maxm-r-arm', x1: '0', y1: '-3.2', x2: '3.1', y2: '-4.3' }),
909
+ React.createElement('line', { className: 'maxm-r-leg', x1: '0', y1: '1.2', x2: '-3.1', y2: '4.4' }),
910
+ React.createElement('line', { className: 'maxm-r-leg', x1: '0', y1: '1.2', x2: '3.1', y2: '3.4' }),
911
+ )
912
+
913
+ const badgeStyle = hudPos !== null ? { left: hudPos.x + 'px', top: hudPos.y + 'px', transform: 'translate(-50%, -50%)' } : undefined
914
+
915
+ const badge = React.createElement('div', {
916
+ className: badgeClass,
917
+ style: badgeStyle,
918
+ title: (v.mode === 'paused' ? '点击继续计时' : '点击暂停计时') + '(拖动可移动位置,双击复位)',
919
+ onClick: (e) => { if (suppressHudClick) return; togglePause(e) },
920
+ onPointerDown: (e) => {
921
+ if (e.button !== 0) return
922
+ const el = e.currentTarget
923
+ const rect = el.getBoundingClientRect()
924
+ // Anchor the drag on the badge CENTRE, so the ring lands centred under
925
+ // the pointer and expands/collapses around the same point.
926
+ hudDrag = { startX: e.clientX, startY: e.clientY, cx: rect.left + rect.width / 2, cy: rect.top + rect.height / 2, moved: false, captured: false }
927
+ // NOTE: no setPointerCapture here — capturing on pointerdown retargets
928
+ // the click to the badge and swallows clicks on the side buttons.
929
+ },
930
+ onPointerMove: (e) => {
931
+ if (hudDrag === null) return
932
+ const dx = e.clientX - hudDrag.startX
933
+ const dy = e.clientY - hudDrag.startY
934
+ if (!hudDrag.moved && Math.abs(dx) < 4 && Math.abs(dy) < 4) return
935
+ hudDrag.moved = true
936
+ const el = e.currentTarget
937
+ if (!hudDrag.captured) {
938
+ try { el.setPointerCapture(e.pointerId) } catch (err) { /* ignore */ }
939
+ hudDrag.captured = true
940
+ }
941
+ const x = Math.round(Math.max(15, Math.min(window.innerWidth - 15, hudDrag.cx + dx)))
942
+ const y = Math.round(Math.max(15, Math.min(window.innerHeight - 15, hudDrag.cy + dy)))
943
+ hudPos = { x, y }
944
+ el.style.left = x + 'px'
945
+ el.style.top = y + 'px'
946
+ el.style.transform = 'translate(-50%, -50%)'
947
+ },
948
+ onPointerUp: (e) => {
949
+ const dragged = hudDrag !== null && hudDrag.moved
950
+ const captured = hudDrag !== null && hudDrag.captured === true
951
+ hudDrag = null
952
+ if (captured) { try { e.currentTarget.releasePointerCapture(e.pointerId) } catch (err) { /* ignore */ } }
953
+ if (dragged) {
954
+ try { localStorage.setItem(HUD_POS_KEY, JSON.stringify(hudPos)) } catch (err) { /* ignore */ }
955
+ suppressHudClick = true
956
+ setTimeout(() => { suppressHudClick = false }, 0)
957
+ }
958
+ },
959
+ onDoubleClick: (e) => {
960
+ hudPos = null
961
+ try { localStorage.removeItem(HUD_POS_KEY) } catch (err) { /* ignore */ }
962
+ const el = e.currentTarget
963
+ el.style.left = ''
964
+ el.style.top = ''
965
+ el.style.transform = ''
966
+ },
967
+ },
968
+ // Collapsed mini ring (hidden while hovered/expanded).
969
+ React.createElement('svg', { className: 'maxm-mini', viewBox: '0 0 40 40', 'aria-hidden': true },
970
+ React.createElement('defs', null,
971
+ React.createElement('linearGradient', { id: 'maxmSandMini', x1: '0', y1: '0', x2: '1', y2: '1' },
972
+ React.createElement('stop', { offset: '0%', stopColor: '#fde68a' }),
973
+ React.createElement('stop', { offset: '50%', stopColor: '#fbbf24' }),
974
+ React.createElement('stop', { offset: '100%', stopColor: '#b45309' }),
975
+ ),
976
+ ),
977
+ React.createElement('circle', { className: 'maxm-mini-track', cx: '20', cy: '20', r: '15' }),
978
+ React.createElement('circle', {
979
+ className: 'maxm-mini-fill', cx: '20', cy: '20', r: '15',
980
+ style: { strokeDasharray: miniC, strokeDashoffset: miniC * (1 - miniP) },
981
+ }),
982
+ miniRunner,
983
+ ),
984
+ tabRole === 'leader' ? React.createElement('button', {
985
+ type: 'button',
986
+ className: 'maxm-act-btn maxm-act-left',
987
+ title: v.mode === 'offduty' ? '开始加班' : '下班',
988
+ onPointerDown: (e) => { e.stopPropagation() },
989
+ onClick: (e) => { e.stopPropagation(); if (v.mode === 'offduty') { startOvertime() } else { goOffDuty() } },
990
+ }, v.mode === 'offduty' ? '💼' : '🌙') : null,
991
+ React.createElement('svg', { className: 'maxm-svg', viewBox: '0 0 150 66', 'aria-hidden': true },
992
+ React.createElement('defs', null,
993
+ React.createElement('linearGradient', { id: 'maxmSand', x1: '0', y1: '0', x2: '1', y2: '1' },
994
+ React.createElement('stop', { offset: '0%', stopColor: '#fde68a' }),
995
+ React.createElement('stop', { offset: '50%', stopColor: '#fbbf24' }),
996
+ React.createElement('stop', { offset: '100%', stopColor: '#b45309' }),
997
+ ),
998
+ ),
999
+ React.createElement('path', { className: 'maxm-track', d: TRACK }),
1000
+ React.createElement('path', { className: 'maxm-lane', d: TRACK_INNER }),
1001
+ React.createElement('path', {
1002
+ className: 'maxm-fill', d: TRACK,
1003
+ ref: (el) => {
1004
+ S.pathEl = el
1005
+ if (el) {
1006
+ S.total = el.getTotalLength()
1007
+ el.style.strokeDasharray = String(S.total)
1008
+ el.style.strokeDashoffset = String(S.total * (1 - Math.min(1, Math.max(0, currentPhase(Date.now())))))
1009
+ }
1010
+ },
1011
+ style: {
1012
+ strokeDasharray: S.total > 0 ? S.total : '0.001',
1013
+ strokeDashoffset: S.total > 0 ? S.total * (1 - Math.min(1, Math.max(0, v.p))) : 0,
1014
+ },
1015
+ }),
1016
+ React.createElement('text', { className: 'maxm-time-text', x: '75', y: '36.5' }, statusText),
1017
+ React.createElement('g', { className: 'maxm-head', style: { transform: 'translate(' + pt.x + 'px, ' + pt.y + 'px)' } },
1018
+ React.createElement('g', { className: 'maxm-runner' },
1019
+ React.createElement('circle', { className: 'maxm-r-head', cx: '0', cy: '-6.6', r: '2.2' }),
1020
+ React.createElement('line', { className: 'maxm-r-body', x1: '0', y1: '-4.4', x2: '0', y2: '1.2' }),
1021
+ React.createElement('line', { className: 'maxm-r-arm', x1: '0', y1: '-3.2', x2: '-3.3', y2: '-1' }),
1022
+ React.createElement('line', { className: 'maxm-r-arm', x1: '0', y1: '-3.2', x2: '3.1', y2: '-4.3' }),
1023
+ React.createElement('line', { className: 'maxm-r-leg', x1: '0', y1: '1.2', x2: '-3.1', y2: '4.4' }),
1024
+ React.createElement('line', { className: 'maxm-r-leg', x1: '0', y1: '1.2', x2: '3.1', y2: '3.4' }),
1025
+ ),
1026
+ ),
1027
+ ),
1028
+ tabRole === 'leader' && v.mode !== 'offduty' ? React.createElement('button', {
1029
+ type: 'button',
1030
+ className: 'maxm-act-btn maxm-act-right',
1031
+ title: v.mode === 'paused' ? '继续计时' : '暂停计时',
1032
+ onPointerDown: (e) => { e.stopPropagation() },
1033
+ onClick: (e) => { e.stopPropagation(); togglePause() },
1034
+ }, v.mode === 'paused' ? '▶' : '⏸') : null,
1035
+ )
1036
+
1037
+ let modal = null
1038
+ if (v.modal) {
1039
+ if (v.mode === 'break') {
1040
+ modal = React.createElement('div', { className: 'maxm-modal', role: 'dialog' },
1041
+ React.createElement('div', { className: 'maxm-m-title maxm-m-break-title' }, '🧘 休息中,放松一下'),
1042
+ React.createElement('div', { className: 'maxm-m-count' }, fmt(v.breakMs)),
1043
+ React.createElement('div', { className: 'maxm-m-tips' },
1044
+ React.createElement('span', null, '💧 喝口水'),
1045
+ React.createElement('span', null, '👀 看看远处'),
1046
+ React.createElement('span', null, '🙆 伸个懒腰'),
1047
+ React.createElement('span', null, '🚶 起来走走'),
1048
+ ),
1049
+ React.createElement('button', { className: 'maxm-btn maxm-btn-ghost', onClick: endBreak }, '▶ 我回来了,继续工作'),
1050
+ )
1051
+ } else {
1052
+ modal = React.createElement('div', { className: 'maxm-modal', role: 'dialog' },
1053
+ React.createElement('div', { className: 'maxm-m-title' }, '⏰ 该起来走走了'),
1054
+ React.createElement('div', { className: 'maxm-m-body' }, '你已经连续坐满 ' + v.remindMin + ' 分钟啦。起来接杯水、伸个懒腰,让眼睛看看远处吧~'),
1055
+ React.createElement('div', { className: 'maxm-m-stats' }, '本次运行 · 已提醒 ' + v.stats.popups + ' 次 · 完成休息 ' + v.stats.breaks + ' 次 · 完成轮次 ' + v.stats.cycles),
1056
+ React.createElement('div', { className: 'maxm-m-stats' }, '提示:点「我去休息」会暂停计时并记一次休息,倒计时结束自动重新计'),
1057
+ v.notifOk ? null : React.createElement('div', { className: 'maxm-m-stats', style: { color: 'var(--dsw-alias-state-warn-primary, #f5a623)' } }, '💡 未发送桌面通知:检查「久坐沙漏 · 设置」的开关与授权;若已开启仍收不到,检查 Windows 通知设置 / 专注助手'),
1058
+ React.createElement('div', { className: 'maxm-m-actions' },
1059
+ React.createElement('button', { className: 'maxm-btn maxm-btn-primary', onClick: ackBreak }, '✅ 我去休息(' + CFG.breakMin + ' 分钟倒计时)'),
1060
+ React.createElement('button', { className: 'maxm-btn maxm-btn-ghost', onClick: snooze }, '⏳ 再坐 ' + CFG.snoozeMin + ' 分钟'),
1061
+ ),
1062
+ )
1063
+ }
1064
+ }
1065
+
1066
+ return React.createElement(React.Fragment, null, badge, modal)
1067
+ }
1068
+
1069
+ function SettingsPage() {
1070
+ const [form, setForm] = React.useState(() => ({ cycleMin: CFG.cycleMin, remindMin: CFG.remindMin, breakMin: CFG.breakMin, snoozeMin: CFG.snoozeMin, idleMin: CFG.idleMin, notif: CFG.notif, sound: CFG.sound, workH: CFG.workH, workM: CFG.workM }))
1071
+ const [flash, setFlash] = React.useState('')
1072
+ const [perm, setPerm] = React.useState(() => { try { return typeof Notification !== 'undefined' ? String(Notification.permission) : '不支持' } catch (e) { return '不支持' } })
1073
+
1074
+ const set = (k, val) => setForm(Object.assign({}, form, { [k]: val }))
1075
+
1076
+ const num = (k, label, hint, lo, hi) => React.createElement('label', { className: 'maxm-set-row', key: k },
1077
+ React.createElement('span', { className: 'maxm-set-lab' }, label, React.createElement('span', { className: 'maxm-set-hint' }, hint)),
1078
+ React.createElement('input', { type: 'number', className: 'maxm-set-num', min: lo, max: hi, value: form[k], onChange: (e) => set(k, Number(e.target.value)) }),
1079
+ )
1080
+ const tog = (k, label, hint) => React.createElement('label', { className: 'maxm-set-row', key: k },
1081
+ React.createElement('span', { className: 'maxm-set-lab' }, label, React.createElement('span', { className: 'maxm-set-hint' }, hint)),
1082
+ React.createElement('input', { type: 'checkbox', className: 'maxm-set-check', checked: form[k], onChange: (e) => set(k, e.target.checked) }),
1083
+ )
1084
+ const btn = (label, cls, onClick) => React.createElement('button', { className: 'maxm-btn ' + cls, onClick: onClick }, label)
1085
+
1086
+ const save = () => {
1087
+ CFG.cycleMin = mins(form.cycleMin, 5, 120)
1088
+ CFG.remindMin = mins(form.remindMin, 10, 180)
1089
+ CFG.breakMin = mins(form.breakMin, 1, 30)
1090
+ CFG.snoozeMin = mins(form.snoozeMin, 1, 30)
1091
+ CFG.idleMin = mins(form.idleMin, 1, 30)
1092
+ CFG.notif = !!form.notif
1093
+ CFG.sound = !!form.sound
1094
+ CFG.workH = mins(form.workH, 0, 23)
1095
+ CFG.workM = mins(form.workM, 0, 59)
1096
+ persistCfg()
1097
+ if (S.mode === 'offduty') S.nextAutoAt = nextAutoStart(Date.now())
1098
+ if (S.mode === 'sitting') S.nextRemindAt = S.sitAnchor + remindMs()
1099
+ setForm({ cycleMin: CFG.cycleMin, remindMin: CFG.remindMin, breakMin: CFG.breakMin, snoozeMin: CFG.snoozeMin, idleMin: CFG.idleMin, notif: CFG.notif, sound: CFG.sound, workH: CFG.workH, workM: CFG.workM })
1100
+ setFlash('已保存 ✓')
1101
+ setTimeout(() => setFlash(''), 2500)
1102
+ try { if (CFG.notif && typeof Notification !== 'undefined' && Notification.permission === 'default') Notification.requestPermission() } catch (e) { }
1103
+ }
1104
+
1105
+ const reset = () => {
1106
+ for (const k in DEFAULTS) CFG[k] = DEFAULTS[k]
1107
+ CFG.idlePause = true
1108
+ CFG.globalIdle = true
1109
+ CFG.autoStart = true
1110
+ CFG.workdays = true
1111
+ CFG.autoBreak = true
1112
+ persistCfg()
1113
+ if (S.mode === 'offduty') S.nextAutoAt = nextAutoStart(Date.now())
1114
+ if (S.mode === 'sitting') S.nextRemindAt = S.sitAnchor + remindMs()
1115
+ setForm({ cycleMin: CFG.cycleMin, remindMin: CFG.remindMin, breakMin: CFG.breakMin, snoozeMin: CFG.snoozeMin, idleMin: CFG.idleMin, notif: CFG.notif, sound: CFG.sound, workH: CFG.workH, workM: CFG.workM })
1116
+ setFlash('已恢复默认 ✓')
1117
+ setTimeout(() => setFlash(''), 2500)
1118
+ }
1119
+
1120
+ const testNotif = () => {
1121
+ const sendTest = (title, body) => {
1122
+ try {
1123
+ const n = new Notification(title, { body })
1124
+ n.onclick = () => { try { window.focus() } catch (e) { } }
1125
+ return true
1126
+ } catch (e) { return false }
1127
+ }
1128
+ try {
1129
+ if (typeof Notification === 'undefined') {
1130
+ setPerm('不支持')
1131
+ setFlash('⚠ 当前浏览器不支持桌面通知')
1132
+ return
1133
+ }
1134
+ if (Notification.permission === 'granted') {
1135
+ const sent = sendTest('✅ 桌面通知正常', '这是 MAX 久坐沙漏的测试通知。到点提醒(默认每 30 分钟)就会以这种形式出现。')
1136
+ setPerm('granted')
1137
+ setFlash(sent ? '✅ 测试通知已发送——留意屏幕右下角(或 Windows 通知中心)' : '⚠ 通知构造失败,请检查浏览器/系统通知是否被禁用')
1138
+ } else if (Notification.permission === 'denied') {
1139
+ setPerm('denied')
1140
+ setFlash('⚠ 权限已被拒绝:点地址栏左侧的锁/铃铛图标 → 通知 → 允许;或进浏览器站点设置把本地址的通知打开')
1141
+ } else {
1142
+ const r = Notification.requestPermission()
1143
+ setFlash('⏳ 已发出权限请求——请留意浏览器左上角或地址栏的弹窗,选择「允许」')
1144
+ if (r && typeof r.then === 'function') {
1145
+ r.then((p) => {
1146
+ setPerm(String(p))
1147
+ if (p === 'granted') {
1148
+ sendTest('✅ 桌面通知已开启', 'MAX 久坐沙漏:以后每到提醒时间,会在这里提醒你起来活动。')
1149
+ setFlash('✅ 已授权并发送测试通知——留意屏幕右下角')
1150
+ } else if (p === 'denied') {
1151
+ setFlash('⚠ 已拒绝。可到浏览器站点设置里重新允许(地址栏锁图标 → 通知)')
1152
+ } else {
1153
+ setFlash('未做选择,仍为未授权状态;再点一次按钮试试')
1154
+ }
1155
+ })
1156
+ } else {
1157
+ setPerm(String(Notification.permission))
1158
+ setFlash('已提交请求,请在浏览器弹窗中选择允许')
1159
+ }
1160
+ }
1161
+ setTimeout(() => setFlash(''), 8000)
1162
+ } catch (e) {
1163
+ setPerm('失败')
1164
+ setFlash('⚠ 请求失败:' + String(e && e.message ? e.message : e))
1165
+ }
1166
+ }
1167
+
1168
+ const testSound = () => { const was = CFG.sound; CFG.sound = true; beep(false); CFG.sound = was }
1169
+
1170
+ const permText = perm === 'granted' ? '✅ 已开启——到点会在系统里弹通知' : perm === 'denied' ? '❌ 已被拒绝(点下方按钮查看开启方法)' : perm === '不支持' ? '当前浏览器不支持' : '未授权(点下方按钮请求)'
1171
+ const roleText = role === 'leader' ? '🟢 本页正在计时' : role === 'follower' ? '🟡 副标签页:计时由另一标签页驱动,本页只读' : '⏳ 正在选举计时标签页…'
1172
+ const holidayText = Object.keys(HOLIDAYS).length > 0 ? '✅ 节假日数据已加载(' + Object.keys(HOLIDAYS).length + ' 天标记)' : '⚠ 节假日数据未加载:暂按周末判断,法定假日请留意'
1173
+ const onWin = /Win/i.test(navigator.platform || '')
1174
+ const globalText = S.globalSupported
1175
+ ? '✅ 全局检测已连接 · 系统级空闲 ' + fmt(S.globalIdleMs ?? 0)
1176
+ : onWin
1177
+ ? '⚠ 全局检测未连接 · 自动暂停已临时关闭(防误判)· 重启 dsh web 后恢复'
1178
+ : '⚠ 全局检测仅支持 Windows,已回退为页面内检测'
1179
+
1180
+ return React.createElement('div', { className: 'maxm-page' },
1181
+ React.createElement('div', { className: 'maxm-page-title' }, '久坐沙漏 · 设置'),
1182
+ React.createElement('div', { className: 'maxm-page-sub' }, '保存后立即生效,并持久保存在本浏览器(localStorage)'),
1183
+ num('cycleMin', '沙漏循环时长', '沙流从 M 流到 X 的一轮时长(分钟)', 5, 120),
1184
+ num('remindMin', '提醒间隔', '连续坐多久后弹窗提醒起身(分钟)', 10, 180),
1185
+ num('breakMin', '休息时长', '点“起来了”后的休息倒计时(分钟)', 1, 30),
1186
+ num('snoozeMin', '暂缓时长', '点“再坐一会儿”后延迟多久提醒(分钟)', 1, 30),
1187
+ num('idleMin', '离开判定', '无键鼠操作多久视为离开(分钟)', 1, 30),
1188
+ num('workH', '上班时间 · 时', '工作日自动恢复计时的小时(0-23)', 0, 23),
1189
+ num('workM', '上班时间 · 分', '工作日自动恢复计时的分钟(0-59)', 0, 59),
1190
+ tog('notif', '桌面通知', '切到其他应用/标签页也能收到系统通知'),
1191
+ tog('sound', '提示音', '到点播放一声轻快的提示音'),
1192
+ React.createElement('div', { className: 'maxm-set-actions' },
1193
+ btn('💾 保存设置', 'maxm-btn-primary', save),
1194
+ btn('恢复默认', 'maxm-btn-ghost', reset),
1195
+ ),
1196
+ flash ? React.createElement('div', { className: 'maxm-set-flash' }, flash) : null,
1197
+ React.createElement('div', { className: 'maxm-page-sep' }),
1198
+ React.createElement('div', { className: 'maxm-set-lab' }, roleText),
1199
+ React.createElement('div', { className: 'maxm-set-lab' }, globalText),
1200
+ React.createElement('div', { className: 'maxm-set-lab' }, holidayText),
1201
+ React.createElement('div', { className: 'maxm-set-lab' }, '通知权限:' + permText),
1202
+ React.createElement('div', { className: 'maxm-set-actions' },
1203
+ btn('🔔 请求 / 测试桌面通知', 'maxm-btn-ghost', testNotif),
1204
+ btn('🔊 测试提示音', 'maxm-btn-ghost', testSound),
1205
+ btn('🔄 刷新节假日数据', 'maxm-btn-ghost', () => { setFlash('正在刷新节假日数据…'); loadHolidays() }),
1206
+ ),
1207
+ )
1208
+ }
1209
+
1210
+ function ReportPage() {
1211
+ const [now, setNow] = React.useState(Date.now())
1212
+ const [view, setView] = React.useState('calendar')
1213
+ const [ym, setYm] = React.useState(() => { const d = new Date(); return { y: d.getFullYear(), m: d.getMonth() } })
1214
+ const [sel, setSel] = React.useState(() => dateKey(Date.now()))
1215
+ const [rflash, setRflash] = React.useState('')
1216
+ const [previewUrl, setPreviewUrl] = React.useState(null)
1217
+ React.useEffect(() => {
1218
+ setNow(Date.now())
1219
+ const t = setInterval(() => setNow(Date.now()), 15000)
1220
+ return () => clearInterval(t)
1221
+ }, [])
1222
+
1223
+ const todayKey = dateKey(Date.now())
1224
+ const WEEK = ['一', '二', '三', '四', '五', '六', '日']
1225
+
1226
+ function fmtShort(ms) {
1227
+ if (ms <= 0) return ''
1228
+ const m = Math.round(ms / 60000)
1229
+ if (m < 60) return m + 'm'
1230
+ return Math.floor(m / 60) + 'h' + String(m % 60).padStart(2, '0')
1231
+ }
1232
+
1233
+ const tb = HIST[todayKey] || { sitMs: 0, breaks: 0, reminders: 0, maxStretch: 0 }
1234
+ // The stretch that is still open right now counts toward "longest
1235
+ // continuous" too, marked as in-progress. Clamp to the sitting anchor so
1236
+ // it can never exceed the accumulated sitting time.
1237
+ const openStretchMs = S.mode === 'sitting' ? Date.now() - Math.max(S.stretchStart, S.sitAnchor) : 0
1238
+ const openIsMax = openStretchMs >= 60000 && openStretchMs >= (tb.maxStretch || 0)
1239
+ const tbStretch = Math.max(tb.maxStretch || 0, openStretchMs)
1240
+ const tbSit = daySitMs(tb) + openStretchMs
1241
+ let max30Stretch = openStretchMs
1242
+ for (let i = 0; i < 30; i++) {
1243
+ const b = HIST[dateKey(Date.now() - i * 86400000)]
1244
+ if (b && typeof b.maxStretch === 'number' && b.maxStretch > max30Stretch) max30Stretch = b.maxStretch
1245
+ }
1246
+
1247
+ function agg(days) {
1248
+ let sit = 0, br = 0, re = 0, cy = 0, nDays = 0
1249
+ for (let i = 0; i < days; i++) {
1250
+ const b = HIST[dateKey(Date.now() - i * 86400000)]
1251
+ const sitV = daySitMs(b) + (i === 0 ? openStretchMs : 0)
1252
+ if (sitV > 0) nDays++
1253
+ if (b) { sit += sitV; br += b.breaks; re += b.reminders; cy += b.cycles }
1254
+ }
1255
+ return { sit, br, re, cy, nDays }
1256
+ }
1257
+ const w7 = agg(7)
1258
+ const w30 = agg(30)
1259
+
1260
+ // ---- calendar cells ----
1261
+ const first = new Date(ym.y, ym.m, 1)
1262
+ const lead = (first.getDay() + 6) % 7
1263
+ const dim = new Date(ym.y, ym.m + 1, 0).getDate()
1264
+ const cells = []
1265
+ for (let i = 0; i < lead; i++) cells.push(null)
1266
+ for (let d = 1; d <= dim; d++) cells.push({ d })
1267
+ const LEVEL_BG = ['', 'rgba(46,206,113,.10)', 'rgba(251,191,36,.16)', 'rgba(245,158,11,.26)', 'rgba(220,68,68,.32)']
1268
+
1269
+ const cellEl = (c) => {
1270
+ const key = dateKey(new Date(ym.y, ym.m, c.d).getTime())
1271
+ const b = HIST[key] || { sitMs: 0, breaks: 0, cycles: 0, reminders: 0 }
1272
+ const future = key > todayKey
1273
+ const sit = daySitMs(b) + (key === todayKey ? openStretchMs : 0)
1274
+ const level = sit <= 0 ? 0 : sit < 7200000 ? 1 : sit < 14400000 ? 2 : sit < 21600000 ? 3 : 4
1275
+ const cls = 'maxm-cal-cell' + (key === todayKey ? ' maxm-cal-today' : '') + (key === sel ? ' maxm-cal-sel' : '') + (future ? ' maxm-cal-future' : '')
1276
+ const dow = new Date(ym.y, ym.m, c.d).getDay()
1277
+ const h = HOLIDAYS[key]
1278
+ const weekend = dow === 0 || dow === 6
1279
+ const dayCls = 'maxm-cal-day' + (weekend && !(h && !h.holiday) ? ' maxm-cal-day-we' : '') + (h && h.holiday ? ' maxm-cal-day-ho' : '')
1280
+ const title = h ? (h.holiday ? (h.name || '节假日') : '调休上班') : (weekend ? '周末' : undefined)
1281
+ return React.createElement('div', {
1282
+ className: cls, key, style: { background: LEVEL_BG[level] },
1283
+ title,
1284
+ onClick: () => { if (!future) setSel(key) },
1285
+ },
1286
+ React.createElement('div', { className: dayCls }, c.d,
1287
+ h ? React.createElement('span', { className: 'maxm-cal-tag' }, h.holiday ? '假' : '班') : null),
1288
+ sit > 0 ? React.createElement('div', { className: 'maxm-cal-time' }, fmtShort(sit)) : null,
1289
+ (b.breaks > 0 || b.reminders > 0) ? React.createElement('div', { className: 'maxm-cal-sub' },
1290
+ (b.breaks > 0 ? '休' + b.breaks : '') + (b.reminders > 0 ? (b.breaks > 0 ? ' · ' : '') + '提' + b.reminders : '')) : null,
1291
+ )
1292
+ }
1293
+
1294
+ // ---- selected day detail ----
1295
+ const sd = new Date(Number(sel.slice(0, 4)), Number(sel.slice(5, 7)) - 1, Number(sel.slice(8, 10)))
1296
+ const sb = HIST[sel] || { sitMs: 0, breaks: 0, cycles: 0, reminders: 0 }
1297
+ const selTitle = (sd.getMonth() + 1) + '月' + sd.getDate() + '日 · 周' + WEEK[(sd.getDay() + 6) % 7] + (sel === todayKey ? '(今天)' : '')
1298
+ const selEmpty = (sel === todayKey ? tbSit : daySitMs(sb)) <= 0 && sb.breaks <= 0 && sb.reminders <= 0
1299
+
1300
+ const clear = () => {
1301
+ for (const k in HIST) delete HIST[k]
1302
+ persistHist()
1303
+ logEvent('clear', '清除了历史数据')
1304
+ setNow(Date.now())
1305
+ }
1306
+
1307
+ const nav = (delta) => {
1308
+ let y = ym.y
1309
+ let m = ym.m + delta
1310
+ if (m < 0) { m = 11; y -= 1 }
1311
+ if (m > 11) { m = 0; y += 1 }
1312
+ setYm({ y, m })
1313
+ }
1314
+
1315
+ // ---- stats view data ----
1316
+ let bestKey = null, bestMs = 0, mildKey = null, mildMs = Infinity, recDays = 0
1317
+ for (const k in HIST) {
1318
+ const b = HIST[k]
1319
+ if (!b) continue
1320
+ const v = daySitMs(b) + (k === todayKey ? openStretchMs : 0)
1321
+ if (v > 0) recDays++
1322
+ if (v > bestMs) { bestMs = v; bestKey = k }
1323
+ if (v > 0 && v < mildMs) { mildMs = v; mildKey = k }
1324
+ }
1325
+ const dayLabel = (k) => {
1326
+ const d = new Date(Number(k.slice(0, 4)), Number(k.slice(5, 7)) - 1, Number(k.slice(8, 10)))
1327
+ return (d.getMonth() + 1) + '/' + d.getDate()
1328
+ }
1329
+ const conv = w30.re > 0 ? Math.round(100 * w30.br / w30.re) + '%' : '—'
1330
+
1331
+ const bars = []
1332
+ for (let i = 0; i < 7; i++) {
1333
+ const t = new Date(Date.now() - i * 86400000)
1334
+ const k = dateKey(t.getTime())
1335
+ const b = HIST[k] || { sitMs: 0, breaks: 0 }
1336
+ bars.push({ k, label: i === 0 ? '今天' : (t.getMonth() + 1) + '/' + t.getDate(), sitMs: daySitMs(b) + (i === 0 ? openStretchMs : 0), breaks: b.breaks })
1337
+ }
1338
+ const barMax = Math.max(1, ...bars.map((b) => b.sitMs))
1339
+
1340
+ const vtab = React.createElement('div', { className: 'maxm-vtab' },
1341
+ React.createElement('button', { className: view === 'calendar' ? 'maxm-vtab-on' : '', onClick: () => setView('calendar') }, '📅 日历'),
1342
+ React.createElement('button', { className: view === 'stats' ? 'maxm-vtab-on' : '', onClick: () => setView('stats') }, '📊 统计'),
1343
+ )
1344
+
1345
+ const dayEvents = EVENTS.filter((e) => e && typeof e.t === 'number' && dateKey(e.t) === sel)
1346
+ const dayEventsBlock = dayEvents.length > 0 ? React.createElement('div', { className: 'maxm-evs' },
1347
+ React.createElement('div', { className: 'maxm-page-sub' }, '当日事件时间线'),
1348
+ dayEvents.map((e) => {
1349
+ const d = new Date(e.t)
1350
+ return React.createElement('div', { className: 'maxm-evrow', key: e.t + '-' + e.type },
1351
+ React.createElement('span', { className: 'maxm-evtime' }, String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0')),
1352
+ React.createElement('span', { className: 'maxm-evnote' }, e.note),
1353
+ )
1354
+ }),
1355
+ ) : null
1356
+
1357
+ const calView = React.createElement(React.Fragment, null,
1358
+ React.createElement('div', { className: 'maxm-cal-head' },
1359
+ React.createElement('button', { className: 'maxm-cal-nav', onClick: () => nav(-1) }, '‹'),
1360
+ React.createElement('div', { className: 'maxm-cal-title' }, ym.y + ' 年 ' + (ym.m + 1) + ' 月'),
1361
+ React.createElement('button', { className: 'maxm-cal-nav', onClick: () => nav(1) }, '›'),
1362
+ React.createElement('button', {
1363
+ className: 'maxm-cal-todaybtn',
1364
+ onClick: () => { const d = new Date(); setYm({ y: d.getFullYear(), m: d.getMonth() }); setSel(todayKey) },
1365
+ }, '回今天'),
1366
+ ),
1367
+ React.createElement('div', { className: 'maxm-cal-grid' },
1368
+ WEEK.map((w) => React.createElement('div', { className: 'maxm-cal-dow', key: 'w' + w }, w)),
1369
+ cells.map((c, i) => c === null ? React.createElement('div', { className: 'maxm-cal-cell maxm-cal-empty', key: 'pad' + i }) : cellEl(c)),
1370
+ ),
1371
+ React.createElement('div', { className: 'maxm-cal-detail' },
1372
+ React.createElement('div', { style: { fontSize: 12, fontWeight: 600, color: 'var(--dsw-alias-label-primary,#eee)', marginBottom: 6 } }, '📋 ' + selTitle),
1373
+ selEmpty
1374
+ ? React.createElement('div', { className: 'maxm-page-sub' }, '这一天没有在座记录——说明你坐得不多,或者插件当时没开 🙂')
1375
+ : React.createElement('div', { className: 'maxm-today' },
1376
+ React.createElement('span', null, '🪑 累计在座 ' + fmtHm(sel === todayKey ? tbSit : daySitMs(sb))),
1377
+ React.createElement('span', null, '📏 最长连续 ' + fmtHm(sel === todayKey ? tbStretch : (sb.maxStretch || 0)) + (sel === todayKey && openIsMax ? '(进行中)' : '')),
1378
+ React.createElement('span', null, '⏰ 提醒 ' + sb.reminders + ' 次'),
1379
+ React.createElement('span', null, '✅ 休息 ' + sb.breaks + ' 次'),
1380
+ React.createElement('span', null, '🔄 轮次 ' + sb.cycles),
1381
+ ),
1382
+ dayEventsBlock,
1383
+ ),
1384
+ )
1385
+
1386
+ const renderPreview = () => {
1387
+ try {
1388
+ const W = 720
1389
+ const H = 950
1390
+ const c = document.createElement('canvas')
1391
+ c.width = W * 3
1392
+ c.height = H * 3
1393
+ const x = c.getContext('2d')
1394
+ if (x === null) throw new Error('canvas 2d unavailable')
1395
+ x.scale(3, 3)
1396
+ x.fillStyle = '#14161b'
1397
+ x.fillRect(0, 0, W, H)
1398
+ x.fillStyle = '#1b1e26'
1399
+ x.fillRect(0, 0, W, 110)
1400
+ x.fillStyle = '#fbbf24'
1401
+ x.fillRect(0, 110, W, 4)
1402
+ const d0 = new Date()
1403
+ x.fillStyle = '#f2f3f7'
1404
+ x.font = '700 26px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1405
+ x.fillText('MAX 久坐沙漏 · 每日报告', 32, 56)
1406
+ x.fillStyle = '#9aa0ab'
1407
+ x.font = '14px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1408
+ x.fillText(d0.getFullYear() + ' 年 ' + (d0.getMonth() + 1) + ' 月 ' + d0.getDate() + ' 日 ' + String(d0.getHours()).padStart(2, '0') + ':' + String(d0.getMinutes()).padStart(2, '0') + ' 生成', 32, 86)
1409
+ let y = 152
1410
+ const section = (title) => {
1411
+ x.fillStyle = '#fbbf24'
1412
+ x.font = '700 17px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1413
+ x.fillText(title, 32, y)
1414
+ y += 26
1415
+ }
1416
+ const row = (label, value) => {
1417
+ x.fillStyle = '#aeb4bf'
1418
+ x.font = '14px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1419
+ x.fillText(label, 32, y)
1420
+ x.fillStyle = '#f2f3f7'
1421
+ x.font = '700 15px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1422
+ x.textAlign = 'right'
1423
+ x.fillText(value, W - 32, y)
1424
+ x.textAlign = 'left'
1425
+ y += 30
1426
+ }
1427
+ section('今日概览')
1428
+ row('累计在座(当天总时长,多段累加)', fmtHm(tbSit))
1429
+ row('最长连续在座(单次不离开)', fmtHm(tbStretch) + (openIsMax ? '(进行中)' : ''))
1430
+ row('提醒 / 完成休息', tb.reminders + ' 次 / ' + tb.breaks + ' 次')
1431
+ y += 12
1432
+ section('近 7 天每日累计在座')
1433
+ for (let i = 0; i < bars.length; i++) {
1434
+ const b = bars[i]
1435
+ x.fillStyle = '#aeb4bf'
1436
+ x.font = '12px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1437
+ x.fillText(b.label, 32, y + 11)
1438
+ x.fillStyle = '#232833'
1439
+ x.fillRect(120, y, W - 320, 16)
1440
+ const w = b.sitMs > 0 ? Math.max(4, (W - 320) * (b.sitMs / barMax)) : 0
1441
+ const g = x.createLinearGradient(120, 0, 120 + (W - 320), 0)
1442
+ g.addColorStop(0, '#fbbf24')
1443
+ g.addColorStop(1, '#b45309')
1444
+ x.fillStyle = g
1445
+ x.fillRect(120, y, w, 16)
1446
+ x.fillStyle = '#f2f3f7'
1447
+ x.font = '700 12px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1448
+ x.textAlign = 'right'
1449
+ x.fillText(fmtHm(b.sitMs), W - 32, y + 12)
1450
+ x.textAlign = 'left'
1451
+ y += 30
1452
+ }
1453
+ y += 12
1454
+ section('近 30 天汇总')
1455
+ row('累计在座', fmtHm(w30.sit))
1456
+ row('日均在座(' + w30.nDays + ' 天有记录)', w30.nDays > 0 ? fmtHm(w30.sit / w30.nDays) : '—')
1457
+ row('最长连续在座', fmtHm(max30Stretch) + (openIsMax ? '(进行中)' : ''))
1458
+ row('完成休息 / 提醒', w30.br + ' 次 / ' + w30.re + ' 次')
1459
+ y += 14
1460
+ x.fillStyle = '#636a76'
1461
+ x.font = '12px system-ui, "Segoe UI", "Microsoft YaHei", sans-serif'
1462
+ x.fillText('由 dsh-sitmax 插件生成 · 数据来源:本机浏览器(localStorage)', 32, y)
1463
+ const url = c.toDataURL('image/png')
1464
+ setPreviewUrl(url)
1465
+ } catch (e) {
1466
+ setRflash('⚠ 预览失败:' + String(e && e.message ? e.message : e))
1467
+ }
1468
+ }
1469
+
1470
+ const card = (k, v) => React.createElement('div', { className: 'maxm-card' },
1471
+ React.createElement('div', { className: 'maxm-card-v' }, v),
1472
+ React.createElement('div', { className: 'maxm-card-k' }, k),
1473
+ )
1474
+
1475
+ const statsView = React.createElement(React.Fragment, null,
1476
+ React.createElement('div', { className: 'maxm-page-sub' }, '「累计在座」是当天坐在电脑前的总时长(多段累加),不是连续坐着的时长;「最长连续」才是单次不离开的最长时长。'),
1477
+ React.createElement('div', { className: 'maxm-cards' },
1478
+ card('今日累计在座', fmtHm(tbSit)),
1479
+ card('今日最长连续在座', fmtHm(tbStretch) + (openIsMax ? ' · 进行中' : '')),
1480
+ card('近 7 天累计在座', fmtHm(w7.sit)),
1481
+ card('近 30 天累计在座', fmtHm(w30.sit)),
1482
+ card('近 30 天日均在座(' + w30.nDays + ' 天有记录)', w30.nDays > 0 ? fmtHm(w30.sit / w30.nDays) : '—'),
1483
+ card('近 30 天最长连续在座', fmtHm(max30Stretch) + (openIsMax ? ' · 进行中' : '')),
1484
+ card('近 30 天完成休息', w30.br + ' 次'),
1485
+ card('近 30 天提醒', w30.re + ' 次'),
1486
+ card('提醒 → 休息转化率', conv),
1487
+ ),
1488
+ bestKey !== null ? React.createElement('div', { className: 'maxm-page-sub' }, '🏆 单日累计最多:' + dayLabel(bestKey) + ' · ' + fmtHm(bestMs)) : null,
1489
+ mildKey !== null ? React.createElement('div', { className: 'maxm-page-sub' }, '🌿 单日累计最少:' + dayLabel(mildKey) + ' · ' + fmtHm(mildMs)) : null,
1490
+ React.createElement('div', { className: 'maxm-page-sub' }, '共 ' + recDays + ' 天有记录'),
1491
+ React.createElement('div', { className: 'maxm-page-title', style: { fontSize: 14, marginTop: 6 } }, '近 7 天每日累计在座'),
1492
+ bars.map((b) => React.createElement('div', { className: 'maxm-bar-row', key: b.k },
1493
+ React.createElement('span', { className: 'maxm-bar-lab' }, b.label),
1494
+ React.createElement('div', { className: 'maxm-bar-track' },
1495
+ React.createElement('div', { className: 'maxm-bar-fill', style: { width: (100 * b.sitMs / barMax).toFixed(1) + '%' } }),
1496
+ ),
1497
+ React.createElement('span', { className: 'maxm-bar-val' }, fmtHm(b.sitMs) + ' · 休' + b.breaks),
1498
+ )),
1499
+ rflash ? React.createElement('div', { className: 'maxm-set-flash' }, rflash) : null,
1500
+ React.createElement('div', { className: 'maxm-set-actions' },
1501
+ React.createElement('button', { className: 'maxm-btn maxm-btn-primary', onClick: renderPreview }, '🖼 预览报告图片'),
1502
+ React.createElement('button', { className: 'maxm-btn maxm-btn-ghost', onClick: clear }, '🗑 清除历史数据'),
1503
+ ),
1504
+ )
1505
+
1506
+ return React.createElement('div', { className: 'maxm-page' },
1507
+ React.createElement('div', { className: 'maxm-page-title' }, '久坐沙漏 · 每日报告'),
1508
+ React.createElement('div', { className: 'maxm-page-sub' }, '数据保存在本浏览器,跨会话累计;按自然日归档'),
1509
+ vtab,
1510
+ view === 'calendar' ? calView : statsView,
1511
+ previewUrl !== null ? React.createElement('div', { className: 'maxm-pv-backdrop', onClick: () => setPreviewUrl(null) },
1512
+ React.createElement('div', { className: 'maxm-pv-box', onClick: (e) => e.stopPropagation() },
1513
+ React.createElement('img', { className: 'maxm-pv-img', src: previewUrl, alt: '久坐报告预览' }),
1514
+ React.createElement('button', { type: 'button', className: 'maxm-pv-close', 'aria-label': '关闭预览', onClick: () => setPreviewUrl(null) }, '✕'),
1515
+ ),
1516
+ ) : null,
1517
+ )
1518
+ }
1519
+
1520
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register(
1521
+ { name: 'shell.overlay', id: 'dsh-sitmax-hud', order: 0, label: 'MAX 久坐监督沙漏' },
1522
+ () => React.createElement(MAXWidget),
1523
+ ))
1524
+ ctx.slots.inject('settings.section', () => ctx.slots.register(
1525
+ { name: 'settings.section', id: 'dsh-sitmax-settings', order: 12, label: '久坐沙漏 · 设置' },
1526
+ () => React.createElement(SettingsPage),
1527
+ ))
1528
+ ctx.slots.inject('settings.section', () => ctx.slots.register(
1529
+ { name: 'settings.section', id: 'dsh-sitmax-report', order: 13, label: '久坐沙漏 · 报告' },
1530
+ () => React.createElement(ReportPage),
1531
+ ))
1532
+ }
1533
+
1534
+ return module.exports;
1535
+ }
1536
+ });