sldshr commited on
Commit
d146e3e
·
verified ·
1 Parent(s): 12eab8a

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +795 -23
index.html CHANGED
@@ -1,24 +1,796 @@
1
  <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <link rel="stylesheet" type="text/css" media="(prefers-color-scheme: dark)" href="./assets/theme-element-dark.a6fddb2f.css" class="theme">
5
- <link rel="stylesheet" type="text/css" media="(prefers-color-scheme: light)" href="./assets/theme-element-light.78427b5a.css" class="theme">
6
-
7
- <meta charset="utf-8">
8
- <title>Hydrogen Chat</title>
9
- <meta name="viewport" content="width=device-width, user-scalable=no">
10
- <meta name="application-name" content="Hydrogen Chat"/>
11
- <meta name="apple-mobile-web-app-capable" content="yes">
12
- <meta name="apple-mobile-web-app-status-bar-style" content="black">
13
- <meta name="apple-mobile-web-app-title" content="Hydrogen Chat">
14
- <meta name="description" content="A matrix chat application">
15
- <link rel="apple-touch-icon" href="./assets/icon-maskable.965d12c4.png">
16
- <link rel="icon" type="image/png" href="./assets/icon-maskable.965d12c4.png">
17
-
18
- <script type="module" crossorigin src="./assets/index.e65aa065.js"></script>
19
- <link rel="manifest" href="./assets/manifest.1f23c85b.json">
20
- </head>
21
- <body class="hydrogen">
22
-
23
- </body>
24
- </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>