@soffits/dsh-notify-inbox 0.1.3 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Under Unread, a notification you open, mark done or snooze stays where it is, shown as read, until you leave the view or tap Unread again, so the list never moves under your finger. Mark all read works the same way.
6
+ - Read notifications have a Mark unread button, in the row and in the open notification. It works on ones that Mark all read covered too.
7
+ - A done or snoozed notification shows its state in the collapsed row.
8
+ - On narrow screens the header wraps under the title instead of squeezing it.
9
+
10
+ ## 0.2.0
11
+
12
+ - Every word on the page comes from `locale/<tag>.json`, one file per language, picked up by what files exist; a missing key falls back to the primary language, then English. French joins English and Chinese.
13
+ - The test push speaks the page's language; the push payload and service worker carry no built-in words.
14
+ - The buttons module is the card board's current one (words come from the page's own table).
15
+
3
16
  ## 0.1.3
4
17
 
5
18
  - The buttons chunk keeps its names inside its own scope, so it loads next to another plugin's copy on the same page (DSH runs chunks as classic scripts in one global scope).
package/README.md CHANGED
@@ -84,9 +84,13 @@ Open the inbox on the device and press **Turn on**. The browser picks its own pu
84
84
 
85
85
  Tapping a notification opens the inbox on it. A device whose subscription expired is dropped the first time its push service says so.
86
86
 
87
+ ## Languages
88
+
89
+ The page follows DSH's language. Its words live in `locale/<tag>.json` (`ui` for the page, `meta` for the plugin list): English, French and Chinese ship. Another language is one more file with the same keys; anything it leaves out comes from its primary language (`pt` for `pt-BR`), then English. Notification text is shown as it was sent.
90
+
87
91
  ## Files the plugin writes
88
92
 
89
- All under `dataDir`: `<person>/read.json` (read marks), `<person>/actions.jsonl` (presses), `.push/subscriptions.json` and `.push/cursor.json` (how far each inbox was pushed, so a restart doesn't push the backlog), and the VAPID key unless `vapidFile` says otherwise. It never rewrites `inbox.jsonl`.
93
+ All under `dataDir`: `<person>/read.json` (read and unread marks), `<person>/actions.jsonl` (presses), `.push/subscriptions.json` and `.push/cursor.json` (how far each inbox was pushed, so a restart doesn't push the backlog), and the VAPID key unless `vapidFile` says otherwise. It never rewrites `inbox.jsonl`.
90
94
 
91
95
  ## Removing it
92
96
 
package/client.actions.js CHANGED
@@ -4,13 +4,23 @@
4
4
  *
5
5
  * A DSH client chunk: dsh-card-board's client loads it with
6
6
  * `require.async('./client.actions.js')`. Another plugin can ship a copy as
7
- * its own `client.actions.js`, changing OWNER below to its package name; the
8
- * file has no imports and takes React and the client context as arguments.
7
+ * its own `client.actions.js`, changing OWNER below to its package name.
8
+ *
9
+ * DSH runs a chunk as a classic script, so everything sits inside one function
10
+ * (a top-level `const` would clash with another plugin's copy and the second
11
+ * chunk would never register).
9
12
  *
10
13
  * const { createActions } = await require.async('./client.actions.js')
11
- * const ui = createActions({ React, ctx, locale: 'en', press })
14
+ * const ui = createActions({ React, ctx, t, press })
12
15
  * h(ui.ActionBar, { actions, states, chat, onPress })
13
16
  *
17
+ * `t(key, params)` gives the words in the person's language; the host plugin
18
+ * keeps them in its one message table. The keys it must know are exported as
19
+ * `KEYS`: chat, chatAbout, done, snooze, event, link, in3h, tomorrow, pick,
20
+ * set, cancel, sending, pending, handled, unhandled, failed ({message}),
21
+ * noWorkspace. `t` is called while rendering, so a language switch shows up
22
+ * without building the buttons again.
23
+ *
14
24
  * `press(action, extra)` is the plugin's own server call for done, snooze and
15
25
  * event (extra carries `until` for a snooze); it should resolve once the
16
26
  * server has accepted the press. `chat` and `link` never reach the server:
@@ -21,63 +31,34 @@
21
31
  (() => {
22
32
  const OWNER = '@soffits/dsh-notify-inbox'
23
33
 
24
- const WORDS = {
25
- en: {
26
- chat: 'Ask',
27
- chatAbout: 'Chat about this',
28
- done: 'Done',
29
- snooze: 'Snooze',
30
- open: 'Open',
31
- in3h: 'In 3 hours',
32
- tomorrow: 'Tomorrow 9:00',
33
- pick: 'Pick a time…',
34
- set: 'Snooze',
35
- cancel: 'Cancel',
36
- sending: 'Sending…',
37
- pending: 'Waiting for it to be picked up',
38
- handled: 'Done',
39
- unhandled: 'Nothing picked this up yet',
40
- failed: 'Didn’t go through: {message}',
41
- noWorkspace: 'Open a conversation once first, then try again.',
42
- },
43
- zh: {
44
- chat: '问问',
45
- chatAbout: '聊聊这个',
46
- done: '完成',
47
- snooze: '稍后提醒',
48
- open: '打开',
49
- in3h: '3 小时后',
50
- tomorrow: '明天 9:00',
51
- pick: '选个时间…',
52
- set: '稍后提醒',
53
- cancel: '取消',
54
- sending: '发送中…',
55
- pending: '等待处理',
56
- handled: '已处理',
57
- unhandled: '还没有被处理',
58
- failed: '没有成功:{message}',
59
- noWorkspace: '请先打开一次对话,再试一次。',
60
- },
61
- }
34
+ const KEYS = ['chat', 'chatAbout', 'done', 'snooze', 'event', 'link', 'in3h', 'tomorrow', 'pick', 'set', 'cancel', 'sending', 'pending', 'handled', 'unhandled', 'failed', 'noWorkspace']
62
35
 
63
36
  const CSS = `
64
- .ua-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
65
- .ua-btn{box-sizing:border-box;display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 10px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;white-space:nowrap;text-decoration:none;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3)}
37
+ .ua-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center;min-width:0}
38
+ .ua-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:32px;max-width:100%;padding:0 12px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;text-decoration:none;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3)}
39
+ .ua-btn span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
66
40
  .ua-btn svg{flex:none;width:14px;height:14px}
67
41
  .ua-btn:disabled{cursor:default;opacity:.7}
68
42
  @media (hover:hover){.ua-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
69
- .ua-icon{width:26px;height:26px;padding:0;justify-content:center;box-shadow:none;color:var(--dsw-alias-label-tertiary)}
43
+ .ua-icon{width:32px;padding:0;box-shadow:none;color:var(--dsw-alias-label-tertiary)}
70
44
  .ua-btn[data-state=pending] svg,.ua-btn[data-state=sending] svg{animation:ua-pulse 1.2s ease-in-out infinite}
71
45
  .ua-btn[data-state=done]{color:var(--dsw-alias-state-success-primary)}
72
46
  .ua-btn[data-state=unhandled]{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}
73
47
  @keyframes ua-pulse{50%{opacity:.35}}
74
- .ua-wrap{position:relative;display:inline-flex}
48
+ .ua-wrap{position:relative;display:inline-flex;max-width:100%;flex-wrap:wrap;align-items:center;gap:4px 8px}
75
49
  .ua-menu{position:absolute;z-index:20;top:calc(100% + 4px);right:0;min-width:168px;padding:4px;border-radius:12px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base));box-shadow:0 6px 24px #0000001f,inset 0 0 0 .5px var(--dsw-alias-border-l2);display:flex;flex-direction:column}
76
- .ua-menu button{display:flex;align-items:center;gap:8px;padding:7px 10px;border:0;border-radius:8px;background:none;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;text-align:left;cursor:pointer}
50
+ .ua-menu button{display:flex;align-items:center;gap:8px;min-height:36px;padding:7px 10px;border:0;border-radius:8px;background:none;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;text-align:left;cursor:pointer}
77
51
  @media (hover:hover){.ua-menu button:hover{background:var(--dsw-alias-interactive-bg-hover)}}
78
- .ua-menu input{margin:4px 6px;padding:6px 8px;border:.5px solid var(--dsw-alias-border-l3);border-radius:8px;background:transparent;color:inherit;font:inherit;font-size:13px}
52
+ .ua-menu input{margin:4px 6px;min-height:36px;padding:6px 8px;border:.5px solid var(--dsw-alias-border-l3);border-radius:8px;background:transparent;color:inherit;font:inherit;font-size:16px}
79
53
  .ua-menuRow{display:flex;justify-content:flex-end;gap:4px;padding:2px 4px}
80
- .ua-error{color:var(--dsw-alias-state-error-primary);font-size:12px}
54
+ .ua-error{flex-basis:100%;color:var(--dsw-alias-state-error-primary);font-size:12px;overflow-wrap:anywhere}
55
+ @media (width<=768px),(pointer:coarse){
56
+ .ua-btn{min-height:40px}
57
+ .ua-icon{width:40px}
58
+ .ua-menu{position:fixed;z-index:1000;top:auto;left:12px;right:12px;bottom:12px;max-height:60vh;overflow:auto;padding:8px;box-shadow:0 8px 40px #00000040,inset 0 0 0 .5px var(--dsw-alias-border-l2)}
59
+ .ua-menu button{min-height:44px;font-size:15px}
60
+ .ua-menu input{min-height:44px}
61
+ }
81
62
  `
82
63
 
83
64
  const ICONS = {
@@ -90,10 +71,6 @@ const ICONS = {
90
71
  unhandled: 'M8 3.5v5.5M8 12v.5',
91
72
  }
92
73
 
93
- function fill(text, params) {
94
- return String(text).replace(/\{(\w+)\}/g, (match, key) => (key in params ? String(params[key]) : match))
95
- }
96
-
97
74
  /** The next 09:00 after now, as an ISO string. */
98
75
  function tomorrowMorning(now = new Date()) {
99
76
  const date = new Date(now)
@@ -118,14 +95,12 @@ function chatText({ prompt = '', title, lines = [], context }) {
118
95
  * @param {object} options
119
96
  * @param {object} options.React - the page's React
120
97
  * @param {object} options.ctx - the plugin's client context (ctx.get reaches the Web UI's services)
121
- * @param {string} [options.locale] - 'zh…' picks Chinese words, anything else English
98
+ * @param {(key: string, params?: object) => string} options.t - the words in the person's language, one of KEYS
122
99
  * @param {(action: object, extra: object) => Promise<unknown>} [options.press] - the server call for done, snooze and event
123
100
  */
124
- function createActions({ React, ctx, locale = 'en', press }) {
101
+ function createActions({ React, ctx, t, press }) {
125
102
  const h = React.createElement
126
103
  const { useState, useEffect, useRef } = React
127
- const words = WORDS[String(locale).toLowerCase().startsWith('zh') ? 'zh' : 'en']
128
- const t = key => words[key] ?? WORDS.en[key] ?? key
129
104
 
130
105
  if (typeof document !== 'undefined' && !document.getElementById('dsh-actions-ui-style')) {
131
106
  const style = document.createElement('style')
@@ -198,7 +173,7 @@ function createActions({ React, ctx, locale = 'en', press }) {
198
173
  const [menu, setMenu] = useState(false)
199
174
  useEffect(() => { if (state) setLocal(null) }, [state])
200
175
  const shown = local ?? state
201
- const label = action.label ?? t(action.kind === 'chat' ? 'chat' : action.kind === 'link' ? 'open' : action.kind)
176
+ const label = action.label ?? t(action.kind)
202
177
  const title = shown === 'sending' ? t('sending') : shown === 'pending' ? t('pending') : shown === 'done' ? t('handled') : shown === 'unhandled' ? t('unhandled') : error ?? label
203
178
  const icon = shown === 'done' ? 'done' : shown === 'unhandled' ? 'unhandled' : action.kind
204
179
  const className = `ua-btn${compact ? ' ua-icon' : ''}`
@@ -223,7 +198,7 @@ function createActions({ React, ctx, locale = 'en', press }) {
223
198
  }
224
199
  } catch (reason) {
225
200
  setLocal(null)
226
- setError(fill(t('failed'), { message: reason?.message ?? String(reason) }))
201
+ setError(t('failed', { message: reason?.message ?? String(reason) }))
227
202
  }
228
203
  }
229
204
  const onClick = () => {
@@ -255,5 +230,5 @@ function createActions({ React, ctx, locale = 'en', press }) {
255
230
  return { ActionBar, ActionButton, Icon, startChat, chatText, t }
256
231
  }
257
232
 
258
- window.__ModuleLoader__.load({ id: OWNER, chunk: 'client.actions.js', factory: () => ({ createActions, chatText }) })
233
+ window.__ModuleLoader__.load({ id: OWNER, chunk: 'client.actions.js', factory: () => ({ createActions, chatText, KEYS }) })
259
234
  })()
package/client.js CHANGED
@@ -22,78 +22,13 @@ window.__ModuleLoader__.load({
22
22
  const PENDING_MS = 2 * 60 * 1000
23
23
  const api = path => new URL(`api/notify-inbox/${path}`, document.baseURI).href
24
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
- 'press.pending': 'Sent, waiting…',
41
- 'press.unhandled': 'Nobody picked this up yet',
42
- 'press.done': 'Marked done',
43
- 'press.snoozed': 'Will remind you {time}',
44
- 'push.title': 'Notifications on this device',
45
- 'push.on': 'On',
46
- 'push.off': 'Off',
47
- 'push.enable': 'Turn on',
48
- 'push.disable': 'Turn off',
49
- 'push.test': 'Send a test',
50
- 'push.testSent': 'Test sent to {n} device(s).',
51
- 'push.denied': 'Notifications are blocked for this site in the browser settings.',
52
- 'push.unsupported': 'This browser can’t receive push notifications here.',
53
- 'push.ios': 'On iPhone or iPad, add this site to the Home Screen and open it from there to turn notifications on.',
54
- 'error': 'Couldn’t load: {message}',
55
- 'time.locale': 'en-US',
56
- }
57
- const zh = {
58
- panel: '收件箱',
59
- title: '收件箱',
60
- 'filter.unread': '未读',
61
- 'filter.all': '全部',
62
- 'markAll': '全部已读',
63
- 'empty.unread': '没有未读通知。',
64
- 'empty.all': '还没有通知。',
65
- 'loadMore': '更早的',
66
- 'urgent': '紧急',
67
- 'test': '测试',
68
- 'alsoSent': '同时发到',
69
- 'notSent': '没有发到别处',
70
- 'files': '附件',
71
- 'notStored': '未保存:{reason}',
72
- 'press.pending': '已发出,等待处理…',
73
- 'press.unhandled': '暂时没有人处理',
74
- 'press.done': '已标为完成',
75
- 'press.snoozed': '会在{time}再提醒',
76
- 'push.title': '本设备的通知',
77
- 'push.on': '已开启',
78
- 'push.off': '未开启',
79
- 'push.enable': '开启',
80
- 'push.disable': '关闭',
81
- 'push.test': '发一条测试',
82
- 'push.testSent': '测试已发到 {n} 台设备。',
83
- 'push.denied': '浏览器设置里禁止了这个网站的通知。',
84
- 'push.unsupported': '这个浏览器在这里收不到推送通知。',
85
- 'push.ios': 'iPhone 或 iPad 上,先把这个网站添加到主屏幕,再从主屏幕打开,才能开启通知。',
86
- 'error': '加载失败:{message}',
87
- 'time.locale': 'zh-CN',
88
- }
89
-
90
25
  const CSS = `
91
26
  .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}
92
27
  .nib-scroll{flex:1;min-height:0;overflow:auto;scrollbar-gutter:stable}
93
28
  .nib-content{max-width:820px;margin:0 auto;padding:0 clamp(16px,4vw,48px) 48px}
94
29
  .nib-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;padding-top:28px;margin-bottom:16px}
95
30
  [data-platform=darwin] .nib-head{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}
96
- .nib-head h1{margin:0;font-size:20px;font-weight:500;line-height:28px;flex:1;min-width:0}
31
+ .nib-head h1{margin:0;font-size:20px;font-weight:500;line-height:28px;flex:1 0 auto;max-width:100%}
97
32
  .nib-count{color:var(--dsw-alias-label-tertiary);font-size:13px;margin-left:8px;font-weight:400}
98
33
  .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))}
99
34
  .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}
@@ -109,6 +44,9 @@ window.__ModuleLoader__.load({
109
44
  .nib-list{display:flex;flex-direction:column;gap:2px;margin:0;padding:0;list-style:none}
110
45
  .nib-item{border-radius:12px;padding:10px 12px;position:relative}
111
46
  .nib-item.nib-open{background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-interactive-bg-hover))}
47
+ .nib-line{display:flex;align-items:flex-start;gap:4px}
48
+ .nib-mark{flex:none;display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;margin:-3px -6px -3px 0;border:none;border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}
49
+ @media (hover:hover){.nib-mark:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
112
50
  .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}
113
51
  .nib-dot{flex:none;width:8px;height:8px;border-radius:50%;margin-top:8px;background:transparent}
114
52
  .nib-unread .nib-dot{background:var(--dsw-alias-state-business-primary)}
@@ -121,7 +59,7 @@ window.__ModuleLoader__.load({
121
59
  .nib-time{flex:none;color:var(--dsw-alias-label-caption);font-size:12px}
122
60
  .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}
123
61
  .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}
124
- .nib-chip.nib-muted{color:var(--dsw-alias-label-tertiary)}
62
+ .nib-chip.nib-muted{color:var(--dsw-alias-label-tertiary);font-weight:400;max-width:45%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
125
63
  .nib-body{margin:8px 0 0 18px;display:flex;flex-direction:column;gap:10px}
126
64
  .nib-text{white-space:pre-wrap;overflow-wrap:anywhere;font-size:14px;line-height:22px}
127
65
  .nib-links{display:flex;flex-direction:column;gap:2px;font-size:13px}
@@ -131,13 +69,14 @@ window.__ModuleLoader__.load({
131
69
  .nib-ok{color:var(--dsw-alias-state-success-primary)}
132
70
  .nib-bad{color:var(--dsw-alias-state-error-primary)}
133
71
  .nib-actions{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
72
+ .nib-actions .nib-btn{height:32px;padding:0 12px}
134
73
  .nib-status{color:var(--dsw-alias-label-tertiary);font-size:12px}
135
74
  .nib-empty{color:var(--dsw-alias-label-tertiary);padding:24px 12px}
136
75
  .nib-error{color:var(--dsw-alias-state-error-primary);padding:12px}
137
76
  .nib-more{margin:12px auto 0;display:flex}
138
77
  .nib-icon{position:relative;display:inline-flex}
139
78
  .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}
140
- @media (width<=640px),(pointer:coarse){.nib-btn,.nib-tab,.nib-page .ua-btn{min-height:40px;min-width:40px}.nib-tab{padding-inline:14px}.nib-tabs{border-radius:12px}}
79
+ @media (width<=640px),(pointer:coarse){.nib-btn,.nib-tab,.nib-page .ua-btn{min-height:40px;min-width:40px}.nib-mark{width:40px;height:40px;margin:-10px -8px -10px 0}.nib-tab{padding-inline:14px}.nib-tabs{border-radius:12px}}
141
80
  @media (width<=640px){.nib-content{padding-inline:12px}.nib-head{padding-top:16px}.nib-body{margin-left:0}.nib-item{padding:10px 8px}}
142
81
  `
143
82
 
@@ -220,8 +159,9 @@ window.__ModuleLoader__.load({
220
159
  return states
221
160
  }
222
161
 
223
- function Actions({ item, t, ui }) {
224
- if (ui === null) return null
162
+ function Actions({ item, t, ui, onMark }) {
163
+ const markUnread = item.read && h('button', { type: 'button', className: 'nib-btn', onClick: () => onMark(item, false) }, t('markUnread'))
164
+ if (ui === null) return markUnread ? h('div', { className: 'nib-actions' }, markUnread) : null
225
165
  const declared = item.actions.some(action => action.kind === 'chat') ? item.actions : [{ kind: 'chat', id: 'chat', payload: {} }, ...item.actions]
226
166
  const chat = action => ui.startChat({
227
167
  text: ui.chatText({ prompt: action.payload?.prompt ?? '', title: item.title || item.spoken, lines: (item.text || item.spoken).split('\n'),
@@ -234,17 +174,26 @@ window.__ModuleLoader__.load({
234
174
  }
235
175
  const status = pressStatus(item, t)
236
176
  return h('div', { className: 'nib-actions' }, h(ui.ActionBar, { actions: declared, states: pressStates(item), chat, onPress }),
177
+ markUnread,
237
178
  status && h('span', { className: 'nib-status' }, status))
238
179
  }
239
180
 
240
181
  // ---- one notification ----
241
182
 
242
- function Item({ item, t, open, onToggle, ui }) {
183
+ function MarkUnreadIcon() {
184
+ return h('svg', { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, focusable: 'false' },
185
+ h('path', { d: 'M9.5 3.5H3A1.5 1.5 0 0 0 1.5 5v6.5A1.5 1.5 0 0 0 3 13h9a1.5 1.5 0 0 0 1.5-1.5V8' }),
186
+ h('path', { d: 'M1.8 4.6 7.5 8.6l2.3-1.6' }),
187
+ h('circle', { cx: 12.5, cy: 3.5, r: 2, fill: 'currentColor', stroke: 'none' }))
188
+ }
189
+
190
+ function Item({ item, t, open, onToggle, onMark, ui }) {
243
191
  const urgent = item.lane === 'interrupt'
244
192
  const className = ['nib-item', item.read ? '' : 'nib-unread', urgent ? 'nib-urgent' : '', open ? 'nib-open' : ''].filter(Boolean).join(' ')
245
193
  const title = item.title || item.spoken || item.text.slice(0, 80)
246
194
  const sub = item.spoken && item.spoken !== title ? item.spoken : item.text !== title ? item.text : ''
247
195
  return h('li', { className, id: `nib-${item.id}` },
196
+ h('div', { className: 'nib-line' },
248
197
  h('button', { type: 'button', className: 'nib-row', 'aria-expanded': open, onClick: () => onToggle(item) },
249
198
  h('span', { className: 'nib-dot', 'aria-hidden': true }),
250
199
  h('span', { className: 'nib-main' },
@@ -252,8 +201,10 @@ window.__ModuleLoader__.load({
252
201
  urgent && h('span', { className: 'nib-chip' }, t('urgent')),
253
202
  item.test && h('span', { className: 'nib-chip nib-muted' }, t('test')),
254
203
  h('span', { className: 'nib-title' }, title),
204
+ !open && item.presses.length > 0 && h('span', { className: 'nib-chip nib-muted' }, pressStatus(item, t)),
255
205
  h('span', { className: 'nib-time', title: absolute(item.time, t) }, relative(item.time, t))),
256
206
  !open && sub && h('span', { className: 'nib-spoken' }, sub))),
207
+ item.read && !open && h('button', { type: 'button', className: 'nib-mark', title: t('markUnread'), 'aria-label': t('markUnread'), onClick: () => onMark(item, false) }, h(MarkUnreadIcon))),
257
208
  open && h('div', { className: 'nib-body' },
258
209
  item.text && item.text !== title && h('div', { className: 'nib-text' }, item.text),
259
210
  item.links.length > 0 && h('div', { className: 'nib-links' },
@@ -263,7 +214,7 @@ window.__ModuleLoader__.load({
263
214
  item.files.map(file => file.stored
264
215
  ? h('a', { key: file.name, href: api(`file?id=${encodeURIComponent(item.id)}&name=${encodeURIComponent(file.name)}`), target: '_blank', rel: 'noopener' }, file.name)
265
216
  : h('span', { key: file.name, className: 'nib-meta' }, `${file.name} (${t('notStored', { reason: file.reason || '?' })})`))),
266
- h(Actions, { item, t, ui }),
217
+ h(Actions, { item, t, ui, onMark }),
267
218
  h('div', { className: 'nib-meta' },
268
219
  item.routed.length === 0 ? t('notSent') : h(React.Fragment, null, `${t('alsoSent')}: `,
269
220
  item.routed.map(row => h('span', { key: row.destination, className: 'nib-route', title: row.detail || '' },
@@ -285,7 +236,7 @@ window.__ModuleLoader__.load({
285
236
  const ua = navigator.userAgent
286
237
  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' : ''
287
238
  const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser'
288
- return [browser, os].filter(Boolean).join(' on ')
239
+ return [browser, os].filter(Boolean).join(' · ')
289
240
  }
290
241
 
291
242
  async function currentSubscription() {
@@ -347,7 +298,7 @@ window.__ModuleLoader__.load({
347
298
  setState('off')
348
299
  })
349
300
  const test = run(async () => {
350
- const result = await call('push/test', {})
301
+ const result = await call('push/test', { title: t('push.testTitle'), body: t('push.testBody') })
351
302
  setNote(t('push.testSent', { n: result.sent }))
352
303
  })
353
304
  return h('div', { className: 'nib-push' },
@@ -369,30 +320,28 @@ window.__ModuleLoader__.load({
369
320
  const [more, setMore] = useState(false)
370
321
  const [error, setError] = useState(null)
371
322
  const [open, setOpen] = useState(() => shared.linked)
372
- const openRef = useRef(open)
373
- openRef.current = open
323
+ // Rows shown under Unread during this visit stay on screen as they turn read, done or snoozed,
324
+ // so the list never moves under the person's finger; leaving the view (or tapping its tab again) lets them go.
325
+ const shown = useRef(new Set())
326
+ const [visit, setVisit] = useState(0)
374
327
  const [ui, setUi] = useState(null)
375
328
  useEffect(() => {
376
329
  let live = true
377
- makeActions(t('time.locale')).then(made => { if (live) setUi(made) }, reason => { console.warn('notify-inbox: buttons unavailable', reason) })
330
+ makeActions().then(made => { if (live) setUi(made) }, reason => { console.warn('notify-inbox: buttons unavailable', reason) })
378
331
  return () => { live = false }
379
332
  }, [])
380
333
 
381
334
  const load = useCallback(async (append) => {
382
335
  try {
383
336
  const params = new URLSearchParams()
384
- if (filter === 'unread') params.set('unread', '1')
337
+ if (filter === 'unread') {
338
+ params.set('unread', '1')
339
+ if (shown.current.size > 0) params.set('keep', [...shown.current].join(','))
340
+ }
385
341
  if (append && items?.length) params.set('before', items[items.length - 1].id)
386
342
  const page = await call(`items?${params}`)
387
- setItems(previous => {
388
- if (append && previous) return [...previous, ...page.items]
389
- // The open item stays where it was even when it no longer matches the filter (opening marks it read).
390
- const kept = previous?.findIndex(row => row.id === openRef.current) ?? -1
391
- if (kept < 0 || page.items.some(row => row.id === openRef.current)) return page.items
392
- const next = [...page.items]
393
- next.splice(Math.min(kept, next.length), 0, { ...previous[kept], read: true })
394
- return next
395
- })
343
+ if (filter === 'unread') for (const row of page.items) shown.current.add(row.id)
344
+ setItems(previous => (append && previous ? [...previous, ...page.items] : page.items))
396
345
  setMore(page.more)
397
346
  setError(null)
398
347
  } catch (reason) {
@@ -400,23 +349,29 @@ window.__ModuleLoader__.load({
400
349
  }
401
350
  }, [filter, items])
402
351
 
403
- useEffect(() => { load(false) }, [filter, version])
352
+ useEffect(() => { load(false) }, [filter, version, visit])
353
+ const showView = key => {
354
+ shown.current = new Set()
355
+ if (key === filter) setVisit(n => n + 1)
356
+ else setFilter(key)
357
+ }
404
358
  useEffect(() => {
405
359
  if (!linked) return
406
- setFilter('all')
360
+ showView('all')
407
361
  setOpen(linked)
408
362
  shared.linked = null
409
363
  call('read', { ids: [linked] }).then(changed, () => {})
410
364
  setTimeout(() => document.getElementById(`nib-${linked}`)?.scrollIntoView({ block: 'center' }), 300)
411
365
  }, [linked])
412
366
 
367
+ const mark = (item, read) => {
368
+ setItems(list => list.map(row => (row.id === item.id ? { ...row, read } : row)))
369
+ call('read', { ids: [item.id], read }).then(changed, reason => setError(reason.message))
370
+ }
413
371
  const toggle = item => {
414
372
  const next = open === item.id ? null : item.id
415
373
  setOpen(next)
416
- if (next !== null && !item.read) {
417
- setItems(list => list.map(row => (row.id === item.id ? { ...row, read: true } : row)))
418
- call('read', { ids: [item.id] }).then(changed, () => {})
419
- }
374
+ if (next !== null && !item.read) mark(item, true)
420
375
  }
421
376
  const markAll = () => call('read', { all: true }).then(changed, reason => setError(reason.message))
422
377
 
@@ -426,13 +381,13 @@ window.__ModuleLoader__.load({
426
381
  h('div', { className: 'nib-head' },
427
382
  h('h1', null, t('title'), unread > 0 && h('span', { className: 'nib-count' }, unread)),
428
383
  h('div', { className: 'nib-tabs', role: 'group' },
429
- ['unread', 'all'].map(key => h('button', { key, type: 'button', className: 'nib-tab', 'aria-pressed': filter === key, onClick: () => setFilter(key) }, t(`filter.${key}`)))),
384
+ ['unread', 'all'].map(key => h('button', { key, type: 'button', className: 'nib-tab', 'aria-pressed': filter === key, onClick: () => showView(key) }, t(`filter.${key}`)))),
430
385
  h('button', { type: 'button', className: 'nib-btn', disabled: unread === 0, onClick: markAll }, t('markAll'))),
431
386
  h(PushControl, { t }),
432
387
  error && h('p', { className: 'nib-error', role: 'alert' }, t('error', { message: error })),
433
388
  items !== null && items.length === 0 && h('p', { className: 'nib-empty' }, t(filter === 'unread' ? 'empty.unread' : 'empty.all')),
434
389
  items !== null && h('ul', { className: 'nib-list' },
435
- items.map(item => h(Item, { key: item.id, item, t, open: open === item.id, onToggle: toggle, ui }))),
390
+ items.map(item => h(Item, { key: item.id, item, t, open: open === item.id, onToggle: toggle, onMark: mark, ui }))),
436
391
  more && h('button', { type: 'button', className: 'nib-btn nib-more', onClick: () => load(true) }, t('loadMore')))))
437
392
  }
438
393
 
@@ -449,9 +404,15 @@ window.__ModuleLoader__.load({
449
404
  return {
450
405
  inject: ['slots', 'locale'],
451
406
  apply(ctx) {
407
+ // The words come from the plugin's locale/<tag>.json files, served complete per tag.
452
408
  ctx.effect(() => {
453
- const disposers = [ctx.locale.register(NS, 'en', en), ctx.locale.register(NS, 'zh', zh)]
454
- return () => { for (const dispose of disposers) dispose() }
409
+ let disposers = []
410
+ let live = true
411
+ call('strings').then(({ tables }) => {
412
+ if (!live) return
413
+ disposers = Object.entries(tables).map(([tag, table]) => ctx.locale.register(NS, tag, table))
414
+ }, reason => console.warn('notify-inbox: words unavailable', reason))
415
+ return () => { live = false; for (const dispose of disposers) dispose() }
455
416
  }, 'notify-inbox: dictionaries')
456
417
  const t = ctx.locale.bind(NS)
457
418
 
@@ -464,7 +425,7 @@ window.__ModuleLoader__.load({
464
425
  return () => tag.remove()
465
426
  }, 'notify-inbox: styles')
466
427
 
467
- const makeActions = locale => loadActions().then(module => module.createActions({ React, ctx, locale }))
428
+ const makeActions = () => loadActions().then(module => module.createActions({ React, ctx, t: (key, params) => t(`action.${key}`, params) }))
468
429
 
469
430
  ctx.slots.inject('main', () => ctx.slots.register({
470
431
  name: 'main',
package/index.js CHANGED
@@ -11,12 +11,14 @@
11
11
  import { readFileSync } from 'node:fs'
12
12
  import { homedir } from 'node:os'
13
13
  import { isAbsolute, join, resolve } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
14
15
  import z from '@deepseek-ai/schemastery'
15
16
  import { createPeople, expandHome } from './src/access.js'
16
17
  import { createActions } from './src/actions.js'
17
18
  import { createPush } from './src/push.js'
18
19
  import { createRoutes } from './src/routes.js'
19
20
  import { createStore } from './src/store.js'
21
+ import { readLocales, tables } from './src/locales.js'
20
22
 
21
23
  export const name = 'dsh-notify-inbox'
22
24
  export const inject = ['connection']
@@ -68,7 +70,8 @@ export function apply(ctx, config) {
68
70
  })
69
71
  const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
70
72
  const pollSeconds = config.pollSeconds ?? 5
71
- const routes = createRoutes({ store, people, push, actions, identity: () => ctx.get('requestIdentity'), serviceWorker, pollSeconds: Math.max(pollSeconds, 15) })
73
+ const strings = readLocales(fileURLToPath(new URL('./locale/', import.meta.url))).then(tables)
74
+ const routes = createRoutes({ store, people, push, actions, identity: () => ctx.get('requestIdentity'), serviceWorker, strings: () => strings, pollSeconds: Math.max(pollSeconds, 15) })
72
75
  for (const route of routes) ctx.connection.fetch.register(route)
73
76
 
74
77
  let stopped = false
package/locale/en.json CHANGED
@@ -1 +1,58 @@
1
- { "meta": { "title": "Notification Inbox", "description": "One inbox for the notifications your assistant and scripts send: read and unread per person, Web Push to phones and browsers, and buttons to act on each one." } }
1
+ {
2
+ "meta": {
3
+ "title": "Notification Inbox",
4
+ "description": "One inbox for the notifications your assistant and scripts send: read and unread per person, Web Push to phones and browsers, and buttons to act on each one."
5
+ },
6
+ "ui": {
7
+ "panel": "Inbox",
8
+ "title": "Inbox",
9
+ "filter.unread": "Unread",
10
+ "filter.all": "All",
11
+ "markAll": "Mark all read",
12
+ "markUnread": "Mark unread",
13
+ "empty.unread": "Nothing unread.",
14
+ "empty.all": "No notifications yet.",
15
+ "loadMore": "Show older",
16
+ "urgent": "Urgent",
17
+ "test": "Test",
18
+ "alsoSent": "Also sent to",
19
+ "notSent": "Not sent anywhere else",
20
+ "files": "Attachments",
21
+ "notStored": "not kept: {reason}",
22
+ "press.pending": "Sent, waiting…",
23
+ "press.unhandled": "Nobody picked this up yet",
24
+ "press.done": "Marked done",
25
+ "press.snoozed": "Will remind you {time}",
26
+ "push.title": "Notifications on this device",
27
+ "push.on": "On",
28
+ "push.off": "Off",
29
+ "push.enable": "Turn on",
30
+ "push.disable": "Turn off",
31
+ "push.test": "Send a test",
32
+ "push.testSent": "Test sent to {n} device(s).",
33
+ "push.denied": "Notifications are blocked for this site in the browser settings.",
34
+ "push.unsupported": "This browser can’t receive push notifications here.",
35
+ "push.ios": "On iPhone or iPad, add this site to the Home Screen and open it from there to turn notifications on.",
36
+ "error": "Couldn’t load: {message}",
37
+ "time.locale": "en-US",
38
+ "action.chat": "Ask",
39
+ "action.chatAbout": "Chat about this",
40
+ "action.done": "Done",
41
+ "action.snooze": "Snooze",
42
+ "action.event": "Go",
43
+ "action.link": "Open",
44
+ "action.in3h": "In 3 hours",
45
+ "action.tomorrow": "Tomorrow 9:00",
46
+ "action.pick": "Pick a time…",
47
+ "action.set": "Snooze",
48
+ "action.cancel": "Cancel",
49
+ "action.sending": "Sending…",
50
+ "action.pending": "Waiting for it to be picked up",
51
+ "action.handled": "Done",
52
+ "action.unhandled": "Nothing picked this up yet",
53
+ "action.failed": "Didn’t go through: {message}",
54
+ "action.noWorkspace": "Open a conversation once first, then try again.",
55
+ "push.testTitle": "Inbox",
56
+ "push.testBody": "Notifications reach this device."
57
+ }
58
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "meta": {
3
+ "title": "Boîte de notifications",
4
+ "description": "Toutes les notifications de votre assistant et de vos scripts au même endroit : lues et non lues par personne, notifications push sur téléphone et navigateur, et des boutons pour agir sur chacune."
5
+ },
6
+ "ui": {
7
+ "panel": "Notifications",
8
+ "title": "Notifications",
9
+ "filter.unread": "Non lues",
10
+ "filter.all": "Toutes",
11
+ "markAll": "Tout marquer comme lu",
12
+ "markUnread": "Marquer comme non lu",
13
+ "empty.unread": "Rien de non lu.",
14
+ "empty.all": "Pas encore de notifications.",
15
+ "loadMore": "Plus anciennes",
16
+ "urgent": "Urgent",
17
+ "test": "Test",
18
+ "alsoSent": "Aussi envoyé à",
19
+ "notSent": "Envoyé nulle part ailleurs",
20
+ "files": "Pièces jointes",
21
+ "notStored": "non conservé : {reason}",
22
+ "press.pending": "Envoyé, en attente…",
23
+ "press.unhandled": "Personne ne l’a encore pris en charge",
24
+ "press.done": "Marqué comme fait",
25
+ "press.snoozed": "Rappel {time}",
26
+ "push.title": "Notifications sur cet appareil",
27
+ "push.on": "Activées",
28
+ "push.off": "Désactivées",
29
+ "push.enable": "Activer",
30
+ "push.disable": "Désactiver",
31
+ "push.test": "Envoyer un test",
32
+ "push.testSent": "Test envoyé à {n} appareil(s).",
33
+ "push.denied": "Les notifications de ce site sont bloquées dans les réglages du navigateur.",
34
+ "push.unsupported": "Ce navigateur ne peut pas recevoir de notifications ici.",
35
+ "push.ios": "Sur iPhone ou iPad, ajoutez ce site à l’écran d’accueil et ouvrez-le depuis là pour activer les notifications.",
36
+ "error": "Chargement impossible : {message}",
37
+ "time.locale": "fr-FR",
38
+ "action.chat": "Demander",
39
+ "action.chatAbout": "En discuter",
40
+ "action.done": "Fait",
41
+ "action.snooze": "Plus tard",
42
+ "action.event": "Lancer",
43
+ "action.link": "Ouvrir",
44
+ "action.in3h": "Dans 3 heures",
45
+ "action.tomorrow": "Demain 9:00",
46
+ "action.pick": "Choisir une heure…",
47
+ "action.set": "Rappeler",
48
+ "action.cancel": "Annuler",
49
+ "action.sending": "Envoi…",
50
+ "action.pending": "En attente de traitement",
51
+ "action.handled": "Fait",
52
+ "action.unhandled": "Personne ne l’a encore pris en charge",
53
+ "action.failed": "Échec : {message}",
54
+ "action.noWorkspace": "Ouvrez d’abord une conversation, puis réessayez.",
55
+ "push.testTitle": "Notifications",
56
+ "push.testBody": "Les notifications arrivent sur cet appareil."
57
+ }
58
+ }
package/locale/zh.json CHANGED
@@ -1 +1,58 @@
1
- { "meta": { "title": "通知收件箱", "description": "助手和脚本发出的通知都收在这里:每个人各看各的、分已读未读,推送到手机和浏览器,每条通知都能直接操作。" } }
1
+ {
2
+ "meta": {
3
+ "title": "通知收件箱",
4
+ "description": "助手和脚本发出的通知都收在这里:每个人各看各的、分已读未读,推送到手机和浏览器,每条通知都能直接操作。"
5
+ },
6
+ "ui": {
7
+ "panel": "收件箱",
8
+ "title": "收件箱",
9
+ "filter.unread": "未读",
10
+ "filter.all": "全部",
11
+ "markAll": "全部已读",
12
+ "markUnread": "标为未读",
13
+ "empty.unread": "没有未读通知。",
14
+ "empty.all": "还没有通知。",
15
+ "loadMore": "更早的",
16
+ "urgent": "紧急",
17
+ "test": "测试",
18
+ "alsoSent": "同时发到",
19
+ "notSent": "没有发到别处",
20
+ "files": "附件",
21
+ "notStored": "未保存:{reason}",
22
+ "press.pending": "已发出,等待处理…",
23
+ "press.unhandled": "暂时没有人处理",
24
+ "press.done": "已标为完成",
25
+ "press.snoozed": "会在{time}再提醒",
26
+ "push.title": "本设备的通知",
27
+ "push.on": "已开启",
28
+ "push.off": "未开启",
29
+ "push.enable": "开启",
30
+ "push.disable": "关闭",
31
+ "push.test": "发一条测试",
32
+ "push.testSent": "测试已发到 {n} 台设备。",
33
+ "push.denied": "浏览器设置里禁止了这个网站的通知。",
34
+ "push.unsupported": "这个浏览器在这里收不到推送通知。",
35
+ "push.ios": "iPhone 或 iPad 上,先把这个网站添加到主屏幕,再从主屏幕打开,才能开启通知。",
36
+ "error": "加载失败:{message}",
37
+ "time.locale": "zh-CN",
38
+ "action.chat": "问问",
39
+ "action.chatAbout": "聊聊这个",
40
+ "action.done": "完成",
41
+ "action.snooze": "稍后提醒",
42
+ "action.event": "执行",
43
+ "action.link": "打开",
44
+ "action.in3h": "3 小时后",
45
+ "action.tomorrow": "明天 9:00",
46
+ "action.pick": "选个时间…",
47
+ "action.set": "稍后提醒",
48
+ "action.cancel": "取消",
49
+ "action.sending": "发送中…",
50
+ "action.pending": "等待处理",
51
+ "action.handled": "已处理",
52
+ "action.unhandled": "还没有被处理",
53
+ "action.failed": "没有成功:{message}",
54
+ "action.noWorkspace": "请先打开一次对话,再试一次。",
55
+ "push.testTitle": "收件箱",
56
+ "push.testBody": "这台设备能收到通知了。"
57
+ }
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-notify-inbox",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "A notification inbox for DeepSeek Harness: each person sees their own notifications with read and unread, gets Web Push on their phone or browser, and can act on them.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/locales.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The page's words: one `locale/<tag>.json` per language, `{ meta, ui }`.
3
+ * Which languages exist is whatever files are there; adding one needs no code.
4
+ * Each table the page gets is complete: a key missing from `zh-CN` comes from
5
+ * `zh`, then from `en`.
6
+ */
7
+ import { readdir, readFile } from 'node:fs/promises'
8
+ import { join } from 'node:path'
9
+
10
+ export const BASE = 'en'
11
+ const TAG = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/
12
+
13
+ /** `{ tag: ui }` for every `<tag>.json` in the folder with a `ui` object. */
14
+ export async function readLocales(dir) {
15
+ const out = {}
16
+ for (const name of (await readdir(dir)).sort()) {
17
+ const tag = name.replace(/\.json$/, '')
18
+ if (tag === name || !TAG.test(tag)) continue
19
+ const value = JSON.parse(await readFile(join(dir, name), 'utf8'))
20
+ if (typeof value?.ui === 'object' && value.ui !== null) out[tag] = value.ui
21
+ }
22
+ return out
23
+ }
24
+
25
+ const primary = tag => tag.split('-')[0]
26
+
27
+ /**
28
+ * Complete tables by tag: exact tag, then its primary subtag, then the base
29
+ * language. A regional file without its primary one also answers for the
30
+ * primary tag, so `zh-CN.json` alone serves a page set to `zh`.
31
+ */
32
+ export function tables(locales) {
33
+ const base = locales[BASE] ?? {}
34
+ const out = {}
35
+ for (const tag of Object.keys(locales)) {
36
+ out[tag] = { ...base, ...(locales[primary(tag)] ?? {}), ...locales[tag] }
37
+ if (out[primary(tag)] === undefined && locales[primary(tag)] === undefined) out[primary(tag)] = out[tag]
38
+ }
39
+ return out
40
+ }
package/src/push.js CHANGED
@@ -83,7 +83,7 @@ export function checkSubscription(value) {
83
83
 
84
84
  /** The notification a record becomes: what the push service carries (encrypted) and the service worker shows. */
85
85
  export function payloadOf(record) {
86
- const title = record.title || record.spoken.slice(0, 60) || 'Notification'
86
+ const title = record.title || record.spoken.slice(0, 60) || record.text.slice(0, 60) || record.domain
87
87
  const body = record.spoken && record.spoken !== record.title ? record.spoken : record.text
88
88
  return {
89
89
  title: record.test ? `[test] ${title}` : title,
@@ -167,11 +167,11 @@ export function createPush({ dataDir, vapidFile, subject, perPerson, warn, fetch
167
167
  return { sent, removed: gone.length }
168
168
  }
169
169
 
170
- /** Push a test to the asking person's devices. */
171
- function test(person) {
170
+ /** Push a test, in the words the asking page sends, to the asking person's devices. */
171
+ function test(person, { title, body }) {
172
172
  return serial(async () => {
173
173
  const subs = (await subscriptions()).filter(sub => (sub.person ?? null) === (person ?? null))
174
- return deliver(subs, { title: 'Inbox', body: 'Notifications reach this device.', tag: 'notify-inbox-test', url: './?notify-inbox=', urgent: false }, false)
174
+ return deliver(subs, { title: String(title ?? '').slice(0, 80), body: String(body ?? '').slice(0, BODY_LIMIT), tag: 'notify-inbox-test', url: './?notify-inbox=', urgent: false }, false)
175
175
  })
176
176
  }
177
177
 
package/src/routes.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * answer is decided here, per request, from who is asking.
5
5
  *
6
6
  * GET /api/notify-inbox/summary unread count and newest time (badge)
7
- * GET /api/notify-inbox/items?unread=1&before=&limit=
8
- * POST /api/notify-inbox/read { ids: [...] } or { all: true }
7
+ * GET /api/notify-inbox/items?unread=1&keep=&before=&limit=
8
+ * POST /api/notify-inbox/read { ids: [...], read?: false } or { all: true }
9
9
  * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press
10
10
  * GET /api/notify-inbox/file?id=&name= a stored attachment
11
11
  * GET /api/notify-inbox/push/config { publicKey }
@@ -13,6 +13,7 @@
13
13
  * POST /api/notify-inbox/push/subscribe { subscription, label }
14
14
  * POST /api/notify-inbox/push/unsubscribe { endpoint }
15
15
  * POST /api/notify-inbox/push/test
16
+ * GET /api/notify-inbox/strings the page's words by language tag (src/locales.js)
16
17
  * GET /api/notify-inbox/sw.js the service worker (scope /api/notify-inbox/)
17
18
  */
18
19
  import { readFile } from 'node:fs/promises'
@@ -23,6 +24,8 @@ import { PERSON_PATTERN, RECORD_ID_PATTERN } from './store.js'
23
24
  export const PREFIX = '/api/notify-inbox'
24
25
  const MAX_BODY = 16 * 1024
25
26
  const PAGE = 50
27
+ /** Most rows the Unread view keeps on screen after they turn read (ids in `keep`). */
28
+ const KEEP_MAX = 200
26
29
 
27
30
  const HEADERS = {
28
31
  'content-type': 'application/json; charset=utf-8',
@@ -58,9 +61,10 @@ async function body(request) {
58
61
  * @param {ReturnType<import('./actions.js').createActions>} options.actions
59
62
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
60
63
  * @param {string} options.serviceWorker - the service worker's source
64
+ * @param {() => Promise<Record<string, Record<string, string>>>} [options.strings] - the page's words, complete per tag
61
65
  * @param {number} options.pollSeconds
62
66
  */
63
- export function createRoutes({ store, people, push, actions, identity, serviceWorker, pollSeconds }) {
67
+ export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), pollSeconds }) {
64
68
  /** Who is asking, as the inbox folders they may read; undefined with the response to send instead. */
65
69
  async function caller() {
66
70
  const viewer = await viewerOf(people, identity())
@@ -97,7 +101,11 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
97
101
  const params = new URL(request.url).searchParams
98
102
  const limit = Math.min(Math.max(Number(params.get('limit')) || PAGE, 1), 200)
99
103
  let { items } = await store.view(who.folders)
100
- if (params.get('unread') === '1') items = items.filter(item => !item.read)
104
+ if (params.get('unread') === '1') {
105
+ // `keep` holds what the page already shows under Unread, so those rows stay put as they turn read.
106
+ const keep = new Set((params.get('keep') ?? '').split(',').filter(id => RECORD_ID_PATTERN.test(id)).slice(0, KEEP_MAX))
107
+ items = items.filter(item => !item.read || keep.has(item.id))
108
+ }
101
109
  const before = params.get('before')
102
110
  if (before) {
103
111
  const at = items.findIndex(item => item.id === before)
@@ -123,7 +131,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
123
131
  for (const person of who.folders) await store.markAllRead(person)
124
132
  } else if (Array.isArray(value.ids)) {
125
133
  const ids = value.ids.filter(id => typeof id === 'string').slice(0, 500)
126
- for (const person of who.folders) await store.markRead(person, ids)
134
+ for (const person of who.folders) await store.setRead(person, ids, value.read !== false)
127
135
  } else {
128
136
  return json(400, { error: 'Send ids or all.' })
129
137
  }
@@ -138,7 +146,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
138
146
  if (declared === undefined) return json(400, { error: 'This notification has no such button.' })
139
147
  if (!['done', 'snooze', 'event'].includes(declared.kind)) return json(400, { error: 'This button acts in the page.' })
140
148
  const result = await actions.press(record.person, record, declared, { until: value.until })
141
- await store.markRead(record.person, [record.id])
149
+ await store.setRead(record.person, [record.id], true)
142
150
  return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
143
151
  })
144
152
 
@@ -181,7 +189,9 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
181
189
  await push.unsubscribe(who.person, value.endpoint)
182
190
  return json(200, { ok: true })
183
191
  })
184
- const pushTest = handle(async (_request, who) => json(200, await push.test(who.person)))
192
+ const pushTest = handle(async (request, who) => json(200, await push.test(who.person, await body(request))))
193
+
194
+ const words = async () => json(200, { tables: await strings() }, { 'cache-control': 'private, max-age=300' })
185
195
 
186
196
  const worker = async () => new Response(serviceWorker, {
187
197
  status: 200,
@@ -201,6 +211,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
201
211
  post('/push/subscribe', subscribe),
202
212
  post('/push/unsubscribe', unsubscribe),
203
213
  post('/push/test', pushTest),
214
+ get('/strings', words),
204
215
  get('/sw.js', worker),
205
216
  ]
206
217
  }
package/src/store.js CHANGED
@@ -118,8 +118,13 @@ async function atomicWrite(path, value) {
118
118
  await rename(tmp, path)
119
119
  }
120
120
 
121
- /** Read marks: everything up to `readBefore` (ISO time) is read, plus the ids in `read`. */
121
+ /**
122
+ * Read marks: everything up to `readBefore` (ISO time) is read, plus the ids in
123
+ * `read`, except the ids in `unread` (marked unread again after the watermark
124
+ * passed them).
125
+ */
122
126
  export function isRead(marks, record) {
127
+ if (marks.unread.includes(record.id)) return false
123
128
  return (marks.readBefore !== '' && record.time <= marks.readBefore) || marks.read.includes(record.id)
124
129
  }
125
130
 
@@ -164,9 +169,10 @@ export function createStore(dataDir) {
164
169
  async function marks(person) {
165
170
  try {
166
171
  const value = JSON.parse(await readFile(join(dataDir, person, READ), 'utf8'))
167
- return { readBefore: text(value.readBefore), read: list(value.read).filter(id => typeof id === 'string') }
172
+ const ids = key => list(value[key]).filter(id => typeof id === 'string')
173
+ return { readBefore: text(value.readBefore), read: ids('read'), unread: ids('unread') }
168
174
  } catch {
169
- return { readBefore: '', read: [] }
175
+ return { readBefore: '', read: [], unread: [] }
170
176
  }
171
177
  }
172
178
 
@@ -175,22 +181,35 @@ export function createStore(dataDir) {
175
181
  await atomicWrite(join(dataDir, person, READ), value)
176
182
  }
177
183
 
178
- /** Mark some records read; ids that aren't this person's are ignored. */
179
- async function markRead(person, ids) {
180
- const known = new Set((await records(person)).records.map(record => record.id))
184
+ /**
185
+ * Mark some records read or unread; ids that aren't this person's are ignored.
186
+ * Each list keeps only what the watermark doesn't already say.
187
+ */
188
+ async function setRead(person, ids, value) {
189
+ const byId = new Map((await records(person)).records.map(record => [record.id, record]))
181
190
  const current = await marks(person)
182
- const read = [...new Set([...current.read, ...ids.filter(id => known.has(id))])]
183
- await saveMarks(person, { readBefore: current.readBefore, read })
191
+ const read = new Set(current.read)
192
+ const unread = new Set(current.unread)
193
+ for (const id of ids) {
194
+ const record = byId.get(id)
195
+ if (record === undefined) continue
196
+ const covered = current.readBefore !== '' && record.time <= current.readBefore
197
+ read.delete(id)
198
+ unread.delete(id)
199
+ if (value && !covered) read.add(id)
200
+ if (!value && covered) unread.add(id)
201
+ }
202
+ await saveMarks(person, { readBefore: current.readBefore, read: [...read], unread: [...unread] })
184
203
  }
185
204
 
186
- /** Mark everything up to the newest record read; the per-id list drops what the watermark covers. */
205
+ /** Mark everything up to the newest record read; the per-id lists drop what the watermark covers. */
187
206
  async function markAllRead(person) {
188
207
  const all = (await records(person)).records
189
208
  if (all.length === 0) return
190
209
  const readBefore = all.reduce((latest, record) => (record.time > latest ? record.time : latest), '')
191
210
  const current = await marks(person)
192
211
  const byId = new Map(all.map(record => [record.id, record]))
193
- await saveMarks(person, { readBefore, read: current.read.filter(id => byId.has(id) && byId.get(id).time > readBefore) })
212
+ await saveMarks(person, { readBefore, read: current.read.filter(id => byId.has(id) && byId.get(id).time > readBefore), unread: [] })
194
213
  }
195
214
 
196
215
  /** The records of these people, newest first, each with `read`. */
@@ -219,5 +238,5 @@ export function createStore(dataDir) {
219
238
  return undefined
220
239
  }
221
240
 
222
- return { persons, records, marks, markRead, markAllRead, view, file }
241
+ return { persons, records, marks, setRead, markAllRead, view, file }
223
242
  }
package/src/sw.js CHANGED
@@ -15,7 +15,7 @@ function payloadOf(event) {
15
15
  } catch {
16
16
  // An unreadable payload still shows something.
17
17
  }
18
- return { title: 'Inbox', body: 'You have a new notification.' }
18
+ return { title: self.location.host, body: '' }
19
19
  }
20
20
 
21
21
  self.addEventListener('push', event => {
@@ -31,7 +31,7 @@ self.addEventListener('push', event => {
31
31
  options.tag = value.tag
32
32
  options.renotify = true
33
33
  }
34
- event.waitUntil(self.registration.showNotification(typeof value.title === 'string' && value.title ? value.title : 'Inbox', options))
34
+ event.waitUntil(self.registration.showNotification(typeof value.title === 'string' && value.title ? value.title : self.location.host, options))
35
35
  })
36
36
 
37
37
  self.addEventListener('notificationclick', event => {