sldshr commited on
Commit
c2dc3f3
·
verified ·
1 Parent(s): 964d59d

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +769 -860
index.html CHANGED
@@ -1,887 +1,796 @@
1
  <!DOCTYPE html>
2
  <html lang="ru">
3
  <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Matrix Web Client</title>
7
- <script src="https://cdn.tailwindcss.com"></script>
8
- <style>
9
- body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #1e1e1e; color: #d4d4d4; }
10
- .retro-border { border: 1px solid #4a4a4a; box-shadow: inset 1px 1px 0 #5a5a5a, inset -1px -1px 0 #000; }
11
- .retro-panel { background-color: #2d2d2d; border: 1px solid #111; box-shadow: 1px 1px 3px rgba(0,0,0,0.5); }
12
- .retro-input { background-color: #1e1e1e; border: 1px solid #000; color: #fff; box-shadow: inset 1px 1px 2px rgba(0,0,0,0.8); }
13
- .retro-btn { background: linear-gradient(to bottom, #4a4a4a, #2d2d2d); border: 1px solid #111; color: #fff; box-shadow: inset 1px 1px 0 #6a6a6a; cursor: pointer; text-shadow: 1px 1px 0 #000; transition: all 0.1s; }
14
- .retro-btn:hover { background: linear-gradient(to bottom, #5a5a5a, #3d3d3d); }
15
- .retro-btn:active { background: #2d2d2d; box-shadow: inset 1px 1px 2px #000; }
16
- .scroll-custom::-webkit-scrollbar { width: 8px; }
17
- .scroll-custom::-webkit-scrollbar-track { background: #1e1e1e; border-left: 1px solid #111; }
18
- .scroll-custom::-webkit-scrollbar-thumb { background: #4a4a4a; border: 1px solid #111; }
19
- .room-item:hover { background-color: #3d3d3d; cursor: pointer; }
20
- .room-item.active { background-color: #005a9e; border-color: #0078d7; }
21
- .msg-actions { opacity: 0; transition: opacity 0.2s; }
22
- .group:hover .msg-actions { opacity: 1; }
23
- </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  </head>
25
- <body class="h-screen w-screen overflow-hidden flex items-center justify-center text-sm">
26
-
27
- <div id="toast-container" class="fixed top-4 right-4 z-50 flex flex-col gap-2"></div>
28
-
29
- <div id="login-screen" class="retro-panel w-96 p-6 flex flex-col gap-4">
30
- <div class="text-center mb-4">
31
- <h1 class="text-2xl font-bold text-white mb-1">Matrix Client</h1>
32
- <p class="text-xs text-gray-400">Zero-dependency pure API client</p>
33
- </div>
34
- <div class="flex flex-col gap-1">
35
- <label class="text-xs text-gray-300">Homeserver URL</label>
36
- <input type="text" id="login-server" value="https://matrix.unredacted.org" class="retro-input p-2 rounded-sm outline-none focus:border-blue-500">
37
- </div>
38
- <div class="flex flex-col gap-1">
39
- <label class="text-xs text-gray-300">Username / MXID</label>
40
- <input type="text" id="login-user" placeholder="user (without @server)" class="retro-input p-2 rounded-sm outline-none focus:border-blue-500">
41
- </div>
42
- <div class="flex flex-col gap-1">
43
- <label class="text-xs text-gray-300">Password</label>
44
- <input type="password" id="login-pass" class="retro-input p-2 rounded-sm outline-none focus:border-blue-500">
45
- </div>
46
- <button id="btn-login" class="retro-btn py-2 mt-2 font-bold rounded-sm">Connect</button>
47
  </div>
48
-
49
- <div id="app-screen" class="hidden w-full h-full flex bg-[#1e1e1e]">
50
- <!-- Sidebar -->
51
- <div class="w-72 border-r border-[#111] bg-[#252526] flex flex-col flex-shrink-0">
52
- <!-- Current User Info -->
53
- <div class="p-3 border-b border-[#111] flex items-center justify-between bg-[#2d2d2d] shadow-sm">
54
- <div class="flex items-center gap-2 overflow-hidden cursor-pointer" onclick="openMyProfile()">
55
- <img id="my-avatar" src="https://placehold.co/32x32/1e1e1e/fff?text=?" class="w-8 h-8 rounded-full border border-gray-600 object-cover">
56
- <div class="flex flex-col overflow-hidden">
57
- <span id="my-name" class="font-bold text-white truncate text-xs">...</span>
58
- <span id="my-id" class="text-[10px] text-gray-400 truncate">...</span>
59
- </div>
60
- </div>
61
- <button onclick="logout()" title="Logout" class="retro-btn p-1 px-2 text-xs rounded-sm ml-2">Выход</button>
62
- </div>
63
- <!-- Actions -->
64
- <div class="p-2 grid grid-cols-2 gap-1 border-b border-[#111]">
65
- <button onclick="openModal('create-room-modal')" class="retro-btn py-1 text-xs rounded-sm">Создать</button>
66
- <button onclick="openModal('join-room-modal')" class="retro-btn py-1 text-xs rounded-sm">Войти / DM</button>
67
- </div>
68
- <!-- Room List -->
69
- <div class="flex-1 overflow-y-auto scroll-custom p-1" id="room-list">
70
- <!-- Rooms rendered here -->
71
- </div>
72
- </div>
73
-
74
- <div class="flex-1 flex flex-col min-w-0 bg-[#1e1e1e] relative">
75
- <!-- Room Header -->
76
- <div id="room-header" class="hidden h-14 border-b border-[#111] bg-[#2d2d2d] items-center px-4 justify-between flex-shrink-0">
77
- <div class="flex items-center gap-3 overflow-hidden">
78
- <img id="active-room-avatar" src="https://placehold.co/40x40/1e1e1e/fff?text=?" class="w-10 h-10 rounded-full border border-gray-600 object-cover">
79
- <div class="flex flex-col">
80
- <div class="flex items-center gap-2">
81
- <span id="active-room-name" class="font-bold text-white text-base truncate max-w-md">Select a room</span>
82
- <span id="active-room-enc" class="hidden text-xs bg-red-900 text-red-200 px-1 rounded">E2EE</span>
83
- </div>
84
- <span id="active-room-topic" class="text-xs text-gray-400 truncate max-w-lg"></span>
85
- </div>
86
- </div>
87
- <div class="flex gap-2">
88
- <button onclick="openModal('invite-modal')" class="retro-btn px-3 py-1 text-xs rounded-sm">Пригласить</button>
89
- <button onclick="leaveCurrentRoom()" class="retro-btn px-3 py-1 text-xs rounded-sm text-red-400 border-red-900">Выйти</button>
90
- </div>
91
- </div>
92
-
93
- <!-- Empty State -->
94
- <div id="empty-state" class="flex-1 flex flex-col items-center justify-center text-gray-500">
95
- <div class="text-4xl mb-4">💬</div>
96
- <p>Выберите чат слева или создайте новый</p>
97
- </div>
98
-
99
- <!-- Messages Timeline -->
100
- <div id="chat-timeline" class="hidden flex-1 overflow-y-auto scroll-custom p-4 space-y-3 bg-[#1e1e1e]">
101
- <!-- Messages rendered here -->
102
- </div>
103
-
104
- <!-- Message Input Area -->
105
- <div id="chat-input-area" class="hidden border-t border-[#111] bg-[#2d2d2d] flex-shrink-0 p-3 flex flex-col gap-2">
106
- <!-- Reply Context -->
107
- <div id="reply-context" class="hidden bg-[#1e1e1e] border-l-2 border-blue-500 p-2 text-xs flex justify-between items-center rounded-sm text-gray-300">
108
- <div class="truncate">
109
- <span class="font-bold text-blue-400 mr-2" id="reply-sender">User</span>
110
- <span id="reply-text" class="text-gray-400 truncate">...</span>
111
- </div>
112
- <button onclick="cancelReply()" class="ml-2 text-gray-500 hover:text-white font-bold">×</button>
113
- </div>
114
- <div class="flex gap-2 items-end">
115
- <textarea id="msg-input" rows="2" placeholder="Написать сообщение..." class="flex-1 retro-input p-2 rounded-sm outline-none focus:border-blue-500 resize-none scroll-custom text-sm" onkeydown="handleInputKey(event)"></textarea>
116
- <button onclick="sendCurrentMessage()" class="retro-btn px-4 py-2 h-full rounded-sm font-bold h-[54px]">Отправить</button>
117
- </div>
118
- </div>
119
- </div>
120
  </div>
121
 
122
- <div id="modal-backdrop" class="hidden fixed inset-0 bg-black bg-opacity-70 z-40 flex items-center justify-center backdrop-blur-sm">
123
-
124
- <!-- User Profile Modal -->
125
- <div id="profile-modal" class="hidden retro-panel w-80 p-5 rounded-sm flex flex-col items-center gap-4 relative modal-content">
126
- <button onclick="closeModals()" class="absolute top-2 right-3 text-gray-400 hover:text-white font-bold text-lg">×</button>
127
- <img id="mod-prof-avatar" src="" class="w-24 h-24 rounded-full border-2 border-gray-500 object-cover mt-2">
128
- <div class="text-center w-full">
129
- <h2 id="mod-prof-name" class="text-lg font-bold text-white truncate w-full">Name</h2>
130
- <p id="mod-prof-id" class="text-xs text-gray-400 truncate w-full">@user:server.com</p>
131
- </div>
132
- <div class="flex flex-col gap-2 w-full mt-2">
133
- <button id="btn-prof-copy" class="retro-btn py-2 text-sm rounded-sm">Скопировать ссылку</button>
134
- <button id="btn-prof-dm" class="retro-btn py-2 text-sm rounded-sm text-blue-300">Написать (DM)</button>
135
- </div>
136
- </div>
137
-
138
- <!-- Create Room Modal -->
139
- <div id="create-room-modal" class="hidden retro-panel w-96 p-5 rounded-sm flex flex-col gap-4 relative modal-content">
140
- <button onclick="closeModals()" class="absolute top-2 right-3 text-gray-400 hover:text-white font-bold text-lg">×</button>
141
- <h2 class="text-lg font-bold text-white mb-2">Создать комнату</h2>
142
- <div class="flex flex-col gap-1">
143
- <label class="text-xs text-gray-300">Аватар (файл)</label>
144
- <input type="file" id="create-room-avatar" accept="image/*" class="text-xs retro-input p-1">
145
- </div>
146
- <div class="flex flex-col gap-1">
147
- <label class="text-xs text-gray-300">Название *</label>
148
- <input type="text" id="create-room-name" class="retro-input p-2 rounded-sm text-sm">
149
- </div>
150
- <div class="flex flex-col gap-1">
151
- <label class="text-xs text-gray-300">Тема (Topic)</label>
152
- <input type="text" id="create-room-topic" class="retro-input p-2 rounded-sm text-sm">
153
- </div>
154
- <div class="flex gap-4 mt-2">
155
- <label class="flex items-center gap-1 text-sm text-gray-300 cursor-pointer">
156
- <input type="radio" name="room-vis" value="public" class="accent-blue-500"> Публичная
157
- </label>
158
- <label class="flex items-center gap-1 text-sm text-gray-300 cursor-pointer">
159
- <input type="radio" name="room-vis" value="private" checked class="accent-blue-500"> Приватная
160
- </label>
161
- </div>
162
- <button onclick="submitCreateRoom()" class="retro-btn py-2 mt-2 text-sm font-bold rounded-sm">Создать</button>
163
- </div>
164
-
165
- <!-- Join/DM Modal -->
166
- <div id="join-room-modal" class="hidden retro-panel w-96 p-5 rounded-sm flex flex-col gap-4 relative modal-content">
167
- <button onclick="closeModals()" class="absolute top-2 right-3 text-gray-400 hover:text-white font-bold text-lg">×</button>
168
- <h2 class="text-lg font-bold text-white mb-2">Войти / Написать</h2>
169
- <div class="flex flex-col gap-1">
170
- <label class="text-xs text-gray-300">ID пользователя или Алиас комнаты</label>
171
- <input type="text" id="join-target-id" placeholder="@user:server.com OR #room:server.com" class="retro-input p-2 rounded-sm text-sm">
172
- <p class="text-[10px] text-gray-500 mt-1">Если ввести @user, создастся личный чат (DM). Если #room или !room, будет выполнен вход в комнату.</p>
173
- </div>
174
- <button onclick="submitJoinOrDM()" class="retro-btn py-2 mt-2 text-sm font-bold rounded-sm">Подключиться</button>
175
- </div>
176
-
177
- <!-- Invite Modal -->
178
- <div id="invite-modal" class="hidden retro-panel w-80 p-5 rounded-sm flex flex-col gap-4 relative modal-content">
179
- <button onclick="closeModals()" class="absolute top-2 right-3 text-gray-400 hover:text-white font-bold text-lg">×</button>
180
- <h2 class="text-lg font-bold text-white mb-2">Пригласить</h2>
181
- <div class="flex flex-col gap-1">
182
- <label class="text-xs text-gray-300">ID пользователя</label>
183
- <input type="text" id="invite-target-id" placeholder="@user:server.com" class="retro-input p-2 rounded-sm text-sm">
184
- </div>
185
- <button onclick="submitInvite()" class="retro-btn py-2 mt-2 text-sm font-bold rounded-sm">Отправить приглашение</button>
186
- </div>
187
  </div>
188
-
189
- <script>
190
- // State
191
- const state = {
192
- baseUrl: localStorage.getItem('mx_base_url') || 'https://matrix.unredacted.org',
193
- token: localStorage.getItem('mx_access_token') || '',
194
- userId: localStorage.getItem('mx_user_id') || '',
195
- syncToken: localStorage.getItem('mx_sync_token') || '',
196
- isSyncing: false,
197
- rooms: {}, // Data layer
198
- activeRoomId: null,
199
- replyingTo: null, // { eventId, sender, body }
200
- myProfile: {}
201
- };
202
-
203
- // DOM Elements
204
- const el = {
205
- login: document.getElementById('login-screen'),
206
- app: document.getElementById('app-screen'),
207
- modals: document.getElementById('modal-backdrop'),
208
- roomList: document.getElementById('room-list'),
209
- chatTimeline: document.getElementById('chat-timeline'),
210
- chatInput: document.getElementById('chat-input-area'),
211
- roomHeader: document.getElementById('room-header'),
212
- emptyState: document.getElementById('empty-state'),
213
- toastContainer: document.getElementById('toast-container')
214
- };
215
-
216
- // Utility: Toast notifications
217
- function showToast(msg, isError = false) {
218
- const toast = document.createElement('div');
219
- toast.className = `px-4 py-2 rounded shadow-md text-sm text-white ${isError ? 'bg-red-700' : 'bg-green-700'} border border-${isError ? 'red' : 'green'}-900 opacity-90 transition-opacity`;
220
- toast.innerText = msg;
221
- el.toastContainer.appendChild(toast);
222
- setTimeout(() => {
223
- toast.classList.add('opacity-0');
224
- setTimeout(() => toast.remove(), 300);
225
- }, 3000);
226
- }
227
-
228
- // Utility: Core API fetch wrapper
229
- async function apiCall(endpoint, method = 'GET', body = null, isMediaUpload = false) {
230
- const headers = {};
231
- if (state.token) headers['Authorization'] = `Bearer ${state.token}`;
232
-
233
- if (body && !isMediaUpload) {
234
- headers['Content-Type'] = 'application/json';
235
- body = JSON.stringify(body);
236
- }
237
-
238
- try {
239
- const res = await fetch(`${state.baseUrl}/_matrix/${isMediaUpload ? 'media' : 'client'}/v3${endpoint}`, {
240
- method,
241
- headers,
242
- body
243
- });
244
-
245
- if (res.status === 401) {
246
- logout();
247
- throw new Error("Unauthorized");
248
- }
249
-
250
- const data = await res.json();
251
- if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
252
- return data;
253
- } catch (err) {
254
- console.error("API Error:", err);
255
- throw err;
256
- }
257
- }
258
-
259
- function getMediaUrl(mxcUrl, width=null, height=null) {
260
- if (!mxcUrl) return null;
261
- if (!mxcUrl.startsWith('mxc://')) return mxcUrl; // Might be a standard HTTP url if malformed, but fallback
262
-
263
- const parts = mxcUrl.replace('mxc://', '').split('/');
264
- const serverName = parts[0];
265
- const mediaId = parts[1];
266
-
267
- if (width && height) {
268
- return `${state.baseUrl}/_matrix/media/v3/thumbnail/${serverName}/${mediaId}?width=${width}&height=${height}&method=crop`;
269
- } else {
270
- return `${state.baseUrl}/_matrix/media/v3/download/${serverName}/${mediaId}`;
271
- }
272
- }
273
-
274
- function escapeHtml(unsafe) {
275
- return (unsafe || '').toString()
276
- .replace(/&/g, "&amp;")
277
- .replace(/</g, "&lt;")
278
- .replace(/>/g, "&gt;")
279
- .replace(/"/g, "&quot;")
280
- .replace(/'/g, "&#039;");
281
- }
282
-
283
- document.getElementById('btn-login').onclick = async () => {
284
- const server = document.getElementById('login-server').value.trim();
285
- const user = document.getElementById('login-user').value.trim();
286
- const pass = document.getElementById('login-pass').value;
287
-
288
- if (!server || !user || !pass) {
289
- showToast("Заполните все поля", true);
290
- return;
291
- }
292
-
293
- // Normalize base URL
294
- state.baseUrl = server.replace(/\/$/, "");
295
- if (!state.baseUrl.startsWith('http')) state.baseUrl = 'https://' + state.baseUrl;
296
-
297
- const btn = document.getElementById('btn-login');
298
- btn.innerText = "Подключение...";
299
- btn.disabled = true;
300
-
301
- try {
302
- const data = await apiCall('/login', 'POST', {
303
- type: 'm.login.password',
304
- identifier: { type: 'm.id.user', user: user },
305
- password: pass
306
- });
307
-
308
- state.token = data.access_token;
309
- state.userId = data.user_id;
310
-
311
- localStorage.setItem('mx_base_url', state.baseUrl);
312
- localStorage.setItem('mx_access_token', state.token);
313
- localStorage.setItem('mx_user_id', state.userId);
314
-
315
- showToast("Вход выполнен успешно");
316
- initApp();
317
- } catch (e) {
318
- showToast("Ошибка входа: " + e.message, true);
319
- btn.innerText = "Connect";
320
- btn.disabled = false;
321
- }
322
- };
323
-
324
- function logout() {
325
- localStorage.clear();
326
- location.reload();
327
- }
328
-
329
- async function initApp() {
330
- el.login.classList.add('hidden');
331
- el.app.classList.remove('hidden');
332
-
333
- // Load own profile basic info
334
- try {
335
- const profile = await apiCall(`/profile/${encodeURIComponent(state.userId)}`);
336
- state.myProfile = profile;
337
- document.getElementById('my-name').innerText = profile.displayname || state.userId;
338
- document.getElementById('my-id').innerText = state.userId;
339
- if (profile.avatar_url) {
340
- document.getElementById('my-avatar').src = getMediaUrl(profile.avatar_url, 64, 64);
341
- }
342
- } catch (e) {
343
- document.getElementById('my-name').innerText = state.userId;
344
- }
345
-
346
- // Start Sync Loop
347
- startSync();
348
  }
349
-
350
- async function startSync() {
351
- if (state.isSyncing) return;
352
- state.isSyncing = true;
353
-
354
- while (state.isSyncing) {
355
- try {
356
- let url = `/sync?timeout=30000`;
357
- if (state.syncToken) url += `&since=${state.syncToken}`;
358
-
359
- const data = await apiCall(url);
360
- state.syncToken = data.next_batch;
361
- localStorage.setItem('mx_sync_token', state.syncToken);
362
-
363
- processSyncData(data);
364
- } catch (e) {
365
- if (e.message !== "Unauthorized") {
366
- console.error("Sync error, retrying in 5s...", e);
367
- await new Promise(r => setTimeout(r, 5000));
368
- } else {
369
- break;
370
- }
371
- }
372
- }
373
  }
374
-
375
- function processSyncData(data) {
376
- let roomsUpdated = false;
377
-
378
- // Process Joined Rooms
379
- if (data.rooms && data.rooms.join) {
380
- for (const [roomId, roomData] of Object.entries(data.rooms.join)) {
381
- if (!state.rooms[roomId]) {
382
- state.rooms[roomId] = { id: roomId, name: '', topic: '', avatar: null, members: {}, timeline: [], isEncrypted: false };
383
- roomsUpdated = true;
384
- }
385
- const room = state.rooms[roomId];
386
-
387
- // Helper to process state
388
- const processState = (ev) => {
389
- if (ev.type === 'm.room.name') { room.name = ev.content.name; roomsUpdated = true; }
390
- else if (ev.type === 'm.room.topic') room.topic = ev.content.topic;
391
- else if (ev.type === 'm.room.avatar') { room.avatar = ev.content.url; roomsUpdated = true; }
392
- else if (ev.type === 'm.room.encryption') room.isEncrypted = true;
393
- else if (ev.type === 'm.room.member') {
394
- room.members[ev.state_key] = {
395
- displayname: ev.content.displayname,
396
- avatar_url: ev.content.avatar_url,
397
- membership: ev.content.membership
398
- };
399
- roomsUpdated = true;
400
- }
401
- };
402
-
403
- // State events (current state)
404
- if (roomData.state && roomData.state.events) {
405
- roomData.state.events.forEach(processState);
406
- }
407
-
408
- // Timeline events (messages and inline state changes)
409
- if (roomData.timeline && roomData.timeline.events) {
410
- roomData.timeline.events.forEach(ev => {
411
- if (ev.state_key !== undefined) processState(ev);
412
-
413
- // Check if event already exists to avoid dupes during sync overlap
414
- if (!room.timeline.find(e => e.event_id === ev.event_id)) {
415
- room.timeline.push(ev);
416
- if (state.activeRoomId === roomId) {
417
- appendMessageToUI(ev);
418
- }
419
- }
420
- });
421
- }
422
- }
423
- }
424
-
425
- // Process Invites (Basic auto-accept or UI notice could go here, for simplicity we skip rendering invites separately but user can join manually via ID)
426
-
427
- if (roomsUpdated) renderRoomList();
428
  }
429
-
430
- function getComputedRoomName(room) {
431
- if (room.name) return room.name;
432
- // Fallback to member names
433
- const otherMembers = Object.keys(room.members)
434
- .filter(id => id !== state.userId && room.members[id].membership === 'join')
435
- .map(id => room.members[id].displayname || id);
436
-
437
- if (otherMembers.length > 0) return otherMembers.join(', ');
438
- return "Empty Room";
 
 
 
 
 
 
 
 
 
439
  }
440
-
441
- function renderRoomList() {
442
- el.roomList.innerHTML = '';
443
-
444
- const roomsArray = Object.values(state.rooms).sort((a, b) => {
445
- // Sort by latest activity - simple fallback: just alphabetical for now
446
- const nameA = getComputedRoomName(a).toLowerCase();
447
- const nameB = getComputedRoomName(b).toLowerCase();
448
- return nameA.localeCompare(nameB);
449
- });
450
-
451
- roomsArray.forEach(room => {
452
- const div = document.createElement('div');
453
- const displayName = escapeHtml(getComputedRoomName(room));
454
- const avatarSrc = getMediaUrl(room.avatar, 40, 40) || `https://placehold.co/40x40/2d2d2d/fff?text=${encodeURIComponent(displayName.charAt(0))}`;
455
-
456
- div.className = `room-item p-2 border-b border-[#111] flex items-center gap-3 transition-colors ${state.activeRoomId === room.id ? 'active' : ''}`;
457
- div.onclick = () => switchRoom(room.id);
458
-
459
- div.innerHTML = `
460
- <img src="${avatarSrc}" class="w-8 h-8 rounded-full border border-gray-600 object-cover flex-shrink-0">
461
- <div class="flex flex-col overflow-hidden w-full">
462
- <span class="text-white text-xs font-bold truncate">${displayName}</span>
463
- <span class="text-gray-400 text-[10px] truncate">${room.isEncrypted ? '🔒 Зашифровано' : (room.topic || 'No topic')}</span>
464
- </div>
465
- `;
466
- el.roomList.appendChild(div);
467
- });
468
  }
469
-
470
- function switchRoom(roomId) {
471
- if (!state.rooms[roomId]) return;
472
- state.activeRoomId = roomId;
473
- renderRoomList(); // Update active class
474
-
475
- const room = state.rooms[roomId];
476
- el.emptyState.classList.add('hidden');
477
- el.roomHeader.classList.remove('hidden');
478
- el.chatTimeline.classList.remove('hidden');
479
- el.chatInput.classList.remove('hidden');
480
-
481
- // Header
482
- const displayName = getComputedRoomName(room);
483
- document.getElementById('active-room-name').innerText = displayName;
484
- document.getElementById('active-room-topic').innerText = room.topic || roomId;
485
- document.getElementById('active-room-avatar').src = getMediaUrl(room.avatar, 64, 64) || `https://placehold.co/64x64/2d2d2d/fff?text=${encodeURIComponent(displayName.charAt(0))}`;
486
-
487
- const encBadge = document.getElementById('active-room-enc');
488
- if (room.isEncrypted) encBadge.classList.remove('hidden');
489
- else encBadge.classList.add('hidden');
490
-
491
- // Timeline
492
- el.chatTimeline.innerHTML = '';
493
- room.timeline.forEach(ev => appendMessageToUI(ev, true));
494
- scrollToBottom();
495
- cancelReply(); // Clear any pending reply context
496
- }
497
-
498
- function scrollToBottom() {
499
- setTimeout(() => {
500
- el.chatTimeline.scrollTop = el.chatTimeline.scrollHeight;
501
- }, 50);
502
- }
503
-
504
- function appendMessageToUI(ev, batch = false) {
505
- // Handle Redactions (Deletions)
506
- if (ev.type === 'm.room.redaction') {
507
- const target = document.getElementById(`msg-${ev.redacts}`);
508
- if (target) {
509
- const bodyEl = target.querySelector('.msg-body');
510
- if (bodyEl) bodyEl.innerHTML = '<span class="italic text-gray-500">🚫 Сообщение удалено</span>';
511
- }
512
- return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  }
514
-
515
- if (ev.type !== 'm.room.message' && ev.type !== 'm.room.encrypted') return;
516
-
517
- const room = state.rooms[state.activeRoomId];
518
- const senderInfo = room.members[ev.sender] || {};
519
- const senderName = senderInfo.displayname || ev.sender;
520
- const senderAvatar = getMediaUrl(senderInfo.avatar_url, 32, 32) || `https://placehold.co/32x32/1e1e1e/fff?text=${encodeURIComponent(senderName.charAt(0))}`;
521
- const time = new Date(ev.origin_server_ts).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
522
-
523
- let contentBody = '';
524
- let isMedia = false;
525
- let mediaHtml = '';
526
-
527
- // Check if redacted (sometimes sent within unsigned data)
528
- if (ev.unsigned && ev.unsigned.redacted_because) {
529
- contentBody = '<span class="italic text-gray-500">🚫 Сообщение удалено</span>';
530
- } else if (ev.type === 'm.room.encrypted') {
531
- contentBody = '<span class="italic text-yellow-600">🔒 Сообщение зашифровано (не поддерживается клиентом)</span>';
532
- } else {
533
- if (!ev.content) return;
534
-
535
- // Format reply block if exists
536
- let replyHtml = '';
537
- if (ev.content['m.relates_to'] && ev.content['m.relates_to']['m.in_reply_to']) {
538
- replyHtml = `<div class="text-xs bg-[#252526] border-l-2 border-gray-500 p-1 mb-1 text-gray-400 rounded-sm">В ответ на сообщение</div>`;
539
- }
540
-
541
- if (ev.content.msgtype === 'm.text') {
542
- contentBody = replyHtml + escapeHtml(ev.content.body).replace(/\n/g, '<br>');
543
- } else if (ev.content.msgtype === 'm.image' && ev.content.url) {
544
- isMedia = true;
545
- mediaHtml = `<img src="${getMediaUrl(ev.content.url)}" class="max-w-xs max-h-64 rounded border border-gray-700 mt-1 cursor-pointer" onclick="window.open(this.src)">`;
546
- contentBody = replyHtml + `<span class="text-gray-400 text-xs">${escapeHtml(ev.content.body)}</span>`;
547
- } else {
548
- contentBody = replyHtml + `<span class="italic text-gray-400">Формат [${ev.content.msgtype}] не поддерживается</span>`;
549
- }
550
- }
551
-
552
- const div = document.createElement('div');
553
- div.id = `msg-${ev.event_id}`;
554
- div.className = 'group flex gap-3 hover:bg-[#252526] p-1 rounded transition-colors relative';
555
-
556
- const isMe = ev.sender === state.userId;
557
-
558
- div.innerHTML = `
559
- <img src="${senderAvatar}" class="w-8 h-8 rounded border border-gray-600 object-cover cursor-pointer hover:opacity-80" onclick="openUserProfile('${ev.sender}')" title="Открыть профиль">
560
- <div class="flex flex-col min-w-0 w-full">
561
- <div class="flex items-baseline gap-2">
562
- <span class="font-bold text-sm text-[#569cd6] cursor-pointer hover:underline" onclick="openUserProfile('${ev.sender}')">${escapeHtml(senderName)}</span>
563
- <span class="text-[10px] text-gray-500">${time}</span>
564
- </div>
565
- <div class="msg-body text-gray-300 text-sm break-words">${contentBody}</div>
566
- ${mediaHtml}
567
- </div>
568
- <div class="msg-actions absolute top-2 right-2 flex gap-1 bg-[#1e1e1e] p-1 rounded border border-[#111] shadow">
569
- <button onclick="setupReply('${ev.event_id}', '${escapeHtml(senderName)}', '${escapeHtml(ev.content?.body || 'Медиа')}')" class="text-xs text-gray-400 hover:text-white px-1">Ответить</button>
570
- ${isMe ? `<button onclick="deleteMessage('${ev.event_id}')" class="text-xs text-red-500 hover:text-red-400 px-1 border-l border-gray-700 ml-1">Удалить</button>` : ''}
571
- </div>
572
- `;
573
-
574
- el.chatTimeline.appendChild(div);
575
-
576
- if (!batch) {
577
- const isAtBottom = el.chatTimeline.scrollHeight - el.chatTimeline.scrollTop <= el.chatTimeline.clientHeight + 100;
578
- if (isAtBottom || isMe) scrollToBottom();
579
- }
580
- }
581
-
582
- function setupReply(eventId, sender, body) {
583
- state.replyingTo = { eventId, sender, body };
584
- document.getElementById('reply-context').classList.remove('hidden');
585
- document.getElementById('reply-sender').innerText = sender;
586
- document.getElementById('reply-text').innerText = body.length > 50 ? body.substring(0, 50) + '...' : body;
587
- document.getElementById('msg-input').focus();
588
- }
589
-
590
- function cancelReply() {
591
- state.replyingTo = null;
592
- document.getElementById('reply-context').classList.add('hidden');
593
- }
594
-
595
- function handleInputKey(e) {
596
- if (e.key === 'Enter' && !e.shiftKey) {
597
- e.preventDefault();
598
- sendCurrentMessage();
599
- }
600
- }
601
-
602
- async function sendCurrentMessage() {
603
- if (!state.activeRoomId) return;
604
- const input = document.getElementById('msg-input');
605
- const text = input.value.trim();
606
- if (!text) return;
607
-
608
- input.value = ''; // Fast clear for UX
609
-
610
- const txnId = `m${Date.now()}`;
611
- const content = {
612
- msgtype: 'm.text',
613
- body: text
614
- };
615
-
616
- if (state.replyingTo) {
617
- content['m.relates_to'] = {
618
- 'm.in_reply_to': { event_id: state.replyingTo.eventId }
619
  };
620
- // Adding rich reply fallback for matrix spec
621
- content.format = "org.matrix.custom.html";
622
- content.formatted_body = `<mx-reply><blockquote>In reply to <a href="https://matrix.to/#/${state.activeRoomId}/${state.replyingTo.eventId}">@${state.replyingTo.sender}</a><br>${escapeHtml(state.replyingTo.body)}</blockquote></mx-reply>${escapeHtml(text).replace(/\n/g, '<br>')}`;
623
- content.body = `> <${state.replyingTo.sender}> ${state.replyingTo.body}\n\n${text}`;
624
- cancelReply();
625
- }
626
-
627
- try {
628
- await apiCall(`/rooms/${encodeURIComponent(state.activeRoomId)}/send/m.room.message/${txnId}`, 'PUT', content);
629
- // The message will appear via sync loop shortly
630
- } catch (e) {
631
- showToast("Ошибка отправки: " + e.message, true);
632
- input.value = text; // Restore text
633
- }
634
- }
635
-
636
- async function deleteMessage(eventId) {
637
- if (!state.activeRoomId) return;
638
- const txnId = `t${Date.now()}`;
639
- try {
640
- await apiCall(`/rooms/${encodeURIComponent(state.activeRoomId)}/redact/${eventId}/${txnId}`, 'PUT', {
641
- reason: "User requested deletion"
642
- });
643
- showToast("Сообщение удалено");
644
- // Sync handles UI update
645
- } catch (e) {
646
- showToast("Не удалось удалить: " + e.message, true);
647
- }
648
- }
649
-
650
- function openModal(id) {
651
- el.modals.classList.remove('hidden');
652
- document.querySelectorAll('.modal-content').forEach(m => m.classList.add('hidden'));
653
- document.getElementById(id).classList.remove('hidden');
654
- }
655
-
656
- function closeModals() {
657
- el.modals.classList.add('hidden');
658
- }
659
-
660
- function openMyProfile() {
661
- openUserProfile(state.userId);
662
- }
663
-
664
- async function openUserProfile(userId) {
665
- openModal('profile-modal');
666
- const modName = document.getElementById('mod-prof-name');
667
- const modId = document.getElementById('mod-prof-id');
668
- const modAvatar = document.getElementById('mod-prof-avatar');
669
-
670
- modName.innerText = "Загрузка...";
671
- modId.innerText = userId;
672
- modAvatar.src = `https://placehold.co/128x128/1e1e1e/fff?text=?`;
673
-
674
- try {
675
- const profile = await apiCall(`/profile/${encodeURIComponent(userId)}`);
676
- modName.innerText = profile.displayname || userId;
677
- if (profile.avatar_url) {
678
- modAvatar.src = getMediaUrl(profile.avatar_url, 256, 256);
679
- }
680
- } catch (e) {
681
- modName.innerText = userId;
682
- // Profile might be private or not exist, ignore
683
- }
684
-
685
- document.getElementById('btn-prof-copy').onclick = () => {
686
- const link = `https://matrix.to/#/${userId}`;
687
- // Fallback approach for iframe clipboards
688
- const textArea = document.createElement("textarea");
689
- textArea.value = link;
690
- document.body.appendChild(textArea);
691
- textArea.select();
692
- try {
693
- document.execCommand('copy');
694
- showToast("Ссылка скопирована!");
695
- } catch (err) {
696
- showToast("Не удалось скопировать", true);
697
  }
698
- document.body.removeChild(textArea);
699
- };
700
-
701
- const dmBtn = document.getElementById('btn-prof-dm');
702
- if (userId === state.userId) {
703
- dmBtn.classList.add('hidden');
704
- } else {
705
- dmBtn.classList.remove('hidden');
706
- dmBtn.onclick = () => {
707
- closeModals();
708
- createDirectMessage(userId);
709
- };
710
  }
711
- }
712
-
713
- async function uploadMedia(file) {
714
- const formData = new FormData();
715
- formData.append('file', file);
716
-
717
- try {
718
- const res = await fetch(`${state.baseUrl}/_matrix/media/v3/upload`, {
719
- method: 'POST',
720
- headers: { 'Authorization': `Bearer ${state.token}`, 'Content-Type': file.type },
721
- body: file
722
- });
723
- const data = await res.json();
724
- if (!res.ok) throw new Error(data.error);
725
- return data.content_uri; // returns mxc:// string
726
- } catch (e) {
727
- throw e;
728
- }
729
- }
730
-
731
- async function submitCreateRoom() {
732
- const name = document.getElementById('create-room-name').value.trim();
733
- const topic = document.getElementById('create-room-topic').value.trim();
734
- const visibility = document.querySelector('input[name="room-vis"]:checked').value;
735
- const fileInput = document.getElementById('create-room-avatar');
736
-
737
- if (!name) { showToast("Укажите название", true); return; }
738
-
739
- const payload = {
740
- name: name,
741
- preset: visibility === 'public' ? 'public_chat' : 'private_chat',
742
- initial_state: []
743
- };
744
-
745
- if (topic) payload.topic = topic;
746
-
747
- try {
748
- // Upload avatar if selected
749
- if (fileInput.files.length > 0) {
750
- const mxc = await uploadMedia(fileInput.files[0]);
751
- payload.initial_state.push({
752
- type: 'm.room.avatar',
753
- state_key: '',
754
- content: { url: mxc }
755
- });
756
- }
757
-
758
- const data = await apiCall('/createRoom', 'POST', payload);
759
- showToast("Комната создана");
760
- closeModals();
761
- // Reset inputs
762
- document.getElementById('create-room-name').value = '';
763
- document.getElementById('create-room-topic').value = '';
764
- fileInput.value = '';
765
-
766
- // Automatically switch to it when sync catches up
767
- setTimeout(() => {
768
- if (state.rooms[data.room_id]) switchRoom(data.room_id);
769
- }, 1500);
770
-
771
- } catch (e) {
772
- showToast("Ошибка создания: " + e.message, true);
773
  }
 
 
 
 
 
774
  }
775
 
776
- async function createDirectMessage(targetUserId) {
777
- try {
778
- showToast("Создание чата...");
779
- const data = await apiCall('/createRoom', 'POST', {
780
- preset: 'trusted_private_chat',
781
- is_direct: true,
782
- invite: [targetUserId]
783
- });
784
- showToast("Чат создан");
785
- setTimeout(() => {
786
- if (state.rooms[data.room_id]) switchRoom(data.room_id);
787
- }, 1500);
788
- } catch (e) {
789
- showToast("Ошибка: " + e.message, true);
790
- }
791
  }
792
-
793
- async function submitJoinOrDM() {
794
- const target = document.getElementById('join-target-id').value.trim();
795
- if (!target) return;
796
-
797
- try {
798
- if (target.startsWith('@')) {
799
- // Create DM
800
- await createDirectMessage(target);
801
- closeModals();
802
- } else if (target.startsWith('#') || target.startsWith('!')) {
803
- // Join Room
804
- showToast("Подключение к комнате...");
805
- const data = await apiCall(`/join/${encodeURIComponent(target)}`, 'POST', {});
806
- showToast("Вы вошли в комнату");
807
- closeModals();
808
- setTimeout(() => switchRoom(data.room_id), 1500);
809
- } else {
810
- showToast("Неверный формат. Используйте @user... или #room...", true);
811
- }
812
- } catch (e) {
813
- showToast("Ошибка: " + e.message, true);
814
  }
815
- document.getElementById('join-target-id').value = '';
816
  }
817
-
818
- async function submitInvite() {
819
- if (!state.activeRoomId) return;
820
- const target = document.getElementById('invite-target-id').value.trim();
821
- if (!target) return;
822
-
823
- try {
824
- await apiCall(`/rooms/${encodeURIComponent(state.activeRoomId)}/invite`, 'POST', {
825
- user_id: target
826
- });
827
- showToast(`Приглашение отправлено ${target}`);
828
- closeModals();
829
- document.getElementById('invite-target-id').value = '';
830
- } catch (e) {
831
- showToast("Ошибка: " + e.message, true);
832
- }
833
  }
834
-
835
- async function leaveCurrentRoom() {
836
- if (!state.activeRoomId) return;
837
- // Using basic UI replace instead of window.confirm
838
- const header = document.getElementById('active-room-name');
839
- const originalName = header.innerText;
840
- header.innerText = "Подтвердите выход (кликните снова)";
841
- header.classList.add('text-red-500');
842
-
843
- const btn = el.roomHeader.querySelector('button.text-red-400');
844
- const originalOnclick = btn.onclick;
845
-
846
- btn.onclick = async () => {
847
- try {
848
- await apiCall(`/rooms/${encodeURIComponent(state.activeRoomId)}/leave`, 'POST', {});
849
- showToast("Вы вышли из комнаты");
850
-
851
- // Clear state immediately for UX
852
- delete state.rooms[state.activeRoomId];
853
- state.activeRoomId = null;
854
- renderRoomList();
855
-
856
- el.roomHeader.classList.add('hidden');
857
- el.chatTimeline.classList.add('hidden');
858
- el.chatInput.classList.add('hidden');
859
- el.emptyState.classList.remove('hidden');
860
-
861
- } catch (e) {
862
- showToast("Ошибка: " + e.message, true);
863
- } finally {
864
- btn.onclick = originalOnclick;
865
- header.classList.remove('text-red-500');
866
- }
867
- };
868
-
869
- // Timeout to cancel confirm
870
- setTimeout(() => {
871
- header.innerText = originalName;
872
- header.classList.remove('text-red-500');
873
- btn.onclick = originalOnclick;
874
- }, 3000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
875
  }
876
-
877
- window.onload = () => {
878
- if (state.token && state.userId) {
879
- initApp();
880
- } else {
881
- el.login.classList.remove('hidden');
882
- }
883
- };
884
-
885
- </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886
  </body>
887
  </html>
 
1
  <!DOCTYPE html>
2
  <html lang="ru">
3
  <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Matrix клиент (unredacted.org)</title>
7
+ <style>
8
+ /* ----- Общие стили ----- */
9
+ * {
10
+ margin: 0;
11
+ padding: 0;
12
+ box-sizing: border-box;
13
+ }
14
+ body {
15
+ font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
16
+ background: #1a1a1e;
17
+ color: #e4e4e7;
18
+ height: 100vh;
19
+ display: flex;
20
+ flex-direction: column;
21
+ }
22
+ button {
23
+ background: #2c2c32;
24
+ color: #e4e4e7;
25
+ border: 1px solid #3f3f46;
26
+ padding: 0.5rem 1rem;
27
+ border-radius: 6px;
28
+ cursor: pointer;
29
+ font-size: 0.9rem;
30
+ transition: background 0.2s;
31
+ }
32
+ button:hover {
33
+ background: #3f3f46;
34
+ }
35
+ input,
36
+ textarea {
37
+ background: #2c2c32;
38
+ color: #e4e4e7;
39
+ border: 1px solid #3f3f46;
40
+ padding: 0.5rem;
41
+ border-radius: 6px;
42
+ font-size: 0.9rem;
43
+ width: 100%;
44
+ outline: none;
45
+ }
46
+ input:focus,
47
+ textarea:focus {
48
+ border-color: #6b6b7a;
49
+ }
50
+ .hidden {
51
+ display: none !important;
52
+ }
53
+ .flex-row {
54
+ display: flex;
55
+ gap: 0.5rem;
56
+ align-items: center;
57
+ }
58
+ .flex-col {
59
+ display: flex;
60
+ flex-direction: column;
61
+ gap: 0.5rem;
62
+ }
63
+
64
+ /* ----- Экран входа ----- */
65
+ #login-screen {
66
+ max-width: 400px;
67
+ margin: 5rem auto;
68
+ padding: 2rem;
69
+ background: #24242a;
70
+ border-radius: 12px;
71
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
72
+ }
73
+ #login-screen h1 {
74
+ font-size: 1.8rem;
75
+ margin-bottom: 1.5rem;
76
+ text-align: center;
77
+ font-weight: 500;
78
+ letter-spacing: -0.5px;
79
+ }
80
+ #login-screen .field {
81
+ margin-bottom: 1rem;
82
+ }
83
+ #login-screen .field label {
84
+ display: block;
85
+ font-size: 0.85rem;
86
+ color: #a1a1aa;
87
+ margin-bottom: 0.25rem;
88
+ }
89
+ #login-status {
90
+ margin-top: 1rem;
91
+ color: #f87171;
92
+ font-size: 0.9rem;
93
+ text-align: center;
94
+ min-height: 1.5rem;
95
+ }
96
+
97
+ /* ----- Основной интерфейс ----- */
98
+ #app {
99
+ display: none;
100
+ height: 100vh;
101
+ flex-direction: row;
102
+ }
103
+ #app.active {
104
+ display: flex;
105
+ }
106
+
107
+ /* ----- Боковая панель (комнаты) ----- */
108
+ #sidebar {
109
+ width: 280px;
110
+ min-width: 200px;
111
+ background: #1f1f23;
112
+ border-right: 1px solid #2d2d33;
113
+ display: flex;
114
+ flex-direction: column;
115
+ height: 100vh;
116
+ overflow: hidden;
117
+ }
118
+ #sidebar-header {
119
+ padding: 1rem;
120
+ border-bottom: 1px solid #2d2d33;
121
+ display: flex;
122
+ justify-content: space-between;
123
+ align-items: center;
124
+ flex-shrink: 0;
125
+ }
126
+ #sidebar-header .user {
127
+ font-size: 0.85rem;
128
+ color: #a1a1aa;
129
+ overflow: hidden;
130
+ text-overflow: ellipsis;
131
+ white-space: nowrap;
132
+ max-width: 140px;
133
+ }
134
+ #sidebar-header button {
135
+ padding: 0.25rem 0.75rem;
136
+ font-size: 0.8rem;
137
+ }
138
+ #room-list {
139
+ flex: 1;
140
+ overflow-y: auto;
141
+ padding: 0.5rem 0;
142
+ }
143
+ .room-item {
144
+ padding: 0.6rem 1rem;
145
+ cursor: pointer;
146
+ border-left: 3px solid transparent;
147
+ transition: background 0.15s;
148
+ display: flex;
149
+ align-items: center;
150
+ gap: 0.5rem;
151
+ font-size: 0.95rem;
152
+ }
153
+ .room-item:hover {
154
+ background: #2c2c32;
155
+ }
156
+ .room-item.active {
157
+ background: #2c2c32;
158
+ border-left-color: #818cf8;
159
+ }
160
+ .room-item .name {
161
+ flex: 1;
162
+ overflow: hidden;
163
+ text-overflow: ellipsis;
164
+ white-space: nowrap;
165
+ }
166
+ .room-item .badge {
167
+ background: #818cf8;
168
+ color: #fff;
169
+ border-radius: 12px;
170
+ padding: 0 0.6rem;
171
+ font-size: 0.7rem;
172
+ line-height: 1.4rem;
173
+ font-weight: 600;
174
+ }
175
+
176
+ /* ----- Область чата ----- */
177
+ #chat {
178
+ flex: 1;
179
+ display: flex;
180
+ flex-direction: column;
181
+ height: 100vh;
182
+ background: #18181b;
183
+ min-width: 0;
184
+ }
185
+ #chat-header {
186
+ padding: 0.8rem 1.5rem;
187
+ border-bottom: 1px solid #2d2d33;
188
+ flex-shrink: 0;
189
+ background: #1f1f23;
190
+ }
191
+ #chat-header .room-name {
192
+ font-size: 1.1rem;
193
+ font-weight: 500;
194
+ }
195
+ #chat-header .room-topic {
196
+ font-size: 0.85rem;
197
+ color: #a1a1aa;
198
+ margin-top: 0.1rem;
199
+ }
200
+
201
+ #messages {
202
+ flex: 1;
203
+ overflow-y: auto;
204
+ padding: 1rem 1.5rem;
205
+ display: flex;
206
+ flex-direction: column;
207
+ gap: 0.4rem;
208
+ background: #18181b;
209
+ }
210
+ .msg {
211
+ display: flex;
212
+ flex-direction: column;
213
+ padding: 0.3rem 0.6rem;
214
+ border-radius: 6px;
215
+ max-width: 80%;
216
+ word-wrap: break-word;
217
+ line-height: 1.4;
218
+ }
219
+ .msg.self {
220
+ align-self: flex-end;
221
+ background: #2c2c3a;
222
+ }
223
+ .msg.other {
224
+ align-self: flex-start;
225
+ background: #24242a;
226
+ }
227
+ .msg .sender {
228
+ font-size: 0.75rem;
229
+ color: #a1a1aa;
230
+ margin-bottom: 0.1rem;
231
+ }
232
+ .msg .body {
233
+ font-size: 0.95rem;
234
+ }
235
+ .msg .time {
236
+ font-size: 0.65rem;
237
+ color: #6b6b7a;
238
+ align-self: flex-end;
239
+ margin-top: 0.1rem;
240
+ }
241
+ .msg .event-id {
242
+ font-size: 0.6rem;
243
+ color: #4b4b5a;
244
+ word-break: break-all;
245
+ }
246
+
247
+ #compose {
248
+ padding: 0.8rem 1.5rem;
249
+ border-top: 1px solid #2d2d33;
250
+ flex-shrink: 0;
251
+ background: #1f1f23;
252
+ display: flex;
253
+ gap: 0.5rem;
254
+ align-items: flex-end;
255
+ }
256
+ #compose textarea {
257
+ resize: none;
258
+ height: 44px;
259
+ max-height: 120px;
260
+ padding: 0.6rem;
261
+ flex: 1;
262
+ }
263
+ #compose button {
264
+ height: 44px;
265
+ padding: 0 1.2rem;
266
+ flex-shrink: 0;
267
+ background: #818cf8;
268
+ border-color: #818cf8;
269
+ color: #fff;
270
+ font-weight: 500;
271
+ }
272
+ #compose button:hover {
273
+ background: #6b74d6;
274
+ border-color: #6b74d6;
275
+ }
276
+
277
+ /* ----- Скролл ----- */
278
+ ::-webkit-scrollbar {
279
+ width: 6px;
280
+ }
281
+ ::-webkit-scrollbar-track {
282
+ background: #1a1a1e;
283
+ }
284
+ ::-webkit-scrollbar-thumb {
285
+ background: #3f3f46;
286
+ border-radius: 4px;
287
+ }
288
+ ::-webkit-scrollbar-thumb:hover {
289
+ background: #52525b;
290
+ }
291
+
292
+ /* Адаптив */
293
+ @media (max-width: 640px) {
294
+ #sidebar {
295
+ width: 200px;
296
+ min-width: 140px;
297
+ }
298
+ #sidebar-header .user {
299
+ max-width: 80px;
300
+ }
301
+ #messages {
302
+ padding: 0.5rem;
303
+ }
304
+ .msg {
305
+ max-width: 95%;
306
+ }
307
+ }
308
+ </style>
309
  </head>
310
+ <body>
311
+
312
+ <!-- ===== ЭКРАН ВХОДА ===== -->
313
+ <div id="login-screen">
314
+ <h1>🧩 Matrix</h1>
315
+ <form id="login-form" class="flex-col">
316
+ <div class="field">
317
+ <label for="user">Имя пользователя (@user:server)</label>
318
+ <input type="text" id="user" placeholder="@alice:matrix.unredacted.org" />
319
+ </div>
320
+ <div class="field">
321
+ <label for="pass">Пароль</label>
322
+ <input type="password" id="pass" placeholder="••••••••" />
323
+ </div>
324
+ <button type="submit" style="width:100%; margin-top:0.5rem;">Войти</button>
325
+ <div id="login-status"></div>
326
+ </form>
327
+ <div style="margin-top:1rem; font-size:0.8rem; color:#6b6b7a; text-align:center;">
328
+ Сервер: matrix.unredacted.org
 
 
 
329
  </div>
330
+ </div>
331
+
332
+ <!-- ===== ОСНОВНОЙ ИНТЕРФЕЙС ===== -->
333
+ <div id="app">
334
+ <!-- Боковая панель -->
335
+ <div id="sidebar">
336
+ <div id="sidebar-header">
337
+ <span class="user" id="current-user">@user</span>
338
+ <button id="logout-btn" title="Выйти">🚪</button>
339
+ </div>
340
+ <div id="room-list"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  </div>
342
 
343
+ <!-- Чат -->
344
+ <div id="chat">
345
+ <div id="chat-header">
346
+ <div class="room-name" id="room-name">Выберите комнату</div>
347
+ <div class="room-topic" id="room-topic"></div>
348
+ </div>
349
+ <div id="messages"></div>
350
+ <div id="compose">
351
+ <textarea id="msg-input" placeholder="Введите сообщение…" rows="1"></textarea>
352
+ <button id="send-btn">Отправить</button>
353
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  </div>
355
+ </div>
356
+
357
+ <script>
358
+ // ============================================================
359
+ // Matrix клиент (matrix.unredacted.org)
360
+ // Использует Client-Server API v3
361
+ // ============================================================
362
+
363
+ const HS_URL = 'https://matrix.unredacted.org';
364
+
365
+ // ----- Состояние -----
366
+ let accessToken = null;
367
+ let userId = null;
368
+ let deviceId = null;
369
+
370
+ let rooms = {}; // roomId -> { name, topic, timeline: [msg], unread }
371
+ let currentRoomId = null;
372
+ let syncFilter = null;
373
+ let syncSince = null;
374
+ let syncTimeout = null;
375
+ let isSyncing = false;
376
+
377
+ // DOM ссылки
378
+ const loginScreen = document.getElementById('login-screen');
379
+ const app = document.getElementById('app');
380
+ const loginForm = document.getElementById('login-form');
381
+ const loginStatus = document.getElementById('login-status');
382
+ const userInput = document.getElementById('user');
383
+ const passInput = document.getElementById('pass');
384
+
385
+ const roomList = document.getElementById('room-list');
386
+ const messagesContainer = document.getElementById('messages');
387
+ const roomNameEl = document.getElementById('room-name');
388
+ const roomTopicEl = document.getElementById('room-topic');
389
+ const msgInput = document.getElementById('msg-input');
390
+ const sendBtn = document.getElementById('send-btn');
391
+ const logoutBtn = document.getElementById('logout-btn');
392
+ const currentUserEl = document.getElementById('current-user');
393
+
394
+ // ----- Вспомогательные функции -----
395
+ function escapeHtml(text) {
396
+ if (!text) return '';
397
+ const div = document.createElement('div');
398
+ div.textContent = text;
399
+ return div.innerHTML;
400
+ }
401
+
402
+ function formatTime(ts) {
403
+ if (!ts) return '';
404
+ const d = new Date(ts);
405
+ return d.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
406
+ }
407
+
408
+ function getRoomDisplayName(roomId, name) {
409
+ return name && name.trim() ? name.trim() : roomId;
410
+ }
411
+
412
+ // ----- API запросы -----
413
+ async function matrixRequest(endpoint, method = 'GET', body = null, token = null) {
414
+ const url = HS_URL + endpoint;
415
+ const headers = {
416
+ 'Content-Type': 'application/json',
417
+ 'Accept': 'application/json',
418
+ };
419
+ if (token) {
420
+ headers['Authorization'] = 'Bearer ' + token;
421
+ }
422
+ const opts = {
423
+ method,
424
+ headers,
425
+ };
426
+ if (body) {
427
+ opts.body = JSON.stringify(body);
428
+ }
429
+ const resp = await fetch(url, opts);
430
+ if (!resp.ok) {
431
+ let errMsg = `${resp.status} ${resp.statusText}`;
432
+ try {
433
+ const data = await resp.json();
434
+ if (data.error) errMsg = data.error;
435
+ } catch (_) { /* ignore */ }
436
+ throw new Error(errMsg);
437
+ }
438
+ if (resp.status === 204) return null;
439
+ return resp.json();
440
+ }
441
+
442
+ // ----- Логин -----
443
+ async function doLogin(user, password) {
444
+ try {
445
+ const data = await matrixRequest('/_matrix/client/v3/login', 'POST', {
446
+ type: 'm.login.password',
447
+ identifier: { type: 'm.id.user', user },
448
+ password,
449
+ initial_device_display_name: 'Web Client (unredacted)',
450
+ });
451
+ accessToken = data.access_token;
452
+ userId = data.user_id;
453
+ deviceId = data.device_id;
454
+ return true;
455
+ } catch (err) {
456
+ loginStatus.textContent = 'Ошибка: ' + err.message;
457
+ return false;
458
+ }
459
+ }
460
+
461
+ // ----- Загрузка комнат -----
462
+ async function fetchJoinedRooms() {
463
+ const data = await matrixRequest('/_matrix/client/v3/joined_rooms', 'GET', null, accessToken);
464
+ const roomIds = data.joined_rooms || [];
465
+ // Получаем информацию о каждой комнате (state)
466
+ for (const id of roomIds) {
467
+ await fetchRoomState(id);
468
+ }
469
+ return roomIds;
470
+ }
471
+
472
+ async function fetchRoomState(roomId) {
473
+ try {
474
+ const state = await matrixRequest(`/_matrix/client/v3/rooms/${roomId}/state`, 'GET', null, accessToken);
475
+ let name = roomId;
476
+ let topic = '';
477
+ for (const ev of state) {
478
+ if (ev.type === 'm.room.name') name = ev.content.name || roomId;
479
+ if (ev.type === 'm.room.topic') topic = ev.content.topic || '';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  }
481
+ if (!rooms[roomId]) {
482
+ rooms[roomId] = { name, topic, timeline: [], unread: 0 };
483
+ } else {
484
+ rooms[roomId].name = name;
485
+ rooms[roomId].topic = topic;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
  }
487
+ // Загружаем последние 20 сообщений
488
+ await fetchRoomMessages(roomId, 20);
489
+ } catch (err) {
490
+ console.warn('Не удалось получить state для', roomId, err);
491
+ if (!rooms[roomId]) {
492
+ rooms[roomId] = { name: roomId, topic: '', timeline: [], unread: 0 };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  }
494
+ }
495
+ }
496
+
497
+ async function fetchRoomMessages(roomId, limit = 20) {
498
+ try {
499
+ const data = await matrixRequest(
500
+ `/_matrix/client/v3/rooms/${roomId}/messages?dir=b&limit=${limit}&filter={"types":["m.room.message"]}`,
501
+ 'GET', null, accessToken
502
+ );
503
+ const events = data.chunk || [];
504
+ const timeline = events.reverse().map(ev => ({
505
+ eventId: ev.event_id,
506
+ sender: ev.sender,
507
+ body: ev.content?.body || '',
508
+ ts: ev.origin_server_ts,
509
+ type: ev.type,
510
+ }));
511
+ if (rooms[roomId]) {
512
+ rooms[roomId].timeline = timeline;
513
  }
514
+ } catch (err) {
515
+ console.warn('Не удалось загрузить сообщения для', roomId, err);
516
+ if (rooms[roomId] && !rooms[roomId].timeline) {
517
+ rooms[roomId].timeline = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  }
519
+ }
520
+ }
521
+
522
+ // ----- Отправка сообщения -----
523
+ async function sendMessage(roomId, text) {
524
+ if (!text.trim()) return;
525
+ const txnId = Date.now() + '-' + Math.random().toString(36).slice(2, 8);
526
+ const body = {
527
+ msgtype: 'm.text',
528
+ body: text.trim(),
529
+ };
530
+ try {
531
+ await matrixRequest(
532
+ `/_matrix/client/v3/rooms/${roomId}/send/m.room.message/${txnId}`,
533
+ 'PUT', body, accessToken
534
+ );
535
+ // Сообщение появится в синке
536
+ } catch (err) {
537
+ alert('Не удалось отправить: ' + err.message);
538
+ }
539
+ }
540
+
541
+ // ----- Синхронизация (long-polling) -----
542
+ async function startSync() {
543
+ if (isSyncing) return;
544
+ isSyncing = true;
545
+ try {
546
+ await doSync();
547
+ } catch (err) {
548
+ console.error('Sync error:', err);
549
+ // Продолжим через секунду
550
+ setTimeout(() => { isSyncing = false;
551
+ startSync(); }, 1000);
552
+ } finally {
553
+ isSyncing = false;
554
+ }
555
+ }
556
+
557
+ async function doSync() {
558
+ let url = '/_matrix/client/v3/sync?timeout=30000';
559
+ if (syncSince) url += '&since=' + encodeURIComponent(syncSince);
560
+ if (syncFilter) url += '&filter=' + encodeURIComponent(syncFilter);
561
+ try {
562
+ const data = await matrixRequest(url, 'GET', null, accessToken);
563
+ syncSince = data.next_batch || syncSince;
564
+
565
+ // Обрабатываем комнаты
566
+ const roomsData = data.rooms || {};
567
+ const join = roomsData.join || {};
568
+
569
+ for (const [roomId, roomData] of Object.entries(join)) {
570
+ if (!rooms[roomId]) {
571
+ rooms[roomId] = { name: roomId, topic: '', timeline: [], unread: 0 };
572
+ }
573
+ // Обновляем state если есть
574
+ if (roomData.state) {
575
+ const events = roomData.state.events || [];
576
+ for (const ev of events) {
577
+ if (ev.type === 'm.room.name') {
578
+ rooms[roomId].name = ev.content.name || roomId;
579
+ }
580
+ if (ev.type === 'm.room.topic') {
581
+ rooms[roomId].topic = ev.content.topic || '';
582
+ }
583
  }
584
+ }
585
+ // Добавляем новые сообщения
586
+ if (roomData.timeline) {
587
+ const events = roomData.timeline.events || [];
588
+ let newMsgs = 0;
589
+ for (const ev of events) {
590
+ if (ev.type === 'm.room.message') {
591
+ const msg = {
592
+ eventId: ev.event_id,
593
+ sender: ev.sender,
594
+ body: ev.content?.body || '',
595
+ ts: ev.origin_server_ts,
596
+ type: ev.type,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  };
598
+ // Избегаем дубликатов по event_id
599
+ if (!rooms[roomId].timeline.some(m => m.eventId === msg.eventId)) {
600
+ rooms[roomId].timeline.push(msg);
601
+ newMsgs++;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602
  }
603
+ }
 
 
 
 
 
 
 
 
 
 
 
604
  }
605
+ if (newMsgs > 0 && roomId !== currentRoomId) {
606
+ rooms[roomId].unread = (rooms[roomId].unread || 0) + newMsgs;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  }
608
+ }
609
+ // Обновляем unread (если есть)
610
+ if (roomData.unread_notifications) {
611
+ rooms[roomId].unread = roomData.unread_notifications.highlight_count || 0;
612
+ }
613
  }
614
 
615
+ // Обновляем UI
616
+ renderRoomList();
617
+ if (currentRoomId && rooms[currentRoomId]) {
618
+ renderMessages(currentRoomId);
 
 
 
 
 
 
 
 
 
 
 
619
  }
620
+ // Запускаем следующий синк
621
+ if (accessToken) {
622
+ // Небольшая задержка перед следующим вызовом
623
+ setTimeout(() => {
624
+ if (accessToken && !isSyncing) {
625
+ doSync().catch(() => {});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
626
  }
627
+ }, 100);
628
  }
629
+ } catch (err) {
630
+ if (err.message.includes('401') || err.message.includes('403')) {
631
+ // Сессия истекла
632
+ alert('Сессия истекла. Войдите снова.');
633
+ logout();
634
+ return;
 
 
 
 
 
 
 
 
 
 
635
  }
636
+ throw err;
637
+ }
638
+ }
639
+
640
+ // ----- Рендеринг -----
641
+ function renderRoomList() {
642
+ const ids = Object.keys(rooms);
643
+ if (ids.length === 0) {
644
+ roomList.innerHTML = '<div style="padding:1rem;color:#6b6b7a;">Нет комнат</div>';
645
+ return;
646
+ }
647
+ let html = '';
648
+ for (const id of ids) {
649
+ const r = rooms[id];
650
+ const name = getRoomDisplayName(id, r.name);
651
+ const active = (id === currentRoomId) ? 'active' : '';
652
+ const unread = (r.unread && r.unread > 0) ? `<span class="badge">${r.unread}</span>` : '';
653
+ html += `<div class="room-item ${active}" data-room-id="${id}">
654
+ <span class="name">${escapeHtml(name)}</span>
655
+ ${unread}
656
+ </div>`;
657
+ }
658
+ roomList.innerHTML = html;
659
+ // Обработчики кликов
660
+ document.querySelectorAll('.room-item').forEach(el => {
661
+ el.addEventListener('click', () => {
662
+ const id = el.dataset.roomId;
663
+ if (id && rooms[id]) {
664
+ selectRoom(id);
665
+ }
666
+ });
667
+ });
668
+ }
669
+
670
+ function renderMessages(roomId) {
671
+ const r = rooms[roomId];
672
+ if (!r) return;
673
+ // Очищаем unread для этой комнаты
674
+ r.unread = 0;
675
+ renderRoomList();
676
+
677
+ messagesContainer.innerHTML = '';
678
+ const timeline = r.timeline || [];
679
+ for (const msg of timeline) {
680
+ const isSelf = (msg.sender === userId);
681
+ const div = document.createElement('div');
682
+ div.className = `msg ${isSelf ? 'self' : 'other'}`;
683
+ const senderName = msg.sender ? msg.sender.split(':')[0].replace('@', '') : 'unknown';
684
+ div.innerHTML = `
685
+ <div class="sender">${escapeHtml(senderName)}</div>
686
+ <div class="body">${escapeHtml(msg.body)}</div>
687
+ <div class="time">${formatTime(msg.ts)}</div>
688
+ <div class="event-id">${msg.eventId ? escapeHtml(msg.eventId.slice(0,8)) : ''}</div>
689
+ `;
690
+ messagesContainer.appendChild(div);
691
+ }
692
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
693
+ }
694
+
695
+ function selectRoom(roomId) {
696
+ currentRoomId = roomId;
697
+ const r = rooms[roomId];
698
+ if (r) {
699
+ roomNameEl.textContent = getRoomDisplayName(roomId, r.name);
700
+ roomTopicEl.textContent = r.topic || '';
701
+ renderMessages(roomId);
702
+ renderRoomList();
703
+ // Если нужно, подгружаем больше сообщений (лениво)
704
+ }
705
+ }
706
+
707
+ // ----- Выход -----
708
+ function logout() {
709
+ accessToken = null;
710
+ userId = null;
711
+ deviceId = null;
712
+ syncSince = null;
713
+ rooms = {};
714
+ currentRoomId = null;
715
+ isSyncing = false;
716
+ if (syncTimeout) {
717
+ clearTimeout(syncTimeout);
718
+ syncTimeout = null;
719
+ }
720
+ loginScreen.style.display = 'block';
721
+ app.classList.remove('active');
722
+ loginStatus.textContent = '';
723
+ userInput.value = '';
724
+ passInput.value = '';
725
+ roomList.innerHTML = '';
726
+ messagesContainer.innerHTML = '';
727
+ roomNameEl.textContent = 'Выберите комнату';
728
+ roomTopicEl.textContent = '';
729
+ }
730
+
731
+ // ----- Обработчики UI -----
732
+ loginForm.addEventListener('submit', async (e) => {
733
+ e.preventDefault();
734
+ const user = userInput.value.trim();
735
+ const pass = passInput.value;
736
+ if (!user || !pass) {
737
+ loginStatus.textContent = 'Заполните все поля';
738
+ return;
739
+ }
740
+ loginStatus.textContent = 'Вход…';
741
+ const ok = await doLogin(user, pass);
742
+ if (ok) {
743
+ loginScreen.style.display = 'none';
744
+ app.classList.add('active');
745
+ currentUserEl.textContent = userId;
746
+ // Загружаем комнаты
747
+ try {
748
+ await fetchJoinedRooms();
749
+ renderRoomList();
750
+ // Если есть комнаты, выбираем первую
751
+ const ids = Object.keys(rooms);
752
+ if (ids.length > 0) {
753
+ selectRoom(ids[0]);
754
+ }
755
+ // Запускаем синк
756
+ startSync();
757
+ } catch (err) {
758
+ alert('Ошибка загрузки комнат: ' + err.message);
759
+ logout();
760
  }
761
+ }
762
+ });
763
+
764
+ sendBtn.addEventListener('click', () => {
765
+ if (!currentRoomId) {
766
+ alert('Выберите комнату');
767
+ return;
768
+ }
769
+ const text = msgInput.value;
770
+ if (!text.trim()) return;
771
+ sendMessage(currentRoomId, text);
772
+ msgInput.value = '';
773
+ msgInput.focus();
774
+ });
775
+
776
+ msgInput.addEventListener('keydown', (e) => {
777
+ if (e.key === 'Enter' && !e.shiftKey) {
778
+ e.preventDefault();
779
+ sendBtn.click();
780
+ }
781
+ });
782
+
783
+ logoutBtn.addEventListener('click', logout);
784
+
785
+ // Обработчик потери фокуса для автоматического расширения textarea
786
+ msgInput.addEventListener('input', () => {
787
+ msgInput.style.height = '44px';
788
+ msgInput.style.height = Math.min(msgInput.scrollHeight, 120) + 'px';
789
+ });
790
+
791
+ // Инициализация: если уже есть токен (на случай перезагрузки) - но мы не храним, просим логин.
792
+ // Можно было бы сохранять в sessionStorage, но для простоты оставим так.
793
+ console.log('Matrix клиент готов (unredacted.org)');
794
+ </script>
795
  </body>
796
  </html>