@soffits/dsh-notify-inbox 0.4.0 → 0.6.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/CHANGELOG.md +16 -0
- package/README.md +42 -4
- package/client.js +334 -213
- package/docs/ui.md +38 -0
- package/index.js +41 -19
- package/locale/en.json +24 -6
- package/locale/fr.json +25 -7
- package/locale/zh.json +23 -5
- package/package.json +24 -4
- package/src/changes.js +104 -0
- package/src/domains.js +49 -0
- package/src/routes.js +77 -18
- package/src/store.js +156 -15
- package/src/view.js +117 -0
package/src/routes.js
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
* browser first and a `requestIdentity` provider sees the request; every
|
|
4
4
|
* answer is decided here, per request, from who is asking.
|
|
5
5
|
*
|
|
6
|
-
* GET /api/notify-inbox/summary unread
|
|
7
|
-
* GET /api/notify-inbox/items?
|
|
6
|
+
* GET /api/notify-inbox/summary counts per group, unread, the summary line, the domain map
|
|
7
|
+
* GET /api/notify-inbox/items?view=needs-you&keep=&before=&limit=
|
|
8
|
+
* GET /api/notify-inbox/events text/event-stream: a notice whenever the caller's inbox changed
|
|
8
9
|
* POST /api/notify-inbox/read { ids: [...], read?: false } or { all: true }
|
|
9
|
-
* POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press
|
|
10
|
+
* POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press (record: a
|
|
11
|
+
* record id or an ask's id; an ask's own buttons win in its thread)
|
|
10
12
|
* GET /api/notify-inbox/file?id=&name= a stored attachment
|
|
11
13
|
* GET /api/notify-inbox/push/config { publicKey }
|
|
12
14
|
* POST /api/notify-inbox/push/state { endpoint } → { subscribed }
|
|
@@ -21,12 +23,15 @@ import { extname } from 'node:path'
|
|
|
21
23
|
import { viewerOf } from './access.js'
|
|
22
24
|
import { EMITTING } from './actions.js'
|
|
23
25
|
import { PERSON_PATTERN, RECORD_ID_PATTERN } from './store.js'
|
|
26
|
+
import { buildItems, countItems } from './view.js'
|
|
24
27
|
|
|
25
28
|
export const PREFIX = '/api/notify-inbox'
|
|
26
29
|
const MAX_BODY = 16 * 1024
|
|
27
30
|
const PAGE = 50
|
|
28
|
-
/** Most
|
|
31
|
+
/** Most items a filtered view keeps on screen after they leave it (keys in `keep`). */
|
|
29
32
|
const KEEP_MAX = 200
|
|
33
|
+
const ITEM_KEY = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$/
|
|
34
|
+
const HEARTBEAT_MS = 25 * 1000
|
|
30
35
|
|
|
31
36
|
const HEADERS = {
|
|
32
37
|
'content-type': 'application/json; charset=utf-8',
|
|
@@ -63,9 +68,11 @@ async function body(request) {
|
|
|
63
68
|
* @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
|
|
64
69
|
* @param {string} options.serviceWorker - the service worker's source
|
|
65
70
|
* @param {() => Promise<Record<string, Record<string, string>>>} [options.strings] - the page's words, complete per tag
|
|
66
|
-
* @param {
|
|
71
|
+
* @param {ReturnType<import('./changes.js').createChanges>} options.changes
|
|
72
|
+
* @param {Record<string, { icon: string, tone?: string }>} options.domains - the domain map (src/domains.js)
|
|
73
|
+
* @param {number} options.summaryHours - how long a summary line is shown
|
|
67
74
|
*/
|
|
68
|
-
export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}),
|
|
75
|
+
export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), changes, domains, summaryHours }) {
|
|
69
76
|
/** Who is asking, as the inbox folders they may read; undefined with the response to send instead. */
|
|
70
77
|
async function caller() {
|
|
71
78
|
const viewer = await viewerOf(people, identity())
|
|
@@ -91,37 +98,88 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
|
|
|
91
98
|
return items.map(item => ({ ...item, presses: byPerson.get(item.person)?.get(item.id) ?? [] }))
|
|
92
99
|
}
|
|
93
100
|
|
|
101
|
+
/** The caller's items, folded and grouped as of now. */
|
|
102
|
+
async function itemsOf(who) {
|
|
103
|
+
const { items: records, asks, bad } = await store.view(who.folders)
|
|
104
|
+
return { items: buildItems(records, Date.now(), asks), bad }
|
|
105
|
+
}
|
|
106
|
+
|
|
94
107
|
const summary = handle(async (_request, who) => {
|
|
95
|
-
const { items, bad } = await store.
|
|
96
|
-
const unread = items
|
|
97
|
-
const
|
|
98
|
-
return json(200, { mode: who.mode, person: who.person, unread, total: items.length,
|
|
108
|
+
const [{ items, bad }, line] = await Promise.all([itemsOf(who), store.summaryLine(who.folders, summaryHours)])
|
|
109
|
+
const { groups, unread } = countItems(items)
|
|
110
|
+
const latest = items.reduce((newest, item) => (newest === null || item.time > newest ? item.time : newest), null)
|
|
111
|
+
return json(200, { mode: who.mode, person: who.person, unread, groups, total: items.length, latest, line, domains, problems: { badLines: bad } })
|
|
99
112
|
})
|
|
100
113
|
|
|
101
114
|
const list = handle(async (request, who) => {
|
|
102
115
|
const params = new URL(request.url).searchParams
|
|
103
116
|
const limit = Math.min(Math.max(Number(params.get('limit')) || PAGE, 1), 200)
|
|
104
|
-
let { items } = await
|
|
105
|
-
if (params.get('
|
|
106
|
-
// `keep` holds what the page already shows
|
|
107
|
-
const keep = new Set((params.get('keep') ?? '').split(',').filter(
|
|
108
|
-
items = items.filter(item =>
|
|
117
|
+
let { items } = await itemsOf(who)
|
|
118
|
+
if (params.get('view') === 'needs-you') {
|
|
119
|
+
// `keep` holds what the page already shows in this view, so those items stay put as they leave it.
|
|
120
|
+
const keep = new Set((params.get('keep') ?? '').split(',').filter(key => ITEM_KEY.test(key)).slice(0, KEEP_MAX))
|
|
121
|
+
items = items.filter(item => item.group === 'needs-you' || keep.has(item.key))
|
|
109
122
|
}
|
|
110
123
|
const before = params.get('before')
|
|
111
124
|
if (before) {
|
|
112
|
-
const at = items.findIndex(item => item.
|
|
125
|
+
const at = items.findIndex(item => item.key === before)
|
|
113
126
|
items = at < 0 ? [] : items.slice(at + 1)
|
|
114
127
|
}
|
|
115
128
|
const page = items.slice(0, limit)
|
|
116
129
|
return json(200, { items: await withPresses(who, page), more: items.length > limit })
|
|
117
130
|
})
|
|
118
131
|
|
|
119
|
-
/**
|
|
132
|
+
/** A notice per change, a comment every 25 s so proxies keep the stream open; ends when the page goes. */
|
|
133
|
+
const events = handle(async (request, who) => {
|
|
134
|
+
const encoder = new TextEncoder()
|
|
135
|
+
let stop = () => {}
|
|
136
|
+
const stream = new ReadableStream({
|
|
137
|
+
start(controller) {
|
|
138
|
+
const write = chunk => {
|
|
139
|
+
try {
|
|
140
|
+
controller.enqueue(encoder.encode(chunk))
|
|
141
|
+
} catch {
|
|
142
|
+
stop()
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
write('retry: 5000\n: open\n\n')
|
|
146
|
+
const unlisten = changes.listen(who.mode === 'owner' ? null : who.folders, () => write(`data: ${JSON.stringify({ type: 'change', at: new Date().toISOString() })}\n\n`))
|
|
147
|
+
const beat = setInterval(() => write(': beat\n\n'), HEARTBEAT_MS)
|
|
148
|
+
stop = () => {
|
|
149
|
+
unlisten()
|
|
150
|
+
clearInterval(beat)
|
|
151
|
+
}
|
|
152
|
+
request.signal?.addEventListener('abort', () => {
|
|
153
|
+
stop()
|
|
154
|
+
try {
|
|
155
|
+
controller.close()
|
|
156
|
+
} catch {
|
|
157
|
+
// Already closed.
|
|
158
|
+
}
|
|
159
|
+
}, { once: true })
|
|
160
|
+
},
|
|
161
|
+
cancel() {
|
|
162
|
+
stop()
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
return new Response(stream, {
|
|
166
|
+
status: 200,
|
|
167
|
+
headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'private, no-cache, no-transform', 'x-accel-buffering': 'no', 'x-content-type-options': 'nosniff' },
|
|
168
|
+
})
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The record (or open ask) with this id the caller may see, with the buttons it answers to: an open
|
|
173
|
+
* ask's own for the ask and every record in its thread. Undefined when there is none.
|
|
174
|
+
*/
|
|
120
175
|
async function recordOf(who, id) {
|
|
121
176
|
if (typeof id !== 'string' || !RECORD_ID_PATTERN.test(id)) return undefined
|
|
122
177
|
for (const person of who.folders) {
|
|
178
|
+
const { asks } = await store.asks(person)
|
|
123
179
|
const record = (await store.records(person)).records.find(row => row.id === id)
|
|
124
|
-
|
|
180
|
+
const ask = asks.find(row => row.id === id || row.id === record?.thread)
|
|
181
|
+
if (record !== undefined) return ask === undefined ? record : { ...record, actions: [...record.actions.filter(a => a.kind !== 'done' && a.kind !== 'snooze'), ...ask.actions] }
|
|
182
|
+
if (ask !== undefined) return { ...ask, key: '', thread: ask.id }
|
|
125
183
|
}
|
|
126
184
|
return undefined
|
|
127
185
|
}
|
|
@@ -204,6 +262,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
|
|
|
204
262
|
return [
|
|
205
263
|
get('/summary', summary),
|
|
206
264
|
get('/items', list),
|
|
265
|
+
get('/events', events),
|
|
207
266
|
post('/read', read),
|
|
208
267
|
post('/action', action),
|
|
209
268
|
get('/file', file),
|
package/src/store.js
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
* <dataDir>/<person>/inbox.jsonl one record per line; written by the router only
|
|
6
6
|
* <dataDir>/<person>/files/<id>/<name> attachments the router copied in
|
|
7
7
|
* <dataDir>/<person>/read.json read marks; written by this plugin only
|
|
8
|
+
* <dataDir>/<person>/summary.json the line shown above the items; written by the router's side
|
|
9
|
+
* <dataDir>/<person>/asks.json what waits on the person's answer now; written by whatever keeps their
|
|
10
|
+
* list of asks (a Todo), read fresh each time
|
|
8
11
|
*
|
|
9
12
|
* Records are re-read incrementally: only the bytes appended since the last
|
|
10
13
|
* look are parsed, and the whole file again when it shrank or was replaced
|
|
@@ -18,18 +21,92 @@ export const PERSON_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
|
|
18
21
|
export const RECORD_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$/
|
|
19
22
|
const INBOX = 'inbox.jsonl'
|
|
20
23
|
const READ = 'read.json'
|
|
24
|
+
const SUMMARY = 'summary.json'
|
|
25
|
+
const ASKS = 'asks.json'
|
|
21
26
|
|
|
22
27
|
const text = value => (typeof value === 'string' ? value : '')
|
|
23
28
|
const list = value => (Array.isArray(value) ? value : [])
|
|
24
29
|
/** Text a person reads: a string, or a map from language tag to text (the page picks the language). */
|
|
25
30
|
const words = value => (typeof value === 'string' ? value : value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(v => typeof v === 'string') ? value : '')
|
|
26
31
|
|
|
32
|
+
export const GROUPS = ['urgent', 'needs-you', 'live', 'handled', 'info']
|
|
33
|
+
const MAX_THREAD = 120
|
|
34
|
+
const MAX_ASK_TEXT = 8000
|
|
35
|
+
|
|
36
|
+
const isoTime = value => {
|
|
37
|
+
const at = Date.parse(text(value))
|
|
38
|
+
return Number.isNaN(at) ? undefined : new Date(at).toISOString()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** `live` as `{ until?, progress?: { from, to } }`, or null. */
|
|
42
|
+
function liveOf(raw) {
|
|
43
|
+
if (raw === true) return {}
|
|
44
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
|
|
45
|
+
const out = {}
|
|
46
|
+
const until = isoTime(raw.until)
|
|
47
|
+
if (until !== undefined) out.until = until
|
|
48
|
+
const from = isoTime(raw.progress?.from)
|
|
49
|
+
const to = isoTime(raw.progress?.to)
|
|
50
|
+
if (from !== undefined && to !== undefined && from < to) out.progress = { from, to }
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** `handled` as `{ text, at? }`, or null. */
|
|
55
|
+
function handledOf(raw) {
|
|
56
|
+
const value = typeof raw === 'string' ? { text: raw } : raw
|
|
57
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value) || text(value.text).trim() === '') return null
|
|
58
|
+
const at = isoTime(value.at)
|
|
59
|
+
return at === undefined ? { text: value.text.trim() } : { text: value.text.trim(), at }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The group a record belongs in. A writer usually says (`attention`); for a record that doesn't,
|
|
64
|
+
* the same default the router documents: handled, then live, then urgent for an interrupt, else info.
|
|
65
|
+
* Needs-you is never a default: it is for asks (see `asks`).
|
|
66
|
+
*/
|
|
67
|
+
export function attentionOf(record) {
|
|
68
|
+
if (GROUPS.includes(record.attention)) return record.attention
|
|
69
|
+
if (record.handled !== null) return 'handled'
|
|
70
|
+
if (record.live !== null) return 'live'
|
|
71
|
+
if (record.lane === 'interrupt') return 'urgent'
|
|
72
|
+
return 'info'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const actionsOf = raw => list(raw).filter(action => typeof action?.kind === 'string' && typeof action?.id === 'string').map(action => ({
|
|
76
|
+
kind: action.kind,
|
|
77
|
+
id: action.id,
|
|
78
|
+
label: words(action.label) || undefined,
|
|
79
|
+
payload: typeof action.payload === 'object' && action.payload !== null && !Array.isArray(action.payload) ? action.payload : {},
|
|
80
|
+
...(typeof action.inverse?.kind === 'string' ? { inverse: { kind: action.inverse.kind, payload: typeof action.inverse.payload === 'object' && action.inverse.payload !== null ? action.inverse.payload : {} } } : {}),
|
|
81
|
+
}))
|
|
82
|
+
|
|
83
|
+
/** One entry of `asks.json` as the page gets it, or undefined when it is not one. */
|
|
84
|
+
export function normalizeAsk(raw, person) {
|
|
85
|
+
if (typeof raw !== 'object' || raw === null || !RECORD_ID_PATTERN.test(text(raw.id))) return undefined
|
|
86
|
+
const time = isoTime(raw.time)
|
|
87
|
+
if (time === undefined || text(raw.title).trim() === '') return undefined
|
|
88
|
+
const day = value => (/^\d{4}-\d{2}-\d{2}$/.test(text(value)) ? value : undefined)
|
|
89
|
+
return {
|
|
90
|
+
id: raw.id,
|
|
91
|
+
person,
|
|
92
|
+
time,
|
|
93
|
+
title: text(raw.title),
|
|
94
|
+
text: text(raw.text).slice(0, MAX_ASK_TEXT),
|
|
95
|
+
domain: text(raw.domain),
|
|
96
|
+
next: day(raw.next),
|
|
97
|
+
due: day(raw.due),
|
|
98
|
+
points: Number.isFinite(raw.points) && raw.points > 0 ? Math.round(raw.points) : null,
|
|
99
|
+
session: /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(text(raw.session)) ? raw.session : null,
|
|
100
|
+
actions: actionsOf(raw.actions),
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
27
104
|
/** A record as the page gets it, or undefined when the line is not one. */
|
|
28
105
|
export function normalize(raw, person) {
|
|
29
106
|
if (typeof raw !== 'object' || raw === null || !RECORD_ID_PATTERN.test(text(raw.id))) return undefined
|
|
30
107
|
const time = Date.parse(text(raw.time))
|
|
31
108
|
if (Number.isNaN(time)) return undefined
|
|
32
|
-
|
|
109
|
+
const record = {
|
|
33
110
|
id: raw.id,
|
|
34
111
|
person,
|
|
35
112
|
time: new Date(time).toISOString(),
|
|
@@ -47,12 +124,12 @@ export function normalize(raw, person) {
|
|
|
47
124
|
})),
|
|
48
125
|
source: text(raw.source),
|
|
49
126
|
key: text(raw.key),
|
|
50
|
-
actions:
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
})),
|
|
127
|
+
actions: actionsOf(raw.actions),
|
|
128
|
+
attention: text(raw.attention),
|
|
129
|
+
thread: text(raw.thread).trim().slice(0, MAX_THREAD),
|
|
130
|
+
live: liveOf(raw.live),
|
|
131
|
+
handled: handledOf(raw.handled),
|
|
132
|
+
session: /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(text(raw.session)) ? raw.session : null,
|
|
56
133
|
test: raw.test === true,
|
|
57
134
|
push: raw.push !== false,
|
|
58
135
|
routed: list(raw.routed).filter(row => typeof row?.destination === 'string').map(row => ({
|
|
@@ -62,6 +139,9 @@ export function normalize(raw, person) {
|
|
|
62
139
|
detail: text(row.detail) || undefined,
|
|
63
140
|
})),
|
|
64
141
|
}
|
|
142
|
+
record.attention = attentionOf(record)
|
|
143
|
+
if (record.live === null && record.attention === 'live') record.live = {}
|
|
144
|
+
return record
|
|
65
145
|
}
|
|
66
146
|
|
|
67
147
|
/** A "this press was handled" line the router appends after acting on a press, or undefined. */
|
|
@@ -114,6 +194,24 @@ export async function readFrom(path, offset) {
|
|
|
114
194
|
}
|
|
115
195
|
}
|
|
116
196
|
|
|
197
|
+
const HEAD_BYTES = 256
|
|
198
|
+
|
|
199
|
+
/** The first bytes of a file, as text (empty when it can't be read). */
|
|
200
|
+
async function readHead(path, length) {
|
|
201
|
+
try {
|
|
202
|
+
const handle = await open(path, 'r')
|
|
203
|
+
try {
|
|
204
|
+
const buffer = Buffer.alloc(length)
|
|
205
|
+
const { bytesRead } = await handle.read(buffer, 0, length, 0)
|
|
206
|
+
return buffer.subarray(0, bytesRead).toString('latin1')
|
|
207
|
+
} finally {
|
|
208
|
+
await handle.close()
|
|
209
|
+
}
|
|
210
|
+
} catch {
|
|
211
|
+
return ''
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
117
215
|
async function atomicWrite(path, value) {
|
|
118
216
|
const tmp = `${path}.${process.pid}.${Date.now()}.tmp`
|
|
119
217
|
await writeFile(tmp, JSON.stringify(value), { mode: 0o600 })
|
|
@@ -154,11 +252,14 @@ export function createStore(dataDir) {
|
|
|
154
252
|
return { records: [], handled: [], bad: 0 }
|
|
155
253
|
}
|
|
156
254
|
let entry = cache.get(person)
|
|
157
|
-
|
|
158
|
-
|
|
255
|
+
// A file rewritten in place (same inode, someone removed a line by hand) starts differently.
|
|
256
|
+
const replaced = entry !== undefined && entry.head !== '' && (await readHead(path, entry.head.length)) !== entry.head
|
|
257
|
+
if (entry === undefined || entry.ino !== info.ino || info.size < entry.offset || replaced) {
|
|
258
|
+
entry = { ino: info.ino, offset: 0, head: '', records: [], handled: [], bad: 0 }
|
|
159
259
|
cache.set(person, entry)
|
|
160
260
|
}
|
|
161
261
|
if (info.size > entry.offset) {
|
|
262
|
+
if (entry.offset === 0) entry.head = await readHead(path, HEAD_BYTES)
|
|
162
263
|
const parsed = parseLines(await readFrom(path, entry.offset), person)
|
|
163
264
|
entry.records.push(...parsed.records)
|
|
164
265
|
entry.handled.push(...parsed.handled)
|
|
@@ -168,6 +269,20 @@ export function createStore(dataDir) {
|
|
|
168
269
|
return { records: entry.records, handled: entry.handled, bad: entry.bad }
|
|
169
270
|
}
|
|
170
271
|
|
|
272
|
+
/**
|
|
273
|
+
* What waits on this person now, read fresh from `<person>/asks.json`: `{ present, asks }`. Without the
|
|
274
|
+
* file nothing is said about asks and records keep their own groups; with it, it alone says what needs them.
|
|
275
|
+
*/
|
|
276
|
+
async function asks(person) {
|
|
277
|
+
let value
|
|
278
|
+
try {
|
|
279
|
+
value = JSON.parse(await readFile(join(dataDir, person, ASKS), 'utf8'))
|
|
280
|
+
} catch {
|
|
281
|
+
return { present: false, asks: [] }
|
|
282
|
+
}
|
|
283
|
+
return { present: true, asks: list(value?.asks).map(raw => normalizeAsk(raw, person)).filter(Boolean) }
|
|
284
|
+
}
|
|
285
|
+
|
|
171
286
|
async function marks(person) {
|
|
172
287
|
try {
|
|
173
288
|
const value = JSON.parse(await readFile(join(dataDir, person, READ), 'utf8'))
|
|
@@ -188,7 +303,7 @@ export function createStore(dataDir) {
|
|
|
188
303
|
* Each list keeps only what the watermark doesn't already say.
|
|
189
304
|
*/
|
|
190
305
|
async function setRead(person, ids, value) {
|
|
191
|
-
const byId = new Map((await records(person)).records.map(
|
|
306
|
+
const byId = new Map([...(await asks(person)).asks, ...(await records(person)).records].map(row => [row.id, row]))
|
|
192
307
|
const current = await marks(person)
|
|
193
308
|
const read = new Set(current.read)
|
|
194
309
|
const unread = new Set(current.unread)
|
|
@@ -214,19 +329,45 @@ export function createStore(dataDir) {
|
|
|
214
329
|
await saveMarks(person, { readBefore, read: current.read.filter(id => byId.has(id) && byId.get(id).time > readBefore), unread: [] })
|
|
215
330
|
}
|
|
216
331
|
|
|
217
|
-
/**
|
|
332
|
+
/**
|
|
333
|
+
* The records of these people, newest first, each with `read` and the `outcomes` of presses on it, and
|
|
334
|
+
* their asks by person (`{ present, asks }`, each ask with `read`).
|
|
335
|
+
*/
|
|
218
336
|
async function view(people) {
|
|
219
337
|
const out = []
|
|
338
|
+
const asking = new Map()
|
|
220
339
|
let bad = 0
|
|
221
340
|
for (const person of people) {
|
|
222
|
-
const [{ records: rows, handled, bad: skipped }, marked] = await Promise.all([records(person), marks(person)])
|
|
341
|
+
const [{ records: rows, handled, bad: skipped }, marked, open] = await Promise.all([records(person), marks(person), asks(person)])
|
|
223
342
|
bad += skipped
|
|
224
343
|
const byRecord = new Map()
|
|
225
344
|
for (const status of handled) byRecord.set(status.record, [...(byRecord.get(status.record) ?? []), status])
|
|
226
|
-
for (const record of rows) out.push({ ...record, read: isRead(marked, record),
|
|
345
|
+
for (const record of rows) out.push({ ...record, read: isRead(marked, record), outcomes: byRecord.get(record.id) ?? [] })
|
|
346
|
+
asking.set(person, { present: open.present, asks: open.asks.map(ask => ({ ...ask, read: isRead(marked, ask), outcomes: byRecord.get(ask.id) ?? [] })) })
|
|
227
347
|
}
|
|
228
348
|
out.sort((a, b) => (a.time === b.time ? 0 : a.time < b.time ? 1 : -1))
|
|
229
|
-
return { items: out, bad }
|
|
349
|
+
return { items: out, asks: asking, bad }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The newest summary line of these people (`<person>/summary.json`, `{ text, at }`, written by
|
|
354
|
+
* whatever keeps the inbox), or null when there is none or it is older than `maxHours`.
|
|
355
|
+
*/
|
|
356
|
+
async function summaryLine(people, maxHours, now = Date.now()) {
|
|
357
|
+
let best = null
|
|
358
|
+
for (const person of people) {
|
|
359
|
+
let value
|
|
360
|
+
try {
|
|
361
|
+
value = JSON.parse(await readFile(join(dataDir, person, SUMMARY), 'utf8'))
|
|
362
|
+
} catch {
|
|
363
|
+
continue
|
|
364
|
+
}
|
|
365
|
+
const said = words(value?.text)
|
|
366
|
+
const at = isoTime(value?.at)
|
|
367
|
+
if (said === '' || at === undefined || now - Date.parse(at) > maxHours * 3600 * 1000) continue
|
|
368
|
+
if (best === null || at > best.at) best = { text: said, at }
|
|
369
|
+
}
|
|
370
|
+
return best
|
|
230
371
|
}
|
|
231
372
|
|
|
232
373
|
/** Where a stored attachment lives, or undefined. */
|
|
@@ -240,5 +381,5 @@ export function createStore(dataDir) {
|
|
|
240
381
|
return undefined
|
|
241
382
|
}
|
|
242
383
|
|
|
243
|
-
return { persons, records, marks, setRead, markAllRead, view, file }
|
|
384
|
+
return { persons, records, asks, marks, setRead, markAllRead, view, summaryLine, file }
|
|
244
385
|
}
|
package/src/view.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the page lists: items, not records. Records of one person with the same
|
|
3
|
+
* `thread` fold into one item, the newest on top and the older ones as its
|
|
4
|
+
* history; a live thread's newest record simply replaces the item. Each item
|
|
5
|
+
* gets the group it shows in now, which can differ from what its writer said:
|
|
6
|
+
* an urgent item the person marked done is handled, a snoozed one waits under
|
|
7
|
+
* info until it comes back as a new record, and a live item whose time is over
|
|
8
|
+
* is info.
|
|
9
|
+
*
|
|
10
|
+
* A person whose inbox has an asks file (`asks.json`) gets their "Needs you"
|
|
11
|
+
* from it alone: each open ask is one item, with the records of its thread
|
|
12
|
+
* folded in when there are any, and a record that said needs-you but whose
|
|
13
|
+
* ask is no longer open has been dealt with in its source, so it is handled.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash } from 'node:crypto'
|
|
16
|
+
import { GROUPS } from './store.js'
|
|
17
|
+
|
|
18
|
+
/** A live item without `until` stops being live this long after its last update. */
|
|
19
|
+
export const LIVE_IDLE_MS = 6 * 60 * 60 * 1000
|
|
20
|
+
const HISTORY_MAX = 20
|
|
21
|
+
|
|
22
|
+
/** A stable key for an item: the record id, or a hash of person and thread (safe in a query string). */
|
|
23
|
+
export function itemKey(record) {
|
|
24
|
+
if (record.thread === '') return record.id
|
|
25
|
+
return `t-${createHash('sha256').update(`${record.person}\n${record.thread}`).digest('hex').slice(0, 20)}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Whether a record's live state still runs at `now` (ms). */
|
|
29
|
+
export function liveNow(record, now) {
|
|
30
|
+
if (record.live === null) return false
|
|
31
|
+
const end = record.live.until !== undefined ? Date.parse(record.live.until) : Date.parse(record.time) + LIVE_IDLE_MS
|
|
32
|
+
return now < end
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The group an item's newest record shows in at `now`, with `moved` saying why when it isn't the
|
|
37
|
+
* writer's: 'done' (the person marked it done), 'snoozed', 'ended' (a live item past its time) or
|
|
38
|
+
* 'closed' (its ask is no longer open). `asked` is the person's asks (`{ present, open: Set }`).
|
|
39
|
+
*/
|
|
40
|
+
export function groupOf(record, now, asked = { present: false, open: new Set() }) {
|
|
41
|
+
if (record.attention === 'needs-you' && asked.present) {
|
|
42
|
+
if (asked.open.has(record.thread)) return { group: 'needs-you', moved: null }
|
|
43
|
+
return record.thread === '' ? { group: record.lane === 'interrupt' ? 'urgent' : 'info', moved: null } : { group: 'handled', moved: 'closed' }
|
|
44
|
+
}
|
|
45
|
+
if (record.attention === 'urgent' || record.attention === 'needs-you') {
|
|
46
|
+
const last = record.outcomes.findLast(row => row.result === 'done' || row.result === 'snoozed')
|
|
47
|
+
if (last?.result === 'done') return { group: 'handled', moved: 'done' }
|
|
48
|
+
if (last?.result === 'snoozed' && (last.until === undefined || Date.parse(last.until) > now)) return { group: 'info', moved: 'snoozed' }
|
|
49
|
+
}
|
|
50
|
+
if (record.attention === 'live' && !liveNow(record, now)) return { group: 'info', moved: 'ended' }
|
|
51
|
+
return { group: record.attention, moved: null }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** An open ask as an item: alone, or on top of its thread's newest record. */
|
|
55
|
+
function askItem(ask, record) {
|
|
56
|
+
const base = record ?? {
|
|
57
|
+
id: ask.id, person: ask.person, time: ask.time, lane: 'next-moment', domain: ask.domain, title: ask.title, spoken: '',
|
|
58
|
+
text: ask.text, links: [], files: [], source: '', key: '', actions: [], thread: ask.id, live: null, handled: null,
|
|
59
|
+
session: null, test: false, push: false, routed: [], read: ask.read, outcomes: ask.outcomes,
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
...base,
|
|
63
|
+
title: ask.title,
|
|
64
|
+
text: record === undefined || record.text === '' ? ask.text : record.text,
|
|
65
|
+
actions: [...base.actions.filter(action => action.kind !== 'done' && action.kind !== 'snooze'), ...ask.actions],
|
|
66
|
+
attention: 'needs-you',
|
|
67
|
+
session: ask.session ?? base.session,
|
|
68
|
+
ask: { id: ask.id, points: ask.points, next: ask.next, due: ask.due, text: ask.text },
|
|
69
|
+
read: record === undefined ? ask.read : base.read,
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Fold records (newest first, each with `read` and `outcomes`) and the people's asks (person →
|
|
75
|
+
* `{ present, asks }`) into items, ordered by group (urgent, needs-you, live, handled, info) and
|
|
76
|
+
* newest first within a group.
|
|
77
|
+
*/
|
|
78
|
+
export function buildItems(records, now, asking = new Map()) {
|
|
79
|
+
const asked = new Map([...asking].map(([person, value]) => [person, { present: value.present, open: new Map(value.asks.map(ask => [ask.id, ask])) }]))
|
|
80
|
+
const byKey = new Map()
|
|
81
|
+
for (const record of records) {
|
|
82
|
+
const key = itemKey(record)
|
|
83
|
+
const item = byKey.get(key)
|
|
84
|
+
if (item === undefined) {
|
|
85
|
+
byKey.set(key, { ...record, key, ids: [record.id], history: [] })
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
item.ids.push(record.id)
|
|
89
|
+
item.read &&= record.read
|
|
90
|
+
if (item.history.length < HISTORY_MAX) item.history.push({ id: record.id, time: record.time, title: record.title, spoken: record.spoken })
|
|
91
|
+
}
|
|
92
|
+
for (const [person, { open }] of asked) {
|
|
93
|
+
for (const ask of open.values()) {
|
|
94
|
+
const key = itemKey({ person, thread: ask.id, id: ask.id })
|
|
95
|
+
const folded = byKey.get(key)
|
|
96
|
+
byKey.set(key, folded === undefined ? { ...askItem(ask), key, ids: [ask.id], history: [] } : { ...askItem(ask, folded), key, ids: folded.ids, history: folded.history })
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const items = [...byKey.values()].map(item => {
|
|
100
|
+
const mine = asked.get(item.person)
|
|
101
|
+
const where = groupOf(item, now, mine === undefined ? undefined : { present: mine.present, open: mine.open })
|
|
102
|
+
return { ...item, ...where, liveNow: liveNow(item, now) }
|
|
103
|
+
})
|
|
104
|
+
const rank = group => GROUPS.indexOf(group)
|
|
105
|
+
return items.sort((a, b) => rank(a.group) - rank(b.group) || (a.time === b.time ? 0 : a.time < b.time ? 1 : -1))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** How many items each group has, and how many are unread. */
|
|
109
|
+
export function countItems(items) {
|
|
110
|
+
const groups = Object.fromEntries(GROUPS.map(group => [group, 0]))
|
|
111
|
+
let unread = 0
|
|
112
|
+
for (const item of items) {
|
|
113
|
+
groups[item.group] += 1
|
|
114
|
+
if (!item.read) unread += 1
|
|
115
|
+
}
|
|
116
|
+
return { groups, unread }
|
|
117
|
+
}
|