@soffits/dsh-notify-inbox 0.0.0-stage → 0.1.0

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/client.js ADDED
@@ -0,0 +1,582 @@
1
+ /*
2
+ * Browser half of dsh-notify-inbox: the Inbox entry in the sidebar (with the
3
+ * unread count), its page, turning Web Push on for this browser, and the
4
+ * buttons on each notification.
5
+ *
6
+ * Plain JavaScript in DSH's Client module format (no build step); React comes
7
+ * from the page's module table. Everything the page shows comes from the
8
+ * plugin's /api/notify-inbox routes, which decide per request who is asking.
9
+ * A link with ?notify-inbox=<id> opens the page on that notification.
10
+ */
11
+ window.__ModuleLoader__.load({
12
+ id: '@soffits/dsh-notify-inbox',
13
+ factory(require) {
14
+ const React = require('react')
15
+ const h = React.createElement
16
+ const { useState, useEffect, useCallback, useSyncExternalStore } = React
17
+
18
+ const NS = 'dsh-notify-inbox'
19
+ const PANEL = 'dsh-notify-inbox'
20
+ const LINK_PARAM = 'notify-inbox'
21
+ const STYLE_ID = 'dsh-notify-inbox-style'
22
+ const PENDING_MS = 2 * 60 * 1000
23
+ const api = path => new URL(`api/notify-inbox/${path}`, document.baseURI).href
24
+
25
+ const en = {
26
+ panel: 'Inbox',
27
+ title: 'Inbox',
28
+ 'filter.unread': 'Unread',
29
+ 'filter.all': 'All',
30
+ 'markAll': 'Mark all read',
31
+ 'empty.unread': 'Nothing unread.',
32
+ 'empty.all': 'No notifications yet.',
33
+ 'loadMore': 'Show older',
34
+ 'urgent': 'Urgent',
35
+ 'test': 'Test',
36
+ 'alsoSent': 'Also sent to',
37
+ 'notSent': 'Not sent anywhere else',
38
+ 'files': 'Attachments',
39
+ 'notStored': 'not kept: {reason}',
40
+ 'action.chat': 'Ask about this',
41
+ 'action.done': 'Done',
42
+ 'action.snooze': 'Remind me later',
43
+ 'action.event': 'Send',
44
+ 'action.link': 'Open',
45
+ 'snooze.hour': 'In an hour',
46
+ 'snooze.evening': 'This evening',
47
+ 'snooze.tomorrow': 'Tomorrow morning',
48
+ 'press.pending': 'Sent, waiting…',
49
+ 'press.unhandled': 'Nobody picked this up yet',
50
+ 'press.done': 'Marked done',
51
+ 'press.snoozed': 'Will remind you {time}',
52
+ 'chat.intro': 'About this notification:',
53
+ 'chat.unavailable': 'Open a workspace first, then try again.',
54
+ 'push.title': 'Notifications on this device',
55
+ 'push.on': 'On',
56
+ 'push.off': 'Off',
57
+ 'push.enable': 'Turn on',
58
+ 'push.disable': 'Turn off',
59
+ 'push.test': 'Send a test',
60
+ 'push.testSent': 'Test sent to {n} device(s).',
61
+ 'push.denied': 'Notifications are blocked for this site in the browser settings.',
62
+ 'push.unsupported': 'This browser can’t receive push notifications here.',
63
+ 'push.ios': 'On iPhone or iPad, add this site to the Home Screen and open it from there to turn notifications on.',
64
+ 'error': 'Couldn’t load: {message}',
65
+ 'time.locale': 'en-US',
66
+ }
67
+ const zh = {
68
+ panel: '收件箱',
69
+ title: '收件箱',
70
+ 'filter.unread': '未读',
71
+ 'filter.all': '全部',
72
+ 'markAll': '全部已读',
73
+ 'empty.unread': '没有未读通知。',
74
+ 'empty.all': '还没有通知。',
75
+ 'loadMore': '更早的',
76
+ 'urgent': '紧急',
77
+ 'test': '测试',
78
+ 'alsoSent': '同时发到',
79
+ 'notSent': '没有发到别处',
80
+ 'files': '附件',
81
+ 'notStored': '未保存:{reason}',
82
+ 'action.chat': '问问这条',
83
+ 'action.done': '完成',
84
+ 'action.snooze': '稍后提醒',
85
+ 'action.event': '发送',
86
+ 'action.link': '打开',
87
+ 'snooze.hour': '一小时后',
88
+ 'snooze.evening': '今晚',
89
+ 'snooze.tomorrow': '明早',
90
+ 'press.pending': '已发出,等待处理…',
91
+ 'press.unhandled': '暂时没有人处理',
92
+ 'press.done': '已标为完成',
93
+ 'press.snoozed': '会在{time}再提醒',
94
+ 'chat.intro': '关于这条通知:',
95
+ 'chat.unavailable': '先打开一个工作区,再试一次。',
96
+ 'push.title': '本设备的通知',
97
+ 'push.on': '已开启',
98
+ 'push.off': '未开启',
99
+ 'push.enable': '开启',
100
+ 'push.disable': '关闭',
101
+ 'push.test': '发一条测试',
102
+ 'push.testSent': '测试已发到 {n} 台设备。',
103
+ 'push.denied': '浏览器设置里禁止了这个网站的通知。',
104
+ 'push.unsupported': '这个浏览器在这里收不到推送通知。',
105
+ 'push.ios': 'iPhone 或 iPad 上,先把这个网站添加到主屏幕,再从主屏幕打开,才能开启通知。',
106
+ 'error': '加载失败:{message}',
107
+ 'time.locale': 'zh-CN',
108
+ }
109
+
110
+ const CSS = `
111
+ .nib-page{width:100%;min-width:0;height:100%;min-height:0;display:flex;flex-direction:column;overflow:hidden;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font-size:14px;line-height:1.6}
112
+ .nib-scroll{flex:1;min-height:0;overflow:auto;scrollbar-gutter:stable}
113
+ .nib-content{max-width:820px;margin:0 auto;padding:0 clamp(16px,4vw,48px) 48px}
114
+ .nib-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;padding-top:28px;margin-bottom:16px}
115
+ [data-platform=darwin] .nib-head{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}
116
+ .nib-head h1{margin:0;font-size:20px;font-weight:500;line-height:28px;flex:1;min-width:0}
117
+ .nib-count{color:var(--dsw-alias-label-tertiary);font-size:13px;margin-left:8px;font-weight:400}
118
+ .nib-tabs{display:inline-flex;gap:2px;padding:2px;border-radius:10px;background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-interactive-bg-hover))}
119
+ .nib-tab{border:none;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;padding:2px 12px;border-radius:8px;cursor:pointer}
120
+ .nib-tab[aria-pressed=true]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 0 0 .5px var(--dsw-alias-border-l3)}
121
+ .nib-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:4px;height:28px;padding:0 10px;border:none;border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;box-shadow:inset 0 0 0 var(--dsh-hairline-width,.5px) var(--dsh-button-outline-color,var(--dsw-alias-border-l3));text-decoration:none;white-space:nowrap}
122
+ .nib-btn:disabled{cursor:not-allowed;opacity:.4}
123
+ @media (hover:hover){.nib-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.nib-item:hover{background:var(--dsw-alias-interactive-bg-hover)}}
124
+ .nib-primary{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-on-color,#fff);box-shadow:none}
125
+ .nib-push{display:flex;align-items:center;flex-wrap:wrap;gap:8px;padding:10px 12px;margin-bottom:16px;border-radius:12px;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary);font-size:13px}
126
+ .nib-push strong{font-weight:500;color:var(--dsw-alias-label-primary)}
127
+ .nib-push .nib-grow{flex:1;min-width:120px}
128
+ .nib-hint{width:100%;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
129
+ .nib-list{display:flex;flex-direction:column;gap:2px;margin:0;padding:0;list-style:none}
130
+ .nib-item{border-radius:12px;padding:10px 12px;position:relative}
131
+ .nib-item.nib-open{background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-interactive-bg-hover))}
132
+ .nib-row{display:flex;gap:10px;align-items:flex-start;width:100%;border:none;background:transparent;color:inherit;font:inherit;text-align:left;padding:0;cursor:pointer}
133
+ .nib-dot{flex:none;width:8px;height:8px;border-radius:50%;margin-top:8px;background:transparent}
134
+ .nib-unread .nib-dot{background:var(--dsw-alias-state-business-primary)}
135
+ .nib-unread.nib-urgent .nib-dot{background:var(--dsw-alias-state-error-primary)}
136
+ .nib-main{flex:1;min-width:0}
137
+ .nib-titleLine{display:flex;align-items:baseline;gap:8px;min-width:0}
138
+ .nib-title{flex:1;min-width:0;font-weight:400;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}
139
+ .nib-unread .nib-title{font-weight:600;color:var(--dsw-alias-label-primary)}
140
+ .nib-open .nib-title{white-space:normal;overflow-wrap:anywhere}
141
+ .nib-time{flex:none;color:var(--dsw-alias-label-caption);font-size:12px}
142
+ .nib-spoken{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow-wrap:anywhere}
143
+ .nib-chip{display:inline-block;flex:none;padding:0 6px;border-radius:6px;font-size:11px;line-height:18px;font-weight:500;color:var(--dsw-alias-state-error-primary);box-shadow:inset 0 0 0 .5px currentColor}
144
+ .nib-chip.nib-muted{color:var(--dsw-alias-label-tertiary)}
145
+ .nib-body{margin:8px 0 0 18px;display:flex;flex-direction:column;gap:10px}
146
+ .nib-text{white-space:pre-wrap;overflow-wrap:anywhere;font-size:14px;line-height:22px}
147
+ .nib-links{display:flex;flex-direction:column;gap:2px;font-size:13px}
148
+ .nib-links a{color:var(--dsw-alias-state-business-primary);overflow-wrap:anywhere}
149
+ .nib-meta{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
150
+ .nib-route{display:inline-flex;gap:3px;margin-right:10px}
151
+ .nib-ok{color:var(--dsw-alias-state-success-primary)}
152
+ .nib-bad{color:var(--dsw-alias-state-error-primary)}
153
+ .nib-actions{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
154
+ .nib-menu{display:flex;flex-wrap:wrap;gap:6px;padding:6px;border-radius:10px;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3)}
155
+ .nib-status{color:var(--dsw-alias-label-tertiary);font-size:12px}
156
+ .nib-empty{color:var(--dsw-alias-label-tertiary);padding:24px 12px}
157
+ .nib-error{color:var(--dsw-alias-state-error-primary);padding:12px}
158
+ .nib-more{margin:12px auto 0;display:flex}
159
+ .nib-icon{position:relative;display:inline-flex}
160
+ .nib-badge{position:absolute;top:-5px;right:-8px;min-width:14px;height:14px;padding:0 3px;box-sizing:border-box;border-radius:7px;background:var(--dsw-alias-state-error-primary);color:#fff;font-size:9px;font-weight:600;line-height:14px;text-align:center;pointer-events:none}
161
+ @media (width<=640px){.nib-content{padding-inline:12px}.nib-head{padding-top:16px}.nib-body{margin-left:0}.nib-item{padding:10px 8px}}
162
+ `
163
+
164
+ // ---- shared state: the unread count and a version that bumps when anything changes ----
165
+
166
+ const shared = { unread: 0, version: 0, pollSeconds: 30, linked: null }
167
+ const listeners = new Set()
168
+ const emit = () => { for (const listener of listeners) listener() }
169
+ const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener) }
170
+ const useShared = select => useSyncExternalStore(subscribe, () => select(shared))
171
+
172
+ async function call(path, value) {
173
+ const init = value === undefined
174
+ ? { credentials: 'same-origin', headers: { accept: 'application/json' } }
175
+ : { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(value) }
176
+ const response = await fetch(api(path), init)
177
+ const body = await response.json().catch(() => ({}))
178
+ if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`)
179
+ return body
180
+ }
181
+
182
+ let lastSummary = ''
183
+ async function refreshSummary() {
184
+ try {
185
+ const summary = await call('summary')
186
+ shared.pollSeconds = summary.pollSeconds || 30
187
+ const key = `${summary.unread}|${summary.latest}|${summary.total}`
188
+ if (key !== lastSummary) {
189
+ lastSummary = key
190
+ shared.unread = summary.unread
191
+ shared.version += 1
192
+ emit()
193
+ }
194
+ } catch {
195
+ // Signed out or DSH restarting; try again at the next tick.
196
+ }
197
+ }
198
+ const changed = () => { lastSummary = ''; refreshSummary() }
199
+
200
+ // ---- time ----
201
+
202
+ function relative(iso, t) {
203
+ const seconds = (Date.parse(iso) - Date.now()) / 1000
204
+ const format = new Intl.RelativeTimeFormat(t('time.locale'), { numeric: 'auto', style: 'short' })
205
+ const abs = Math.abs(seconds)
206
+ if (abs < 60) return format.format(Math.round(seconds), 'second')
207
+ if (abs < 3600) return format.format(Math.round(seconds / 60), 'minute')
208
+ if (abs < 86400) return format.format(Math.round(seconds / 3600), 'hour')
209
+ if (abs < 86400 * 7) return format.format(Math.round(seconds / 86400), 'day')
210
+ return new Date(iso).toLocaleDateString(t('time.locale'), { month: 'short', day: 'numeric' })
211
+ }
212
+ const absolute = (iso, t) => new Date(iso).toLocaleString(t('time.locale'), { dateStyle: 'medium', timeStyle: 'short' })
213
+
214
+ /** Snooze choices as ISO times with this browser's offset. */
215
+ function snoozeTimes() {
216
+ const now = new Date()
217
+ const hour = new Date(now.getTime() + 3600 * 1000)
218
+ const evening = new Date(now)
219
+ evening.setHours(19, 0, 0, 0)
220
+ if (evening.getTime() - now.getTime() < 2 * 3600 * 1000) evening.setTime(now.getTime() + 3 * 3600 * 1000)
221
+ const tomorrow = new Date(now)
222
+ tomorrow.setDate(tomorrow.getDate() + 1)
223
+ tomorrow.setHours(9, 0, 0, 0)
224
+ const iso = date => {
225
+ const offset = -date.getTimezoneOffset()
226
+ const pad = n => String(Math.floor(Math.abs(n))).padStart(2, '0')
227
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:00${offset >= 0 ? '+' : '-'}${pad(offset / 60)}:${pad(offset % 60)}`
228
+ }
229
+ return [['snooze.hour', iso(hour)], ['snooze.evening', iso(evening)], ['snooze.tomorrow', iso(tomorrow)]]
230
+ }
231
+
232
+ /** What happened to this item's latest press, in words, or null. */
233
+ function pressStatus(item, t) {
234
+ const press = item.presses[item.presses.length - 1]
235
+ if (press === undefined) return null
236
+ const handled = item.handled.find(row => row.press === press.press)
237
+ if (handled !== undefined) {
238
+ if (handled.result === 'snoozed' && handled.until) return t('press.snoozed', { time: absolute(handled.until, t) })
239
+ if (handled.result === 'done') return t('press.done')
240
+ return handled.result
241
+ }
242
+ return Date.now() - Date.parse(press.at) < PENDING_MS ? t('press.pending') : t('press.unhandled')
243
+ }
244
+
245
+ function chatPrompt(item, t) {
246
+ const quoted = [item.title, item.text || item.spoken].filter(Boolean).join('\n\n').split('\n').map(line => `> ${line}`).join('\n')
247
+ const context = { notification: item.id, time: item.time, lane: item.lane, domain: item.domain || undefined, links: item.links.length ? item.links : undefined }
248
+ return `${t('chat.intro')}\n\n${quoted}\n\n\`\`\`json\n${JSON.stringify(context)}\n\`\`\`\n\n`
249
+ }
250
+
251
+ // ---- the actions row (a thin local adapter until a shared actions module exists) ----
252
+
253
+ function Actions({ item, t, startChat }) {
254
+ const [snoozing, setSnoozing] = useState(false)
255
+ const [busy, setBusy] = useState(false)
256
+ const [error, setError] = useState(null)
257
+ const press = async (action, until) => {
258
+ setBusy(true)
259
+ setError(null)
260
+ try {
261
+ await call('action', { record: item.id, action: action.id, ...(until ? { until } : {}) })
262
+ setSnoozing(false)
263
+ changed()
264
+ } catch (reason) {
265
+ setError(reason.message)
266
+ } finally {
267
+ setBusy(false)
268
+ }
269
+ }
270
+ const declared = item.actions.filter(action => action.kind !== 'chat')
271
+ const chat = item.actions.find(action => action.kind === 'chat') ?? { kind: 'chat', id: 'chat', label: '', payload: {} }
272
+ const label = action => action.label || t(`action.${action.kind}`)
273
+ const buttons = [
274
+ h('button', { key: 'chat', type: 'button', className: 'nib-btn', onClick: () => startChat(chat.payload?.prompt ? `${chat.payload.prompt}\n\n${chatPrompt(item, t)}` : chatPrompt(item, t)) }, label(chat)),
275
+ ...declared.map(action => {
276
+ if (action.kind === 'link') {
277
+ return h('a', { key: action.id, className: 'nib-btn', href: action.payload.url, target: action.payload.url.startsWith('/') ? undefined : '_blank', rel: 'noopener noreferrer' }, label(action))
278
+ }
279
+ if (action.kind === 'snooze' && !action.payload.until) {
280
+ return h('button', { key: action.id, type: 'button', className: 'nib-btn', disabled: busy, 'aria-expanded': snoozing, onClick: () => setSnoozing(!snoozing) }, label(action))
281
+ }
282
+ return h('button', { key: action.id, type: 'button', className: `nib-btn${action.kind === 'done' ? ' nib-primary' : ''}`, disabled: busy, onClick: () => press(action) }, label(action))
283
+ }),
284
+ ]
285
+ const snooze = declared.find(action => action.kind === 'snooze')
286
+ const status = pressStatus(item, t)
287
+ return h(React.Fragment, null,
288
+ h('div', { className: 'nib-actions' }, ...buttons, status && h('span', { className: 'nib-status' }, status)),
289
+ snoozing && snooze && h('div', { className: 'nib-menu', role: 'group' },
290
+ snoozeTimes().map(([key, until]) => h('button', { key, type: 'button', className: 'nib-btn', disabled: busy, onClick: () => press(snooze, until) }, t(key)))),
291
+ error && h('div', { className: 'nib-error', role: 'alert' }, error))
292
+ }
293
+
294
+ // ---- one notification ----
295
+
296
+ function Item({ item, t, open, onToggle, startChat }) {
297
+ const urgent = item.lane === 'interrupt'
298
+ const className = ['nib-item', item.read ? '' : 'nib-unread', urgent ? 'nib-urgent' : '', open ? 'nib-open' : ''].filter(Boolean).join(' ')
299
+ const title = item.title || item.spoken || item.text.slice(0, 80)
300
+ const sub = item.spoken && item.spoken !== title ? item.spoken : item.text !== title ? item.text : ''
301
+ return h('li', { className, id: `nib-${item.id}` },
302
+ h('button', { type: 'button', className: 'nib-row', 'aria-expanded': open, onClick: () => onToggle(item) },
303
+ h('span', { className: 'nib-dot', 'aria-hidden': true }),
304
+ h('span', { className: 'nib-main' },
305
+ h('span', { className: 'nib-titleLine' },
306
+ urgent && h('span', { className: 'nib-chip' }, t('urgent')),
307
+ item.test && h('span', { className: 'nib-chip nib-muted' }, t('test')),
308
+ h('span', { className: 'nib-title' }, title),
309
+ h('span', { className: 'nib-time', title: absolute(item.time, t) }, relative(item.time, t))),
310
+ !open && sub && h('span', { className: 'nib-spoken' }, sub))),
311
+ open && h('div', { className: 'nib-body' },
312
+ item.text && item.text !== title && h('div', { className: 'nib-text' }, item.text),
313
+ item.links.length > 0 && h('div', { className: 'nib-links' },
314
+ item.links.map(link => h('a', { key: link, href: link, target: '_blank', rel: 'noopener noreferrer' }, link))),
315
+ item.files.length > 0 && h('div', { className: 'nib-links' },
316
+ h('span', { className: 'nib-meta' }, t('files')),
317
+ item.files.map(file => file.stored
318
+ ? h('a', { key: file.name, href: api(`file?id=${encodeURIComponent(item.id)}&name=${encodeURIComponent(file.name)}`), target: '_blank', rel: 'noopener' }, file.name)
319
+ : h('span', { key: file.name, className: 'nib-meta' }, `${file.name} (${t('notStored', { reason: file.reason || '?' })})`))),
320
+ h(Actions, { item, t, startChat }),
321
+ h('div', { className: 'nib-meta' },
322
+ item.routed.length === 0 ? t('notSent') : h(React.Fragment, null, `${t('alsoSent')}: `,
323
+ item.routed.map(row => h('span', { key: row.destination, className: 'nib-route', title: row.detail || '' },
324
+ row.destination, h('span', { className: row.ok ? 'nib-ok' : 'nib-bad' }, row.ok ? '✓' : '✗'),
325
+ !row.ok && row.detail ? ` ${row.detail}` : ''))),
326
+ ` · ${absolute(item.time, t)}`)))
327
+ }
328
+
329
+ // ---- push on this device ----
330
+
331
+ const pushSupported = () => typeof navigator !== 'undefined' && 'serviceWorker' in navigator && typeof window.PushManager === 'function' && typeof window.Notification === 'function'
332
+ const isIos = () => /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
333
+ const standalone = () => window.matchMedia?.('(display-mode: standalone)').matches || navigator.standalone === true
334
+ const keyBytes = base64url => {
335
+ const base64 = base64url.replaceAll('-', '+').replaceAll('_', '/')
336
+ return Uint8Array.from(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')), c => c.charCodeAt(0))
337
+ }
338
+ const deviceLabel = () => {
339
+ const ua = navigator.userAgent
340
+ const os = /iPhone|iPad/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : ''
341
+ const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser'
342
+ return [browser, os].filter(Boolean).join(' on ')
343
+ }
344
+
345
+ async function currentSubscription() {
346
+ const registration = await navigator.serviceWorker.getRegistration(api(''))
347
+ return (await registration?.pushManager.getSubscription()) ?? null
348
+ }
349
+
350
+ function PushControl({ t }) {
351
+ const supported = pushSupported()
352
+ const [state, setState] = useState('checking')
353
+ const [note, setNote] = useState(null)
354
+ const [busy, setBusy] = useState(false)
355
+ useEffect(() => {
356
+ if (!supported) return
357
+ let live = true
358
+ currentSubscription()
359
+ .then(async sub => (sub === null ? false : (await call('push/state', { endpoint: sub.endpoint })).subscribed))
360
+ .then(on => { if (live) setState(on ? 'on' : 'off') }, () => { if (live) setState('off') })
361
+ return () => { live = false }
362
+ }, [supported])
363
+ if (!supported) {
364
+ return h('div', { className: 'nib-push' }, h('span', { className: 'nib-grow' }, h('strong', null, t('push.title'))),
365
+ h('span', { className: 'nib-hint' }, isIos() && !standalone() ? t('push.ios') : t('push.unsupported')))
366
+ }
367
+ const run = task => async () => {
368
+ setBusy(true)
369
+ setNote(null)
370
+ try {
371
+ await task()
372
+ } catch (reason) {
373
+ setNote(reason.message)
374
+ } finally {
375
+ setBusy(false)
376
+ }
377
+ }
378
+ const enable = run(async () => {
379
+ const permission = await Notification.requestPermission()
380
+ if (permission !== 'granted') {
381
+ setNote(t('push.denied'))
382
+ return
383
+ }
384
+ const { publicKey } = await call('push/config')
385
+ const registration = await navigator.serviceWorker.register(api('sw.js'), { scope: api('') })
386
+ const worker = registration.installing ?? registration.waiting ?? registration.active
387
+ if (worker && worker.state !== 'activated') {
388
+ await new Promise(resolve => worker.addEventListener('statechange', () => { if (worker.state === 'activated') resolve() }))
389
+ }
390
+ let sub = await registration.pushManager.getSubscription()
391
+ sub ??= await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(publicKey) })
392
+ await call('push/subscribe', { subscription: sub.toJSON(), label: deviceLabel() })
393
+ setState('on')
394
+ })
395
+ const disable = run(async () => {
396
+ const sub = await currentSubscription()
397
+ if (sub !== null) {
398
+ await call('push/unsubscribe', { endpoint: sub.endpoint })
399
+ await sub.unsubscribe()
400
+ }
401
+ setState('off')
402
+ })
403
+ const test = run(async () => {
404
+ const result = await call('push/test', {})
405
+ setNote(t('push.testSent', { n: result.sent }))
406
+ })
407
+ return h('div', { className: 'nib-push' },
408
+ h('span', { className: 'nib-grow' }, h('strong', null, t('push.title')), ' · ', state === 'on' ? t('push.on') : state === 'off' ? t('push.off') : '…'),
409
+ state === 'on' && h('button', { type: 'button', className: 'nib-btn', disabled: busy, onClick: test }, t('push.test')),
410
+ state === 'on' && h('button', { type: 'button', className: 'nib-btn', disabled: busy, onClick: disable }, t('push.disable')),
411
+ state === 'off' && h('button', { type: 'button', className: 'nib-btn nib-primary', disabled: busy, onClick: enable }, t('push.enable')),
412
+ note && h('span', { className: 'nib-hint' }, note))
413
+ }
414
+
415
+ // ---- the page ----
416
+
417
+ function InboxPage({ translate: t, startChat }) {
418
+ const version = useShared(s => s.version)
419
+ const unread = useShared(s => s.unread)
420
+ const linked = useShared(s => s.linked)
421
+ const [filter, setFilter] = useState(() => (shared.linked ? 'all' : 'unread'))
422
+ const [items, setItems] = useState(null)
423
+ const [more, setMore] = useState(false)
424
+ const [error, setError] = useState(null)
425
+ const [open, setOpen] = useState(() => shared.linked)
426
+
427
+ const load = useCallback(async (append) => {
428
+ try {
429
+ const params = new URLSearchParams()
430
+ if (filter === 'unread') params.set('unread', '1')
431
+ if (append && items?.length) params.set('before', items[items.length - 1].id)
432
+ const page = await call(`items?${params}`)
433
+ setItems(previous => (append && previous ? [...previous, ...page.items] : page.items))
434
+ setMore(page.more)
435
+ setError(null)
436
+ } catch (reason) {
437
+ setError(reason.message)
438
+ }
439
+ }, [filter, items])
440
+
441
+ useEffect(() => { load(false) }, [filter, version])
442
+ useEffect(() => {
443
+ if (!linked) return
444
+ setFilter('all')
445
+ setOpen(linked)
446
+ shared.linked = null
447
+ call('read', { ids: [linked] }).then(changed, () => {})
448
+ setTimeout(() => document.getElementById(`nib-${linked}`)?.scrollIntoView({ block: 'center' }), 300)
449
+ }, [linked])
450
+
451
+ const toggle = item => {
452
+ const next = open === item.id ? null : item.id
453
+ setOpen(next)
454
+ if (next !== null && !item.read) {
455
+ setItems(list => list.map(row => (row.id === item.id ? { ...row, read: true } : row)))
456
+ call('read', { ids: [item.id] }).then(changed, () => {})
457
+ }
458
+ }
459
+ const markAll = () => call('read', { all: true }).then(changed, reason => setError(reason.message))
460
+
461
+ return h('div', { className: 'nib-page' },
462
+ h('div', { className: 'nib-scroll' },
463
+ h('div', { className: 'nib-content' },
464
+ h('div', { className: 'nib-head' },
465
+ h('h1', null, t('title'), unread > 0 && h('span', { className: 'nib-count' }, unread)),
466
+ h('div', { className: 'nib-tabs', role: 'group' },
467
+ ['unread', 'all'].map(key => h('button', { key, type: 'button', className: 'nib-tab', 'aria-pressed': filter === key, onClick: () => setFilter(key) }, t(`filter.${key}`)))),
468
+ h('button', { type: 'button', className: 'nib-btn', disabled: unread === 0, onClick: markAll }, t('markAll'))),
469
+ h(PushControl, { t }),
470
+ error && h('p', { className: 'nib-error', role: 'alert' }, t('error', { message: error })),
471
+ items !== null && items.length === 0 && h('p', { className: 'nib-empty' }, t(filter === 'unread' ? 'empty.unread' : 'empty.all')),
472
+ items !== null && h('ul', { className: 'nib-list' },
473
+ items.map(item => h(Item, { key: item.id, item, t, open: open === item.id, onToggle: toggle, startChat }))),
474
+ more && h('button', { type: 'button', className: 'nib-btn nib-more', onClick: () => load(true) }, t('loadMore')))))
475
+ }
476
+
477
+ function SidebarIcon({ size }) {
478
+ const unread = useShared(s => s.unread)
479
+ const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' }
480
+ return h('span', { className: 'nib-icon' },
481
+ h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, focusable: 'false' },
482
+ h('path', { d: 'M8 2.2c-2.3 0-3.9 1.8-3.9 4v2.3L3 10.4c-.2.4.1.9.5.9h9c.4 0 .7-.5.5-.9l-1.1-1.9V6.2c0-2.2-1.6-4-3.9-4Z', ...stroke }),
483
+ h('path', { d: 'M6.5 13.2c.3.7.9 1.1 1.5 1.1s1.2-.4 1.5-1.1', ...stroke })),
484
+ unread > 0 && h('span', { className: 'nib-badge' }, unread > 99 ? '99+' : String(unread)))
485
+ }
486
+
487
+ return {
488
+ inject: ['slots', 'locale'],
489
+ apply(ctx) {
490
+ ctx.effect(() => {
491
+ const disposers = [ctx.locale.register(NS, 'en', en), ctx.locale.register(NS, 'zh', zh)]
492
+ return () => { for (const dispose of disposers) dispose() }
493
+ }, 'notify-inbox: dictionaries')
494
+ const t = ctx.locale.bind(NS)
495
+
496
+ ctx.effect(() => {
497
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return () => {}
498
+ const tag = document.createElement('style')
499
+ tag.id = STYLE_ID
500
+ tag.textContent = CSS
501
+ document.head.appendChild(tag)
502
+ return () => tag.remove()
503
+ }, 'notify-inbox: styles')
504
+
505
+ const startChat = prompt => {
506
+ const workspace = ctx.get('uiWorkspace')
507
+ if (workspace === undefined) {
508
+ window.alert(t('chat.unavailable'))
509
+ return
510
+ }
511
+ workspace.startSession(undefined, { prompt, whenDraftExists: 'replace' })
512
+ }
513
+
514
+ ctx.slots.inject('main', () => ctx.slots.register({
515
+ name: 'main',
516
+ key: PANEL,
517
+ locale: NS,
518
+ inject: () => ({ translate: t, startChat }),
519
+ }, InboxPage))
520
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
521
+ name: 'sidebar.panellist',
522
+ id: PANEL,
523
+ order: 11,
524
+ locale: NS,
525
+ label: () => t('panel'),
526
+ }, SidebarIcon))
527
+
528
+ // The unread count: checked while the page is visible, and right away when it becomes visible.
529
+ ctx.effect(() => {
530
+ let timer
531
+ const tick = () => {
532
+ clearTimeout(timer)
533
+ if (document.visibilityState === 'visible') refreshSummary()
534
+ timer = setTimeout(tick, shared.pollSeconds * 1000)
535
+ }
536
+ const onVisible = () => { if (document.visibilityState === 'visible') tick() }
537
+ document.addEventListener('visibilitychange', onVisible)
538
+ tick()
539
+ return () => { clearTimeout(timer); document.removeEventListener('visibilitychange', onVisible) }
540
+ }, 'notify-inbox: unread count')
541
+
542
+ // ?notify-inbox=<id> (a tapped push, a shared link) opens the page on that notification.
543
+ const openLinked = id => {
544
+ shared.linked = id || null
545
+ emit()
546
+ let tries = 0
547
+ const timer = setInterval(() => {
548
+ const layout = ctx.get('layout')
549
+ try {
550
+ layout?.selectPanel(PANEL)
551
+ if (layout) clearInterval(timer)
552
+ } catch {
553
+ // The main slot entry is not registered yet.
554
+ }
555
+ if (++tries > 50) clearInterval(timer)
556
+ }, 100)
557
+ }
558
+ ctx.effect(() => {
559
+ const params = new URLSearchParams(location.search)
560
+ if (params.has(LINK_PARAM)) {
561
+ const id = params.get(LINK_PARAM)
562
+ params.delete(LINK_PARAM)
563
+ const query = params.toString()
564
+ history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`)
565
+ openLinked(id)
566
+ }
567
+ const onMessage = event => {
568
+ if (event.data?.type !== 'notify-inbox/open') return
569
+ try {
570
+ openLinked(new URL(event.data.url, location.href).searchParams.get(LINK_PARAM))
571
+ } catch {
572
+ // Not one of ours.
573
+ }
574
+ }
575
+ navigator.serviceWorker?.addEventListener('message', onMessage)
576
+ navigator.serviceWorker?.startMessages?.()
577
+ return () => navigator.serviceWorker?.removeEventListener('message', onMessage)
578
+ }, 'notify-inbox: links')
579
+ },
580
+ }
581
+ },
582
+ })
@@ -0,0 +1,9 @@
1
+ # Bundle layer for @soffits/dsh-notify-inbox: one Host row serving the inbox
2
+ # to the Web UI. Set dataDir (the folder your notification router files into)
3
+ # and, for a DSH several people sign in to, people / peopleFile in a profile
4
+ # override of this row.
5
+ - insert:
6
+ - id: notify-inbox
7
+ name: '@soffits/dsh-notify-inbox'
8
+ config:
9
+ dataDir: ~/.dsh/notify-inbox
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" fill="none">
2
+ <rect width="64" height="64" rx="14" fill="#4D6BFE"/>
3
+ <path d="M32 14c-7.2 0-12 5.4-12 12.4v7.4l-3.6 6.2c-.7 1.2.2 2.7 1.6 2.7h28c1.4 0 2.3-1.5 1.6-2.7L44 33.8v-7.4C44 19.4 39.2 14 32 14Z" stroke="#fff" stroke-width="3.5" stroke-linejoin="round"/>
4
+ <path d="M27 47.5c.9 2.3 2.8 3.7 5 3.7s4.1-1.4 5-3.7" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
5
+ <circle cx="45" cy="18" r="6" fill="#FF6B5B" stroke="#4D6BFE" stroke-width="2.5"/>
6
+ </svg>