@coda-console/friends 0.2.0 → 0.3.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/view/app.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  // 好友页:本机 Accord 身份与名片、接受好友邀请、好友列表。Accord 的读写(coda/accord@1)都在这里按交互发起;
2
2
  // 备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用 textContent / DOM API 渲染,不进 innerHTML。
3
- import { Bridge } from 'coda-view://lib/v1/bridge.js';
4
- import { COLORS, checked, mergeFriendRows, normalizeProfileInput, parseInvite, readProfileRecord, shortAuthor } from '../lib/friends.mjs';
3
+ import { CARD_KIND, COLORS, cardFallbackNotice, checked, mergeFriendRows, mergeProfileAndCard, normalizeProfileInput, parseInvite, readCardRecord, readProfileRecord,
4
+ shortAuthor } from '../lib/friends.mjs';
5
+ import { createMachineBridge, pickMachine, reachableMachines } from '../lib/view-machine.mjs';
5
6
 
6
7
  const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
7
- const coda = window.coda, bridge = new Bridge();
8
+ const coda = window.coda;
8
9
  const root = document.getElementById('root');
9
10
  const COLOR_NAMES = { blue: '蓝', orange: '橙', green: '绿', purple: '紫', pink: '粉', teal: '青', gray: '灰' };
10
11
  const STATUS_TEXT = { bound: '已互认', pending: '待互认', conflict: '密钥冲突' };
@@ -19,48 +20,70 @@ const h = (tag, attrs = {}, ...children) => {
19
20
  return node;
20
21
  };
21
22
 
22
- const state = { author: null, friends: [], profiles: [], notes: {}, loaded: false, problem: null, editing: null, removing: null, busy: new Set(), notice: new Map() };
23
+ const newState = () => ({ author: null, friends: [], profiles: [], cards: [], notes: {}, loaded: false, problem: null, notesProblem: null, editing: null, removing: null, busy: new Set(), notice: new Map() });
24
+ const state = newState();
25
+ let currentMachine = pickMachine(coda, coda.getState?.()?.machine);
26
+ // 读写都发往当前选中的机器;单机时不指明。多步操作在入口取一次,之后不再读 currentMachine。
27
+ const via = () => (currentMachine ? { machine: currentMachine } : undefined);
28
+ // 每次选机自增(A → B → A 也不同):旧机器的订阅回调、异步回写,凭它丢弃。
29
+ let selectionGen = 0;
23
30
 
24
31
  // ---- 备注:经模块存在本机 ----
25
32
  const pendingReplies = new Map();
26
33
  let counter = 0;
27
- bridge.on('reply', ({ rid, ok, value, error }) => {
28
- const wait = pendingReplies.get(rid);
29
- if (!wait) return;
30
- pendingReplies.delete(rid);
31
- if (ok) wait.resolve(value); else wait.reject(new Error(error));
34
+ const bridge = createMachineBridge({
35
+ coda,
36
+ getMachine: () => currentMachine,
37
+ getEpoch: () => selectionGen,
38
+ onMessage({ type, rid, ok, value, error }) {
39
+ if (type !== 'reply') return;
40
+ const wait = pendingReplies.get(rid);
41
+ if (!wait) return;
42
+ pendingReplies.delete(rid);
43
+ if (ok) wait.resolve(value); else wait.reject(new Error(error));
44
+ },
45
+ onError(error, msg) {
46
+ const wait = pendingReplies.get(msg.rid);
47
+ if (!wait) return;
48
+ pendingReplies.delete(msg.rid);
49
+ wait.reject(new Error(`发送失败:${error?.message ?? error}`));
50
+ },
32
51
  });
33
52
  function ask(type, input = {}) {
34
- const rid = `n${++counter}`;
53
+ const rid = `n${++counter}`, machine = currentMachine;
35
54
  return new Promise((resolve, reject) => {
36
55
  const timer = setTimeout(() => { pendingReplies.delete(rid); reject(new Error('模块没有回应')); }, 10_000);
37
- pendingReplies.set(rid, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
56
+ pendingReplies.set(rid, { machine, resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
38
57
  bridge.send({ type, rid, ...input });
39
58
  });
40
59
  }
41
60
 
42
61
  // ---- 读本机 Accord ----
43
62
  let reading = 0;
63
+ // profile 与 friends/card 各读各的:一种读不到或没有记录,不挡另一种。
44
64
  async function readProfiles() {
45
65
  const mine = ++reading;
46
- try {
47
- const { records } = await coda.query(LOCAL, 'records', { kind: 'profile', limit: 200 });
48
- if (mine !== reading) return;
49
- state.profiles = records;
50
- state.problem = null;
51
- if (!own.touched) loadOwn();
52
- } catch (e) { if (mine === reading) state.problem = `读不到好友名片:${e.message}`; }
66
+ const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 }, via())));
67
+ if (mine !== reading) return;
68
+ if (profiles.status === 'fulfilled') state.profiles = profiles.value?.records ?? [];
69
+ if (cards.status === 'fulfilled') state.cards = cards.value?.records ?? [];
70
+ const failed = [profiles, cards].find(read => read.status === 'rejected');
71
+ state.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
72
+ if (!own.touched) loadOwn();
53
73
  draw();
54
74
  }
55
- const own = { touched: false, name: '', emoji: '', color: 'blue' };
75
+ const blankOwn = () => ({ touched: false, name: '', emoji: '', color: 'blue', avatar: undefined });
76
+ const own = blankOwn();
77
+ const latestOwn = (records, read) => records.map(read).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
78
+ // 本机名片:与好友列表同一条合并规则(profile 写了的优先,缺的由 friends/card 补);头像随表单带着,重新发布不会把它丢掉或带回已清除的。
56
79
  function loadOwn() {
57
- const mine = state.profiles.map(readProfileRecord).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
80
+ const mine = mergeProfileAndCard(latestOwn(state.profiles, readProfileRecord), latestOwn(state.cards, readCardRecord));
58
81
  if (!mine) return;
59
- Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue' });
82
+ Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue', avatar: mine.avatarPresent ? mine.avatar : undefined });
60
83
  syncOwnForm();
61
84
  }
62
85
 
63
- let watched = false;
86
+ let watching = null;
64
87
  function onChange({ type, entry }) {
65
88
  if (type === 'DELETED' || !entry) return;
66
89
  state.author = entry.spec?.author ?? null;
@@ -70,13 +93,48 @@ function onChange({ type, entry }) {
70
93
  readProfiles();
71
94
  }
72
95
  async function start() {
73
- try { state.notes = await ask('notes.list'); } catch (e) { state.problem = `读不到本地备注:${e.message}`; }
74
- if (!watched) {
75
- watched = true;
76
- try { await coda.watch(ACCORD, onChange, { id: 'local' }); }
77
- catch (e) { watched = false; state.problem = `读不到本机的好友信息:${e.message}`; state.loaded = true; }
96
+ const gen = selectionGen, opts = via();
97
+ try { state.notes = await ask('notes.list'); state.notesProblem = null; }
98
+ catch (e) { if (gen === selectionGen) { state.notesProblem = `读不到本地备注:${e.message}`; draw(); } }
99
+ if (gen !== selectionGen) return;
100
+ if (!watching) {
101
+ let mine;
102
+ try {
103
+ mine = watching = Promise.resolve(coda.watch(ACCORD, entry => { if (gen === selectionGen) onChange(entry); }, { id: 'local' }, opts));
104
+ await mine;
105
+ } catch (e) { if (watching === mine) watching = null; if (gen === selectionGen) { state.problem = `读不到本机的好友信息:${e.message}`; state.loaded = true; } }
78
106
  }
107
+ if (gen === selectionGen) draw();
108
+ }
109
+
110
+ // ---- 多台机器提供这页时,选看哪台 ----
111
+ const machineBar = h('div', { class: 'machines' });
112
+ function drawMachines() {
113
+ const machines = reachableMachines(coda);
114
+ machineBar.hidden = machines.length < 2;
115
+ machineBar.replaceChildren(...(machines.length < 2 ? [] : machines.map(m => {
116
+ const button = h('button', { class: 'btn quiet small', type: 'button', 'aria-pressed': String(m.id === currentMachine), onclick: () => switchMachine(m.id) });
117
+ button.textContent = m.name || m.id;
118
+ return button;
119
+ })));
120
+ }
121
+ function switchMachine(id) {
122
+ if (id === currentMachine) return;
123
+ currentMachine = id;
124
+ selectionGen++;
125
+ coda.setState?.({ machine: currentMachine });
126
+ reading++;
127
+ watching?.then(w => w?.dispose?.(), () => {});
128
+ watching = null;
129
+ for (const [rid, wait] of [...pendingReplies]) { pendingReplies.delete(rid); wait.reject(new Error('已切换机器')); }
130
+ Object.assign(state, newState());
131
+ Object.assign(own, blankOwn());
132
+ syncOwnForm();
133
+ ownForm.button.disabled = false; invite.button.disabled = false;
134
+ for (const target of [ownForm.message, identity.message, invite.message]) say(target, '');
135
+ drawMachines();
79
136
  draw();
137
+ start();
80
138
  }
81
139
 
82
140
  // ---- 我的身份与名片 ----
@@ -96,26 +154,40 @@ function say(target, text, kind = 'hint') { target.className = kind; target.text
96
154
  async function publishProfile() {
97
155
  let body;
98
156
  try { body = normalizeProfileInput(own); } catch (e) { return say(ownForm.message, e.message, 'error'); }
157
+ const gen = selectionGen, opts = via(), author = state.author, live = () => gen === selectionGen;
99
158
  ownForm.button.disabled = true;
100
159
  say(ownForm.message, '正在发布…', 'progress');
101
160
  try {
102
- await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] });
103
- say(ownForm.message, '名片已发布,好友会看到它', 'ok');
104
- readProfiles();
105
- } catch (e) { say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
106
- ownForm.button.disabled = false;
161
+ try {
162
+ await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] }, opts);
163
+ if (live()) say(ownForm.message, '名片已发布,好友会看到它', 'ok');
164
+ } catch (e) {
165
+ // 绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
166
+ if (e?.code !== 'forbidden') throw e;
167
+ await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] }, opts);
168
+ // 缓存的 state.profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。已切机就不必查了。
169
+ if (live()) {
170
+ let rooted = null;
171
+ try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author, limit: 1 }, opts))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
172
+ if (live()) say(ownForm.message, cardFallbackNotice(rooted), 'ok');
173
+ }
174
+ }
175
+ if (live()) readProfiles();
176
+ } catch (e) { if (live()) say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
177
+ if (live()) ownForm.button.disabled = false;
107
178
  }
108
179
  const identity = { key: h('span', { class: 'key mono selectable' }), copy: h('button', { class: 'btn quiet small', type: 'button', onclick: copyKey }, '复制公钥'), message: h('p', { class: 'hint' }) };
109
180
  async function copyKey() {
110
181
  if (!state.author) return;
111
- try { await coda.copy(state.author); say(identity.message, '公钥已复制', 'ok'); } catch (e) { say(identity.message, `复制失败:${e.message}`, 'error'); }
182
+ const gen = selectionGen;
183
+ try { await coda.copy(state.author); if (gen === selectionGen) say(identity.message, '公钥已复制', 'ok'); } catch (e) { if (gen === selectionGen) say(identity.message, `复制失败:${e.message}`, 'error'); }
112
184
  }
113
185
 
114
186
  // ---- 添加好友 ----
115
187
  const invite = {
116
188
  paste: h('textarea', { placeholder: '粘贴邀请:JSON、coda-friend:// 链接,或多行 control=… / authKey=…', autocomplete: 'off', spellcheck: 'false', oninput: parsePaste }),
117
- control: h('input', { type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://…' }),
118
- authKey: h('input', { type: 'password', autocomplete: 'off', spellcheck: 'false', placeholder: '入网码,提交后立即清空' }),
189
+ control: h('input', { type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://…', oninput: dropHidden }),
190
+ authKey: h('input', { type: 'password', autocomplete: 'off', spellcheck: 'false', placeholder: '入网码,提交后立即清空', oninput: dropHidden }),
119
191
  linkId: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空自动生成' }),
120
192
  scope: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空用本机空间' }),
121
193
  peerNode: h('input', { type: 'text', autocomplete: 'off', placeholder: '可选' }),
@@ -123,14 +195,17 @@ const invite = {
123
195
  button: h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受邀请'),
124
196
  hidden: {},
125
197
  };
198
+ // hostname、peerPort 只随识别出的那份邀请:手改入网地址或入网码就是另一份邀请了,丢掉;改 linkId、scope、peerNode 不算。
199
+ function dropHidden() { invite.hidden = {}; }
126
200
  function parsePaste() {
201
+ invite.hidden = {};
127
202
  const text = invite.paste.value;
128
203
  if (!text.trim()) return say(invite.message, '', 'hint');
129
204
  try {
130
205
  const found = parseInvite(text);
131
206
  for (const name of ['control', 'authKey', 'scope', 'peerNode']) if (found[name]) invite[name].value = found[name];
132
207
  if (found.linkId && !/^f-[0-9a-f]{8}$/.test(found.linkId)) invite.linkId.value = found.linkId;
133
- invite.hidden.hostname = found.hostname ?? '';
208
+ invite.hidden = { hostname: found.hostname ?? '', peerPort: found.peerPort };
134
209
  say(invite.message, '已识别邀请,核对后点「接受邀请」', 'ok');
135
210
  } catch (e) { say(invite.message, e.message, 'error'); }
136
211
  }
@@ -142,50 +217,67 @@ async function submitInvite() {
142
217
  let input;
143
218
  try {
144
219
  input = checked({ control: invite.control.value, authKey: invite.authKey.value, linkId: invite.linkId.value, scope: invite.scope.value,
145
- peerNode: invite.peerNode.value, hostname: invite.hidden.hostname });
220
+ peerNode: invite.peerNode.value, hostname: invite.hidden.hostname, peerPort: invite.hidden.peerPort });
146
221
  } catch (e) {
147
222
  // 只填了粘贴区、还没有识别出来:再试着从粘贴区解析一次。
148
223
  try { input = parseInvite(invite.paste.value); } catch { return say(invite.message, e.message, 'error'); }
149
224
  }
150
225
  // 入网码是凭据:取出后立刻清空所有输入框,不写进任何存储或日志。
151
226
  clearInvite();
227
+ const gen = selectionGen, opts = via(), live = () => gen === selectionGen;
152
228
  invite.button.disabled = true;
153
229
  say(invite.message, '正在接受邀请,加入对方的通道…', 'progress');
154
230
  const peerNode = input.peerNode;
155
231
  let node;
156
232
  try {
157
- ({ node } = await coda.call(LOCAL, 'accept', input));
158
- } catch (e) { input = null; invite.button.disabled = false; return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error'); }
233
+ ({ node } = await coda.call(LOCAL, 'accept', input, opts));
234
+ } catch (e) {
235
+ input = null;
236
+ if (!live()) return;
237
+ invite.button.disabled = false;
238
+ return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error');
239
+ }
159
240
  input = null;
160
- say(invite.message, '已加入通道,正在与对方互认…', 'progress');
241
+ if (live()) say(invite.message, '已加入通道,正在与对方互认…', 'progress');
161
242
  try {
162
- await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) });
163
- say(invite.message, '好友已添加并完成互认', 'ok');
164
- } catch (e) { say(invite.message, `已加入通道,但互认暂未完成(${e.message})。可稍后在好友列表点「互认」重试`, 'error'); }
165
- invite.button.disabled = false;
243
+ await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) }, opts);
244
+ if (live()) say(invite.message, '好友已添加并完成互认', 'ok');
245
+ } catch (e) { if (live()) say(invite.message, `已加入通道,但互认暂未完成(${e.message})。可稍后在好友列表点「互认」重试`, 'error'); }
246
+ if (live()) invite.button.disabled = false;
166
247
  }
167
248
 
168
249
  // ---- 好友列表 ----
169
250
  const list = h('div');
170
251
  const countBadge = h('span', { class: 'count' });
171
- function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, notes: state.notes }); }
252
+ function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, cards: state.cards, notes: state.notes }); }
172
253
 
173
254
  async function handshake(row) {
255
+ const gen = selectionGen, opts = via();
174
256
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在互认…' }); draw();
175
- try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }); state.notice.set(row.node, { kind: 'ok', text: '互认完成' }); }
176
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `互认失败:${e.message}` }); }
177
- state.busy.delete(row.node); draw();
257
+ let notice;
258
+ try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }, opts); notice = { kind: 'ok', text: '互认完成' }; }
259
+ catch (e) { notice = { kind: 'error', text: `互认失败:${e.message}` }; }
260
+ if (gen !== selectionGen) return;
261
+ state.notice.set(row.node, notice); state.busy.delete(row.node); draw();
178
262
  }
179
263
  async function remove(row) {
264
+ const gen = selectionGen, opts = via();
180
265
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在移除…' }); draw();
181
- try { await coda.call(LOCAL, 'remove', { node: row.node }); state.notice.delete(row.node); state.removing = null; }
182
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `移除失败:${e.message}` }); }
266
+ let failure = null;
267
+ try { await coda.call(LOCAL, 'remove', { node: row.node }, opts); }
268
+ catch (e) { failure = { kind: 'error', text: `移除失败:${e.message}` }; }
269
+ if (gen !== selectionGen) return;
270
+ if (failure) state.notice.set(row.node, failure); else { state.notice.delete(row.node); state.removing = null; }
183
271
  state.busy.delete(row.node); draw();
184
272
  }
185
273
  async function saveNote(row, text) {
274
+ const gen = selectionGen;
186
275
  state.editing = null;
187
- try { state.notes = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); state.notice.delete(row.node); }
188
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `备注没存下:${e.message}` }); }
276
+ let saved, failure;
277
+ try { saved = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); }
278
+ catch (e) { failure = { kind: 'error', text: `备注没存下:${e.message}` }; }
279
+ if (gen !== selectionGen) return;
280
+ if (failure) state.notice.set(row.node, failure); else { state.notes = saved; state.notice.delete(row.node); }
189
281
  draw();
190
282
  }
191
283
 
@@ -220,8 +312,9 @@ function friendRow(row) {
220
312
 
221
313
  const problem = h('p', { class: 'error selectable' });
222
314
  function draw() {
223
- problem.textContent = state.problem ?? '';
224
- problem.hidden = !state.problem;
315
+ const problems = [state.notesProblem, state.problem].filter(Boolean).join(';');
316
+ problem.textContent = problems;
317
+ problem.hidden = !problems;
225
318
  identity.key.textContent = state.author ? `ed25519:${shortAuthor(state.author)}…` : state.loaded ? '未取得' : '读取中…';
226
319
  identity.copy.disabled = !state.author;
227
320
  const shown = rows();
@@ -231,7 +324,7 @@ function draw() {
231
324
  : h('p', { class: 'empty' }, state.loaded ? '还没有好友。在上面粘贴对方发来的邀请即可添加。' : '正在读取…'));
232
325
  }
233
326
 
234
- root.replaceChildren(h('div', { class: 'page' }, problem,
327
+ root.replaceChildren(h('div', { class: 'page' }, machineBar, problem,
235
328
  h('section', {}, h('h2', {}, '我的身份与名片'), h('div', { class: 'card' },
236
329
  h('div', { class: 'line identity' }, h('span', { class: 'secondary' }, '本机公钥'), identity.key, h('span', { class: 'spacer' }), identity.copy), identity.message,
237
330
  h('div', { class: 'fields' }, h('label', { class: 'field' }, h('span', {}, '昵称'), ownForm.name), h('label', { class: 'field' }, h('span', {}, '头像'), ownForm.emoji)),
@@ -250,6 +343,7 @@ root.replaceChildren(h('div', { class: 'page' }, problem,
250
343
  h('div', { class: 'line' }, invite.button), invite.message)),
251
344
  h('section', {}, h('h2', {}, '好友', countBadge), list)));
252
345
  syncOwnForm();
346
+ drawMachines();
253
347
  draw();
254
348
 
255
349
  function refresh() { readProfiles(); }
package/view/style.css CHANGED
@@ -34,6 +34,8 @@ input, select, textarea { width: 100%; min-width: 0; padding: 7px 9px; border-ra
34
34
  textarea { min-height: 84px; resize: vertical; }
35
35
  .btn { padding: 7px 14px; border-radius: var(--coda-radius, 8px); border: 0; font-weight: 600; background: var(--coda-accent, #0a84ff); color: #fff; }
36
36
  .btn.quiet { background: var(--coda-fill, rgba(120, 120, 128, .12)); color: var(--coda-foreground, #1d1d1f); }
37
+ .machines { display: flex; flex-wrap: wrap; gap: 8px; }
38
+ .btn.quiet[aria-pressed="true"] { background: var(--coda-accent, #0a84ff); color: #fff; }
37
39
  .btn.danger { background: color-mix(in srgb, var(--coda-red, #ff3b30) 14%, transparent); color: var(--coda-red, #ff3b30); }
38
40
  .btn.small { padding: 3px 10px; font-weight: 500; font-size: .92em; }
39
41
  details > summary { cursor: pointer; color: var(--coda-secondary, #6e6e73); }