@coda-console/friends 0.3.0 → 0.4.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,41 +1,63 @@
1
- // 好友页:本机 Accord 身份与名片、接受好友邀请、好友列表。Accord 的读写(coda/accord@1)都在这里按交互发起;
2
- // 备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用 textContent / DOM API 渲染,不进 innerHTML。
3
- import { Bridge } from 'coda-view://lib/v1/bridge.js';
4
- import { CARD_KIND, COLORS, cardFallbackNotice, checked, mergeFriendRows, mergeProfileAndCard, normalizeProfileInput, parseInvite, readCardRecord, readProfileRecord,
5
- shortAuthor } from '../lib/friends.mjs';
1
+ // 好友页:本机 Accord 身份与名片(Hero + 状态条)、编辑名片(含本地选图裁剪上传)、好友列表与详情、添加好友。
2
+ // Accord 的读写(coda/accord@1)都在这里按交互发起;备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用
3
+ // textContent / DOM API 渲染,从不拼 HTML 字符串;头像图片地址只来自 resolveAvatar(经 readContentPointer 白名单校验)。
4
+ 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';
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
- const coda = window.coda, bridge = new Bridge();
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 state = { author: null, friends: [], profiles: [], cards: [], notes: {}, loaded: false, problem: null, editing: null, removing: null, busy: new Set(), notice: new Map() };
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
+ // 编辑名片的会话代际:每次打开、关闭编辑弹层或切机自增;旧会话的发布做完后不碰新会话的弹层、按钮、提示和裁剪。
32
+ let editorGen = 0;
33
+ function say(target, text, kind = 'hint') { target.className = kind; target.textContent = text; }
24
34
 
25
35
  // ---- 备注:经模块存在本机 ----
26
36
  const pendingReplies = new Map();
27
37
  let counter = 0;
28
- bridge.on('reply', ({ rid, ok, value, error }) => {
29
- const wait = pendingReplies.get(rid);
30
- if (!wait) return;
31
- pendingReplies.delete(rid);
32
- if (ok) wait.resolve(value); else wait.reject(new Error(error));
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
+ },
33
55
  });
34
56
  function ask(type, input = {}) {
35
- const rid = `n${++counter}`;
57
+ const rid = `n${++counter}`, machine = currentMachine;
36
58
  return new Promise((resolve, reject) => {
37
59
  const timer = setTimeout(() => { pendingReplies.delete(rid); reject(new Error('模块没有回应')); }, 10_000);
38
- pendingReplies.set(rid, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
60
+ pendingReplies.set(rid, { machine, resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
39
61
  bridge.send({ type, rid, ...input });
40
62
  });
41
63
  }
@@ -45,28 +67,29 @@ let reading = 0;
45
67
  // profile 与 friends/card 各读各的:一种读不到或没有记录,不挡另一种。
46
68
  async function readProfiles() {
47
69
  const mine = ++reading;
48
- const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 })));
70
+ const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 }, via())));
49
71
  if (mine !== reading) return;
50
72
  if (profiles.status === 'fulfilled') state.profiles = profiles.value?.records ?? [];
51
73
  if (cards.status === 'fulfilled') state.cards = cards.value?.records ?? [];
52
74
  const failed = [profiles, cards].find(read => read.status === 'rejected');
53
75
  state.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
54
- if (!own.touched) loadOwn();
76
+ loadOwn();
55
77
  draw();
56
78
  }
57
- const own = { touched: false, name: '', emoji: '', color: 'blue', avatar: undefined };
79
+ // 本机已发布的名片(Hero 展示它);编辑弹层另有一份草稿,打开时从它拷贝。
80
+ const blankOwn = () => ({ name: '', emoji: '', color: 'blue', avatar: undefined });
81
+ const own = blankOwn();
58
82
  const latestOwn = (records, read) => records.map(read).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
59
- // 本机名片:与好友列表同一条合并规则(profile 写了的优先,缺的由 friends/card 补);头像随表单带着,重新发布不会把它丢掉或带回已清除的。
83
+ // 与好友列表同一条合并规则(profile 写了的优先,缺的由 friends/card 补);头像随名片带着,重新发布不会把它丢掉或带回已清除的。
60
84
  function loadOwn() {
61
85
  const mine = mergeProfileAndCard(latestOwn(state.profiles, readProfileRecord), latestOwn(state.cards, readCardRecord));
62
- if (!mine) return;
63
- Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue', avatar: mine.avatarPresent ? mine.avatar : undefined });
64
- syncOwnForm();
86
+ if (mine) Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue', avatar: mine.avatarPresent ? mine.avatar : undefined });
65
87
  }
66
88
 
67
- let watched = false;
89
+ let watching = null;
68
90
  function onChange({ type, entry }) {
69
91
  if (type === 'DELETED' || !entry) return;
92
+ state.entry = entry;
70
93
  state.author = entry.spec?.author ?? null;
71
94
  state.friends = entry.status?.friends ?? [];
72
95
  state.loaded = true;
@@ -74,55 +97,319 @@ function onChange({ type, entry }) {
74
97
  readProfiles();
75
98
  }
76
99
  async function start() {
77
- try { state.notes = await ask('notes.list'); } catch (e) { state.problem = `读不到本地备注:${e.message}`; }
78
- if (!watched) {
79
- watched = true;
80
- try { await coda.watch(ACCORD, onChange, { id: 'local' }); }
81
- catch (e) { watched = false; state.problem = `读不到本机的好友信息:${e.message}`; state.loaded = true; }
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; } }
82
110
  }
111
+ if (gen === selectionGen) draw();
112
+ }
113
+
114
+ // ---- 头像 ----
115
+ // 按 resolveAvatar 的描述画头像;图片加载失败记下地址、就地换成它的 fallback,重绘时不再试(点「刷新」清空重试)。
116
+ function avatar(desc, size) {
117
+ const node = h('span', { 'aria-hidden': 'true' });
118
+ const show = d => {
119
+ if (d.kind === 'photo' && state.failedPhotos.has(d.url)) return show(d.fallback);
120
+ node.className = `av ${size} k-${d.kind}`;
121
+ if (d.kind === 'photo') node.replaceChildren(h('img', { src: d.url, alt: '', draggable: 'false', onerror: () => { state.failedPhotos.add(d.url); show(d.fallback); } }));
122
+ else if (d.kind === 'identicon') node.replaceChildren(identiconSvg(d.grid));
123
+ else node.textContent = d.kind === 'emoji' ? d.emoji : d.text;
124
+ };
125
+ show(desc);
126
+ return node;
127
+ }
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() });
130
+ 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
+ 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
+
133
+ // ---- 弹层:宽屏居中模态,窄屏底部抽屉;同一时间只开一个 ----
134
+ let openDialog = null;
135
+ function makeDialog({ title, close: closeLabel, onClose, foot }) {
136
+ const heading = h('h3', {}, title), body = h('div', { class: 'dlg-body' });
137
+ const panel = h('div', { class: 'dialog', role: 'dialog', 'aria-modal': 'true' }, h('div', { class: 'grabber', 'aria-hidden': 'true' }),
138
+ h('div', { class: 'dlg-head' }, heading, h('button', { class: 'btn quiet small', type: 'button', onclick: () => closeDialog() }, closeLabel)),
139
+ body, foot ? h('div', { class: 'dlg-foot' }, foot) : null);
140
+ const scrim = h('div', { class: 'scrim', onclick: e => { if (e.target === scrim) closeDialog(); } }, panel);
141
+ scrim.hidden = true;
142
+ return { scrim, heading, body, onClose };
143
+ }
144
+ function showDialog(dialog) {
145
+ if (openDialog && openDialog !== dialog) closeDialog();
146
+ dialog.scrim.hidden = false;
147
+ openDialog = dialog;
148
+ coda.scroll?.(false)?.catch(() => {});
149
+ }
150
+ function closeDialog() {
151
+ const dialog = openDialog;
152
+ if (!dialog) return;
153
+ openDialog = null;
154
+ dialog.scrim.hidden = true;
155
+ dialog.onClose?.();
156
+ coda.scroll?.(true)?.catch(() => {});
157
+ }
158
+ addEventListener('keydown', e => { if (e.key === 'Escape' && openDialog) closeDialog(); });
159
+
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();
83
190
  draw();
191
+ start();
84
192
  }
85
193
 
86
- // ---- 我的身份与名片 ----
87
- const ownForm = {
88
- name: h('input', { type: 'text', maxlength: '40', placeholder: '昵称(1–40 字)', autocomplete: 'off', oninput: e => { own.touched = true; own.name = e.target.value; } }),
89
- emoji: h('input', { type: 'text', placeholder: '头像 Emoji(可选)', autocomplete: 'off', oninput: e => { own.touched = true; own.emoji = e.target.value; } }),
90
- swatches: h('div', { class: 'swatches' }),
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' }),
91
201
  message: h('p', { class: 'hint' }),
92
- button: h('button', { class: 'btn', type: 'button', onclick: publishProfile }, '发布名片'),
202
+ friends: h('div', { class: 'tile' }),
203
+ cert: h('div', { class: 'tile' }),
93
204
  };
94
- function syncOwnForm() {
95
- ownForm.name.value = own.name; ownForm.emoji.value = own.emoji;
96
- 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),
97
- onclick: () => { own.touched = true; own.color = color; syncOwnForm(); } })));
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)));
213
+ const CERT = {
214
+ active: { dot: 'ok-dot', text: '可发布' },
215
+ needs_cert: { dot: 'warn-dot', text: '需要证书', sub: '需绑定或续期代签证书:前往客户端「设置 › 身份」处理后再发布名片' },
216
+ no_identity: { dot: 'off-dot', text: '未建身份', sub: '前往客户端「设置 › 身份」创建' },
217
+ };
218
+ 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);
98
221
  }
99
- function say(target, text, kind = 'hint') { target.className = kind; target.textContent = text; }
100
- async function publishProfile() {
101
- let body;
102
- try { body = normalizeProfileInput(own); } catch (e) { return say(ownForm.message, e.message, 'error'); }
103
- ownForm.button.disabled = true;
104
- say(ownForm.message, '正在发布…', 'progress');
105
- try {
106
- try {
107
- await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] });
108
- say(ownForm.message, '名片已发布,好友会看到它', 'ok');
109
- } catch (e) {
110
- // 绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
111
- if (e?.code !== 'forbidden') throw e;
112
- await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] });
113
- // 缓存的 state.profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。
114
- let rooted = null;
115
- try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author: state.author, limit: 1 }))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
116
- say(ownForm.message, cardFallbackNotice(rooted), 'ok');
117
- }
118
- readProfiles();
119
- } catch (e) { say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
120
- ownForm.button.disabled = false;
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);
121
245
  }
122
- const identity = { key: h('span', { class: 'key mono selectable' }), copy: h('button', { class: 'btn quiet small', type: 'button', onclick: copyKey }, '复制公钥'), message: h('p', { class: 'hint' }) };
123
246
  async function copyKey() {
124
247
  if (!state.author) return;
125
- try { await coda.copy(state.author); say(identity.message, '公钥已复制', 'ok'); } catch (e) { say(identity.message, `复制失败:${e.message}`, 'error'); }
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'); }
250
+ }
251
+
252
+ // ---- 编辑名片 ----
253
+ // 草稿:mode 决定头像怎么发;avatar 是沿用的已有图片指针(清除照片后为 null),新选的图在 cropper 里。
254
+ const draft = { name: '', color: 'blue', mode: 'identicon', emoji: '', avatar: null };
255
+ const preview = { canvas: h('canvas', { class: 'preview-canvas', width: 144, height: 144 }) };
256
+ const cropper = createCropper({ onChange: () => { if (draft.mode === 'photo' && cropper.ready) mirrorCrop(); } });
257
+ function mirrorCrop() {
258
+ const ctx = preview.canvas.getContext('2d');
259
+ ctx.clearRect(0, 0, 144, 144);
260
+ ctx.drawImage(cropper.canvas, 0, 0, 144, 144);
261
+ }
262
+ const editor = {
263
+ dialog: null,
264
+ preview: h('div', { class: 'mini-card' }),
265
+ modes: h('div', { class: 'seg', role: 'group', 'aria-label': '头像类型' }),
266
+ file: h('input', { type: 'file', accept: 'image/*', onchange: pickFile }),
267
+ photo: h('div', { class: 'pane' }),
268
+ emoji: h('input', { type: 'text', maxlength: '8', placeholder: '自定义 Emoji(1–8 字)', autocomplete: 'off', oninput: e => { draft.emoji = e.target.value; syncEditor(); } }),
269
+ emojis: h('div', { class: 'emoji-grid' }),
270
+ other: h('p', { class: 'hint' }),
271
+ name: h('input', { type: 'text', maxlength: '40', placeholder: '昵称(1–40 字)', autocomplete: 'off', oninput: e => { draft.name = e.target.value; syncPreview(); } }),
272
+ swatches: h('div', { class: 'swatches', role: 'group', 'aria-label': '主题色' }),
273
+ message: h('p', { class: 'hint' }),
274
+ publish: h('button', { class: 'btn', type: 'button', onclick: publishCard }, '发布名片'),
275
+ };
276
+ editor.file.hidden = true;
277
+ editor.emojiPane = h('div', { class: 'pane' }, editor.emojis, editor.emoji);
278
+ editor.dialog = makeDialog({ title: '编辑名片', close: '取消', onClose: () => { editorGen++; cropper.clear(); },
279
+ foot: [editor.message, h('span', { class: 'spacer' }), editor.publish] });
280
+ editor.dialog.body.append(h('div', { class: 'ed-cols' },
281
+ h('div', { class: 'ed-preview' }, editor.preview, h('p', { class: 'hint center' }, '实时预览 · 好友看到的效果')),
282
+ h('div', { class: 'ed-controls' },
283
+ h('span', { class: 'lbl' }, '头像'), editor.modes, editor.file, editor.photo, editor.emojiPane, editor.other,
284
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, '昵称'), editor.name),
285
+ h('div', { class: 'field' }, h('span', { class: 'lbl' }, '主题色'), editor.swatches))));
286
+
287
+ const modeOf = card => (card.avatar ? 'photo' : !card.emoji ? 'identicon' : card.emoji === initialChar(card.name, '') ? 'monogram' : 'emoji');
288
+ function openEditor() {
289
+ editorGen++;
290
+ cropper.clear();
291
+ editor.publish.disabled = false;
292
+ Object.assign(draft, { name: own.name, color: own.color, mode: modeOf(own), emoji: own.emoji, avatar: own.avatar ?? null });
293
+ editor.name.value = draft.name;
294
+ editor.emoji.value = draft.mode === 'emoji' ? draft.emoji : '';
295
+ if (draft.mode !== 'emoji') draft.emoji = '';
296
+ say(editor.message, '');
297
+ syncEditor();
298
+ showDialog(editor.dialog);
299
+ }
300
+ 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() });
303
+ if (draft.mode === 'emoji') return resolveAvatar({ emoji: draft.emoji, author, name });
304
+ if (draft.mode === 'monogram') return { kind: 'monogram', text: initialChar(name) };
305
+ return resolveAvatar({ author, name });
306
+ }
307
+ function syncPreview() {
308
+ const fresh = draft.mode === 'photo' && cropper.ready;
309
+ editor.preview.className = `mini-card c-${draft.color}`;
310
+ editor.preview.replaceChildren(h('div', { class: 'banner small' }),
311
+ h('div', { class: 'mini-body' },
312
+ h('span', { class: 'av-ring md' }, fresh ? h('span', { class: 'av md k-photo' }, preview.canvas) : avatar(draftAvatar(), 'md')),
313
+ h('div', { class: 'mini-name truncate' }, draft.name.trim() || '未命名'),
314
+ state.author ? h('div', { class: 'mono secondary' }, `@${shortAuthor(state.author)}`) : null));
315
+ if (fresh) mirrorCrop();
316
+ if (draft.mode === 'monogram') editor.other.textContent = `以昵称首字「${initialChar(draft.name)}」作头像,昵称改了它跟着变。`;
317
+ }
318
+ function syncEditor() {
319
+ editor.modes.replaceChildren(...MODES.map(([mode, label]) => h('button', { type: 'button', 'aria-pressed': String(draft.mode === mode), onclick: () => { draft.mode = mode; syncEditor(); } }, label)));
320
+ editor.photo.hidden = draft.mode !== 'photo';
321
+ editor.emojiPane.hidden = draft.mode !== 'emoji';
322
+ editor.other.hidden = draft.mode !== 'identicon' && draft.mode !== 'monogram';
323
+ editor.other.textContent = draft.mode === 'identicon' ? (state.author ? '由你的公钥确定性生成的 5×5 几何纹,换设备也一样。' : '取得身份后按公钥生成几何纹;现在先以昵称首字代替。') : '';
324
+ const choose = h('button', { class: 'btn quiet small', type: 'button', onclick: () => editor.file.click() }, cropper.ready || draft.avatar ? '换一张' : '选择图片');
325
+ const clear = cropper.ready || draft.avatar ? h('button', { class: 'btn danger small', type: 'button', onclick: clearPhoto }, '清除照片') : null;
326
+ fill(editor.photo, ...(cropper.ready
327
+ ? [cropper.box, h('div', { class: 'zoom-row' }, h('span', { class: 'secondary' }, '缩放'), cropper.zoom, cropper.zoomText),
328
+ h('div', { class: 'actions' }, choose, h('button', { class: 'btn quiet small', type: 'button', onclick: () => cropper.reset() }, '重置裁切'), clear),
329
+ h('p', { class: 'hint' }, '拖动图片调整位置;发布时导出 512×512 的正方形头像。')]
330
+ : [h('p', { class: 'hint' }, draft.avatar ? '正在使用已发布的照片。' : '从本机选一张图片,裁剪成正方形头像。'), h('div', { class: 'actions' }, choose, clear)]));
331
+ editor.emojis.replaceChildren(...EMOJIS.map(mark => h('button', { type: 'button', class: 'emoji-opt', 'aria-label': `Emoji ${mark}`, 'aria-pressed': String(draft.emoji === mark),
332
+ onclick: () => { draft.emoji = mark; editor.emoji.value = mark; syncEditor(); } }, mark)));
333
+ 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),
334
+ onclick: () => { draft.color = color; syncEditor(); } })));
335
+ syncPreview();
336
+ }
337
+ function pickFile(e) {
338
+ const file = e.target.files?.[0];
339
+ e.target.value = '';
340
+ if (!file) return;
341
+ say(editor.message, '');
342
+ cropper.load(file).then(loaded => { if (loaded) { draft.mode = 'photo'; syncEditor(); } }, error => { say(editor.message, error.message, 'error'); syncEditor(); });
343
+ }
344
+ function clearPhoto() {
345
+ cropper.clear();
346
+ draft.avatar = null;
347
+ draft.mode = 'identicon';
348
+ syncEditor();
349
+ }
350
+ // 发布用的名片字段:原名片有图而这次不用照片,就显式写 avatar: null 清除;照片模式没换图就沿用已有指针,不重复上传。
351
+ function draftFields() {
352
+ const fields = { name: draft.name, color: draft.color }, drop = own.avatar ? null : undefined;
353
+ if (draft.mode === 'photo') {
354
+ if (!cropper.ready && !draft.avatar) throw new Error('请先选择一张图片,或换用其他头像类型');
355
+ return { ...fields, emoji: own.emoji, avatar: cropper.ready ? undefined : draft.avatar };
356
+ }
357
+ if (draft.mode === 'emoji') {
358
+ if (!draft.emoji.trim()) throw new Error('请选一个或输入一个 Emoji');
359
+ return { ...fields, emoji: draft.emoji, avatar: drop };
360
+ }
361
+ // 字标不扩协议:把昵称首字写进 emoji,双方都按 emoji 显示。
362
+ return { ...fields, emoji: draft.mode === 'monogram' ? initialChar(draft.name, '') : undefined, avatar: drop };
363
+ }
364
+ async function uploadAvatar(blob, machine) {
365
+ let response;
366
+ try { response = await fetch(blobUploadUrl(machine), { method: 'POST', headers: { 'Content-Type': blob.type }, body: blob }); }
367
+ catch (e) { throw new Error(`头像上传失败(网络错误:${e.message})`); }
368
+ if (!response.ok) throw new Error(UPLOAD_ERRORS[response.status] ?? `头像上传失败(HTTP ${response.status})`);
369
+ const { owner, path, sha256, mime, size, name } = await response.json();
370
+ return normalizeContentPointer({ owner, path, sha256, mime, size, name });
371
+ }
372
+ // 发 profile;绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
373
+ async function publishBody(body, opts, author, live) {
374
+ try {
375
+ await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] }, opts);
376
+ return '名片已发布,好友会看到它';
377
+ } catch (e) {
378
+ if (e?.code !== 'forbidden') throw e;
379
+ await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] }, opts);
380
+ // 缓存的 state.profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。已切机就不必查了。
381
+ if (!live()) return null;
382
+ let rooted = null;
383
+ try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author, limit: 1 }, opts))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
384
+ return cardFallbackNotice(rooted);
385
+ }
386
+ }
387
+ // 上传与发布都绑定入口时的机器与代际:途中切了机,仍在原机器做完,但不往新机器的页面写任何状态。
388
+ async function publishCard() {
389
+ const upload = draft.mode === 'photo' && cropper.ready;
390
+ let body;
391
+ 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;
394
+ editor.publish.disabled = true;
395
+ try {
396
+ if (upload) {
397
+ say(editor.message, '正在处理图片…', 'progress');
398
+ const blob = await cropper.export();
399
+ if (current()) say(editor.message, '正在上传头像…', 'progress');
400
+ body = { ...body, avatar: await uploadAvatar(blob, machine) };
401
+ }
402
+ if (current()) say(editor.message, '正在发布…', 'progress');
403
+ const notice = await publishBody(body, opts, author, live);
404
+ if (live()) readProfiles();
405
+ if (current()) {
406
+ // 关弹层会让会话代际自增,所以先恢复按钮。
407
+ editor.publish.disabled = false;
408
+ closeDialog();
409
+ say(hero.message, notice, 'ok');
410
+ }
411
+ } catch (e) { if (current()) say(editor.message, `没有发布成功:${e.message}`, 'error'); }
412
+ if (current()) editor.publish.disabled = false;
126
413
  }
127
414
 
128
415
  // ---- 添加好友 ----
@@ -137,6 +424,17 @@ const invite = {
137
424
  button: h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受邀请'),
138
425
  hidden: {},
139
426
  };
427
+ invite.dialog = makeDialog({ title: '添加好友', close: '关闭' });
428
+ invite.dialog.body.append(h('div', { class: 'stack' },
429
+ h('p', { class: 'hint' }, '暂需由对方提供 friend 角色入网码,后续将支持客户端一键生成邀请。'),
430
+ invite.paste,
431
+ h('details', {}, h('summary', {}, '分字段填写'), h('div', { class: 'fields' },
432
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'control(入网地址)'), invite.control),
433
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'authKey(入网码)'), invite.authKey),
434
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'linkId'), invite.linkId),
435
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'scope'), invite.scope),
436
+ h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'peerNode'), invite.peerNode))),
437
+ h('div', { class: 'line' }, invite.button), invite.message));
140
438
  // hostname、peerPort 只随识别出的那份邀请:手改入网地址或入网码就是另一份邀请了,丢掉;改 linkId、scope、peerNode 不算。
141
439
  function dropHidden() { invite.hidden = {}; }
142
440
  function parsePaste() {
@@ -166,111 +464,160 @@ async function submitInvite() {
166
464
  }
167
465
  // 入网码是凭据:取出后立刻清空所有输入框,不写进任何存储或日志。
168
466
  clearInvite();
467
+ const gen = selectionGen, opts = via(), live = () => gen === selectionGen;
169
468
  invite.button.disabled = true;
170
469
  say(invite.message, '正在接受邀请,加入对方的通道…', 'progress');
171
470
  const peerNode = input.peerNode;
172
471
  let node;
173
472
  try {
174
- ({ node } = await coda.call(LOCAL, 'accept', input));
175
- } catch (e) { input = null; invite.button.disabled = false; return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error'); }
473
+ ({ node } = await coda.call(LOCAL, 'accept', input, opts));
474
+ } catch (e) {
475
+ input = null;
476
+ if (!live()) return;
477
+ invite.button.disabled = false;
478
+ return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error');
479
+ }
176
480
  input = null;
177
- say(invite.message, '已加入通道,正在与对方互认…', 'progress');
481
+ if (live()) say(invite.message, '已加入通道,正在与对方互认…', 'progress');
178
482
  try {
179
- await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) });
180
- say(invite.message, '好友已添加并完成互认', 'ok');
181
- } catch (e) { say(invite.message, `已加入通道,但互认暂未完成(${e.message})。可稍后在好友列表点「互认」重试`, 'error'); }
182
- invite.button.disabled = false;
483
+ 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;
183
487
  }
184
488
 
185
- // ---- 好友列表 ----
489
+ // ---- 好友列表与详情 ----
186
490
  const list = h('div');
187
491
  const countBadge = h('span', { class: 'count' });
188
492
  function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, cards: state.cards, notes: state.notes }); }
189
493
 
190
494
  async function handshake(row) {
495
+ const gen = selectionGen, opts = via();
191
496
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在互认…' }); draw();
192
- try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }); state.notice.set(row.node, { kind: 'ok', text: '互认完成' }); }
193
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `互认失败:${e.message}` }); }
194
- state.busy.delete(row.node); draw();
497
+ let notice;
498
+ try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }, opts); notice = { kind: 'ok', text: '互认完成' }; }
499
+ 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();
195
502
  }
196
503
  async function remove(row) {
504
+ const gen = selectionGen, opts = via();
197
505
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在移除…' }); draw();
198
- try { await coda.call(LOCAL, 'remove', { node: row.node }); state.notice.delete(row.node); state.removing = null; }
199
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `移除失败:${e.message}` }); }
200
- state.busy.delete(row.node); draw();
506
+ let failure = null;
507
+ try { await coda.call(LOCAL, 'remove', { node: row.node }, opts); }
508
+ 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);
512
+ else {
513
+ state.notice.delete(row.node); state.removing = null;
514
+ if (state.detail === row.node) closeDialog();
515
+ }
516
+ draw();
201
517
  }
202
518
  async function saveNote(row, text) {
203
- state.editing = null;
204
- try { state.notes = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); state.notice.delete(row.node); }
205
- catch (e) { state.notice.set(row.node, { kind: 'error', text: `备注没存下:${e.message}` }); }
519
+ const gen = selectionGen;
520
+ state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在保存备注…' }); draw();
521
+ let saved, failure;
522
+ try { saved = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); }
523
+ 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);
527
+ 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 ?? '';
531
+ }
206
532
  draw();
207
533
  }
208
534
 
209
- function friendRow(row) {
535
+ const detail = {
536
+ dialog: makeDialog({ title: '好友', close: '完成', onClose: () => { state.detail = null; state.removing = null; } }),
537
+ card: h('div'),
538
+ info: h('dl', { class: 'facts' }),
539
+ note: h('input', { type: 'text', maxlength: '40', placeholder: '备注名(只存在本机,不会发给好友)', autocomplete: 'off',
540
+ onkeydown: e => { if (e.key === 'Enter') noteAction(row => saveNote(row, detail.note.value)); } }),
541
+ noteButtons: h('div', { class: 'line' }),
542
+ actions: h('div', { class: 'actions split' }),
543
+ notice: h('div'),
544
+ };
545
+ detail.dialog.body.append(h('div', { class: 'stack' }, detail.card, detail.info,
546
+ h('div', { class: 'field' }, h('span', { class: 'lbl' }, '本机备注'), h('div', { class: 'line nowrap' }, detail.note, detail.noteButtons)),
547
+ 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;
552
+ detail.note.value = row.note;
553
+ drawDetail();
554
+ showDialog(detail.dialog);
555
+ }
556
+ 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(); } }
561
+ }
562
+ function drawDetail() {
563
+ const row = detailRow();
564
+ if (!row) return;
210
565
  const busy = state.busy.has(row.node), notice = state.notice.get(row.node);
211
- const avatar = h('div', { class: `avatar c-${row.color}`, 'aria-hidden': 'true' }, row.emoji || [...(row.note || row.profileName || '友')][0]);
212
- const names = h('div', { class: 'who' },
213
- h('span', { class: 'title truncate selectable' }, row.title),
214
- row.note && row.profileName ? h('span', { class: 'secondary truncate selectable' }, row.profileName) : null,
215
- h('span', { class: 'secondary mono truncate selectable' }, [row.short ? `ed25519:${row.short}` : '密钥未互认', row.peerNode ?? row.node].join(' · ')));
216
- const head = h('div', { class: 'line' }, avatar, names, h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status]));
217
- let body;
218
- if (state.editing === row.node) {
219
- const input = h('input', { type: 'text', maxlength: '40', value: row.note, placeholder: '备注名(只存在本机,不会发给好友)', autocomplete: 'off',
220
- onkeydown: e => { if (e.key === 'Enter') saveNote(row, input.value); else if (e.key === 'Escape') { state.editing = null; draw(); } } });
221
- body = h('div', { class: 'line' }, input,
222
- h('button', { class: 'btn small', type: 'button', onclick: () => saveNote(row, input.value) }, '保存'),
223
- h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.editing = null; draw(); } }, '取消'));
224
- queueMicrotask(() => input.focus());
225
- } else if (state.removing === row.node) {
226
- body = h('div', { class: 'actions' }, h('span', { class: 'secondary' }, '移除后不再同步这位好友,确定吗?'),
566
+ detail.dialog.heading.textContent = row.title;
567
+ 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')),
569
+ h('div', { class: 'mini-names' }, h('div', { class: 'mini-name truncate selectable' }, row.title),
570
+ row.note && row.profileName ? h('div', { class: 'secondary truncate selectable' }, `原名 ${row.profileName}`) : null),
571
+ h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status]))));
572
+ detail.info.replaceChildren(
573
+ ...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),
575
+ ...fact('节点', h('span', { class: 'mono' }, row.peerNode ?? row.node)),
576
+ ...fact('连接', STATUS_TEXT[row.status]));
577
+ 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
581
+ ? [h('span', { class: 'secondary' }, '移除后不再同步这位好友,确定吗?'), h('span', { class: 'spacer' }),
227
582
  h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => remove(row) }, '确认移除'),
228
- h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.removing = null; draw(); } }, '取消'));
229
- } else {
230
- body = h('div', { class: 'actions' },
231
- h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.editing = row.node; draw(); } }, row.note ? '改备注' : '备注'),
232
- h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => handshake(row) }, '互认'),
233
- h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => { state.removing = row.node; draw(); } }, '移除'));
234
- }
235
- return h('li', { class: 'row' }, head, body, notice ? h('p', { class: notice.kind }, notice.text) : null);
583
+ 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(); } }, '移除好友…')]));
586
+ fill(detail.notice,
587
+ row.status === 'conflict' ? h('p', { class: 'warn-box' }, '对方的密钥与之前互认的不一致,可能换了设备或身份。确认是本人后可「重新互认」,否则建议移除。') : null,
588
+ notice ? h('p', { class: notice.kind }, notice.text) : null);
589
+ }
590
+
591
+ function friendTile(row) {
592
+ 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'),
595
+ h('span', { class: 'f-info' }, h('span', { class: 'f-name truncate' }, row.title), h('span', { class: 'f-meta truncate' }, secondary)),
596
+ h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status])));
236
597
  }
237
598
 
238
599
  const problem = h('p', { class: 'error selectable' });
239
600
  function draw() {
240
- problem.textContent = state.problem ?? '';
241
- problem.hidden = !state.problem;
242
- identity.key.textContent = state.author ? `ed25519:${shortAuthor(state.author)}…` : state.loaded ? '未取得' : '读取中…';
243
- identity.copy.disabled = !state.author;
601
+ const problems = [state.notesProblem, state.problem].filter(Boolean).join(';');
602
+ problem.textContent = problems;
603
+ problem.hidden = !problems;
244
604
  const shown = rows();
605
+ drawHero(shown);
245
606
  countBadge.textContent = String(shown.length);
246
607
  countBadge.hidden = !shown.length;
247
- list.replaceChildren(shown.length ? h('ul', { class: 'list' }, shown.map(friendRow))
248
- : h('p', { class: 'empty' }, state.loaded ? '还没有好友。在上面粘贴对方发来的邀请即可添加。' : '正在读取…'));
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(); }
249
611
  }
250
612
 
251
- root.replaceChildren(h('div', { class: 'page' }, problem,
252
- h('section', {}, h('h2', {}, '我的身份与名片'), h('div', { class: 'card' },
253
- h('div', { class: 'line identity' }, h('span', { class: 'secondary' }, '本机公钥'), identity.key, h('span', { class: 'spacer' }), identity.copy), identity.message,
254
- h('div', { class: 'fields' }, h('label', { class: 'field' }, h('span', {}, '昵称'), ownForm.name), h('label', { class: 'field' }, h('span', {}, '头像'), ownForm.emoji)),
255
- h('div', { class: 'field' }, h('span', { class: 'secondary' }, '主题色'), ownForm.swatches),
256
- h('div', { class: 'line' }, ownForm.button), ownForm.message,
257
- h('p', { class: 'hint' }, '名片对所有人公开,只含昵称、头像和主题色。'))),
258
- h('section', {}, h('h2', {}, '添加好友'), h('div', { class: 'card' },
259
- h('p', { class: 'hint' }, '暂需由对方提供 friend 角色入网码,后续将支持客户端一键生成邀请。'),
260
- invite.paste,
261
- h('details', {}, h('summary', {}, '分字段填写'), h('div', { class: 'fields' },
262
- h('label', { class: 'field' }, h('span', {}, 'control(入网地址)'), invite.control),
263
- h('label', { class: 'field' }, h('span', {}, 'authKey(入网码)'), invite.authKey),
264
- h('label', { class: 'field' }, h('span', {}, 'linkId'), invite.linkId),
265
- h('label', { class: 'field' }, h('span', {}, 'scope'), invite.scope),
266
- h('label', { class: 'field' }, h('span', {}, 'peerNode'), invite.peerNode))),
267
- h('div', { class: 'line' }, invite.button), invite.message)),
268
- h('section', {}, h('h2', {}, '好友', countBadge), list)));
269
- syncOwnForm();
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();
617
+ syncEditor();
270
618
  draw();
271
619
 
272
- function refresh() { readProfiles(); }
273
- coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') refresh(); });
620
+ coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') { state.failedPhotos.clear(); draw(); readProfiles(); } });
274
621
  coda.toolbar([{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }]).catch(() => {});
275
622
  coda.header({ text: '好友' }).catch(() => {});
276
623
  start();