@coda-console/friends 0.0.0 → 0.2.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 ADDED
@@ -0,0 +1,259 @@
1
+ // 好友页:本机 Accord 身份与名片、接受好友邀请、好友列表。Accord 的读写(coda/accord@1)都在这里按交互发起;
2
+ // 备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用 textContent / DOM API 渲染,不进 innerHTML。
3
+ import { Bridge } from 'coda-view://lib/v1/bridge.js';
4
+ import { COLORS, checked, mergeFriendRows, normalizeProfileInput, parseInvite, readProfileRecord, shortAuthor } from '../lib/friends.mjs';
5
+
6
+ const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
7
+ const coda = window.coda, bridge = new Bridge();
8
+ const root = document.getElementById('root');
9
+ const COLOR_NAMES = { blue: '蓝', orange: '橙', green: '绿', purple: '紫', pink: '粉', teal: '青', gray: '灰' };
10
+ const STATUS_TEXT = { bound: '已互认', pending: '待互认', conflict: '密钥冲突' };
11
+
12
+ const h = (tag, attrs = {}, ...children) => {
13
+ const node = document.createElement(tag);
14
+ for (const [key, value] of Object.entries(attrs)) {
15
+ if (value === undefined || value === null || value === false) continue;
16
+ if (key.startsWith('on')) node.addEventListener(key.slice(2), value); else node.setAttribute(key, value === true ? '' : value);
17
+ }
18
+ node.append(...children.flat().filter(c => c !== null && c !== undefined && c !== false));
19
+ return node;
20
+ };
21
+
22
+ const state = { author: null, friends: [], profiles: [], notes: {}, loaded: false, problem: null, editing: null, removing: null, busy: new Set(), notice: new Map() };
23
+
24
+ // ---- 备注:经模块存在本机 ----
25
+ const pendingReplies = new Map();
26
+ let counter = 0;
27
+ bridge.on('reply', ({ rid, ok, value, error }) => {
28
+ const wait = pendingReplies.get(rid);
29
+ if (!wait) return;
30
+ pendingReplies.delete(rid);
31
+ if (ok) wait.resolve(value); else wait.reject(new Error(error));
32
+ });
33
+ function ask(type, input = {}) {
34
+ const rid = `n${++counter}`;
35
+ return new Promise((resolve, reject) => {
36
+ const timer = setTimeout(() => { pendingReplies.delete(rid); reject(new Error('模块没有回应')); }, 10_000);
37
+ pendingReplies.set(rid, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
38
+ bridge.send({ type, rid, ...input });
39
+ });
40
+ }
41
+
42
+ // ---- 读本机 Accord ----
43
+ let reading = 0;
44
+ async function readProfiles() {
45
+ const mine = ++reading;
46
+ try {
47
+ const { records } = await coda.query(LOCAL, 'records', { kind: 'profile', limit: 200 });
48
+ if (mine !== reading) return;
49
+ state.profiles = records;
50
+ state.problem = null;
51
+ if (!own.touched) loadOwn();
52
+ } catch (e) { if (mine === reading) state.problem = `读不到好友名片:${e.message}`; }
53
+ draw();
54
+ }
55
+ const own = { touched: false, name: '', emoji: '', color: 'blue' };
56
+ function loadOwn() {
57
+ const mine = state.profiles.map(readProfileRecord).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
58
+ if (!mine) return;
59
+ Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue' });
60
+ syncOwnForm();
61
+ }
62
+
63
+ let watched = false;
64
+ function onChange({ type, entry }) {
65
+ if (type === 'DELETED' || !entry) return;
66
+ state.author = entry.spec?.author ?? null;
67
+ state.friends = entry.status?.friends ?? [];
68
+ state.loaded = true;
69
+ draw();
70
+ readProfiles();
71
+ }
72
+ async function start() {
73
+ try { state.notes = await ask('notes.list'); } catch (e) { state.problem = `读不到本地备注:${e.message}`; }
74
+ if (!watched) {
75
+ watched = true;
76
+ try { await coda.watch(ACCORD, onChange, { id: 'local' }); }
77
+ catch (e) { watched = false; state.problem = `读不到本机的好友信息:${e.message}`; state.loaded = true; }
78
+ }
79
+ draw();
80
+ }
81
+
82
+ // ---- 我的身份与名片 ----
83
+ const ownForm = {
84
+ name: h('input', { type: 'text', maxlength: '40', placeholder: '昵称(1–40 字)', autocomplete: 'off', oninput: e => { own.touched = true; own.name = e.target.value; } }),
85
+ emoji: h('input', { type: 'text', placeholder: '头像 Emoji(可选)', autocomplete: 'off', oninput: e => { own.touched = true; own.emoji = e.target.value; } }),
86
+ swatches: h('div', { class: 'swatches' }),
87
+ message: h('p', { class: 'hint' }),
88
+ button: h('button', { class: 'btn', type: 'button', onclick: publishProfile }, '发布名片'),
89
+ };
90
+ function syncOwnForm() {
91
+ ownForm.name.value = own.name; ownForm.emoji.value = own.emoji;
92
+ 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),
93
+ onclick: () => { own.touched = true; own.color = color; syncOwnForm(); } })));
94
+ }
95
+ function say(target, text, kind = 'hint') { target.className = kind; target.textContent = text; }
96
+ async function publishProfile() {
97
+ let body;
98
+ try { body = normalizeProfileInput(own); } catch (e) { return say(ownForm.message, e.message, 'error'); }
99
+ ownForm.button.disabled = true;
100
+ say(ownForm.message, '正在发布…', 'progress');
101
+ try {
102
+ await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] });
103
+ say(ownForm.message, '名片已发布,好友会看到它', 'ok');
104
+ readProfiles();
105
+ } catch (e) { say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
106
+ ownForm.button.disabled = false;
107
+ }
108
+ const identity = { key: h('span', { class: 'key mono selectable' }), copy: h('button', { class: 'btn quiet small', type: 'button', onclick: copyKey }, '复制公钥'), message: h('p', { class: 'hint' }) };
109
+ async function copyKey() {
110
+ if (!state.author) return;
111
+ try { await coda.copy(state.author); say(identity.message, '公钥已复制', 'ok'); } catch (e) { say(identity.message, `复制失败:${e.message}`, 'error'); }
112
+ }
113
+
114
+ // ---- 添加好友 ----
115
+ const invite = {
116
+ paste: h('textarea', { placeholder: '粘贴邀请:JSON、coda-friend:// 链接,或多行 control=… / authKey=…', autocomplete: 'off', spellcheck: 'false', oninput: parsePaste }),
117
+ control: h('input', { type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://…' }),
118
+ authKey: h('input', { type: 'password', autocomplete: 'off', spellcheck: 'false', placeholder: '入网码,提交后立即清空' }),
119
+ linkId: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空自动生成' }),
120
+ scope: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空用本机空间' }),
121
+ peerNode: h('input', { type: 'text', autocomplete: 'off', placeholder: '可选' }),
122
+ message: h('p', { class: 'hint' }),
123
+ button: h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受邀请'),
124
+ hidden: {},
125
+ };
126
+ function parsePaste() {
127
+ const text = invite.paste.value;
128
+ if (!text.trim()) return say(invite.message, '', 'hint');
129
+ try {
130
+ const found = parseInvite(text);
131
+ for (const name of ['control', 'authKey', 'scope', 'peerNode']) if (found[name]) invite[name].value = found[name];
132
+ if (found.linkId && !/^f-[0-9a-f]{8}$/.test(found.linkId)) invite.linkId.value = found.linkId;
133
+ invite.hidden.hostname = found.hostname ?? '';
134
+ say(invite.message, '已识别邀请,核对后点「接受邀请」', 'ok');
135
+ } catch (e) { say(invite.message, e.message, 'error'); }
136
+ }
137
+ function clearInvite() {
138
+ for (const name of ['paste', 'control', 'authKey', 'linkId', 'scope', 'peerNode']) invite[name].value = '';
139
+ invite.hidden = {};
140
+ }
141
+ async function submitInvite() {
142
+ let input;
143
+ try {
144
+ input = checked({ control: invite.control.value, authKey: invite.authKey.value, linkId: invite.linkId.value, scope: invite.scope.value,
145
+ peerNode: invite.peerNode.value, hostname: invite.hidden.hostname });
146
+ } catch (e) {
147
+ // 只填了粘贴区、还没有识别出来:再试着从粘贴区解析一次。
148
+ try { input = parseInvite(invite.paste.value); } catch { return say(invite.message, e.message, 'error'); }
149
+ }
150
+ // 入网码是凭据:取出后立刻清空所有输入框,不写进任何存储或日志。
151
+ clearInvite();
152
+ invite.button.disabled = true;
153
+ say(invite.message, '正在接受邀请,加入对方的通道…', 'progress');
154
+ const peerNode = input.peerNode;
155
+ let node;
156
+ try {
157
+ ({ node } = await coda.call(LOCAL, 'accept', input));
158
+ } catch (e) { input = null; invite.button.disabled = false; return say(invite.message, `接受邀请失败:${e.message}。入网码已清空,请重新粘贴邀请再试`, 'error'); }
159
+ input = null;
160
+ say(invite.message, '已加入通道,正在与对方互认…', 'progress');
161
+ try {
162
+ await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) });
163
+ say(invite.message, '好友已添加并完成互认', 'ok');
164
+ } catch (e) { say(invite.message, `已加入通道,但互认暂未完成(${e.message})。可稍后在好友列表点「互认」重试`, 'error'); }
165
+ invite.button.disabled = false;
166
+ }
167
+
168
+ // ---- 好友列表 ----
169
+ const list = h('div');
170
+ const countBadge = h('span', { class: 'count' });
171
+ function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, notes: state.notes }); }
172
+
173
+ async function handshake(row) {
174
+ state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在互认…' }); draw();
175
+ try { await coda.call(LOCAL, 'handshake', { node: row.node, ...(row.peerNode ? { peerNode: row.peerNode } : {}) }); state.notice.set(row.node, { kind: 'ok', text: '互认完成' }); }
176
+ catch (e) { state.notice.set(row.node, { kind: 'error', text: `互认失败:${e.message}` }); }
177
+ state.busy.delete(row.node); draw();
178
+ }
179
+ async function remove(row) {
180
+ state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在移除…' }); draw();
181
+ try { await coda.call(LOCAL, 'remove', { node: row.node }); state.notice.delete(row.node); state.removing = null; }
182
+ catch (e) { state.notice.set(row.node, { kind: 'error', text: `移除失败:${e.message}` }); }
183
+ state.busy.delete(row.node); draw();
184
+ }
185
+ async function saveNote(row, text) {
186
+ state.editing = null;
187
+ try { state.notes = await ask(text.trim() ? 'notes.set' : 'notes.delete', { node: row.node, note: text }); state.notice.delete(row.node); }
188
+ catch (e) { state.notice.set(row.node, { kind: 'error', text: `备注没存下:${e.message}` }); }
189
+ draw();
190
+ }
191
+
192
+ function friendRow(row) {
193
+ const busy = state.busy.has(row.node), notice = state.notice.get(row.node);
194
+ const avatar = h('div', { class: `avatar c-${row.color}`, 'aria-hidden': 'true' }, row.emoji || [...(row.note || row.profileName || '友')][0]);
195
+ const names = h('div', { class: 'who' },
196
+ h('span', { class: 'title truncate selectable' }, row.title),
197
+ row.note && row.profileName ? h('span', { class: 'secondary truncate selectable' }, row.profileName) : null,
198
+ h('span', { class: 'secondary mono truncate selectable' }, [row.short ? `ed25519:${row.short}` : '密钥未互认', row.peerNode ?? row.node].join(' · ')));
199
+ const head = h('div', { class: 'line' }, avatar, names, h('span', { class: `badge ${row.status}` }, STATUS_TEXT[row.status]));
200
+ let body;
201
+ if (state.editing === row.node) {
202
+ const input = h('input', { type: 'text', maxlength: '40', value: row.note, placeholder: '备注名(只存在本机,不会发给好友)', autocomplete: 'off',
203
+ onkeydown: e => { if (e.key === 'Enter') saveNote(row, input.value); else if (e.key === 'Escape') { state.editing = null; draw(); } } });
204
+ body = h('div', { class: 'line' }, input,
205
+ h('button', { class: 'btn small', type: 'button', onclick: () => saveNote(row, input.value) }, '保存'),
206
+ h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.editing = null; draw(); } }, '取消'));
207
+ queueMicrotask(() => input.focus());
208
+ } else if (state.removing === row.node) {
209
+ body = h('div', { class: 'actions' }, h('span', { class: 'secondary' }, '移除后不再同步这位好友,确定吗?'),
210
+ h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => remove(row) }, '确认移除'),
211
+ h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.removing = null; draw(); } }, '取消'));
212
+ } else {
213
+ body = h('div', { class: 'actions' },
214
+ h('button', { class: 'btn quiet small', type: 'button', onclick: () => { state.editing = row.node; draw(); } }, row.note ? '改备注' : '备注'),
215
+ h('button', { class: 'btn quiet small', type: 'button', disabled: busy, onclick: () => handshake(row) }, '互认'),
216
+ h('button', { class: 'btn danger small', type: 'button', disabled: busy, onclick: () => { state.removing = row.node; draw(); } }, '移除'));
217
+ }
218
+ return h('li', { class: 'row' }, head, body, notice ? h('p', { class: notice.kind }, notice.text) : null);
219
+ }
220
+
221
+ const problem = h('p', { class: 'error selectable' });
222
+ function draw() {
223
+ problem.textContent = state.problem ?? '';
224
+ problem.hidden = !state.problem;
225
+ identity.key.textContent = state.author ? `ed25519:${shortAuthor(state.author)}…` : state.loaded ? '未取得' : '读取中…';
226
+ identity.copy.disabled = !state.author;
227
+ const shown = rows();
228
+ countBadge.textContent = String(shown.length);
229
+ countBadge.hidden = !shown.length;
230
+ list.replaceChildren(shown.length ? h('ul', { class: 'list' }, shown.map(friendRow))
231
+ : h('p', { class: 'empty' }, state.loaded ? '还没有好友。在上面粘贴对方发来的邀请即可添加。' : '正在读取…'));
232
+ }
233
+
234
+ root.replaceChildren(h('div', { class: 'page' }, problem,
235
+ h('section', {}, h('h2', {}, '我的身份与名片'), h('div', { class: 'card' },
236
+ h('div', { class: 'line identity' }, h('span', { class: 'secondary' }, '本机公钥'), identity.key, h('span', { class: 'spacer' }), identity.copy), identity.message,
237
+ h('div', { class: 'fields' }, h('label', { class: 'field' }, h('span', {}, '昵称'), ownForm.name), h('label', { class: 'field' }, h('span', {}, '头像'), ownForm.emoji)),
238
+ h('div', { class: 'field' }, h('span', { class: 'secondary' }, '主题色'), ownForm.swatches),
239
+ h('div', { class: 'line' }, ownForm.button), ownForm.message,
240
+ h('p', { class: 'hint' }, '名片对所有人公开,只含昵称、头像和主题色。'))),
241
+ h('section', {}, h('h2', {}, '添加好友'), h('div', { class: 'card' },
242
+ h('p', { class: 'hint' }, '暂需由对方提供 friend 角色入网码,后续将支持客户端一键生成邀请。'),
243
+ invite.paste,
244
+ h('details', {}, h('summary', {}, '分字段填写'), h('div', { class: 'fields' },
245
+ h('label', { class: 'field' }, h('span', {}, 'control(入网地址)'), invite.control),
246
+ h('label', { class: 'field' }, h('span', {}, 'authKey(入网码)'), invite.authKey),
247
+ h('label', { class: 'field' }, h('span', {}, 'linkId'), invite.linkId),
248
+ h('label', { class: 'field' }, h('span', {}, 'scope'), invite.scope),
249
+ h('label', { class: 'field' }, h('span', {}, 'peerNode'), invite.peerNode))),
250
+ h('div', { class: 'line' }, invite.button), invite.message)),
251
+ h('section', {}, h('h2', {}, '好友', countBadge), list)));
252
+ syncOwnForm();
253
+ draw();
254
+
255
+ function refresh() { readProfiles(); }
256
+ coda.on('toolbar', ({ id } = {}) => { if (id === 'refresh') refresh(); });
257
+ coda.toolbar([{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }]).catch(() => {});
258
+ coda.header({ text: '好友' }).catch(() => {});
259
+ start();
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <link rel="stylesheet" href="style.css">
7
+ </head>
8
+ <body>
9
+ <main id="root"></main>
10
+ <script type="module" src="app.mjs"></script>
11
+ </body>
12
+ </html>
package/view/style.css ADDED
@@ -0,0 +1,61 @@
1
+ /* 好友页:只用 App 给的 --coda-* 变量,手机优先。 */
2
+ :root {
3
+ font: var(--coda-font-size, 13px)/1.45 var(--coda-font, -apple-system, system-ui, sans-serif);
4
+ color: var(--coda-foreground, #1d1d1f); background: transparent;
5
+ }
6
+ * { box-sizing: border-box; }
7
+ html, body { margin: 0; }
8
+ button, input, select, textarea { font: inherit; color: inherit; }
9
+ button { cursor: pointer; }
10
+ button:disabled { opacity: .5; cursor: default; }
11
+ :focus-visible { outline: 2px solid var(--coda-accent, #0a84ff); outline-offset: 2px; border-radius: 6px; }
12
+ .selectable { -webkit-user-select: text; user-select: text; }
13
+ .mono { font-family: var(--coda-mono, ui-monospace, Menlo, monospace); font-size: .92em; }
14
+ .secondary { color: var(--coda-secondary, #6e6e73); }
15
+ .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
16
+ .spacer { flex: 1 1 auto; }
17
+
18
+ .page { max-width: 760px; margin: 0 auto; padding: 12px 16px 24px; }
19
+ section { margin-top: 20px; }
20
+ section:first-child { margin-top: 0; }
21
+ h2 { display: flex; align-items: center; gap: 6px; margin: 0 0 8px; font-size: 1em; font-weight: 600; }
22
+ .count { padding: 0 6px; border-radius: 8px; font-size: .85em; background: var(--coda-fill, rgba(120, 120, 128, .12)); color: var(--coda-secondary, #6e6e73); }
23
+ .card { padding: 12px; border-radius: var(--coda-radius-card, 12px); background: var(--coda-card, rgba(120, 120, 128, .08)); border: 1px solid var(--coda-separator, rgba(60, 60, 67, .18)); display: flex; flex-direction: column; gap: 10px; }
24
+ .hint { margin: 0; color: var(--coda-secondary, #6e6e73); font-size: .92em; }
25
+ .error { margin: 0; color: var(--coda-red, #ff3b30); overflow-wrap: anywhere; }
26
+ .ok { margin: 0; color: var(--coda-green, #34c759); }
27
+ .progress { margin: 0; color: var(--coda-secondary, #6e6e73); }
28
+ .empty { margin: 0; color: var(--coda-secondary, #6e6e73); }
29
+
30
+ .line { display: flex; align-items: center; gap: 8px; min-width: 0; flex-wrap: wrap; }
31
+ label.field { display: flex; flex-direction: column; gap: 4px; flex: 1 1 140px; min-width: 0; }
32
+ label.field > span { color: var(--coda-secondary, #6e6e73); font-size: .92em; }
33
+ input, select, textarea { width: 100%; min-width: 0; padding: 7px 9px; border-radius: var(--coda-radius, 8px); border: 1px solid var(--coda-separator, rgba(60, 60, 67, .18)); background: var(--coda-background, transparent); }
34
+ textarea { min-height: 84px; resize: vertical; }
35
+ .btn { padding: 7px 14px; border-radius: var(--coda-radius, 8px); border: 0; font-weight: 600; background: var(--coda-accent, #0a84ff); color: #fff; }
36
+ .btn.quiet { background: var(--coda-fill, rgba(120, 120, 128, .12)); color: var(--coda-foreground, #1d1d1f); }
37
+ .btn.danger { background: color-mix(in srgb, var(--coda-red, #ff3b30) 14%, transparent); color: var(--coda-red, #ff3b30); }
38
+ .btn.small { padding: 3px 10px; font-weight: 500; font-size: .92em; }
39
+ details > summary { cursor: pointer; color: var(--coda-secondary, #6e6e73); }
40
+ details[open] > summary { margin-bottom: 10px; }
41
+ .fields { display: flex; flex-wrap: wrap; gap: 10px; }
42
+
43
+ .identity { align-items: center; }
44
+ .key { font-weight: 600; }
45
+ .swatches { display: flex; gap: 8px; flex-wrap: wrap; }
46
+ .swatch { width: 26px; height: 26px; border-radius: 50%; border: 2px solid transparent; padding: 0; }
47
+ .swatch[aria-pressed="true"] { border-color: var(--coda-foreground, #1d1d1f); }
48
+
49
+ .list { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--coda-separator, rgba(60, 60, 67, .18)); }
50
+ .row { padding: 10px 0; border-bottom: 1px solid var(--coda-separator, rgba(60, 60, 67, .18)); display: flex; flex-direction: column; gap: 6px; }
51
+ .avatar { width: 38px; height: 38px; flex: none; border-radius: 50%; display: grid; place-items: center; font-size: 1.25em; font-weight: 600; color: #fff; }
52
+ .who { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
53
+ .title { font-weight: 600; }
54
+ .badge { padding: 1px 7px; border-radius: 6px; font-size: .88em; white-space: nowrap; background: var(--coda-fill, rgba(120, 120, 128, .12)); color: var(--coda-secondary, #6e6e73); }
55
+ .badge.bound { background: color-mix(in srgb, var(--coda-green, #34c759) 16%, transparent); color: var(--coda-green, #34c759); }
56
+ .badge.pending { background: color-mix(in srgb, var(--coda-orange, #ff9500) 16%, transparent); color: var(--coda-orange, #ff9500); }
57
+ .badge.conflict { background: color-mix(in srgb, var(--coda-red, #ff3b30) 16%, transparent); color: var(--coda-red, #ff3b30); }
58
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; }
59
+ .c-blue { background: var(--coda-blue, #0a84ff); } .c-orange { background: var(--coda-orange, #ff9500); } .c-green { background: var(--coda-green, #34c759); }
60
+ .c-purple { background: var(--coda-purple, #af52de); } .c-pink { background: var(--coda-pink, #ff2d55); } .c-teal { background: var(--coda-teal, #30b0c7); }
61
+ .c-gray { background: var(--coda-tertiary, #8e8e93); }