@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/README.md CHANGED
@@ -2,9 +2,10 @@
2
2
 
3
3
  管理本机的 Accord 身份、个人名片与熟人好友通道(`coda/accord@1`)。
4
4
 
5
- - **我的身份与名片**:显示本机公钥短码,可复制公钥;昵称、头像 Emoji、主题色以公开的 `profile` / `self` 记录发布;本机绑定了代签证书、`profile` 被拒(`forbidden`)时改发可代签的社交名片 `friends/card` / `self`。
6
- - **添加好友**:粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
7
- - **好友列表**:实时跟随好友表变化;可备注、重新互认、移除。
5
+ - **我的名片**:名片卡显示昵称、头像、主题色与本机公钥短码(点按复制),下方状态条给出已互认好友数(有待互认、冲突时提示)与身份、证书状态;多台机器提供这页时顶部可切换,连不上的机器置灰并注明原因。
6
+ - **编辑名片**:头像可选照片、几何纹(按公钥生成)、Emoji 或字标(昵称首字,写进 `emoji`)。照片从本机选图,在弹层里拖动、缩放裁成 512×512,优先编 WebP(不支持时用 JPEG),上传到 `coda-view://blob/content` 后把内容指针写进名片的 `avatar`;只改昵称、颜色不重新上传,换成非照片头像时写 `avatar: null` 清除。名片以公开的 `profile` / `self` 记录发布;本机绑定了代签证书、`profile` 被拒(`forbidden`)时改发可代签的社交名片 `friends/card` / `self`。
7
+ - **添加好友**:点名片上的「添加好友」,粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
8
+ - **好友列表**:实时跟随好友表变化,宽屏双列;显示好友的照片头像(读不出时退回 Emoji、几何纹或首字,点「刷新」重试)。点好友打开详情:完整公钥、节点名、本机备注、重新互认、二次确认后移除。
8
9
  - **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录、发私信与动态、实时跟随私信与动态,不必各自处理没有身份、证书过期和重试。
9
10
 
10
11
  ## 社交网关
package/lib/avatar.mjs ADDED
@@ -0,0 +1,86 @@
1
+ // 好友页头像与 Accord 状态的纯逻辑:头像地址、回退链、确定性几何纹、身份与好友统计。
2
+ // 页面(WKWebView)与 Node 单测都直接加载它,所以只用标准 JS 和 ./friends.mjs,不拼 HTML。
3
+
4
+ import { certStateOf, readContentPointer, shortAuthor } from './friends.mjs';
5
+
6
+ /** 头像图片的大小上限,与客户端和后端的 5 MiB 一致。 */
7
+ export const BLOB_MAX_BYTES = 5 * 1024 * 1024;
8
+
9
+ const CONTROL_CHARS = /[\p{Cc}\u2028\u2029]/gu;
10
+ const AUTHOR = /^ed25519:([0-9a-f]{64})$/;
11
+ const MAX_EMOJI = 8;
12
+
13
+ const clean = text => typeof text === 'string' ? text.replace(CONTROL_CHARS, '').trim() : '';
14
+ const machineQuery = machine => typeof machine === 'string' && machine.trim() ? `?coda-machine=${encodeURIComponent(machine.trim())}` : '';
15
+
16
+ /** 头像指针的读取地址:指针不合法(或为空)给 null;多机空间里带上 machine。 */
17
+ export function blobReadUrl(pointer, machine) {
18
+ const p = readContentPointer(pointer);
19
+ return p ? `coda-view://blob/${p.owner}/content/${p.sha256}${machineQuery(machine)}` : null;
20
+ }
21
+
22
+ /** 上传头像的地址;多机空间里带上 machine。 */
23
+ export const blobUploadUrl = machine => `coda-view://blob/content${machineQuery(machine)}`;
24
+
25
+ /** 一串字节的确定性混合(FNV-1a 作种,mulberry32 取数),给几何纹用。 */
26
+ function* stream(bytes) {
27
+ let seed = 0x811c9dc5;
28
+ for (const byte of bytes) seed = Math.imul(seed ^ byte, 0x01000193) >>> 0;
29
+ for (;;) {
30
+ seed = (seed + 0x6d2b79f5) >>> 0;
31
+ let t = seed;
32
+ t = Math.imul(t ^ (t >>> 15), t | 1);
33
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
34
+ yield (t ^ (t >>> 14)) >>> 0;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * 5×5 水平轴对称的几何纹(`grid[r][c] === grid[r][4 - c]`):同一个 author 永远同一张,
40
+ * 不会全空也不会全满。合法的 `ed25519:<64 位十六进制>` 取公钥字节推导,其余非空串取其字符码兜底。
41
+ */
42
+ export function identiconPattern(author) {
43
+ const text = String(author ?? '');
44
+ const hex = AUTHOR.exec(text)?.[1];
45
+ const bytes = hex ? Array.from({ length: 32 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16)) : [...text].map(ch => ch.codePointAt(0));
46
+ for (const draw of stream(bytes)) {
47
+ const grid = Array.from({ length: 5 }, (_, r) => {
48
+ const half = [0, 1, 2].map(c => ((draw >>> (r * 3 + c)) & 1) === 1);
49
+ return [half[0], half[1], half[2], half[1], half[0]];
50
+ });
51
+ const active = grid.flat().filter(Boolean).length;
52
+ if (active >= 8 && active <= 18) return grid;
53
+ }
54
+ }
55
+
56
+ /** 昵称等文本的首字:清掉控制字符与首尾空白后取第一个 Unicode 字符,ASCII 字母转大写,空则给 fallback。 */
57
+ export function initialChar(text, fallback = '友') {
58
+ const first = [...clean(text)][0];
59
+ return first ? (/^[a-z]$/.test(first) ? first.toUpperCase() : first) : fallback;
60
+ }
61
+
62
+ /**
63
+ * 决定头像怎么展示,只返回纯数据:
64
+ * 有可读的图片指针且没失败 → photo;否则有 emoji(1–8 字)→ emoji;否则有合法 author(且 prefer 不是 monogram)→ identicon;否则 monogram。
65
+ * photo 带 `fallback`:图片加载失败时直接换用的描述。
66
+ */
67
+ export function resolveAvatar({ avatar, emoji, author, name, fallback = '友', machine, photoFailed = false, prefer = 'auto' } = {}) {
68
+ const url = photoFailed ? null : blobReadUrl(avatar, machine);
69
+ if (url) return { kind: 'photo', url, fallback: resolveAvatar({ avatar, emoji, author, name, fallback, machine, photoFailed: true, prefer }) };
70
+ const mark = clean(emoji);
71
+ if (mark && [...mark].length <= MAX_EMOJI) return { kind: 'emoji', emoji: mark };
72
+ if (prefer !== 'monogram' && AUTHOR.test(author ?? '')) return { kind: 'identicon', grid: identiconPattern(author), author };
73
+ return { kind: 'monogram', text: initialChar(name, fallback) };
74
+ }
75
+
76
+ /**
77
+ * 本机 Accord 身份与证书状态(判定见 friends.mjs 的 certStateOf),加上好友统计。
78
+ */
79
+ export function accordStatusSummary(entry, rows = []) {
80
+ const certificate = entry?.status?.certificate;
81
+ const author = entry?.spec?.author ?? null;
82
+ const until = [certificate?.until, certificate?.expiresAt].find(value => Number.isFinite(value) && value > 0);
83
+ const count = status => rows.filter(row => row.status === status).length;
84
+ return { cert: certStateOf(entry), author, short: shortAuthor(author), certUntil: until ?? null,
85
+ friends: { total: rows.length, bound: count('bound'), pending: count('pending'), conflict: count('conflict') } };
86
+ }
package/lib/friends.mjs CHANGED
@@ -217,6 +217,19 @@ export function shortAuthor(author) {
217
217
  return match ? match[1].slice(0, 8) : '';
218
218
  }
219
219
 
220
+ /**
221
+ * 本机 Accord 记录(`coda/accord@1` 的 local)的证书状态:状态里写了 `certificate` 的按它判:null 没有身份,
222
+ * `active` 为 true 才是可发布,其余要换证书;旧宿主不写这个键,有作者就当可发布(发布遇 invalid_state 再落到需要证书)。
223
+ */
224
+ export function certStateOf(accord) {
225
+ const status = accord?.status;
226
+ if (status && typeof status === 'object' && Object.hasOwn(status, 'certificate')) {
227
+ if (status.certificate === null) return 'no_identity';
228
+ return status.certificate?.active === true ? 'active' : 'needs_cert';
229
+ }
230
+ return accord?.spec?.author ? 'active' : 'no_identity';
231
+ }
232
+
220
233
  // ---- 好友列表 ----
221
234
 
222
235
  const RANK = { conflict: 0, pending: 1, bound: 2 };
package/lib/outbox.mjs CHANGED
@@ -47,18 +47,7 @@ export function checkPublish({ kind, id, body, audience = ['public'] } = {}) {
47
47
  return { kind, id, body: JSON.parse(text), audience: [...audience] };
48
48
  }
49
49
 
50
- /**
51
- * 本机 Accord 记录(`coda/accord@1` 的 local)的证书状态:状态里写了 `certificate` 的按它判:null 没有身份,
52
- * `active` 为 true 才是可发布,其余要换证书;旧宿主不写这个键,有作者就当可发布(发布遇 invalid_state 再落到需要证书)。
53
- */
54
- export function certStateOf(accord) {
55
- const status = accord?.status;
56
- if (status && typeof status === 'object' && Object.hasOwn(status, 'certificate')) {
57
- if (status.certificate === null) return 'no_identity';
58
- return status.certificate?.active === true ? 'active' : 'needs_cert';
59
- }
60
- return accord?.spec?.author ? 'active' : 'no_identity';
61
- }
50
+ export { certStateOf } from './friends.mjs';
62
51
 
63
52
  const canonical = value => {
64
53
  if (Array.isArray(value)) return value.map(canonical);
@@ -0,0 +1,42 @@
1
+ // 页面选机器与发消息的纯逻辑:多台机器都提供这页时,页面须指明消息发往哪台。不碰 Coda 的 Node API;页面和单测都加载它。
2
+
3
+ export function reachableMachines(coda) {
4
+ const list = Array.isArray(coda?.machines) ? coda.machines : [coda?.machine];
5
+ const seen = new Set();
6
+ return list.filter(m => {
7
+ if (typeof m?.id !== 'string' || !m.id || m.unreachable || seen.has(m.id)) return false;
8
+ seen.add(m.id);
9
+ return true;
10
+ });
11
+ }
12
+
13
+ export function pickMachine(coda, savedId) {
14
+ const ids = reachableMachines(coda).map(m => m.id);
15
+ if (typeof savedId === 'string' && ids.includes(savedId)) return savedId;
16
+ const own = coda?.machine?.id;
17
+ if (ids.includes(own)) return own;
18
+ return ids[0] ?? own ?? null;
19
+ }
20
+
21
+ // 入队瞬间固定目标机器与代际(getEpoch,调用方每次选机自增);轮到它发送时选择已变,就整条丢弃,不发往新机器、也不报错。
22
+ // 发送失败交给 onError(error, msg, machine, epoch),不吞;只收当前目标机器的回包。send 返回的 Promise 以「是否发出」收尾。
23
+ export function createMachineBridge({ coda, getMachine, getEpoch, onMessage, onError, targetWindow = globalThis }) {
24
+ let chain = Promise.resolve();
25
+ const send = msg => {
26
+ const machine = getMachine(), epoch = getEpoch?.();
27
+ chain = chain.then(async () => {
28
+ if (getMachine() !== machine || getEpoch?.() !== epoch) return false;
29
+ try { await coda.postMessage(msg, machine ? { machine } : undefined); return true; } catch (error) { onError(error, msg, machine, epoch); return false; }
30
+ });
31
+ return chain;
32
+ };
33
+ const listener = event => {
34
+ const d = event.data;
35
+ if (!(d && typeof d === 'object' && typeof d.type === 'string')) return;
36
+ const current = getMachine();
37
+ if (event.machine?.id && current && event.machine.id !== current) return;
38
+ onMessage(d, event);
39
+ };
40
+ targetWindow.addEventListener('message', listener);
41
+ return { send, dispose: () => targetWindow.removeEventListener('message', listener) };
42
+ }
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName": "好友",
5
5
  "description": "管理 Accord 身份、个人名片与熟人好友通道",
6
6
  "icon": { "symbol": "person.2.fill", "color": "blue" },
7
- "version": "0.3.0",
7
+ "version": "0.4.0",
8
8
  "categories": [
9
9
  "Skills 与工具"
10
10
  ],