terminalchat-cli 0.0.0-stage → 0.1.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/src/store.js ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * src/store.js — atomic JSON persistence for ~/.terminalchat/
3
+ *
4
+ * All writes go to a temp file first, then rename() so readers never see
5
+ * a partial write. History files are append-only (.jsonl) and don't use
6
+ * the atomic rename path.
7
+ *
8
+ * createStore(baseDir) returns a per-instance store bound to baseDir so
9
+ * multiple engines in the same process never step on each other's data.
10
+ * The module-level convenience exports (identity/friends/…) still read
11
+ * from TCHAT_DATA_DIR for the default single-engine case.
12
+ */
13
+ import {
14
+ readFileSync, writeFileSync, mkdirSync, renameSync,
15
+ existsSync, chmodSync, appendFileSync, createReadStream,
16
+ } from 'node:fs'
17
+ import { resolve, dirname } from 'node:path'
18
+ import { homedir } from 'node:os'
19
+ import { randomBytes } from 'node:crypto'
20
+ import { createInterface } from 'node:readline'
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Low-level helpers (take an explicit baseDir)
24
+ // ---------------------------------------------------------------------------
25
+
26
+ function _resolve (baseDir, sub) {
27
+ return sub ? resolve(baseDir, sub) : baseDir
28
+ }
29
+
30
+ function _ensure (baseDir) {
31
+ mkdirSync(_resolve(baseDir, ''), { recursive: true })
32
+ mkdirSync(_resolve(baseDir, 'history'), { recursive: true })
33
+ }
34
+
35
+ function _readJSON (baseDir, relPath, defaultValue = null) {
36
+ const full = _resolve(baseDir, relPath)
37
+ if (!existsSync(full)) return defaultValue
38
+ return JSON.parse(readFileSync(full, 'utf8'))
39
+ }
40
+
41
+ function _writeJSON (baseDir, relPath, data, mode = null) {
42
+ const full = _resolve(baseDir, relPath)
43
+ mkdirSync(dirname(full), { recursive: true })
44
+ const tmp = `${full}.${randomBytes(4).toString('hex')}.tmp`
45
+ writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
46
+ if (mode !== null) chmodSync(tmp, mode)
47
+ renameSync(tmp, full)
48
+ }
49
+
50
+ function _appendHistory (baseDir, friendKeyHex, entry) {
51
+ const full = _resolve(baseDir, `history/${friendKeyHex}.jsonl`)
52
+ mkdirSync(dirname(full), { recursive: true })
53
+ appendFileSync(full, JSON.stringify(entry) + '\n', 'utf8')
54
+ }
55
+
56
+ async function _readHistory (baseDir, friendKeyHex, n = 50) {
57
+ const full = _resolve(baseDir, `history/${friendKeyHex}.jsonl`)
58
+ if (!existsSync(full)) return []
59
+ const lines = []
60
+ const rl = createInterface({ input: createReadStream(full, 'utf8'), crlfDelay: Infinity })
61
+ for await (const line of rl) {
62
+ if (!line.trim()) continue
63
+ try { lines.push(JSON.parse(line)) } catch { /* skip corrupt */ }
64
+ if (lines.length > n) lines.shift()
65
+ }
66
+ return lines
67
+ }
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // createStore — per-instance factory (use this in Engine)
71
+ // ---------------------------------------------------------------------------
72
+
73
+ /**
74
+ * Returns a store object bound to `baseDir`. Each Engine should create its
75
+ * own store so concurrent engines in the same process don't interfere.
76
+ */
77
+ export function createStore (baseDir) {
78
+ return {
79
+ baseDir,
80
+ ensure: () => _ensure(baseDir),
81
+ readJSON: (p, def) => _readJSON(baseDir, p, def),
82
+ writeJSON: (p, d, m) => _writeJSON(baseDir, p, d, m),
83
+ appendHistory: (k, e) => _appendHistory(baseDir, k, e),
84
+ readHistory: (k, n) => _readHistory(baseDir, k, n),
85
+
86
+ identity: {
87
+ load: () => _readJSON(baseDir, 'identity.json', null),
88
+ save: (kp) => _writeJSON(baseDir, 'identity.json', kp, 0o600),
89
+ },
90
+ friends: {
91
+ load: () => _readJSON(baseDir, 'friends.json', {}),
92
+ save: (d) => _writeJSON(baseDir, 'friends.json', d),
93
+ },
94
+ invites: {
95
+ load: () => _readJSON(baseDir, 'invites.json', {}),
96
+ save: (d) => _writeJSON(baseDir, 'invites.json', d),
97
+ },
98
+ outbox: {
99
+ load: () => _readJSON(baseDir, 'outbox.json', {}),
100
+ save: (d) => _writeJSON(baseDir, 'outbox.json', d),
101
+ },
102
+ state: {
103
+ load: () => _readJSON(baseDir, 'state.json', { nextSeq: {}, ackedUpTo: {} }),
104
+ save: (d) => _writeJSON(baseDir, 'state.json', d),
105
+ },
106
+ }
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // Default base directory (falls back to TCHAT_DATA_DIR or ~/.terminalchat)
111
+ // ---------------------------------------------------------------------------
112
+
113
+ function defaultBase () {
114
+ return process.env.TCHAT_DATA_DIR ?? resolve(homedir(), '.terminalchat')
115
+ }
116
+
117
+ // ---------------------------------------------------------------------------
118
+ // Module-level convenience exports (use TCHAT_DATA_DIR, single-engine default)
119
+ // ---------------------------------------------------------------------------
120
+
121
+ export function dataDir (sub = '') {
122
+ return _resolve(defaultBase(), sub)
123
+ }
124
+
125
+ export function ensureDataDir () {
126
+ _ensure(defaultBase())
127
+ }
128
+
129
+ export function readJSON (relPath, defaultValue = null) {
130
+ return _readJSON(defaultBase(), relPath, defaultValue)
131
+ }
132
+
133
+ export function writeJSON (relPath, data, mode = null) {
134
+ _writeJSON(defaultBase(), relPath, data, mode)
135
+ }
136
+
137
+ export function appendHistory (friendKeyHex, entry) {
138
+ _appendHistory(defaultBase(), friendKeyHex, entry)
139
+ }
140
+
141
+ export async function readHistory (friendKeyHex, n = 50) {
142
+ return _readHistory(defaultBase(), friendKeyHex, n)
143
+ }
144
+
145
+ export const identity = {
146
+ load: () => readJSON('identity.json', null),
147
+ save: (kp) => writeJSON('identity.json', kp, 0o600),
148
+ }
149
+
150
+ export const friends = {
151
+ load: () => readJSON('friends.json', {}),
152
+ save: (data) => writeJSON('friends.json', data),
153
+ }
154
+
155
+ export const invites = {
156
+ load: () => readJSON('invites.json', {}),
157
+ save: (data) => writeJSON('invites.json', data),
158
+ }
159
+
160
+ export const outbox = {
161
+ load: () => readJSON('outbox.json', {}),
162
+ save: (data) => writeJSON('outbox.json', data),
163
+ }
164
+
165
+ export const state = {
166
+ load: () => readJSON('state.json', { nextSeq: {}, ackedUpTo: {} }),
167
+ save: (data) => writeJSON('state.json', data),
168
+ }
package/src/ui/App.js ADDED
@@ -0,0 +1,82 @@
1
+ import React, { useMemo, useState } from 'react'
2
+ import { Box, Text, useInput, useApp } from 'ink'
3
+ import { Engine } from '../engine.js'
4
+ import { useEngine } from './useEngine.js'
5
+ import { Sidebar } from './Sidebar.js'
6
+ import { ChatPane } from './ChatPane.js'
7
+ import { Actions, AddFriendOverlay, HistoryOverlay, InviteOverlay, JoinOverlay, WhoamiOverlay } from './Overlays.js'
8
+
9
+ const h = React.createElement
10
+
11
+ export default function App ({ engine: providedEngine } = {}) {
12
+ const { exit } = useApp()
13
+ const engine = useMemo(() => providedEngine ?? new Engine(), [providedEngine])
14
+ const state = useEngine(engine)
15
+ const [focus, setFocus] = useState('input')
16
+ const [input, setInput] = useState('')
17
+ const [overlay, setOverlay] = useState(null)
18
+ const [selection, setSelection] = useState(0)
19
+ const selectedKey = state.selectedKey ?? state.friends[selection]?.keyHex
20
+ const friend = state.friends.find(item => item.keyHex === selectedKey)
21
+
22
+ useInput((value, key) => {
23
+ if (key.ctrl && value === 'c') {
24
+ engine.shutdown().finally(exit)
25
+ return
26
+ }
27
+ if (key.escape) { setOverlay(null); return }
28
+ if (overlay) {
29
+ if (overlay === 'actions' && /^[1-5]$/.test(value)) {
30
+ setOverlay(['invite', 'add', 'join', 'whoami', 'history'][Number(value) - 1])
31
+ }
32
+ return
33
+ }
34
+ if (key.tab) { setFocus(previous => previous === 'sidebar' ? 'input' : 'sidebar'); return }
35
+ if (focus === 'sidebar' && (key.upArrow || key.downArrow)) {
36
+ const next = Math.max(0, Math.min(state.friends.length - 1, selection + (key.downArrow ? 1 : -1)))
37
+ setSelection(next)
38
+ state.selectFriend(state.friends[next]?.keyHex)
39
+ }
40
+ if (key.ctrl && value === 'n') setOverlay('actions')
41
+ })
42
+
43
+ const send = body => {
44
+ if (friend && body.trim()) {
45
+ try { engine.sendMessage(friend.keyHex, body) } catch (error) { engine.emit('error', error) }
46
+ setInput('')
47
+ }
48
+ }
49
+
50
+ if (!state.ready) return h(Box, { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' },
51
+ h(Text, { bold: true, color: 'cyan' }, '◉ TERMINALCHAT'),
52
+ h(Text, { dimColor: true }, 'Connecting securely…'),
53
+ state.error && h(Text, { color: 'red' }, state.error.message)
54
+ )
55
+
56
+ let modal = null
57
+ if (overlay === 'actions') modal = h(Actions, { onChoose: item => {
58
+ const next = { Invite: 'invite', 'Add friend': 'add', Join: 'join', 'Who am I': 'whoami', History: 'history' }[item]
59
+ setOverlay(next)
60
+ } })
61
+ if (overlay === 'invite') modal = h(InviteOverlay, { engine })
62
+ if (overlay === 'add') modal = h(AddFriendOverlay, { engine, onDone: () => setOverlay(null), onError: error => { engine.emit('error', error); setOverlay(null) } })
63
+ if (overlay === 'join') modal = h(JoinOverlay, { engine, onJoined: () => setOverlay(null), onError: error => { engine.emit('error', error); setOverlay(null) } })
64
+ if (overlay === 'whoami') modal = h(WhoamiOverlay, { engine })
65
+ if (overlay === 'history' && friend) modal = h(HistoryOverlay, { engine, friendKey: friend.keyHex })
66
+
67
+ const identity = engine.whoami()
68
+ return h(Box, { flexDirection: 'column', height: '100%' },
69
+ h(Box, { justifyContent: 'space-between', borderStyle: 'single', borderColor: 'cyan', paddingX: 1 },
70
+ h(Text, { bold: true, color: 'cyan' }, '◉ TERMINALCHAT'),
71
+ h(Text, { dimColor: true }, `${identity.name} · ${identity.publicKey.slice(0, 12)}…`)
72
+ ),
73
+ h(Box, { flexGrow: 1, marginTop: 0 },
74
+ h(Sidebar, { friends: state.friends, selectedKey, unread: state.unread, onSelect: state.selectFriend, focused: focus === 'sidebar' }),
75
+ h(ChatPane, { friend, messages: state.messages[selectedKey], input, setInput, onSubmit: send, focused: focus === 'input' })
76
+ ),
77
+ h(Box, { borderStyle: 'single', borderColor: state.error ? 'red' : 'gray', paddingX: 1 },
78
+ h(Text, { color: state.error ? 'red' : undefined, dimColor: !state.error }, state.error ? `⚠ ${state.error.message}` : 'Ctrl+N Actions · Tab Focus · Esc Close · Ctrl+C Quit')
79
+ ),
80
+ modal
81
+ )
82
+ }
@@ -0,0 +1,48 @@
1
+ import React from 'react'
2
+ import { Box, Text } from 'ink'
3
+ import TextInput from 'ink-text-input'
4
+
5
+ const h = React.createElement
6
+
7
+ export function ChatPane ({ friend, messages, input, setInput, onSubmit, focused }) {
8
+ const displayedMessages = messages ?? []
9
+
10
+ return h(Box, { flexDirection: 'column', flexGrow: 1, paddingLeft: 1, paddingRight: 1 },
11
+ h(Box, { justifyContent: 'space-between', borderStyle: 'round', borderColor: friend ? 'cyan' : 'gray', paddingX: 1 },
12
+ h(Text, { bold: true, color: friend ? 'cyan' : 'gray' }, friend ? friend.name : 'NO CONVERSATION'),
13
+ friend ? h(Text, { color: friend.online ? 'green' : 'gray' }, friend.online ? '● online' : '○ offline') : null
14
+ ),
15
+ h(Box, { flexDirection: 'column', flexGrow: 1, marginTop: 1, marginBottom: 1 },
16
+ !friend
17
+ ? h(Box, { flexGrow: 1, alignItems: 'center', justifyContent: 'center' },
18
+ h(Box, { flexDirection: 'column', alignItems: 'center' },
19
+ h(Text, { bold: true, color: 'cyan' }, 'TerminalChat'),
20
+ h(Text, { dimColor: true }, 'Press Ctrl+N to invite or join')
21
+ )
22
+ )
23
+ : displayedMessages.length === 0
24
+ ? h(Box, { flexGrow: 1, alignItems: 'center', justifyContent: 'center' },
25
+ h(Text, { dimColor: true }, 'No messages yet. Say hello.')
26
+ )
27
+ : displayedMessages.map((message, index) => {
28
+ const outgoing = message.direction === 'out'
29
+ const time = new Date(message.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
30
+ return h(Box, { key: `${message.sender}-${message.seq}-${index}`, justifyContent: outgoing ? 'flex-end' : 'flex-start', marginBottom: 0 },
31
+ h(Box, { flexDirection: 'column', alignItems: outgoing ? 'flex-end' : 'flex-start', maxWidth: 58 },
32
+ h(Text, { color: outgoing ? 'cyan' : 'green', bold: outgoing }, outgoing ? 'YOU' : (friend.name || 'PEER')),
33
+ h(Box, { borderStyle: 'round', borderColor: outgoing ? 'cyan' : 'green', paddingX: 1 },
34
+ h(Text, { wrap: 'wrap' }, message.body)
35
+ ),
36
+ h(Text, { dimColor: true }, `${time}${outgoing ? (message.delivered ? ' ✓ delivered' : ' … pending') : ''}`)
37
+ )
38
+ )
39
+ })
40
+ ),
41
+ friend
42
+ ? h(Box, { borderStyle: 'double', borderColor: focused ? 'cyan' : 'gray', paddingX: 1, height: 3 },
43
+ h(Text, { color: focused ? 'cyan' : 'gray', bold: true }, '› '),
44
+ h(TextInput, { value: input, onChange: setInput, onSubmit, focus: focused, placeholder: 'Write a message…' })
45
+ )
46
+ : h(Box, { borderStyle: 'round', borderColor: 'gray', paddingX: 1 }, h(Text, { dimColor: true }, 'Select or add a friend to chat'))
47
+ )
48
+ }
@@ -0,0 +1,92 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import { Box, Text, useInput } from 'ink'
3
+ import TextInput from 'ink-text-input'
4
+
5
+ const h = React.createElement
6
+
7
+ function Overlay ({ title, children }) {
8
+ return h(Box, { position: 'absolute', width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' },
9
+ h(Box, { flexDirection: 'column', borderStyle: 'double', borderColor: 'cyan', paddingX: 2, paddingY: 1, width: 60 },
10
+ h(Text, { bold: true, color: 'cyan' }, title), children
11
+ )
12
+ )
13
+ }
14
+
15
+ export function Actions ({ onChoose }) {
16
+ const items = ['Invite', 'Add friend', 'Join', 'Who am I', 'History']
17
+ const [selected, setSelected] = useState(0)
18
+
19
+ useInput((value, key) => {
20
+ if (key.upArrow) setSelected(previous => (previous + items.length - 1) % items.length)
21
+ if (key.downArrow) setSelected(previous => (previous + 1) % items.length)
22
+ if (key.return) onChoose(items[selected])
23
+ if (/^[1-5]$/.test(value)) onChoose(items[Number(value) - 1])
24
+ })
25
+
26
+ return h(Overlay, { title: 'Actions' },
27
+ ...items.map((item, index) => h(Text, {
28
+ key: item,
29
+ bold: index === selected,
30
+ color: index === selected ? 'cyan' : undefined,
31
+ backgroundColor: index === selected ? 'blue' : undefined,
32
+ }, `${index + 1}. ${index === selected ? '›' : ' '} ${item}`)),
33
+ h(Text, { dimColor: true }, '↑/↓ select · Enter open · Esc close')
34
+ )
35
+ }
36
+
37
+ export function InviteOverlay ({ engine }) {
38
+ return h(Overlay, { title: 'Invite' },
39
+ h(Text, null, engine.createInvite()),
40
+ h(Text, { dimColor: true }, 'Share this code · Esc closes')
41
+ )
42
+ }
43
+
44
+ export function WhoamiOverlay ({ engine }) {
45
+ const identity = engine.whoami()
46
+ return h(Overlay, { title: 'Who am I?' },
47
+ h(Text, null, identity.name),
48
+ h(Text, { wrap: 'wrap' }, identity.publicKey),
49
+ h(Text, { dimColor: true }, 'Esc closes')
50
+ )
51
+ }
52
+
53
+ export function AddFriendOverlay ({ engine, onDone, onError }) {
54
+ const [name, setName] = useState('')
55
+ const [key, setKey] = useState('')
56
+ const [editingKey, setEditingKey] = useState(false)
57
+
58
+ return h(Overlay, { title: 'Add friend' },
59
+ h(Text, { color: 'cyan' }, editingKey ? 'Public key (64 hex characters)' : 'Display name'),
60
+ !editingKey
61
+ ? h(TextInput, { value: name, onChange: setName, focus: true, onSubmit: () => setEditingKey(true) })
62
+ : h(TextInput, { value: key, onChange: setKey, focus: true, onSubmit: () => {
63
+ try {
64
+ if (!name.trim()) throw new Error('Enter a display name')
65
+ if (!/^[0-9a-fA-F]{64}$/.test(key.trim())) throw new Error('Public key must be 64 hex characters')
66
+ engine.addFriend(name.trim(), key.trim().toLowerCase())
67
+ onDone()
68
+ } catch (error) { onError?.(error) }
69
+ } }),
70
+ h(Text, { dimColor: true }, editingKey ? 'Enter adds friend · Esc closes' : 'Enter continues · Esc closes')
71
+ )
72
+ }
73
+
74
+ export function JoinOverlay ({ engine, onJoined, onError }) {
75
+ const [code, setCode] = useState('')
76
+ return h(Overlay, { title: 'Join' },
77
+ h(Text, null, 'Invite code'),
78
+ h(TextInput, { value: code, onChange: setCode, focus: true, onSubmit: async () => {
79
+ try { await engine.join(code); onJoined() } catch (error) { onError(error) }
80
+ } }),
81
+ h(Text, { dimColor: true }, 'Enter submits · Esc closes')
82
+ )
83
+ }
84
+
85
+ export function HistoryOverlay ({ engine, friendKey }) {
86
+ const [messages, setMessages] = useState(null)
87
+ useEffect(() => { engine.getHistory(friendKey, 20).then(setMessages) }, [engine, friendKey])
88
+ return h(Overlay, { title: 'History' },
89
+ ...(messages ?? [ { body: 'Loading…' } ]).map((message, index) => h(Text, { key: index }, message.body)),
90
+ h(Text, { dimColor: true }, 'Esc closes')
91
+ )
92
+ }
@@ -0,0 +1,33 @@
1
+ import React from 'react'
2
+ import { Box, Text } from 'ink'
3
+
4
+ const h = React.createElement
5
+
6
+ export function Sidebar ({ friends, selectedKey, unread, onSelect, focused }) {
7
+ const onlineCount = friends.filter(friend => friend.online).length
8
+
9
+ return h(Box, { flexDirection: 'column', width: 30, borderStyle: 'round', borderColor: focused ? 'cyan' : 'gray', paddingX: 1 },
10
+ h(Box, { justifyContent: 'space-between' },
11
+ h(Text, { bold: true, color: 'cyan' }, 'CONVERSATIONS'),
12
+ h(Text, { dimColor: true }, `${onlineCount}/${friends.length}`)
13
+ ),
14
+ h(Box, { marginTop: 1, marginBottom: 1 }, h(Text, { dimColor: true }, friends.length ? 'Use ↑/↓ to move' : 'No contacts connected')),
15
+ friends.length === 0
16
+ ? h(Box, { flexDirection: 'column', marginTop: 1 },
17
+ h(Text, { color: 'yellow' }, 'Start a conversation'),
18
+ h(Text, { dimColor: true }, 'Ctrl+N → Join or Invite')
19
+ )
20
+ : friends.map(friend => {
21
+ const selected = friend.keyHex === selectedKey
22
+ const unreadCount = unread[friend.keyHex] ?? 0
23
+ return h(Box, { key: friend.keyHex, paddingX: selected ? 0 : 1 },
24
+ h(Text, {
25
+ bold: selected,
26
+ color: selected ? 'black' : friend.online ? 'green' : 'gray',
27
+ backgroundColor: selected ? 'cyan' : undefined,
28
+ }, `${selected ? '› ' : ' '}${friend.online ? '●' : '○'} ${friend.name}${unreadCount ? ` ${unreadCount}` : ''}`)
29
+ )
30
+ }),
31
+ h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, 'Tab switch · Ctrl+N actions'))
32
+ )
33
+ }
@@ -0,0 +1,85 @@
1
+ import { useEffect, useState } from 'react'
2
+
3
+ export function useEngine (engine) {
4
+ const [snapshot, setSnapshot] = useState({
5
+ friends: [],
6
+ selectedKey: null,
7
+ messages: {},
8
+ unread: {},
9
+ online: {},
10
+ ready: false,
11
+ error: null,
12
+ })
13
+
14
+ useEffect(() => {
15
+ let active = true
16
+ const refresh = () => {
17
+ if (!active) return
18
+ setSnapshot(previous => ({
19
+ ...previous,
20
+ friends: engine.getFriends(),
21
+ online: Object.fromEntries(engine.getFriends().map(friend => [friend.keyHex, friend.online])),
22
+ }))
23
+ }
24
+
25
+ const onReady = async () => {
26
+ const friends = engine.getFriends()
27
+ const messages = {}
28
+ for (const friend of friends) messages[friend.keyHex] = await engine.getHistory(friend.keyHex)
29
+ if (active) setSnapshot(previous => ({ ...previous, friends, messages, ready: true }))
30
+ }
31
+ const onMessage = async (key, entry) => {
32
+ const history = await engine.getHistory(key)
33
+ if (!active) return
34
+ setSnapshot(previous => ({
35
+ ...previous,
36
+ messages: { ...previous.messages, [key]: history },
37
+ unread: entry.direction === 'in' && previous.selectedKey !== key
38
+ ? { ...previous.unread, [key]: (previous.unread[key] ?? 0) + 1 }
39
+ : previous.unread,
40
+ }))
41
+ }
42
+ const onFriend = () => refresh()
43
+ const onAck = async (key, seq) => {
44
+ const history = await engine.getHistory(key)
45
+ if (!active) return
46
+ setSnapshot(previous => ({
47
+ ...previous,
48
+ friends: engine.getFriends(),
49
+ messages: { ...previous.messages, [key]: history },
50
+ online: Object.fromEntries(engine.getFriends().map(friend => [friend.keyHex, friend.online])),
51
+ }))
52
+ }
53
+ const onError = error => setSnapshot(previous => ({ ...previous, error }))
54
+
55
+ engine.on('ready', onReady)
56
+ engine.on('message', onMessage)
57
+ engine.on('friend-added', onFriend)
58
+ engine.on('friend-online', onFriend)
59
+ engine.on('friend-offline', onFriend)
60
+ engine.on('ack', onAck)
61
+ engine.on('error', onError)
62
+ if (engine._started) {
63
+ onReady()
64
+ } else {
65
+ engine.start().catch(onError)
66
+ }
67
+
68
+ return () => {
69
+ active = false
70
+ for (const [event, listener] of [
71
+ ['ready', onReady], ['message', onMessage], ['friend-added', onFriend],
72
+ ['friend-online', onFriend], ['friend-offline', onFriend],
73
+ ['ack', onAck], ['error', onError],
74
+ ]) engine.off(event, listener)
75
+ }
76
+ }, [engine])
77
+
78
+ const selectFriend = key => setSnapshot(previous => ({
79
+ ...previous,
80
+ selectedKey: key,
81
+ unread: { ...previous.unread, [key]: 0 },
82
+ }))
83
+
84
+ return { ...snapshot, selectFriend }
85
+ }