@alexsun-top/opencode-chat-room 0.2.3 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +44 -7
- package/README.zh-CN.md +44 -7
- package/package.json +6 -2
- package/plugin.ts +21 -6
- package/server/assets/DOMPURIFY-LICENSE +202 -0
- package/server/assets/MARKED-LICENSE +44 -0
- package/server/assets/NOTICE.txt +6 -0
- package/server/assets/base.css +225 -0
- package/server/assets/chat/events.js +148 -0
- package/server/assets/chat/index.js +12 -0
- package/server/assets/chat/markdown.js +65 -0
- package/server/assets/chat/members.js +201 -0
- package/server/assets/chat/mentions.js +131 -0
- package/server/assets/chat/messages.js +489 -0
- package/server/assets/chat/rooms.js +443 -0
- package/server/assets/chat/state.js +327 -0
- package/server/assets/conversation.css +364 -0
- package/server/assets/dompurify-3.4.7.js +3 -0
- package/server/assets/marked-18.0.4.js +79 -0
- package/server/assets/responsive.css +119 -0
- package/server/chat-server.ts +39 -43
- package/server/chat.html +27 -1984
- package/server/history-route.ts +2 -1
- package/server/inbox.ts +1 -1
- package/server/member-routes.ts +117 -0
- package/server/newrooms.ts +86 -0
- package/server/wake.ts +13 -14
- package/src/agent-presence.ts +60 -0
- package/src/agent-receipts.ts +107 -0
- package/src/background.ts +70 -25
- package/src/center-client.ts +25 -6
- package/src/center-inbox.ts +77 -37
- package/src/center-wake.ts +43 -9
- package/src/member-state.ts +25 -0
- package/src/mentions.ts +7 -0
- package/src/plugin-notifications.ts +75 -23
- package/src/queue-transport.ts +17 -1
- package/src/queue.ts +36 -2
- package/src/receiver-state.ts +108 -6
- package/src/room-service.ts +19 -1
- package/src/sqlite-state.ts +123 -16
- package/src/store.ts +28 -1
- package/src/v2-plugin.ts +10 -2
- package/src/v2-receiver.ts +67 -45
- package/src/watch.ts +17 -3
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
export const app = {
|
|
2
|
+
$: (selector) => document.querySelector(selector),
|
|
3
|
+
state: {
|
|
4
|
+
room: null, myName: "", unread: 0, drafts: new Map(), rooms: new Map(),
|
|
5
|
+
pollGeneration: 0, navigationGeneration: 0, draftRevision: new Map(), memberSessions: new Map(),
|
|
6
|
+
retryingFailedIds: new Set(), pollController: null, memberRefreshTimer: 0, receiptRefreshTimer: 0, receiptObservationFrame: 0,
|
|
7
|
+
receiptObservation: null,
|
|
8
|
+
memberApiUnavailable: new Set(), receiptApiUnavailable: new Set(),
|
|
9
|
+
receipts: new Map(), acknowledgedMessages: new Map(), pendingAcknowledgements: new Map(),
|
|
10
|
+
pendingAction: null, watcherTimer: 0, restored: false,
|
|
11
|
+
},
|
|
12
|
+
rendered: 0,
|
|
13
|
+
firstMessageId: null,
|
|
14
|
+
pollDelay: 2000,
|
|
15
|
+
copyTimer: 0,
|
|
16
|
+
failedRenderIds: new Set(),
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function createRandomId() {
|
|
20
|
+
const crypto = globalThis.crypto;
|
|
21
|
+
if (crypto?.randomUUID) return crypto.randomUUID();
|
|
22
|
+
if (!crypto?.getRandomValues) throw new Error("Secure session ID generation is unavailable");
|
|
23
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
24
|
+
bytes[6] = (bytes[6] & 15) | 64;
|
|
25
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
26
|
+
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
27
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createAuth(storage, fetcher, translate = (key) => key, sessionStore) {
|
|
31
|
+
const memory = Object.create(null);
|
|
32
|
+
let memorySessionID = "";
|
|
33
|
+
const read = (key) => {
|
|
34
|
+
if (Object.hasOwn(memory, key)) return memory[key];
|
|
35
|
+
try { return (storage ?? globalThis.localStorage).getItem(key); } catch { return null; }
|
|
36
|
+
};
|
|
37
|
+
const write = (key, value) => {
|
|
38
|
+
const stored = value == null ? null : String(value);
|
|
39
|
+
try {
|
|
40
|
+
const store = storage ?? globalThis.localStorage;
|
|
41
|
+
if (stored == null) store.removeItem(key);
|
|
42
|
+
else store.setItem(key, stored);
|
|
43
|
+
delete memory[key];
|
|
44
|
+
} catch { memory[key] = stored; }
|
|
45
|
+
};
|
|
46
|
+
const readSession = (key) => {
|
|
47
|
+
try { return (sessionStore ?? globalThis.sessionStorage).getItem(key); } catch { return null; }
|
|
48
|
+
};
|
|
49
|
+
const writeSession = (key, value) => {
|
|
50
|
+
try {
|
|
51
|
+
const store = sessionStore ?? globalThis.sessionStorage;
|
|
52
|
+
if (value == null) store.removeItem(key);
|
|
53
|
+
else store.setItem(key, value);
|
|
54
|
+
} catch { /* Tab-scoped state is best effort. */ }
|
|
55
|
+
};
|
|
56
|
+
const auth = {
|
|
57
|
+
get sessionID() {
|
|
58
|
+
if (memorySessionID) return memorySessionID;
|
|
59
|
+
try {
|
|
60
|
+
const store = sessionStore ?? globalThis.sessionStorage;
|
|
61
|
+
memorySessionID = store.getItem("chat.sessionID") || "";
|
|
62
|
+
} catch { /* Keep one identity in memory when tab storage is blocked. */ }
|
|
63
|
+
if (!memorySessionID) {
|
|
64
|
+
memorySessionID = createRandomId();
|
|
65
|
+
try { (sessionStore ?? globalThis.sessionStorage).setItem("chat.sessionID", memorySessionID); }
|
|
66
|
+
catch { /* In-memory identity remains stable. */ }
|
|
67
|
+
}
|
|
68
|
+
return memorySessionID;
|
|
69
|
+
},
|
|
70
|
+
get roomId() {
|
|
71
|
+
const active = readSession("chat.roomId");
|
|
72
|
+
if (active) return active;
|
|
73
|
+
const legacy = read("chat.roomId");
|
|
74
|
+
if (legacy) writeSession("chat.roomId", legacy);
|
|
75
|
+
return legacy || "";
|
|
76
|
+
},
|
|
77
|
+
set roomId(value) { writeSession("chat.roomId", value || null); write("chat.roomId", null); },
|
|
78
|
+
get name() { return readSession("chat.name") || read("chat.name") || ""; },
|
|
79
|
+
set name(value) { writeSession("chat.name", value || null); write("chat.name", null); },
|
|
80
|
+
get token() { return read("chat.token") || ""; }, set token(value) { write("chat.token", value || null); },
|
|
81
|
+
get locale() { return read("chat.locale") || "en"; }, set locale(value) { write("chat.locale", value || null); },
|
|
82
|
+
get joinedRoomIds() {
|
|
83
|
+
try {
|
|
84
|
+
const ids = JSON.parse(readSession("chat.joinedRoomIds") || "[]");
|
|
85
|
+
return Array.isArray(ids) ? [...new Set(ids.filter((id) => typeof id === "string"))] : [];
|
|
86
|
+
} catch { return []; }
|
|
87
|
+
},
|
|
88
|
+
set joinedRoomIds(ids) { writeSession("chat.joinedRoomIds", JSON.stringify([...new Set(ids)])); },
|
|
89
|
+
get roomNames() { try { return JSON.parse(readSession("chat.roomNames") || "{}"); } catch { return {}; } },
|
|
90
|
+
set roomNames(value) { writeSession("chat.roomNames", JSON.stringify(value)); },
|
|
91
|
+
get drafts() { try { return JSON.parse(readSession("chat.drafts") || "{}"); } catch { return {}; } },
|
|
92
|
+
set drafts(value) { writeSession("chat.drafts", JSON.stringify(value)); },
|
|
93
|
+
get positions() { try { return JSON.parse(readSession("chat.positions") || "{}"); } catch { return {}; } },
|
|
94
|
+
set positions(value) { writeSession("chat.positions", JSON.stringify(value)); },
|
|
95
|
+
get failedMessages() {
|
|
96
|
+
try {
|
|
97
|
+
const value = JSON.parse(readSession("chat.failedMessages") || "{}");
|
|
98
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
99
|
+
} catch { return {}; }
|
|
100
|
+
},
|
|
101
|
+
set failedMessages(value) { writeSession("chat.failedMessages", JSON.stringify(value)); },
|
|
102
|
+
};
|
|
103
|
+
const saveToken = (value) => { auth.token = String(value ?? "").trim(); return auth.token; };
|
|
104
|
+
const api = async (url, options = {}) => {
|
|
105
|
+
const headers = { ...options.headers };
|
|
106
|
+
if (options.body) headers["Content-Type"] = "application/json";
|
|
107
|
+
if (auth.token) headers.Authorization = `Bearer ${auth.token}`;
|
|
108
|
+
let response;
|
|
109
|
+
try { response = await (fetcher ?? globalThis.fetch)(url, { ...options, headers }); }
|
|
110
|
+
catch {
|
|
111
|
+
const error = new Error(translate("networkError"));
|
|
112
|
+
error.network = true;
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
const data = await response.json().catch(() => ({}));
|
|
116
|
+
if (!response.ok) {
|
|
117
|
+
const error = new Error(data.error || translate("requestFailed", { status: response.status }));
|
|
118
|
+
error.status = response.status;
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
return data;
|
|
122
|
+
};
|
|
123
|
+
return { LS: auth, saveToken, api };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const messages = {
|
|
127
|
+
en: {
|
|
128
|
+
brand: "Casual Chat", documentTitle: "Casual Chat · Lightweight Chatroom",
|
|
129
|
+
roomTitle: ({ name }) => `${name} · Casual Chat`,
|
|
130
|
+
tagline: "A lightweight chat room. Enter a room ID to join, or create a new one.",
|
|
131
|
+
languageLabel: "Language", roomIdLabel: "Room ID", roomIdPlaceholder: "Paste or enter a room ID",
|
|
132
|
+
nameLabel: "Your name", namePlaceholder: "What should we call you?", joinRoom: "Join room",
|
|
133
|
+
or: "or", newRoomNameLabel: "New room name", newRoomNamePlaceholder: "e.g. Weekend movie night",
|
|
134
|
+
createRoom: "Create room", tokenOptional: "Access token (optional)", bearerToken: "Bearer token",
|
|
135
|
+
tokenPlaceholder: "Enter if the server requires it", save: "Save",
|
|
136
|
+
tokenHint: "If the server requires an access token (401), all requests will include it.",
|
|
137
|
+
existingRooms: "Rooms", noRooms: "No rooms yet. Create one.", copyRoomId: "Copy room ID",
|
|
138
|
+
newRoom: "Create a room",
|
|
139
|
+
copyRoomIdTitle: ({ id }) => `Click to copy the full room ID: ${id}`, copied: "Copied",
|
|
140
|
+
members: "Members", membersCount: ({ count }) => `Members (${count})`, noMembers: "No members yet.",
|
|
141
|
+
settings: "Settings", tokenRequired: "The server requires an access token (401).",
|
|
142
|
+
leave: "Leave", reconnecting: "Connection lost. Retrying…", messageList: "Message list",
|
|
143
|
+
noMessages: "No messages yet. Say something.", latestMessages: "Back to latest messages",
|
|
144
|
+
mentionMembers: "Choose a member to mention", messagePlaceholder: "Message · Enter sends · Shift+Enter adds a line",
|
|
145
|
+
send: "Send", roomMeta: ({ members, count }) => `${members} ${members === 1 ? "member" : "members"} · ${count} ${count === 1 ? "message" : "messages"}`,
|
|
146
|
+
joinArrow: "Join →", joinDirectTitle: "Click to join directly", mentionEmpty: "No matching members",
|
|
147
|
+
joined: "Joined", joinAction: "Join room", unreadMessages: ({ count }) => `${count} unread`,
|
|
148
|
+
mentionHint: "↑↓ Select · Enter to confirm · Esc to close", today: "Today", yesterday: "Yesterday",
|
|
149
|
+
earlierMessages: "Earlier messages omitted", you: "You", saved: "Saved",
|
|
150
|
+
savedMemory: "Saved for this tab only", copyFailed: ({ id }) => `Copy failed. Copy manually: ${id}`,
|
|
151
|
+
copyCode: "Copy code", copiedCode: "Copied", copyCodeFailed: "Could not copy code. Select and copy it manually.",
|
|
152
|
+
networkError: "Network connection failed", requestFailed: ({ status }) => `Request failed (HTTP ${status})`,
|
|
153
|
+
roomIdRequired: "Enter a room ID", nameRequired: "Enter your name", authRetry: "The server requires an access token. Enter it and try again.",
|
|
154
|
+
networkRetry: "Unable to connect to the server. Check your network and try again.",
|
|
155
|
+
joinFailed: ({ message }) => `Could not join: ${message}`, roomNameRequired: "Enter a room name",
|
|
156
|
+
createFailed: ({ message }) => `Could not create the room: ${message}`,
|
|
157
|
+
roomNotFound: "This room is gone, or you no longer have access.",
|
|
158
|
+
sendAuth: "Send failed: an access token is required", sendNetwork: "Send failed. Your message is saved below.",
|
|
159
|
+
sendFailed: ({ message }) => `Send failed: ${message}`,
|
|
160
|
+
failedMessages: "Messages not sent", retryFailed: "Retry", discardFailed: "Discard",
|
|
161
|
+
roomListError: "Unable to load rooms. You can enter a room ID directly.", guest: "Guest",
|
|
162
|
+
roomsLabel: "Rooms", refreshRooms: "Refresh rooms", identityLabel: ({ name }) => `Chatting as ${name}`,
|
|
163
|
+
direct: "Direct", messagePrivately: "Message privately", removeMember: "Remove",
|
|
164
|
+
kickConfirm: ({ name, id }) => `Remove ${name} (session ${id}) from this room?`,
|
|
165
|
+
deleteRoom: "Delete room", deleteConfirm: ({ name }) => `Delete “${name}” and all its messages? This cannot be undone.`,
|
|
166
|
+
allMembers: "Everyone", messageCount: ({ count }) => `${count} / 2000`,
|
|
167
|
+
privacyNote: "Anyone with the shared token can read direct messages and manage rooms; the server can read them too.",
|
|
168
|
+
systemJoined: ({ name }) => `${name} joined the room`, systemLeft: ({ name }) => `${name} left the room`,
|
|
169
|
+
activity_working: "Working", activity_idle: "Foreground idle", activity_waiting: "Waiting", activity_unknown: "Status unknown", activity_offline: "Status stale",
|
|
170
|
+
activityHint_working: "The agent reports active work.", activityHint_idle: "Foreground is idle; background work may continue.", activityHint_waiting: "The agent reports that it is waiting.", activityHint_unknown: "No activity report is available.", activityHint_offline: "The last status is stale; this does not prove the agent is offline.",
|
|
171
|
+
receiptCount: ({ count }) => `Read by ${count}`, departedMember: "left",
|
|
172
|
+
receiptEvidence_displayed: "Shown on screen", receiptEvidence_tool: "Fetched with room tool", receiptEvidence_context: "Full message reached agent context preparation (not proof of understanding)",
|
|
173
|
+
},
|
|
174
|
+
"zh-CN": {
|
|
175
|
+
brand: "闲叙", documentTitle: "闲叙 · 轻量聊天室", roomTitle: ({ name }) => `${name} · 闲叙`,
|
|
176
|
+
tagline: "一个轻量的聊天房间。输入房间 ID 加入,或直接新建一个。", languageLabel: "语言",
|
|
177
|
+
roomIdLabel: "房间 ID", roomIdPlaceholder: "粘贴或输入房间 ID", nameLabel: "你的昵称",
|
|
178
|
+
namePlaceholder: "怎么称呼你", joinRoom: "加入房间", or: "或", newRoomNameLabel: "新房间名称",
|
|
179
|
+
newRoomNamePlaceholder: "例如:周末电影夜", createRoom: "创建新房间", tokenOptional: "访问令牌(可选)",
|
|
180
|
+
bearerToken: "Bearer Token", tokenPlaceholder: "服务器要求时填写", save: "保存",
|
|
181
|
+
tokenHint: "若服务器设置了访问令牌(401),所有请求都会带上它。", existingRooms: "房间",
|
|
182
|
+
noRooms: "还没有房间,创建一个吧。", copyRoomId: "复制房间 ID",
|
|
183
|
+
newRoom: "创建房间",
|
|
184
|
+
copyRoomIdTitle: ({ id }) => `点击复制完整房间 ID:${id}`, copied: "已复制", members: "成员",
|
|
185
|
+
membersCount: ({ count }) => `成员 ${count}`, noMembers: "暂无成员", settings: "设置",
|
|
186
|
+
tokenRequired: "服务器要求访问令牌(401)。", leave: "离开", reconnecting: "连接中断,正在重试…",
|
|
187
|
+
messageList: "消息列表", noMessages: "还没有消息,说点什么吧。", latestMessages: "回到最新消息",
|
|
188
|
+
mentionMembers: "选择要提及的成员", messagePlaceholder: "输入消息,Enter 发送,Shift+Enter 换行",
|
|
189
|
+
send: "发送", roomMeta: ({ members, count }) => `${members} 人 · ${count} 条消息`, joinArrow: "加入 →",
|
|
190
|
+
joinDirectTitle: "点击直接加入", mentionEmpty: "没有匹配的成员", mentionHint: "↑↓ 选择 · Enter 确认 · Esc 关闭",
|
|
191
|
+
joined: "已加入", joinAction: "加入房间", unreadMessages: ({ count }) => `${count} 条未读`,
|
|
192
|
+
today: "今天", yesterday: "昨天", earlierMessages: "更早的消息已省略", you: "我", saved: "已保存",
|
|
193
|
+
savedMemory: "仅保存于当前标签页", copyFailed: ({ id }) => `复制失败,请手动复制:${id}`,
|
|
194
|
+
copyCode: "复制代码", copiedCode: "已复制", copyCodeFailed: "复制失败,请手动选择并复制代码。",
|
|
195
|
+
networkError: "网络连接失败", requestFailed: ({ status }) => `请求失败(HTTP ${status})`,
|
|
196
|
+
roomIdRequired: "请输入房间 ID", nameRequired: "请输入你的昵称", authRetry: "服务器要求访问令牌,请填写后重试",
|
|
197
|
+
networkRetry: "无法连接服务器,请检查网络后重试", joinFailed: ({ message }) => `加入失败:${message}`,
|
|
198
|
+
roomNameRequired: "请输入房间名称", createFailed: ({ message }) => `创建失败:${message}`,
|
|
199
|
+
roomNotFound: "房间不存在,或你已被移出房间", sendAuth: "发送失败:需要访问令牌",
|
|
200
|
+
sendNetwork: "发送失败,消息已保存在下方", sendFailed: ({ message }) => `发送失败:${message}`,
|
|
201
|
+
failedMessages: "未发送的消息", retryFailed: "重试", discardFailed: "删除",
|
|
202
|
+
roomListError: "无法加载房间列表,可直接输入房间 ID 加入。", guest: "访客", roomsLabel: "房间列表",
|
|
203
|
+
refreshRooms: "刷新房间", identityLabel: ({ name }) => `当前昵称:${name}`, direct: "私聊",
|
|
204
|
+
messagePrivately: "私聊", removeMember: "移除", kickConfirm: ({ name, id }) => `确定将 ${name}(会话 ${id})移出此房间?`,
|
|
205
|
+
deleteRoom: "删除房间", deleteConfirm: ({ name }) => `删除“${name}”及全部聊天记录?此操作无法撤销。`,
|
|
206
|
+
allMembers: "所有人", messageCount: ({ count }) => `${count} / 2000`,
|
|
207
|
+
privacyNote: "持有共享令牌的人都可以读取私聊内容和管理房间;服务器也可以读取私聊内容。",
|
|
208
|
+
systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`,
|
|
209
|
+
activity_working: "工作中", activity_idle: "前台空闲", activity_waiting: "等待中", activity_unknown: "状态未知", activity_offline: "状态已过期",
|
|
210
|
+
activityHint_working: "Agent 正在报告工作状态。", activityHint_idle: "前台空闲;后台任务仍可能继续。", activityHint_waiting: "Agent 正在报告等待状态。", activityHint_unknown: "暂无活动状态报告。", activityHint_offline: "最近的状态已过期;这不能证明 Agent 已离线。",
|
|
211
|
+
receiptCount: ({ count }) => `已读 ${count} 人`, departedMember: "已离开",
|
|
212
|
+
receiptEvidence_displayed: "已显示在屏幕上", receiptEvidence_tool: "通过房间工具读取", receiptEvidence_context: "完整消息已进入 Agent 上下文准备阶段(不代表已理解)",
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
app.t = (key, values = {}) => {
|
|
217
|
+
const entry = messages[app.locale][key] ?? messages.en[key] ?? key;
|
|
218
|
+
const text = typeof entry === "function" ? entry(values) : entry;
|
|
219
|
+
return String(text).replace(/\{(\w+)\}/g, (_, name) => values[name] ?? "");
|
|
220
|
+
};
|
|
221
|
+
export const { LS, saveToken, api } = createAuth(undefined, undefined, (key, values) => app.t(key, values));
|
|
222
|
+
app.LS = LS;
|
|
223
|
+
app.api = api;
|
|
224
|
+
app.setToken = saveToken;
|
|
225
|
+
app.locale = LS.locale === "zh-CN" ? "zh-CN" : "en";
|
|
226
|
+
app.state.joinedIds = new Set(LS.joinedRoomIds);
|
|
227
|
+
app.state.drafts = new Map(Object.entries(LS.drafts));
|
|
228
|
+
app.state.positions = new Map(Object.entries(LS.positions).map(([id, value]) => [id, Number(value) || 0]));
|
|
229
|
+
app.state.roomNames = new Map(Object.entries(LS.roomNames));
|
|
230
|
+
app.state.failedMessages = new Map(Object.entries(LS.failedMessages).map(([id, items]) => [id, Array.isArray(items) ? items.filter((item) => item && typeof item.id === "string" && typeof item.text === "string") : []]));
|
|
231
|
+
app.saveDraft = (roomId, text) => {
|
|
232
|
+
app.state.drafts.set(roomId, text);
|
|
233
|
+
LS.drafts = Object.fromEntries(app.state.drafts);
|
|
234
|
+
};
|
|
235
|
+
app.clearDraft = (roomId) => {
|
|
236
|
+
app.state.drafts.delete(roomId);
|
|
237
|
+
LS.drafts = Object.fromEntries(app.state.drafts);
|
|
238
|
+
};
|
|
239
|
+
app.saveFailedMessages = (roomId, items) => {
|
|
240
|
+
if (items.length) app.state.failedMessages.set(roomId, items);
|
|
241
|
+
else app.state.failedMessages.delete(roomId);
|
|
242
|
+
LS.failedMessages = Object.fromEntries(app.state.failedMessages);
|
|
243
|
+
};
|
|
244
|
+
app.savePosition = (roomId, position) => {
|
|
245
|
+
app.state.positions.set(roomId, position);
|
|
246
|
+
LS.positions = Object.fromEntries(app.state.positions);
|
|
247
|
+
};
|
|
248
|
+
app.clearPosition = (roomId) => {
|
|
249
|
+
app.state.positions.delete(roomId);
|
|
250
|
+
LS.positions = Object.fromEntries(app.state.positions);
|
|
251
|
+
};
|
|
252
|
+
app.saveJoinedIds = () => { LS.joinedRoomIds = [...app.state.joinedIds]; };
|
|
253
|
+
app.saveRoomNames = () => { LS.roomNames = Object.fromEntries(app.state.roomNames); };
|
|
254
|
+
app.setText = (element, key, values = {}) => {
|
|
255
|
+
element.dataset.i18n = key;
|
|
256
|
+
element._i18nValues = values;
|
|
257
|
+
element.textContent = app.t(key, values);
|
|
258
|
+
};
|
|
259
|
+
app.applyLocale = () => {
|
|
260
|
+
document.documentElement.lang = app.locale;
|
|
261
|
+
document.querySelectorAll("[data-i18n]").forEach((element) => {
|
|
262
|
+
element.textContent = element._flashKey
|
|
263
|
+
? app.t(element._flashKey)
|
|
264
|
+
: app.t(element.dataset.i18n, element._i18nValues || {});
|
|
265
|
+
});
|
|
266
|
+
for (const attribute of ["aria-label", "title", "placeholder"]) {
|
|
267
|
+
document.querySelectorAll(`[data-i18n-${attribute}]`).forEach((element) => {
|
|
268
|
+
element.setAttribute(attribute, app.t(element.getAttribute(`data-i18n-${attribute}`), element._i18nValues || {}));
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
document.querySelectorAll(".locale-select").forEach((select) => { select.value = app.locale; });
|
|
272
|
+
app.updateDraftCount?.();
|
|
273
|
+
app.updateMentionList?.();
|
|
274
|
+
app.renderFailedMessages?.();
|
|
275
|
+
if (app.state.room) {
|
|
276
|
+
app.renderHead();
|
|
277
|
+
app.renderMembers();
|
|
278
|
+
app.rerenderMessages();
|
|
279
|
+
} else app.updateTitle();
|
|
280
|
+
};
|
|
281
|
+
app.setLocale = (locale) => {
|
|
282
|
+
app.locale = locale === "zh-CN" ? "zh-CN" : "en";
|
|
283
|
+
LS.locale = app.locale;
|
|
284
|
+
app.applyLocale();
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
app.intlLocale = () => app.locale === "zh-CN" ? "zh-CN" : "en-US";
|
|
288
|
+
app.fmtTime = (timestamp) => {
|
|
289
|
+
const date = new Date(timestamp);
|
|
290
|
+
return date.toDateString() === new Date().toDateString()
|
|
291
|
+
? `${app.t("today")} ${app.timeHM(timestamp)}`
|
|
292
|
+
: new Intl.DateTimeFormat(app.intlLocale(), { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }).format(date);
|
|
293
|
+
};
|
|
294
|
+
app.timeHM = (timestamp) => new Date(timestamp).toLocaleTimeString(app.intlLocale(), { hour: "2-digit", minute: "2-digit" });
|
|
295
|
+
app.dayText = (timestamp) => {
|
|
296
|
+
const date = new Date(timestamp), now = new Date();
|
|
297
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
298
|
+
const thatDay = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
299
|
+
const difference = Math.round((today - thatDay) / 86400000);
|
|
300
|
+
if (difference === 0) return app.t("today");
|
|
301
|
+
if (difference === 1) return app.t("yesterday");
|
|
302
|
+
return new Intl.DateTimeFormat(app.intlLocale(), { month: "short", day: "numeric" }).format(date);
|
|
303
|
+
};
|
|
304
|
+
app.flash = (button, key) => {
|
|
305
|
+
button._flashKey = key;
|
|
306
|
+
button.textContent = app.t(key);
|
|
307
|
+
setTimeout(() => {
|
|
308
|
+
if (button._flashKey !== key) return;
|
|
309
|
+
delete button._flashKey;
|
|
310
|
+
button.textContent = app.t(button.dataset.i18n, button._i18nValues || {});
|
|
311
|
+
}, 1200);
|
|
312
|
+
};
|
|
313
|
+
app.updateTitle = () => {
|
|
314
|
+
const title = app.state.room ? app.t("roomTitle", { name: app.state.room.name }) : app.t("documentTitle");
|
|
315
|
+
document.title = app.state.unread ? `(${app.state.unread}) ${title}` : title;
|
|
316
|
+
};
|
|
317
|
+
app.setOnline = (online) => { app.$("#connBar").hidden = online; };
|
|
318
|
+
app.showSendError = (key, values = {}) => {
|
|
319
|
+
app.setText(app.$("#sendError"), key, values);
|
|
320
|
+
app.$("#sendError").hidden = false;
|
|
321
|
+
};
|
|
322
|
+
app.hideSendError = () => { app.$("#sendError").hidden = true; };
|
|
323
|
+
app.showJoinError = (key, values = {}) => {
|
|
324
|
+
app.setText(app.$("#joinError"), key, values);
|
|
325
|
+
app.$("#joinError").hidden = false;
|
|
326
|
+
};
|
|
327
|
+
app.hideJoinError = () => { app.$("#joinError").hidden = true; };
|