@yaks/notify 0.0.0-stage → 0.2.36

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/whereabouts.js ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Where a person is available right now, channel by channel: the Operator's
3
+ * page open and focused, open in a background tab, an app's page open,
4
+ * Discord's status, and when they last texted or emailed. Each is a
5
+ * `whereabouts` row a host writes when the channel says something new
6
+ * ({@link noted}), and each fades on its own once the channel has gone quiet
7
+ * longer than its {@link FADE}, so a dropped socket or a lost close never
8
+ * leaves someone "here" for good.
9
+ *
10
+ * Pure: a host reads the rows, applies what {@link noted} returns, and reads
11
+ * {@link glance} to say it ({@link whereaboutsLine}) or to choose where to reach
12
+ * the person ({@link reachBy}).
13
+ *
14
+ * ```ts
15
+ * import { glance, noted, whereaboutsLine, reachBy } from '@yaks/notify/whereabouts'
16
+ * import { equal } from '@yaks/testing'
17
+ *
18
+ * let now = Date.parse('2026-11-20T12:00:00Z')
19
+ * let tab = noted(undefined, { person: 'jeff', channel: 'operator', place: 'home', state: 'here' }, now)!
20
+ * let discord = noted(undefined, { person: 'jeff', channel: 'discord', state: 'online' }, now)!
21
+ * let seen = glance([tab, discord], { place: 'home', now })
22
+ * equal(whereaboutsLine('Jeff', seen), 'Jeff: here, this tab · Discord online')
23
+ * equal(reachBy(seen), 'tab')
24
+ * // The same state said again soon after writes nothing.
25
+ * equal(noted(tab, { person: 'jeff', channel: 'operator', place: 'home', state: 'here' }, now + 1000), undefined)
26
+ * ```
27
+ */ import { derivedEid } from "@yaks/graph/identity";
28
+ let MINUTE = 60_000;
29
+ let HOUR = 60 * MINUTE;
30
+ /** How long a channel's last word stands. A page says its state again while
31
+ * it is open ({@link BEAT}), so a page whose close was lost fades in minutes;
32
+ * Discord says a change only when there is one, and resends every status
33
+ * when its bot reconnects; a text or an email is a moment, said as "texted
34
+ * 2h ago" for a day. */ export let FADE = {
35
+ operator: 15 * MINUTE,
36
+ apps: 15 * MINUTE,
37
+ discord: 12 * HOUR,
38
+ text: 24 * HOUR,
39
+ email: 24 * HOUR
40
+ };
41
+ /** How often an open page says its state again. */ export let BEAT = 5 * MINUTE;
42
+ // A state that says the person is not there: never worth a new row.
43
+ let gone = (s)=>s == 'away' || s == 'offline';
44
+ /** The row a person's whereabouts on `channel` (at `place`) is kept in. */ export let whereaboutsEid = (person, channel, place)=>derivedEid(`whereabouts|${person}|${channel}|${place ?? ''}`);
45
+ /**
46
+ * The write `said` needs, given the row it replaces: none when the state is
47
+ * unchanged and its row is still fresh (younger than a third of its fade),
48
+ * so a page saying "still here" every {@link BEAT} writes about once in
49
+ * three, and Discord's many identical updates write once. A person never
50
+ * seen there who is said to be away writes nothing.
51
+ */ export let noted = (row, said, now = Date.now())=>{
52
+ let was = row?.whereabouts;
53
+ let age = now - Date.parse(was?.at ?? '');
54
+ if (!was?.state && gone(said.state)) return;
55
+ if (was?.state == said.state && age < FADE[said.channel] / 3) return;
56
+ if (gone(said.state) && (gone(was?.state) || !(age < FADE[said.channel]))) {
57
+ return;
58
+ }
59
+ return {
60
+ entity: {
61
+ eid: whereaboutsEid(said.person, said.channel, said.place)
62
+ },
63
+ whereabouts: {
64
+ person: said.person,
65
+ channel: said.channel,
66
+ ...said.place ? {
67
+ place: said.place
68
+ } : {},
69
+ state: said.state,
70
+ at: new Date(now).toISOString()
71
+ }
72
+ };
73
+ };
74
+ /** The tab a socket's frame says, none for any other frame. */ export let tabSaid = (frame)=>{
75
+ let tab = frame?.tab;
76
+ if (!tab || typeof tab != 'object') return;
77
+ let { visible, focused, idle } = tab;
78
+ return {
79
+ visible: visible === true,
80
+ focused: focused === true,
81
+ ...typeof idle == 'boolean' ? {
82
+ idle
83
+ } : {}
84
+ };
85
+ };
86
+ /** The state of a page across a person's tabs on it: `here`
87
+ * when one is visible and focused, `background` when one is open, `away`
88
+ * when none is. */ export let tabsState = (tabs)=>tabs.some((t)=>t.visible && t.focused) ? 'here' : tabs.length ? 'background' : 'away';
89
+ export let tabActivity = (tabs)=>tabs.some((t)=>t.visible && t.focused && t.idle === false) ? 'active' : tabs.length ? 'away' : 'offline';
90
+ /** The durable timestamp of when a person's first page opened or last page closed. */ export let pageWord = (person, state, now)=>({
91
+ entity: {
92
+ eid: whereaboutsEid(person, 'apps')
93
+ },
94
+ whereabouts: {
95
+ person,
96
+ channel: 'apps',
97
+ state,
98
+ at: new Date(now).toISOString()
99
+ }
100
+ });
101
+ /** Read the unplaced page's history with the tabs that are still connected.
102
+ * A disconnected page's timestamp still stands, even when its close was lost. */ export let pageWhereabouts = (history, person, tabs, now)=>{
103
+ let eid = whereaboutsEid(person, 'apps');
104
+ let past = history.find((row)=>row.entity.eid == eid);
105
+ if (!past && !tabs.length) return history;
106
+ let activity = tabActivity(tabs);
107
+ let state = activity == 'active' ? 'here' : activity == 'away' ? 'background' : 'away';
108
+ let page = past ?? pageWord(person, state, now);
109
+ return [
110
+ ...history.filter((row)=>row.entity.eid != eid),
111
+ {
112
+ ...page,
113
+ whereabouts: {
114
+ ...page.whereabouts,
115
+ state,
116
+ live: !!tabs.length
117
+ }
118
+ }
119
+ ];
120
+ };
121
+ /** Activity as seen in the computed unplaced page row. */ export let pageActivity = (rows)=>{
122
+ let page = rows.find(({ whereabouts: p })=>p?.live && p.channel == 'apps' && !p.place);
123
+ return page ? page.whereabouts?.state == 'here' ? 'active' : 'away' : 'offline';
124
+ };
125
+ /** Whether a channel's last word still stands. A live page follows its socket. */ export let fresh = (p, now)=>!!p.live || now - Date.parse(p.at ?? '') < (FADE[p.channel] ?? 0);
126
+ /** The rows still standing, read as one Operator's glance: `place` is its
127
+ * space. */ export let glance = (rows, { place, now = Date.now() })=>{
128
+ let seen = {
129
+ now
130
+ };
131
+ for (let { whereabouts: p } of rows){
132
+ if (!p?.channel || !p.state || !p.at) continue;
133
+ let channel = p.channel;
134
+ if (!fresh(p, now)) continue;
135
+ if (channel == 'operator' && p.place == place) {
136
+ if (p.state == 'here' || p.state == 'background') {
137
+ seen.tab = seen.tab == 'here' ? 'here' : p.state;
138
+ }
139
+ } else if (channel == 'operator' || channel == 'apps') {
140
+ if (!gone(p.state)) seen.elsewhere = true;
141
+ } else if (channel == 'discord') {
142
+ seen.discord = p.state;
143
+ } else if (channel == 'text') seen.texted = latest(seen.texted, p.at);
144
+ else if (channel == 'email') seen.emailed = latest(seen.emailed, p.at);
145
+ }
146
+ return seen;
147
+ };
148
+ /** The presence the rows still standing say, none when no page of the
149
+ * person's is open. Never stored: it is read off the rows each time. */ export let presence = (rows, now = Date.now())=>{
150
+ let spaces = new Set(), apps = new Set();
151
+ let open = false;
152
+ for (let { whereabouts: p } of rows){
153
+ let channel = p?.channel;
154
+ if (channel != 'operator' && channel != 'apps') continue;
155
+ if (!p?.state || gone(p.state) || !p.at) continue;
156
+ if (!fresh(p, now)) continue;
157
+ open = true;
158
+ if (p.place) (channel == 'operator' ? spaces : apps).add(p.place);
159
+ }
160
+ if (!open) return;
161
+ return {
162
+ state: spaces.size ? 'building' : 'online',
163
+ spaces: [
164
+ ...spaces
165
+ ],
166
+ apps: [
167
+ ...apps
168
+ ]
169
+ };
170
+ };
171
+ /** When a person was last active on yaks.app: the newest word any page of
172
+ * theirs, or a text or an email to their Operator, said of them, faded or
173
+ * not. Discord's status is not something they did here. None for someone
174
+ * never seen. */ export let lastSeen = (rows)=>{
175
+ let last;
176
+ for (let { whereabouts: p } of rows){
177
+ if (p?.at && p.channel && p.channel != 'discord') last = latest(last, p.at);
178
+ }
179
+ return last;
180
+ };
181
+ let latest = (a, b)=>!a || b > a ? b : a;
182
+ /** How long ago `at` was, as a person says it: 4m, 2h, 1d. */ export let ago = (at, now)=>{
183
+ let ms = Math.max(0, now - Date.parse(at));
184
+ return ms < HOUR ? `${Math.max(1, Math.round(ms / MINUTE))}m` : ms < 24 * HOUR ? `${Math.round(ms / HOUR)}h` : `${Math.round(ms / (24 * HOUR))}d`;
185
+ };
186
+ let DISCORD = {
187
+ online: 'Discord online',
188
+ idle: 'Discord idle',
189
+ dnd: 'Discord do not disturb',
190
+ offline: 'Discord offline'
191
+ };
192
+ /** The glance in one short line, for each of an Operator's turns:
193
+ * "Jeff: here, this tab · Discord online". */ export let whereaboutsLine = (name, g)=>{
194
+ let parts = [
195
+ g.tab == 'here' ? 'here, this tab' : g.tab == 'background' ? 'this Operator open in a background tab' : g.elsewhere ? 'on yaks.app, not on this Operator' : 'not on yaks.app',
196
+ g.discord && DISCORD[g.discord],
197
+ g.texted && `texted ${ago(g.texted, g.now)} ago`,
198
+ g.emailed && `emailed ${ago(g.emailed, g.now)} ago`
199
+ ];
200
+ return `${name}: ${parts.filter(Boolean).join(' · ')}`;
201
+ };
202
+ export let reachBy = (g)=>g.tab == 'here' ? 'tab' : g.tab == 'background' || g.elsewhere ? 'notification' : g.discord == 'online' ? 'discord' : 'usual';
203
+ //# sourceMappingURL=whereabouts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whereabouts.js","sources":["./whereabouts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,SAAS,UAAU,oCAAyC;AA6B5D,IAAI,SAAS;AACb,IAAI,OAAO,KAAK;AAEhB;;;;sBAIsB,GACtB,OAAO,IAAI,OAAgC;EACzC,UAAU,KAAK;EACf,MAAM,KAAK;EACX,SAAS,KAAK;EACd,MAAM,KAAK;EACX,OAAO,KAAK;AACd,EAAC;AAED,iDAAiD,GACjD,OAAO,IAAI,OAAe,IAAI,OAAM;AAEpC,oEAAoE;AACpE,IAAI,OAAO,CAAC,IAAe,KAAK,UAAU,KAAK;AAE/C,yEAAyE,GACzE,OAAO,IAAI,iBAAiB,CAC1B,QACA,SACA,QACW,WAAW,CAAC,YAAY,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,EAAE,SAAS,IAAI,EAAC;AAE1E;;;;;;CAMC,GACD,OAAO,IAAI,QAAQ,CACjB,KACA,MACA,MAAc,KAAK,GAAG,EAAE;EAExB,IAAI,MAAM,K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AO,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC;IAChD,EAAE,OAAO,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC;GACpD;EACD,OAAO,GAAG,KAAK,EAAE,EAAE,MAAM,MAAM,CAAC,SAAS,IAAI,CAAC,QAAQ;AACxD,EAAC;AAOD,OAAO,IAAI,UAAU,CAAC,IACpB,EAAE,GAAG,IAAI,SACL,QACA,EAAE,GAAG,IAAI,gBAAgB,EAAE,SAAS,GACpC,iBACA,EAAE,OAAO,IAAI,WACb,YACA,QAAO"}
package/whereabouts.ts ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Where a person is available right now, channel by channel: the Operator's
3
+ * page open and focused, open in a background tab, an app's page open,
4
+ * Discord's status, and when they last texted or emailed. Each is a
5
+ * `whereabouts` row a host writes when the channel says something new
6
+ * ({@link noted}), and each fades on its own once the channel has gone quiet
7
+ * longer than its {@link FADE}, so a dropped socket or a lost close never
8
+ * leaves someone "here" for good.
9
+ *
10
+ * Pure: a host reads the rows, applies what {@link noted} returns, and reads
11
+ * {@link glance} to say it ({@link whereaboutsLine}) or to choose where to reach
12
+ * the person ({@link reachBy}).
13
+ *
14
+ * ```ts
15
+ * import { glance, noted, whereaboutsLine, reachBy } from '@yaks/notify/whereabouts'
16
+ * import { equal } from '@yaks/testing'
17
+ *
18
+ * let now = Date.parse('2026-11-20T12:00:00Z')
19
+ * let tab = noted(undefined, { person: 'jeff', channel: 'operator', place: 'home', state: 'here' }, now)!
20
+ * let discord = noted(undefined, { person: 'jeff', channel: 'discord', state: 'online' }, now)!
21
+ * let seen = glance([tab, discord], { place: 'home', now })
22
+ * equal(whereaboutsLine('Jeff', seen), 'Jeff: here, this tab · Discord online')
23
+ * equal(reachBy(seen), 'tab')
24
+ * // The same state said again soon after writes nothing.
25
+ * equal(noted(tab, { person: 'jeff', channel: 'operator', place: 'home', state: 'here' }, now + 1000), undefined)
26
+ * ```
27
+ */
28
+
29
+ import { derivedEid } from '@yaks/graph/identity'
30
+
31
+ export type Channel = 'operator' | 'apps' | 'discord' | 'text' | 'email'
32
+ export type State =
33
+ | 'here'
34
+ | 'background'
35
+ | 'away'
36
+ | 'open'
37
+ | 'online'
38
+ | 'idle'
39
+ | 'dnd'
40
+ | 'offline'
41
+ | 'used'
42
+
43
+ /** What a channel said of a person: `place` is which Operator (its space)
44
+ * or which app, for the channels a person can have several of. */
45
+ export type Said = {
46
+ person: string
47
+ channel: Channel
48
+ place?: string
49
+ state: State
50
+ }
51
+
52
+ /** A `whereabouts` row as a host reads it. */
53
+ export type Row = {
54
+ entity: { eid: string }
55
+ whereabouts?: Partial<Said> & { at?: string; live?: boolean }
56
+ }
57
+
58
+ let MINUTE = 60_000
59
+ let HOUR = 60 * MINUTE
60
+
61
+ /** How long a channel's last word stands. A page says its state again while
62
+ * it is open ({@link BEAT}), so a page whose close was lost fades in minutes;
63
+ * Discord says a change only when there is one, and resends every status
64
+ * when its bot reconnects; a text or an email is a moment, said as "texted
65
+ * 2h ago" for a day. */
66
+ export let FADE: Record<Channel, number> = {
67
+ operator: 15 * MINUTE,
68
+ apps: 15 * MINUTE,
69
+ discord: 12 * HOUR,
70
+ text: 24 * HOUR,
71
+ email: 24 * HOUR,
72
+ }
73
+
74
+ /** How often an open page says its state again. */
75
+ export let BEAT: number = 5 * MINUTE
76
+
77
+ // A state that says the person is not there: never worth a new row.
78
+ let gone = (s?: string) => s == 'away' || s == 'offline'
79
+
80
+ /** The row a person's whereabouts on `channel` (at `place`) is kept in. */
81
+ export let whereaboutsEid = (
82
+ person: string,
83
+ channel: Channel,
84
+ place?: string,
85
+ ): string => derivedEid(`whereabouts|${person}|${channel}|${place ?? ''}`)
86
+
87
+ /**
88
+ * The write `said` needs, given the row it replaces: none when the state is
89
+ * unchanged and its row is still fresh (younger than a third of its fade),
90
+ * so a page saying "still here" every {@link BEAT} writes about once in
91
+ * three, and Discord's many identical updates write once. A person never
92
+ * seen there who is said to be away writes nothing.
93
+ */
94
+ export let noted = (
95
+ row: Row | undefined,
96
+ said: Said,
97
+ now: number = Date.now(),
98
+ ): Row | undefined => {
99
+ let was = row?.whereabouts
100
+ let age = now - Date.parse(was?.at ?? '')
101
+ if (!was?.state && gone(said.state)) return
102
+ if (was?.state == said.state && age < FADE[said.channel] / 3) return
103
+ if (gone(said.state) && (gone(was?.state) || !(age < FADE[said.channel]))) {
104
+ return
105
+ }
106
+ return {
107
+ entity: { eid: whereaboutsEid(said.person, said.channel, said.place) },
108
+ whereabouts: {
109
+ person: said.person,
110
+ channel: said.channel,
111
+ ...said.place ? { place: said.place } : {},
112
+ state: said.state,
113
+ at: new Date(now).toISOString(),
114
+ },
115
+ }
116
+ }
117
+
118
+ /** What a tab reports on its socket. Older clients omit the input signal. */
119
+ export type Tab = { visible: boolean; focused: boolean; idle?: boolean }
120
+
121
+ /** The tab a socket's frame says, none for any other frame. */
122
+ export let tabSaid = (frame: unknown): Tab | undefined => {
123
+ let tab = (frame as { tab?: unknown } | null)?.tab
124
+ if (!tab || typeof tab != 'object') return
125
+ let { visible, focused, idle } = tab as Record<string, unknown>
126
+ return {
127
+ visible: visible === true,
128
+ focused: focused === true,
129
+ ...typeof idle == 'boolean' ? { idle } : {},
130
+ }
131
+ }
132
+
133
+ /** The state of a page across a person's tabs on it: `here`
134
+ * when one is visible and focused, `background` when one is open, `away`
135
+ * when none is. */
136
+ export let tabsState = (tabs: Tab[]): State =>
137
+ tabs.some((t) => t.visible && t.focused)
138
+ ? 'here'
139
+ : tabs.length
140
+ ? 'background'
141
+ : 'away'
142
+
143
+ /** The activity visible to friends across the person's open page tabs. */
144
+ export type Activity = 'active' | 'away' | 'offline'
145
+
146
+ export let tabActivity = (tabs: Tab[]): Activity =>
147
+ tabs.some((t) => t.visible && t.focused && t.idle === false)
148
+ ? 'active'
149
+ : tabs.length
150
+ ? 'away'
151
+ : 'offline'
152
+
153
+ /** The durable timestamp of when a person's first page opened or last page closed. */
154
+ export let pageWord = (person: string, state: State, now: number): Row => ({
155
+ entity: { eid: whereaboutsEid(person, 'apps') },
156
+ whereabouts: {
157
+ person,
158
+ channel: 'apps',
159
+ state,
160
+ at: new Date(now).toISOString(),
161
+ },
162
+ })
163
+
164
+ /** Read the unplaced page's history with the tabs that are still connected.
165
+ * A disconnected page's timestamp still stands, even when its close was lost. */
166
+ export let pageWhereabouts = (
167
+ history: Row[],
168
+ person: string,
169
+ tabs: Tab[],
170
+ now: number,
171
+ ): Row[] => {
172
+ let eid = whereaboutsEid(person, 'apps')
173
+ let past = history.find((row) => row.entity.eid == eid)
174
+ if (!past && !tabs.length) return history
175
+ let activity = tabActivity(tabs)
176
+ let state: State = activity == 'active'
177
+ ? 'here'
178
+ : activity == 'away'
179
+ ? 'background'
180
+ : 'away'
181
+ let page = past ?? pageWord(person, state, now)
182
+ return [
183
+ ...history.filter((row) => row.entity.eid != eid),
184
+ {
185
+ ...page,
186
+ whereabouts: { ...page.whereabouts, state, live: !!tabs.length },
187
+ },
188
+ ]
189
+ }
190
+
191
+ /** Activity as seen in the computed unplaced page row. */
192
+ export let pageActivity = (rows: Row[]): Activity => {
193
+ let page = rows.find(({ whereabouts: p }) =>
194
+ p?.live && p.channel == 'apps' && !p.place
195
+ )
196
+ return page
197
+ ? page.whereabouts?.state == 'here' ? 'active' : 'away'
198
+ : 'offline'
199
+ }
200
+
201
+ /** Whether a channel's last word still stands. A live page follows its socket. */
202
+ export let fresh = (p: NonNullable<Row['whereabouts']>, now: number): boolean =>
203
+ !!p.live || now - Date.parse(p.at ?? '') < (FADE[p.channel as Channel] ?? 0)
204
+
205
+ /** Where a person is, at a glance, as one Operator (of `place`) sees it. */
206
+ export type Glance = {
207
+ /** this Operator's page: focused, or open in a background tab */
208
+ tab?: 'here' | 'background'
209
+ /** another Operator's page or an app's page is open */
210
+ elsewhere?: boolean
211
+ discord?: 'online' | 'idle' | 'dnd' | 'offline'
212
+ /** when they last texted, or emailed, within a day */
213
+ texted?: string
214
+ emailed?: string
215
+ now: number
216
+ }
217
+
218
+ /** The rows still standing, read as one Operator's glance: `place` is its
219
+ * space. */
220
+ export let glance = (
221
+ rows: Row[],
222
+ { place, now = Date.now() }: { place?: string; now?: number },
223
+ ): Glance => {
224
+ let seen: Glance = { now }
225
+ for (let { whereabouts: p } of rows) {
226
+ if (!p?.channel || !p.state || !p.at) continue
227
+ let channel = p.channel as Channel
228
+ if (!fresh(p, now)) continue
229
+ if (channel == 'operator' && p.place == place) {
230
+ if (p.state == 'here' || p.state == 'background') {
231
+ seen.tab = seen.tab == 'here' ? 'here' : p.state
232
+ }
233
+ } else if (channel == 'operator' || channel == 'apps') {
234
+ if (!gone(p.state)) seen.elsewhere = true
235
+ } else if (channel == 'discord') {
236
+ seen.discord = p.state as Glance['discord']
237
+ } else if (channel == 'text') seen.texted = latest(seen.texted, p.at)
238
+ else if (channel == 'email') seen.emailed = latest(seen.emailed, p.at)
239
+ }
240
+ return seen
241
+ }
242
+
243
+ /** Where a person is on yaks.app now, as their friends see it: `building`
244
+ * while an Operator's page of theirs is open, else `online` while an app's
245
+ * page or another yaks.app page is; `spaces` and `apps` are the places those
246
+ * pages name, the Operator's space and the app. */
247
+ export type Presence = {
248
+ state: 'building' | 'online'
249
+ spaces: string[]
250
+ apps: string[]
251
+ }
252
+
253
+ /** The presence the rows still standing say, none when no page of the
254
+ * person's is open. Never stored: it is read off the rows each time. */
255
+ export let presence = (
256
+ rows: Row[],
257
+ now: number = Date.now(),
258
+ ): Presence | undefined => {
259
+ let spaces = new Set<string>(), apps = new Set<string>()
260
+ let open = false
261
+ for (let { whereabouts: p } of rows) {
262
+ let channel = p?.channel
263
+ if (channel != 'operator' && channel != 'apps') continue
264
+ if (!p?.state || gone(p.state) || !p.at) continue
265
+ if (!fresh(p, now)) continue
266
+ open = true
267
+ if (p.place) (channel == 'operator' ? spaces : apps).add(p.place)
268
+ }
269
+ if (!open) return
270
+ return {
271
+ state: spaces.size ? 'building' : 'online',
272
+ spaces: [...spaces],
273
+ apps: [...apps],
274
+ }
275
+ }
276
+
277
+ /** When a person was last active on yaks.app: the newest word any page of
278
+ * theirs, or a text or an email to their Operator, said of them, faded or
279
+ * not. Discord's status is not something they did here. None for someone
280
+ * never seen. */
281
+ export let lastSeen = (rows: Row[]): string | undefined => {
282
+ let last: string | undefined
283
+ for (let { whereabouts: p } of rows) {
284
+ if (p?.at && p.channel && p.channel != 'discord') last = latest(last, p.at)
285
+ }
286
+ return last
287
+ }
288
+
289
+ let latest = (a: string | undefined, b: string) => !a || b > a ? b : a
290
+
291
+ /** How long ago `at` was, as a person says it: 4m, 2h, 1d. */
292
+ export let ago = (at: string, now: number): string => {
293
+ let ms = Math.max(0, now - Date.parse(at))
294
+ return ms < HOUR
295
+ ? `${Math.max(1, Math.round(ms / MINUTE))}m`
296
+ : ms < 24 * HOUR
297
+ ? `${Math.round(ms / HOUR)}h`
298
+ : `${Math.round(ms / (24 * HOUR))}d`
299
+ }
300
+
301
+ let DISCORD: Record<string, string> = {
302
+ online: 'Discord online',
303
+ idle: 'Discord idle',
304
+ dnd: 'Discord do not disturb',
305
+ offline: 'Discord offline',
306
+ }
307
+
308
+ /** The glance in one short line, for each of an Operator's turns:
309
+ * "Jeff: here, this tab · Discord online". */
310
+ export let whereaboutsLine = (name: string, g: Glance): string => {
311
+ let parts = [
312
+ g.tab == 'here'
313
+ ? 'here, this tab'
314
+ : g.tab == 'background'
315
+ ? 'this Operator open in a background tab'
316
+ : g.elsewhere
317
+ ? 'on yaks.app, not on this Operator'
318
+ : 'not on yaks.app',
319
+ g.discord && DISCORD[g.discord],
320
+ g.texted && `texted ${ago(g.texted, g.now)} ago`,
321
+ g.emailed && `emailed ${ago(g.emailed, g.now)} ago`,
322
+ ]
323
+ return `${name}: ${parts.filter(Boolean).join(' · ')}`
324
+ }
325
+
326
+ /** Where something that needs the person reaches them now: in the tab they
327
+ * are looking at, a notification when that tab is in the background or they
328
+ * are elsewhere on yaks.app, Discord when they are on it and not on
329
+ * yaks.app, and otherwise their usual channel. */
330
+ export type Reach = 'tab' | 'notification' | 'discord' | 'usual'
331
+ export let reachBy = (g: Glance): Reach =>
332
+ g.tab == 'here'
333
+ ? 'tab'
334
+ : g.tab == 'background' || g.elsewhere
335
+ ? 'notification'
336
+ : g.discord == 'online'
337
+ ? 'discord'
338
+ : 'usual'