@guokit-dev/im-react 0.0.0-stage → 0.27.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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/dist/index.cjs +3095 -0
  4. package/dist/index.mjs +3073 -0
  5. package/dist/style.css +280 -0
  6. package/dist/types/core/chatController.d.ts +121 -0
  7. package/dist/types/core/externalStore.d.ts +25 -0
  8. package/dist/types/core/features.d.ts +8 -0
  9. package/dist/types/core/format.d.ts +32 -0
  10. package/dist/types/core/imStore.d.ts +8 -0
  11. package/dist/types/core/index.d.ts +9 -0
  12. package/dist/types/core/media.d.ts +37 -0
  13. package/dist/types/core/memberCache.d.ts +31 -0
  14. package/dist/types/core/mention.d.ts +31 -0
  15. package/dist/types/core/strings.d.ts +309 -0
  16. package/dist/types/index.d.ts +11 -0
  17. package/dist/types/ui/chat/ChatPage.d.ts +11 -0
  18. package/dist/types/ui/chat/Composer.d.ts +29 -0
  19. package/dist/types/ui/chat/MessageList.d.ts +17 -0
  20. package/dist/types/ui/chat/MessageRow.d.ts +24 -0
  21. package/dist/types/ui/chat/bubbles.d.ts +26 -0
  22. package/dist/types/ui/chat/emojis.d.ts +2 -0
  23. package/dist/types/ui/context.d.ts +44 -0
  24. package/dist/types/ui/conversation/ConversationList.d.ts +13 -0
  25. package/dist/types/ui/hooks.d.ts +7 -0
  26. package/dist/types/ui/layout/ImWorkspace.d.ts +8 -0
  27. package/dist/types/ui/layout/Layers.d.ts +19 -0
  28. package/dist/types/ui/layout/frame.d.ts +14 -0
  29. package/dist/types/ui/layout/useWide.d.ts +4 -0
  30. package/dist/types/ui/menu/Report.d.ts +7 -0
  31. package/dist/types/ui/navigator.d.ts +73 -0
  32. package/dist/types/ui/routes.d.ts +7 -0
  33. package/dist/types/ui/theme.d.ts +30 -0
  34. package/dist/types/ui/types.d.ts +44 -0
  35. package/dist/types/ui/viewer/ImageViewer.d.ts +6 -0
  36. package/dist/types/ui/viewer/VideoPlayer.d.ts +5 -0
  37. package/dist/types/ui/widgets/Avatar.d.ts +16 -0
  38. package/dist/types/ui/widgets/Icon.d.ts +32 -0
  39. package/dist/types/ui/widgets/Menu.d.ts +36 -0
  40. package/dist/types/ui/widgets/Page.d.ts +16 -0
  41. package/dist/types/ui/widgets/UnreadBadge.d.ts +11 -0
  42. package/dist/types/ui/widgets/feedback.d.ts +23 -0
  43. package/dist/types/ui/widgets/useFocusTrap.d.ts +2 -0
  44. package/package.json +54 -4
package/dist/index.mjs ADDED
@@ -0,0 +1,3073 @@
1
+ 'use client';
2
+
3
+ // src/ui/context.tsx
4
+ import { createContext as createContext4, useCallback as useCallback7, useContext as useContext4, useEffect as useEffect9, useMemo as useMemo6, useRef as useRef8 } from "react";
5
+
6
+ // src/core/strings.ts
7
+ var defaultStrings = {
8
+ conversationsTitle: "消息",
9
+ markAllRead: "全部已读",
10
+ disconnected: "网络连接已断开,正在重连…",
11
+ emptyConversations: "暂无消息",
12
+ groupChat: "群聊",
13
+ atMe: "[有人@我] ",
14
+ pin: "置顶",
15
+ unpin: "取消置顶",
16
+ mute: "消息免打扰",
17
+ unmute: "取消免打扰",
18
+ deleteConversation: "删除会话",
19
+ deleteConversationConfirm: "删除后,聊天记录将从本设备移除。",
20
+ cancel: "取消",
21
+ confirm: "确定",
22
+ yesterday: "昨天",
23
+ weekdays: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
24
+ operationFailed: "操作失败",
25
+ typing: "对方正在输入…",
26
+ notInGroup: "你已不在群聊中",
27
+ read: "已读",
28
+ unreadMark: "未读",
29
+ aiGenerated: "AI 生成",
30
+ send: "发送",
31
+ sendRejected: "消息未能发出",
32
+ you: "你",
33
+ peer: "对方",
34
+ admin: "管理员",
35
+ system: "系统",
36
+ recalled: "{name}撤回了一条消息",
37
+ image: "[图片]",
38
+ voice: "[语音]",
39
+ video: "[视频]",
40
+ file: "[文件]",
41
+ location: "[位置]",
42
+ unsupported: "[暂不支持的消息]",
43
+ tipCreate: "{op}创建了群聊",
44
+ tipJoin: "{op}邀请{targets}加入了群聊",
45
+ tipQuit: "{targets}退出了群聊",
46
+ tipKick: "{op}将{targets}移出了群聊",
47
+ tipDismiss: "群聊已解散",
48
+ tipUpdate: "{op}修改了群资料",
49
+ tipRename: "{op}将群名改为「{name}」",
50
+ tipNotice: "{op}更新了群公告",
51
+ tipAdminOn: "{targets}成为管理员",
52
+ tipAdminOff: "{targets}不再是管理员",
53
+ tipTransfer: "{targets}成为新群主",
54
+ tipMute: "{targets}被禁言",
55
+ tipUnmute: "{targets}被解除禁言",
56
+ tipOther: "[群通知]",
57
+ mentionTitle: "选择提醒的人",
58
+ search: "搜索",
59
+ atAll: "所有人",
60
+ emoji: "表情",
61
+ keyboard: "键盘",
62
+ more: "更多",
63
+ cardKinds: { "order": "订单", "product": "商品", "service": "服务", "article": "文章", "page": "页面", "ticket": "工单" },
64
+ cardKindOther: "链接",
65
+ album: "相册",
66
+ camera: "拍摄",
67
+ fileItem: "文件",
68
+ holdToTalk: "按住 说话",
69
+ releaseToSend: "松开 发送",
70
+ slideUpToCancel: "手指上滑,取消发送",
71
+ releaseToCancel: "松开手指,取消发送",
72
+ tooShort: "说话时间太短",
73
+ noMicPermission: "没有麦克风权限",
74
+ voiceInput: "语音输入",
75
+ fileTooLarge: "文件过大,最大 {mb} MB",
76
+ videoUnreadable: "读不了这个视频",
77
+ copy: "复制",
78
+ copied: "已复制",
79
+ recall: "撤回",
80
+ report: "举报",
81
+ reportReasons: { "porn": "色情低俗", "fraud": "诈骗", "harass": "骚扰辱骂", "ad": "广告营销", "illegal": "违法违规", "other": "其他" },
82
+ alsoBlock: "同时拉黑对方",
83
+ submit: "提交",
84
+ reported: "已提交,我们会尽快处理",
85
+ reportDuplicated: "已有一条待处理的举报",
86
+ // B 期:通用
87
+ done: "完成",
88
+ indexBar: "字母索引",
89
+ unknownUser: "用户 {id}",
90
+ rateLimited: "操作过于频繁,请稍后再试",
91
+ // B 期:会话列表「+」菜单
92
+ startGroupChat: "发起群聊",
93
+ addFriend: "添加朋友",
94
+ // B 期:通讯录
95
+ contactsTitle: "通讯录",
96
+ contactsSearchHint: "搜索备注或昵称",
97
+ newFriends: "新的朋友",
98
+ groupChats: "群聊",
99
+ blocklist: "黑名单",
100
+ allFriends: "全部",
101
+ emptyContacts: "还没有好友",
102
+ emptyGroupChats: "暂无群聊",
103
+ // B 期:新的朋友
104
+ requestsIn: "收到的",
105
+ requestsOut: "发出的",
106
+ accept: "同意",
107
+ reject: "拒绝",
108
+ requestPending: "等待验证",
109
+ requestAccepted: "已添加",
110
+ requestRejected: "已拒绝",
111
+ requestExpired: "已过期",
112
+ requestsTip: "超过 30 天未处理的申请自动过期;拒绝不会通知对方",
113
+ emptyRequests: "暂无申请",
114
+ // B 期:添加朋友
115
+ addFriendHint: "账号或搜索号",
116
+ addFriendTip: "需要完整输入对方的账号或搜索号,不支持按昵称模糊查找",
117
+ matchedByUserId: "账号:{q}",
118
+ matchedBySearchKey: "搜索号:{q}",
119
+ view: "查看",
120
+ userNotFound: "没有找到该用户",
121
+ userNotFoundTip: "请确认账号或搜索号是否完整、正确",
122
+ searchSelf: "这是你自己",
123
+ // B 期:资料卡
124
+ userCardTitle: "资料卡",
125
+ nicknameLabel: "昵称:{name}",
126
+ accountLabel: "账号:{id}",
127
+ remarkAndGroups: "备注和分组",
128
+ friendSince: "成为好友",
129
+ sendMessage: "发消息",
130
+ blockUser: "加入黑名单",
131
+ blockConfirm: "对方不会收到通知。拉黑后对方发给你的消息会被拒收,也不能再申请加你为朋友。",
132
+ deleteFriend: "删除好友",
133
+ deleteFriendConfirm: "确定删除好友「{name}」?",
134
+ addToContacts: "添加到通讯录",
135
+ friendRequestTitle: "发送添加朋友申请",
136
+ friendRequestDefault: "我是{name}",
137
+ sendRequest: "发送申请",
138
+ requestSent: "申请已发送",
139
+ becameFriends: "已添加为好友",
140
+ addDenied: "对方不允许加好友",
141
+ addBlocked: "无法添加对方为好友",
142
+ // B 期:备注与分组
143
+ remark: "备注",
144
+ remarkTip: "昵称:{name}。备注只有你自己能看到,清空后显示昵称",
145
+ clearRemark: "清空备注",
146
+ friendGroupsMulti: "分组(可多选)",
147
+ manageFriendGroups: "管理分组",
148
+ newFriendGroup: "新建分组",
149
+ friendGroupName: "分组名称",
150
+ // B 期:分组管理
151
+ friendGroupsTitle: "好友分组",
152
+ friendGroupsTip: "拖动右侧把手调整顺序;删除分组不会删除组里的好友",
153
+ rename: "重命名",
154
+ deleteFriendGroup: "删除分组",
155
+ deleteFriendGroupConfirm: "删除分组「{name}」?组里的好友不会被删除。",
156
+ dragToSort: "拖动排序",
157
+ // B 期:群资料
158
+ groupInfoTitle: "群聊信息",
159
+ groupIdAndCount: "群号 {id} · {n} 人",
160
+ inviteMember: "邀请",
161
+ removeMember: "移出",
162
+ viewAllMembers: "查看全部 {n} 名成员",
163
+ groupNameLabel: "群聊名称",
164
+ groupNotice: "群公告",
165
+ notSet: "未设置",
166
+ pinChat: "置顶聊天",
167
+ groupManage: "群管理",
168
+ muteAll: "全员禁言",
169
+ muteAllTip: "开启后只有群主和管理员可以发言",
170
+ inviteAdminOnly: "仅群主和管理员可邀请",
171
+ groupAdmins: "群管理员",
172
+ peopleCount: "{n} 人",
173
+ transferOwner: "转让群主",
174
+ clearHistory: "清空聊天记录",
175
+ clearHistoryConfirm: "确定清空本群的聊天记录?",
176
+ quitGroup: "退出群聊",
177
+ quitGroupConfirm: "退出后,将不再接收此群聊的消息。",
178
+ ownerQuitTip: "群主要先转让群主,才能退出群聊",
179
+ dismissGroup: "解散群聊",
180
+ dismissGroupConfirm: "解散后,所有成员都无法再发言。",
181
+ roleOwner: "群主",
182
+ roleAdmin: "管理员",
183
+ roleMember: "成员",
184
+ // B 期:群成员
185
+ groupMembersTitle: "群成员",
186
+ searchMembers: "搜索群成员",
187
+ mutedRemaining: "禁言 · 还剩 {time}",
188
+ joinedAt: "{role} · {date} 进群",
189
+ viewProfile: "查看资料",
190
+ setAdmin: "设为管理员",
191
+ unsetAdmin: "取消管理员",
192
+ muteMember: "禁言",
193
+ unmuteMember: "解除禁言",
194
+ muteDurations: { 600: "10 分钟", 3600: "1 小时", 43200: "12 小时", 86400: "1 天", 604800: "7 天", 2592e3: "30 天" },
195
+ durationMinutes: "{n} 分钟",
196
+ durationHours: "{n} 小时",
197
+ durationDays: "{n} 天",
198
+ kickMember: "移出群聊",
199
+ kickConfirm: "确定将「{name}」移出群聊?",
200
+ transferTo: "转让群主给他",
201
+ transferConfirm: "确定将群主转让给「{name}」?转让后你将成为普通成员。",
202
+ // B 期:选择好友
203
+ selectFriendsTitle: "选择好友",
204
+ doneWithCount: "完成({n})",
205
+ searchFriends: "搜索好友",
206
+ alreadyInGroup: "已在群里",
207
+ inviteToGroup: "邀请进群",
208
+ skippedMembers: "{n} 人未能加入",
209
+ groupNameSeparator: "、",
210
+ // B 期:群公告
211
+ editNotice: "编辑",
212
+ publish: "发布",
213
+ noticePublishedAt: "{date} 发布",
214
+ noticeEditTip: "只有群主和管理员可以编辑",
215
+ noticeHint: "公告内容",
216
+ noticePublishTip: "发布后会在群里发一条提示",
217
+ emptyNotice: "暂无群公告",
218
+ // B 期:隐私与黑名单
219
+ privacyTitle: "隐私",
220
+ addMeWhen: "加我为朋友时",
221
+ addPolicyTitles: ["需要我验证", "允许任何人直接加我", "不允许任何人加我"],
222
+ addPolicyTips: ["对方发申请,我同意后成为朋友", "对方点「添加」后直接成为朋友", "对方能搜到我,但发不了申请"],
223
+ blocklistTip: "对方不会收到通知。拉黑后对方发给你的消息会被拒收,也不能再申请加你为朋友",
224
+ unblock: "移出",
225
+ blockedAt: "{date} 拉黑",
226
+ emptyBlocklist: "黑名单是空的",
227
+ // C 期:消息搜索与定位
228
+ searchContacts: "联系人",
229
+ searchGroups: "群聊",
230
+ searchMessagesTitle: "聊天记录",
231
+ searchMore: "查看更多",
232
+ searchRelated: "{n} 条相关聊天记录",
233
+ searchLoadMore: "继续加载",
234
+ searchNoResult: "没有找到相关结果",
235
+ searchFailed: "搜索失败,点击重试",
236
+ searchNoMore: "没有更多了",
237
+ findChatHistory: "查找聊天记录",
238
+ conversationGone: "会话已不存在",
239
+ backToLatest: "回到最新消息",
240
+ // C 期:客服会话
241
+ csTitle: "客服",
242
+ csBot: "智能助手接待中",
243
+ csHandoff: "转人工",
244
+ csQueued: "排队中,前面还有 {n} 位",
245
+ csQueuedNext: "排队中,马上为您接入",
246
+ csOffline: "暂无客服在线,可以先留下联系方式",
247
+ csOfflineWait: "暂无客服在线,请稍候",
248
+ csActive: "人工客服接待中",
249
+ csLeave: "留联系方式",
250
+ leaveTitle: "留下联系方式",
251
+ leaveTip: "客服上线后按您留的方式联系您。留言内容就是您刚才在会话里说的话,不用再填。",
252
+ leaveName: "称呼(选填)",
253
+ leavePhone: "手机号",
254
+ leaveEmail: "邮箱",
255
+ leaveOptional: "选填",
256
+ leaveContactTip: "手机号与邮箱至少填一项",
257
+ leaveDone: "已提交",
258
+ ratingTitle: "请对本次服务进行评价",
259
+ ratingLevels: ["非常不满意", "不满意", "一般", "满意", "非常满意"],
260
+ ratingScore: "{n} 星 · {label}",
261
+ ratingComment: "说说您的感受(选填)",
262
+ ratingCommentHint: "200 字以内",
263
+ ratingSubmit: "提交评价",
264
+ ratingDone: "已评价,感谢您的反馈",
265
+ back: "返回",
266
+ close: "关闭",
267
+ inputPlaceholder: "发消息…",
268
+ enterToSend: "Enter 发送,Shift+Enter 换行",
269
+ dropToSend: "松开即可发送给 {name}",
270
+ removeAttachment: "移除",
271
+ sendImageOrVideo: "发送图片或视频",
272
+ sendFile: "发送文件",
273
+ zoomIn: "放大",
274
+ zoomOut: "缩小",
275
+ prevImage: "上一张",
276
+ nextImage: "下一张",
277
+ openOriginal: "在新标签页打开原图",
278
+ navMessages: "消息",
279
+ selectConversation: "选择一个会话开始聊天",
280
+ fileNotAllowed: "站点未开放发送这类文件",
281
+ imageIndex: "{n} / {total}"
282
+ };
283
+ function mergeStrings(over) {
284
+ return over ? { ...defaultStrings, ...over } : defaultStrings;
285
+ }
286
+ function fill(template, vars) {
287
+ return template.replace(/\{(\w+)\}/g, (m, k) => k in vars ? String(vars[k]) : m);
288
+ }
289
+
290
+ // src/ui/navigator.ts
291
+ import { createContext, useCallback, useContext, useMemo, useReducer } from "react";
292
+ var routePlacement = {
293
+ conversations: "list",
294
+ chat: "main",
295
+ report: "dialog",
296
+ imageViewer: "overlay",
297
+ videoPlayer: "overlay"
298
+ };
299
+ var initialNav = { list: { name: "conversations" }, main: null, drawer: [], dialog: [], overlay: [] };
300
+ function navReducer(s, a) {
301
+ switch (a.type) {
302
+ case "open": {
303
+ const p = routePlacement[a.route.name];
304
+ if (p === "list") return { ...s, list: a.route, drawer: [], dialog: [] };
305
+ if (p === "main") return { ...s, main: a.route, drawer: [], dialog: [] };
306
+ if (p === "drawer") return { ...s, drawer: [...s.drawer, a.route] };
307
+ if (p === "dialog") return { ...s, dialog: [...s.dialog, a.route] };
308
+ return { ...s, overlay: [...s.overlay, a.route] };
309
+ }
310
+ case "back":
311
+ if (s.overlay.length) return { ...s, overlay: s.overlay.slice(0, -1) };
312
+ if (s.dialog.length) return { ...s, dialog: s.dialog.slice(0, -1) };
313
+ if (s.drawer.length) return { ...s, drawer: s.drawer.slice(0, -1) };
314
+ if (s.main) return { ...s, main: null };
315
+ return s;
316
+ case "close":
317
+ return { ...s, drawer: [], dialog: [], overlay: [] };
318
+ }
319
+ }
320
+ function topRoute(s) {
321
+ return s.overlay.at(-1) ?? s.dialog.at(-1) ?? s.drawer.at(-1) ?? s.main ?? null;
322
+ }
323
+ var NavContext = createContext(null);
324
+ function useNavState(workspace, onMainOrList) {
325
+ const [state, dispatch] = useReducer(navReducer, initialNav);
326
+ const open = useCallback((route) => {
327
+ const p = routePlacement[route.name];
328
+ if (!workspace && (p === "main" || p === "list")) {
329
+ onMainOrList?.(route);
330
+ return;
331
+ }
332
+ dispatch({ type: "open", route });
333
+ }, [workspace, onMainOrList]);
334
+ const back = useCallback(() => dispatch({ type: "back" }), []);
335
+ const close = useCallback(() => dispatch({ type: "close" }), []);
336
+ return useMemo(() => ({ state, open, back, close, workspace }), [state, open, back, close, workspace]);
337
+ }
338
+ function useNavContext() {
339
+ const nav = useContext(NavContext);
340
+ if (!nav) throw new Error("没有找到 GuokitImUi:IM 组件要放在 GuokitImUi 下面。");
341
+ return nav;
342
+ }
343
+ function useImNavigator() {
344
+ return useNavContext();
345
+ }
346
+
347
+ // src/ui/theme.ts
348
+ var px = (v) => typeof v === "number" ? `${v}px` : v;
349
+ var radius = (s) => s === "circle" ? "50%" : "25%";
350
+ function themeVars(t) {
351
+ const v = {};
352
+ if (!t) return v;
353
+ if (t.accent) v["--gkim-accent"] = t.accent;
354
+ if (t.selfBubble) v["--gkim-bubble-self-bg"] = t.selfBubble;
355
+ if (t.selfBubbleText) v["--gkim-bubble-self-fg"] = t.selfBubbleText;
356
+ if (t.peerBubble) v["--gkim-bubble-peer-bg"] = t.peerBubble;
357
+ if (t.peerBubbleText) v["--gkim-bubble-peer-fg"] = t.peerBubbleText;
358
+ if (t.bubbleRadius != null) v["--gkim-bubble-radius"] = px(t.bubbleRadius);
359
+ if (t.avatarShape) v["--gkim-avatar-radius"] = radius(t.avatarShape);
360
+ if (t.groupAvatarShape) v["--gkim-group-avatar-radius"] = radius(t.groupAvatarShape);
361
+ if (t.avatarSize != null) v["--gkim-avatar-size"] = px(t.avatarSize);
362
+ if (t.chatBackground) v["--gkim-chat-bg"] = t.chatBackground;
363
+ if (t.timeDividerSize != null) v["--gkim-time-divider-size"] = px(t.timeDividerSize);
364
+ return v;
365
+ }
366
+
367
+ // src/ui/layout/Layers.tsx
368
+ import { useMemo as useMemo5 } from "react";
369
+
370
+ // src/ui/chat/ChatPage.tsx
371
+ import { useCallback as useCallback6, useEffect as useEffect6, useMemo as useMemo4, useRef as useRef7, useState as useState6, useSyncExternalStore } from "react";
372
+ import { ImApiError } from "@guokit-dev/im";
373
+
374
+ // src/core/externalStore.ts
375
+ var ListenerSet = class {
376
+ constructor(onFirst, onLast) {
377
+ this.onFirst = onFirst;
378
+ this.onLast = onLast;
379
+ this.entries = /* @__PURE__ */ new Set();
380
+ }
381
+ get size() {
382
+ return this.entries.size;
383
+ }
384
+ add(fn) {
385
+ if (this.entries.size === 0) this.onFirst?.();
386
+ const entry = { fn };
387
+ this.entries.add(entry);
388
+ return () => {
389
+ if (!this.entries.delete(entry)) return;
390
+ if (this.entries.size === 0) this.onLast?.();
391
+ };
392
+ }
393
+ notify() {
394
+ for (const e of [...this.entries]) e.fn();
395
+ }
396
+ /** 丢掉全部订阅者,不调 onLast(销毁时用,调用方自己收尾)。 */
397
+ clear() {
398
+ this.entries.clear();
399
+ }
400
+ };
401
+
402
+ // src/core/features.ts
403
+ var cache = /* @__PURE__ */ new WeakMap();
404
+ function cachedFeatures(im) {
405
+ const me = im.currentUserId;
406
+ if (me === null) return Promise.reject(new Error("未登录"));
407
+ const hit = cache.get(im);
408
+ if (hit && hit.userId === me) return hit.promise;
409
+ let promise;
410
+ try {
411
+ promise = im.features();
412
+ } catch (e) {
413
+ return Promise.reject(e);
414
+ }
415
+ const entry = { userId: me, promise };
416
+ cache.set(im, entry);
417
+ promise.catch(() => {
418
+ if (cache.get(im) === entry) cache.delete(im);
419
+ });
420
+ return promise;
421
+ }
422
+
423
+ // src/core/chatController.ts
424
+ var _ChatController = class _ChatController {
425
+ constructor(im, target) {
426
+ this.im = im;
427
+ this.byClient = /* @__PURE__ */ new Map();
428
+ this.sorted = null;
429
+ this.snap = null;
430
+ this.offs = [];
431
+ this.listeners = new ListenerSet();
432
+ this.newListeners = /* @__PURE__ */ new Set();
433
+ this.started = false;
434
+ this.disposed = false;
435
+ this.historyLoaded = false;
436
+ this.active = true;
437
+ this.loading = true;
438
+ this.loadingMore = false;
439
+ this.hasMore = true;
440
+ this.peerTyping = false;
441
+ this.features = null;
442
+ this.progress = {};
443
+ this.localFiles = {};
444
+ /** 发出去、还没从 messageUpdated 认领到 clientMsgId 的图片,按调用顺序。 */
445
+ this.awaiting = [];
446
+ // ---------------- 订阅 ----------------
447
+ this.subscribe = (fn) => this.listeners.add(fn);
448
+ this.getSnapshot = () => this.snap ?? (this.snap = this.buildSnapshot());
449
+ let peerId = null;
450
+ let groupId = null;
451
+ let conv = null;
452
+ if ("conversation" in target) {
453
+ conv = target.conversation;
454
+ groupId = conv?.group?.groupId ?? null;
455
+ peerId = groupId === null ? conv?.peer?.userId ?? null : null;
456
+ } else if ("group" in target) {
457
+ groupId = target.group;
458
+ } else {
459
+ peerId = target.peer;
460
+ }
461
+ if (!peerId && !groupId) throw new TypeError("聊天对象不能为空:peer、group 须为非空字符串,conversation 须有 peer 或 group");
462
+ this.peerId = peerId;
463
+ this.groupId = groupId;
464
+ this.conv = conv;
465
+ }
466
+ get isGroup() {
467
+ return this.groupId !== null;
468
+ }
469
+ get conversationId() {
470
+ return this.conv?.id ?? null;
471
+ }
472
+ /** `send*` 的目标参数。 */
473
+ get sendTarget() {
474
+ return this.groupId !== null ? { groupId: this.groupId } : this.peerId;
475
+ }
476
+ get target() {
477
+ return { peerId: this.peerId, groupId: this.groupId, conversationId: this.conversationId, to: this.peerId ?? "" };
478
+ }
479
+ /** 有新消息进来(对方的、或本人在别的设备发的);页面据此决定是否滚到底。返回取消函数。 */
480
+ onNewMessage(fn) {
481
+ this.newListeners.add(fn);
482
+ return () => void this.newListeners.delete(fn);
483
+ }
484
+ buildSnapshot() {
485
+ const c = this.conv;
486
+ return {
487
+ messages: this.sorted ?? (this.sorted = [...this.byClient.values()].sort(compare)),
488
+ loading: this.loading,
489
+ loadingMore: this.loadingMore,
490
+ hasMore: this.hasMore,
491
+ peerTyping: this.peerTyping,
492
+ conversation: c,
493
+ conversationId: c?.id ?? null,
494
+ quit: c?.group?.quit ?? false,
495
+ peerReadSeq: this.isGroup || c?.type === "service" ? null : c?.peerReadSeq ?? null,
496
+ features: this.features,
497
+ progress: this.progress,
498
+ localFiles: this.localFiles
499
+ };
500
+ }
501
+ notify() {
502
+ if (this.disposed) return;
503
+ this.snap = null;
504
+ this.listeners.notify();
505
+ }
506
+ // ---------------- 加载 ----------------
507
+ /** 挂上 SDK 事件并加载首屏。重复调用无效。 */
508
+ async start() {
509
+ if (this.started || this.disposed) return;
510
+ this.started = true;
511
+ const im = this.im;
512
+ this.offs.push(
513
+ im.on("newMessage", (m) => this.onMessage(m, true)),
514
+ im.on("messageUpdated", (m) => this.onMessage(m, false)),
515
+ im.on("conversations", (list) => this.onConversations(list)),
516
+ im.on("sendProgress", (p) => {
517
+ if (!this.byClient.has(p.clientMsgId)) return;
518
+ this.progress = { ...this.progress, [p.clientMsgId]: p.total > 0 ? p.sent / p.total : null };
519
+ this.notify();
520
+ }),
521
+ im.on("typing", (t) => {
522
+ if (!this.isGroup && t.conversationId === this.conversationId && this.peerTyping !== t.active) {
523
+ this.peerTyping = t.active;
524
+ this.notify();
525
+ }
526
+ })
527
+ );
528
+ cachedFeatures(im).then(
529
+ (f) => {
530
+ this.features = f;
531
+ this.notify();
532
+ },
533
+ () => {
534
+ }
535
+ );
536
+ try {
537
+ this.conv ?? (this.conv = this.isGroup ? im.conversationWithGroup(this.groupId) : im.conversationWith(this.peerId));
538
+ if (this.conv === null) {
539
+ this.merge(this.isGroup ? im.pendingToGroup(this.groupId) : im.pendingTo(this.peerId));
540
+ this.hasMore = false;
541
+ } else {
542
+ await this.loadLatest();
543
+ }
544
+ } catch {
545
+ this.hasMore = false;
546
+ }
547
+ if (this.disposed) return;
548
+ this.loading = false;
549
+ this.notify();
550
+ }
551
+ async loadLatest() {
552
+ const id = this.conversationId;
553
+ this.historyLoaded = true;
554
+ const list = await this.im.messages(id, { limit: _ChatController.pageSize });
555
+ if (this.disposed) return;
556
+ this.merge(list);
557
+ this.hasMore = list.filter((m) => m.seq !== null).length >= _ChatController.pageSize;
558
+ this.markRead();
559
+ }
560
+ /** 滚到顶时调:用最早一条**已确认**的消息作 before 再取一页。失败留着 hasMore,下次再试。 */
561
+ async loadMore() {
562
+ const id = this.conversationId;
563
+ if (this.loadingMore || !this.hasMore || id === null || this.disposed) return;
564
+ const first = this.getSnapshot().messages.find((m) => m.seq !== null);
565
+ if (!first) {
566
+ this.hasMore = false;
567
+ this.notify();
568
+ return;
569
+ }
570
+ this.loadingMore = true;
571
+ this.notify();
572
+ try {
573
+ const list = await this.im.messages(id, { before: first, limit: _ChatController.pageSize });
574
+ if (this.disposed) return;
575
+ this.merge(list);
576
+ this.hasMore = list.length >= _ChatController.pageSize;
577
+ } catch {
578
+ }
579
+ this.loadingMore = false;
580
+ this.notify();
581
+ }
582
+ // ---------------- 事件 ----------------
583
+ belongs(m) {
584
+ const id = this.conversationId;
585
+ if (id !== null && m.conversationId === id) return true;
586
+ if (this.groupId !== null) return m.groupId !== null && m.groupId.toLowerCase() === this.groupId.toLowerCase();
587
+ return m.groupId === null && (m.from === this.peerId || m.to === this.peerId);
588
+ }
589
+ onMessage(m, fresh) {
590
+ if (this.disposed || !this.belongs(m)) return;
591
+ const cid = m.clientMsgId;
592
+ if (m.status !== "sending" && cid in this.progress) {
593
+ const rest = { ...this.progress };
594
+ delete rest[cid];
595
+ this.progress = rest;
596
+ }
597
+ if (m.isSelf && m.type === "image" && m.status === "sending" && !(cid in this.localFiles) && this.awaiting.length) {
598
+ this.localFiles = { ...this.localFiles, [cid]: this.awaiting.shift() };
599
+ }
600
+ this.merge([m]);
601
+ this.adopt(m.conversationId);
602
+ if (fresh) {
603
+ if (!m.isSelf) this.peerTyping = false;
604
+ this.markRead();
605
+ }
606
+ this.notify();
607
+ if (fresh) for (const fn of [...this.newListeners]) fn(m);
608
+ }
609
+ /** 还没有会话时,首条消息发送成功后从消息里拿会话 id,再拉历史、标已读。 */
610
+ adopt(id) {
611
+ if (id === null || this.conversationId !== null) return;
612
+ let c = null;
613
+ try {
614
+ c = this.isGroup ? this.im.conversationWithGroup(this.groupId) : this.im.conversationWith(this.peerId);
615
+ } catch {
616
+ return;
617
+ }
618
+ if (!c || c.id !== id) return;
619
+ this.conv = c;
620
+ if (!this.historyLoaded) this.loadLatest().then(() => this.notify(), () => {
621
+ });
622
+ }
623
+ onConversations(list) {
624
+ const id = this.conversationId;
625
+ const gid = this.groupId?.toLowerCase();
626
+ for (const c of list) {
627
+ const hit = id !== null ? c.id === id : gid !== void 0 ? c.group?.groupId.toLowerCase() === gid : c.group === null && c.peer?.userId === this.peerId;
628
+ if (!hit) continue;
629
+ if (c === this.conv) return;
630
+ const first = this.conv === null;
631
+ this.conv = c;
632
+ if (first && !this.historyLoaded && !this.loading) this.loadLatest().then(() => this.notify(), () => {
633
+ });
634
+ this.notify();
635
+ return;
636
+ }
637
+ }
638
+ merge(list) {
639
+ for (const m of list) this.byClient.set(m.clientMsgId, m);
640
+ this.sorted = null;
641
+ }
642
+ markRead() {
643
+ const id = this.conversationId;
644
+ if (id === null || !this.active || this.disposed) return;
645
+ try {
646
+ this.im.markRead(id).catch(() => {
647
+ });
648
+ } catch {
649
+ }
650
+ }
651
+ /** 页面前后台切换时调(如 visibilitychange);回到前台补一次已读。 */
652
+ setActive(active) {
653
+ this.active = active;
654
+ if (active) this.markRead();
655
+ }
656
+ /** 单聊输入变化时调(SDK 按 3 秒节流);群聊服务端不支持,不发。 */
657
+ typing() {
658
+ const id = this.conversationId;
659
+ if (this.isGroup || id === null) return;
660
+ try {
661
+ this.im.sendTyping(id).catch(() => {
662
+ });
663
+ } catch {
664
+ }
665
+ }
666
+ // ---------------- 发送 ----------------
667
+ //
668
+ // 发送失败不抛,看返回消息的 status(failed 可 resend,rejected 只显示原因)与 errorCode。
669
+ // 参数不对、未登录时 SDK 同步抛,这里变成 rejected Promise。
670
+ track(m) {
671
+ this.onMessage(m, false);
672
+ return m;
673
+ }
674
+ /** 发文字;at 只在群里有效(`@all` 为所有人)。 */
675
+ async sendText(text, at) {
676
+ const opts = at && at.length ? { at: [...at] } : {};
677
+ return this.track(await this.im.sendText(this.sendTarget, text, opts));
678
+ }
679
+ /** 发图(JPEG / PNG / GIF / WebP);原文件留在快照 `localFiles` 里做预览。 */
680
+ async sendImage(file) {
681
+ this.awaiting.push(file);
682
+ let m;
683
+ try {
684
+ m = await this.im.sendImage(this.sendTarget, file);
685
+ } finally {
686
+ const i = this.awaiting.indexOf(file);
687
+ if (i >= 0) this.awaiting.splice(i, 1);
688
+ }
689
+ if (!(m.clientMsgId in this.localFiles)) this.localFiles = { ...this.localFiles, [m.clientMsgId]: file };
690
+ return this.track(m);
691
+ }
692
+ /** 发视频(mp4 / mov);时长与宽高必填(用 media 的 readVideoMeta 读),越界 SDK 抛 RangeError。 */
693
+ async sendVideo(file, meta) {
694
+ const { durationMs, width, height } = meta;
695
+ return this.track(await this.im.sendVideo(this.sendTarget, file, { durationMs, width, height }));
696
+ }
697
+ /** 发文件;name 不传取 File.name(要带扩展名)。 */
698
+ async sendFile(file, name) {
699
+ return this.track(await this.im.sendFile(this.sendTarget, file, name ? { name } : {}));
700
+ }
701
+ /** 重发 failed 的消息;rejected 等其他状态不调 SDK,直接 reject。 */
702
+ async resend(m) {
703
+ if (m.status !== "failed") throw new TypeError("只能重发 failed 的消息");
704
+ return this.track(await this.im.resend(m));
705
+ }
706
+ /** 撤回自己发的一条;没开启、超时限抛 ImApiError(直接显示 message)。成功后列表随 messageUpdated 更新。 */
707
+ async recall(m) {
708
+ await this.im.recall(m);
709
+ }
710
+ dispose() {
711
+ if (this.disposed) return;
712
+ this.disposed = true;
713
+ this.offs.forEach((f) => f());
714
+ this.offs = [];
715
+ this.listeners.clear();
716
+ this.newListeners.clear();
717
+ }
718
+ };
719
+ _ChatController.pageSize = 30;
720
+ var ChatController = _ChatController;
721
+ function compare(a, b) {
722
+ const sa = a.seq;
723
+ const sb = b.seq;
724
+ if (sa !== null && sb !== null) return sa - sb;
725
+ if (sa !== null) return -1;
726
+ if (sb !== null) return 1;
727
+ return a.createdAt - b.createdAt;
728
+ }
729
+
730
+ // src/core/format.ts
731
+ function conversationTitle(c, s) {
732
+ const g = c.group;
733
+ if (g) return g.name !== "" ? g.name : s.groupChat;
734
+ const p = c.peer;
735
+ if (!p) return "";
736
+ if (p.remark !== "") return p.remark;
737
+ if (p.nickname !== "") return p.nickname;
738
+ return p.userId;
739
+ }
740
+ function conversationSummary(c, s) {
741
+ return { atMe: c.atMe && c.unread > 0 ? s.atMe : "", text: c.lastMessage?.preview ?? "" };
742
+ }
743
+ var two = (n) => String(n).padStart(2, "0");
744
+ var DAY = 864e5;
745
+ function startOfDay(d) {
746
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
747
+ }
748
+ function formatConversationTime(time, s, now = Date.now()) {
749
+ const t = new Date(time);
750
+ const n = new Date(now);
751
+ const diff = Math.round((startOfDay(n) - startOfDay(t)) / DAY);
752
+ if (diff <= 0) return `${two(t.getHours())}:${two(t.getMinutes())}`;
753
+ if (diff === 1) return s.yesterday;
754
+ if (diff < 7) return s.weekdays[(t.getDay() + 6) % 7];
755
+ if (t.getFullYear() === n.getFullYear()) return `${t.getMonth() + 1}/${t.getDate()}`;
756
+ return `${t.getFullYear()}/${t.getMonth() + 1}/${t.getDate()}`;
757
+ }
758
+ function formatMessageTime(time, s, now = Date.now()) {
759
+ const t = new Date(time);
760
+ const hm = `${two(t.getHours())}:${two(t.getMinutes())}`;
761
+ const day = formatConversationTime(time, s, now);
762
+ return day === hm ? hm : `${day} ${hm}`;
763
+ }
764
+ function isTipMessage(m) {
765
+ return m.isRecalled || m.type === "group_tip" || m.from === "@system";
766
+ }
767
+ function tipText(m, s, opts) {
768
+ const { nameOf, me, isGroup } = opts;
769
+ const c = m.content ?? {};
770
+ const snap = c.names;
771
+ const who = (id) => {
772
+ if (id === "@system") return s.system;
773
+ if (id === me) return s.you;
774
+ const n = nameOf(id);
775
+ if (n !== id) return n;
776
+ const v = snap && typeof snap === "object" && !Array.isArray(snap) ? snap[id] : null;
777
+ return typeof v === "string" && v !== "" ? v : id;
778
+ };
779
+ if (m.isRecalled) {
780
+ let name;
781
+ switch (m.recalledBy) {
782
+ case "agent":
783
+ case "server":
784
+ case "admin":
785
+ name = s.admin;
786
+ break;
787
+ default:
788
+ name = m.isSelf ? s.you : isGroup ? nameOf(m.from) : s.peer;
789
+ }
790
+ return fill(s.recalled, { name });
791
+ }
792
+ if (m.type !== "group_tip") {
793
+ const t = c.text;
794
+ return typeof t === "string" && t !== "" ? t : s.tipOther;
795
+ }
796
+ const op = who(typeof c.operator === "string" ? c.operator : "@system");
797
+ const targets = Array.isArray(c.targets) ? c.targets.filter((x) => typeof x === "string").map(who).join("、") : "";
798
+ const f = (tpl, name = "") => fill(tpl, { op, targets, name });
799
+ switch (c.action) {
800
+ case "create":
801
+ return f(s.tipCreate);
802
+ case "join":
803
+ return f(s.tipJoin);
804
+ case "quit":
805
+ return f(s.tipQuit);
806
+ case "kick":
807
+ return f(s.tipKick);
808
+ case "dismiss":
809
+ return f(s.tipDismiss);
810
+ case "update": {
811
+ const name = c.fields && typeof c.fields === "object" ? c.fields.name : null;
812
+ return typeof name === "string" ? f(s.tipRename, name) : f(s.tipUpdate);
813
+ }
814
+ case "notice":
815
+ return f(s.tipNotice);
816
+ case "role":
817
+ return f(c.role === 1 ? s.tipAdminOn : s.tipAdminOff);
818
+ case "transfer":
819
+ return f(s.tipTransfer);
820
+ case "mute":
821
+ return f(c.until == null ? s.tipUnmute : s.tipMute);
822
+ default:
823
+ return s.tipOther;
824
+ }
825
+ }
826
+
827
+ // src/core/media.ts
828
+ var IMAGE_MIME = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
829
+ var VIDEO_MIME = /* @__PURE__ */ new Set(["video/mp4", "video/quicktime"]);
830
+ function classifyFile(file) {
831
+ const mime = (file.type || "").toLowerCase();
832
+ if (IMAGE_MIME.has(mime)) return "image";
833
+ if (VIDEO_MIME.has(mime)) return "video";
834
+ return "file";
835
+ }
836
+ function checkSize(file, kind, features) {
837
+ if (kind === "image") return null;
838
+ const maxMb = kind === "video" ? features.videoMaxMb : features.fileMaxMb;
839
+ if (!(maxMb > 0)) return { reason: "disabled", maxMb: 0 };
840
+ return file.size > maxMb * 1024 * 1024 ? { reason: "tooLarge", maxMb } : null;
841
+ }
842
+ function readVideoMeta(file, timeoutMs = 1e4) {
843
+ return new Promise((resolve) => {
844
+ const url = URL.createObjectURL(file);
845
+ const video = document.createElement("video");
846
+ let done = false;
847
+ const finish = (v) => {
848
+ if (done) return;
849
+ done = true;
850
+ clearTimeout(timer);
851
+ video.onloadedmetadata = null;
852
+ video.onerror = null;
853
+ video.removeAttribute("src");
854
+ video.load();
855
+ URL.revokeObjectURL(url);
856
+ resolve(v);
857
+ };
858
+ const timer = setTimeout(() => finish(null), timeoutMs);
859
+ video.preload = "metadata";
860
+ video.muted = true;
861
+ video.onloadedmetadata = () => {
862
+ const width = video.videoWidth;
863
+ const height = video.videoHeight;
864
+ const sec = video.duration;
865
+ if (!(width > 0 && height > 0 && Number.isFinite(sec) && sec > 0)) return finish(null);
866
+ finish({ durationMs: Math.round(sec * 1e3), width, height });
867
+ };
868
+ video.onerror = () => finish(null);
869
+ video.src = url;
870
+ });
871
+ }
872
+ var ObjectUrlRegistry = class {
873
+ constructor() {
874
+ this.entries = /* @__PURE__ */ new Map();
875
+ }
876
+ /** 登记并返回地址;同一 key 同一文件重复登记返回原地址,换了文件先回收旧的。 */
877
+ register(key, file) {
878
+ const hit = this.entries.get(key);
879
+ if (hit && hit.file === file) return hit.url;
880
+ if (hit) URL.revokeObjectURL(hit.url);
881
+ const url = URL.createObjectURL(file);
882
+ this.entries.set(key, { file, url });
883
+ return url;
884
+ }
885
+ get(key) {
886
+ return this.entries.get(key)?.url ?? null;
887
+ }
888
+ release(key) {
889
+ const hit = this.entries.get(key);
890
+ if (!hit) return;
891
+ URL.revokeObjectURL(hit.url);
892
+ this.entries.delete(key);
893
+ }
894
+ /** 和一份 key → 文件 的表对齐(如 ChatController 快照的 `localFiles`):缺的登记,多出来的回收。 */
895
+ sync(files) {
896
+ for (const key of [...this.entries.keys()]) if (!(key in files)) this.release(key);
897
+ for (const [key, file] of Object.entries(files)) this.register(key, file);
898
+ }
899
+ releaseAll() {
900
+ for (const { url } of this.entries.values()) URL.revokeObjectURL(url);
901
+ this.entries.clear();
902
+ }
903
+ };
904
+
905
+ // src/core/memberCache.ts
906
+ var _MemberCache = class _MemberCache {
907
+ constructor(im, groupId) {
908
+ this.im = im;
909
+ this.groupId = groupId;
910
+ this.map = /* @__PURE__ */ new Map();
911
+ this.list = null;
912
+ this.gen = 0;
913
+ this.disposed = false;
914
+ this.off = null;
915
+ this.listeners = new ListenerSet();
916
+ this.subscribe = (fn) => this.listeners.add(fn);
917
+ this.getSnapshot = () => this.map;
918
+ }
919
+ /** 开始监听群变动并拉第一次。重复调用无效。 */
920
+ start() {
921
+ if (this.off || this.disposed) return;
922
+ const gid = this.groupId.toLowerCase();
923
+ this.off = this.im.on("groupChanged", (c) => {
924
+ if (c.groupId.toLowerCase() === gid) void this.reload();
925
+ });
926
+ void this.reload();
927
+ }
928
+ /** 当前在群的成员,按进群先后。 */
929
+ get members() {
930
+ return this.list ?? (this.list = [...this.map.values()]);
931
+ }
932
+ get(userId) {
933
+ return this.map.get(userId);
934
+ }
935
+ /** 显示名:在缓存里用昵称(空时 userId),不在(已退群)用 userId。 */
936
+ nameOf(userId) {
937
+ const m = this.map.get(userId);
938
+ return !m || m.nickname === "" ? userId : m.nickname;
939
+ }
940
+ async reload() {
941
+ const gen = ++this.gen;
942
+ const next = /* @__PURE__ */ new Map();
943
+ let cursor = null;
944
+ try {
945
+ do {
946
+ const page = await this.im.groupMembers(this.groupId, {
947
+ cursor,
948
+ limit: 100
949
+ });
950
+ for (const m of page.items) next.set(m.userId, m);
951
+ cursor = page.nextCursor;
952
+ } while (cursor !== null && next.size < _MemberCache.max);
953
+ } catch {
954
+ return;
955
+ }
956
+ if (this.disposed || gen !== this.gen) return;
957
+ this.map = next;
958
+ this.list = null;
959
+ this.listeners.notify();
960
+ }
961
+ dispose() {
962
+ this.disposed = true;
963
+ this.off?.();
964
+ this.off = null;
965
+ this.listeners.clear();
966
+ }
967
+ };
968
+ _MemberCache.max = 500;
969
+ var MemberCache = _MemberCache;
970
+
971
+ // src/ui/widgets/feedback.tsx
972
+ import { createContext as createContext2, useCallback as useCallback2, useContext as useContext2, useMemo as useMemo2, useRef as useRef2, useState } from "react";
973
+
974
+ // src/ui/widgets/useFocusTrap.ts
975
+ import { useEffect, useRef } from "react";
976
+ var FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])';
977
+ function useFocusTrap(active = true) {
978
+ const ref = useRef(null);
979
+ useEffect(() => {
980
+ if (!active) return;
981
+ const el = ref.current;
982
+ if (!el) return;
983
+ const prev = document.activeElement;
984
+ const first = el.querySelector("[data-autofocus]") ?? el.querySelector(FOCUSABLE);
985
+ (first ?? el).focus();
986
+ const onKey = (e) => {
987
+ if (e.key !== "Tab") return;
988
+ const items = Array.from(el.querySelectorAll(FOCUSABLE));
989
+ if (!items.length) return;
990
+ const a = items[0], b = items[items.length - 1];
991
+ if (e.shiftKey && document.activeElement === a) {
992
+ e.preventDefault();
993
+ b.focus();
994
+ } else if (!e.shiftKey && document.activeElement === b) {
995
+ e.preventDefault();
996
+ a.focus();
997
+ }
998
+ };
999
+ el.addEventListener("keydown", onKey);
1000
+ return () => {
1001
+ el.removeEventListener("keydown", onKey);
1002
+ if (prev && document.contains(prev)) prev.focus();
1003
+ };
1004
+ }, [active]);
1005
+ return ref;
1006
+ }
1007
+
1008
+ // src/ui/widgets/feedback.tsx
1009
+ import { jsx, jsxs } from "react/jsx-runtime";
1010
+ var Ctx = createContext2(null);
1011
+ function ConfirmBox({ o, labels, done }) {
1012
+ const ref = useFocusTrap();
1013
+ return /* @__PURE__ */ jsxs("div", { className: "gkim-dialog-layer gkim-dialog-layer--top", onKeyDown: (e) => {
1014
+ if (e.key === "Escape") {
1015
+ e.stopPropagation();
1016
+ done(false);
1017
+ }
1018
+ }, children: [
1019
+ /* @__PURE__ */ jsx("div", { className: "gkim-scrim", onClick: () => done(false) }),
1020
+ /* @__PURE__ */ jsxs("div", { className: "gkim-dialog gkim-confirm", ref, role: "alertdialog", "aria-modal": "true", "aria-label": o.title ?? o.content, tabIndex: -1, children: [
1021
+ o.title && /* @__PURE__ */ jsx("h2", { className: "gkim-confirm__title", children: o.title }),
1022
+ /* @__PURE__ */ jsx("p", { className: "gkim-confirm__text", children: o.content }),
1023
+ /* @__PURE__ */ jsxs("div", { className: "gkim-confirm__actions", children: [
1024
+ /* @__PURE__ */ jsx("button", { type: "button", className: "gkim-btn", onClick: () => done(false), children: labels.cancel }),
1025
+ /* @__PURE__ */ jsx("button", { type: "button", "data-autofocus": true, className: o.danger ? "gkim-btn gkim-btn--danger" : "gkim-btn gkim-btn--primary", onClick: () => done(true), children: o.ok ?? labels.ok })
1026
+ ] })
1027
+ ] })
1028
+ ] });
1029
+ }
1030
+ function FeedbackProvider({ labels, children }) {
1031
+ const [toastText, setToast] = useState(null);
1032
+ const timer = useRef2(void 0);
1033
+ const [pending, setPending] = useState(null);
1034
+ const toast = useCallback2((text) => {
1035
+ setToast(text);
1036
+ clearTimeout(timer.current);
1037
+ timer.current = setTimeout(() => setToast(null), 2500);
1038
+ }, []);
1039
+ const confirm = useCallback2((o) => new Promise((resolve) => setPending({ o, resolve })), []);
1040
+ const value = useMemo2(() => ({ toast, confirm }), [toast, confirm]);
1041
+ return /* @__PURE__ */ jsxs(Ctx.Provider, { value, children: [
1042
+ children,
1043
+ pending && /* @__PURE__ */ jsx(ConfirmBox, { o: pending.o, labels, done: (v) => {
1044
+ pending.resolve(v);
1045
+ setPending(null);
1046
+ } }),
1047
+ /* @__PURE__ */ jsx("div", { className: "gkim-toast-region", role: "status", "aria-live": "polite", children: toastText && /* @__PURE__ */ jsx("div", { className: "gkim-toast", children: toastText }) })
1048
+ ] });
1049
+ }
1050
+ function useFeedback() {
1051
+ const v = useContext2(Ctx);
1052
+ if (!v) throw new Error("没有找到 GuokitImUi:IM 组件要放在 GuokitImUi 下面。");
1053
+ return v;
1054
+ }
1055
+
1056
+ // src/ui/widgets/Icon.tsx
1057
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1058
+ var PATHS = {
1059
+ message: /* @__PURE__ */ jsx2("path", { d: "M4 5h16v11H9l-5 4z" }),
1060
+ back: /* @__PURE__ */ jsx2("path", { d: "M15 5l-7 7 7 7" }),
1061
+ close: /* @__PURE__ */ jsx2("path", { d: "M6 6l12 12M18 6L6 18" }),
1062
+ more: /* @__PURE__ */ jsxs2(Fragment, { children: [
1063
+ /* @__PURE__ */ jsx2("circle", { cx: "5", cy: "12", r: "1.2" }),
1064
+ /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "12", r: "1.2" }),
1065
+ /* @__PURE__ */ jsx2("circle", { cx: "19", cy: "12", r: "1.2" })
1066
+ ] }),
1067
+ emoji: /* @__PURE__ */ jsxs2(Fragment, { children: [
1068
+ /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "12", r: "9.5" }),
1069
+ /* @__PURE__ */ jsx2("path", { d: "M8 14.5a5 5 0 0 0 8 0" }),
1070
+ /* @__PURE__ */ jsx2("path", { d: "M9 9.5v.01M15 9.5v.01" })
1071
+ ] }),
1072
+ image: /* @__PURE__ */ jsxs2(Fragment, { children: [
1073
+ /* @__PURE__ */ jsx2("rect", { x: "3", y: "4", width: "18", height: "16", rx: "2" }),
1074
+ /* @__PURE__ */ jsx2("circle", { cx: "9", cy: "10", r: "2" }),
1075
+ /* @__PURE__ */ jsx2("path", { d: "M21 16l-5-5-9 9" })
1076
+ ] }),
1077
+ file: /* @__PURE__ */ jsxs2(Fragment, { children: [
1078
+ /* @__PURE__ */ jsx2("path", { d: "M6 3h8l4 4v14H6z" }),
1079
+ /* @__PURE__ */ jsx2("path", { d: "M14 3v4h4" })
1080
+ ] }),
1081
+ plus: /* @__PURE__ */ jsxs2(Fragment, { children: [
1082
+ /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "12", r: "9.5" }),
1083
+ /* @__PURE__ */ jsx2("path", { d: "M12 8v8M8 12h8" })
1084
+ ] }),
1085
+ copy: /* @__PURE__ */ jsxs2(Fragment, { children: [
1086
+ /* @__PURE__ */ jsx2("rect", { x: "8", y: "8", width: "12", height: "12", rx: "2" }),
1087
+ /* @__PURE__ */ jsx2("path", { d: "M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3" })
1088
+ ] }),
1089
+ recall: /* @__PURE__ */ jsxs2(Fragment, { children: [
1090
+ /* @__PURE__ */ jsx2("path", { d: "M9 14L4 9l5-5" }),
1091
+ /* @__PURE__ */ jsx2("path", { d: "M4 9h10a6 6 0 0 1 0 12h-3" })
1092
+ ] }),
1093
+ report: /* @__PURE__ */ jsx2(Fragment, { children: /* @__PURE__ */ jsx2("path", { d: "M5 21V4h11l-1.5 4L16 12H5" }) }),
1094
+ down: /* @__PURE__ */ jsx2("path", { d: "M12 5v14M6 13l6 6 6-6" }),
1095
+ play: /* @__PURE__ */ jsx2("path", { d: "M8 5l11 7-11 7z" }),
1096
+ pause: /* @__PURE__ */ jsx2("path", { d: "M8 5v14M16 5v14" }),
1097
+ zoomIn: /* @__PURE__ */ jsxs2(Fragment, { children: [
1098
+ /* @__PURE__ */ jsx2("circle", { cx: "11", cy: "11", r: "7" }),
1099
+ /* @__PURE__ */ jsx2("path", { d: "M21 21l-4.3-4.3M11 8v6M8 11h6" })
1100
+ ] }),
1101
+ zoomOut: /* @__PURE__ */ jsxs2(Fragment, { children: [
1102
+ /* @__PURE__ */ jsx2("circle", { cx: "11", cy: "11", r: "7" }),
1103
+ /* @__PURE__ */ jsx2("path", { d: "M21 21l-4.3-4.3M8 11h6" })
1104
+ ] }),
1105
+ external: /* @__PURE__ */ jsxs2(Fragment, { children: [
1106
+ /* @__PURE__ */ jsx2("path", { d: "M14 4h6v6" }),
1107
+ /* @__PURE__ */ jsx2("path", { d: "M20 4l-9 9" }),
1108
+ /* @__PURE__ */ jsx2("path", { d: "M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5" })
1109
+ ] }),
1110
+ location: /* @__PURE__ */ jsxs2(Fragment, { children: [
1111
+ /* @__PURE__ */ jsx2("path", { d: "M12 21s-7-6.2-7-11a7 7 0 0 1 14 0c0 4.8-7 11-7 11z" }),
1112
+ /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "10", r: "2.5" })
1113
+ ] }),
1114
+ alert: /* @__PURE__ */ jsxs2(Fragment, { children: [
1115
+ /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "12", r: "9.5" }),
1116
+ /* @__PURE__ */ jsx2("path", { d: "M12 7.5v5.5M12 16.5v.01" })
1117
+ ] }),
1118
+ retry: /* @__PURE__ */ jsxs2(Fragment, { children: [
1119
+ /* @__PURE__ */ jsx2("path", { d: "M20 11a8 8 0 1 0-2.3 5.7" }),
1120
+ /* @__PURE__ */ jsx2("path", { d: "M20 4v7h-7" })
1121
+ ] }),
1122
+ group: /* @__PURE__ */ jsxs2(Fragment, { children: [
1123
+ /* @__PURE__ */ jsx2("circle", { cx: "9", cy: "8", r: "3.5" }),
1124
+ /* @__PURE__ */ jsx2("path", { d: "M2.5 20a6.5 6.5 0 0 1 13 0" }),
1125
+ /* @__PURE__ */ jsx2("path", { d: "M16 4.5a3.5 3.5 0 0 1 0 7" }),
1126
+ /* @__PURE__ */ jsx2("path", { d: "M18 14a6 6 0 0 1 3.5 6" })
1127
+ ] }),
1128
+ check: /* @__PURE__ */ jsx2("path", { d: "M5 12l5 5 9-10" }),
1129
+ checkAll: /* @__PURE__ */ jsxs2(Fragment, { children: [
1130
+ /* @__PURE__ */ jsx2("path", { d: "M2 12l5 5 9-10" }),
1131
+ /* @__PURE__ */ jsx2("path", { d: "M12 16l1 1 9-10" })
1132
+ ] }),
1133
+ mute: /* @__PURE__ */ jsxs2(Fragment, { children: [
1134
+ /* @__PURE__ */ jsx2("path", { d: "M13.7 21a2 2 0 0 1-3.4 0" }),
1135
+ /* @__PURE__ */ jsx2("path", { d: "M18 8a6 6 0 0 0-9.3-5" }),
1136
+ /* @__PURE__ */ jsx2("path", { d: "M6.3 6.3A6 6 0 0 0 6 8c0 7-3 9-3 9h14" }),
1137
+ /* @__PURE__ */ jsx2("path", { d: "M3 3l18 18" })
1138
+ ] })
1139
+ };
1140
+ function Icon({ name, size = 20 }) {
1141
+ return /* @__PURE__ */ jsx2(
1142
+ "svg",
1143
+ {
1144
+ className: "gkim-icon",
1145
+ width: size,
1146
+ height: size,
1147
+ viewBox: "0 0 24 24",
1148
+ fill: "none",
1149
+ stroke: "currentColor",
1150
+ strokeWidth: 1.8,
1151
+ strokeLinecap: "round",
1152
+ strokeLinejoin: "round",
1153
+ "aria-hidden": "true",
1154
+ children: PATHS[name]
1155
+ }
1156
+ );
1157
+ }
1158
+
1159
+ // src/ui/widgets/Page.tsx
1160
+ import { useId } from "react";
1161
+
1162
+ // src/ui/layout/frame.ts
1163
+ import { createContext as createContext3, useContext as useContext3 } from "react";
1164
+ var noop = () => {
1165
+ };
1166
+ var FrameContext = createContext3({ kind: "standalone", canBack: false, back: noop, close: noop });
1167
+ function useFrame() {
1168
+ return useContext3(FrameContext);
1169
+ }
1170
+
1171
+ // src/ui/widgets/Page.tsx
1172
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1173
+ function Page({ title, actions, banner, footer, children, className, scroll = true }) {
1174
+ const f = useFrame();
1175
+ const s = useImUi().strings;
1176
+ const titleId = useId();
1177
+ const dialog = f.kind === "dialog";
1178
+ return /* @__PURE__ */ jsxs3(
1179
+ "section",
1180
+ {
1181
+ className: `gkim-page gkim-page--${f.kind}${className ? " " + className : ""}`,
1182
+ role: dialog ? "dialog" : void 0,
1183
+ "aria-modal": dialog || void 0,
1184
+ "aria-labelledby": titleId,
1185
+ children: [
1186
+ /* @__PURE__ */ jsxs3("header", { className: "gkim-page__head", children: [
1187
+ f.canBack && /* @__PURE__ */ jsx3("button", { type: "button", className: "gkim-iconbtn", "aria-label": s.back, onClick: f.back, children: /* @__PURE__ */ jsx3(Icon, { name: "back" }) }),
1188
+ /* @__PURE__ */ jsx3("h2", { id: titleId, className: "gkim-page__title", children: title }),
1189
+ /* @__PURE__ */ jsxs3("div", { className: "gkim-page__actions", children: [
1190
+ actions,
1191
+ (f.kind === "drawer" || dialog) && /* @__PURE__ */ jsx3("button", { type: "button", className: "gkim-iconbtn", "aria-label": s.close, onClick: f.close, children: /* @__PURE__ */ jsx3(Icon, { name: "close" }) })
1192
+ ] })
1193
+ ] }),
1194
+ banner,
1195
+ /* @__PURE__ */ jsx3("div", { className: scroll ? "gkim-page__body gkim-page__body--scroll" : "gkim-page__body", children }),
1196
+ footer && /* @__PURE__ */ jsx3("footer", { className: "gkim-page__foot", children: footer })
1197
+ ]
1198
+ }
1199
+ );
1200
+ }
1201
+
1202
+ // src/ui/chat/Composer.tsx
1203
+ import { forwardRef, useCallback as useCallback4, useEffect as useEffect3, useImperativeHandle, useLayoutEffect as useLayoutEffect2, useMemo as useMemo3, useRef as useRef4, useState as useState4 } from "react";
1204
+
1205
+ // src/core/mention.ts
1206
+ var mentionToken = (m) => `@${m.name} `;
1207
+ var _MentionEditing = class _MentionEditing {
1208
+ constructor() {
1209
+ this.list = [];
1210
+ }
1211
+ get mentions() {
1212
+ return this.list;
1213
+ }
1214
+ clear() {
1215
+ this.list = [];
1216
+ }
1217
+ /** 把 `value` 里 `atIndex` 处那个「@」换成 `@昵称 `,光标放到它后面;那里不是「@」时插在光标处。 */
1218
+ insert(value, atIndex, m) {
1219
+ const { text } = value;
1220
+ const token = mentionToken(m);
1221
+ const hasAt = atIndex >= 0 && atIndex < text.length && text[atIndex] === "@";
1222
+ const start = hasAt ? atIndex : Math.min(Math.max(value.cursor, 0), text.length);
1223
+ const end = hasAt ? atIndex + 1 : start;
1224
+ this.list.push(m);
1225
+ return { text: text.slice(0, start) + token + text.slice(end), cursor: start + token.length };
1226
+ }
1227
+ /**
1228
+ * 输入变化时调:删除碰到某个 `@昵称 ` 时把整段删掉。返回应当显示的值;没变就原样返回 `next`(同一引用)。
1229
+ * 删除同时有插入(替换选区)时不处理。
1230
+ */
1231
+ onChanged(old, next) {
1232
+ const now = next.text;
1233
+ if (now.length >= old.length || this.list.length === 0) return next;
1234
+ let a = 0;
1235
+ while (a < now.length && old[a] === now[a]) a++;
1236
+ let b = 0;
1237
+ while (b < now.length - a && old[old.length - 1 - b] === now[now.length - 1 - b]) b++;
1238
+ const delStart = a;
1239
+ const delEnd = old.length - b;
1240
+ if (now.length - a - b !== 0) return next;
1241
+ for (const m of this.list) {
1242
+ const token = mentionToken(m);
1243
+ let from = 0;
1244
+ for (; ; ) {
1245
+ const i = old.indexOf(token, from);
1246
+ if (i < 0) break;
1247
+ const j = i + token.length;
1248
+ if (delStart < j && delEnd > i) {
1249
+ const s = Math.min(delStart, i);
1250
+ const e = Math.max(delEnd, j);
1251
+ return { text: old.slice(0, s) + old.slice(e), cursor: s };
1252
+ }
1253
+ from = j;
1254
+ }
1255
+ }
1256
+ return next;
1257
+ }
1258
+ /** 发送时的 at 列表:文字里还完整留着的 @,去重,最多 20 个。 */
1259
+ atIds(text) {
1260
+ const out = [];
1261
+ for (const m of this.list) {
1262
+ if (text.includes(mentionToken(m)) && !out.includes(m.userId)) out.push(m.userId);
1263
+ if (out.length >= _MentionEditing.maxAt) break;
1264
+ }
1265
+ return out;
1266
+ }
1267
+ };
1268
+ /** 一条最多 @ 20 人(服务端限制)。 */
1269
+ _MentionEditing.maxAt = 20;
1270
+ var MentionEditing = _MentionEditing;
1271
+
1272
+ // src/ui/widgets/Avatar.tsx
1273
+ import { useState as useState2 } from "react";
1274
+ import { jsx as jsx4 } from "react/jsx-runtime";
1275
+ var PALETTE = ["#0F766E", "#B45309", "#7C3AED", "#BE185D", "#4D7C0F", "#0369A1", "#9A3412", "#475569"];
1276
+ function avatarColor(id) {
1277
+ let h = 0;
1278
+ for (let i = 0; i < id.length; i++) h = h * 31 + id.charCodeAt(i) & 2147483647;
1279
+ return PALETTE[h % PALETTE.length];
1280
+ }
1281
+ function avatarInitial(name, id) {
1282
+ const s = name.trim() || id;
1283
+ if (!s) return "?";
1284
+ return String.fromCodePoint(s.codePointAt(0)).toUpperCase();
1285
+ }
1286
+ function Avatar({ id, name, url, size, group, onClick }) {
1287
+ const [broken, setBroken] = useState2(null);
1288
+ const label = name || id;
1289
+ const style = size ? { ["--gkim-av"]: `${size}px` } : void 0;
1290
+ const cls = `gkim-avatar${group ? " gkim-avatar--group" : ""}`;
1291
+ const inner = url && broken !== url ? /* @__PURE__ */ jsx4("img", { src: url, alt: "", onError: () => setBroken(url) }) : /* @__PURE__ */ jsx4("span", { style: { background: avatarColor(id) }, children: avatarInitial(name, id) });
1292
+ if (onClick) {
1293
+ return /* @__PURE__ */ jsx4("button", { type: "button", className: cls, style, "aria-label": label, onClick, children: inner });
1294
+ }
1295
+ return /* @__PURE__ */ jsx4("span", { className: cls, style, role: "img", "aria-label": label, children: inner });
1296
+ }
1297
+
1298
+ // src/ui/widgets/Menu.tsx
1299
+ import { useCallback as useCallback3, useEffect as useEffect2, useLayoutEffect, useRef as useRef3, useState as useState3 } from "react";
1300
+ import { createPortal } from "react-dom";
1301
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1302
+ function Menu({ entries, x, y, onClose, label }) {
1303
+ const ref = useRef3(null);
1304
+ const [pos, setPos] = useState3({ left: x, top: y });
1305
+ const [sub, setSub] = useState3(null);
1306
+ useLayoutEffect(() => {
1307
+ const el = ref.current;
1308
+ if (!el) return;
1309
+ const r = el.getBoundingClientRect();
1310
+ const vw = window.innerWidth, vh = window.innerHeight;
1311
+ setPos({ left: x + r.width > vw - 8 ? Math.max(8, x - r.width) : x, top: y + r.height > vh - 8 ? Math.max(8, y - r.height) : y });
1312
+ }, [x, y]);
1313
+ useEffect2(() => {
1314
+ const prev = document.activeElement;
1315
+ ref.current?.querySelector('[role="menuitem"]:not([disabled])')?.focus();
1316
+ const down = (e) => {
1317
+ if (ref.current && !ref.current.contains(e.target)) onClose();
1318
+ };
1319
+ document.addEventListener("mousedown", down, true);
1320
+ window.addEventListener("blur", onClose);
1321
+ return () => {
1322
+ document.removeEventListener("mousedown", down, true);
1323
+ window.removeEventListener("blur", onClose);
1324
+ if (prev && document.contains(prev)) prev.focus();
1325
+ };
1326
+ }, [onClose]);
1327
+ const onKey = (e) => {
1328
+ const items = Array.from(ref.current?.querySelectorAll(':scope > [role="menuitem"]:not([disabled])') ?? []);
1329
+ const i = items.indexOf(document.activeElement);
1330
+ if (e.key === "ArrowDown") {
1331
+ e.preventDefault();
1332
+ items[(i + 1) % items.length]?.focus();
1333
+ } else if (e.key === "ArrowUp") {
1334
+ e.preventDefault();
1335
+ items[(i - 1 + items.length) % items.length]?.focus();
1336
+ } else if (e.key === "Escape") {
1337
+ e.preventDefault();
1338
+ e.stopPropagation();
1339
+ onClose();
1340
+ } else if (e.key === "Tab") {
1341
+ e.preventDefault();
1342
+ onClose();
1343
+ }
1344
+ };
1345
+ const menu = /* @__PURE__ */ jsx5(
1346
+ "div",
1347
+ {
1348
+ ref,
1349
+ className: "gkim-menu gkim-root-menu",
1350
+ role: "menu",
1351
+ "aria-label": label,
1352
+ style: pos,
1353
+ onKeyDown: onKey,
1354
+ onContextMenu: (e) => e.preventDefault(),
1355
+ children: entries.map((it, i) => /* @__PURE__ */ jsxs4(
1356
+ "button",
1357
+ {
1358
+ type: "button",
1359
+ role: "menuitem",
1360
+ disabled: it.disabled,
1361
+ "aria-haspopup": it.children ? "menu" : void 0,
1362
+ "aria-expanded": it.children ? sub === i : void 0,
1363
+ className: `gkim-menu__item${it.danger ? " gkim-menu__item--danger" : ""}`,
1364
+ onMouseEnter: () => setSub(it.children ? i : null),
1365
+ onKeyDown: (e) => {
1366
+ if (it.children && e.key === "ArrowRight") {
1367
+ e.preventDefault();
1368
+ setSub(i);
1369
+ }
1370
+ },
1371
+ onClick: () => {
1372
+ if (it.children) {
1373
+ setSub(i);
1374
+ return;
1375
+ }
1376
+ onClose();
1377
+ it.onSelect();
1378
+ },
1379
+ children: [
1380
+ it.icon,
1381
+ /* @__PURE__ */ jsx5("span", { children: it.label }),
1382
+ it.children && /* @__PURE__ */ jsx5("span", { className: "gkim-menu__arrow", children: "›" }),
1383
+ it.children && sub === i && /* @__PURE__ */ jsx5("div", { className: "gkim-menu gkim-menu--sub", role: "menu", children: it.children.map((c, j) => /* @__PURE__ */ jsx5(
1384
+ "span",
1385
+ {
1386
+ role: "menuitem",
1387
+ tabIndex: 0,
1388
+ className: "gkim-menu__item",
1389
+ onClick: (e) => {
1390
+ e.stopPropagation();
1391
+ onClose();
1392
+ c.onSelect();
1393
+ },
1394
+ onKeyDown: (e) => {
1395
+ if (e.key === "Enter") {
1396
+ e.stopPropagation();
1397
+ onClose();
1398
+ c.onSelect();
1399
+ }
1400
+ },
1401
+ children: c.label
1402
+ },
1403
+ j
1404
+ )) })
1405
+ ]
1406
+ },
1407
+ i
1408
+ ))
1409
+ }
1410
+ );
1411
+ const host = typeof document !== "undefined" && (document.activeElement?.closest(".gkim-root") ?? document.querySelector(".gkim-root")) || document.body;
1412
+ return createPortal(menu, host);
1413
+ }
1414
+ function useContextMenu() {
1415
+ const [at, setAt] = useState3(null);
1416
+ const timer = useRef3(void 0);
1417
+ const start = useRef3(null);
1418
+ const bind = {
1419
+ onContextMenu: (e) => {
1420
+ e.preventDefault();
1421
+ setAt({ x: e.clientX, y: e.clientY });
1422
+ },
1423
+ onTouchStart: (e) => {
1424
+ const t = e.touches[0];
1425
+ start.current = { x: t.clientX, y: t.clientY };
1426
+ timer.current = setTimeout(() => {
1427
+ if (start.current) setAt(start.current);
1428
+ }, 500);
1429
+ },
1430
+ onTouchMove: (e) => {
1431
+ const t = e.touches[0], s = start.current;
1432
+ if (s && Math.hypot(t.clientX - s.x, t.clientY - s.y) > 10) {
1433
+ clearTimeout(timer.current);
1434
+ start.current = null;
1435
+ }
1436
+ },
1437
+ onTouchEnd: () => {
1438
+ clearTimeout(timer.current);
1439
+ start.current = null;
1440
+ }
1441
+ };
1442
+ const close = useCallback3(() => setAt(null), []);
1443
+ return { at, open: setAt, close, bind };
1444
+ }
1445
+
1446
+ // src/ui/chat/emojis.ts
1447
+ var EMOJIS = [
1448
+ "😀",
1449
+ "😁",
1450
+ "😂",
1451
+ "🤣",
1452
+ "😊",
1453
+ "😍",
1454
+ "😘",
1455
+ "😜",
1456
+ "🤔",
1457
+ "😏",
1458
+ "😎",
1459
+ "🥳",
1460
+ "😭",
1461
+ "😢",
1462
+ "😡",
1463
+ "😱",
1464
+ "😴",
1465
+ "🤗",
1466
+ "🙄",
1467
+ "😅",
1468
+ "😆",
1469
+ "😉",
1470
+ "😋",
1471
+ "😇",
1472
+ "🥰",
1473
+ "🤩",
1474
+ "😌",
1475
+ "😔",
1476
+ "😳",
1477
+ "🤯",
1478
+ "😤",
1479
+ "😷",
1480
+ "🤒",
1481
+ "🤧",
1482
+ "🥺",
1483
+ "😬",
1484
+ "🤐",
1485
+ "🤫",
1486
+ "🤭",
1487
+ "😶",
1488
+ "👍",
1489
+ "👎",
1490
+ "👏",
1491
+ "🙏",
1492
+ "💪",
1493
+ "👌",
1494
+ "✌️",
1495
+ "🤝",
1496
+ "👋",
1497
+ "🙌",
1498
+ "❤️",
1499
+ "💔",
1500
+ "💯",
1501
+ "🔥",
1502
+ "✨",
1503
+ "🎉",
1504
+ "🎁",
1505
+ "🌹",
1506
+ "☕",
1507
+ "🍺",
1508
+ "🍉",
1509
+ "🍰",
1510
+ "🧧",
1511
+ "💰",
1512
+ "📅",
1513
+ "⏰",
1514
+ "✅",
1515
+ "❌",
1516
+ "❓",
1517
+ "⭐"
1518
+ ];
1519
+
1520
+ // src/ui/chat/Composer.tsx
1521
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1522
+ var MAX_ROWS_PX = 6 * 21 + 8;
1523
+ var seq = 0;
1524
+ var Composer = forwardRef(function Composer2(p, ref) {
1525
+ const { im, strings: s, moreItems } = useImUi();
1526
+ const { toast } = useFeedback();
1527
+ const [text, setText] = useState4("");
1528
+ const [tray, setTray] = useState4([]);
1529
+ const [emoji, setEmoji] = useState4(false);
1530
+ const [more, setMore] = useState4(null);
1531
+ const [mention, setMention] = useState4(null);
1532
+ const [busy, setBusy] = useState4(false);
1533
+ const closeMore = useCallback4(() => setMore(null), []);
1534
+ const ta = useRef4(null);
1535
+ const media = useRef4(null);
1536
+ const anyFile = useRef4(null);
1537
+ const mentions = useMemo3(() => new MentionEditing(), []);
1538
+ const f = p.features;
1539
+ const canImage = true;
1540
+ const canVideo = (f?.videoMaxMb ?? 0) > 0;
1541
+ const canFile = (f?.fileMaxMb ?? 0) > 0;
1542
+ useLayoutEffect2(() => {
1543
+ const el = ta.current;
1544
+ if (!el) return;
1545
+ el.style.height = "auto";
1546
+ el.style.height = `${Math.min(el.scrollHeight, MAX_ROWS_PX)}px`;
1547
+ }, [text]);
1548
+ const addFiles = (files) => {
1549
+ if (!f) return;
1550
+ const ok = [];
1551
+ for (const file of files) {
1552
+ let kind = classifyFile(file);
1553
+ if (kind === "video" && !canVideo) kind = "file";
1554
+ const issue = checkSize(file, kind, f);
1555
+ if (issue) {
1556
+ toast(issue.reason === "disabled" ? s.fileNotAllowed : fill(s.fileTooLarge, { mb: issue.maxMb }));
1557
+ continue;
1558
+ }
1559
+ ok.push({ id: ++seq, file, kind });
1560
+ }
1561
+ if (ok.length) setTray((t) => [...t, ...ok]);
1562
+ };
1563
+ useImperativeHandle(ref, () => ({ addFiles }));
1564
+ const thumbs = useMemo3(() => /* @__PURE__ */ new Map(), []);
1565
+ useEffect3(() => {
1566
+ for (const [id, url] of thumbs) if (!tray.some((a) => a.id === id)) {
1567
+ URL.revokeObjectURL(url);
1568
+ thumbs.delete(id);
1569
+ }
1570
+ }, [tray, thumbs]);
1571
+ useEffect3(() => () => {
1572
+ for (const url of thumbs.values()) URL.revokeObjectURL(url);
1573
+ }, [thumbs]);
1574
+ const thumb = (a) => {
1575
+ let u = thumbs.get(a.id);
1576
+ if (!u) {
1577
+ u = URL.createObjectURL(a.file);
1578
+ thumbs.set(a.id, u);
1579
+ }
1580
+ return u;
1581
+ };
1582
+ const candidates = useMemo3(() => {
1583
+ if (!mention || !p.members) return [];
1584
+ const q = mention.q.toLowerCase();
1585
+ const me = im.currentUserId;
1586
+ const list = [];
1587
+ if (p.canAtAll && !q) list.push({ userId: "@all", name: s.atAll });
1588
+ for (const m of p.members) {
1589
+ if (m.userId === me) continue;
1590
+ if (q && !m.nickname.toLowerCase().includes(q) && !m.userId.toLowerCase().includes(q)) continue;
1591
+ list.push({ userId: m.userId, name: m.nickname || m.userId });
1592
+ if (list.length >= 50) break;
1593
+ }
1594
+ return list;
1595
+ }, [mention, p.members, p.canAtAll, im, s]);
1596
+ const pickMention = (m) => {
1597
+ if (!mention) return;
1598
+ const el = ta.current;
1599
+ const base = text.slice(0, mention.at + 1) + text.slice(mention.at + 1 + mention.q.length);
1600
+ const r = mentions.insert({ text: base, cursor: mention.at + 1 }, mention.at, m);
1601
+ setText(r.text);
1602
+ setMention(null);
1603
+ requestAnimationFrame(() => {
1604
+ el?.focus();
1605
+ el?.setSelectionRange(r.cursor, r.cursor);
1606
+ });
1607
+ };
1608
+ const onChange = (value, cursor) => {
1609
+ const fixed = mentions.onChanged(text, { text: value, cursor });
1610
+ setText(fixed.text);
1611
+ if (fixed.text !== value) requestAnimationFrame(() => ta.current?.setSelectionRange(fixed.cursor, fixed.cursor));
1612
+ p.onTyping?.();
1613
+ if (!p.members) return;
1614
+ const before = fixed.text.slice(0, fixed.cursor);
1615
+ const at = before.lastIndexOf("@");
1616
+ if (at >= 0 && !/\s/.test(before.slice(at + 1)) && (mention || fixed.text.length > text.length)) {
1617
+ setMention({ at, q: before.slice(at + 1), i: 0 });
1618
+ } else if (mention) setMention(null);
1619
+ };
1620
+ const send = async () => {
1621
+ if (busy) return;
1622
+ const t = text.trim();
1623
+ if (!t && !tray.length) return;
1624
+ setBusy(true);
1625
+ const files = tray;
1626
+ const at = mentions.atIds(text);
1627
+ setTray([]);
1628
+ setText("");
1629
+ mentions.clear();
1630
+ try {
1631
+ for (const a of files) await p.onSendFile(a);
1632
+ if (t) await p.onSend(t, at);
1633
+ } finally {
1634
+ setBusy(false);
1635
+ ta.current?.focus();
1636
+ }
1637
+ };
1638
+ const onKey = (e) => {
1639
+ if (mention && candidates.length) {
1640
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1641
+ e.preventDefault();
1642
+ const d = e.key === "ArrowDown" ? 1 : -1;
1643
+ setMention({ ...mention, i: (mention.i + d + candidates.length) % candidates.length });
1644
+ return;
1645
+ }
1646
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
1647
+ e.preventDefault();
1648
+ pickMention(candidates[mention.i]);
1649
+ return;
1650
+ }
1651
+ if (e.key === "Escape") {
1652
+ e.preventDefault();
1653
+ e.stopPropagation();
1654
+ setMention(null);
1655
+ return;
1656
+ }
1657
+ }
1658
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) {
1659
+ e.preventDefault();
1660
+ void send();
1661
+ }
1662
+ };
1663
+ const onPaste = (e) => {
1664
+ const files = Array.from(e.clipboardData.files);
1665
+ if (!files.length) return;
1666
+ e.preventDefault();
1667
+ addFiles(files);
1668
+ };
1669
+ const insertEmoji = (x) => {
1670
+ const el = ta.current;
1671
+ const a = el?.selectionStart ?? text.length, b = el?.selectionEnd ?? text.length;
1672
+ const next = text.slice(0, a) + x + text.slice(b);
1673
+ setText(next);
1674
+ requestAnimationFrame(() => {
1675
+ el?.focus();
1676
+ el?.setSelectionRange(a + x.length, a + x.length);
1677
+ });
1678
+ };
1679
+ const onEmojiKey = (e) => {
1680
+ const btns = Array.from(e.currentTarget.querySelectorAll("button"));
1681
+ const i = btns.indexOf(document.activeElement);
1682
+ const step = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: 10, ArrowUp: -10 }[e.key];
1683
+ if (step) {
1684
+ e.preventDefault();
1685
+ btns[Math.min(btns.length - 1, Math.max(0, i + step))]?.focus();
1686
+ }
1687
+ if (e.key === "Escape") {
1688
+ e.preventDefault();
1689
+ e.stopPropagation();
1690
+ setEmoji(false);
1691
+ ta.current?.focus();
1692
+ }
1693
+ };
1694
+ if (p.disabledHint) return /* @__PURE__ */ jsx6("div", { className: "gkim-composer gkim-composer--disabled", children: p.disabledHint });
1695
+ const accept = ["image/jpeg", "image/png", "image/gif", "image/webp", ...canVideo ? ["video/mp4", "video/quicktime"] : []].join(",");
1696
+ return /* @__PURE__ */ jsxs5("div", { className: "gkim-composer", onPaste, children: [
1697
+ emoji && /* @__PURE__ */ jsx6("div", { className: "gkim-emoji", role: "dialog", "aria-label": s.emoji, onKeyDown: onEmojiKey, children: EMOJIS.map((x) => /* @__PURE__ */ jsx6("button", { type: "button", onClick: () => insertEmoji(x), children: x }, x)) }),
1698
+ mention && candidates.length > 0 && /* @__PURE__ */ jsx6("ul", { className: "gkim-mention-pick", role: "listbox", "aria-label": s.mentionTitle, children: candidates.map((m, i) => /* @__PURE__ */ jsxs5(
1699
+ "li",
1700
+ {
1701
+ role: "option",
1702
+ "aria-selected": i === mention.i,
1703
+ onMouseDown: (e) => {
1704
+ e.preventDefault();
1705
+ pickMention(m);
1706
+ },
1707
+ children: [
1708
+ m.userId === "@all" ? /* @__PURE__ */ jsx6("span", { className: "gkim-mention-pick__all", children: /* @__PURE__ */ jsx6(Icon, { name: "group", size: 16 }) }) : /* @__PURE__ */ jsx6(Avatar, { id: m.userId, name: m.name, url: p.members?.find((x) => x.userId === m.userId)?.avatarUrl, size: 28 }),
1709
+ /* @__PURE__ */ jsx6("span", { children: m.name })
1710
+ ]
1711
+ },
1712
+ m.userId
1713
+ )) }),
1714
+ /* @__PURE__ */ jsxs5("div", { className: "gkim-composer__tools", children: [
1715
+ /* @__PURE__ */ jsx6(
1716
+ "button",
1717
+ {
1718
+ type: "button",
1719
+ className: "gkim-iconbtn",
1720
+ "aria-label": s.emoji,
1721
+ "aria-expanded": emoji,
1722
+ onClick: () => setEmoji((v) => !v),
1723
+ children: /* @__PURE__ */ jsx6(Icon, { name: "emoji" })
1724
+ }
1725
+ ),
1726
+ canImage && /* @__PURE__ */ jsx6("button", { type: "button", className: "gkim-iconbtn", "aria-label": s.sendImageOrVideo, onClick: () => media.current?.click(), children: /* @__PURE__ */ jsx6(Icon, { name: "image" }) }),
1727
+ canFile && /* @__PURE__ */ jsx6("button", { type: "button", className: "gkim-iconbtn", "aria-label": s.sendFile, onClick: () => anyFile.current?.click(), children: /* @__PURE__ */ jsx6(Icon, { name: "file" }) }),
1728
+ moreItems.length > 0 && p.target && /* @__PURE__ */ jsx6(
1729
+ "button",
1730
+ {
1731
+ type: "button",
1732
+ className: "gkim-iconbtn",
1733
+ "aria-label": s.more,
1734
+ "aria-haspopup": "menu",
1735
+ onClick: (e) => {
1736
+ const r = e.currentTarget.getBoundingClientRect();
1737
+ setMore({ x: r.left, y: r.top - 8 });
1738
+ },
1739
+ children: /* @__PURE__ */ jsx6(Icon, { name: "plus" })
1740
+ }
1741
+ ),
1742
+ /* @__PURE__ */ jsx6(
1743
+ "input",
1744
+ {
1745
+ ref: media,
1746
+ type: "file",
1747
+ hidden: true,
1748
+ multiple: true,
1749
+ accept,
1750
+ onChange: (e) => {
1751
+ addFiles(Array.from(e.target.files ?? []));
1752
+ e.target.value = "";
1753
+ }
1754
+ }
1755
+ ),
1756
+ /* @__PURE__ */ jsx6(
1757
+ "input",
1758
+ {
1759
+ ref: anyFile,
1760
+ type: "file",
1761
+ hidden: true,
1762
+ multiple: true,
1763
+ onChange: (e) => {
1764
+ addFiles(Array.from(e.target.files ?? []));
1765
+ e.target.value = "";
1766
+ }
1767
+ }
1768
+ )
1769
+ ] }),
1770
+ tray.length > 0 && /* @__PURE__ */ jsx6("ul", { className: "gkim-tray", "aria-label": "附件", children: tray.map((a) => /* @__PURE__ */ jsxs5("li", { className: "gkim-tray__item", children: [
1771
+ a.kind === "image" ? /* @__PURE__ */ jsx6("img", { src: thumb(a), alt: "" }) : /* @__PURE__ */ jsxs5("span", { className: "gkim-tray__file", children: [
1772
+ /* @__PURE__ */ jsx6(Icon, { name: a.kind === "video" ? "play" : "file", size: 18 }),
1773
+ /* @__PURE__ */ jsx6("span", { children: a.file.name })
1774
+ ] }),
1775
+ /* @__PURE__ */ jsx6(
1776
+ "button",
1777
+ {
1778
+ type: "button",
1779
+ className: "gkim-tray__x",
1780
+ "aria-label": `${s.removeAttachment} ${a.file.name}`,
1781
+ onClick: () => setTray((t) => t.filter((x) => x.id !== a.id)),
1782
+ children: /* @__PURE__ */ jsx6(Icon, { name: "close", size: 12 })
1783
+ }
1784
+ )
1785
+ ] }, a.id)) }),
1786
+ /* @__PURE__ */ jsxs5("label", { className: "gkim-composer__field", children: [
1787
+ /* @__PURE__ */ jsx6("span", { className: "gkim-sr-only", children: s.inputPlaceholder }),
1788
+ /* @__PURE__ */ jsx6(
1789
+ "textarea",
1790
+ {
1791
+ ref: ta,
1792
+ rows: 1,
1793
+ value: text,
1794
+ placeholder: s.inputPlaceholder,
1795
+ "aria-autocomplete": p.members ? "list" : void 0,
1796
+ "aria-expanded": p.members ? !!mention : void 0,
1797
+ onChange: (e) => onChange(e.target.value, e.target.selectionStart ?? e.target.value.length),
1798
+ onKeyDown: onKey,
1799
+ onBlur: () => setMention(null)
1800
+ }
1801
+ )
1802
+ ] }),
1803
+ /* @__PURE__ */ jsxs5("div", { className: "gkim-composer__foot", children: [
1804
+ /* @__PURE__ */ jsx6("span", { className: "gkim-composer__hint", children: s.enterToSend }),
1805
+ /* @__PURE__ */ jsx6(
1806
+ "button",
1807
+ {
1808
+ type: "button",
1809
+ className: "gkim-btn gkim-btn--primary gkim-composer__send",
1810
+ disabled: busy || !text.trim() && !tray.length,
1811
+ onClick: send,
1812
+ children: s.send
1813
+ }
1814
+ )
1815
+ ] }),
1816
+ more && p.target && /* @__PURE__ */ jsx6(
1817
+ Menu,
1818
+ {
1819
+ x: more.x,
1820
+ y: more.y,
1821
+ onClose: closeMore,
1822
+ label: s.more,
1823
+ entries: moreItems.map((it) => ({ label: it.label, icon: it.icon, onSelect: () => it.onClick(p.target) }))
1824
+ }
1825
+ )
1826
+ ] });
1827
+ });
1828
+
1829
+ // src/ui/chat/MessageList.tsx
1830
+ import { Fragment as Fragment3, useCallback as useCallback5, useEffect as useEffect5, useLayoutEffect as useLayoutEffect3, useRef as useRef6 } from "react";
1831
+
1832
+ // src/ui/chat/MessageRow.tsx
1833
+ import { memo, useRef as useRef5 } from "react";
1834
+
1835
+ // src/ui/chat/bubbles.tsx
1836
+ import { useEffect as useEffect4, useState as useState5 } from "react";
1837
+ import { messageCard } from "@guokit-dev/im";
1838
+ import { Fragment as Fragment2, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
1839
+ function useAsyncUrl(load) {
1840
+ const [url, setUrl] = useState5(null);
1841
+ const enabled = load !== null;
1842
+ useEffect4(() => {
1843
+ if (!load) return;
1844
+ let alive = true;
1845
+ Promise.resolve().then(load).then((u) => {
1846
+ if (alive) setUrl(u);
1847
+ }, () => {
1848
+ });
1849
+ return () => {
1850
+ alive = false;
1851
+ };
1852
+ }, [enabled]);
1853
+ return url;
1854
+ }
1855
+ function fit(w, h, max = 180, min = 80) {
1856
+ const ww = typeof w === "number" && w > 0 ? w : max;
1857
+ const hh = typeof h === "number" && h > 0 ? h : max;
1858
+ const scale = max / Math.max(ww, hh);
1859
+ const clamp = (v) => Math.min(max, Math.max(min, v));
1860
+ return { width: clamp(ww * scale), height: clamp(hh * scale) };
1861
+ }
1862
+ function formatFileSize(bytes) {
1863
+ if (bytes == null) return "";
1864
+ if (bytes < 1024) return `${bytes} B`;
1865
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1866
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
1867
+ }
1868
+ function formatDuration(sec) {
1869
+ if (sec == null) return "";
1870
+ const s = Math.round(sec);
1871
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
1872
+ }
1873
+ function openExternal(url) {
1874
+ window.open(url, "_blank", "noopener");
1875
+ }
1876
+ var MENTION = /@[^\s@]+/g;
1877
+ function TextBubble({ message: m, text, children }) {
1878
+ const raw = text ?? (typeof m.content.text === "string" ? m.content.text : "");
1879
+ let body = children ?? raw;
1880
+ if (!children && m.groupId && Array.isArray(m.content.at)) {
1881
+ const out = [];
1882
+ let i = 0;
1883
+ for (const x of raw.matchAll(MENTION)) {
1884
+ if (x.index > i) out.push(raw.slice(i, x.index));
1885
+ out.push(/* @__PURE__ */ jsx7("span", { className: "gkim-mention", children: x[0] }, x.index));
1886
+ i = x.index + x[0].length;
1887
+ }
1888
+ if (i < raw.length) out.push(raw.slice(i));
1889
+ body = out;
1890
+ }
1891
+ return /* @__PURE__ */ jsx7("div", { className: `gkim-bubble gkim-bubble--text${m.isSelf ? " gkim-bubble--self" : ""}`, children: body });
1892
+ }
1893
+ function ProgressMask({ p }) {
1894
+ if (p == null) return null;
1895
+ return /* @__PURE__ */ jsxs6("span", { className: "gkim-media__mask", children: [
1896
+ Math.round(p * 100),
1897
+ "%"
1898
+ ] });
1899
+ }
1900
+ function ImageBubble({ message: m, localUrl, progress, onImageClick }) {
1901
+ const { im, strings: s } = useImUi();
1902
+ const sent = m.status === "sent";
1903
+ const remote = useAsyncUrl(sent && !localUrl ? () => im.imageUrl(m) : null);
1904
+ const [broken, setBroken] = useState5(false);
1905
+ const src = localUrl ?? remote;
1906
+ const size = fit(m.content.width, m.content.height);
1907
+ const img = src && !broken ? /* @__PURE__ */ jsx7("img", { src, alt: s.image, onError: () => setBroken(true) }) : /* @__PURE__ */ jsx7("span", { className: "gkim-media__ph", children: /* @__PURE__ */ jsx7(Icon, { name: "image" }) });
1908
+ const style = { width: size.width, height: size.height };
1909
+ if (sent && onImageClick) {
1910
+ return /* @__PURE__ */ jsxs6("button", { type: "button", className: "gkim-media", style, "aria-label": s.image, onClick: () => onImageClick(m), children: [
1911
+ img,
1912
+ /* @__PURE__ */ jsx7(ProgressMask, { p: progress })
1913
+ ] });
1914
+ }
1915
+ return /* @__PURE__ */ jsxs6("span", { className: "gkim-media", style, children: [
1916
+ img,
1917
+ /* @__PURE__ */ jsx7(ProgressMask, { p: progress })
1918
+ ] });
1919
+ }
1920
+ function VideoBubble({ message: m, progress, onVideoClick }) {
1921
+ const { im, strings: s } = useImUi();
1922
+ const sent = m.status === "sent";
1923
+ const cover = useAsyncUrl(sent ? () => im.videoCoverUrl(m) : null);
1924
+ const size = fit(m.content.width, m.content.height, 200);
1925
+ const inner = /* @__PURE__ */ jsxs6(Fragment2, { children: [
1926
+ cover ? /* @__PURE__ */ jsx7("img", { src: cover, alt: "" }) : /* @__PURE__ */ jsx7("span", { className: "gkim-media__dark" }),
1927
+ progress == null && /* @__PURE__ */ jsx7("span", { className: "gkim-media__play", children: /* @__PURE__ */ jsx7(Icon, { name: "play", size: 28 }) }),
1928
+ /* @__PURE__ */ jsx7(ProgressMask, { p: progress }),
1929
+ /* @__PURE__ */ jsx7("span", { className: "gkim-media__dur", children: formatDuration(m.duration) })
1930
+ ] });
1931
+ const style = { width: size.width, height: size.height };
1932
+ if (sent && onVideoClick) {
1933
+ return /* @__PURE__ */ jsx7("button", { type: "button", className: "gkim-media", style, "aria-label": s.video, onClick: () => onVideoClick(m), children: inner });
1934
+ }
1935
+ return /* @__PURE__ */ jsx7("span", { className: "gkim-media", style, children: inner });
1936
+ }
1937
+ function VoiceBubble({ message: m, playing, onVoiceClick }) {
1938
+ const { strings: s } = useImUi();
1939
+ const sec = m.duration ?? 0;
1940
+ const width = 80 + Math.min(sec, 60) * 2;
1941
+ return /* @__PURE__ */ jsxs6(
1942
+ "button",
1943
+ {
1944
+ type: "button",
1945
+ className: `gkim-bubble gkim-bubble--voice${m.isSelf ? " gkim-bubble--self" : ""}`,
1946
+ style: { width },
1947
+ "aria-label": `${s.voice} ${formatDuration(m.duration)}`,
1948
+ "aria-pressed": playing,
1949
+ disabled: m.status !== "sent",
1950
+ onClick: () => onVoiceClick?.(m),
1951
+ children: [
1952
+ /* @__PURE__ */ jsx7(Icon, { name: playing ? "pause" : "play", size: 16 }),
1953
+ /* @__PURE__ */ jsxs6("span", { children: [
1954
+ Math.round(sec),
1955
+ "″"
1956
+ ] })
1957
+ ]
1958
+ }
1959
+ );
1960
+ }
1961
+ function FileBubble({ message: m, progress }) {
1962
+ const { im, strings: s } = useImUi();
1963
+ const name = m.fileName ?? s.file;
1964
+ const dot = name.lastIndexOf(".");
1965
+ const ext = dot > 0 && dot < name.length - 1 ? name.slice(dot + 1).toUpperCase().slice(0, 4) : "?";
1966
+ const open = async () => {
1967
+ const url = await im.fileUrl(m).catch(() => null);
1968
+ if (url) openExternal(url);
1969
+ };
1970
+ return /* @__PURE__ */ jsxs6("button", { type: "button", className: "gkim-framed gkim-file", disabled: m.status !== "sent", onClick: open, children: [
1971
+ /* @__PURE__ */ jsxs6("span", { className: "gkim-file__info", children: [
1972
+ /* @__PURE__ */ jsx7("span", { className: "gkim-file__name", children: name }),
1973
+ /* @__PURE__ */ jsx7("span", { className: "gkim-file__size", children: formatFileSize(m.fileSize) }),
1974
+ progress != null && /* @__PURE__ */ jsx7("span", { className: "gkim-progress", children: /* @__PURE__ */ jsx7("span", { style: { width: `${Math.round(progress * 100)}%` } }) })
1975
+ ] }),
1976
+ /* @__PURE__ */ jsx7("span", { className: "gkim-file__ext", children: ext })
1977
+ ] });
1978
+ }
1979
+ function LocationBubble({ message: m }) {
1980
+ const { strings: s, callbacks } = useImUi();
1981
+ const name = typeof m.content.name === "string" ? m.content.name.trim() : "";
1982
+ const address = typeof m.content.address === "string" ? m.content.address.trim() : "";
1983
+ const inner = /* @__PURE__ */ jsxs6(Fragment2, { children: [
1984
+ /* @__PURE__ */ jsxs6("span", { className: "gkim-location__text", children: [
1985
+ /* @__PURE__ */ jsx7("span", { className: "gkim-location__name", children: name || s.location }),
1986
+ address && /* @__PURE__ */ jsx7("span", { className: "gkim-location__addr", children: address })
1987
+ ] }),
1988
+ /* @__PURE__ */ jsx7("span", { className: "gkim-location__map", children: /* @__PURE__ */ jsx7(Icon, { name: "location", size: 32 }) })
1989
+ ] });
1990
+ const onTap = callbacks.onLocationTap;
1991
+ if (!onTap) return /* @__PURE__ */ jsx7("div", { className: "gkim-framed gkim-location", children: inner });
1992
+ return /* @__PURE__ */ jsx7("button", { type: "button", className: "gkim-framed gkim-location", onClick: () => onTap(m), children: inner });
1993
+ }
1994
+ function CardBubble({ message: m, card }) {
1995
+ const { strings: s, callbacks } = useImUi();
1996
+ const link = card.webLink ?? card.appLink;
1997
+ const onClick = callbacks.onCardTap ? () => callbacks.onCardTap(card, m) : link ? () => openExternal(link) : void 0;
1998
+ const inner = /* @__PURE__ */ jsxs6(Fragment2, { children: [
1999
+ card.kind != null && /* @__PURE__ */ jsx7("span", { className: "gkim-card__kind", children: s.cardKinds[card.kind] ?? s.cardKindOther }),
2000
+ /* @__PURE__ */ jsxs6("span", { className: "gkim-card__main", children: [
2001
+ card.image && /* @__PURE__ */ jsx7("img", { className: "gkim-card__img", src: card.image, alt: "" }),
2002
+ /* @__PURE__ */ jsxs6("span", { className: "gkim-card__text", children: [
2003
+ /* @__PURE__ */ jsx7("span", { className: "gkim-card__title", children: card.title }),
2004
+ card.subtitle && /* @__PURE__ */ jsx7("span", { className: "gkim-card__sub", children: card.subtitle })
2005
+ ] })
2006
+ ] }),
2007
+ card.fields.length > 0 && /* @__PURE__ */ jsx7("span", { className: "gkim-card__fields", children: card.fields.slice(0, 4).map((f, i) => /* @__PURE__ */ jsxs6("span", { className: "gkim-card__field", children: [
2008
+ /* @__PURE__ */ jsx7("span", { children: f.label }),
2009
+ /* @__PURE__ */ jsx7("span", { children: f.value })
2010
+ ] }, i)) })
2011
+ ] });
2012
+ if (!onClick) return /* @__PURE__ */ jsx7("div", { className: "gkim-framed gkim-card", children: inner });
2013
+ return /* @__PURE__ */ jsx7("button", { type: "button", className: "gkim-framed gkim-card", onClick, children: inner });
2014
+ }
2015
+ function MessageContent(props) {
2016
+ const { messageRenderers, strings: s } = useImUi();
2017
+ const m = props.message;
2018
+ const custom = messageRenderers[m.type]?.(m);
2019
+ if (custom != null) return /* @__PURE__ */ jsx7(Fragment2, { children: custom });
2020
+ switch (m.type) {
2021
+ case "text":
2022
+ return /* @__PURE__ */ jsx7(TextBubble, { message: m });
2023
+ case "image":
2024
+ return /* @__PURE__ */ jsx7(ImageBubble, { ...props });
2025
+ case "file":
2026
+ return /* @__PURE__ */ jsx7(FileBubble, { ...props });
2027
+ case "location":
2028
+ return /* @__PURE__ */ jsx7(LocationBubble, { ...props });
2029
+ case "video":
2030
+ return /* @__PURE__ */ jsx7(VideoBubble, { ...props });
2031
+ case "voice":
2032
+ return /* @__PURE__ */ jsx7(VoiceBubble, { ...props });
2033
+ case "custom": {
2034
+ const card = messageCard(m);
2035
+ if (card) return /* @__PURE__ */ jsx7(CardBubble, { message: m, card });
2036
+ const desc = m.content.desc;
2037
+ return /* @__PURE__ */ jsx7(TextBubble, { message: m, text: typeof desc === "string" && desc ? desc : s.unsupported });
2038
+ }
2039
+ default:
2040
+ return /* @__PURE__ */ jsx7(TextBubble, { message: m, text: s.unsupported });
2041
+ }
2042
+ }
2043
+
2044
+ // src/ui/chat/MessageRow.tsx
2045
+ import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
2046
+ function CenterTip({ text }) {
2047
+ return /* @__PURE__ */ jsx8("div", { className: "gkim-tip", children: text });
2048
+ }
2049
+ var MessageRow = memo(function MessageRow2(p) {
2050
+ const { strings: s } = useImUi();
2051
+ const { toast } = useFeedback();
2052
+ const m = p.message;
2053
+ const self = m.isSelf;
2054
+ const tappable = !self && !m.from.startsWith("@") && p.onAvatarClick;
2055
+ let status = null;
2056
+ if (m.status === "sending") status = /* @__PURE__ */ jsx8("span", { className: "gkim-row__sending", role: "img", "aria-label": "…" });
2057
+ else if (m.status === "failed" || m.status === "rejected") {
2058
+ const rejected = m.status === "rejected";
2059
+ status = /* @__PURE__ */ jsx8(
2060
+ "button",
2061
+ {
2062
+ type: "button",
2063
+ className: "gkim-row__status",
2064
+ "aria-label": rejected ? s.sendRejected : s.operationFailed,
2065
+ title: rejected ? m.errorMessage || s.sendRejected : void 0,
2066
+ onClick: () => rejected ? toast(m.errorMessage || s.sendRejected) : p.onResend?.(m),
2067
+ children: /* @__PURE__ */ jsx8(Icon, { name: rejected ? "alert" : "retry", size: 18 })
2068
+ }
2069
+ );
2070
+ }
2071
+ const press = useRef5(null);
2072
+ const touchStart = (e) => {
2073
+ if (!p.onMenu) return;
2074
+ const t = e.touches[0];
2075
+ const x = t.clientX, y = t.clientY;
2076
+ press.current = { x, y, t: setTimeout(() => {
2077
+ press.current = null;
2078
+ p.onMenu(m, x, y);
2079
+ }, 500) };
2080
+ };
2081
+ const touchMove = (e) => {
2082
+ const c = press.current, t = e.touches[0];
2083
+ if (c && Math.hypot(t.clientX - c.x, t.clientY - c.y) > 10) {
2084
+ clearTimeout(c.t);
2085
+ press.current = null;
2086
+ }
2087
+ };
2088
+ const touchEnd = () => {
2089
+ if (press.current) {
2090
+ clearTimeout(press.current.t);
2091
+ press.current = null;
2092
+ }
2093
+ };
2094
+ const menu = (e) => {
2095
+ if (!p.onMenu) return;
2096
+ e.preventDefault();
2097
+ p.onMenu(m, e.clientX, e.clientY);
2098
+ };
2099
+ return /* @__PURE__ */ jsxs7("div", { className: `gkim-row${self ? " gkim-row--self" : ""}`, "data-cid": m.clientMsgId, children: [
2100
+ /* @__PURE__ */ jsx8(
2101
+ Avatar,
2102
+ {
2103
+ id: m.from,
2104
+ name: p.senderName,
2105
+ url: p.senderAvatarUrl,
2106
+ onClick: tappable ? () => p.onAvatarClick(m.from) : void 0
2107
+ }
2108
+ ),
2109
+ /* @__PURE__ */ jsxs7("div", { className: "gkim-row__col", children: [
2110
+ p.showName && !self && /* @__PURE__ */ jsx8("span", { className: "gkim-row__name", children: p.senderName }),
2111
+ /* @__PURE__ */ jsxs7("div", { className: "gkim-row__line", children: [
2112
+ self && status,
2113
+ /* @__PURE__ */ jsxs7("div", { className: "gkim-row__bubble", onContextMenu: menu, onTouchStart: touchStart, onTouchMove: touchMove, onTouchEnd: touchEnd, children: [
2114
+ /* @__PURE__ */ jsx8(
2115
+ MessageContent,
2116
+ {
2117
+ message: m,
2118
+ localUrl: p.localUrl,
2119
+ progress: p.progress,
2120
+ playing: p.playing,
2121
+ onImageClick: p.onImageClick,
2122
+ onVideoClick: p.onVideoClick,
2123
+ onVoiceClick: p.onVoiceClick
2124
+ }
2125
+ ),
2126
+ p.hoverBar
2127
+ ] }),
2128
+ !self && status
2129
+ ] }),
2130
+ p.read !== null && self && /* @__PURE__ */ jsx8("span", { className: `gkim-row__meta${p.read ? "" : " gkim-row__meta--unread"}`, children: p.read ? s.read : s.unreadMark }),
2131
+ m.isBot && /* @__PURE__ */ jsx8("span", { className: "gkim-row__meta", children: s.aiGenerated })
2132
+ ] })
2133
+ ] });
2134
+ });
2135
+
2136
+ // src/ui/chat/MessageList.tsx
2137
+ import { jsx as jsx9, jsxs as jsxs8 } from "react/jsx-runtime";
2138
+ var FIVE_MIN = 5 * 6e4;
2139
+ function MessageList({ ctl, snap, isGroup, nameOf, renderRow, scrollRef }) {
2140
+ const { im, strings: s } = useImUi();
2141
+ const ref = useRef6(null);
2142
+ const me = im.currentUserId;
2143
+ const nearTop = (el) => el.scrollHeight - el.clientHeight + el.scrollTop < 200;
2144
+ const check = useCallback5(() => {
2145
+ const el = ref.current;
2146
+ if (el && snap.hasMore && !snap.loadingMore && nearTop(el)) ctl.loadMore();
2147
+ }, [ctl, snap.hasMore, snap.loadingMore]);
2148
+ useLayoutEffect3(() => {
2149
+ check();
2150
+ }, [check, snap.messages]);
2151
+ useEffect5(() => {
2152
+ scrollRef.current = () => {
2153
+ if (ref.current) ref.current.scrollTop = 0;
2154
+ };
2155
+ return () => {
2156
+ scrollRef.current = null;
2157
+ };
2158
+ }, [scrollRef]);
2159
+ useEffect5(() => ctl.onNewMessage((m) => {
2160
+ const el = ref.current;
2161
+ if (el && (m.isSelf || el.scrollTop > -120)) el.scrollTop = 0;
2162
+ }), [ctl]);
2163
+ const now = Date.now();
2164
+ const items = [];
2165
+ let prev = null;
2166
+ for (const m of snap.messages) {
2167
+ if (prev === null || m.createdAt - prev >= FIVE_MIN) {
2168
+ items.push(/* @__PURE__ */ jsx9(CenterTip, { text: formatMessageTime(m.createdAt, s, now) }, `t-${m.clientMsgId}`));
2169
+ }
2170
+ prev = m.createdAt;
2171
+ if (isTipMessage(m)) {
2172
+ items.push(/* @__PURE__ */ jsx9(CenterTip, { text: tipText(m, s, { nameOf, me, isGroup }) }, m.clientMsgId));
2173
+ continue;
2174
+ }
2175
+ items.push(/* @__PURE__ */ jsx9(Fragment3, { children: renderRow(m) }, m.clientMsgId));
2176
+ }
2177
+ return /* @__PURE__ */ jsx9("div", { className: "gkim-msglist", ref, onScroll: check, role: "log", "aria-live": "polite", "aria-relevant": "additions", children: /* @__PURE__ */ jsxs8("div", { className: "gkim-msglist__inner", children: [
2178
+ snap.loadingMore && /* @__PURE__ */ jsx9("span", { className: "gkim-msglist__spinner", role: "img", "aria-label": "…" }),
2179
+ items
2180
+ ] }) });
2181
+ }
2182
+
2183
+ // src/ui/chat/ChatPage.tsx
2184
+ import { Fragment as Fragment4, jsx as jsx10, jsxs as jsxs9 } from "react/jsx-runtime";
2185
+ var noSub = () => () => {
2186
+ };
2187
+ var EMPTY_SNAP = {
2188
+ messages: [],
2189
+ loading: true,
2190
+ loadingMore: false,
2191
+ hasMore: false,
2192
+ peerTyping: false,
2193
+ conversation: null,
2194
+ conversationId: null,
2195
+ quit: false,
2196
+ peerReadSeq: null,
2197
+ features: null,
2198
+ progress: {},
2199
+ localFiles: {}
2200
+ };
2201
+ var EMPTY_MEMBERS = /* @__PURE__ */ new Map();
2202
+ function targetOf(p) {
2203
+ const n = Number(p.conversation != null) + Number(p.peer != null) + Number(p.group != null);
2204
+ if (n !== 1) throw new TypeError("ImChat:conversation、peer、group 须且只能传一个");
2205
+ if (p.conversation) return { conversation: p.conversation };
2206
+ if (p.peer != null) {
2207
+ if (!p.peer) throw new TypeError("ImChat:peer 不能为空");
2208
+ return { peer: p.peer };
2209
+ }
2210
+ if (!p.group) throw new TypeError("ImChat:group 不能为空");
2211
+ return { group: p.group };
2212
+ }
2213
+ function ImChat(props) {
2214
+ const target = targetOf(props);
2215
+ const { im, me, strings: s, callbacks } = useImUi();
2216
+ const nav = useNavContext();
2217
+ const { toast } = useFeedback();
2218
+ const key = "conversation" in target ? `c${target.conversation.id}` : "group" in target ? `g${target.group}` : `p${target.peer}`;
2219
+ const isGroup = "group" in target || "conversation" in target && target.conversation.group !== null;
2220
+ const groupId = "group" in target ? target.group : "conversation" in target ? target.conversation.group?.groupId ?? null : null;
2221
+ const [ctl, setCtl] = useState6(null);
2222
+ useEffect6(() => {
2223
+ const c = new ChatController(im, target);
2224
+ setCtl(c);
2225
+ void c.start();
2226
+ const vis = () => c.setActive(document.visibilityState === "visible");
2227
+ document.addEventListener("visibilitychange", vis);
2228
+ return () => {
2229
+ document.removeEventListener("visibilitychange", vis);
2230
+ c.dispose();
2231
+ };
2232
+ }, [im, key]);
2233
+ const snap = useSyncExternalStore(ctl?.subscribe ?? noSub, ctl?.getSnapshot ?? (() => EMPTY_SNAP));
2234
+ const [members, setMembers] = useState6(null);
2235
+ useEffect6(() => {
2236
+ if (!groupId) return;
2237
+ const m = new MemberCache(im, groupId);
2238
+ setMembers(m);
2239
+ m.start();
2240
+ return () => {
2241
+ m.dispose();
2242
+ setMembers(null);
2243
+ };
2244
+ }, [im, groupId]);
2245
+ const memberMap = useSyncExternalStore(members?.subscribe ?? noSub, members?.getSnapshot ?? (() => EMPTY_MEMBERS));
2246
+ const memberList = useMemo4(() => [...memberMap.values()], [memberMap]);
2247
+ const urls = useMemo4(() => new ObjectUrlRegistry(), []);
2248
+ useEffect6(() => () => urls.releaseAll(), [urls]);
2249
+ urls.sync(snap.localFiles);
2250
+ const conv = snap.conversation;
2251
+ const myId = im.currentUserId;
2252
+ const nameOf = useCallback6((id) => {
2253
+ const mm = memberMap.get(id);
2254
+ if (mm && mm.nickname) return mm.nickname;
2255
+ if (id === myId) return me.nickname || id;
2256
+ if (conv?.peer && conv.peer.userId === id) return conversationTitle(conv, s);
2257
+ return id;
2258
+ }, [memberMap, myId, me.nickname, conv, s]);
2259
+ const avatarOf = useCallback6((id) => {
2260
+ const mm = memberMap.get(id);
2261
+ if (mm?.avatarUrl) return mm.avatarUrl;
2262
+ if (id === myId) return me.avatarUrl ?? "";
2263
+ return conv?.peer && conv.peer.userId === id ? conv.peer.avatarUrl : "";
2264
+ }, [memberMap, myId, me.avatarUrl, conv]);
2265
+ const audio = useRef7(null);
2266
+ const [playing, setPlaying] = useState6(null);
2267
+ useEffect6(() => () => {
2268
+ audio.current?.pause();
2269
+ }, []);
2270
+ const onVoice = useCallback6(async (m) => {
2271
+ const a = audio.current ?? (audio.current = new Audio());
2272
+ a.onended = () => setPlaying(null);
2273
+ if (playing === m.clientMsgId) {
2274
+ a.pause();
2275
+ setPlaying(null);
2276
+ return;
2277
+ }
2278
+ a.pause();
2279
+ const url = await im.voiceUrl(m).catch(() => null);
2280
+ if (!url) return;
2281
+ a.src = url;
2282
+ setPlaying(m.clientMsgId);
2283
+ a.play().catch(() => setPlaying(null));
2284
+ }, [im, playing]);
2285
+ const onImage = useCallback6((m) => {
2286
+ const images = snap.messages.filter((x) => x.type === "image" && x.status === "sent");
2287
+ const index = images.findIndex((x) => x.clientMsgId === m.clientMsgId);
2288
+ if (index >= 0) nav.open({ name: "imageViewer", images, index });
2289
+ }, [snap.messages, nav]);
2290
+ const onVideo = useCallback6((m) => {
2291
+ audio.current?.pause();
2292
+ setPlaying(null);
2293
+ nav.open({ name: "videoPlayer", message: m });
2294
+ }, [nav]);
2295
+ const onResend = useCallback6((m) => {
2296
+ ctl?.resend(m).catch(() => toast(s.sendRejected));
2297
+ }, [ctl, toast, s]);
2298
+ const onAvatar = callbacks.onAvatarTap;
2299
+ const scrollToLatest = useRef7(null);
2300
+ const send = useCallback6(async (text, at) => {
2301
+ if (!ctl) return;
2302
+ try {
2303
+ const m = await ctl.sendText(text, at);
2304
+ scrollToLatest.current?.();
2305
+ if (m.status === "rejected") toast(m.errorMessage || s.sendRejected);
2306
+ } catch {
2307
+ toast(s.operationFailed);
2308
+ }
2309
+ }, [ctl, toast, s]);
2310
+ const sendFile = useCallback6(async (a) => {
2311
+ if (!ctl) return;
2312
+ try {
2313
+ let m;
2314
+ if (a.kind === "image") m = await ctl.sendImage(a.file);
2315
+ else if (a.kind === "video") {
2316
+ const meta = await readVideoMeta(a.file);
2317
+ m = meta ? await ctl.sendVideo(a.file, meta) : await ctl.sendFile(a.file, a.file.name);
2318
+ } else m = await ctl.sendFile(a.file, a.file.name);
2319
+ scrollToLatest.current?.();
2320
+ if (m.status === "rejected") toast(m.errorMessage || s.sendRejected);
2321
+ } catch (e) {
2322
+ toast(e instanceof RangeError ? e.message : s.operationFailed);
2323
+ }
2324
+ }, [ctl, toast, s]);
2325
+ const composer = useRef7(null);
2326
+ const [dragging, setDragging] = useState6(false);
2327
+ const depth = useRef7(0);
2328
+ const hasFiles = (e) => Array.from(e.dataTransfer.types).includes("Files");
2329
+ const dropProps = snap.quit ? {} : {
2330
+ onDragEnter: (e) => {
2331
+ if (!hasFiles(e)) return;
2332
+ e.preventDefault();
2333
+ depth.current++;
2334
+ setDragging(true);
2335
+ },
2336
+ onDragOver: (e) => {
2337
+ if (hasFiles(e)) e.preventDefault();
2338
+ },
2339
+ onDragLeave: () => {
2340
+ if (--depth.current <= 0) {
2341
+ depth.current = 0;
2342
+ setDragging(false);
2343
+ }
2344
+ },
2345
+ onDrop: (e) => {
2346
+ if (!hasFiles(e)) return;
2347
+ e.preventDefault();
2348
+ depth.current = 0;
2349
+ setDragging(false);
2350
+ composer.current?.addFiles(Array.from(e.dataTransfer.files));
2351
+ }
2352
+ };
2353
+ const [menu, setMenu] = useState6(null);
2354
+ const closeMenu = useCallback6(() => setMenu(null), []);
2355
+ const { menuItems } = useImUi();
2356
+ const recallMinutes = snap.features?.recallMinutes ?? 0;
2357
+ const entriesFor = useCallback6((m) => {
2358
+ const out = [];
2359
+ if (m.type === "text") {
2360
+ out.push({ label: s.copy, icon: /* @__PURE__ */ jsx10(Icon, { name: "copy", size: 16 }), onSelect: () => {
2361
+ navigator.clipboard?.writeText(typeof m.content.text === "string" ? m.content.text : "").then(() => toast(s.copied), () => toast(s.operationFailed));
2362
+ } });
2363
+ }
2364
+ if (m.isSelf && m.id !== null && m.status === "sent" && recallMinutes > 0 && Date.now() - m.createdAt < recallMinutes * 6e4) {
2365
+ out.push({ label: s.recall, icon: /* @__PURE__ */ jsx10(Icon, { name: "recall", size: 16 }), onSelect: () => {
2366
+ ctl?.recall(m).catch((e) => toast(e instanceof ImApiError && e.message ? e.message : s.operationFailed));
2367
+ } });
2368
+ }
2369
+ if (!m.isSelf && m.id !== null) {
2370
+ out.push({ label: s.report, icon: /* @__PURE__ */ jsx10(Icon, { name: "report", size: 16 }), onSelect: () => {
2371
+ nav.open({ name: "report", target: m.from, title: s.report, messageIds: [m.id] });
2372
+ } });
2373
+ }
2374
+ for (const it of menuItems?.(m) ?? []) out.push({ label: it.label, icon: it.icon, onSelect: () => it.onClick(m) });
2375
+ return out;
2376
+ }, [s, toast, recallMinutes, ctl, nav, menuItems]);
2377
+ const onMenu = useCallback6((m, x, y) => {
2378
+ if (entriesFor(m).length) setMenu({ m, x, y });
2379
+ }, [entriesFor]);
2380
+ const hoverBar = (m) => {
2381
+ const all = entriesFor(m);
2382
+ if (!all.length || m.status !== "sent") return null;
2383
+ return /* @__PURE__ */ jsxs9("div", { className: "gkim-hoverbar", role: "toolbar", "aria-label": s.more, children: [
2384
+ all.slice(0, 2).map((e, i) => /* @__PURE__ */ jsx10("button", { type: "button", className: "gkim-hoverbar__btn", "aria-label": e.label, title: e.label, onClick: e.onSelect, children: e.icon }, i)),
2385
+ all.length > 2 && /* @__PURE__ */ jsx10(
2386
+ "button",
2387
+ {
2388
+ type: "button",
2389
+ className: "gkim-hoverbar__btn",
2390
+ "aria-label": s.more,
2391
+ title: s.more,
2392
+ "aria-haspopup": "menu",
2393
+ onClick: (ev) => {
2394
+ const r = ev.currentTarget.getBoundingClientRect();
2395
+ setMenu({ m, x: r.left, y: r.bottom + 4 });
2396
+ },
2397
+ children: /* @__PURE__ */ jsx10(Icon, { name: "more", size: 16 })
2398
+ }
2399
+ )
2400
+ ] });
2401
+ };
2402
+ const peerReadSeq = snap.peerReadSeq;
2403
+ const renderRow = (m) => /* @__PURE__ */ jsx10(
2404
+ MessageRow,
2405
+ {
2406
+ message: m,
2407
+ senderName: nameOf(m.from),
2408
+ senderAvatarUrl: avatarOf(m.from),
2409
+ showName: isGroup,
2410
+ read: m.isSelf && peerReadSeq !== null && m.seq !== null ? m.seq <= peerReadSeq : null,
2411
+ localUrl: urls.get(m.clientMsgId),
2412
+ progress: snap.progress[m.clientMsgId],
2413
+ playing: playing === m.clientMsgId,
2414
+ onResend,
2415
+ onAvatarClick: onAvatar,
2416
+ onImageClick: onImage,
2417
+ onVideoClick: onVideo,
2418
+ onVoiceClick: onVoice,
2419
+ onMenu,
2420
+ hoverBar: hoverBar(m)
2421
+ }
2422
+ );
2423
+ let title = conv ? conversationTitle(conv, s) : groupId ?? props.peer ?? "";
2424
+ let count = null;
2425
+ if (conv?.group && !conv.group.quit) {
2426
+ const cached = memberMap.size;
2427
+ count = cached > 0 && cached < MemberCache.max ? cached : conv.group.memberCount;
2428
+ if (!count) count = null;
2429
+ }
2430
+ if (!title) title = s.groupChat;
2431
+ const groupInfo = callbacks.onGroupInfoTap;
2432
+ const actions = isGroup && groupId && groupInfo ? /* @__PURE__ */ jsx10("button", { type: "button", className: "gkim-iconbtn", "aria-label": s.groupInfoTitle, onClick: () => groupInfo(groupId), children: /* @__PURE__ */ jsx10(Icon, { name: "more" }) }) : null;
2433
+ return /* @__PURE__ */ jsxs9(
2434
+ Page,
2435
+ {
2436
+ className: "gkim-chat",
2437
+ scroll: false,
2438
+ actions,
2439
+ title: /* @__PURE__ */ jsxs9(Fragment4, { children: [
2440
+ title,
2441
+ count !== null && /* @__PURE__ */ jsxs9("span", { className: "gkim-chat__count", children: [
2442
+ "(",
2443
+ count,
2444
+ ")"
2445
+ ] }),
2446
+ !isGroup && snap.peerTyping && /* @__PURE__ */ jsx10("span", { className: "gkim-chat__sub", children: s.typing })
2447
+ ] }),
2448
+ footer: /* @__PURE__ */ jsx10(
2449
+ Composer,
2450
+ {
2451
+ ref: composer,
2452
+ onSend: send,
2453
+ onSendFile: sendFile,
2454
+ onTyping: () => ctl?.typing(),
2455
+ disabledHint: snap.quit ? s.notInGroup : null,
2456
+ features: snap.features,
2457
+ members: isGroup ? memberList : null,
2458
+ canAtAll: (conv?.group?.role ?? 0) >= 1,
2459
+ target: ctl?.target ?? null
2460
+ }
2461
+ ),
2462
+ children: [
2463
+ /* @__PURE__ */ jsxs9("div", { className: "gkim-chat__area", ...dropProps, children: [
2464
+ snap.loading || !ctl ? /* @__PURE__ */ jsx10("div", { className: "gkim-loading", children: /* @__PURE__ */ jsx10("span", { className: "gkim-msglist__spinner", role: "img", "aria-label": "…" }) }) : /* @__PURE__ */ jsx10(MessageList, { ctl, snap, isGroup, nameOf, renderRow, scrollRef: scrollToLatest }),
2465
+ dragging && /* @__PURE__ */ jsx10("div", { className: "gkim-dropmask", children: fill(s.dropToSend, { name: title }) })
2466
+ ] }),
2467
+ menu && /* @__PURE__ */ jsx10(Menu, { entries: entriesFor(menu.m), x: menu.x, y: menu.y, onClose: closeMenu })
2468
+ ]
2469
+ }
2470
+ );
2471
+ }
2472
+
2473
+ // src/ui/conversation/ConversationList.tsx
2474
+ import { useState as useState7 } from "react";
2475
+ import { ImApiError as ImApiError2 } from "@guokit-dev/im";
2476
+
2477
+ // src/ui/hooks.ts
2478
+ import { useSyncExternalStore as useSyncExternalStore2 } from "react";
2479
+
2480
+ // src/core/imStore.ts
2481
+ var EMPTY = Object.freeze([]);
2482
+ var cache2 = /* @__PURE__ */ new WeakMap();
2483
+ function storesOf(im) {
2484
+ let s = cache2.get(im);
2485
+ if (!s) cache2.set(im, s = {});
2486
+ return s;
2487
+ }
2488
+ function conversationsStore(im) {
2489
+ const s = storesOf(im);
2490
+ return s.conversations ?? (s.conversations = createConversationsStore(im));
2491
+ }
2492
+ function totalUnreadStore(im) {
2493
+ const s = storesOf(im);
2494
+ return s.totalUnread ?? (s.totalUnread = valueStore(im, "totalUnread", () => im.totalUnread));
2495
+ }
2496
+ function connectionStore(im) {
2497
+ const s = storesOf(im);
2498
+ return s.connection ?? (s.connection = valueStore(im, "connection", () => im.connectionState));
2499
+ }
2500
+ function createConversationsStore(im) {
2501
+ let snap = EMPTY;
2502
+ let owner = null;
2503
+ let last = EMPTY;
2504
+ let offs = [];
2505
+ const getSnapshot = () => {
2506
+ const me = im.currentUserId;
2507
+ if (me === null) {
2508
+ snap = EMPTY;
2509
+ owner = null;
2510
+ return EMPTY;
2511
+ }
2512
+ return me === owner ? snap : EMPTY;
2513
+ };
2514
+ const check = () => {
2515
+ const v = getSnapshot();
2516
+ if (v === last) return;
2517
+ last = v;
2518
+ listeners.notify();
2519
+ };
2520
+ const listeners = new ListenerSet(
2521
+ () => {
2522
+ offs = [
2523
+ im.on("conversations", (list) => {
2524
+ const me2 = im.currentUserId;
2525
+ if (me2 === null) return;
2526
+ snap = list;
2527
+ owner = me2;
2528
+ check();
2529
+ }),
2530
+ im.on("connection", check),
2531
+ im.on("totalUnread", check)
2532
+ ];
2533
+ const me = im.currentUserId;
2534
+ if (me !== null) {
2535
+ try {
2536
+ snap = im.conversations();
2537
+ owner = me;
2538
+ } catch {
2539
+ }
2540
+ }
2541
+ last = getSnapshot();
2542
+ },
2543
+ () => {
2544
+ offs.forEach((f) => f());
2545
+ offs = [];
2546
+ }
2547
+ );
2548
+ return { subscribe: (fn) => listeners.add(fn), getSnapshot };
2549
+ }
2550
+ function valueStore(im, event, read) {
2551
+ let off = null;
2552
+ let last;
2553
+ const listeners = new ListenerSet(
2554
+ () => {
2555
+ last = read();
2556
+ off = im.on(event, () => {
2557
+ const v = read();
2558
+ if (v === last) return;
2559
+ last = v;
2560
+ listeners.notify();
2561
+ });
2562
+ },
2563
+ () => {
2564
+ off?.();
2565
+ off = null;
2566
+ }
2567
+ );
2568
+ return { subscribe: (fn) => listeners.add(fn), getSnapshot: read };
2569
+ }
2570
+
2571
+ // src/ui/hooks.ts
2572
+ function useStore(s) {
2573
+ return useSyncExternalStore2(s.subscribe, s.getSnapshot, s.getSnapshot);
2574
+ }
2575
+ function useConversations() {
2576
+ return useStore(conversationsStore(useIm()));
2577
+ }
2578
+ function useTotalUnread() {
2579
+ return useStore(totalUnreadStore(useIm()));
2580
+ }
2581
+ function useConnection() {
2582
+ return useStore(connectionStore(useIm()));
2583
+ }
2584
+
2585
+ // src/ui/widgets/UnreadBadge.tsx
2586
+ import { jsx as jsx11, jsxs as jsxs10 } from "react/jsx-runtime";
2587
+ function Badge({ count = 0, dot = false, muted = false }) {
2588
+ if (dot) return /* @__PURE__ */ jsx11("span", { className: "gkim-badge gkim-badge--dot", "aria-hidden": "true" });
2589
+ if (count <= 0) return null;
2590
+ return /* @__PURE__ */ jsx11("span", { className: `gkim-badge${muted ? " gkim-badge--muted" : ""}`, children: count > 99 ? "99+" : count });
2591
+ }
2592
+ function ImUnreadBadge({ children }) {
2593
+ const n = useTotalUnread();
2594
+ return /* @__PURE__ */ jsxs10("span", { className: "gkim-badge-anchor", children: [
2595
+ children,
2596
+ /* @__PURE__ */ jsx11(Badge, { count: n })
2597
+ ] });
2598
+ }
2599
+
2600
+ // src/ui/conversation/ConversationList.tsx
2601
+ import { jsx as jsx12, jsxs as jsxs11 } from "react/jsx-runtime";
2602
+ function errorText(e, fallback) {
2603
+ return e instanceof ImApiError2 && e.message ? e.message : fallback;
2604
+ }
2605
+ function Row({ c, selected, onOpen }) {
2606
+ const { im, strings: s } = useImUi();
2607
+ const { toast, confirm } = useFeedback();
2608
+ const menu = useContextMenu();
2609
+ const title = conversationTitle(c, s);
2610
+ const sum = conversationSummary(c, s);
2611
+ const g = c.group;
2612
+ const run = async (f) => {
2613
+ try {
2614
+ await f();
2615
+ } catch (e) {
2616
+ toast(errorText(e, s.operationFailed));
2617
+ }
2618
+ };
2619
+ const entries = [
2620
+ { label: c.pinned ? s.unpin : s.pin, onSelect: () => run(() => im.setPinned(c.id, !c.pinned)) },
2621
+ { label: c.muted ? s.unmute : s.mute, onSelect: () => run(() => im.setMuted(c.id, !c.muted)) },
2622
+ {
2623
+ label: s.deleteConversation,
2624
+ danger: true,
2625
+ onSelect: async () => {
2626
+ if (await confirm({ title: s.deleteConversation, content: s.deleteConversationConfirm, danger: true })) run(() => im.deleteConversation(c.id));
2627
+ }
2628
+ }
2629
+ ];
2630
+ return /* @__PURE__ */ jsxs11("li", { className: `gkim-conv${c.pinned ? " gkim-conv--pinned" : ""}${selected ? " gkim-conv--selected" : ""}`, children: [
2631
+ /* @__PURE__ */ jsxs11(
2632
+ "button",
2633
+ {
2634
+ type: "button",
2635
+ className: "gkim-conv__btn",
2636
+ onClick: onOpen,
2637
+ "aria-current": selected || void 0,
2638
+ "aria-label": c.unread > 0 ? `${title},${c.unread} 条未读` : title,
2639
+ ...menu.bind,
2640
+ children: [
2641
+ /* @__PURE__ */ jsxs11("span", { className: "gkim-conv__avatar", children: [
2642
+ /* @__PURE__ */ jsx12(
2643
+ Avatar,
2644
+ {
2645
+ id: g?.groupId ?? c.peer?.userId ?? "",
2646
+ name: title,
2647
+ url: g?.avatarUrl ?? c.peer?.avatarUrl,
2648
+ group: !!g,
2649
+ size: void 0
2650
+ }
2651
+ ),
2652
+ c.unread > 0 && /* @__PURE__ */ jsx12("span", { className: "gkim-conv__badge", children: /* @__PURE__ */ jsx12(Badge, { count: c.unread, dot: c.muted }) })
2653
+ ] }),
2654
+ /* @__PURE__ */ jsxs11("span", { className: "gkim-conv__body", children: [
2655
+ /* @__PURE__ */ jsxs11("span", { className: "gkim-conv__line", children: [
2656
+ /* @__PURE__ */ jsx12("span", { className: "gkim-conv__title", children: title }),
2657
+ /* @__PURE__ */ jsx12("span", { className: "gkim-conv__time", children: formatConversationTime(c.lastMsgAt, s) })
2658
+ ] }),
2659
+ /* @__PURE__ */ jsxs11("span", { className: "gkim-conv__line", children: [
2660
+ /* @__PURE__ */ jsxs11("span", { className: "gkim-conv__preview", children: [
2661
+ sum.atMe && /* @__PURE__ */ jsx12("span", { className: "gkim-conv__at", children: sum.atMe }),
2662
+ sum.text
2663
+ ] }),
2664
+ c.muted && /* @__PURE__ */ jsx12("span", { className: "gkim-conv__muted", "aria-label": s.mute, children: /* @__PURE__ */ jsx12(Icon, { name: "mute", size: 14 }) })
2665
+ ] })
2666
+ ] })
2667
+ ]
2668
+ }
2669
+ ),
2670
+ menu.at && /* @__PURE__ */ jsx12(Menu, { entries, x: menu.at.x, y: menu.at.y, onClose: menu.close, label: title })
2671
+ ] });
2672
+ }
2673
+ function ImConversationList({ onOpen, showAddMenu = true, showSearch = true, selectedId }) {
2674
+ const { im, strings: s } = useImUi();
2675
+ const { toast } = useFeedback();
2676
+ const convs = useConversations();
2677
+ const conn = useConnection();
2678
+ const nav = useNavContext();
2679
+ const frame = useFrame();
2680
+ const [busy, setBusy] = useState7(false);
2681
+ void showAddMenu;
2682
+ void showSearch;
2683
+ const mainChat = nav.state.main?.name === "chat" ? nav.state.main.target : null;
2684
+ const selected = selectedId !== void 0 ? selectedId : mainChat?.conversation?.id ?? null;
2685
+ const open = (c) => onOpen ? onOpen(c) : nav.open({ name: "chat", target: { conversation: c } });
2686
+ const anyUnread = convs.some((c) => c.unread > 0);
2687
+ const markAll = async () => {
2688
+ setBusy(true);
2689
+ try {
2690
+ await im.markAllRead();
2691
+ } catch (e) {
2692
+ toast(errorText(e, s.operationFailed));
2693
+ } finally {
2694
+ setBusy(false);
2695
+ }
2696
+ };
2697
+ const markAllBtn = (
2698
+ // 总未读不含免打扰会话,按各会话判断,免打扰的也能一键清掉。
2699
+ /* @__PURE__ */ jsx12(
2700
+ "button",
2701
+ {
2702
+ type: "button",
2703
+ className: "gkim-iconbtn",
2704
+ "aria-label": s.markAllRead,
2705
+ title: s.markAllRead,
2706
+ disabled: !anyUnread || busy,
2707
+ onClick: markAll,
2708
+ children: /* @__PURE__ */ jsx12(Icon, { name: "checkAll" })
2709
+ }
2710
+ )
2711
+ );
2712
+ const banner = conn === "disconnected" ? /* @__PURE__ */ jsx12("div", { className: "gkim-banner gkim-banner--danger", role: "status", children: s.disconnected }) : null;
2713
+ const list = convs.length === 0 ? /* @__PURE__ */ jsx12("div", { className: "gkim-empty gkim-grow", children: s.emptyConversations }) : /* @__PURE__ */ jsx12("ul", { className: "gkim-conv-list", "aria-label": s.conversationsTitle, children: convs.map((c) => /* @__PURE__ */ jsx12(Row, { c, selected: c.id === selected, onOpen: () => open(c) }, c.id)) });
2714
+ if (frame.kind === "list") {
2715
+ return /* @__PURE__ */ jsxs11("div", { className: "gkim-listpane", children: [
2716
+ /* @__PURE__ */ jsxs11("div", { className: "gkim-listpane__head", children: [
2717
+ /* @__PURE__ */ jsx12("h2", { className: "gkim-sr-only", children: s.conversationsTitle }),
2718
+ /* @__PURE__ */ jsx12("div", { className: "gkim-grow" }),
2719
+ markAllBtn
2720
+ ] }),
2721
+ banner,
2722
+ list
2723
+ ] });
2724
+ }
2725
+ return /* @__PURE__ */ jsx12(Page, { title: s.conversationsTitle, actions: markAllBtn, banner, children: list });
2726
+ }
2727
+
2728
+ // src/ui/menu/Report.tsx
2729
+ import { useState as useState8 } from "react";
2730
+ import { ImApiError as ImApiError3, reportReasons } from "@guokit-dev/im";
2731
+ import { Fragment as Fragment5, jsx as jsx13, jsxs as jsxs12 } from "react/jsx-runtime";
2732
+ function ReportDialog({ target, title, messageIds }) {
2733
+ const { im, strings: s } = useImUi();
2734
+ const { toast } = useFeedback();
2735
+ const frame = useFrame();
2736
+ const [reason, setReason] = useState8(null);
2737
+ const [block, setBlock] = useState8(false);
2738
+ const [busy, setBusy] = useState8(false);
2739
+ const submit = async () => {
2740
+ if (!reason) return;
2741
+ setBusy(true);
2742
+ let tip;
2743
+ try {
2744
+ const r = await im.report(typeof target === "string" ? target : target.groupId, reason, { messageIds: messageIds?.length ? messageIds : void 0, block });
2745
+ tip = r.duplicated ? s.reportDuplicated : s.reported;
2746
+ } catch (e) {
2747
+ tip = e instanceof ImApiError3 && e.message ? e.message : s.operationFailed;
2748
+ }
2749
+ toast(tip);
2750
+ frame.close();
2751
+ };
2752
+ return /* @__PURE__ */ jsxs12(
2753
+ Page,
2754
+ {
2755
+ title,
2756
+ className: "gkim-report",
2757
+ footer: /* @__PURE__ */ jsxs12(Fragment5, { children: [
2758
+ /* @__PURE__ */ jsx13("button", { type: "button", className: "gkim-btn", onClick: frame.close, children: s.cancel }),
2759
+ /* @__PURE__ */ jsx13("button", { type: "button", className: "gkim-btn gkim-btn--primary", disabled: !reason || busy, onClick: submit, children: s.submit })
2760
+ ] }),
2761
+ children: [
2762
+ /* @__PURE__ */ jsxs12("fieldset", { className: "gkim-report__reasons", children: [
2763
+ /* @__PURE__ */ jsx13("legend", { className: "gkim-sr-only", children: title }),
2764
+ reportReasons.map((r) => /* @__PURE__ */ jsxs12("label", { className: `gkim-choice${reason === r ? " gkim-choice--on" : ""}`, children: [
2765
+ /* @__PURE__ */ jsx13("input", { type: "radio", name: "gkim-report-reason", value: r, checked: reason === r, disabled: busy, onChange: () => setReason(r) }),
2766
+ /* @__PURE__ */ jsx13("span", { children: s.reportReasons[r] ?? r })
2767
+ ] }, r))
2768
+ ] }),
2769
+ /* @__PURE__ */ jsxs12("label", { className: "gkim-check", children: [
2770
+ /* @__PURE__ */ jsx13("input", { type: "checkbox", checked: block, disabled: busy, onChange: (e) => setBlock(e.target.checked) }),
2771
+ /* @__PURE__ */ jsx13("span", { children: s.alsoBlock })
2772
+ ] })
2773
+ ]
2774
+ }
2775
+ );
2776
+ }
2777
+
2778
+ // src/ui/viewer/ImageViewer.tsx
2779
+ import { useEffect as useEffect7, useState as useState9 } from "react";
2780
+ import { jsx as jsx14, jsxs as jsxs13 } from "react/jsx-runtime";
2781
+ var MIN = 1;
2782
+ var MAX = 4;
2783
+ function ImageViewer({ images, index }) {
2784
+ const { im, strings: s } = useImUi();
2785
+ const frame = useFrame();
2786
+ const [i, setI] = useState9(index);
2787
+ const [scale, setScale] = useState9(1);
2788
+ const [urls, setUrls] = useState9({});
2789
+ const m = images[i];
2790
+ useEffect7(() => {
2791
+ if (!m || m.clientMsgId in urls) return;
2792
+ let alive = true;
2793
+ im.imageUrl(m).then((u) => {
2794
+ if (alive) setUrls((x) => ({ ...x, [m.clientMsgId]: u }));
2795
+ }, () => {
2796
+ });
2797
+ return () => {
2798
+ alive = false;
2799
+ };
2800
+ }, [im, m, urls]);
2801
+ const go = (d) => {
2802
+ const n = i + d;
2803
+ if (n >= 0 && n < images.length) {
2804
+ setI(n);
2805
+ setScale(1);
2806
+ }
2807
+ };
2808
+ const zoom = (d) => setScale((v) => Math.min(MAX, Math.max(MIN, +(v + d).toFixed(2))));
2809
+ const onKey = (e) => {
2810
+ if (e.key === "ArrowLeft") go(-1);
2811
+ else if (e.key === "ArrowRight") go(1);
2812
+ else if (e.key === "+" || e.key === "=") zoom(0.5);
2813
+ else if (e.key === "-") zoom(-0.5);
2814
+ };
2815
+ const onWheel = (e) => zoom(e.deltaY < 0 ? 0.25 : -0.25);
2816
+ const url = m ? urls[m.clientMsgId] : null;
2817
+ return /* @__PURE__ */ jsxs13("div", { className: "gkim-viewer", onKeyDown: onKey, children: [
2818
+ /* @__PURE__ */ jsxs13("div", { className: "gkim-viewer__bar", children: [
2819
+ /* @__PURE__ */ jsx14("span", { className: "gkim-viewer__count", children: fill(s.imageIndex, { n: i + 1, total: images.length }) }),
2820
+ /* @__PURE__ */ jsx14("button", { type: "button", className: "gkim-viewer__btn", "aria-label": s.zoomOut, disabled: scale <= MIN, onClick: () => zoom(-0.5), children: /* @__PURE__ */ jsx14(Icon, { name: "zoomOut" }) }),
2821
+ /* @__PURE__ */ jsx14("button", { type: "button", className: "gkim-viewer__btn", "aria-label": s.zoomIn, disabled: scale >= MAX, onClick: () => zoom(0.5), children: /* @__PURE__ */ jsx14(Icon, { name: "zoomIn" }) }),
2822
+ url && /* @__PURE__ */ jsx14("a", { className: "gkim-viewer__btn", href: url, target: "_blank", rel: "noopener", "aria-label": s.openOriginal, title: s.openOriginal, children: /* @__PURE__ */ jsx14(Icon, { name: "external" }) }),
2823
+ /* @__PURE__ */ jsx14("button", { type: "button", className: "gkim-viewer__btn", "aria-label": s.close, "data-autofocus": true, onClick: frame.close, children: /* @__PURE__ */ jsx14(Icon, { name: "close" }) })
2824
+ ] }),
2825
+ /* @__PURE__ */ jsxs13("div", { className: "gkim-viewer__stage", onWheel, onClick: (e) => {
2826
+ if (e.target === e.currentTarget) frame.close();
2827
+ }, children: [
2828
+ url ? /* @__PURE__ */ jsx14("img", { src: url, alt: s.image, style: { transform: `scale(${scale})` }, onDoubleClick: () => setScale((v) => v > 1 ? 1 : 2), draggable: false }) : /* @__PURE__ */ jsx14("span", { className: "gkim-msglist__spinner", role: "img", "aria-label": "…" }),
2829
+ i > 0 && /* @__PURE__ */ jsx14("button", { type: "button", className: "gkim-viewer__nav gkim-viewer__nav--prev", "aria-label": s.prevImage, onClick: () => go(-1), children: /* @__PURE__ */ jsx14(Icon, { name: "back", size: 28 }) }),
2830
+ i < images.length - 1 && /* @__PURE__ */ jsx14("button", { type: "button", className: "gkim-viewer__nav gkim-viewer__nav--next", "aria-label": s.nextImage, onClick: () => go(1), children: /* @__PURE__ */ jsx14(Icon, { name: "back", size: 28 }) })
2831
+ ] })
2832
+ ] });
2833
+ }
2834
+
2835
+ // src/ui/viewer/VideoPlayer.tsx
2836
+ import { useEffect as useEffect8, useState as useState10 } from "react";
2837
+ import { jsx as jsx15, jsxs as jsxs14 } from "react/jsx-runtime";
2838
+ function VideoPlayer({ message }) {
2839
+ const { im, strings: s } = useImUi();
2840
+ const frame = useFrame();
2841
+ const [url, setUrl] = useState10(null);
2842
+ const [failed, setFailed] = useState10(false);
2843
+ useEffect8(() => {
2844
+ let alive = true;
2845
+ im.videoUrl(message).then((u) => {
2846
+ if (alive) {
2847
+ setUrl(u);
2848
+ if (!u) setFailed(true);
2849
+ }
2850
+ }, () => alive && setFailed(true));
2851
+ return () => {
2852
+ alive = false;
2853
+ };
2854
+ }, [im, message]);
2855
+ return /* @__PURE__ */ jsxs14("div", { className: "gkim-viewer", children: [
2856
+ /* @__PURE__ */ jsxs14("div", { className: "gkim-viewer__bar", children: [
2857
+ /* @__PURE__ */ jsx15("span", { className: "gkim-viewer__count" }),
2858
+ /* @__PURE__ */ jsx15("button", { type: "button", className: "gkim-viewer__btn", "aria-label": s.close, "data-autofocus": true, onClick: frame.close, children: /* @__PURE__ */ jsx15(Icon, { name: "close" }) })
2859
+ ] }),
2860
+ /* @__PURE__ */ jsx15("div", { className: "gkim-viewer__stage", onClick: (e) => {
2861
+ if (e.target === e.currentTarget) frame.close();
2862
+ }, children: url ? /* @__PURE__ */ jsx15("video", { src: url, controls: true, autoPlay: true, playsInline: true }) : failed ? /* @__PURE__ */ jsx15("span", { children: s.operationFailed }) : /* @__PURE__ */ jsx15("span", { className: "gkim-msglist__spinner", role: "img", "aria-label": "…" }) })
2863
+ ] });
2864
+ }
2865
+
2866
+ // src/ui/routes.tsx
2867
+ import { jsx as jsx16 } from "react/jsx-runtime";
2868
+ function renderRoute(route) {
2869
+ switch (route.name) {
2870
+ case "conversations":
2871
+ return /* @__PURE__ */ jsx16(ImConversationList, {});
2872
+ case "chat": {
2873
+ const t = route.target;
2874
+ if (t.conversation) return /* @__PURE__ */ jsx16(ImChat, { conversation: t.conversation }, `c${t.conversation.id}`);
2875
+ if (t.group) return /* @__PURE__ */ jsx16(ImChat, { group: t.group }, `g${t.group}`);
2876
+ return /* @__PURE__ */ jsx16(ImChat, { peer: t.peer }, `p${t.peer}`);
2877
+ }
2878
+ case "report":
2879
+ return /* @__PURE__ */ jsx16(ReportDialog, { target: route.target, title: route.title, messageIds: route.messageIds });
2880
+ case "imageViewer":
2881
+ return /* @__PURE__ */ jsx16(ImageViewer, { images: route.images, index: route.index });
2882
+ case "videoPlayer":
2883
+ return /* @__PURE__ */ jsx16(VideoPlayer, { message: route.message });
2884
+ default:
2885
+ return null;
2886
+ }
2887
+ }
2888
+
2889
+ // src/ui/layout/Layers.tsx
2890
+ import { Fragment as Fragment6, jsx as jsx17, jsxs as jsxs15 } from "react/jsx-runtime";
2891
+ function escToBack(back) {
2892
+ return (e) => {
2893
+ if (e.key === "Escape") {
2894
+ e.stopPropagation();
2895
+ back();
2896
+ }
2897
+ };
2898
+ }
2899
+ function FrameBox({ frame, children }) {
2900
+ return /* @__PURE__ */ jsx17(FrameContext.Provider, { value: frame, children });
2901
+ }
2902
+ function DrawerLayer({ stack, back, close }) {
2903
+ const ref = useFocusTrap(stack.length > 0);
2904
+ if (!stack.length) return null;
2905
+ return /* @__PURE__ */ jsxs15("div", { className: "gkim-drawer-layer", children: [
2906
+ /* @__PURE__ */ jsx17("div", { className: "gkim-scrim", onClick: close }),
2907
+ /* @__PURE__ */ jsx17("aside", { className: "gkim-drawer", ref, tabIndex: -1, onKeyDown: escToBack(back), children: stack.map((r, i) => /* @__PURE__ */ jsx17("div", { className: "gkim-stack-item", hidden: i !== stack.length - 1, children: /* @__PURE__ */ jsx17(FrameBox, { frame: { kind: "drawer", canBack: i > 0, back, close }, children: renderRoute(r) }) }, i)) })
2908
+ ] });
2909
+ }
2910
+ function DialogBox({ children, back }) {
2911
+ const ref = useFocusTrap();
2912
+ return /* @__PURE__ */ jsxs15("div", { className: "gkim-dialog-layer", onKeyDown: escToBack(back), children: [
2913
+ /* @__PURE__ */ jsx17("div", { className: "gkim-scrim", onClick: back }),
2914
+ /* @__PURE__ */ jsx17("div", { className: "gkim-dialog", ref, tabIndex: -1, children })
2915
+ ] });
2916
+ }
2917
+ function DialogLayer({ stack, back }) {
2918
+ return /* @__PURE__ */ jsx17(Fragment6, { children: stack.map((r, i) => /* @__PURE__ */ jsx17(DialogBox, { back, children: /* @__PURE__ */ jsx17(FrameBox, { frame: { kind: "dialog", canBack: false, back, close: back }, children: renderRoute(r) }) }, i)) });
2919
+ }
2920
+ function OverlayBox({ children, back }) {
2921
+ const ref = useFocusTrap();
2922
+ return /* @__PURE__ */ jsx17("div", { className: "gkim-overlay", ref, tabIndex: -1, onKeyDown: escToBack(back), children });
2923
+ }
2924
+ function OverlayLayer({ stack, back }) {
2925
+ return /* @__PURE__ */ jsx17(Fragment6, { children: stack.map((r, i) => /* @__PURE__ */ jsx17(OverlayBox, { back, children: /* @__PURE__ */ jsx17(FrameBox, { frame: { kind: "dialog", canBack: false, back, close: back }, children: renderRoute(r) }) }, i)) });
2926
+ }
2927
+ function LayerHost() {
2928
+ const { state: st, back, close } = useNavContext();
2929
+ return useMemo5(() => /* @__PURE__ */ jsxs15(Fragment6, { children: [
2930
+ /* @__PURE__ */ jsx17(DrawerLayer, { stack: st.drawer, back, close }),
2931
+ /* @__PURE__ */ jsx17(DialogLayer, { stack: st.dialog, back }),
2932
+ /* @__PURE__ */ jsx17(OverlayLayer, { stack: st.overlay, back })
2933
+ ] }), [st, back, close]);
2934
+ }
2935
+
2936
+ // src/ui/context.tsx
2937
+ import { jsx as jsx18, jsxs as jsxs16 } from "react/jsx-runtime";
2938
+ var UiContext = createContext4(null);
2939
+ var EMPTY2 = {};
2940
+ var NO_ITEMS = [];
2941
+ function chatTargetOf(t) {
2942
+ const c = t.conversation;
2943
+ const peerId = c ? c.group ? null : c.peer?.userId ?? null : t.peer ?? null;
2944
+ const groupId = c ? c.group?.groupId ?? null : t.group ?? null;
2945
+ return { peerId, groupId, conversationId: c?.id ?? null, to: peerId ?? "" };
2946
+ }
2947
+ function GuokitImUi(props) {
2948
+ const { im, me, theme, strings, callbacks, messageRenderers, moreItems, menuItems, className, style, children } = props;
2949
+ const merged = useMemo6(() => mergeStrings(strings), [strings]);
2950
+ const cb = callbacks ?? EMPTY2;
2951
+ const value = useMemo6(() => ({
2952
+ im,
2953
+ me: me ?? EMPTY2,
2954
+ strings: merged,
2955
+ callbacks: cb,
2956
+ messageRenderers: messageRenderers ?? EMPTY2,
2957
+ moreItems: moreItems ?? NO_ITEMS,
2958
+ menuItems
2959
+ }), [im, me, merged, cb, messageRenderers, moreItems, menuItems]);
2960
+ const cbRef = useRef8(cb);
2961
+ cbRef.current = cb;
2962
+ useEffect9(() => im.on("kickedOut", () => cbRef.current.onKickedOut?.()), [im]);
2963
+ const onMainOrList = useCallback7((r) => {
2964
+ if (r.name === "chat") cbRef.current.onOpenConversation?.(chatTargetOf(r.target));
2965
+ }, []);
2966
+ const nav = useNavState(false, onMainOrList);
2967
+ return /* @__PURE__ */ jsx18(UiContext.Provider, { value, children: /* @__PURE__ */ jsx18(NavContext.Provider, { value: nav, children: /* @__PURE__ */ jsx18("div", { className: className ? `gkim-root ${className}` : "gkim-root", style: { ...themeVars(theme), ...style }, children: /* @__PURE__ */ jsxs16(FeedbackProvider, { labels: { ok: merged.confirm, cancel: merged.cancel }, children: [
2968
+ children,
2969
+ /* @__PURE__ */ jsx18(LayerHost, {})
2970
+ ] }) }) }) });
2971
+ }
2972
+ function useImUi() {
2973
+ const v = useContext4(UiContext);
2974
+ if (!v) throw new Error("没有找到 GuokitImUi:IM 组件要放在 GuokitImUi 下面。");
2975
+ return v;
2976
+ }
2977
+ function useIm() {
2978
+ return useImUi().im;
2979
+ }
2980
+
2981
+ // src/ui/layout/ImWorkspace.tsx
2982
+ import { useEffect as useEffect10, useRef as useRef9 } from "react";
2983
+
2984
+ // src/ui/layout/useWide.ts
2985
+ import { useLayoutEffect as useLayoutEffect4, useState as useState11 } from "react";
2986
+ var WIDE_MIN = 768;
2987
+ function useWide(ref) {
2988
+ const [wide, setWide] = useState11(true);
2989
+ useLayoutEffect4(() => {
2990
+ const el = ref.current;
2991
+ if (!el || typeof ResizeObserver === "undefined") return;
2992
+ const ro = new ResizeObserver((entries) => {
2993
+ const w = entries[0]?.contentRect.width ?? el.clientWidth;
2994
+ setWide(w >= WIDE_MIN);
2995
+ });
2996
+ ro.observe(el);
2997
+ return () => ro.disconnect();
2998
+ }, [ref]);
2999
+ return wide;
3000
+ }
3001
+
3002
+ // src/ui/layout/ImWorkspace.tsx
3003
+ import { Fragment as Fragment7, jsx as jsx19, jsxs as jsxs17 } from "react/jsx-runtime";
3004
+ function Rail() {
3005
+ const { im, me, strings: s } = useImUi();
3006
+ const unread = useTotalUnread();
3007
+ const uid = im.currentUserId ?? "";
3008
+ return /* @__PURE__ */ jsxs17("nav", { className: "gkim-rail", "aria-label": "IM", children: [
3009
+ /* @__PURE__ */ jsx19(Avatar, { id: uid, name: me.nickname ?? "", url: me.avatarUrl, size: 36 }),
3010
+ /* @__PURE__ */ jsxs17("button", { type: "button", className: "gkim-rail__item", "aria-label": s.navMessages, "aria-current": "page", children: [
3011
+ /* @__PURE__ */ jsx19(Icon, { name: "message", size: 22 }),
3012
+ /* @__PURE__ */ jsx19(Badge, { count: unread })
3013
+ ] })
3014
+ ] });
3015
+ }
3016
+ function Wide({ nav }) {
3017
+ const { state: st, back, close } = nav;
3018
+ const { strings: s } = useImUi();
3019
+ const noop2 = () => {
3020
+ };
3021
+ return /* @__PURE__ */ jsxs17(Fragment7, { children: [
3022
+ /* @__PURE__ */ jsx19(Rail, {}),
3023
+ /* @__PURE__ */ jsx19("div", { className: "gkim-listcol", children: /* @__PURE__ */ jsx19(FrameContext.Provider, { value: { kind: "list", canBack: false, back: noop2, close: noop2 }, children: renderRoute(st.list) }) }),
3024
+ /* @__PURE__ */ jsxs17("div", { className: "gkim-main", children: [
3025
+ st.main ? /* @__PURE__ */ jsx19(FrameContext.Provider, { value: { kind: "main", canBack: false, back, close }, children: renderRoute(st.main) }) : /* @__PURE__ */ jsx19("div", { className: "gkim-empty gkim-main__empty", children: s.selectConversation }),
3026
+ /* @__PURE__ */ jsx19(DrawerLayer, { stack: st.drawer, back, close })
3027
+ ] }),
3028
+ /* @__PURE__ */ jsx19(DialogLayer, { stack: st.dialog, back }),
3029
+ /* @__PURE__ */ jsx19(OverlayLayer, { stack: st.overlay, back })
3030
+ ] });
3031
+ }
3032
+ function Narrow({ nav }) {
3033
+ const { state: st, back } = nav;
3034
+ const pages = [
3035
+ { key: "list", route: st.list },
3036
+ ...st.main ? [{ key: "main", route: st.main }] : [],
3037
+ ...st.drawer.map((route, i) => ({ key: `d${i}`, route })),
3038
+ ...st.dialog.map((route, i) => ({ key: `g${i}`, route }))
3039
+ ];
3040
+ return /* @__PURE__ */ jsxs17(Fragment7, { children: [
3041
+ pages.map((p, i) => /* @__PURE__ */ jsx19("div", { className: "gkim-stack-item gkim-narrow-page", hidden: i !== pages.length - 1, children: /* @__PURE__ */ jsx19(FrameContext.Provider, { value: { kind: "page", canBack: i > 0, back, close: back }, children: renderRoute(p.route) }) }, p.key)),
3042
+ /* @__PURE__ */ jsx19(OverlayLayer, { stack: st.overlay, back })
3043
+ ] });
3044
+ }
3045
+ function ImWorkspace({ className }) {
3046
+ const ref = useRef9(null);
3047
+ const wide = useWide(ref);
3048
+ const { callbacks } = useImUi();
3049
+ const nav = useNavState(true);
3050
+ const onNavigate = useRef9(callbacks.onNavigate);
3051
+ onNavigate.current = callbacks.onNavigate;
3052
+ const last = useRef9(nav.state);
3053
+ useEffect10(() => {
3054
+ if (last.current === nav.state) return;
3055
+ last.current = nav.state;
3056
+ onNavigate.current?.(topRoute(nav.state));
3057
+ }, [nav.state]);
3058
+ return /* @__PURE__ */ jsx19(NavContext.Provider, { value: nav, children: /* @__PURE__ */ jsx19("div", { ref, className: `gkim-workspace gkim-workspace--${wide ? "wide" : "narrow"}${className ? " " + className : ""}`, children: wide ? /* @__PURE__ */ jsx19(Wide, { nav }) : /* @__PURE__ */ jsx19(Narrow, { nav }) }) });
3059
+ }
3060
+ export {
3061
+ GuokitImUi,
3062
+ Avatar as ImAvatar,
3063
+ ImChat,
3064
+ ImConversationList,
3065
+ ImUnreadBadge,
3066
+ ImWorkspace,
3067
+ defaultStrings,
3068
+ useConnection,
3069
+ useConversations,
3070
+ useIm,
3071
+ useImNavigator,
3072
+ useTotalUnread
3073
+ };