@coda-console/friends 0.3.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.
@@ -0,0 +1,42 @@
1
+ // 页面选机器与发消息的纯逻辑:多台机器都提供这页时,页面须指明消息发往哪台。不碰 Coda 的 Node API;页面和单测都加载它。
2
+
3
+ export function reachableMachines(coda) {
4
+ const list = Array.isArray(coda?.machines) ? coda.machines : [coda?.machine];
5
+ const seen = new Set();
6
+ return list.filter(m => {
7
+ if (typeof m?.id !== 'string' || !m.id || m.unreachable || seen.has(m.id)) return false;
8
+ seen.add(m.id);
9
+ return true;
10
+ });
11
+ }
12
+
13
+ export function pickMachine(coda, savedId) {
14
+ const ids = reachableMachines(coda).map(m => m.id);
15
+ if (typeof savedId === 'string' && ids.includes(savedId)) return savedId;
16
+ const own = coda?.machine?.id;
17
+ if (ids.includes(own)) return own;
18
+ return ids[0] ?? own ?? null;
19
+ }
20
+
21
+ // 入队瞬间固定目标机器与代际(getEpoch,调用方每次选机自增);轮到它发送时选择已变,就整条丢弃,不发往新机器、也不报错。
22
+ // 发送失败交给 onError(error, msg, machine, epoch),不吞;只收当前目标机器的回包。send 返回的 Promise 以「是否发出」收尾。
23
+ export function createMachineBridge({ coda, getMachine, getEpoch, onMessage, onError, targetWindow = globalThis }) {
24
+ let chain = Promise.resolve();
25
+ const send = msg => {
26
+ const machine = getMachine(), epoch = getEpoch?.();
27
+ chain = chain.then(async () => {
28
+ if (getMachine() !== machine || getEpoch?.() !== epoch) return false;
29
+ try { await coda.postMessage(msg, machine ? { machine } : undefined); return true; } catch (error) { onError(error, msg, machine, epoch); return false; }
30
+ });
31
+ return chain;
32
+ };
33
+ const listener = event => {
34
+ const d = event.data;
35
+ if (!(d && typeof d === 'object' && typeof d.type === 'string')) return;
36
+ const current = getMachine();
37
+ if (event.machine?.id && current && event.machine.id !== current) return;
38
+ onMessage(d, event);
39
+ };
40
+ targetWindow.addEventListener('message', listener);
41
+ return { send, dispose: () => targetWindow.removeEventListener('message', listener) };
42
+ }
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName": "好友",
5
5
  "description": "管理 Accord 身份、个人名片与熟人好友通道",
6
6
  "icon": { "symbol": "person.2.fill", "color": "blue" },
7
- "version": "0.3.0",
7
+ "version": "0.3.1",
8
8
  "categories": [
9
9
  "Skills 与工具"
10
10
  ],
package/view/app.mjs CHANGED
@@ -1,11 +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
3
  import { CARD_KIND, COLORS, cardFallbackNotice, checked, mergeFriendRows, mergeProfileAndCard, normalizeProfileInput, parseInvite, readCardRecord, readProfileRecord,
5
4
  shortAuthor } from '../lib/friends.mjs';
5
+ import { createMachineBridge, pickMachine, reachableMachines } from '../lib/view-machine.mjs';
6
6
 
7
7
  const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
8
- const coda = window.coda, bridge = new Bridge();
8
+ const coda = window.coda;
9
9
  const root = document.getElementById('root');
10
10
  const COLOR_NAMES = { blue: '蓝', orange: '橙', green: '绿', purple: '紫', pink: '粉', teal: '青', gray: '灰' };
11
11
  const STATUS_TEXT = { bound: '已互认', pending: '待互认', conflict: '密钥冲突' };
@@ -20,22 +20,40 @@ const h = (tag, attrs = {}, ...children) => {
20
20
  return node;
21
21
  };
22
22
 
23
- const state = { author: null, friends: [], profiles: [], cards: [], 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;
24
30
 
25
31
  // ---- 备注:经模块存在本机 ----
26
32
  const pendingReplies = new Map();
27
33
  let counter = 0;
28
- bridge.on('reply', ({ rid, ok, value, error }) => {
29
- const wait = pendingReplies.get(rid);
30
- if (!wait) return;
31
- pendingReplies.delete(rid);
32
- 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
+ },
33
51
  });
34
52
  function ask(type, input = {}) {
35
- const rid = `n${++counter}`;
53
+ const rid = `n${++counter}`, machine = currentMachine;
36
54
  return new Promise((resolve, reject) => {
37
55
  const timer = setTimeout(() => { pendingReplies.delete(rid); reject(new Error('模块没有回应')); }, 10_000);
38
- 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); } });
39
57
  bridge.send({ type, rid, ...input });
40
58
  });
41
59
  }
@@ -45,7 +63,7 @@ let reading = 0;
45
63
  // profile 与 friends/card 各读各的:一种读不到或没有记录,不挡另一种。
46
64
  async function readProfiles() {
47
65
  const mine = ++reading;
48
- const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 })));
66
+ const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 }, via())));
49
67
  if (mine !== reading) return;
50
68
  if (profiles.status === 'fulfilled') state.profiles = profiles.value?.records ?? [];
51
69
  if (cards.status === 'fulfilled') state.cards = cards.value?.records ?? [];
@@ -54,7 +72,8 @@ async function readProfiles() {
54
72
  if (!own.touched) loadOwn();
55
73
  draw();
56
74
  }
57
- const own = { touched: false, name: '', emoji: '', color: 'blue', avatar: undefined };
75
+ const blankOwn = () => ({ touched: false, name: '', emoji: '', color: 'blue', avatar: undefined });
76
+ const own = blankOwn();
58
77
  const latestOwn = (records, read) => records.map(read).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
59
78
  // 本机名片:与好友列表同一条合并规则(profile 写了的优先,缺的由 friends/card 补);头像随表单带着,重新发布不会把它丢掉或带回已清除的。
60
79
  function loadOwn() {
@@ -64,7 +83,7 @@ function loadOwn() {
64
83
  syncOwnForm();
65
84
  }
66
85
 
67
- let watched = false;
86
+ let watching = null;
68
87
  function onChange({ type, entry }) {
69
88
  if (type === 'DELETED' || !entry) return;
70
89
  state.author = entry.spec?.author ?? null;
@@ -74,13 +93,48 @@ function onChange({ type, entry }) {
74
93
  readProfiles();
75
94
  }
76
95
  async function start() {
77
- try { state.notes = await ask('notes.list'); } catch (e) { state.problem = `读不到本地备注:${e.message}`; }
78
- if (!watched) {
79
- watched = true;
80
- try { await coda.watch(ACCORD, onChange, { id: 'local' }); }
81
- 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; } }
82
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();
83
136
  draw();
137
+ start();
84
138
  }
85
139
 
86
140
  // ---- 我的身份与名片 ----
@@ -100,29 +154,33 @@ function say(target, text, kind = 'hint') { target.className = kind; target.text
100
154
  async function publishProfile() {
101
155
  let body;
102
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;
103
158
  ownForm.button.disabled = true;
104
159
  say(ownForm.message, '正在发布…', 'progress');
105
160
  try {
106
161
  try {
107
- await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] });
108
- say(ownForm.message, '名片已发布,好友会看到它', 'ok');
162
+ await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] }, opts);
163
+ if (live()) say(ownForm.message, '名片已发布,好友会看到它', 'ok');
109
164
  } catch (e) {
110
165
  // 绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
111
166
  if (e?.code !== 'forbidden') throw e;
112
- await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] });
113
- // 缓存的 state.profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。
114
- let rooted = null;
115
- try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author: state.author, limit: 1 }))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
116
- say(ownForm.message, cardFallbackNotice(rooted), 'ok');
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
+ }
117
174
  }
118
- readProfiles();
119
- } catch (e) { say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
120
- ownForm.button.disabled = false;
175
+ if (live()) readProfiles();
176
+ } catch (e) { if (live()) say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
177
+ if (live()) ownForm.button.disabled = false;
121
178
  }
122
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' }) };
123
180
  async function copyKey() {
124
181
  if (!state.author) return;
125
- 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'); }
126
184
  }
127
185
 
128
186
  // ---- 添加好友 ----
@@ -166,20 +224,26 @@ async function submitInvite() {
166
224
  }
167
225
  // 入网码是凭据:取出后立刻清空所有输入框,不写进任何存储或日志。
168
226
  clearInvite();
227
+ const gen = selectionGen, opts = via(), live = () => gen === selectionGen;
169
228
  invite.button.disabled = true;
170
229
  say(invite.message, '正在接受邀请,加入对方的通道…', 'progress');
171
230
  const peerNode = input.peerNode;
172
231
  let node;
173
232
  try {
174
- ({ node } = await coda.call(LOCAL, 'accept', input));
175
- } 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
+ }
176
240
  input = null;
177
- say(invite.message, '已加入通道,正在与对方互认…', 'progress');
241
+ if (live()) say(invite.message, '已加入通道,正在与对方互认…', 'progress');
178
242
  try {
179
- await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) });
180
- say(invite.message, '好友已添加并完成互认', 'ok');
181
- } catch (e) { say(invite.message, `已加入通道,但互认暂未完成(${e.message})。可稍后在好友列表点「互认」重试`, 'error'); }
182
- 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;
183
247
  }
184
248
 
185
249
  // ---- 好友列表 ----
@@ -188,21 +252,32 @@ const countBadge = h('span', { class: 'count' });
188
252
  function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, cards: state.cards, notes: state.notes }); }
189
253
 
190
254
  async function handshake(row) {
255
+ const gen = selectionGen, opts = via();
191
256
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在互认…' }); draw();
192
- try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }); state.notice.set(row.node, { kind: 'ok', text: '互认完成' }); }
193
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `互认失败:${e.message}` }); }
194
- 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();
195
262
  }
196
263
  async function remove(row) {
264
+ const gen = selectionGen, opts = via();
197
265
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在移除…' }); draw();
198
- try { await coda.call(LOCAL, 'remove', { node: row.node }); state.notice.delete(row.node); state.removing = null; }
199
- 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; }
200
271
  state.busy.delete(row.node); draw();
201
272
  }
202
273
  async function saveNote(row, text) {
274
+ const gen = selectionGen;
203
275
  state.editing = null;
204
- try { state.notes = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); state.notice.delete(row.node); }
205
- 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); }
206
281
  draw();
207
282
  }
208
283
 
@@ -237,8 +312,9 @@ function friendRow(row) {
237
312
 
238
313
  const problem = h('p', { class: 'error selectable' });
239
314
  function draw() {
240
- problem.textContent = state.problem ?? '';
241
- problem.hidden = !state.problem;
315
+ const problems = [state.notesProblem, state.problem].filter(Boolean).join(';');
316
+ problem.textContent = problems;
317
+ problem.hidden = !problems;
242
318
  identity.key.textContent = state.author ? `ed25519:${shortAuthor(state.author)}…` : state.loaded ? '未取得' : '读取中…';
243
319
  identity.copy.disabled = !state.author;
244
320
  const shown = rows();
@@ -248,7 +324,7 @@ function draw() {
248
324
  : h('p', { class: 'empty' }, state.loaded ? '还没有好友。在上面粘贴对方发来的邀请即可添加。' : '正在读取…'));
249
325
  }
250
326
 
251
- root.replaceChildren(h('div', { class: 'page' }, problem,
327
+ root.replaceChildren(h('div', { class: 'page' }, machineBar, problem,
252
328
  h('section', {}, h('h2', {}, '我的身份与名片'), h('div', { class: 'card' },
253
329
  h('div', { class: 'line identity' }, h('span', { class: 'secondary' }, '本机公钥'), identity.key, h('span', { class: 'spacer' }), identity.copy), identity.message,
254
330
  h('div', { class: 'fields' }, h('label', { class: 'field' }, h('span', {}, '昵称'), ownForm.name), h('label', { class: 'field' }, h('span', {}, '头像'), ownForm.emoji)),
@@ -267,6 +343,7 @@ root.replaceChildren(h('div', { class: 'page' }, problem,
267
343
  h('div', { class: 'line' }, invite.button), invite.message)),
268
344
  h('section', {}, h('h2', {}, '好友', countBadge), list)));
269
345
  syncOwnForm();
346
+ drawMachines();
270
347
  draw();
271
348
 
272
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); }