@coda-console/friends 0.4.0 → 0.5.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/README.md CHANGED
@@ -2,12 +2,22 @@
2
2
 
3
3
  管理本机的 Accord 身份、个人名片与熟人好友通道(`coda/accord@1`)。
4
4
 
5
- - **我的名片**:名片卡显示昵称、头像、主题色与本机公钥短码(点按复制),下方状态条给出已互认好友数(有待互认、冲突时提示)与身份、证书状态;多台机器提供这页时顶部可切换,连不上的机器置灰并注明原因。
5
+ - **我的名片**:名片卡显示昵称、头像、主题色与本机公钥短码(点按复制),下方状态条给出已互认好友数(有待互认、冲突时提示)与身份、证书状态。
6
6
  - **编辑名片**:头像可选照片、几何纹(按公钥生成)、Emoji 或字标(昵称首字,写进 `emoji`)。照片从本机选图,在弹层里拖动、缩放裁成 512×512,优先编 WebP(不支持时用 JPEG),上传到 `coda-view://blob/content` 后把内容指针写进名片的 `avatar`;只改昵称、颜色不重新上传,换成非照片头像时写 `avatar: null` 清除。名片以公开的 `profile` / `self` 记录发布;本机绑定了代签证书、`profile` 被拒(`forbidden`)时改发可代签的社交名片 `friends/card` / `self`。
7
7
  - **添加好友**:点名片上的「添加好友」,粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
8
8
  - **好友列表**:实时跟随好友表变化,宽屏双列;显示好友的照片头像(读不出时退回 Emoji、几何纹或首字,点「刷新」重试)。点好友打开详情:完整公钥、节点名、本机备注、重新互认、二次确认后移除。
9
9
  - **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录、发私信与动态、实时跟随私信与动态,不必各自处理没有身份、证书过期和重试。
10
10
 
11
+ ## 几台电脑
12
+
13
+ 页面不自己选电脑:App 的全局视图里有哪几台,页面就读哪几台,没有机器标签。
14
+
15
+ - **我的名片按身份显示**:按各台 Accord 的 `spec.author` 分组,同一身份只显示一张名片,视图里有不同身份的电脑时每个身份一张。同一身份的几台读到的名片不一样(同步有先后)时取记录版本高的那份,不逐字段比对。改名片只发给这个身份里视图顺序第一台能签名(证书可用)的电脑,页面只确认这一台写入成功,头像也上传到这一台;其他电脑要等同步后才显示新名片(同步见下面的「推荐用法」)。不会向几台都发,两台同时改的冲突不处理。
16
+ - **好友按电脑分节**:每台一节,顺序同视图,节标题是电脑名;节里是这台自己的好友通道(好友关系按机器上的通道登记,在 A 上加的好友 B 上不会自动出现),状态条(好友数、证书状态、待互认与冲突)和「添加好友」也在这一节。接受邀请与随后的互认、好友详情里的备注、重新互认、移除,都发给这一节、这一行所在的电脑。没有好友的电脑也占一节;同一个好友在两台上都加了,就在两节里各出现一次,不合并。读不到的电脑(`unreachable`)节里写明原因,不出「添加好友」。
17
+ - **只有一台时**页面不出现节标题,状态条与「添加好友」仍在名片上。
18
+ - **推荐用法**:好友只在一台电脑上加。好友关系登记在那台电脑上,别的电脑不会自动出现这个好友。邀请里的入网码只能用一次,不必在每台上重复加。
19
+ - **几台电脑绑定同一个身份、又在同一个空间里时**,其他电脑发布的记录由 Coda 在这几台之间同步,好友从加了他的那台读取(见 Coda 仓库 `docs/peers.md`)。这是 Coda 基座的行为,本插件不另外保证,也不检查同步是否已经完成。
20
+
11
21
  ## 社交网关
12
22
 
13
23
  签名写入与记录查询全部透传 `coda/accord@1`,网关自己没有第二份目录库。本机网关记录(`friends/social@1`,key `local`)的 `status` 给出作者、证书状态(`no_identity` / `needs_cert` / `active`)、好友数、待发数与暂停的 kind。
@@ -0,0 +1,50 @@
1
+ // 好友页按「视图里的每台电脑」读数据的纯逻辑:成员列表、按身份合并名片、按电脑分节。不碰 Coda 的 Node API;页面和单测都加载它。
2
+ // 页面不自己选机器:App 的全局视图里有哪几台,页面就读哪几台。
3
+
4
+ import { certStateOf, mergeFriendRows, mergeProfileAndCard, readCardRecord, readProfileRecord } from './friends.mjs';
5
+
6
+ /** 视图里的成员(去重、保持 coda.machines 的顺序);`unreachable` 是读不到的原因,可达的为 null。 */
7
+ export function listMembers(coda) {
8
+ const list = Array.isArray(coda?.machines) ? coda.machines : [coda?.machine];
9
+ const seen = new Set();
10
+ return list.filter(m => typeof m?.id === 'string' && m.id && !seen.has(m.id) && seen.add(m.id))
11
+ .map(m => ({ id: m.id, name: m.name || m.id, unreachable: m.unreachable ? (m.unreachable === true ? '暂时连不上' : String(m.unreachable)) : null }));
12
+ }
13
+
14
+ // 一个身份的几台电脑里,某种名片记录(profile 或 friends/card)版本最高的那条,记下是哪台读到的;版本相同取视图里靠前的。
15
+ const newest = (members, records, read, author) => members
16
+ .flatMap(m => m[records].map(read).filter(card => card && card.author === author).map(card => ({ ...card, from: m.id })))
17
+ .reduce((best, one) => (best && best.version >= one.version ? best : one), null);
18
+
19
+ /**
20
+ * 按 `author` 把读到了的成员分组(没有身份的电脑归在 author 为 null 一组;Accord 没读到的成员不参与),组的顺序是成员第一次出现的顺序。
21
+ * 每组一张名片:几台读到的不一样(同步有先后)时,profile 与 friends/card 各取版本最高的一条,再按 mergeProfileAndCard 合成;
22
+ * `from` 是提供头像那条记录的电脑(头像没写就是提供名字的那条)。不逐字段比对。
23
+ * `signer` 是改名片时发往的那一台:组里第一台能签名(证书可用)的,没有就是组里第一台。
24
+ */
25
+ export function identities(members) {
26
+ const groups = new Map();
27
+ for (const member of members.filter(m => m.loaded)) {
28
+ if (!groups.has(member.author)) groups.set(member.author, []);
29
+ groups.get(member.author).push(member);
30
+ }
31
+ return [...groups].map(([author, group]) => {
32
+ const profile = newest(group, 'profiles', readProfileRecord, author), card = newest(group, 'cards', readCardRecord, author);
33
+ const merged = mergeProfileAndCard(profile, card);
34
+ const source = [profile, card].find(one => one?.avatarPresent) ?? profile ?? card;
35
+ return { author, members: group, card: merged && { ...merged, from: source.from }, signer: group.find(m => certStateOf(m.entry) === 'active') ?? group[0] };
36
+ });
37
+ }
38
+
39
+ /**
40
+ * 好友按电脑分节:每个成员一节,顺序同视图;节里是这台自己的好友通道(行的内容见 mergeFriendRows),不同电脑上的同一个好友各出现一次。
41
+ * 只有一个成员时 `title` 为 null(不出节标题);读不到的成员(宿主标了 `unreachable`,或 Accord 读失败 `accordProblem`)`unreachable` 写明原因,没有行。
42
+ */
43
+ export function friendSections(members) {
44
+ return members.map(member => ({
45
+ member,
46
+ title: members.length > 1 ? member.name : null,
47
+ unreachable: member.unreachable || member.accordProblem || null,
48
+ rows: member.unreachable || member.accordProblem ? [] : mergeFriendRows({ friends: member.friends, profiles: member.profiles, cards: member.cards, notes: member.notes }),
49
+ }));
50
+ }
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.4.0",
7
+ "version": "0.5.0",
8
8
  "categories": [
9
9
  "Skills 与工具"
10
10
  ],
package/view/app.mjs CHANGED
@@ -1,10 +1,10 @@
1
- // 好友页:本机 Accord 身份与名片(Hero + 状态条)、编辑名片(含本地选图裁剪上传)、好友列表与详情、添加好友。
2
- // Accord 的读写(coda/accord@1)都在这里按交互发起;备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用
1
+ // 好友页:各台电脑的 Accord 身份与名片(Hero)、编辑名片(含本地选图裁剪上传)、按电脑分节的好友列表与详情、添加好友。
2
+ // 页面不自己选机器:视图里有几台就都读,名片按身份合并、好友按电脑分节(lib/view-members.mjs);写操作发往它所在的那一台。
3
+ // Accord 的读写(coda/accord@1)都在这里按交互发起;备注只经模块存在各台本机。好友的昵称、备注、节点名等外来数据一律用
3
4
  // textContent / DOM API 渲染,从不拼 HTML 字符串;头像图片地址只来自 resolveAvatar(经 readContentPointer 白名单校验)。
4
5
  import { accordStatusSummary, blobUploadUrl, initialChar, resolveAvatar } from '../lib/avatar.mjs';
5
- import { CARD_KIND, COLORS, cardFallbackNotice, checked, mergeFriendRows, mergeProfileAndCard, normalizeCardInput, normalizeContentPointer, parseInvite,
6
- readCardRecord, readProfileRecord, shortAuthor } from '../lib/friends.mjs';
7
- import { createMachineBridge, pickMachine } from '../lib/view-machine.mjs';
6
+ import { CARD_KIND, COLORS, cardFallbackNotice, checked, normalizeCardInput, normalizeContentPointer, parseInvite, readProfileRecord, shortAuthor } from '../lib/friends.mjs';
7
+ import { friendSections, identities, listMembers } from '../lib/view-members.mjs';
8
8
  import { createCropper } from './cropper.mjs';
9
9
  import { fill, h, identiconSvg, svg } from './dom.mjs';
10
10
 
@@ -17,98 +17,66 @@ const MODES = [['photo', '照片'], ['identicon', '几何纹'], ['emoji', 'Emoji
17
17
  const EMOJIS = ['😀', '😎', '🦊', '🐱', '🐼', '🌿', '☕', '🎧', '🚀', '⚡', '🌙', '✨'];
18
18
  const UPLOAD_ERRORS = { 404: '当前客户端还不支持上传头像,请升级 Coda 后再试', 413: '图片太大(超过 5 MiB),请换一张' };
19
19
 
20
- const newState = () => ({ entry: null, author: null, friends: [], profiles: [], cards: [], notes: {}, loaded: false, problem: null, notesProblem: null,
21
- busy: new Set(), notice: new Map(), detail: null, removing: null, failedPhotos: new Set() });
22
- const state = newState();
23
- let currentMachine = pickMachine(coda, coda.getState?.()?.machine);
24
- // 读写都发往当前选中的机器;单机时不指明。多步操作在入口取一次,之后不再读 currentMachine。
25
- const via = () => (currentMachine ? { machine: currentMachine } : undefined);
26
- // 头像图片的读写地址只在多机空间里带 machine。
27
- const multiMachine = () => Array.isArray(coda.machines) && coda.machines.length > 1;
28
- const blobMachine = () => (multiMachine() ? currentMachine : null);
29
- // 每次选机自增(A → B → A 也不同):旧机器的订阅回调、异步回写,凭它丢弃。
30
- let selectionGen = 0;
31
- // 编辑名片的会话代际:每次打开、关闭编辑弹层或切机自增;旧会话的发布做完后不碰新会话的弹层、按钮、提示和裁剪。
20
+ // 视图里的每台电脑(成员在页面生命周期内不变)各存一份数据;读不到的(unreachable)也在,只是不发请求。
21
+ const members = listMembers(coda).map(m => ({ ...m, entry: null, author: null, friends: [], profiles: [], cards: [], notes: {}, loaded: false,
22
+ problem: null, notesProblem: null, accordProblem: null, reading: 0 }));
23
+ const live = members.filter(m => !m.unreachable);
24
+ const multi = members.length > 1;
25
+ const state = { busy: new Set(), notice: new Map(), heroNotice: new Map(), detail: null, removing: null, failedPhotos: new Set() };
26
+ const via = m => ({ machine: m.id });
27
+ // 头像图片的读取地址只在多机空间里带 machine。
28
+ const blobMachine = id => (multi ? id : null);
29
+ const rowKey = (m, node) => `${m.id}\u0000${node}`;
30
+ // 编辑名片的会话代际:每次打开、关闭编辑弹层自增;旧会话的发布做完后不碰新会话的弹层、按钮、提示和裁剪。
32
31
  let editorGen = 0;
33
32
  function say(target, text, kind = 'hint') { target.className = kind; target.textContent = text; }
34
33
 
35
- // ---- 备注:经模块存在本机 ----
34
+ // ---- 备注:经各台的模块存在那台本机 ----
36
35
  const pendingReplies = new Map();
37
36
  let counter = 0;
38
- const bridge = createMachineBridge({
39
- coda,
40
- getMachine: () => currentMachine,
41
- getEpoch: () => selectionGen,
42
- onMessage({ type, rid, ok, value, error }) {
43
- if (type !== 'reply') return;
44
- const wait = pendingReplies.get(rid);
45
- if (!wait) return;
46
- pendingReplies.delete(rid);
47
- if (ok) wait.resolve(value); else wait.reject(new Error(error));
48
- },
49
- onError(error, msg) {
50
- const wait = pendingReplies.get(msg.rid);
51
- if (!wait) return;
52
- pendingReplies.delete(msg.rid);
53
- wait.reject(new Error(`发送失败:${error?.message ?? error}`));
54
- },
55
- });
56
- function ask(type, input = {}) {
57
- const rid = `n${++counter}`, machine = currentMachine;
37
+ function ask(m, type, input = {}) {
38
+ const rid = `n${++counter}`;
58
39
  return new Promise((resolve, reject) => {
40
+ const settle = fn => v => { clearTimeout(timer); pendingReplies.delete(rid); fn(v); };
59
41
  const timer = setTimeout(() => { pendingReplies.delete(rid); reject(new Error('模块没有回应')); }, 10_000);
60
- pendingReplies.set(rid, { machine, resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
61
- bridge.send({ type, rid, ...input });
42
+ pendingReplies.set(rid, { machine: m.id, resolve: settle(resolve), reject: settle(reject) });
43
+ Promise.resolve().then(() => coda.postMessage({ type, rid, ...input }, via(m))).catch(error => pendingReplies.get(rid)?.reject(new Error(`发送失败:${error?.message ?? error}`)));
62
44
  });
63
45
  }
46
+ addEventListener('message', event => {
47
+ const { type, rid, ok, value, error } = event.data ?? {};
48
+ const wait = type === 'reply' ? pendingReplies.get(rid) : null;
49
+ if (!wait || (event.machine?.id && event.machine.id !== wait.machine)) return;
50
+ if (ok) wait.resolve(value); else wait.reject(new Error(error));
51
+ });
64
52
 
65
- // ---- 读本机 Accord ----
66
- let reading = 0;
53
+ // ---- 读各台的 Accord ----
67
54
  // profile 与 friends/card 各读各的:一种读不到或没有记录,不挡另一种。
68
- async function readProfiles() {
69
- const mine = ++reading;
70
- const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 }, via())));
71
- if (mine !== reading) return;
72
- if (profiles.status === 'fulfilled') state.profiles = profiles.value?.records ?? [];
73
- if (cards.status === 'fulfilled') state.cards = cards.value?.records ?? [];
55
+ async function readProfiles(m) {
56
+ const mine = ++m.reading;
57
+ const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 }, via(m))));
58
+ if (mine !== m.reading) return;
59
+ if (profiles.status === 'fulfilled') m.profiles = profiles.value?.records ?? [];
60
+ if (cards.status === 'fulfilled') m.cards = cards.value?.records ?? [];
74
61
  const failed = [profiles, cards].find(read => read.status === 'rejected');
75
- state.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
76
- loadOwn();
62
+ m.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
77
63
  draw();
78
64
  }
79
- // 本机已发布的名片(Hero 展示它);编辑弹层另有一份草稿,打开时从它拷贝。
80
- const blankOwn = () => ({ name: '', emoji: '', color: 'blue', avatar: undefined });
81
- const own = blankOwn();
82
- const latestOwn = (records, read) => records.map(read).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
83
- // 与好友列表同一条合并规则(profile 写了的优先,缺的由 friends/card 补);头像随名片带着,重新发布不会把它丢掉或带回已清除的。
84
- function loadOwn() {
85
- const mine = mergeProfileAndCard(latestOwn(state.profiles, readProfileRecord), latestOwn(state.cards, readCardRecord));
86
- if (mine) Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue', avatar: mine.avatarPresent ? mine.avatar : undefined });
87
- }
88
-
89
- let watching = null;
90
- function onChange({ type, entry }) {
65
+ function onChange(m, { type, entry }) {
91
66
  if (type === 'DELETED' || !entry) return;
92
- state.entry = entry;
93
- state.author = entry.spec?.author ?? null;
94
- state.friends = entry.status?.friends ?? [];
95
- state.loaded = true;
67
+ m.entry = entry;
68
+ m.author = entry.spec?.author ?? null;
69
+ m.friends = entry.status?.friends ?? [];
70
+ m.loaded = true;
71
+ draw();
72
+ readProfiles(m);
73
+ }
74
+ async function start(m) {
75
+ try { m.notes = await ask(m, 'notes.list'); m.notesProblem = null; }
76
+ catch (e) { m.notesProblem = `读不到本地备注:${e.message}`; draw(); }
77
+ try { await coda.watch(ACCORD, event => onChange(m, event), { id: 'local' }, via(m)); }
78
+ catch (e) { m.accordProblem = `读不到本机的好友信息:${e.message}`; }
96
79
  draw();
97
- readProfiles();
98
- }
99
- async function start() {
100
- const gen = selectionGen, opts = via();
101
- try { state.notes = await ask('notes.list'); state.notesProblem = null; }
102
- catch (e) { if (gen === selectionGen) { state.notesProblem = `读不到本地备注:${e.message}`; draw(); } }
103
- if (gen !== selectionGen) return;
104
- if (!watching) {
105
- let mine;
106
- try {
107
- mine = watching = Promise.resolve(coda.watch(ACCORD, entry => { if (gen === selectionGen) onChange(entry); }, { id: 'local' }, opts));
108
- await mine;
109
- } catch (e) { if (watching === mine) watching = null; if (gen === selectionGen) { state.problem = `读不到本机的好友信息:${e.message}`; state.loaded = true; } }
110
- }
111
- if (gen === selectionGen) draw();
112
80
  }
113
81
 
114
82
  // ---- 头像 ----
@@ -125,8 +93,7 @@ function avatar(desc, size) {
125
93
  show(desc);
126
94
  return node;
127
95
  }
128
- const ownAvatar = () => resolveAvatar({ avatar: own.avatar, emoji: own.emoji, author: state.author, name: own.name, machine: blobMachine() });
129
- const rowAvatar = row => resolveAvatar({ avatar: row.avatar, emoji: row.emoji, author: row.author, name: row.title, machine: blobMachine() });
96
+ const rowAvatar = (m, row) => resolveAvatar({ avatar: row.avatar, emoji: row.emoji, author: row.author, name: row.title, machine: blobMachine(m.id) });
130
97
  const cameraIcon = () => svg('svg', { viewBox: '0 0 24 24', width: 11, height: 11, fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4, 'aria-hidden': 'true' },
131
98
  svg('path', { d: 'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z' }), svg('circle', { cx: 12, cy: 13, r: 4 }));
132
99
 
@@ -157,99 +124,63 @@ function closeDialog() {
157
124
  }
158
125
  addEventListener('keydown', e => { if (e.key === 'Escape' && openDialog) closeDialog(); });
159
126
 
160
- // ---- 多台机器提供这页时,选看哪台 ----
161
- const machineBar = h('nav', { class: 'machines', 'aria-label': '选择机器' });
162
- function drawMachines() {
163
- const machines = Array.isArray(coda.machines) ? coda.machines : [];
164
- machineBar.hidden = machines.length < 2;
165
- fill(machineBar, ...(machines.length < 2 ? [] : machines.map(m => {
166
- if (m.unreachable) {
167
- const why = m.unreachable === true ? '暂时连不上' : String(m.unreachable);
168
- return h('button', { class: 'm-pill', type: 'button', disabled: true, title: `不可达:${why}`, 'aria-label': `${m.name || m.id}(不可达:${why})` },
169
- h('span', { class: 'm-dot off' }), m.name || m.id, h('small', { class: 'm-why' }, '不可达'));
170
- }
171
- return h('button', { class: 'm-pill', type: 'button', 'aria-pressed': String(m.id === currentMachine), onclick: () => switchMachine(m.id) }, h('span', { class: 'm-dot' }), m.name || m.id);
172
- })));
173
- }
174
- function switchMachine(id) {
175
- if (id === currentMachine) return;
176
- currentMachine = id;
177
- selectionGen++;
178
- editorGen++;
179
- coda.setState?.({ machine: currentMachine });
180
- reading++;
181
- watching?.then(w => w?.dispose?.(), () => {});
182
- watching = null;
183
- for (const [rid, wait] of [...pendingReplies]) { pendingReplies.delete(rid); wait.reject(new Error('已切换机器')); }
184
- closeDialog();
185
- Object.assign(state, newState());
186
- Object.assign(own, blankOwn());
187
- editor.publish.disabled = false; invite.button.disabled = false;
188
- for (const target of [hero.message, editor.message, invite.message]) say(target, '');
189
- drawMachines();
190
- draw();
191
- start();
192
- }
193
-
194
- // ---- 我的名片:Hero 与状态条 ----
195
- const hero = {
196
- card: h('section', { class: 'hero' }),
197
- avatar: h('button', { class: 'av-ring', type: 'button', 'aria-label': '更换头像', title: '更换头像', onclick: () => openEditor() }),
198
- name: h('h2', { class: 'hero-name selectable' }),
199
- key: h('button', { class: 'fp mono', type: 'button', onclick: copyKey }),
200
- lead: h('p', { class: 'hint' }),
201
- message: h('p', { class: 'hint' }),
202
- friends: h('div', { class: 'tile' }),
203
- cert: h('div', { class: 'tile' }),
204
- };
205
- hero.card.append(
206
- h('div', { class: 'banner' }, h('div', { class: 'banner-acts' },
207
- h('button', { class: 'pill', type: 'button', onclick: () => openEditor() }, '编辑名片'),
208
- h('button', { class: 'pill strong', type: 'button', onclick: () => showDialog(invite.dialog) }, '添加好友'))),
209
- h('div', { class: 'hero-body' },
210
- h('div', { class: 'hero-id' }, hero.avatar, h('div', { class: 'hero-names' }, h('div', { class: 'name-line' }, hero.name, h('span', { class: 'tag' }, '我的名片')), hero.key)),
211
- hero.lead, hero.message,
212
- h('div', { class: 'bento' }, hero.friends, hero.cert)));
127
+ // ---- 我的名片:每个身份一张 Hero ----
128
+ // 只有一台电脑时,名片上带这台的状态条和「添加好友」;几台时这两样都在各自的节里。
213
129
  const CERT = {
214
130
  active: { dot: 'ok-dot', text: '可发布' },
215
131
  needs_cert: { dot: 'warn-dot', text: '需要证书', sub: '需绑定或续期代签证书:前往客户端「设置 › 身份」处理后再发布名片' },
216
132
  no_identity: { dot: 'off-dot', text: '未建身份', sub: '前往客户端「设置 › 身份」创建' },
217
133
  };
218
134
  const formatTime = ms => new Date(ms).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
219
- function tile(node, label, value, sub, dot) {
220
- fill(node, h('span', { class: 'tile-k' }, label), h('span', { class: 'tile-v' }, dot ? h('span', { class: `dot ${dot}` }) : null, value), sub);
221
- }
222
- function drawHero(shown) {
223
- hero.card.className = `hero c-${own.color}`;
224
- hero.avatar.replaceChildren(avatar(ownAvatar(), 'lg'), h('span', { class: 'cam' }, cameraIcon()));
225
- hero.name.textContent = own.name || (state.loaded ? '还没有名片' : '读取中…');
226
- hero.lead.textContent = own.name || !state.loaded ? '' : '点「编辑名片」设置昵称、头像和主题色,好友就能认出你。名片对所有人公开。';
227
- hero.lead.hidden = !hero.lead.textContent;
228
- const summary = accordStatusSummary(state.entry, shown);
229
- hero.key.disabled = !state.author;
230
- hero.key.textContent = state.author ? `ed25519:${summary.short}… · 复制` : !state.loaded ? '读取中…' : summary.cert === 'no_identity' ? '未建身份' : '未取得公钥';
231
- hero.key.title = state.author ? '复制完整公钥' : '';
232
- if (!state.loaded) {
233
- tile(hero.friends, '好友', '读取中…');
234
- tile(hero.cert, '身份', '读取中…');
235
- return;
236
- }
237
- const { bound, pending, conflict, total } = summary.friends;
238
- tile(hero.friends, '好友', `${bound} 位已互认`, h('span', { class: 'tile-s' },
239
- conflict ? h('span', { class: 'badge conflict' }, `${conflict} 冲突`) : null,
240
- pending ? h('span', { class: 'badge pending' }, `${pending} 待互认`) : null,
241
- conflict || pending ? null : total ? '全部已互认' : '还没有好友'));
242
- const cert = CERT[summary.cert];
243
- const sub = summary.cert === 'active' ? (summary.certUntil ? `证书有效至 ${formatTime(summary.certUntil)}` : '名片可正常发布') : cert.sub;
244
- tile(hero.cert, '身份', cert.text, h('span', { class: 'tile-s' }, sub), cert.dot);
135
+ function tile(label, value, sub, dot) {
136
+ return h('div', { class: 'tile' }, h('span', { class: 'tile-k' }, label), h('span', { class: 'tile-v' }, dot ? h('span', { class: `dot ${dot}` }) : null, value), sub);
245
137
  }
246
- async function copyKey() {
247
- if (!state.author) return;
248
- const gen = selectionGen;
249
- try { await coda.copy(state.author); if (gen === selectionGen) say(hero.message, '公钥已复制', 'ok'); } catch (e) { if (gen === selectionGen) say(hero.message, `复制失败:${e.message}`, 'error'); }
138
+ // 一台电脑的好友数与证书状态。
139
+ function statusTiles(m, rows) {
140
+ if (!m.loaded) return h('div', { class: 'bento' }, tile('好友', '读取中…'), tile('身份', '读取中…'));
141
+ const summary = accordStatusSummary(m.entry, rows), { bound, pending, conflict, total } = summary.friends, cert = CERT[summary.cert];
142
+ const sub = summary.cert === 'active' ? (summary.certUntil ? `证书有效至 ${formatTime(summary.certUntil)}` : '名片可正常发布') : cert.sub;
143
+ return h('div', { class: 'bento' },
144
+ tile('好友', `${bound} 位已互认`, h('span', { class: 'tile-s' },
145
+ conflict ? h('span', { class: 'badge conflict' }, `${conflict} 冲突`) : null,
146
+ pending ? h('span', { class: 'badge pending' }, `${pending} 待互认`) : null,
147
+ conflict || pending ? null : total ? '全部已互认' : '还没有好友')),
148
+ tile('身份', cert.text, h('span', { class: 'tile-s' }, sub), cert.dot));
149
+ }
150
+ function drawHero(id, sections) {
151
+ const { author, card, signer } = id, ready = Boolean(signer);
152
+ const own = card ?? blankOwn(), noticeKey = author ?? '';
153
+ const summary = accordStatusSummary(signer?.entry, []);
154
+ const avatarDesc = resolveAvatar({ avatar: card?.avatarPresent ? card.avatar : undefined, emoji: own.emoji, author, name: own.name, machine: blobMachine(card?.from) });
155
+ const notice = state.heroNotice.get(noticeKey);
156
+ const settled = members.every(m => m.loaded || m.unreachable || m.accordProblem);
157
+ const name = own.name || (!settled ? '读取中…' : ready ? '还没有名片' : '读不到名片');
158
+ const single = !multi && sections[0];
159
+ return h('section', { class: `hero c-${own.color ?? 'blue'}` },
160
+ h('div', { class: 'banner' }, h('div', { class: 'banner-acts' },
161
+ h('button', { class: 'pill', type: 'button', disabled: !ready, onclick: () => openEditor(id) }, '编辑名片'),
162
+ single && !single.unreachable ? h('button', { class: 'pill strong', type: 'button', onclick: () => openInvite(single.member) }, '添加好友') : null)),
163
+ h('div', { class: 'hero-body' },
164
+ h('div', { class: 'hero-id' },
165
+ h('button', { class: 'av-ring', type: 'button', 'aria-label': '更换头像', title: '更换头像', disabled: !ready, onclick: () => openEditor(id) },
166
+ avatar(avatarDesc, 'lg'), h('span', { class: 'cam' }, cameraIcon())),
167
+ h('div', { class: 'hero-names' }, h('div', { class: 'name-line' }, h('h2', { class: 'hero-name selectable' }, name), h('span', { class: 'tag' }, '我的名片')),
168
+ h('button', { class: 'fp mono', type: 'button', disabled: !author, title: author ? '复制完整公钥' : '', onclick: () => copyKey(author),
169
+ }, author ? `ed25519:${summary.short}… · 复制` : !ready ? (settled ? '读不到公钥' : '读取中…') : summary.cert === 'no_identity' ? '未建身份' : '未取得公钥'))),
170
+ !own.name && ready && settled ? h('p', { class: 'hint' }, '点「编辑名片」设置昵称、头像和主题色,好友就能认出你。名片对所有人公开。') : null,
171
+ notice ? h('p', { class: notice.kind }, notice.text) : null,
172
+ single && !single.unreachable ? statusTiles(single.member, single.rows) : null));
173
+ }
174
+ async function copyKey(author) {
175
+ try { await coda.copy(author); state.heroNotice.set(author, { kind: 'ok', text: '公钥已复制' }); } catch (e) { state.heroNotice.set(author, { kind: 'error', text: `复制失败:${e.message}` }); }
176
+ draw();
250
177
  }
251
178
 
252
179
  // ---- 编辑名片 ----
180
+ // 正在编辑的名片所属的身份、发往的那一台,和这张名片当前已发布的内容(编辑弹层另有一份草稿,打开时从它拷贝)。
181
+ const blankOwn = () => ({ name: '', emoji: '', color: 'blue', avatar: undefined });
182
+ const own = blankOwn();
183
+ const editing = { author: null, member: null, avatarMachine: null };
253
184
  // 草稿:mode 决定头像怎么发;avatar 是沿用的已有图片指针(清除照片后为 null),新选的图在 cropper 里。
254
185
  const draft = { name: '', color: 'blue', mode: 'identicon', emoji: '', avatar: null };
255
186
  const preview = { canvas: h('canvas', { class: 'preview-canvas', width: 144, height: 144 }) };
@@ -285,8 +216,12 @@ editor.dialog.body.append(h('div', { class: 'ed-cols' },
285
216
  h('div', { class: 'field' }, h('span', { class: 'lbl' }, '主题色'), editor.swatches))));
286
217
 
287
218
  const modeOf = card => (card.avatar ? 'photo' : !card.emoji ? 'identicon' : card.emoji === initialChar(card.name, '') ? 'monogram' : 'emoji');
288
- function openEditor() {
219
+ // 改名片只发给这个身份的一台(id.signer),页面只确认这一台写入成功;同一身份的其他台要等 Coda 基座同步后才显示新名片(本插件不保证、不检查);头像也上传到这一台。
220
+ function openEditor(id) {
221
+ if (!id.signer) return;
289
222
  editorGen++;
223
+ Object.assign(own, blankOwn(), id.card && { name: id.card.name, emoji: id.card.emoji ?? '', color: id.card.color ?? 'blue', avatar: id.card.avatarPresent ? id.card.avatar : undefined });
224
+ Object.assign(editing, { author: id.author, member: id.signer, avatarMachine: blobMachine(id.card?.from) });
290
225
  cropper.clear();
291
226
  editor.publish.disabled = false;
292
227
  Object.assign(draft, { name: own.name, color: own.color, mode: modeOf(own), emoji: own.emoji, avatar: own.avatar ?? null });
@@ -298,8 +233,8 @@ function openEditor() {
298
233
  showDialog(editor.dialog);
299
234
  }
300
235
  function draftAvatar() {
301
- const author = state.author, name = draft.name;
302
- if (draft.mode === 'photo') return resolveAvatar({ avatar: draft.avatar, emoji: own.emoji, author, name, machine: blobMachine() });
236
+ const author = editing.author, name = draft.name;
237
+ if (draft.mode === 'photo') return resolveAvatar({ avatar: draft.avatar, emoji: own.emoji, author, name, machine: editing.avatarMachine });
303
238
  if (draft.mode === 'emoji') return resolveAvatar({ emoji: draft.emoji, author, name });
304
239
  if (draft.mode === 'monogram') return { kind: 'monogram', text: initialChar(name) };
305
240
  return resolveAvatar({ author, name });
@@ -311,7 +246,7 @@ function syncPreview() {
311
246
  h('div', { class: 'mini-body' },
312
247
  h('span', { class: 'av-ring md' }, fresh ? h('span', { class: 'av md k-photo' }, preview.canvas) : avatar(draftAvatar(), 'md')),
313
248
  h('div', { class: 'mini-name truncate' }, draft.name.trim() || '未命名'),
314
- state.author ? h('div', { class: 'mono secondary' }, `@${shortAuthor(state.author)}`) : null));
249
+ editing.author ? h('div', { class: 'mono secondary' }, `@${shortAuthor(editing.author)}`) : null));
315
250
  if (fresh) mirrorCrop();
316
251
  if (draft.mode === 'monogram') editor.other.textContent = `以昵称首字「${initialChar(draft.name)}」作头像,昵称改了它跟着变。`;
317
252
  }
@@ -320,7 +255,7 @@ function syncEditor() {
320
255
  editor.photo.hidden = draft.mode !== 'photo';
321
256
  editor.emojiPane.hidden = draft.mode !== 'emoji';
322
257
  editor.other.hidden = draft.mode !== 'identicon' && draft.mode !== 'monogram';
323
- editor.other.textContent = draft.mode === 'identicon' ? (state.author ? '由你的公钥确定性生成的 5×5 几何纹,换设备也一样。' : '取得身份后按公钥生成几何纹;现在先以昵称首字代替。') : '';
258
+ editor.other.textContent = draft.mode === 'identicon' ? (editing.author ? '由你的公钥确定性生成的 5×5 几何纹,换设备也一样。' : '取得身份后按公钥生成几何纹;现在先以昵称首字代替。') : '';
324
259
  const choose = h('button', { class: 'btn quiet small', type: 'button', onclick: () => editor.file.click() }, cropper.ready || draft.avatar ? '换一张' : '选择图片');
325
260
  const clear = cropper.ready || draft.avatar ? h('button', { class: 'btn danger small', type: 'button', onclick: clearPhoto }, '清除照片') : null;
326
261
  fill(editor.photo, ...(cropper.ready
@@ -370,27 +305,26 @@ async function uploadAvatar(blob, machine) {
370
305
  return normalizeContentPointer({ owner, path, sha256, mime, size, name });
371
306
  }
372
307
  // 发 profile;绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
373
- async function publishBody(body, opts, author, live) {
308
+ async function publishBody(body, opts, author) {
374
309
  try {
375
310
  await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] }, opts);
376
311
  return '名片已发布,好友会看到它';
377
312
  } catch (e) {
378
313
  if (e?.code !== 'forbidden') throw e;
379
314
  await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] }, opts);
380
- // 缓存的 state.profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。已切机就不必查了。
381
- if (!live()) return null;
315
+ // 缓存的 profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。
382
316
  let rooted = null;
383
317
  try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author, limit: 1 }, opts))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
384
318
  return cardFallbackNotice(rooted);
385
319
  }
386
320
  }
387
- // 上传与发布都绑定入口时的机器与代际:途中切了机,仍在原机器做完,但不往新机器的页面写任何状态。
321
+ // 上传与发布都发往入口时定下的那一台;弹层被关掉、重开后,旧会话做完也不往新会话的弹层写任何状态。
388
322
  async function publishCard() {
389
323
  const upload = draft.mode === 'photo' && cropper.ready;
390
324
  let body;
391
325
  try { body = normalizeCardInput(draftFields()); } catch (e) { return say(editor.message, e.message, 'error'); }
392
- const gen = selectionGen, session = editorGen, opts = via(), machine = blobMachine(), author = state.author, live = () => gen === selectionGen;
393
- const current = () => live() && session === editorGen;
326
+ const session = editorGen, { member, author } = editing, opts = via(member), machine = blobMachine(member.id);
327
+ const current = () => session === editorGen;
394
328
  editor.publish.disabled = true;
395
329
  try {
396
330
  if (upload) {
@@ -400,13 +334,14 @@ async function publishCard() {
400
334
  body = { ...body, avatar: await uploadAvatar(blob, machine) };
401
335
  }
402
336
  if (current()) say(editor.message, '正在发布…', 'progress');
403
- const notice = await publishBody(body, opts, author, live);
404
- if (live()) readProfiles();
337
+ const notice = await publishBody(body, opts, author);
338
+ readProfiles(member);
405
339
  if (current()) {
406
340
  // 关弹层会让会话代际自增,所以先恢复按钮。
407
341
  editor.publish.disabled = false;
408
342
  closeDialog();
409
- say(hero.message, notice, 'ok');
343
+ state.heroNotice.set(author ?? '', { kind: 'ok', text: notice });
344
+ draw();
410
345
  }
411
346
  } catch (e) { if (current()) say(editor.message, `没有发布成功:${e.message}`, 'error'); }
412
347
  if (current()) editor.publish.disabled = false;
@@ -425,6 +360,13 @@ const invite = {
425
360
  hidden: {},
426
361
  };
427
362
  invite.dialog = makeDialog({ title: '添加好友', close: '关闭' });
363
+ // 接受邀请和随后的互认都发给打开它的那一节的电脑。
364
+ function openInvite(m) {
365
+ if (invite.target !== m) say(invite.message, '');
366
+ invite.target = m;
367
+ invite.dialog.heading.textContent = multi ? `添加好友 · ${m.name}` : '添加好友';
368
+ showDialog(invite.dialog);
369
+ }
428
370
  invite.dialog.body.append(h('div', { class: 'stack' },
429
371
  h('p', { class: 'hint' }, '暂需由对方提供 friend 角色入网码,后续将支持客户端一键生成邀请。'),
430
372
  invite.paste,
@@ -464,70 +406,65 @@ async function submitInvite() {
464
406
  }
465
407
  // 入网码是凭据:取出后立刻清空所有输入框,不写进任何存储或日志。
466
408
  clearInvite();
467
- const gen = selectionGen, opts = via(), live = () => gen === selectionGen;
409
+ const target = invite.target, opts = via(target), show = (text, kind) => { if (invite.target === target) say(invite.message, text, kind); };
468
410
  invite.button.disabled = true;
469
- say(invite.message, '正在接受邀请,加入对方的通道…', 'progress');
411
+ show('正在接受邀请,加入对方的通道…', 'progress');
470
412
  const peerNode = input.peerNode;
471
413
  let node;
472
414
  try {
473
415
  ({ node } = await coda.call(LOCAL, 'accept', input, opts));
474
416
  } catch (e) {
475
417
  input = null;
476
- if (!live()) return;
477
418
  invite.button.disabled = false;
478
- return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error');
419
+ return show(`接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error');
479
420
  }
480
421
  input = null;
481
- if (live()) say(invite.message, '已加入通道,正在与对方互认…', 'progress');
422
+ show('已加入通道,正在与对方互认…', 'progress');
482
423
  try {
483
424
  await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) }, opts);
484
- if (live()) say(invite.message, '好友已添加并完成互认', 'ok');
485
- } catch (e) { if (live()) say(invite.message, `已加入通道,但互认暂未完成(${e.message})。可稍后在好友详情里点「重新互认」重试`, 'error'); }
486
- if (live()) invite.button.disabled = false;
425
+ show('好友已添加并完成互认', 'ok');
426
+ } catch (e) { show(`已加入通道,但互认暂未完成(${e.message})。可稍后在好友详情里点「重新互认」重试`, 'error'); }
427
+ invite.button.disabled = false;
487
428
  }
488
429
 
489
- // ---- 好友列表与详情 ----
490
- const list = h('div');
491
- const countBadge = h('span', { class: 'count' });
492
- function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, cards: state.cards, notes: state.notes }); }
430
+ // ---- 好友详情:备注、重新互认、移除都发给这一行所在的电脑 ----
431
+ // 不同电脑上的 node 可能相同,忙碌与提示按(电脑, node)记。
432
+ const sectionRows = m => friendSections([m])[0].rows;
493
433
 
494
- async function handshake(row) {
495
- const gen = selectionGen, opts = via();
496
- state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在互认…' }); draw();
434
+ async function handshake(m, row) {
435
+ const key = rowKey(m, row.node);
436
+ state.busy.add(key); state.notice.set(key, { kind: 'progress', text: '正在互认…' }); draw();
497
437
  let notice;
498
- try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }, opts); notice = { kind: 'ok', text: '互认完成' }; }
438
+ try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }, via(m)); notice = { kind: 'ok', text: '互认完成' }; }
499
439
  catch (e) { notice = { kind: 'error', text: `互认失败:${e.message}` }; }
500
- if (gen !== selectionGen) return;
501
- state.notice.set(row.node, notice); state.busy.delete(row.node); draw();
440
+ state.notice.set(key, notice); state.busy.delete(key); draw();
502
441
  }
503
- async function remove(row) {
504
- const gen = selectionGen, opts = via();
505
- state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在移除…' }); draw();
442
+ async function remove(m, row) {
443
+ const key = rowKey(m, row.node);
444
+ state.busy.add(key); state.notice.set(key, { kind: 'progress', text: '正在移除…' }); draw();
506
445
  let failure = null;
507
- try { await coda.call(LOCAL, 'remove', { node: row.node }, opts); }
446
+ try { await coda.call(LOCAL, 'remove', { node: row.node }, via(m)); }
508
447
  catch (e) { failure = { kind: 'error', text: `移除失败:${e.message}` }; }
509
- if (gen !== selectionGen) return;
510
- state.busy.delete(row.node);
511
- if (failure) state.notice.set(row.node, failure);
448
+ state.busy.delete(key);
449
+ if (failure) state.notice.set(key, failure);
512
450
  else {
513
- state.notice.delete(row.node); state.removing = null;
514
- if (state.detail === row.node) closeDialog();
451
+ state.notice.delete(key); state.removing = null;
452
+ if (state.detail?.key === key) closeDialog();
515
453
  }
516
454
  draw();
517
455
  }
518
- async function saveNote(row, text) {
519
- const gen = selectionGen;
520
- state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在保存备注…' }); draw();
456
+ async function saveNote(m, row, text) {
457
+ const key = rowKey(m, row.node);
458
+ state.busy.add(key); state.notice.set(key, { kind: 'progress', text: '正在保存备注…' }); draw();
521
459
  let saved, failure;
522
- try { saved = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); }
460
+ try { saved = await ask(m, text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); }
523
461
  catch (e) { failure = { kind: 'error', text: `备注没存下:${e.message}` }; }
524
- if (gen !== selectionGen) return;
525
- state.busy.delete(row.node);
526
- if (failure) state.notice.set(row.node, failure);
462
+ state.busy.delete(key);
463
+ if (failure) state.notice.set(key, failure);
527
464
  else {
528
- state.notes = saved;
529
- state.notice.set(row.node, { kind: 'ok', text: text.trim() ? '备注已保存' : '备注已清空' });
530
- if (state.detail === row.node) detail.note.value = rows().find(r => r.node === row.node)?.note ?? '';
465
+ m.notes = saved;
466
+ state.notice.set(key, { kind: 'ok', text: text.trim() ? '备注已保存' : '备注已清空' });
467
+ if (state.detail?.key === key) detail.note.value = detailRow()?.note ?? '';
531
468
  }
532
469
  draw();
533
470
  }
@@ -537,7 +474,7 @@ const detail = {
537
474
  card: h('div'),
538
475
  info: h('dl', { class: 'facts' }),
539
476
  note: h('input', { type: 'text', maxlength: '40', placeholder: '备注名(只存在本机,不会发给好友)', autocomplete: 'off',
540
- onkeydown: e => { if (e.key === 'Enter') noteAction(row => saveNote(row, detail.note.value)); } }),
477
+ onkeydown: e => { if (e.key === 'Enter') noteAction(row => saveNote(state.detail.member, row, detail.note.value)); } }),
541
478
  noteButtons: h('div', { class: 'line' }),
542
479
  actions: h('div', { class: 'actions split' }),
543
480
  notice: h('div'),
@@ -545,79 +482,92 @@ const detail = {
545
482
  detail.dialog.body.append(h('div', { class: 'stack' }, detail.card, detail.info,
546
483
  h('div', { class: 'field' }, h('span', { class: 'lbl' }, '本机备注'), h('div', { class: 'line nowrap' }, detail.note, detail.noteButtons)),
547
484
  detail.actions, detail.notice));
548
- const detailRow = () => rows().find(row => row.node === state.detail);
549
- function noteAction(run) { const row = detailRow(); if (row && !state.busy.has(row.node)) run(row); }
550
- function openDetail(row) {
551
- state.detail = row.node; state.removing = null;
485
+ const detailRow = () => state.detail && sectionRows(state.detail.member).find(row => row.node === state.detail.node);
486
+ function noteAction(run) { const row = detailRow(); if (row && !state.busy.has(state.detail.key)) run(row); }
487
+ function openDetail(m, row) {
488
+ state.detail = { member: m, node: row.node, key: rowKey(m, row.node) }; state.removing = null;
552
489
  detail.note.value = row.note;
553
490
  drawDetail();
554
491
  showDialog(detail.dialog);
555
492
  }
556
493
  function fact(label, ...value) { return [h('dt', {}, label), h('dd', { class: 'selectable' }, ...value)]; }
557
- async function copyFriendKey(row) {
558
- const gen = selectionGen;
559
- try { await coda.copy(row.author); if (gen === selectionGen) { state.notice.set(row.node, { kind: 'ok', text: '公钥已复制' }); draw(); } }
560
- catch (e) { if (gen === selectionGen) { state.notice.set(row.node, { kind: 'error', text: `复制失败:${e.message}` }); draw(); } }
494
+ async function copyFriendKey(m, row) {
495
+ const key = rowKey(m, row.node);
496
+ try { await coda.copy(row.author); state.notice.set(key, { kind: 'ok', text: '公钥已复制' }); }
497
+ catch (e) { state.notice.set(key, { kind: 'error', text: `复制失败:${e.message}` }); }
498
+ draw();
561
499
  }
562
500
  function drawDetail() {
563
- const row = detailRow();
501
+ const row = detailRow(), { member: m, key } = state.detail;
564
502
  if (!row) return;
565
- const busy = state.busy.has(row.node), notice = state.notice.get(row.node);
566
- detail.dialog.heading.textContent = row.title;
503
+ const busy = state.busy.has(key), notice = state.notice.get(key);
504
+ detail.dialog.heading.textContent = multi ? `${row.title} · ${m.name}` : row.title;
567
505
  detail.card.replaceChildren(h('div', { class: `mini-card c-${row.color}` }, h('div', { class: 'banner small' }),
568
- h('div', { class: 'mini-body row' }, h('span', { class: 'av-ring lg' }, avatar(rowAvatar(row), 'lg')),
506
+ h('div', { class: 'mini-body row' }, h('span', { class: 'av-ring lg' }, avatar(rowAvatar(m, row), 'lg')),
569
507
  h('div', { class: 'mini-names' }, h('div', { class: 'mini-name truncate selectable' }, row.title),
570
508
  row.note && row.profileName ? h('div', { class: 'secondary truncate selectable' }, `原名 ${row.profileName}`) : null),
571
509
  h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status]))));
572
510
  detail.info.replaceChildren(
573
511
  ...fact('公钥', row.author ? h('span', { class: 'mono key-full' }, row.author) : h('span', { class: 'secondary' }, '密钥未互认'),
574
- row.author ? h('button', { class: 'btn quiet small', type: 'button', onclick: () => copyFriendKey(row) }, '复制公钥') : null),
512
+ row.author ? h('button', { class: 'btn quiet small', type: 'button', onclick: () => copyFriendKey(m, row) }, '复制公钥') : null),
575
513
  ...fact('节点', h('span', { class: 'mono' }, row.peerNode ?? row.node)),
576
514
  ...fact('连接', STATUS_TEXT[row.status]));
577
515
  fill(detail.noteButtons,
578
- h('button', { class: 'btn small', type: 'button', disabled: busy, onclick: () => noteAction(r => saveNote(r, detail.note.value)) }, '保存'),
579
- row.note ? h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => noteAction(r => saveNote(r, '')) }, '清空') : null);
580
- detail.actions.replaceChildren(...(state.removing === row.node
516
+ h('button', { class: 'btn small', type: 'button', disabled: busy, onclick: () => noteAction(r => saveNote(m, r, detail.note.value)) }, '保存'),
517
+ row.note ? h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => noteAction(r => saveNote(m, r, '')) }, '清空') : null);
518
+ detail.actions.replaceChildren(...(state.removing === key
581
519
  ? [h('span', { class: 'secondary' }, '移除后不再同步这位好友,确定吗?'), h('span', { class: 'spacer' }),
582
- h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => remove(row) }, '确认移除'),
520
+ h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => remove(m, row) }, '确认移除'),
583
521
  h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.removing = null; draw(); } }, '再想想')]
584
- : [h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => handshake(row) }, '重新互认'), h('span', { class: 'spacer' }),
585
- h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => { state.removing = row.node; draw(); } }, '移除好友…')]));
522
+ : [h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => handshake(m, row) }, '重新互认'), h('span', { class: 'spacer' }),
523
+ h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => { state.removing = key; draw(); } }, '移除好友…')]));
586
524
  fill(detail.notice,
587
525
  row.status === 'conflict' ? h('p', { class: 'warn-box' }, '对方的密钥与之前互认的不一致,可能换了设备或身份。确认是本人后可「重新互认」,否则建议移除。') : null,
588
526
  notice ? h('p', { class: notice.kind }, notice.text) : null);
589
527
  }
590
528
 
591
- function friendTile(row) {
529
+ function friendTile(m, row) {
592
530
  const secondary = [row.note && row.profileName ? row.profileName : null, row.short ? `@${row.short}` : '密钥未互认'].filter(Boolean).join(' · ');
593
- return h('li', {}, h('button', { class: `f-tile c-${row.color}`, type: 'button', 'aria-label': `${row.title},${STATUS_TEXT[row.status]}`, onclick: () => openDetail(row) },
594
- avatar(rowAvatar(row), 'sm'),
531
+ return h('li', {}, h('button', { class: `f-tile c-${row.color}`, type: 'button', 'aria-label': `${row.title},${STATUS_TEXT[row.status]}`, onclick: () => openDetail(m, row) },
532
+ avatar(rowAvatar(m, row), 'sm'),
595
533
  h('span', { class: 'f-info' }, h('span', { class: 'f-name truncate' }, row.title), h('span', { class: 'f-meta truncate' }, secondary)),
596
534
  h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status])));
597
535
  }
598
536
 
599
- const problem = h('p', { class: 'error selectable' });
537
+ // 每台电脑一节;只有一台时没有节标题,也不重复画名片上已有的状态条和「添加好友」。
538
+ const memberProblems = m => [m.notesProblem, m.problem].filter(Boolean).join(';');
539
+ function drawSection({ member: m, title, unreachable, rows }) {
540
+ const problems = memberProblems(m);
541
+ const down = !unreachable ? null : m.unreachable ? `${m.name} 读不到:${unreachable}` : `${multi ? `${m.name}:` : ''}${unreachable}`;
542
+ const summary = !unreachable && m.loaded ? accordStatusSummary(m.entry, rows) : null;
543
+ // 几台时状态条只在有需要提示的状态(证书有问题、待互认、冲突)时出;只有一台时状态条在名片上。
544
+ const attention = summary && (summary.cert !== 'active' || summary.friends.pending || summary.friends.conflict);
545
+ const empty = !m.loaded ? '正在读取…' : '还没有好友。点上方「添加好友」,粘贴对方发来的邀请即可。';
546
+ return h('section', {},
547
+ h('h2', { class: 'sec' }, title ?? '好友', unreachable ? null : h('span', { class: 'count', hidden: !rows.length }, String(rows.length))),
548
+ down ? h('p', { class: 'error selectable' }, down) : [
549
+ multi && problems ? h('p', { class: 'error selectable' }, problems) : null,
550
+ multi && attention ? statusTiles(m, rows) : null,
551
+ multi ? h('div', { class: 'line' }, h('button', { class: 'pill strong', type: 'button', onclick: () => openInvite(m) }, '添加好友')) : null,
552
+ rows.length ? h('ul', { class: 'friends' }, rows.map(row => friendTile(m, row))) : multi && m.loaded ? null : h('p', { class: 'empty' }, empty)]);
553
+ }
554
+
555
+ const page = h('div', { class: 'page' });
600
556
  function draw() {
601
- const problems = [state.notesProblem, state.problem].filter(Boolean).join(';');
602
- problem.textContent = problems;
603
- problem.hidden = !problems;
604
- const shown = rows();
605
- drawHero(shown);
606
- countBadge.textContent = String(shown.length);
607
- countBadge.hidden = !shown.length;
608
- list.replaceChildren(shown.length ? h('ul', { class: 'friends' }, shown.map(friendTile))
609
- : h('p', { class: 'empty' }, state.loaded ? '还没有好友。点上方「添加好友」,粘贴对方发来的邀请即可。' : '正在读取…'));
610
- if (state.detail !== null) { if (detailRow()) drawDetail(); else closeDialog(); }
557
+ const sections = friendSections(members);
558
+ const ids = identities(live);
559
+ if (!ids.length) ids.push({ author: null, card: null, signer: null, members: [] });
560
+ // 单台时的问题放在页首,和以前一致;几台时各在各的节里。
561
+ const head = multi ? null : memberProblems(members[0] ?? {}) && h('p', { class: 'error selectable' }, memberProblems(members[0]));
562
+ fill(page, head, ids.map(id => drawHero(id, sections)), sections.map(drawSection));
563
+ if (state.detail) { if (detailRow()) drawDetail(); else closeDialog(); }
611
564
  }
612
565
 
613
- root.replaceChildren(h('div', { class: 'page' }, machineBar, problem, hero.card,
614
- h('section', {}, h('h2', { class: 'sec' }, '好友', countBadge), list)),
615
- editor.dialog.scrim, detail.dialog.scrim, invite.dialog.scrim);
616
- drawMachines();
566
+ root.replaceChildren(page, editor.dialog.scrim, detail.dialog.scrim, invite.dialog.scrim);
617
567
  syncEditor();
618
568
  draw();
619
569
 
620
- coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') { state.failedPhotos.clear(); draw(); readProfiles(); } });
570
+ coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') { state.failedPhotos.clear(); for (const m of live) readProfiles(m); draw(); } });
621
571
  coda.toolbar([{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }]).catch(() => {});
622
572
  coda.header({ text: '好友' }).catch(() => {});
623
- start();
573
+ for (const m of live) start(m);
package/view/style.css CHANGED
@@ -64,13 +64,8 @@ details[open] > summary { margin-bottom: 10px; }
64
64
  --c-ink: color-mix(in srgb, var(--c) 78%, var(--fg));
65
65
  }
66
66
 
67
- /* 多机切换条 */
68
- .machines { display: flex; gap: 6px; flex-wrap: wrap; }
69
- .m-pill { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 11px; border: 0; border-radius: 8px; background: var(--fill); color: var(--fg2); font-size: .92em; font-weight: 550; }
70
- .m-pill[aria-pressed="true"] { background: var(--fg); color: var(--bg); }
71
- .m-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--green); }
72
- .m-dot.off { background: var(--fg3); }
73
- .m-why { font-size: .85em; color: var(--fg3); }
67
+ /* 好友按电脑分节 */
68
+ .page > section:not(.hero) > * + * { margin-top: 10px; }
74
69
 
75
70
  /* 点阵柔光渐变 Banner */
76
71
  .banner { position: relative; height: 84px;
@@ -1,42 +0,0 @@
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
- }