@coda-console/friends 0.3.1 → 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/view/app.mjs CHANGED
@@ -1,186 +1,350 @@
1
- // 好友页:本机 Accord 身份与名片、接受好友邀请、好友列表。Accord 的读写(coda/accord@1)都在这里按交互发起;
2
- // 备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用 textContent / DOM API 渲染,不进 innerHTML。
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';
1
+ // 好友页:各台电脑的 Accord 身份与名片(Hero)、编辑名片(含本地选图裁剪上传)、按电脑分节的好友列表与详情、添加好友。
2
+ // 页面不自己选机器:视图里有几台就都读,名片按身份合并、好友按电脑分节(lib/view-members.mjs);写操作发往它所在的那一台。
3
+ // Accord 的读写(coda/accord@1)都在这里按交互发起;备注只经模块存在各台本机。好友的昵称、备注、节点名等外来数据一律用
4
+ // textContent / DOM API 渲染,从不拼 HTML 字符串;头像图片地址只来自 resolveAvatar(经 readContentPointer 白名单校验)。
5
+ import { accordStatusSummary, blobUploadUrl, initialChar, resolveAvatar } from '../lib/avatar.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
+ import { createCropper } from './cropper.mjs';
9
+ import { fill, h, identiconSvg, svg } from './dom.mjs';
6
10
 
7
11
  const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
8
12
  const coda = window.coda;
9
13
  const root = document.getElementById('root');
10
14
  const COLOR_NAMES = { blue: '蓝', orange: '橙', green: '绿', purple: '紫', pink: '粉', teal: '青', gray: '灰' };
11
15
  const STATUS_TEXT = { bound: '已互认', pending: '待互认', conflict: '密钥冲突' };
16
+ const MODES = [['photo', '照片'], ['identicon', '几何纹'], ['emoji', 'Emoji'], ['monogram', '字标']];
17
+ const EMOJIS = ['😀', '😎', '🦊', '🐱', '🐼', '🌿', '☕', '🎧', '🚀', '⚡', '🌙', '✨'];
18
+ const UPLOAD_ERRORS = { 404: '当前客户端还不支持上传头像,请升级 Coda 后再试', 413: '图片太大(超过 5 MiB),请换一张' };
12
19
 
13
- const h = (tag, attrs = {}, ...children) => {
14
- const node = document.createElement(tag);
15
- for (const [key, value] of Object.entries(attrs)) {
16
- if (value === undefined || value === null || value === false) continue;
17
- if (key.startsWith('on')) node.addEventListener(key.slice(2), value); else node.setAttribute(key, value === true ? '' : value);
18
- }
19
- node.append(...children.flat().filter(c => c !== null && c !== undefined && c !== false));
20
- return node;
21
- };
22
-
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;
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
+ // 编辑名片的会话代际:每次打开、关闭编辑弹层自增;旧会话的发布做完后不碰新会话的弹层、按钮、提示和裁剪。
31
+ let editorGen = 0;
32
+ function say(target, text, kind = 'hint') { target.className = kind; target.textContent = text; }
30
33
 
31
- // ---- 备注:经模块存在本机 ----
34
+ // ---- 备注:经各台的模块存在那台本机 ----
32
35
  const pendingReplies = new Map();
33
36
  let counter = 0;
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
- },
51
- });
52
- function ask(type, input = {}) {
53
- const rid = `n${++counter}`, machine = currentMachine;
37
+ function ask(m, type, input = {}) {
38
+ const rid = `n${++counter}`;
54
39
  return new Promise((resolve, reject) => {
40
+ const settle = fn => v => { clearTimeout(timer); pendingReplies.delete(rid); fn(v); };
55
41
  const timer = setTimeout(() => { pendingReplies.delete(rid); reject(new Error('模块没有回应')); }, 10_000);
56
- pendingReplies.set(rid, { machine, resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
57
- 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}`)));
58
44
  });
59
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
+ });
60
52
 
61
- // ---- 读本机 Accord ----
62
- let reading = 0;
53
+ // ---- 读各台的 Accord ----
63
54
  // profile 与 friends/card 各读各的:一种读不到或没有记录,不挡另一种。
64
- async function readProfiles() {
65
- const mine = ++reading;
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 ?? [];
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 ?? [];
70
61
  const failed = [profiles, cards].find(read => read.status === 'rejected');
71
- state.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
72
- if (!own.touched) loadOwn();
62
+ m.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
73
63
  draw();
74
64
  }
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 补);头像随表单带着,重新发布不会把它丢掉或带回已清除的。
79
- function loadOwn() {
80
- const mine = mergeProfileAndCard(latestOwn(state.profiles, readProfileRecord), latestOwn(state.cards, readCardRecord));
81
- if (!mine) return;
82
- Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue', avatar: mine.avatarPresent ? mine.avatar : undefined });
83
- syncOwnForm();
84
- }
85
-
86
- let watching = null;
87
- function onChange({ type, entry }) {
65
+ function onChange(m, { type, entry }) {
88
66
  if (type === 'DELETED' || !entry) return;
89
- state.author = entry.spec?.author ?? null;
90
- state.friends = entry.status?.friends ?? [];
91
- 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}`; }
92
79
  draw();
93
- readProfiles();
94
- }
95
- async function start() {
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; } }
106
- }
107
- if (gen === selectionGen) draw();
108
80
  }
109
81
 
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();
82
+ // ---- 头像 ----
83
+ // 按 resolveAvatar 的描述画头像;图片加载失败记下地址、就地换成它的 fallback,重绘时不再试(点「刷新」清空重试)。
84
+ function avatar(desc, size) {
85
+ const node = h('span', { 'aria-hidden': 'true' });
86
+ const show = d => {
87
+ if (d.kind === 'photo' && state.failedPhotos.has(d.url)) return show(d.fallback);
88
+ node.className = `av ${size} k-${d.kind}`;
89
+ if (d.kind === 'photo') node.replaceChildren(h('img', { src: d.url, alt: '', draggable: 'false', onerror: () => { state.failedPhotos.add(d.url); show(d.fallback); } }));
90
+ else if (d.kind === 'identicon') node.replaceChildren(identiconSvg(d.grid));
91
+ else node.textContent = d.kind === 'emoji' ? d.emoji : d.text;
92
+ };
93
+ show(desc);
94
+ return node;
95
+ }
96
+ const rowAvatar = (m, row) => resolveAvatar({ avatar: row.avatar, emoji: row.emoji, author: row.author, name: row.title, machine: blobMachine(m.id) });
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' },
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 }));
99
+
100
+ // ---- 弹层:宽屏居中模态,窄屏底部抽屉;同一时间只开一个 ----
101
+ let openDialog = null;
102
+ function makeDialog({ title, close: closeLabel, onClose, foot }) {
103
+ const heading = h('h3', {}, title), body = h('div', { class: 'dlg-body' });
104
+ const panel = h('div', { class: 'dialog', role: 'dialog', 'aria-modal': 'true' }, h('div', { class: 'grabber', 'aria-hidden': 'true' }),
105
+ h('div', { class: 'dlg-head' }, heading, h('button', { class: 'btn quiet small', type: 'button', onclick: () => closeDialog() }, closeLabel)),
106
+ body, foot ? h('div', { class: 'dlg-foot' }, foot) : null);
107
+ const scrim = h('div', { class: 'scrim', onclick: e => { if (e.target === scrim) closeDialog(); } }, panel);
108
+ scrim.hidden = true;
109
+ return { scrim, heading, body, onClose };
110
+ }
111
+ function showDialog(dialog) {
112
+ if (openDialog && openDialog !== dialog) closeDialog();
113
+ dialog.scrim.hidden = false;
114
+ openDialog = dialog;
115
+ coda.scroll?.(false)?.catch(() => {});
116
+ }
117
+ function closeDialog() {
118
+ const dialog = openDialog;
119
+ if (!dialog) return;
120
+ openDialog = null;
121
+ dialog.scrim.hidden = true;
122
+ dialog.onClose?.();
123
+ coda.scroll?.(true)?.catch(() => {});
124
+ }
125
+ addEventListener('keydown', e => { if (e.key === 'Escape' && openDialog) closeDialog(); });
126
+
127
+ // ---- 我的名片:每个身份一张 Hero ----
128
+ // 只有一台电脑时,名片上带这台的状态条和「添加好友」;几台时这两样都在各自的节里。
129
+ const CERT = {
130
+ active: { dot: 'ok-dot', text: '可发布' },
131
+ needs_cert: { dot: 'warn-dot', text: '需要证书', sub: '需绑定或续期代签证书:前往客户端「设置 › 身份」处理后再发布名片' },
132
+ no_identity: { dot: 'off-dot', text: '未建身份', sub: '前往客户端「设置 › 身份」创建' },
133
+ };
134
+ const formatTime = ms => new Date(ms).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
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);
137
+ }
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}` }); }
136
176
  draw();
137
- start();
138
177
  }
139
178
 
140
- // ---- 我的身份与名片 ----
141
- const ownForm = {
142
- name: h('input', { type: 'text', maxlength: '40', placeholder: '昵称(1–40 字)', autocomplete: 'off', oninput: e => { own.touched = true; own.name = e.target.value; } }),
143
- emoji: h('input', { type: 'text', placeholder: '头像 Emoji(可选)', autocomplete: 'off', oninput: e => { own.touched = true; own.emoji = e.target.value; } }),
144
- swatches: h('div', { class: 'swatches' }),
179
+ // ---- 编辑名片 ----
180
+ // 正在编辑的名片所属的身份、发往的那一台,和这张名片当前已发布的内容(编辑弹层另有一份草稿,打开时从它拷贝)。
181
+ const blankOwn = () => ({ name: '', emoji: '', color: 'blue', avatar: undefined });
182
+ const own = blankOwn();
183
+ const editing = { author: null, member: null, avatarMachine: null };
184
+ // 草稿:mode 决定头像怎么发;avatar 是沿用的已有图片指针(清除照片后为 null),新选的图在 cropper 里。
185
+ const draft = { name: '', color: 'blue', mode: 'identicon', emoji: '', avatar: null };
186
+ const preview = { canvas: h('canvas', { class: 'preview-canvas', width: 144, height: 144 }) };
187
+ const cropper = createCropper({ onChange: () => { if (draft.mode === 'photo' && cropper.ready) mirrorCrop(); } });
188
+ function mirrorCrop() {
189
+ const ctx = preview.canvas.getContext('2d');
190
+ ctx.clearRect(0, 0, 144, 144);
191
+ ctx.drawImage(cropper.canvas, 0, 0, 144, 144);
192
+ }
193
+ const editor = {
194
+ dialog: null,
195
+ preview: h('div', { class: 'mini-card' }),
196
+ modes: h('div', { class: 'seg', role: 'group', 'aria-label': '头像类型' }),
197
+ file: h('input', { type: 'file', accept: 'image/*', onchange: pickFile }),
198
+ photo: h('div', { class: 'pane' }),
199
+ emoji: h('input', { type: 'text', maxlength: '8', placeholder: '自定义 Emoji(1–8 字)', autocomplete: 'off', oninput: e => { draft.emoji = e.target.value; syncEditor(); } }),
200
+ emojis: h('div', { class: 'emoji-grid' }),
201
+ other: h('p', { class: 'hint' }),
202
+ name: h('input', { type: 'text', maxlength: '40', placeholder: '昵称(1–40 字)', autocomplete: 'off', oninput: e => { draft.name = e.target.value; syncPreview(); } }),
203
+ swatches: h('div', { class: 'swatches', role: 'group', 'aria-label': '主题色' }),
145
204
  message: h('p', { class: 'hint' }),
146
- button: h('button', { class: 'btn', type: 'button', onclick: publishProfile }, '发布名片'),
205
+ publish: h('button', { class: 'btn', type: 'button', onclick: publishCard }, '发布名片'),
147
206
  };
148
- function syncOwnForm() {
149
- ownForm.name.value = own.name; ownForm.emoji.value = own.emoji;
150
- ownForm.swatches.replaceChildren(...COLORS.map(color => h('button', { class: `swatch c-${color}`, type: 'button', 'aria-label': `主题色:${COLOR_NAMES[color]}`, 'aria-pressed': String(own.color === color),
151
- onclick: () => { own.touched = true; own.color = color; syncOwnForm(); } })));
207
+ editor.file.hidden = true;
208
+ editor.emojiPane = h('div', { class: 'pane' }, editor.emojis, editor.emoji);
209
+ editor.dialog = makeDialog({ title: '编辑名片', close: '取消', onClose: () => { editorGen++; cropper.clear(); },
210
+ foot: [editor.message, h('span', { class: 'spacer' }), editor.publish] });
211
+ editor.dialog.body.append(h('div', { class: 'ed-cols' },
212
+ h('div', { class: 'ed-preview' }, editor.preview, h('p', { class: 'hint center' }, '实时预览 · 好友看到的效果')),
213
+ h('div', { class: 'ed-controls' },
214
+ h('span', { class: 'lbl' }, '头像'), editor.modes, editor.file, editor.photo, editor.emojiPane, editor.other,
215
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, '昵称'), editor.name),
216
+ h('div', { class: 'field' }, h('span', { class: 'lbl' }, '主题色'), editor.swatches))));
217
+
218
+ const modeOf = card => (card.avatar ? 'photo' : !card.emoji ? 'identicon' : card.emoji === initialChar(card.name, '') ? 'monogram' : 'emoji');
219
+ // 改名片只发给这个身份的一台(id.signer),页面只确认这一台写入成功;同一身份的其他台要等 Coda 基座同步后才显示新名片(本插件不保证、不检查);头像也上传到这一台。
220
+ function openEditor(id) {
221
+ if (!id.signer) return;
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) });
225
+ cropper.clear();
226
+ editor.publish.disabled = false;
227
+ Object.assign(draft, { name: own.name, color: own.color, mode: modeOf(own), emoji: own.emoji, avatar: own.avatar ?? null });
228
+ editor.name.value = draft.name;
229
+ editor.emoji.value = draft.mode === 'emoji' ? draft.emoji : '';
230
+ if (draft.mode !== 'emoji') draft.emoji = '';
231
+ say(editor.message, '');
232
+ syncEditor();
233
+ showDialog(editor.dialog);
152
234
  }
153
- function say(target, text, kind = 'hint') { target.className = kind; target.textContent = text; }
154
- async function publishProfile() {
235
+ function draftAvatar() {
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 });
238
+ if (draft.mode === 'emoji') return resolveAvatar({ emoji: draft.emoji, author, name });
239
+ if (draft.mode === 'monogram') return { kind: 'monogram', text: initialChar(name) };
240
+ return resolveAvatar({ author, name });
241
+ }
242
+ function syncPreview() {
243
+ const fresh = draft.mode === 'photo' && cropper.ready;
244
+ editor.preview.className = `mini-card c-${draft.color}`;
245
+ editor.preview.replaceChildren(h('div', { class: 'banner small' }),
246
+ h('div', { class: 'mini-body' },
247
+ h('span', { class: 'av-ring md' }, fresh ? h('span', { class: 'av md k-photo' }, preview.canvas) : avatar(draftAvatar(), 'md')),
248
+ h('div', { class: 'mini-name truncate' }, draft.name.trim() || '未命名'),
249
+ editing.author ? h('div', { class: 'mono secondary' }, `@${shortAuthor(editing.author)}`) : null));
250
+ if (fresh) mirrorCrop();
251
+ if (draft.mode === 'monogram') editor.other.textContent = `以昵称首字「${initialChar(draft.name)}」作头像,昵称改了它跟着变。`;
252
+ }
253
+ function syncEditor() {
254
+ editor.modes.replaceChildren(...MODES.map(([mode, label]) => h('button', { type: 'button', 'aria-pressed': String(draft.mode === mode), onclick: () => { draft.mode = mode; syncEditor(); } }, label)));
255
+ editor.photo.hidden = draft.mode !== 'photo';
256
+ editor.emojiPane.hidden = draft.mode !== 'emoji';
257
+ editor.other.hidden = draft.mode !== 'identicon' && draft.mode !== 'monogram';
258
+ editor.other.textContent = draft.mode === 'identicon' ? (editing.author ? '由你的公钥确定性生成的 5×5 几何纹,换设备也一样。' : '取得身份后按公钥生成几何纹;现在先以昵称首字代替。') : '';
259
+ const choose = h('button', { class: 'btn quiet small', type: 'button', onclick: () => editor.file.click() }, cropper.ready || draft.avatar ? '换一张' : '选择图片');
260
+ const clear = cropper.ready || draft.avatar ? h('button', { class: 'btn danger small', type: 'button', onclick: clearPhoto }, '清除照片') : null;
261
+ fill(editor.photo, ...(cropper.ready
262
+ ? [cropper.box, h('div', { class: 'zoom-row' }, h('span', { class: 'secondary' }, '缩放'), cropper.zoom, cropper.zoomText),
263
+ h('div', { class: 'actions' }, choose, h('button', { class: 'btn quiet small', type: 'button', onclick: () => cropper.reset() }, '重置裁切'), clear),
264
+ h('p', { class: 'hint' }, '拖动图片调整位置;发布时导出 512×512 的正方形头像。')]
265
+ : [h('p', { class: 'hint' }, draft.avatar ? '正在使用已发布的照片。' : '从本机选一张图片,裁剪成正方形头像。'), h('div', { class: 'actions' }, choose, clear)]));
266
+ editor.emojis.replaceChildren(...EMOJIS.map(mark => h('button', { type: 'button', class: 'emoji-opt', 'aria-label': `Emoji ${mark}`, 'aria-pressed': String(draft.emoji === mark),
267
+ onclick: () => { draft.emoji = mark; editor.emoji.value = mark; syncEditor(); } }, mark)));
268
+ editor.swatches.replaceChildren(...COLORS.map(color => h('button', { class: `swatch c-${color}`, type: 'button', 'aria-label': `主题色:${COLOR_NAMES[color]}`, 'aria-pressed': String(draft.color === color),
269
+ onclick: () => { draft.color = color; syncEditor(); } })));
270
+ syncPreview();
271
+ }
272
+ function pickFile(e) {
273
+ const file = e.target.files?.[0];
274
+ e.target.value = '';
275
+ if (!file) return;
276
+ say(editor.message, '');
277
+ cropper.load(file).then(loaded => { if (loaded) { draft.mode = 'photo'; syncEditor(); } }, error => { say(editor.message, error.message, 'error'); syncEditor(); });
278
+ }
279
+ function clearPhoto() {
280
+ cropper.clear();
281
+ draft.avatar = null;
282
+ draft.mode = 'identicon';
283
+ syncEditor();
284
+ }
285
+ // 发布用的名片字段:原名片有图而这次不用照片,就显式写 avatar: null 清除;照片模式没换图就沿用已有指针,不重复上传。
286
+ function draftFields() {
287
+ const fields = { name: draft.name, color: draft.color }, drop = own.avatar ? null : undefined;
288
+ if (draft.mode === 'photo') {
289
+ if (!cropper.ready && !draft.avatar) throw new Error('请先选择一张图片,或换用其他头像类型');
290
+ return { ...fields, emoji: own.emoji, avatar: cropper.ready ? undefined : draft.avatar };
291
+ }
292
+ if (draft.mode === 'emoji') {
293
+ if (!draft.emoji.trim()) throw new Error('请选一个或输入一个 Emoji');
294
+ return { ...fields, emoji: draft.emoji, avatar: drop };
295
+ }
296
+ // 字标不扩协议:把昵称首字写进 emoji,双方都按 emoji 显示。
297
+ return { ...fields, emoji: draft.mode === 'monogram' ? initialChar(draft.name, '') : undefined, avatar: drop };
298
+ }
299
+ async function uploadAvatar(blob, machine) {
300
+ let response;
301
+ try { response = await fetch(blobUploadUrl(machine), { method: 'POST', headers: { 'Content-Type': blob.type }, body: blob }); }
302
+ catch (e) { throw new Error(`头像上传失败(网络错误:${e.message})`); }
303
+ if (!response.ok) throw new Error(UPLOAD_ERRORS[response.status] ?? `头像上传失败(HTTP ${response.status})`);
304
+ const { owner, path, sha256, mime, size, name } = await response.json();
305
+ return normalizeContentPointer({ owner, path, sha256, mime, size, name });
306
+ }
307
+ // 发 profile;绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
308
+ async function publishBody(body, opts, author) {
309
+ try {
310
+ await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] }, opts);
311
+ return '名片已发布,好友会看到它';
312
+ } catch (e) {
313
+ if (e?.code !== 'forbidden') throw e;
314
+ await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] }, opts);
315
+ // 缓存的 profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。
316
+ let rooted = null;
317
+ try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author, limit: 1 }, opts))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
318
+ return cardFallbackNotice(rooted);
319
+ }
320
+ }
321
+ // 上传与发布都发往入口时定下的那一台;弹层被关掉、重开后,旧会话做完也不往新会话的弹层写任何状态。
322
+ async function publishCard() {
323
+ const upload = draft.mode === 'photo' && cropper.ready;
155
324
  let body;
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;
158
- ownForm.button.disabled = true;
159
- say(ownForm.message, '正在发布…', 'progress');
325
+ try { body = normalizeCardInput(draftFields()); } catch (e) { return say(editor.message, e.message, 'error'); }
326
+ const session = editorGen, { member, author } = editing, opts = via(member), machine = blobMachine(member.id);
327
+ const current = () => session === editorGen;
328
+ editor.publish.disabled = true;
160
329
  try {
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
- }
330
+ if (upload) {
331
+ say(editor.message, '正在处理图片…', 'progress');
332
+ const blob = await cropper.export();
333
+ if (current()) say(editor.message, '正在上传头像…', 'progress');
334
+ body = { ...body, avatar: await uploadAvatar(blob, machine) };
174
335
  }
175
- if (live()) readProfiles();
176
- } catch (e) { if (live()) say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
177
- if (live()) ownForm.button.disabled = false;
178
- }
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' }) };
180
- async function copyKey() {
181
- if (!state.author) return;
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'); }
336
+ if (current()) say(editor.message, '正在发布…', 'progress');
337
+ const notice = await publishBody(body, opts, author);
338
+ readProfiles(member);
339
+ if (current()) {
340
+ // 关弹层会让会话代际自增,所以先恢复按钮。
341
+ editor.publish.disabled = false;
342
+ closeDialog();
343
+ state.heroNotice.set(author ?? '', { kind: 'ok', text: notice });
344
+ draw();
345
+ }
346
+ } catch (e) { if (current()) say(editor.message, `没有发布成功:${e.message}`, 'error'); }
347
+ if (current()) editor.publish.disabled = false;
184
348
  }
185
349
 
186
350
  // ---- 添加好友 ----
@@ -195,6 +359,24 @@ const invite = {
195
359
  button: h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受邀请'),
196
360
  hidden: {},
197
361
  };
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
+ }
370
+ invite.dialog.body.append(h('div', { class: 'stack' },
371
+ h('p', { class: 'hint' }, '暂需由对方提供 friend 角色入网码,后续将支持客户端一键生成邀请。'),
372
+ invite.paste,
373
+ h('details', {}, h('summary', {}, '分字段填写'), h('div', { class: 'fields' },
374
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'control(入网地址)'), invite.control),
375
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'authKey(入网码)'), invite.authKey),
376
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'linkId'), invite.linkId),
377
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'scope'), invite.scope),
378
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'peerNode'), invite.peerNode))),
379
+ h('div', { class: 'line' }, invite.button), invite.message));
198
380
  // hostname、peerPort 只随识别出的那份邀请:手改入网地址或入网码就是另一份邀请了,丢掉;改 linkId、scope、peerNode 不算。
199
381
  function dropHidden() { invite.hidden = {}; }
200
382
  function parsePaste() {
@@ -224,130 +406,168 @@ async function submitInvite() {
224
406
  }
225
407
  // 入网码是凭据:取出后立刻清空所有输入框,不写进任何存储或日志。
226
408
  clearInvite();
227
- 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); };
228
410
  invite.button.disabled = true;
229
- say(invite.message, '正在接受邀请,加入对方的通道…', 'progress');
411
+ show('正在接受邀请,加入对方的通道…', 'progress');
230
412
  const peerNode = input.peerNode;
231
413
  let node;
232
414
  try {
233
415
  ({ node } = await coda.call(LOCAL, 'accept', input, opts));
234
416
  } catch (e) {
235
417
  input = null;
236
- if (!live()) return;
237
418
  invite.button.disabled = false;
238
- return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error');
419
+ return show(`接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error');
239
420
  }
240
421
  input = null;
241
- if (live()) say(invite.message, '已加入通道,正在与对方互认…', 'progress');
422
+ show('已加入通道,正在与对方互认…', 'progress');
242
423
  try {
243
424
  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;
425
+ show('好友已添加并完成互认', 'ok');
426
+ } catch (e) { show(`已加入通道,但互认暂未完成(${e.message})。可稍后在好友详情里点「重新互认」重试`, 'error'); }
427
+ invite.button.disabled = false;
247
428
  }
248
429
 
249
- // ---- 好友列表 ----
250
- const list = h('div');
251
- const countBadge = h('span', { class: 'count' });
252
- 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;
253
433
 
254
- async function handshake(row) {
255
- const gen = selectionGen, opts = via();
256
- 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();
257
437
  let notice;
258
- 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: '互认完成' }; }
259
439
  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();
440
+ state.notice.set(key, notice); state.busy.delete(key); draw();
262
441
  }
263
- async function remove(row) {
264
- const gen = selectionGen, opts = via();
265
- 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();
266
445
  let failure = null;
267
- try { await coda.call(LOCAL, 'remove', { node: row.node }, opts); }
446
+ try { await coda.call(LOCAL, 'remove', { node: row.node }, via(m)); }
268
447
  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; }
271
- state.busy.delete(row.node); draw();
448
+ state.busy.delete(key);
449
+ if (failure) state.notice.set(key, failure);
450
+ else {
451
+ state.notice.delete(key); state.removing = null;
452
+ if (state.detail?.key === key) closeDialog();
453
+ }
454
+ draw();
272
455
  }
273
- async function saveNote(row, text) {
274
- const gen = selectionGen;
275
- state.editing = null;
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();
276
459
  let saved, failure;
277
- 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 }); }
278
461
  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); }
462
+ state.busy.delete(key);
463
+ if (failure) state.notice.set(key, failure);
464
+ else {
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 ?? '';
468
+ }
281
469
  draw();
282
470
  }
283
471
 
284
- function friendRow(row) {
285
- const busy = state.busy.has(row.node), notice = state.notice.get(row.node);
286
- const avatar = h('div', { class: `avatar c-${row.color}`, 'aria-hidden': 'true' }, row.emoji || [...(row.note || row.profileName || '友')][0]);
287
- const names = h('div', { class: 'who' },
288
- h('span', { class: 'title truncate selectable' }, row.title),
289
- row.note && row.profileName ? h('span', { class: 'secondary truncate selectable' }, row.profileName) : null,
290
- h('span', { class: 'secondary mono truncate selectable' }, [row.short ? `ed25519:${row.short}` : '密钥未互认', row.peerNode ?? row.node].join(' · ')));
291
- const head = h('div', { class: 'line' }, avatar, names, h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status]));
292
- let body;
293
- if (state.editing === row.node) {
294
- const input = h('input', { type: 'text', maxlength: '40', value: row.note, placeholder: '备注名(只存在本机,不会发给好友)', autocomplete: 'off',
295
- onkeydown: e => { if (e.key === 'Enter') saveNote(row, input.value); else if (e.key === 'Escape') { state.editing = null; draw(); } } });
296
- body = h('div', { class: 'line' }, input,
297
- h('button', { class: 'btn small', type: 'button', onclick: () => saveNote(row, input.value) }, '保存'),
298
- h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.editing = null; draw(); } }, '取消'));
299
- queueMicrotask(() => input.focus());
300
- } else if (state.removing === row.node) {
301
- body = h('div', { class: 'actions' }, h('span', { class: 'secondary' }, '移除后不再同步这位好友,确定吗?'),
302
- h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => remove(row) }, '确认移除'),
303
- h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.removing = null; draw(); } }, '取消'));
304
- } else {
305
- body = h('div', { class: 'actions' },
306
- h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.editing = row.node; draw(); } }, row.note ? '改备注' : '备注'),
307
- h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => handshake(row) }, '互认'),
308
- h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => { state.removing = row.node; draw(); } }, '移除'));
309
- }
310
- return h('li', { class: 'row' }, head, body, notice ? h('p', { class: notice.kind }, notice.text) : null);
472
+ const detail = {
473
+ dialog: makeDialog({ title: '好友', close: '完成', onClose: () => { state.detail = null; state.removing = null; } }),
474
+ card: h('div'),
475
+ info: h('dl', { class: 'facts' }),
476
+ note: h('input', { type: 'text', maxlength: '40', placeholder: '备注名(只存在本机,不会发给好友)', autocomplete: 'off',
477
+ onkeydown: e => { if (e.key === 'Enter') noteAction(row => saveNote(state.detail.member, row, detail.note.value)); } }),
478
+ noteButtons: h('div', { class: 'line' }),
479
+ actions: h('div', { class: 'actions split' }),
480
+ notice: h('div'),
481
+ };
482
+ detail.dialog.body.append(h('div', { class: 'stack' }, detail.card, detail.info,
483
+ h('div', { class: 'field' }, h('span', { class: 'lbl' }, '本机备注'), h('div', { class: 'line nowrap' }, detail.note, detail.noteButtons)),
484
+ detail.actions, detail.notice));
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;
489
+ detail.note.value = row.note;
490
+ drawDetail();
491
+ showDialog(detail.dialog);
492
+ }
493
+ function fact(label, ...value) { return [h('dt', {}, label), h('dd', { class: 'selectable' }, ...value)]; }
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();
499
+ }
500
+ function drawDetail() {
501
+ const row = detailRow(), { member: m, key } = state.detail;
502
+ if (!row) return;
503
+ const busy = state.busy.has(key), notice = state.notice.get(key);
504
+ detail.dialog.heading.textContent = multi ? `${row.title} · ${m.name}` : row.title;
505
+ detail.card.replaceChildren(h('div', { class: `mini-card c-${row.color}` }, h('div', { class: 'banner small' }),
506
+ h('div', { class: 'mini-body row' }, h('span', { class: 'av-ring lg' }, avatar(rowAvatar(m, row), 'lg')),
507
+ h('div', { class: 'mini-names' }, h('div', { class: 'mini-name truncate selectable' }, row.title),
508
+ row.note && row.profileName ? h('div', { class: 'secondary truncate selectable' }, `原名 ${row.profileName}`) : null),
509
+ h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status]))));
510
+ detail.info.replaceChildren(
511
+ ...fact('公钥', row.author ? h('span', { class: 'mono key-full' }, row.author) : h('span', { class: 'secondary' }, '密钥未互认'),
512
+ row.author ? h('button', { class: 'btn quiet small', type: 'button', onclick: () => copyFriendKey(m, row) }, '复制公钥') : null),
513
+ ...fact('节点', h('span', { class: 'mono' }, row.peerNode ?? row.node)),
514
+ ...fact('连接', STATUS_TEXT[row.status]));
515
+ fill(detail.noteButtons,
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
519
+ ? [h('span', { class: 'secondary' }, '移除后不再同步这位好友,确定吗?'), h('span', { class: 'spacer' }),
520
+ h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => remove(m, row) }, '确认移除'),
521
+ h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.removing = null; 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(); } }, '移除好友…')]));
524
+ fill(detail.notice,
525
+ row.status === 'conflict' ? h('p', { class: 'warn-box' }, '对方的密钥与之前互认的不一致,可能换了设备或身份。确认是本人后可「重新互认」,否则建议移除。') : null,
526
+ notice ? h('p', { class: notice.kind }, notice.text) : null);
527
+ }
528
+
529
+ function friendTile(m, row) {
530
+ const secondary = [row.note && row.profileName ? row.profileName : null, row.short ? `@${row.short}` : '密钥未互认'].filter(Boolean).join(' · ');
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'),
533
+ h('span', { class: 'f-info' }, h('span', { class: 'f-name truncate' }, row.title), h('span', { class: 'f-meta truncate' }, secondary)),
534
+ h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status])));
535
+ }
536
+
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)]);
311
553
  }
312
554
 
313
- const problem = h('p', { class: 'error selectable' });
555
+ const page = h('div', { class: 'page' });
314
556
  function draw() {
315
- const problems = [state.notesProblem, state.problem].filter(Boolean).join(';');
316
- problem.textContent = problems;
317
- problem.hidden = !problems;
318
- identity.key.textContent = state.author ? `ed25519:${shortAuthor(state.author)}…` : state.loaded ? '未取得' : '读取中…';
319
- identity.copy.disabled = !state.author;
320
- const shown = rows();
321
- countBadge.textContent = String(shown.length);
322
- countBadge.hidden = !shown.length;
323
- list.replaceChildren(shown.length ? h('ul', { class: 'list' }, shown.map(friendRow))
324
- : h('p', { class: 'empty' }, state.loaded ? '还没有好友。在上面粘贴对方发来的邀请即可添加。' : '正在读取…'));
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(); }
325
564
  }
326
565
 
327
- root.replaceChildren(h('div', { class: 'page' }, machineBar, problem,
328
- h('section', {}, h('h2', {}, '我的身份与名片'), h('div', { class: 'card' },
329
- h('div', { class: 'line identity' }, h('span', { class: 'secondary' }, '本机公钥'), identity.key, h('span', { class: 'spacer' }), identity.copy), identity.message,
330
- h('div', { class: 'fields' }, h('label', { class: 'field' }, h('span', {}, '昵称'), ownForm.name), h('label', { class: 'field' }, h('span', {}, '头像'), ownForm.emoji)),
331
- h('div', { class: 'field' }, h('span', { class: 'secondary' }, '主题色'), ownForm.swatches),
332
- h('div', { class: 'line' }, ownForm.button), ownForm.message,
333
- h('p', { class: 'hint' }, '名片对所有人公开,只含昵称、头像和主题色。'))),
334
- h('section', {}, h('h2', {}, '添加好友'), h('div', { class: 'card' },
335
- h('p', { class: 'hint' }, '暂需由对方提供 friend 角色入网码,后续将支持客户端一键生成邀请。'),
336
- invite.paste,
337
- h('details', {}, h('summary', {}, '分字段填写'), h('div', { class: 'fields' },
338
- h('label', { class: 'field' }, h('span', {}, 'control(入网地址)'), invite.control),
339
- h('label', { class: 'field' }, h('span', {}, 'authKey(入网码)'), invite.authKey),
340
- h('label', { class: 'field' }, h('span', {}, 'linkId'), invite.linkId),
341
- h('label', { class: 'field' }, h('span', {}, 'scope'), invite.scope),
342
- h('label', { class: 'field' }, h('span', {}, 'peerNode'), invite.peerNode))),
343
- h('div', { class: 'line' }, invite.button), invite.message)),
344
- h('section', {}, h('h2', {}, '好友', countBadge), list)));
345
- syncOwnForm();
346
- drawMachines();
566
+ root.replaceChildren(page, editor.dialog.scrim, detail.dialog.scrim, invite.dialog.scrim);
567
+ syncEditor();
347
568
  draw();
348
569
 
349
- function refresh() { readProfiles(); }
350
- coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') refresh(); });
570
+ coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') { state.failedPhotos.clear(); for (const m of live) readProfiles(m); draw(); } });
351
571
  coda.toolbar([{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }]).catch(() => {});
352
572
  coda.header({ text: '好友' }).catch(() => {});
353
- start();
573
+ for (const m of live) start(m);