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

Upload 4 files

Browse files
Files changed (4) hide show
  1. index.html +175 -795
  2. js/app.js +1299 -0
  3. js/matrix-service.js +574 -0
  4. styles.css +1148 -0
index.html CHANGED
@@ -1,796 +1,176 @@
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>
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
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
+ <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='7' fill='%230dbd8b'/><text x='16' y='23' font-family='Arial' font-size='20' font-weight='bold' text-anchor='middle' fill='white'>M</text></svg>">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
11
+ <link rel="stylesheet" href="styles.css">
12
+ </head>
13
+ <body>
14
+
15
+ <!-- ===================== LOGIN VIEW ===================== -->
16
+ <div id="login-view" class="login-view">
17
+ <div class="login-card">
18
+ <div class="login-logo">M</div>
19
+ <h1>Matrix Web Client</h1>
20
+ <p class="login-subtitle">Connect to your Matrix homeserver</p>
21
+
22
+ <div class="login-tabs">
23
+ <button type="button" class="tab-btn active" data-tab="password">Password</button>
24
+ <button type="button" class="tab-btn" data-tab="token">Access Token</button>
25
+ </div>
26
+
27
+ <form id="login-password-form" class="login-form">
28
+ <label for="homeserver-input">Homeserver URL</label>
29
+ <input type="url" id="homeserver-input" placeholder="https://matrix.org" spellcheck="false" required>
30
+
31
+ <label for="username-input">Username</label>
32
+ <input type="text" id="username-input" placeholder="@user:server.com" autocomplete="username" spellcheck="false" required>
33
+
34
+ <label for="password-input">Password</label>
35
+ <input type="password" id="password-input" placeholder="••••••••" autocomplete="current-password" required>
36
+
37
+ <button type="submit" class="btn-primary" id="login-password-submit">Sign In</button>
38
+ </form>
39
+
40
+ <form id="login-token-form" class="login-form hidden">
41
+ <label for="token-homeserver-input">Homeserver URL</label>
42
+ <input type="url" id="token-homeserver-input" placeholder="https://matrix.org" spellcheck="false" required>
43
+
44
+ <label for="token-user-input">User ID</label>
45
+ <input type="text" id="token-user-input" placeholder="@user:server.com" spellcheck="false" required>
46
+
47
+ <label for="token-input">Access Token</label>
48
+ <input type="password" id="token-input" placeholder="syt_..." autocomplete="off" required>
49
+
50
+ <button type="submit" class="btn-primary" id="login-token-submit">Sign In</button>
51
+ </form>
52
+
53
+ <div id="login-error" class="login-error hidden"></div>
54
+
55
+ <p class="login-hint">
56
+ Your credentials are sent directly to your homeserver over HTTPS.
57
+ This client does <strong>not</strong> support end-to-end encryption —
58
+ use <a href="https://element.io" target="_blank" rel="noopener">Element</a>
59
+ for encrypted rooms.
60
+ </p>
61
+ </div>
62
+ </div>
63
+
64
+ <!-- ===================== APP VIEW ===================== -->
65
+ <div id="app-view" class="app-view hidden">
66
+
67
+ <!-- Sidebar -->
68
+ <aside class="sidebar">
69
+ <div class="sidebar-user">
70
+ <div class="avatar" id="user-avatar"></div>
71
+ <div class="user-info">
72
+ <div class="user-name" id="user-name"></div>
73
+ <div class="user-id" id="user-id"></div>
74
+ </div>
75
+ <button class="icon-btn" id="logout-btn" title="Sign out" aria-label="Sign out">
76
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"/><line x1="12" y1="2" x2="12" y2="12"/></svg>
77
+ </button>
78
+ </div>
79
+
80
+ <div class="sidebar-actions">
81
+ <button class="action-btn" id="create-room-btn">+ New Room</button>
82
+ <button class="action-btn secondary" id="join-room-btn">Join Room</button>
83
+ </div>
84
+
85
+ <div class="room-search">
86
+ <input type="text" id="room-search-input" placeholder="Filter rooms…" autocomplete="off">
87
+ </div>
88
+
89
+ <div class="room-list" id="room-list"></div>
90
+
91
+ <div class="sidebar-status connecting" id="sync-status">
92
+ <span class="status-dot"></span>
93
+ <span class="status-text">Starting…</span>
94
+ </div>
95
+ </aside>
96
+
97
+ <!-- Main panel -->
98
+ <main class="main-panel">
99
+ <div id="empty-state" class="empty-state">
100
+ <div class="empty-logo">M</div>
101
+ <h2>Select a room</h2>
102
+ <p>Choose a room from the list on the left, or create / join a new one.</p>
103
+ </div>
104
+
105
+ <div id="chat-panel" class="chat-panel hidden">
106
+ <header class="chat-header">
107
+ <div class="avatar" id="chat-room-avatar"></div>
108
+ <div class="chat-room-meta">
109
+ <div class="chat-room-name" id="chat-room-name"></div>
110
+ <div class="chat-room-topic" id="chat-room-topic"></div>
111
+ </div>
112
+ <div class="chat-room-count" id="chat-room-count"></div>
113
+ <button class="icon-btn" id="leave-room-btn" title="Leave room" aria-label="Leave room">
114
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
115
+ </button>
116
+ </header>
117
+
118
+ <div class="timeline" id="timeline"></div>
119
+
120
+ <div class="composer">
121
+ <button class="icon-btn attach-btn" id="attach-btn" title="Attach file" aria-label="Attach file">
122
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
123
+ </button>
124
+ <input type="file" id="file-input" class="hidden" multiple>
125
+ <textarea id="composer-input" rows="1" placeholder="Send a message… (Enter to send, Shift+Enter for a new line)"></textarea>
126
+ <button class="send-btn" id="send-btn" title="Send" aria-label="Send">
127
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>
128
+ </button>
129
+ </div>
130
+ </div>
131
+ </main>
132
+ </div>
133
+
134
+ <!-- ===================== CREATE ROOM MODAL ===================== -->
135
+ <div id="create-room-modal" class="modal-overlay hidden">
136
+ <div class="modal">
137
+ <h2>Create Room</h2>
138
+ <label for="create-room-name">Room name</label>
139
+ <input type="text" id="create-room-name" placeholder="My room" autocomplete="off">
140
+ <label for="create-room-alias">Room alias (optional)</label>
141
+ <input type="text" id="create-room-alias" placeholder="#alias:server.com" autocomplete="off" spellcheck="false">
142
+ <label for="create-room-visibility">Visibility</label>
143
+ <select id="create-room-visibility">
144
+ <option value="private">Private (invite only)</option>
145
+ <option value="public">Public</option>
146
+ </select>
147
+ <div class="modal-actions">
148
+ <button type="button" class="btn-ghost" data-close-modal>Cancel</button>
149
+ <button type="button" class="btn-primary" id="create-room-confirm">Create</button>
150
+ </div>
151
+ <div id="create-room-error" class="modal-error hidden"></div>
152
+ </div>
153
+ </div>
154
+
155
+ <!-- ===================== JOIN ROOM MODAL ===================== -->
156
+ <div id="join-room-modal" class="modal-overlay hidden">
157
+ <div class="modal">
158
+ <h2>Join Room</h2>
159
+ <label for="join-room-input">Room ID or alias</label>
160
+ <input type="text" id="join-room-input" placeholder="#room:server.com" autocomplete="off" spellcheck="false">
161
+ <div class="modal-actions">
162
+ <button type="button" class="btn-ghost" data-close-modal>Cancel</button>
163
+ <button type="button" class="btn-primary" id="join-room-confirm">Join</button>
164
+ </div>
165
+ <div id="join-room-error" class="modal-error hidden"></div>
166
+ </div>
167
+ </div>
168
+
169
+ <div id="toast-container" class="toast-container"></div>
170
+
171
+ <!-- matrix-js-sdk (UMD browser build) -->
172
+ <script src="https://unpkg.com/matrix-js-sdk@latest/browser-matrix.js"></script>
173
+ <script src="js/matrix-service.js"></script>
174
+ <script src="js/app.js"></script>
175
+ </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  </html>
js/app.js ADDED
@@ -0,0 +1,1299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ Matrix Web Client — UI application layer
3
+ ============================================================ */
4
+
5
+ (function () {
6
+ 'use strict';
7
+
8
+ /* ---------------- Helpers ---------------- */
9
+
10
+ function byId(id) {
11
+ return document.getElementById(id);
12
+ }
13
+
14
+ // Build HTML entities via char codes so they can't be mangled by tooling.
15
+ const AMP = String.fromCharCode(38) + 'amp;';
16
+ const LT = String.fromCharCode(60) + 'lt;';
17
+ const GT = String.fromCharCode(62) + 'gt;';
18
+ const QUOT = String.fromCharCode(34) + 'quot;';
19
+
20
+ function escapeHtml(s) {
21
+ return String(s == null ? '' : s)
22
+ .replace(/&/g, AMP)
23
+ .replace(/</g, LT)
24
+ .replace(/>/g, GT)
25
+ .replace(/"/g, QUOT)
26
+ .replace(/'/g, '&#39;');
27
+ }
28
+
29
+ function initials(name) {
30
+ if (!name) return '?';
31
+ const localpart = name.replace(/^@/, '').split(':')[0];
32
+ return (
33
+ localpart
34
+ .split(/[._\-\s]+/)
35
+ .filter(Boolean)
36
+ .slice(0, 2)
37
+ .map((p) => p[0].toUpperCase())
38
+ .join('') || '?'
39
+ );
40
+ }
41
+
42
+ /** Deterministic color from a user id. */
43
+ function colorFor(userId) {
44
+ let hash = 0;
45
+ for (let i = 0; i < userId.length; i++) {
46
+ hash = (hash * 31 + userId.charCodeAt(i)) | 0;
47
+ }
48
+ const hue = Math.abs(hash) % 360;
49
+ return `hsl(${hue}, 45%, 42%)`;
50
+ }
51
+
52
+ function formatTime(ts) {
53
+ const d = new Date(ts);
54
+ const h = d.getHours().toString().padStart(2, '0');
55
+ const m = d.getMinutes().toString().padStart(2, '0');
56
+ return `${h}:${m}`;
57
+ }
58
+
59
+ function formatDay(ts) {
60
+ const d = new Date(ts);
61
+ const now = new Date();
62
+ const yesterday = new Date(now);
63
+ yesterday.setDate(now.getDate() - 1);
64
+
65
+ const sameDay = (a, b) =>
66
+ a.getFullYear() === b.getFullYear() &&
67
+ a.getMonth() === b.getMonth() &&
68
+ a.getDate() === b.getDate();
69
+
70
+ if (sameDay(d, now)) return 'Today';
71
+ if (sameDay(d, yesterday)) return 'Yesterday';
72
+ return d.toLocaleDateString(undefined, {
73
+ weekday: 'long',
74
+ year: 'numeric',
75
+ month: 'long',
76
+ day: 'numeric',
77
+ });
78
+ }
79
+
80
+ function formatFileSize(bytes) {
81
+ if (!bytes && bytes !== 0) return '';
82
+ if (bytes < 1024) return `${bytes} B`;
83
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
84
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
85
+ }
86
+
87
+ function fileIconFor(name) {
88
+ const ext = (name || '').split('.').pop().toLowerCase();
89
+ const icons = {
90
+ pdf: '📄', doc: '📝', docx: '📝', txt: '📄', md: '📄',
91
+ zip: '🗜️', tar: '🗜️', gz: '🗜️', rar: '🗜️', '7z': '🗜️',
92
+ mp3: '🎵', wav: '🎵', ogg: '🎵', flac: '🎵',
93
+ mp4: '🎬', webm: '🎬', mov: '🎬', mkv: '🎬',
94
+ png: '🖼️', jpg: '🖼️', jpeg: '🖼️', gif: '🖼️', svg: '🖼️', webp: '🖼️',
95
+ js: '💻', ts: '💻', py: '💻', html: '💻', css: '💻', json: '💻',
96
+ xls: '📊', xlsx: '📊', csv: '📊',
97
+ ppt: '📽️', pptx: '📽️',
98
+ exe: '⚙️', dmg: '⚙️', apk: '📱',
99
+ };
100
+ return icons[ext] || '📎';
101
+ }
102
+
103
+ /* ---------------- URL + inline formatting ---------------- */
104
+
105
+ const URL_RE = /(https?:\/\/[^\s<]+)/g;
106
+
107
+ function linkify(text) {
108
+ return text.replace(URL_RE, (url) => {
109
+ const href = url.replace(/[.,;:!?]+$/, '');
110
+ const tail = url.slice(href.length);
111
+ return `<a href="${href}" target="_blank" rel="noopener noreferrer">${href}</a>${tail}`;
112
+ });
113
+ }
114
+
115
+ function formatInline(text) {
116
+ // inline code first (placeholders)
117
+ const codeSpans = [];
118
+ text = text.replace(/`([^`]+)`/g, (_, code) => {
119
+ codeSpans.push(code);
120
+ return `\u0000${codeSpans.length - 1}\u0000`;
121
+ });
122
+
123
+ // bold
124
+ text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
125
+ // italic
126
+ text = text.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
127
+ // strikethrough
128
+ text = text.replace(/~~([^~]+)~~/g, '<del>$1</del>');
129
+
130
+ text = linkify(text);
131
+
132
+ // restore code spans
133
+ text = text.replace(/\u0000(\d+)\u0000/g, (_, idx) => {
134
+ return `<code>${codeSpans[Number(idx)]}</code>`;
135
+ });
136
+
137
+ return text;
138
+ }
139
+
140
+ function formatBody(text) {
141
+ const escaped = escapeHtml(text);
142
+ const lines = escaped.split('\n');
143
+ let html = '';
144
+ let codeBuf = [];
145
+ let inCode = false;
146
+
147
+ const flushCode = () => {
148
+ if (codeBuf.length) {
149
+ html += '<pre><code>' + codeBuf.join('\n') + '</code></pre>';
150
+ codeBuf = [];
151
+ }
152
+ };
153
+
154
+ for (let i = 0; i < lines.length; i++) {
155
+ const line = lines[i];
156
+ const fence = line.match(/^```(.*)$/);
157
+
158
+ if (fence) {
159
+ if (inCode) {
160
+ flushCode();
161
+ inCode = false;
162
+ } else {
163
+ flushCode();
164
+ inCode = true;
165
+ }
166
+ continue;
167
+ }
168
+
169
+ if (inCode) {
170
+ codeBuf.push(line);
171
+ continue;
172
+ }
173
+
174
+ // blank line
175
+ if (line.trim() === '') {
176
+ html += '<p><br></p>';
177
+ continue;
178
+ }
179
+
180
+ // blockquote (the line is HTML-escaped, so ">" is now ">")
181
+ const GT_ESCAPED = GT;
182
+ if (line.indexOf(GT_ESCAPED) === 0) {
183
+ const quote = [];
184
+ while (i < lines.length && lines[i].indexOf(GT_ESCAPED) === 0) {
185
+ quote.push(formatInline(lines[i].replace(new RegExp('^' + GT + '\\s?'), '')));
186
+ i++;
187
+ }
188
+ i--;
189
+ html += '<blockquote>' + quote.join('<br>') + '</blockquote>';
190
+ continue;
191
+ }
192
+
193
+ html += '<p>' + formatInline(line) + '</p>';
194
+ }
195
+
196
+ if (inCode) flushCode();
197
+ return html;
198
+ }
199
+
200
+ /* ---------------- State ---------------- */
201
+
202
+ const service = new window.MatrixService();
203
+ let currentRoomId = null;
204
+ let memberCache = {}; // userId -> { name, avatarUrl }
205
+
206
+ /* ---------------- Toasts ---------------- */
207
+
208
+ function toast(message, type, actions) {
209
+ const container = byId('toast-container');
210
+ const el = document.createElement('div');
211
+ el.className = 'toast' + (type === 'error' ? ' error' : '');
212
+
213
+ const text = document.createElement('span');
214
+ text.textContent = message;
215
+ el.appendChild(text);
216
+
217
+ if (actions) {
218
+ const btnWrap = document.createElement('div');
219
+ btnWrap.className = 'toast-actions';
220
+ actions.forEach((a) => {
221
+ const btn = document.createElement('button');
222
+ btn.className = 'toast-btn';
223
+ btn.textContent = a.label;
224
+ btn.addEventListener('click', () => {
225
+ a.onClick();
226
+ el.remove();
227
+ });
228
+ btnWrap.appendChild(btn);
229
+ });
230
+ el.appendChild(btnWrap);
231
+ }
232
+
233
+ container.appendChild(el);
234
+ if (!actions) {
235
+ setTimeout(() => {
236
+ el.style.opacity = '0';
237
+ el.style.transition = 'opacity 0.3s';
238
+ setTimeout(() => el.remove(), 300);
239
+ }, 3500);
240
+ }
241
+ }
242
+
243
+ /* ---------------- Login view ---------------- */
244
+
245
+ const loginTabs = document.querySelectorAll('.tab-btn');
246
+ loginTabs.forEach((tab) => {
247
+ tab.addEventListener('click', () => {
248
+ loginTabs.forEach((t) => t.classList.toggle('active', t === tab));
249
+ const pwd = tab.dataset.tab === 'password';
250
+ byId('login-password-form').classList.toggle('hidden', !pwd);
251
+ byId('login-token-form').classList.toggle('hidden', pwd);
252
+ byId('login-error').classList.add('hidden');
253
+ });
254
+ });
255
+
256
+ function showLoginError(msg) {
257
+ const el = byId('login-error');
258
+ el.textContent = msg;
259
+ el.classList.remove('hidden');
260
+ }
261
+
262
+ async function submitPasswordLogin(e) {
263
+ e.preventDefault();
264
+ const btn = byId('login-password-submit');
265
+ btn.disabled = true;
266
+ btn.textContent = 'Signing in…';
267
+ byId('login-error').classList.add('hidden');
268
+ try {
269
+ await service.loginWithPassword(
270
+ byId('homeserver-input').value,
271
+ byId('username-input').value.trim(),
272
+ byId('password-input').value
273
+ );
274
+ await enterApp();
275
+ } catch (err) {
276
+ showLoginError(getErrorMessage(err));
277
+ } finally {
278
+ btn.disabled = false;
279
+ btn.textContent = 'Sign In';
280
+ }
281
+ }
282
+
283
+ async function submitTokenLogin(e) {
284
+ e.preventDefault();
285
+ const btn = byId('login-token-submit');
286
+ btn.disabled = true;
287
+ btn.textContent = 'Signing in…';
288
+ byId('login-error').classList.add('hidden');
289
+ try {
290
+ await service.loginWithToken(
291
+ byId('token-homeserver-input').value,
292
+ byId('token-user-input').value.trim(),
293
+ byId('token-input').value.trim()
294
+ );
295
+ await enterApp();
296
+ } catch (err) {
297
+ showLoginError(getErrorMessage(err));
298
+ } finally {
299
+ btn.disabled = false;
300
+ btn.textContent = 'Sign In';
301
+ }
302
+ }
303
+
304
+ byId('login-password-form').addEventListener('submit', submitPasswordLogin);
305
+ byId('login-token-form').addEventListener('submit', submitTokenLogin);
306
+
307
+ function getErrorMessage(err) {
308
+ const data = err && err.data;
309
+ if (data && data.error) return data.error;
310
+ if (err && err.message) return err.message;
311
+ return String(err || 'Unknown error');
312
+ }
313
+
314
+ /* ---------------- App lifecycle ---------------- */
315
+
316
+ function showLoginView() {
317
+ byId('login-view').classList.remove('hidden');
318
+ byId('app-view').classList.add('hidden');
319
+ }
320
+
321
+ function showAppView() {
322
+ byId('login-view').classList.add('hidden');
323
+ byId('app-view').classList.remove('hidden');
324
+ }
325
+
326
+ async function enterApp() {
327
+ showAppView();
328
+ setSyncStatus('connecting', 'Connecting…');
329
+ service.startSync();
330
+ try {
331
+ await service.loadMembersForRooms();
332
+ } catch (err) {
333
+ // non-fatal; members will be lazy-loaded as needed
334
+ }
335
+ refreshUserBar();
336
+ renderRoomList();
337
+ }
338
+
339
+ async function init() {
340
+ // Restore saved session if present
341
+ try {
342
+ const session = await service.restoreSession();
343
+ if (session) {
344
+ await enterApp();
345
+ return;
346
+ }
347
+ } catch (err) {
348
+ console.warn('[app] session restore failed:', err);
349
+ // fall through to login view
350
+ }
351
+ showLoginView();
352
+ }
353
+
354
+ async function handleLogout() {
355
+ if (!confirm('Are you sure you want to sign out?')) return;
356
+ try {
357
+ await service.logout();
358
+ } catch (err) {
359
+ console.warn(err);
360
+ }
361
+ currentRoomId = null;
362
+ memberCache = {};
363
+ byId('room-list').innerHTML = '';
364
+ byId('timeline').innerHTML = '';
365
+ byId('chat-panel').classList.add('hidden');
366
+ byId('empty-state').classList.remove('hidden');
367
+ showLoginView();
368
+ }
369
+
370
+ byId('logout-btn').addEventListener('click', handleLogout);
371
+
372
+ /* ---------------- Service event wiring ---------------- */
373
+
374
+ service.on('sync:prepared', (state) => {
375
+ if (state && state.members) memberCache = state.members;
376
+ service
377
+ .loadMembersForRooms()
378
+ .then(() => {
379
+ renderRoomList();
380
+ if (currentRoomId) renderTimeline();
381
+ })
382
+ .catch(() => {});
383
+ });
384
+
385
+ service.on('sync:status', ({ state, error }) => {
386
+ if (state === 'connected') setSyncStatus('connected', 'Connected');
387
+ else if (state === 'error') setSyncStatus('error', error || 'Sync error');
388
+ else setSyncStatus('connecting', 'Reconnecting…');
389
+ });
390
+
391
+ service.on('rooms:changed', () => {
392
+ renderRoomList();
393
+ if (currentRoomId) {
394
+ updateChatHeader();
395
+ }
396
+ });
397
+
398
+ service.on('members:changed', () => {
399
+ const state = service.buildState();
400
+ if (state && state.members) memberCache = state.members;
401
+ renderRoomList();
402
+ if (currentRoomId) renderTimeline();
403
+ });
404
+
405
+ service.on('invite', (invite) => {
406
+ toast(
407
+ `${invite.name || invite.userId} invited you to a room`,
408
+ null,
409
+ [
410
+ {
411
+ label: 'Accept',
412
+ onClick: () => {
413
+ service
414
+ .acceptInvite(invite.roomId)
415
+ .then(() => {
416
+ toast('Joined room');
417
+ if (invite.roomId && service.getRoom(invite.roomId)) {
418
+ selectRoom(invite.roomId);
419
+ } else {
420
+ renderRoomList();
421
+ }
422
+ })
423
+ .catch((err) => toast(getErrorMessage(err), 'error'));
424
+ },
425
+ },
426
+ { label: 'Dismiss', onClick: () => {} },
427
+ ]
428
+ );
429
+ });
430
+
431
+ service.on('event', (ev) => {
432
+ // Only repaint the timeline for events in the currently open room.
433
+ if (ev.roomId === currentRoomId) {
434
+ renderTimeline();
435
+ }
436
+ });
437
+
438
+ /* ---------------- Status bar ---------------- */
439
+
440
+ function setSyncStatus(state, text) {
441
+ const status = byId('sync-status');
442
+ status.className = 'sidebar-status ' + state;
443
+ status.querySelector('.status-text').textContent = text;
444
+ }
445
+
446
+ /* ---------------- User bar ---------------- */
447
+
448
+ function refreshUserBar() {
449
+ const state = service.buildState();
450
+ if (!state) return;
451
+ const avatar = byId('user-avatar');
452
+ avatar.textContent = initials(state.displayName || state.userId);
453
+ avatar.style.backgroundColor = colorFor(state.userId);
454
+ byId('user-name').textContent = state.displayName || state.userId;
455
+ byId('user-id').textContent = state.userId;
456
+ }
457
+
458
+ /* ---------------- Avatar helpers ---------------- */
459
+
460
+ function loadAvatarImage(url) {
461
+ return new Promise((resolve) => {
462
+ const img = new Image();
463
+ img.onload = () => resolve(img);
464
+ img.onerror = () => resolve(null);
465
+ img.src = url;
466
+ });
467
+ }
468
+
469
+ async function applyAvatar(el, url, fallbackText, bgColor) {
470
+ el.textContent = '';
471
+ el.style.background = bgColor || 'linear-gradient(135deg, var(--accent), #059669)';
472
+ if (!url) {
473
+ el.textContent = fallbackText;
474
+ return;
475
+ }
476
+ const img = await loadAvatarImage(url);
477
+ if (img) {
478
+ el.textContent = '';
479
+ el.style.background = 'none';
480
+ el.appendChild(img);
481
+ img.style.width = '100%';
482
+ img.style.height = '100%';
483
+ img.style.borderRadius = '50%';
484
+ img.style.objectFit = 'cover';
485
+ } else {
486
+ el.textContent = fallbackText;
487
+ }
488
+ }
489
+
490
+ /* ---------------- Room list ---------------- */
491
+
492
+ function renderRoomList() {
493
+ const state = service.buildState();
494
+ if (!state) return;
495
+ const filter = byId('room-search-input').value.trim().toLowerCase();
496
+ const container = byId('room-list');
497
+
498
+ const rooms = state.rooms
499
+ .filter((room) => !filter || room.name.toLowerCase().includes(filter))
500
+ .slice()
501
+ .sort(
502
+ (a, b) =>
503
+ (b.lastEvent && b.lastEvent.ts) - (a.lastEvent && a.lastEvent.ts) || 0
504
+ );
505
+
506
+ container.innerHTML = '';
507
+ if (!rooms.length) {
508
+ const empty = document.createElement('div');
509
+ empty.className = 'room-list-empty';
510
+ empty.textContent = filter
511
+ ? 'No matching rooms'
512
+ : 'No rooms yet. Create or join one!';
513
+ container.appendChild(empty);
514
+ return;
515
+ }
516
+
517
+ rooms.forEach((room) => {
518
+ const item = document.createElement('div');
519
+ item.className = 'room-item' + (room.roomId === currentRoomId ? ' active' : '');
520
+ item.dataset.roomId = room.roomId;
521
+
522
+ // Avatar
523
+ const av = document.createElement('div');
524
+ av.className = 'room-avatar';
525
+ if (room.avatarUrl) {
526
+ applyAvatar(av, room.avatarUrl, initials(room.name), colorFor(room.roomId));
527
+ } else {
528
+ av.textContent = initials(room.name);
529
+ av.style.backgroundColor = colorFor(room.roomId);
530
+ }
531
+ item.appendChild(av);
532
+
533
+ // Info
534
+ const info = document.createElement('div');
535
+ info.className = 'room-info';
536
+ const name = document.createElement('div');
537
+ name.className = 'room-name';
538
+ name.textContent = room.name;
539
+ const preview = document.createElement('div');
540
+ preview.className = 'room-preview';
541
+ preview.textContent = room.lastEvent ? summarizeEvent(room.lastEvent) : '';
542
+ info.appendChild(name);
543
+ info.appendChild(preview);
544
+ item.appendChild(info);
545
+
546
+ // Meta (time + unread)
547
+ const meta = document.createElement('div');
548
+ meta.className = 'room-meta';
549
+ const time = document.createElement('div');
550
+ time.className = 'room-time';
551
+ time.textContent =
552
+ room.lastEvent && room.lastEvent.ts ? formatTime(room.lastEvent.ts) : '';
553
+ const unread = document.createElement('div');
554
+ unread.className = 'room-unread';
555
+ unread.textContent = room.unread > 99 ? '99+' : String(room.unread);
556
+ if (room.unread > 0) unread.classList.add('visible');
557
+ meta.appendChild(time);
558
+ meta.appendChild(unread);
559
+ item.appendChild(meta);
560
+
561
+ item.addEventListener('click', () => selectRoom(room.roomId));
562
+ container.appendChild(item);
563
+ });
564
+ }
565
+
566
+ function summarizeEvent(ev) {
567
+ if (ev.redacted) return 'Message deleted';
568
+ if (ev.type === 'm.room.message') {
569
+ const c = ev.content || {};
570
+ if (c.msgtype === 'm.emote') return `${ev.senderName || ev.sender} ${c.body || ''}`;
571
+ if (c.msgtype === 'm.notice') return c.body || '';
572
+ if (c.msgtype === 'm.image') return '📷 ' + (c.body || 'Image');
573
+ if (c.msgtype === 'm.video') return '🎬 ' + (c.body || 'Video');
574
+ if (c.msgtype === 'm.audio') return '🎵 ' + (c.body || 'Audio');
575
+ if (c.msgtype === 'm.file') return '📎 ' + (c.body || 'File');
576
+ const body = c.body || '';
577
+ return body.length > 60 ? body.slice(0, 60) + '…' : body;
578
+ }
579
+ if (ev.type === 'm.room.member') {
580
+ const name = ev.senderName || ev.sender;
581
+ const target = ev.displayname || ev.target || name;
582
+ if (ev.membership === 'join') return `${name} joined the room`;
583
+ if (ev.membership === 'leave') return `${name} left the room`;
584
+ if (ev.membership === 'invite') return `${name} invited ${target}`;
585
+ if (ev.membership === 'ban') return `${name} banned ${target}`;
586
+ return `${name} changed membership`;
587
+ }
588
+ if (ev.type === 'm.room.name') return `Room name changed to “${ev.content.name || ''}”`;
589
+ if (ev.type === 'm.room.topic') return 'Room topic changed';
590
+ if (ev.type === 'm.room.avatar') return 'Room avatar changed';
591
+ if (ev.type === 'm.room.encrypted') return '🔒 Encrypted message';
592
+ return '';
593
+ }
594
+
595
+ /* ---------------- Selecting rooms ---------------- */
596
+
597
+ function selectRoom(roomId) {
598
+ if (
599
+ currentRoomId === roomId &&
600
+ !byId('chat-panel').classList.contains('hidden')
601
+ ) {
602
+ // already open; just mark read
603
+ service.markRoomRead(roomId);
604
+ return;
605
+ }
606
+ currentRoomId = roomId;
607
+ byId('empty-state').classList.add('hidden');
608
+ byId('chat-panel').classList.remove('hidden');
609
+
610
+ // Highlight in room list
611
+ document.querySelectorAll('.room-item').forEach((el) => {
612
+ el.classList.toggle('active', el.dataset.roomId === roomId);
613
+ });
614
+
615
+ updateChatHeader();
616
+ renderTimeline(true);
617
+ service.markRoomRead(roomId);
618
+ byId('composer-input').focus();
619
+ }
620
+
621
+ function updateChatHeader() {
622
+ const room = service.getRoom(currentRoomId);
623
+ if (!room) return;
624
+
625
+ const state = service.buildState();
626
+ const r = state ? state.rooms.find((x) => x.roomId === currentRoomId) : null;
627
+ const name = r ? r.name : room.name;
628
+ const topic = r ? r.topic : room.getTopic();
629
+ const members = r ? r.memberCount : room.getJoinedMemberCount();
630
+
631
+ byId('chat-room-name').textContent = name || room.roomId;
632
+ byId('chat-room-topic').textContent = topic || '';
633
+ byId('chat-room-count').textContent = `${members || 0} member${members === 1 ? '' : 's'}`;
634
+
635
+ const av = byId('chat-room-avatar');
636
+ const url = r ? r.avatarUrl : null;
637
+ if (url) {
638
+ applyAvatar(av, url, initials(name), colorFor(room.roomId));
639
+ } else {
640
+ av.textContent = initials(name);
641
+ av.style.background = colorFor(room.roomId);
642
+ }
643
+ }
644
+
645
+ /* ---------------- Timeline rendering ---------------- */
646
+
647
+ let scrollAnchor = 'bottom';
648
+
649
+ function renderTimeline(forceStick) {
650
+ const room = service.getRoom(currentRoomId);
651
+ if (!room) return;
652
+ const timelineEl = byId('timeline');
653
+
654
+ const sticky =
655
+ scrollAnchor === 'bottom' ||
656
+ forceStick ||
657
+ timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight < 140;
658
+
659
+ const events = service.getRoomTimeline(room.roomId);
660
+ const structs = events.filter((ev) => !isHiddenEvent(ev));
661
+
662
+ timelineEl.innerHTML = '';
663
+
664
+ // Load-earlier button
665
+ const liveSet = room.getLiveTimeline().getTimelineSet();
666
+ if (liveSet && room.getLiveTimeline().canPaginate(liveSet)) {
667
+ const loadBtn = document.createElement('button');
668
+ loadBtn.className = 'load-earlier';
669
+ loadBtn.textContent = 'Load earlier messages';
670
+ loadBtn.addEventListener('click', async () => {
671
+ loadBtn.disabled = true;
672
+ loadBtn.textContent = 'Loading…';
673
+ try {
674
+ await room.paginateEvents(20);
675
+ renderTimeline(true);
676
+ } catch (err) {
677
+ toast('Failed to load earlier messages', 'error');
678
+ loadBtn.remove();
679
+ }
680
+ });
681
+ timelineEl.appendChild(loadBtn);
682
+ }
683
+
684
+ let lastDay = null;
685
+ let prevKey = null;
686
+ let prevTs = 0;
687
+
688
+ structs.forEach((ev) => {
689
+ const day = new Date(ev.ts).toDateString();
690
+ if (day !== lastDay) {
691
+ lastDay = day;
692
+ const divider = document.createElement('div');
693
+ divider.className = 'day-divider';
694
+ divider.textContent = formatDay(ev.ts);
695
+ timelineEl.appendChild(divider);
696
+ }
697
+
698
+ const near = prevTs !== 0 && ev.ts - prevTs < 5 * 60 * 1000;
699
+ const groupSameSender = ev.sender === prevKey && near;
700
+ const el = buildMessageEl(ev, groupSameSender);
701
+ timelineEl.appendChild(el);
702
+
703
+ prevKey = ev.sender;
704
+ prevTs = ev.ts;
705
+ });
706
+
707
+ if (sticky) {
708
+ timelineEl.scrollTop = timelineEl.scrollHeight;
709
+ }
710
+ }
711
+
712
+ function isHiddenEvent(ev) {
713
+ // m.reaction events are rendered into their target message instead.
714
+ if (ev.type === 'm.reaction' && ev.relation && ev.relation.event_id)
715
+ return true;
716
+ // edits are merged into the original message
717
+ if (ev.relation && ev.relation.rel_type === 'm.replace') return true;
718
+ return false;
719
+ }
720
+
721
+ function buildMessageEl(ev, grouped) {
722
+ const wrap = document.createElement('div');
723
+
724
+ if (ev.redacted) {
725
+ wrap.className = 'msg-notice';
726
+ wrap.textContent = 'Message deleted';
727
+ return wrap;
728
+ }
729
+
730
+ // Membership changes -> notice (but hide profile-only updates)
731
+ if (ev.type === 'm.room.member' && ev.membership !== ev.prevMembership) {
732
+ wrap.className = 'msg-notice';
733
+ wrap.textContent = membershipNotice(ev);
734
+ return wrap;
735
+ }
736
+
737
+ // Room name / topic / create changes -> notice
738
+ if (
739
+ ev.type === 'm.room.name' ||
740
+ ev.type === 'm.room.topic' ||
741
+ ev.type === 'm.room.avatar' ||
742
+ ev.type === 'm.room.create'
743
+ ) {
744
+ wrap.className = 'msg-notice';
745
+ wrap.textContent = roomStateNotice(ev);
746
+ return wrap;
747
+ }
748
+
749
+ // Encrypted -> notice
750
+ if (
751
+ ev.type === 'm.room.encrypted' ||
752
+ (ev.type === 'm.room.message' &&
753
+ ev.content &&
754
+ ev.content.msgtype === 'm.bad.encrypted')
755
+ ) {
756
+ wrap.className = 'msg-notice';
757
+ wrap.textContent =
758
+ '🔒 Encrypted message — this client does not support end-to-end encryption.';
759
+ return wrap;
760
+ }
761
+
762
+ // Standard message event
763
+ wrap.className =
764
+ 'msg' +
765
+ (ev.status === 'not_sent' ? ' failed' : '') +
766
+ (ev.status === 'sending' ? ' sending' : '');
767
+ wrap.dataset.eventId = ev.eventId;
768
+
769
+ // Avatar
770
+ const av = document.createElement('div');
771
+ av.className = 'msg-avatar';
772
+ const senderColor = colorFor(ev.sender);
773
+ if (ev.senderAvatar) {
774
+ applyAvatar(
775
+ av,
776
+ ev.senderAvatar,
777
+ initials(ev.senderName || ev.sender),
778
+ senderColor
779
+ );
780
+ } else {
781
+ av.textContent = initials(ev.senderName || ev.sender);
782
+ av.style.background = senderColor;
783
+ }
784
+ if (grouped) {
785
+ av.style.visibility = 'hidden';
786
+ }
787
+ wrap.appendChild(av);
788
+
789
+ // Body
790
+ const body = document.createElement('div');
791
+ body.className = 'msg-body';
792
+
793
+ if (!grouped) {
794
+ const head = document.createElement('div');
795
+ head.className = 'msg-head';
796
+ const sender = document.createElement('span');
797
+ sender.className = 'msg-sender' + (ev.isSelf ? ' self' : '');
798
+ if (ev.isSelf) {
799
+ sender.textContent = 'You (' + (ev.senderName || ev.sender) + ')';
800
+ } else {
801
+ sender.textContent = ev.senderName || ev.sender;
802
+ }
803
+ const time = document.createElement('span');
804
+ time.className = 'msg-time';
805
+ time.textContent = formatTime(ev.ts);
806
+ head.appendChild(sender);
807
+ head.appendChild(time);
808
+ body.appendChild(head);
809
+ }
810
+
811
+ const content = document.createElement('div');
812
+ content.className = 'msg-content';
813
+ content.appendChild(buildMessageContent(ev));
814
+ body.appendChild(content);
815
+
816
+ wrap.appendChild(body);
817
+
818
+ // Reaction menu
819
+ if (!ev.redacted) {
820
+ wrap.appendChild(buildReactionButton(ev));
821
+ }
822
+
823
+ // Reactions
824
+ const reactions = collectReactions(ev.roomId, ev.eventId);
825
+ if (reactions.length) {
826
+ body.appendChild(buildReactionsRow(ev.eventId, reactions));
827
+ }
828
+
829
+ return wrap;
830
+ }
831
+
832
+ function membershipNotice(ev) {
833
+ const name = ev.senderName || ev.sender;
834
+ const target = ev.displayname || ev.target || name;
835
+ if (ev.membership === 'join') return `${name} joined the room`;
836
+ if (ev.membership === 'leave') {
837
+ if (ev.target === ev.sender || !ev.target) return `${name} left the room`;
838
+ return `${name} left`;
839
+ }
840
+ if (ev.membership === 'invite') return `${name} invited ${target}`;
841
+ if (ev.membership === 'ban') return `${name} banned ${target}`;
842
+ if (ev.membership === 'knock') return `${name} knocked`;
843
+ return `${name} (${ev.membership})`;
844
+ }
845
+
846
+ function roomStateNotice(ev) {
847
+ if (ev.type === 'm.room.name') {
848
+ return ev.content && ev.content.name
849
+ ? `Room name changed to “${ev.content.name}”`
850
+ : 'Room name removed';
851
+ }
852
+ if (ev.type === 'm.room.topic') {
853
+ return ev.content && ev.content.topic
854
+ ? `Topic changed: “${ev.content.topic}”`
855
+ : 'Topic removed';
856
+ }
857
+ if (ev.type === 'm.room.avatar') return 'Room avatar changed';
858
+ if (ev.type === 'm.room.create') return 'Room created';
859
+ return '';
860
+ }
861
+
862
+ function buildMessageContent(ev) {
863
+ const holder = document.createElement('div');
864
+
865
+ if (ev.type === 'm.room.message') {
866
+ const c = ev.content || {};
867
+ switch (c.msgtype) {
868
+ case 'm.image': {
869
+ const imgWrap = document.createElement('div');
870
+ const img = document.createElement('img');
871
+ img.loading = 'lazy';
872
+ const url = c.url
873
+ ? service.mxcToHttp(c.url, 640, 480)
874
+ : c.file && c.file.url
875
+ ? service.mxcToHttp(c.file.url, 640, 480)
876
+ : null;
877
+ if (url) {
878
+ img.src = url;
879
+ img.alt = c.body || 'Image';
880
+ imgWrap.appendChild(img);
881
+ img.addEventListener('click', () => window.open(url, '_blank'));
882
+ } else {
883
+ imgWrap.appendChild(buildFileLink(c));
884
+ }
885
+ if (c.body && c.body !== 'Image') {
886
+ const capt = document.createElement('div');
887
+ capt.className = 'msg-caption';
888
+ capt.textContent = c.body;
889
+ imgWrap.appendChild(capt);
890
+ }
891
+ holder.appendChild(imgWrap);
892
+ break;
893
+ }
894
+ case 'm.video': {
895
+ const video = document.createElement('video');
896
+ video.controls = true;
897
+ const url = c.url
898
+ ? service.mxcToHttp(c.url, 640, 480)
899
+ : c.file && c.file.url
900
+ ? service.mxcToHttp(c.file.url, 640, 480)
901
+ : null;
902
+ if (url) {
903
+ video.src = url;
904
+ holder.appendChild(video);
905
+ } else {
906
+ holder.appendChild(buildFileLink(c));
907
+ }
908
+ break;
909
+ }
910
+ case 'm.audio': {
911
+ const audio = document.createElement('audio');
912
+ audio.controls = true;
913
+ const url = c.url
914
+ ? service.mxcToHttp(c.url, 640, 480)
915
+ : c.file && c.file.url
916
+ ? service.mxcToHttp(c.file.url, 640, 480)
917
+ : null;
918
+ if (url) {
919
+ audio.src = url;
920
+ holder.appendChild(audio);
921
+ } else {
922
+ holder.appendChild(buildFileLink(c));
923
+ }
924
+ break;
925
+ }
926
+ case 'm.file':
927
+ case 'm.attachment': {
928
+ holder.appendChild(buildFileLink(c));
929
+ break;
930
+ }
931
+ case 'm.emote': {
932
+ const p = document.createElement('p');
933
+ p.innerHTML =
934
+ `<em>${escapeHtml(ev.senderName || ev.sender)} ${formatInline(
935
+ escapeHtml(c.body || '')
936
+ )}</em>`;
937
+ holder.appendChild(p);
938
+ break;
939
+ }
940
+ case 'm.notice': {
941
+ const p = document.createElement('p');
942
+ p.className = 'msg-notice-text';
943
+ p.innerHTML = formatBody(c.body || '');
944
+ holder.appendChild(p);
945
+ break;
946
+ }
947
+ default: {
948
+ const div = document.createElement('div');
949
+ div.innerHTML = formatBody(c.body || '');
950
+ holder.appendChild(div);
951
+ }
952
+ }
953
+
954
+ if (ev.editOf) {
955
+ const edited = document.createElement('span');
956
+ edited.className = 'msg-edited';
957
+ edited.textContent = '(edited)';
958
+ holder.appendChild(edited);
959
+ }
960
+ if (ev.relation && ev.relation.rel_type === 'm.thread') {
961
+ const rep = document.createElement('div');
962
+ rep.className = 'msg-reply-indicator';
963
+ rep.textContent = '↩ Thread reply';
964
+ holder.prepend(rep);
965
+ }
966
+ }
967
+
968
+ return holder;
969
+ }
970
+
971
+ function buildFileLink(c) {
972
+ const a = document.createElement('a');
973
+ a.className = 'msg-file';
974
+ const url = c.url
975
+ ? service.mxcToHttp(c.url, 640, 480)
976
+ : c.file && c.file.url
977
+ ? service.mxcToHttp(c.file.url, 640, 480)
978
+ : null;
979
+ if (url) {
980
+ a.href = url;
981
+ a.target = '_blank';
982
+ a.rel = 'noopener noreferrer';
983
+ }
984
+
985
+ const icon = document.createElement('div');
986
+ icon.className = 'msg-file-icon';
987
+ icon.textContent = fileIconFor(c.body);
988
+ a.appendChild(icon);
989
+
990
+ const meta = document.createElement('div');
991
+ meta.className = 'msg-file-meta';
992
+ const name = document.createElement('div');
993
+ name.className = 'msg-file-name';
994
+ name.textContent = c.body || 'File';
995
+ const size = document.createElement('div');
996
+ size.className = 'msg-file-size';
997
+ size.textContent = formatFileSize(c.info && c.info.size);
998
+ meta.appendChild(name);
999
+ meta.appendChild(size);
1000
+ a.appendChild(meta);
1001
+
1002
+ return a;
1003
+ }
1004
+
1005
+ /* ---------------- Reactions ---------------- */
1006
+
1007
+ function collectReactions(roomId, targetEventId) {
1008
+ const room = service.getRoom(roomId);
1009
+ if (!room) return [];
1010
+ const counts = {};
1011
+ for (const ev of room.getLiveTimeline().getEvents()) {
1012
+ if (ev.getType() !== 'm.reaction') continue;
1013
+ const rel = ev.getRelation && ev.getRelation();
1014
+ if (!rel || rel.rel_type !== 'm.annotation' || rel.event_id !== targetEventId) continue;
1015
+ if (ev.isRedacted && ev.isRedacted()) continue;
1016
+ const key = (ev.getContent() || {}).key;
1017
+ if (!key) continue;
1018
+ counts[key] = (counts[key] || 0) + 1;
1019
+ }
1020
+ return Object.entries(counts).map(([key, count]) => ({ key, count }));
1021
+ }
1022
+
1023
+ function buildReactionsRow(targetEventId, reactions) {
1024
+ const row = document.createElement('div');
1025
+ row.className = 'msg-reactions';
1026
+ reactions.forEach((r) => {
1027
+ const pill = document.createElement('button');
1028
+ pill.className = 'reaction-pill';
1029
+ pill.textContent = `${r.key} ${r.count}`;
1030
+ pill.title = 'Reaction';
1031
+ pill.addEventListener('click', () => {
1032
+ service.sendReaction(currentRoomId, targetEventId, r.key).catch((err) => {
1033
+ toast(getErrorMessage(err), 'error');
1034
+ });
1035
+ });
1036
+ row.appendChild(pill);
1037
+ });
1038
+ return row;
1039
+ }
1040
+
1041
+ function buildReactionButton(ev) {
1042
+ const wrapper = document.createElement('div');
1043
+ wrapper.className = 'msg-actions';
1044
+
1045
+ const btn = document.createElement('button');
1046
+ btn.className = 'reaction-toggle';
1047
+ btn.title = 'React';
1048
+ btn.textContent = '+';
1049
+ wrapper.appendChild(btn);
1050
+
1051
+ const menu = document.createElement('div');
1052
+ menu.className = 'reaction-menu hidden';
1053
+ ['👍', '❤️', '😄', '🎉', '🔥'].forEach((emoji) => {
1054
+ const b = document.createElement('button');
1055
+ b.className = 'reaction-option';
1056
+ b.textContent = emoji;
1057
+ b.addEventListener('click', (e) => {
1058
+ e.stopPropagation();
1059
+ service
1060
+ .sendReaction(ev.roomId, ev.eventId, emoji)
1061
+ .then(() => {
1062
+ if (ev.roomId === currentRoomId) renderTimeline();
1063
+ })
1064
+ .catch((err) => toast(getErrorMessage(err), 'error'));
1065
+ menu.classList.add('hidden');
1066
+ });
1067
+ menu.appendChild(b);
1068
+ });
1069
+ wrapper.appendChild(menu);
1070
+
1071
+ btn.addEventListener('click', (e) => {
1072
+ e.stopPropagation();
1073
+ menu.classList.toggle('hidden');
1074
+ });
1075
+
1076
+ // Close menu when clicking elsewhere
1077
+ document.addEventListener('click', (e) => {
1078
+ if (!wrapper.contains(e.target)) menu.classList.add('hidden');
1079
+ });
1080
+
1081
+ return wrapper;
1082
+ }
1083
+
1084
+ /* ---------------- Composer ---------------- */
1085
+
1086
+ const composerInput = byId('composer-input');
1087
+ const sendBtn = byId('send-btn');
1088
+
1089
+ function autosize() {
1090
+ composerInput.style.height = 'auto';
1091
+ composerInput.style.height = Math.min(composerInput.scrollHeight, 140) + 'px';
1092
+ }
1093
+
1094
+ composerInput.addEventListener('input', () => {
1095
+ autosize();
1096
+ sendBtn.disabled = !composerInput.value.trim();
1097
+ });
1098
+
1099
+ composerInput.addEventListener('keydown', (e) => {
1100
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
1101
+ e.preventDefault();
1102
+ sendMessage();
1103
+ }
1104
+ });
1105
+
1106
+ function sendMessage() {
1107
+ const text = composerInput.value.trim();
1108
+ if (!text || !currentRoomId) return;
1109
+ service.sendText(currentRoomId, text).catch((err) =>
1110
+ toast(getErrorMessage(err), 'error')
1111
+ );
1112
+ composerInput.value = '';
1113
+ composerInput.style.height = 'auto';
1114
+ sendBtn.disabled = true;
1115
+ scrollAnchor = 'bottom';
1116
+ }
1117
+
1118
+ sendBtn.addEventListener('click', sendMessage);
1119
+
1120
+ /* ---------------- Attachment upload ---------------- */
1121
+
1122
+ const fileInput = byId('file-input');
1123
+ if (fileInput) {
1124
+ byId('attach-btn').addEventListener('click', () => fileInput.click());
1125
+
1126
+ fileInput.addEventListener('change', async () => {
1127
+ const file = fileInput.files && fileInput.files[0];
1128
+ fileInput.value = '';
1129
+ if (!file || !currentRoomId) return;
1130
+
1131
+ toast('Uploading…');
1132
+ try {
1133
+ const { url } = await service.uploadContent(file);
1134
+ const mime = file.type || 'application/octet-stream';
1135
+ let msgtype = 'm.file';
1136
+
1137
+ if (mime.startsWith('image/') && !['image/gif', 'image/svg+xml'].includes(mime)) {
1138
+ msgtype = 'm.image';
1139
+ } else if (mime.startsWith('video/')) {
1140
+ msgtype = 'm.video';
1141
+ } else if (mime.startsWith('audio/')) {
1142
+ msgtype = 'm.audio';
1143
+ }
1144
+
1145
+ if (msgtype === 'm.file') {
1146
+ await service.sendFile(currentRoomId, url, file.name, mime, file.size);
1147
+ } else {
1148
+ await service.sendAttachment(
1149
+ currentRoomId,
1150
+ url,
1151
+ file.name,
1152
+ mime,
1153
+ file.size,
1154
+ msgtype
1155
+ );
1156
+ }
1157
+ toast('Sent ✓');
1158
+ } catch (err) {
1159
+ toast('Upload failed: ' + getErrorMessage(err), 'error');
1160
+ }
1161
+ });
1162
+ }
1163
+
1164
+ /* ---------------- Room search filter ---------------- */
1165
+
1166
+ let searchTimer = null;
1167
+ byId('room-search-input').addEventListener('input', () => {
1168
+ clearTimeout(searchTimer);
1169
+ searchTimer = setTimeout(renderRoomList, 150);
1170
+ });
1171
+
1172
+ /* ---------------- Create / Join room modals ---------------- */
1173
+
1174
+ function openModal(id) {
1175
+ byId(id).classList.remove('hidden');
1176
+ }
1177
+
1178
+ function closeModal(id) {
1179
+ byId(id).classList.add('hidden');
1180
+ }
1181
+
1182
+ document.querySelectorAll('[data-close-modal]').forEach((btn) => {
1183
+ btn.addEventListener('click', () => {
1184
+ const modal = btn.closest('.modal-overlay');
1185
+ if (modal) modal.classList.add('hidden');
1186
+ });
1187
+ });
1188
+
1189
+ document.querySelectorAll('.modal-overlay').forEach((overlay) => {
1190
+ overlay.addEventListener('click', (e) => {
1191
+ if (e.target === overlay) overlay.classList.add('hidden');
1192
+ });
1193
+ });
1194
+
1195
+ byId('create-room-btn').addEventListener('click', () =>
1196
+ openModal('create-room-modal')
1197
+ );
1198
+ byId('join-room-btn').addEventListener('click', () =>
1199
+ openModal('join-room-modal')
1200
+ );
1201
+
1202
+ byId('create-room-confirm').addEventListener('click', async () => {
1203
+ const errEl = byId('create-room-error');
1204
+ errEl.classList.add('hidden');
1205
+ const btn = byId('create-room-confirm');
1206
+ btn.disabled = true;
1207
+ try {
1208
+ const roomId = await service.createRoom({
1209
+ name: byId('create-room-name').value.trim(),
1210
+ alias: byId('create-room-alias').value.trim(),
1211
+ visibility: byId('create-room-visibility').value,
1212
+ });
1213
+ closeModal('create-room-modal');
1214
+ byId('create-room-name').value = '';
1215
+ byId('create-room-alias').value = '';
1216
+ // Update the room list immediately; initial sync will bring the room in.
1217
+ renderRoomList();
1218
+ toast('Room created');
1219
+ // Wait a tick for the room to appear, then select it.
1220
+ setTimeout(() => {
1221
+ if (service.getRoom(roomId)) selectRoom(roomId);
1222
+ }, 600);
1223
+ } catch (err) {
1224
+ errEl.textContent = getErrorMessage(err);
1225
+ errEl.classList.remove('hidden');
1226
+ } finally {
1227
+ btn.disabled = false;
1228
+ }
1229
+ });
1230
+
1231
+ byId('join-room-confirm').addEventListener('click', async () => {
1232
+ const errEl = byId('join-room-error');
1233
+ errEl.classList.add('hidden');
1234
+ const btn = byId('join-room-confirm');
1235
+ btn.disabled = true;
1236
+ try {
1237
+ const roomId = await service.joinRoom(
1238
+ byId('join-room-input').value.trim()
1239
+ );
1240
+ closeModal('join-room-modal');
1241
+ byId('join-room-input').value = '';
1242
+ renderRoomList();
1243
+ setTimeout(() => {
1244
+ if (service.getRoom(roomId)) selectRoom(roomId);
1245
+ }, 600);
1246
+ } catch (err) {
1247
+ errEl.textContent = getErrorMessage(err);
1248
+ errEl.classList.remove('hidden');
1249
+ } finally {
1250
+ btn.disabled = false;
1251
+ }
1252
+ });
1253
+
1254
+ // Leave room button
1255
+ const leaveBtn = byId('leave-room-btn');
1256
+ if (leaveBtn) {
1257
+ leaveBtn.addEventListener('click', async () => {
1258
+ if (!currentRoomId) return;
1259
+ const name = byId('chat-room-name').textContent;
1260
+ if (!confirm(`Leave “${name}”?`)) return;
1261
+ try {
1262
+ await service.leaveRoom(currentRoomId);
1263
+ currentRoomId = null;
1264
+ byId('chat-panel').classList.add('hidden');
1265
+ byId('empty-state').classList.remove('hidden');
1266
+ renderRoomList();
1267
+ // pick another room if available
1268
+ const state = service.buildState();
1269
+ if (state && state.rooms.length) {
1270
+ selectRoom(state.rooms[0].roomId);
1271
+ }
1272
+ } catch (err) {
1273
+ toast(getErrorMessage(err), 'error');
1274
+ }
1275
+ });
1276
+ }
1277
+
1278
+ /* ---------------- Scroll tracking ---------------- */
1279
+
1280
+ const timelineEl = byId('timeline');
1281
+ timelineEl.addEventListener('scroll', () => {
1282
+ scrollAnchor =
1283
+ timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight <
1284
+ 140
1285
+ ? 'bottom'
1286
+ : 'top';
1287
+ if (currentRoomId && scrollAnchor === 'bottom') {
1288
+ clearTimeout(timelineEl._readTimer);
1289
+ timelineEl._readTimer = setTimeout(
1290
+ () => service.markRoomRead(currentRoomId),
1291
+ 400
1292
+ );
1293
+ }
1294
+ });
1295
+
1296
+ /* ---------------- Init ---------------- */
1297
+
1298
+ window.addEventListener('DOMContentLoaded', init);
1299
+ })();
js/matrix-service.js ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * MatrixService
3
+ * Thin wrapper around matrix-js-sdk (UMD browser build) that exposes just
4
+ * the high-level operations this client needs, and normalizes SDK event
5
+ * shapes into plain objects for the UI layer.
6
+ */
7
+ class MatrixService {
8
+ constructor() {
9
+ this.client = null;
10
+ this.session = null;
11
+ this.listeners = {};
12
+ this._store = window.localStorage;
13
+ this._eventsBound = false;
14
+ }
15
+
16
+ /* ---------------- Events ---------------- */
17
+
18
+ on(event, fn) {
19
+ if (!this.listeners[event]) this.listeners[event] = [];
20
+ this.listeners[event].push(fn);
21
+ }
22
+
23
+ _emit(event, payload) {
24
+ (this.listeners[event] || []).forEach((fn) => {
25
+ try {
26
+ fn(payload);
27
+ } catch (err) {
28
+ console.error('[MatrixService] listener error for', event, err);
29
+ }
30
+ });
31
+ }
32
+
33
+ /* ---------------- Session persistence ---------------- */
34
+
35
+ getSavedSession() {
36
+ try {
37
+ const raw = this._store.getItem('matrix_session');
38
+ return raw ? JSON.parse(raw) : null;
39
+ } catch (err) {
40
+ console.error('[MatrixService] failed to read session', err);
41
+ return null;
42
+ }
43
+ }
44
+
45
+ _saveSession(data) {
46
+ this.session = data;
47
+ this._store.setItem('matrix_session', JSON.stringify(data));
48
+ }
49
+
50
+ clearSession() {
51
+ this.session = null;
52
+ this._store.removeItem('matrix_session');
53
+ }
54
+
55
+ /* ---------------- Login ---------------- */
56
+
57
+ async loginWithPassword(homeserver, username, password) {
58
+ const baseUrl = this._normalizeHomeserver(homeserver);
59
+ const client = window.matrixcs.createClient({
60
+ baseUrl,
61
+ userId: username.includes(':') ? username : undefined,
62
+ accessToken: undefined,
63
+ });
64
+ this._eventsBound = false;
65
+
66
+ let loginUser = username;
67
+ // If the user typed a bare username like "alice", try to discover the full
68
+ // user id via /login. matrix-js-sdk normalizes bare usernames automatically
69
+ // using the homeserver domain, so we can pass it straight through.
70
+ const response = await client.login('m.login.password', {
71
+ user: loginUser,
72
+ password,
73
+ initial_device_display_name: 'Matrix Web Client',
74
+ });
75
+
76
+ client.accessToken = response.access_token;
77
+ client.userId = response.user_id;
78
+ client.deviceId = response.device_id || '';
79
+
80
+ this._saveSession({
81
+ baseUrl,
82
+ accessToken: response.access_token,
83
+ userId: response.user_id,
84
+ deviceId: response.device_id || '',
85
+ });
86
+
87
+ this.client = client;
88
+ return response;
89
+ }
90
+
91
+ async loginWithToken(homeserver, userId, accessToken) {
92
+ const baseUrl = this._normalizeHomeserver(homeserver);
93
+ const client = window.matrixcs.createClient({
94
+ baseUrl,
95
+ accessToken,
96
+ userId,
97
+ });
98
+ this._eventsBound = false;
99
+
100
+ // Verify the token is valid by hitting /account/whoami
101
+ const whoami = await client.whoami();
102
+
103
+ this._saveSession({
104
+ baseUrl,
105
+ accessToken,
106
+ userId: whoami.user_id,
107
+ deviceId: '',
108
+ });
109
+
110
+ this.client = client;
111
+ return whoami;
112
+ }
113
+
114
+ /**
115
+ * Restore a previously saved session and start syncing.
116
+ */
117
+ async restoreSession() {
118
+ const session = this.getSavedSession();
119
+ if (!session) return null;
120
+
121
+ const client = window.matrixcs.createClient({
122
+ baseUrl: session.baseUrl,
123
+ accessToken: session.accessToken,
124
+ userId: session.userId,
125
+ deviceId: session.deviceId,
126
+ });
127
+ this._eventsBound = false;
128
+
129
+ this.client = client;
130
+ this.session = session;
131
+
132
+ // Verify the token is still valid before syncing.
133
+ try {
134
+ await client.whoami();
135
+ } catch (err) {
136
+ this.clearSession();
137
+ this.client = null;
138
+ throw new Error('Session expired, please sign in again.');
139
+ }
140
+
141
+ return session;
142
+ }
143
+
144
+ /* ---------------- Syncing ---------------- */
145
+
146
+ startSync() {
147
+ if (!this.client) return;
148
+ this.client.startClient({
149
+ initialSyncLimit: 20,
150
+ lazyLoadMembers: true,
151
+ });
152
+ if (this._eventsBound) return;
153
+ this._eventsBound = true;
154
+ this._bindClientEvents();
155
+ }
156
+
157
+ stopSync() {
158
+ if (this.client) {
159
+ try {
160
+ this.client.stopClient();
161
+ } catch (err) {
162
+ console.warn('[MatrixService] stopClient error:', err);
163
+ }
164
+ }
165
+ }
166
+
167
+ _bindClientEvents() {
168
+ const sdk = this.client;
169
+
170
+ sdk.on('sync', (state, prevState, data) => {
171
+ if (state === 'PREPARED') {
172
+ this._emit('sync:prepared', this.buildState());
173
+ // Refresh room list + timeline once we know the initial sync is done.
174
+ this._emit('rooms:changed');
175
+ } else if (state === 'SYNCING') {
176
+ this._emit('sync:status', { state: 'connected' });
177
+ } else if (state === 'ERROR') {
178
+ this._emit('sync:status', {
179
+ state: 'error',
180
+ error: (data && data.error) || 'Sync error',
181
+ });
182
+ } else if (state === 'RECONNECTING') {
183
+ this._emit('sync:status', { state: 'connecting' });
184
+ }
185
+ });
186
+
187
+ // New / updated events in a room
188
+ sdk.on('Room.timeline', (event, room, toStartOfTimeline) => {
189
+ if (toStartOfTimeline || !room) return;
190
+ this._emit('event', this._eventToStruct(event, room));
191
+ this._emit('rooms:changed');
192
+ });
193
+
194
+ // Member changes (join / leave / invite / profile updates)
195
+ sdk.on('RoomState.members', (event, state) => {
196
+ this._emit('members:changed');
197
+ });
198
+
199
+ sdk.on('Room', (room) => {
200
+ this._emit('rooms:changed');
201
+ });
202
+
203
+ // Live state events (name, topic, joins, etc.)
204
+ sdk.on('RoomState.events', (event, state) => {
205
+ if (event.getType() === 'm.room.name' || event.getType() === 'm.room.topic') {
206
+ this._emit('rooms:changed');
207
+ }
208
+ });
209
+
210
+ sdk.on('RoomMember.membership', (event, member) => {
211
+ if (member.membership === 'invite') {
212
+ this._emit('invite', this._memberToStruct(member));
213
+ }
214
+ });
215
+
216
+ // Track read receipts locally so our own reads are sent to the server.
217
+ sdk.on('Room.receipt', (event, room) => {
218
+ this._emit('rooms:changed');
219
+ });
220
+ }
221
+
222
+ /* ---------------- State / room helpers ---------------- */
223
+
224
+ /**
225
+ * Build a plain state snapshot the UI can render without touching the SDK.
226
+ */
227
+ buildState() {
228
+ if (!this.client) return null;
229
+ const rooms = this.client.getRooms() || [];
230
+ const myUserId = this.client.getUserId();
231
+ const members = this._loadMembers();
232
+
233
+ return {
234
+ userId: myUserId,
235
+ displayName: this._getDisplayName(myUserId),
236
+ members,
237
+ rooms: rooms.map((room) => this._roomToStruct(room)),
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Warm the member cache so avatars/names are available when rendering.
243
+ */
244
+ async loadMembersForRooms() {
245
+ if (!this.client) return;
246
+ const rooms = this.client.getRooms();
247
+ await Promise.all(rooms.map((room) => room.loadMembersIfNeeded().catch(() => {})));
248
+ }
249
+
250
+ _loadMembers() {
251
+ const map = {};
252
+ if (!this.client) return map;
253
+ const rooms = this.client.getRooms();
254
+ for (const room of rooms) {
255
+ const roomMembers = room.getMembers();
256
+ for (const member of roomMembers) {
257
+ const id = member.userId;
258
+ if (!map[id]) {
259
+ map[id] = {
260
+ userId: id,
261
+ name: this._displayNameFor(member),
262
+ avatarUrl: this._mxcToHttp(member.getMxcAvatarUrl()),
263
+ };
264
+ }
265
+ }
266
+ }
267
+ return map;
268
+ }
269
+
270
+ /**
271
+ * Compute a friendly display name for a user id from the member cache.
272
+ */
273
+ _getDisplayName(userId) {
274
+ if (!userId) return '';
275
+ const member = this._findMember(userId);
276
+ return member ? member.name : userId;
277
+ }
278
+
279
+ _findMember(userId) {
280
+ const rooms = this.client ? this.client.getRooms() : [];
281
+ for (const room of rooms) {
282
+ const member = room.getMember(userId);
283
+ if (member && member.name) return { name: member.name, avatarUrl: this._mxcToHttp(member.getMxcAvatarUrl()) };
284
+ }
285
+ return null;
286
+ }
287
+
288
+ getUserAvatar(userId) {
289
+ const found = this._findMember(userId);
290
+ return found ? found.avatarUrl : null;
291
+ }
292
+
293
+ displayNameFor(userId) {
294
+ return this._getDisplayName(userId);
295
+ }
296
+
297
+ /* ---------------- Room serialization ---------------- */
298
+
299
+ _roomToStruct(room) {
300
+ const myUserId = this.client ? this.client.getUserId() : '';
301
+ const lastEvent = this._lastRelevantEvent(room);
302
+ const canonicalAlias = room.getCanonicalAlias();
303
+
304
+ return {
305
+ roomId: room.roomId,
306
+ name: room.name || canonicalAlias || room.roomId,
307
+ canonicalAlias,
308
+ topic: room.getTopic(),
309
+ memberCount: room.getJoinedMemberCount(),
310
+ unread: room.getUnreadNotificationCount('total') || 0,
311
+ avatarUrl: this._roomAvatar(room),
312
+ lastEvent: lastEvent ? this._eventToStruct(lastEvent, room) : null,
313
+ isDirect: Boolean(room.getType && this._isDirect(room)),
314
+ };
315
+ }
316
+
317
+ _isDirect(room) {
318
+ if (!this.client) return false;
319
+ const myId = this.client.getUserId();
320
+ const directMap = this.client.getAccountData('m.direct') || {};
321
+ const content = directMap.getContent ? directMap.getContent() : directMap;
322
+ const rooms = content[myId];
323
+ return Array.isArray(rooms) && rooms.includes(room.roomId);
324
+ }
325
+
326
+ _roomAvatar(room) {
327
+ try {
328
+ const url = room.getAvatarUrl(96, 96, 'crop', false, false);
329
+ if (!url) return null;
330
+ // getAvatarUrl normally returns a full http URL; fall back to mxc conversion.
331
+ return url.indexOf('mxc://') === 0 ? this._mxcToHttp(url) : url;
332
+ } catch (err) {
333
+ return null;
334
+ }
335
+ }
336
+
337
+ _lastRelevantEvent(room) {
338
+ const events = room.timeline || [];
339
+ for (let i = events.length - 1; i >= 0; i--) {
340
+ const ev = events[i];
341
+ const type = ev.getType();
342
+ // Skip pure bookkeeping state events so the preview is meaningful.
343
+ if (
344
+ type === 'm.room.canonical_alias' ||
345
+ type === 'm.room.join_rules' ||
346
+ type === 'm.room.power_levels' ||
347
+ type === 'm.room.avatar' ||
348
+ type === 'm.room.create'
349
+ ) {
350
+ continue;
351
+ }
352
+ return ev;
353
+ }
354
+ return null;
355
+ }
356
+
357
+ /* ---------------- Event serialization ---------------- */
358
+
359
+ _eventToStruct(event, room) {
360
+ const type = event.getType();
361
+ const content = event.getContent() || {};
362
+ const sender = event.getSender();
363
+ let struct = {
364
+ eventId: event.getId(),
365
+ type,
366
+ sender,
367
+ senderName: this.displayNameFor(sender),
368
+ senderAvatar: this.getUserAvatar(sender),
369
+ isSelf: Boolean(this.client && sender === this.client.getUserId()),
370
+ ts: event.getTs(),
371
+ relation: null,
372
+ editOf: null,
373
+ };
374
+
375
+ // Handle edits (m.replace)
376
+ if (content['m.new_content'] && event.getRelation && event.getRelation()) {
377
+ struct.editOf = event.getRelation().event_id;
378
+ struct = {
379
+ ...struct,
380
+ relation: event.getRelation(),
381
+ content: content['m.new_content'] || {},
382
+ };
383
+ } else {
384
+ struct.content = content;
385
+ }
386
+
387
+ if (event.isRedacted && event.isRedacted()) {
388
+ struct.redacted = true;
389
+ }
390
+
391
+ if (type === 'm.room.member') {
392
+ struct.membership = content.membership;
393
+ struct.target = event.getStateKey && event.getStateKey();
394
+ struct.prevMembership = event.getPrevContent && event.getPrevContent().membership;
395
+ struct.displayname = content.displayname;
396
+ }
397
+
398
+ if (room) {
399
+ struct.roomId = room.roomId;
400
+ const roomName = room.name || room.getCanonicalAlias();
401
+ struct.roomName = roomName;
402
+ }
403
+
404
+ return struct;
405
+ }
406
+
407
+ _memberToStruct(member) {
408
+ return {
409
+ userId: member.userId,
410
+ name: this._displayNameFor(member),
411
+ avatarUrl: this._mxcToHttp(member.getMxcAvatarUrl()),
412
+ membership: member.membership,
413
+ roomId: member.roomId,
414
+ };
415
+ }
416
+
417
+ _displayNameFor(member) {
418
+ if (member.name) return member.name;
419
+ return member.userId;
420
+ }
421
+
422
+ /* ---------------- MXC -> HTTP URLs ---------------- */
423
+
424
+ _mxcToHttp(mxc) {
425
+ if (!mxc || !this.client) return null;
426
+ try {
427
+ return this.client.mxcUrlToHttp(mxc, 96, 96, 'crop');
428
+ } catch (err) {
429
+ return null;
430
+ }
431
+ }
432
+
433
+ mxcToHttp(mxc, width, height) {
434
+ if (!mxc || !this.client) return null;
435
+ try {
436
+ return this.client.mxcUrlToHttp(mxc, width || 320, height || 240, 'scale');
437
+ } catch (err) {
438
+ return null;
439
+ }
440
+ }
441
+
442
+ /* ---------------- Room / timeline access ---------------- */
443
+
444
+ getRoom(roomId) {
445
+ return this.client ? this.client.getRoom(roomId) : null;
446
+ }
447
+
448
+ /**
449
+ * Return the live timeline events for a room as plain structs.
450
+ */
451
+ getRoomTimeline(roomId) {
452
+ const room = this.getRoom(roomId);
453
+ if (!room) return [];
454
+ const events = room.getLiveTimeline().getEvents() || [];
455
+ return events.map((ev) => this._eventToStruct(ev, room));
456
+ }
457
+
458
+ /* ---------------- Actions ---------------- */
459
+
460
+ async sendText(roomId, text) {
461
+ return this.client.sendTextMessage(roomId, text);
462
+ }
463
+
464
+ async uploadContent(file) {
465
+ return this.client.uploadContent(file, {
466
+ includeFilename: true,
467
+ type: file.type || 'application/octet-stream',
468
+ });
469
+ }
470
+
471
+ async sendFile(roomId, url, name, mime, size) {
472
+ return this.client.sendMessage(roomId, {
473
+ msgtype: 'm.file',
474
+ body: name,
475
+ filename: name,
476
+ url,
477
+ info: {
478
+ mimetype: mime,
479
+ size,
480
+ },
481
+ });
482
+ }
483
+
484
+ async sendAttachment(roomId, url, name, mime, size, msgtype) {
485
+ return this.client.sendMessage(roomId, {
486
+ msgtype,
487
+ body: name,
488
+ url,
489
+ info: {
490
+ mimetype: mime,
491
+ size,
492
+ },
493
+ });
494
+ }
495
+
496
+ async sendReaction(roomId, targetEventId, key) {
497
+ return this.client.sendEvent(roomId, 'm.reaction', {
498
+ 'm.relates_to': {
499
+ rel_type: 'm.annotation',
500
+ event_id: targetEventId,
501
+ key,
502
+ },
503
+ });
504
+ }
505
+
506
+ async createRoom(options) {
507
+ const opts = {
508
+ name: options.name || undefined,
509
+ visibility: options.visibility || 'private',
510
+ preset: options.visibility === 'public' ? 'public_chat' : 'private_chat',
511
+ invite: options.invite || [],
512
+ room_alias_name: options.alias ? this._extractAliasLocalpart(options.alias) : undefined,
513
+ initial_state: [],
514
+ };
515
+ const roomId = await this.client.createRoom(opts);
516
+ return roomId;
517
+ }
518
+
519
+ async joinRoom(roomIdOrAlias) {
520
+ const result = await this.client.joinRoom(roomIdOrAlias);
521
+ const id = typeof result === 'string' ? result : result.roomId;
522
+ return id;
523
+ }
524
+
525
+ async leaveRoom(roomId) {
526
+ await this.client.leave(roomId);
527
+ }
528
+
529
+ async inviteUser(roomId, userId) {
530
+ await this.client.invite(roomId, userId);
531
+ }
532
+
533
+ async acceptInvite(roomId) {
534
+ await this.client.joinRoom(roomId);
535
+ }
536
+
537
+ async markRoomRead(roomId) {
538
+ const room = this.client.getRoom(roomId);
539
+ if (!room) return;
540
+ const events = room.getLiveTimeline().getEvents();
541
+ const lastEvent = events[events.length - 1];
542
+ if (!lastEvent || lastEvent.getSender() === this.client.getUserId()) return;
543
+ this.client.sendReadReceipt(lastEvent, 'm.read').catch(() => {});
544
+ }
545
+
546
+ async logout() {
547
+ this.stopSync();
548
+ if (this.client && this.client.accessToken) {
549
+ try {
550
+ await this.client.logout();
551
+ } catch (err) {
552
+ // server might be unreachable; just clear locally
553
+ }
554
+ }
555
+ this.clearSession();
556
+ this.client = null;
557
+ }
558
+
559
+ _extractAliasLocalpart(alias) {
560
+ // "#myroom:server.com" -> "myroom"
561
+ return (alias || '').replace(/^#/, '').split(':')[0] || undefined;
562
+ }
563
+
564
+ _normalizeHomeserver(url) {
565
+ let base = (url || '').trim();
566
+ if (!base) throw new Error('Homeserver URL is required.');
567
+ if (!/^https?:\/\//i.test(base)) {
568
+ base = 'https://' + base;
569
+ }
570
+ return base.replace(/\/+$/, '');
571
+ }
572
+ }
573
+
574
+ window.MatrixService = MatrixService;
styles.css ADDED
@@ -0,0 +1,1148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg: #12141a;
3
+ --bg-elevated: #1a1d26;
4
+ --bg-panel: #171a21;
5
+ --bg-hover: #232733;
6
+ --bg-active: #2b303d;
7
+ --border: #2a2e3a;
8
+ --border-strong: #3a3f4d;
9
+ --text: #e6e8ee;
10
+ --text-muted: #9aa0ad;
11
+ --text-faint: #6b7280;
12
+ --accent: #0dbd8b;
13
+ --accent-hover: #0fa97d;
14
+ --accent-soft: rgba(13, 189, 139, 0.14);
15
+ --danger: #ef5350;
16
+ --danger-soft: rgba(239, 83, 80, 0.12);
17
+ --radius: 10px;
18
+ --radius-sm: 7px;
19
+ --shadow: 0 8px 28px rgba(0, 0, 0, 0.45);
20
+ --font: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
21
+ --mono: 'JetBrains Mono', 'Consolas', monospace;
22
+ }
23
+
24
+ * {
25
+ margin: 0;
26
+ padding: 0;
27
+ box-sizing: border-box;
28
+ }
29
+
30
+ html, body {
31
+ height: 100%;
32
+ }
33
+
34
+ body {
35
+ font-family: var(--font);
36
+ background: var(--bg);
37
+ color: var(--text);
38
+ font-size: 14px;
39
+ line-height: 1.5;
40
+ overflow: hidden;
41
+ }
42
+
43
+ ::-webkit-scrollbar {
44
+ width: 8px;
45
+ height: 8px;
46
+ }
47
+ ::-webkit-scrollbar-track {
48
+ background: transparent;
49
+ }
50
+ ::-webkit-scrollbar-thumb {
51
+ background: var(--border-strong);
52
+ border-radius: 4px;
53
+ }
54
+ ::-webkit-scrollbar-thumb:hover {
55
+ background: #4a5060;
56
+ }
57
+
58
+ .hidden {
59
+ display: none !important;
60
+ }
61
+
62
+ button {
63
+ font-family: var(--font);
64
+ cursor: pointer;
65
+ }
66
+
67
+ input, textarea, select {
68
+ font-family: var(--font);
69
+ font-size: 14px;
70
+ color: var(--text);
71
+ background: var(--bg);
72
+ border: 1px solid var(--border);
73
+ border-radius: var(--radius-sm);
74
+ padding: 10px 12px;
75
+ outline: none;
76
+ transition: border-color 0.15s;
77
+ width: 100%;
78
+ }
79
+
80
+ input:focus, textarea:focus, select:focus {
81
+ border-color: var(--accent);
82
+ }
83
+
84
+ input::placeholder, textarea::placeholder {
85
+ color: var(--text-faint);
86
+ }
87
+
88
+ label {
89
+ display: block;
90
+ font-size: 12px;
91
+ font-weight: 600;
92
+ color: var(--text-muted);
93
+ margin-bottom: 6px;
94
+ margin-top: 14px;
95
+ }
96
+
97
+ /* ======================= LOGIN VIEW ======================= */
98
+
99
+ .login-view {
100
+ height: 100vh;
101
+ display: flex;
102
+ align-items: center;
103
+ justify-content: center;
104
+ padding: 24px;
105
+ background:
106
+ radial-gradient(ellipse 80% 60% at 50% -20%, rgba(13, 189, 139, 0.12), transparent),
107
+ var(--bg);
108
+ }
109
+
110
+ .login-card {
111
+ width: 100%;
112
+ max-width: 420px;
113
+ background: var(--bg-elevated);
114
+ border: 1px solid var(--border);
115
+ border-radius: 16px;
116
+ padding: 36px 32px;
117
+ box-shadow: var(--shadow);
118
+ }
119
+
120
+ .login-logo {
121
+ width: 56px;
122
+ height: 56px;
123
+ border-radius: 14px;
124
+ background: linear-gradient(135deg, var(--accent), #059669);
125
+ color: white;
126
+ font-size: 28px;
127
+ font-weight: 700;
128
+ display: flex;
129
+ align-items: center;
130
+ justify-content: center;
131
+ margin: 0 auto 18px;
132
+ }
133
+
134
+ .login-card h1 {
135
+ text-align: center;
136
+ font-size: 22px;
137
+ font-weight: 700;
138
+ }
139
+
140
+ .login-subtitle {
141
+ text-align: center;
142
+ color: var(--text-muted);
143
+ font-size: 13px;
144
+ margin-bottom: 8px;
145
+ }
146
+
147
+ .login-tabs {
148
+ display: flex;
149
+ background: var(--bg);
150
+ border: 1px solid var(--border);
151
+ border-radius: var(--radius-sm);
152
+ padding: 3px;
153
+ margin-top: 20px;
154
+ }
155
+
156
+ .tab-btn {
157
+ flex: 1;
158
+ background: transparent;
159
+ border: none;
160
+ color: var(--text-muted);
161
+ font-size: 13px;
162
+ font-weight: 600;
163
+ padding: 8px;
164
+ border-radius: 5px;
165
+ transition: all 0.15s;
166
+ }
167
+
168
+ .tab-btn.active {
169
+ background: var(--accent-soft);
170
+ color: var(--accent);
171
+ }
172
+
173
+ .btn-primary {
174
+ width: 100%;
175
+ margin-top: 20px;
176
+ background: var(--accent);
177
+ border: none;
178
+ color: #fff;
179
+ font-weight: 600;
180
+ font-size: 14px;
181
+ padding: 11px;
182
+ border-radius: var(--radius-sm);
183
+ transition: background 0.15s;
184
+ }
185
+
186
+ .btn-primary:hover:not(:disabled) {
187
+ background: var(--accent-hover);
188
+ }
189
+
190
+ .btn-primary:disabled {
191
+ opacity: 0.6;
192
+ cursor: not-allowed;
193
+ }
194
+
195
+ .login-error {
196
+ margin-top: 14px;
197
+ color: var(--danger);
198
+ background: var(--danger-soft);
199
+ border: 1px solid rgba(239, 83, 80, 0.3);
200
+ border-radius: var(--radius-sm);
201
+ padding: 10px 12px;
202
+ font-size: 13px;
203
+ word-break: break-word;
204
+ }
205
+
206
+ .login-hint {
207
+ margin-top: 20px;
208
+ font-size: 12px;
209
+ color: var(--text-faint);
210
+ text-align: center;
211
+ line-height: 1.6;
212
+ }
213
+
214
+ .login-hint a {
215
+ color: var(--accent);
216
+ text-decoration: none;
217
+ }
218
+
219
+ /* ======================= APP LAYOUT ======================= */
220
+
221
+ .app-view {
222
+ display: flex;
223
+ height: 100vh;
224
+ }
225
+
226
+ .sidebar {
227
+ width: 280px;
228
+ flex-shrink: 0;
229
+ background: var(--bg-elevated);
230
+ border-right: 1px solid var(--border);
231
+ display: flex;
232
+ flex-direction: column;
233
+ }
234
+
235
+ .sidebar-user {
236
+ display: flex;
237
+ align-items: center;
238
+ gap: 10px;
239
+ padding: 14px 16px;
240
+ border-bottom: 1px solid var(--border);
241
+ }
242
+
243
+ .avatar {
244
+ width: 36px;
245
+ height: 36px;
246
+ border-radius: 50%;
247
+ background: linear-gradient(135deg, var(--accent), #059669);
248
+ color: white;
249
+ font-size: 15px;
250
+ font-weight: 700;
251
+ display: flex;
252
+ align-items: center;
253
+ justify-content: center;
254
+ flex-shrink: 0;
255
+ user-select: none;
256
+ }
257
+
258
+ .user-info {
259
+ flex: 1;
260
+ min-width: 0;
261
+ }
262
+
263
+ .user-name {
264
+ font-size: 13px;
265
+ font-weight: 600;
266
+ white-space: nowrap;
267
+ overflow: hidden;
268
+ text-overflow: ellipsis;
269
+ }
270
+
271
+ .user-id {
272
+ font-size: 11px;
273
+ color: var(--text-faint);
274
+ font-family: var(--mono);
275
+ white-space: nowrap;
276
+ overflow: hidden;
277
+ text-overflow: ellipsis;
278
+ }
279
+
280
+ .icon-btn {
281
+ background: transparent;
282
+ border: none;
283
+ color: var(--text-faint);
284
+ padding: 6px;
285
+ border-radius: var(--radius-sm);
286
+ display: flex;
287
+ align-items: center;
288
+ justify-content: center;
289
+ transition: all 0.15s;
290
+ }
291
+
292
+ .icon-btn:hover {
293
+ color: var(--danger);
294
+ background: var(--danger-soft);
295
+ }
296
+
297
+ .sidebar-actions {
298
+ display: flex;
299
+ gap: 8px;
300
+ padding: 12px 16px;
301
+ }
302
+
303
+ .action-btn {
304
+ flex: 1;
305
+ background: var(--accent-soft);
306
+ border: 1px solid rgba(13, 189, 139, 0.35);
307
+ color: var(--accent);
308
+ font-weight: 600;
309
+ font-size: 12px;
310
+ padding: 8px 10px;
311
+ border-radius: var(--radius-sm);
312
+ white-space: nowrap;
313
+ transition: all 0.15s;
314
+ }
315
+
316
+ .action-btn:hover {
317
+ background: var(--accent);
318
+ color: white;
319
+ }
320
+
321
+ .action-btn.secondary {
322
+ background: transparent;
323
+ border-color: var(--border);
324
+ color: var(--text-muted);
325
+ }
326
+
327
+ .action-btn.secondary:hover {
328
+ background: var(--bg-hover);
329
+ border-color: var(--border-strong);
330
+ color: var(--text);
331
+ }
332
+
333
+ .room-list-empty {
334
+ padding: 24px 16px;
335
+ text-align: center;
336
+ color: var(--text-faint);
337
+ font-size: 13px;
338
+ line-height: 1.5;
339
+ }
340
+
341
+ .room-search {
342
+ padding: 0 16px 10px;
343
+ }
344
+
345
+ .room-list {
346
+ flex: 1;
347
+ overflow-y: auto;
348
+ padding: 0 8px 8px;
349
+ }
350
+
351
+ .room-item {
352
+ display: flex;
353
+ align-items: center;
354
+ gap: 10px;
355
+ padding: 9px 10px;
356
+ border-radius: var(--radius-sm);
357
+ cursor: pointer;
358
+ transition: background 0.12s;
359
+ border: 1px solid transparent;
360
+ }
361
+
362
+ .room-item:hover {
363
+ background: var(--bg-hover);
364
+ }
365
+
366
+ .room-item.active {
367
+ background: var(--bg-active);
368
+ border-color: var(--border-strong);
369
+ }
370
+
371
+ .room-avatar {
372
+ width: 34px;
373
+ height: 34px;
374
+ border-radius: 50%;
375
+ background: #2b303d;
376
+ color: var(--text-muted);
377
+ font-size: 13px;
378
+ font-weight: 700;
379
+ display: flex;
380
+ align-items: center;
381
+ justify-content: center;
382
+ flex-shrink: 0;
383
+ user-select: none;
384
+ }
385
+
386
+ .room-info {
387
+ flex: 1;
388
+ min-width: 0;
389
+ }
390
+
391
+ .room-name {
392
+ font-size: 13px;
393
+ font-weight: 600;
394
+ white-space: nowrap;
395
+ overflow: hidden;
396
+ text-overflow: ellipsis;
397
+ }
398
+
399
+ .room-preview {
400
+ font-size: 11px;
401
+ color: var(--text-faint);
402
+ white-space: nowrap;
403
+ overflow: hidden;
404
+ text-overflow: ellipsis;
405
+ }
406
+
407
+ .room-meta {
408
+ display: flex;
409
+ flex-direction: column;
410
+ align-items: flex-end;
411
+ gap: 3px;
412
+ flex-shrink: 0;
413
+ }
414
+
415
+ .room-time {
416
+ font-size: 10px;
417
+ color: var(--text-faint);
418
+ }
419
+
420
+ .room-unread {
421
+ min-width: 18px;
422
+ height: 18px;
423
+ padding: 0 5px;
424
+ border-radius: 9px;
425
+ background: var(--accent);
426
+ color: white;
427
+ font-size: 10px;
428
+ font-weight: 700;
429
+ display: none;
430
+ align-items: center;
431
+ justify-content: center;
432
+ }
433
+
434
+ .room-unread.visible {
435
+ display: flex;
436
+ }
437
+
438
+ .sidebar-status {
439
+ display: flex;
440
+ align-items: center;
441
+ gap: 8px;
442
+ padding: 10px 16px;
443
+ border-top: 1px solid var(--border);
444
+ font-size: 12px;
445
+ color: var(--text-muted);
446
+ }
447
+
448
+ .status-dot {
449
+ width: 8px;
450
+ height: 8px;
451
+ border-radius: 50%;
452
+ background: #f59e0b;
453
+ flex-shrink: 0;
454
+ }
455
+
456
+ .sidebar-status.connected .status-dot {
457
+ background: var(--accent);
458
+ box-shadow: 0 0 6px rgba(13, 189, 139, 0.6);
459
+ }
460
+
461
+ .sidebar-status.error .status-dot {
462
+ background: var(--danger);
463
+ }
464
+
465
+ .sidebar-status.offline .status-dot {
466
+ background: #6b7280;
467
+ }
468
+
469
+ /* ======================= MAIN PANEL ======================= */
470
+
471
+ .main-panel {
472
+ flex: 1;
473
+ display: flex;
474
+ min-width: 0;
475
+ }
476
+
477
+ .empty-state {
478
+ flex: 1;
479
+ display: flex;
480
+ flex-direction: column;
481
+ align-items: center;
482
+ justify-content: center;
483
+ gap: 8px;
484
+ color: var(--text-muted);
485
+ }
486
+
487
+ .empty-logo {
488
+ width: 72px;
489
+ height: 72px;
490
+ border-radius: 18px;
491
+ background: linear-gradient(135deg, var(--accent), #059669);
492
+ color: white;
493
+ font-size: 36px;
494
+ font-weight: 700;
495
+ display: flex;
496
+ align-items: center;
497
+ justify-content: center;
498
+ margin-bottom: 12px;
499
+ opacity: 0.5;
500
+ }
501
+
502
+ .empty-state h2 {
503
+ color: var(--text);
504
+ font-size: 18px;
505
+ }
506
+
507
+ .empty-state p {
508
+ font-size: 13px;
509
+ max-width: 340px;
510
+ text-align: center;
511
+ }
512
+
513
+ .chat-panel {
514
+ flex: 1;
515
+ display: flex;
516
+ flex-direction: column;
517
+ min-width: 0;
518
+ }
519
+
520
+ .chat-header {
521
+ display: flex;
522
+ align-items: center;
523
+ gap: 12px;
524
+ padding: 12px 18px;
525
+ background: var(--bg-panel);
526
+ border-bottom: 1px solid var(--border);
527
+ }
528
+
529
+ .chat-room-meta {
530
+ flex: 1;
531
+ min-width: 0;
532
+ }
533
+
534
+ .chat-room-name {
535
+ font-size: 15px;
536
+ font-weight: 600;
537
+ white-space: nowrap;
538
+ overflow: hidden;
539
+ text-overflow: ellipsis;
540
+ }
541
+
542
+ .chat-room-topic {
543
+ font-size: 12px;
544
+ color: var(--text-faint);
545
+ white-space: nowrap;
546
+ overflow: hidden;
547
+ text-overflow: ellipsis;
548
+ }
549
+
550
+ .chat-room-count {
551
+ font-size: 12px;
552
+ color: var(--text-muted);
553
+ padding: 4px 10px;
554
+ background: var(--bg-hover);
555
+ border-radius: 12px;
556
+ white-space: nowrap;
557
+ }
558
+
559
+ /* ======================= TIMELINE ======================= */
560
+
561
+ .timeline {
562
+ flex: 1;
563
+ overflow-y: auto;
564
+ padding: 18px 22px;
565
+ display: flex;
566
+ flex-direction: column;
567
+ gap: 1px;
568
+ }
569
+
570
+ .day-divider {
571
+ display: flex;
572
+ align-items: center;
573
+ gap: 12px;
574
+ margin: 18px 0 10px;
575
+ color: var(--text-faint);
576
+ font-size: 11px;
577
+ font-weight: 600;
578
+ text-transform: uppercase;
579
+ letter-spacing: 0.05em;
580
+ }
581
+
582
+ .day-divider::before,
583
+ .day-divider::after {
584
+ content: '';
585
+ flex: 1;
586
+ height: 1px;
587
+ background: var(--border);
588
+ }
589
+
590
+ .msg {
591
+ display: flex;
592
+ gap: 10px;
593
+ padding: 4px 0;
594
+ }
595
+
596
+ .msg-avatar {
597
+ width: 32px;
598
+ height: 32px;
599
+ border-radius: 50%;
600
+ background: #2b303d;
601
+ color: var(--text-muted);
602
+ font-size: 13px;
603
+ font-weight: 700;
604
+ display: flex;
605
+ align-items: center;
606
+ justify-content: center;
607
+ flex-shrink: 0;
608
+ margin-top: 2px;
609
+ user-select: none;
610
+ }
611
+
612
+ .msg-body {
613
+ flex: 1;
614
+ min-width: 0;
615
+ }
616
+
617
+ .msg-head {
618
+ display: flex;
619
+ align-items: baseline;
620
+ gap: 8px;
621
+ margin-bottom: 1px;
622
+ }
623
+
624
+ .msg-sender {
625
+ font-size: 13px;
626
+ font-weight: 600;
627
+ color: var(--text);
628
+ }
629
+
630
+ .msg-sender.self {
631
+ color: var(--accent);
632
+ }
633
+
634
+ .msg-time {
635
+ font-size: 11px;
636
+ color: var(--text-faint);
637
+ }
638
+
639
+ .msg-content {
640
+ font-size: 14px;
641
+ color: var(--text);
642
+ word-wrap: break-word;
643
+ overflow-wrap: break-word;
644
+ }
645
+
646
+ .msg-content p {
647
+ margin: 0 0 6px;
648
+ }
649
+
650
+ .msg-content p:last-child {
651
+ margin-bottom: 0;
652
+ }
653
+
654
+ .msg-content a {
655
+ color: var(--accent);
656
+ text-decoration: none;
657
+ }
658
+
659
+ .msg-content a:hover {
660
+ text-decoration: underline;
661
+ }
662
+
663
+ .msg-caption {
664
+ font-size: 12px;
665
+ color: var(--text-muted);
666
+ margin-top: 2px;
667
+ }
668
+
669
+ .msg-notice-text {
670
+ color: var(--text-muted);
671
+ }
672
+
673
+ .msg-reply-indicator {
674
+ font-size: 11px;
675
+ color: var(--text-faint);
676
+ margin-bottom: 4px;
677
+ }
678
+
679
+ .msg-content pre {
680
+ background: var(--bg);
681
+ border: 1px solid var(--border);
682
+ border-radius: var(--radius-sm);
683
+ padding: 10px 12px;
684
+ overflow-x: auto;
685
+ font-family: var(--mono);
686
+ font-size: 12.5px;
687
+ margin: 6px 0;
688
+ }
689
+
690
+ .msg-content code {
691
+ font-family: var(--mono);
692
+ font-size: 12.5px;
693
+ background: var(--bg);
694
+ border: 1px solid var(--border);
695
+ border-radius: 4px;
696
+ padding: 1px 5px;
697
+ }
698
+
699
+ .msg-content pre code {
700
+ background: none;
701
+ border: none;
702
+ padding: 0;
703
+ }
704
+
705
+ .msg-content blockquote {
706
+ border-left: 3px solid var(--border-strong);
707
+ padding-left: 12px;
708
+ margin: 6px 0;
709
+ color: var(--text-muted);
710
+ }
711
+
712
+ .msg-content ul, .msg-content ol {
713
+ margin: 6px 0;
714
+ padding-left: 22px;
715
+ }
716
+
717
+ .msg-content img {
718
+ max-width: 320px;
719
+ max-height: 240px;
720
+ border-radius: var(--radius-sm);
721
+ display: block;
722
+ margin: 6px 0;
723
+ cursor: pointer;
724
+ border: 1px solid var(--border);
725
+ }
726
+
727
+ .msg-content video {
728
+ max-width: 380px;
729
+ max-height: 260px;
730
+ border-radius: var(--radius-sm);
731
+ display: block;
732
+ margin: 6px 0;
733
+ }
734
+
735
+ .msg-notice {
736
+ font-size: 12px;
737
+ color: var(--text-faint);
738
+ text-align: center;
739
+ padding: 5px 0;
740
+ }
741
+
742
+ .msg-file {
743
+ display: inline-flex;
744
+ align-items: center;
745
+ gap: 10px;
746
+ background: var(--bg);
747
+ border: 1px solid var(--border);
748
+ border-radius: var(--radius-sm);
749
+ padding: 10px 14px;
750
+ margin: 4px 0;
751
+ text-decoration: none;
752
+ color: var(--text);
753
+ transition: border-color 0.15s;
754
+ max-width: 100%;
755
+ }
756
+
757
+ .msg-file:hover {
758
+ border-color: var(--accent);
759
+ }
760
+
761
+ .msg-file-icon {
762
+ width: 36px;
763
+ height: 36px;
764
+ border-radius: 8px;
765
+ background: var(--accent-soft);
766
+ color: var(--accent);
767
+ display: flex;
768
+ align-items: center;
769
+ justify-content: center;
770
+ font-size: 16px;
771
+ flex-shrink: 0;
772
+ }
773
+
774
+ .msg-file-meta {
775
+ min-width: 0;
776
+ }
777
+
778
+ .msg-file-name {
779
+ font-size: 13px;
780
+ font-weight: 500;
781
+ white-space: nowrap;
782
+ overflow: hidden;
783
+ text-overflow: ellipsis;
784
+ }
785
+
786
+ .msg-file-size {
787
+ font-size: 11px;
788
+ color: var(--text-faint);
789
+ }
790
+
791
+ .msg-edited {
792
+ font-size: 11px;
793
+ color: var(--text-faint);
794
+ margin-left: 4px;
795
+ }
796
+
797
+ /* ---- Reactions ---- */
798
+
799
+ .msg-reactions {
800
+ display: flex;
801
+ flex-wrap: wrap;
802
+ gap: 6px;
803
+ margin-top: 6px;
804
+ }
805
+
806
+ .reaction-pill {
807
+ display: inline-flex;
808
+ align-items: center;
809
+ gap: 4px;
810
+ background: var(--bg);
811
+ border: 1px solid var(--border);
812
+ border-radius: 12px;
813
+ color: var(--text-muted);
814
+ font-size: 12px;
815
+ padding: 2px 9px;
816
+ transition: border-color 0.15s, color 0.15s;
817
+ }
818
+
819
+ .reaction-pill:hover {
820
+ border-color: var(--accent);
821
+ color: var(--accent);
822
+ }
823
+
824
+ .msg-actions {
825
+ position: relative;
826
+ opacity: 0;
827
+ transition: opacity 0.15s;
828
+ align-self: flex-start;
829
+ margin-top: 6px;
830
+ flex-shrink: 0;
831
+ }
832
+
833
+ .msg:hover .msg-actions {
834
+ opacity: 1;
835
+ }
836
+
837
+ .reaction-toggle {
838
+ width: 26px;
839
+ height: 26px;
840
+ border-radius: 50%;
841
+ border: 1px solid var(--border);
842
+ background: var(--bg);
843
+ color: var(--text-muted);
844
+ font-size: 14px;
845
+ line-height: 1;
846
+ display: flex;
847
+ align-items: center;
848
+ justify-content: center;
849
+ transition: all 0.15s;
850
+ }
851
+
852
+ .reaction-toggle:hover {
853
+ border-color: var(--accent);
854
+ color: var(--accent);
855
+ }
856
+
857
+ .reaction-menu {
858
+ position: absolute;
859
+ top: 34px;
860
+ left: 0;
861
+ z-index: 20;
862
+ display: flex;
863
+ gap: 4px;
864
+ background: var(--bg-elevated);
865
+ border: 1px solid var(--border-strong);
866
+ border-radius: var(--radius-sm);
867
+ padding: 6px;
868
+ box-shadow: var(--shadow);
869
+ }
870
+
871
+ .reaction-option {
872
+ width: 32px;
873
+ height: 32px;
874
+ border: none;
875
+ background: transparent;
876
+ border-radius: 6px;
877
+ font-size: 17px;
878
+ display: flex;
879
+ align-items: center;
880
+ justify-content: center;
881
+ transition: background 0.12s;
882
+ }
883
+
884
+ .reaction-option:hover {
885
+ background: var(--bg-hover);
886
+ }
887
+
888
+ /* ---- Load earlier ---- */
889
+
890
+ .load-earlier {
891
+ align-self: center;
892
+ background: var(--bg);
893
+ border: 1px solid var(--border);
894
+ color: var(--text-muted);
895
+ font-size: 12px;
896
+ font-weight: 500;
897
+ padding: 7px 14px;
898
+ border-radius: 16px;
899
+ margin-bottom: 14px;
900
+ transition: all 0.15s;
901
+ }
902
+
903
+ .load-earlier:hover:not(:disabled) {
904
+ border-color: var(--accent);
905
+ color: var(--accent);
906
+ }
907
+
908
+ .load-earlier:disabled {
909
+ opacity: 0.5;
910
+ cursor: not-allowed;
911
+ }
912
+
913
+ .sending {
914
+ opacity: 0.6;
915
+ }
916
+
917
+ .failed {
918
+ opacity: 0.7;
919
+ }
920
+
921
+ .failed .msg-content {
922
+ color: var(--danger);
923
+ }
924
+
925
+ /* ======================= COMPOSER ======================= */
926
+
927
+ .composer {
928
+ display: flex;
929
+ align-items: flex-end;
930
+ gap: 10px;
931
+ padding: 12px 18px;
932
+ background: var(--bg-panel);
933
+ border-top: 1px solid var(--border);
934
+ }
935
+
936
+ .attach-btn {
937
+ flex-shrink: 0;
938
+ margin-bottom: 8px;
939
+ color: var(--text-muted);
940
+ }
941
+
942
+ .attach-btn:hover {
943
+ color: var(--accent);
944
+ background: var(--accent-soft);
945
+ }
946
+
947
+ .composer textarea {
948
+ flex: 1;
949
+ resize: none;
950
+ max-height: 140px;
951
+ background: var(--bg);
952
+ border-radius: 12px;
953
+ padding: 11px 14px;
954
+ line-height: 1.4;
955
+ }
956
+
957
+ .send-btn {
958
+ width: 40px;
959
+ height: 40px;
960
+ flex-shrink: 0;
961
+ border-radius: 50%;
962
+ border: none;
963
+ background: var(--accent);
964
+ color: white;
965
+ display: flex;
966
+ align-items: center;
967
+ justify-content: center;
968
+ transition: all 0.15s;
969
+ }
970
+
971
+ .send-btn:hover:not(:disabled) {
972
+ background: var(--accent-hover);
973
+ transform: scale(1.05);
974
+ }
975
+
976
+ .send-btn:disabled {
977
+ opacity: 0.5;
978
+ cursor: not-allowed;
979
+ }
980
+
981
+ /* ======================= MODALS ======================= */
982
+
983
+ .modal-overlay {
984
+ position: fixed;
985
+ inset: 0;
986
+ background: rgba(0, 0, 0, 0.6);
987
+ backdrop-filter: blur(2px);
988
+ display: flex;
989
+ align-items: center;
990
+ justify-content: center;
991
+ z-index: 100;
992
+ }
993
+
994
+ .modal {
995
+ width: 100%;
996
+ max-width: 400px;
997
+ background: var(--bg-elevated);
998
+ border: 1px solid var(--border-strong);
999
+ border-radius: 14px;
1000
+ padding: 24px;
1001
+ box-shadow: var(--shadow);
1002
+ }
1003
+
1004
+ .modal h2 {
1005
+ font-size: 17px;
1006
+ margin-bottom: 4px;
1007
+ }
1008
+
1009
+ .modal-actions {
1010
+ display: flex;
1011
+ gap: 10px;
1012
+ margin-top: 24px;
1013
+ }
1014
+
1015
+ .modal-actions .btn-primary {
1016
+ margin-top: 0;
1017
+ width: auto;
1018
+ padding: 10px 18px;
1019
+ }
1020
+
1021
+ .btn-ghost {
1022
+ background: transparent;
1023
+ border: 1px solid var(--border);
1024
+ color: var(--text-muted);
1025
+ padding: 10px 18px;
1026
+ border-radius: var(--radius-sm);
1027
+ font-weight: 600;
1028
+ font-size: 13px;
1029
+ transition: all 0.15s;
1030
+ }
1031
+
1032
+ .btn-ghost:hover {
1033
+ background: var(--bg-hover);
1034
+ color: var(--text);
1035
+ }
1036
+
1037
+ .modal-error {
1038
+ margin-top: 12px;
1039
+ color: var(--danger);
1040
+ background: var(--danger-soft);
1041
+ border: 1px solid rgba(239, 83, 80, 0.3);
1042
+ border-radius: var(--radius-sm);
1043
+ padding: 8px 10px;
1044
+ font-size: 13px;
1045
+ word-break: break-word;
1046
+ }
1047
+
1048
+ /* ======================= TOASTS ======================= */
1049
+
1050
+ .toast-container {
1051
+ position: fixed;
1052
+ bottom: 20px;
1053
+ left: 50%;
1054
+ transform: translateX(-50%);
1055
+ display: flex;
1056
+ flex-direction: column;
1057
+ gap: 8px;
1058
+ z-index: 200;
1059
+ pointer-events: none;
1060
+ }
1061
+
1062
+ .toast {
1063
+ background: var(--bg-elevated);
1064
+ border: 1px solid var(--border-strong);
1065
+ border-left: 3px solid var(--accent);
1066
+ color: var(--text);
1067
+ padding: 12px 18px;
1068
+ border-radius: var(--radius-sm);
1069
+ font-size: 13px;
1070
+ box-shadow: var(--shadow);
1071
+ max-width: 420px;
1072
+ animation: toast-in 0.25s ease;
1073
+ }
1074
+
1075
+ .toast.error {
1076
+ border-left-color: var(--danger);
1077
+ }
1078
+
1079
+ .toast-actions {
1080
+ display: flex;
1081
+ gap: 8px;
1082
+ margin-top: 10px;
1083
+ }
1084
+
1085
+ .toast-btn {
1086
+ background: var(--accent);
1087
+ border: none;
1088
+ color: white;
1089
+ font-size: 12px;
1090
+ font-weight: 600;
1091
+ padding: 6px 12px;
1092
+ border-radius: var(--radius-sm);
1093
+ transition: background 0.15s;
1094
+ }
1095
+
1096
+ .toast-btn:hover {
1097
+ background: var(--accent-hover);
1098
+ }
1099
+
1100
+ .toast-actions .toast-btn:last-child {
1101
+ background: transparent;
1102
+ border: 1px solid var(--border-strong);
1103
+ color: var(--text-muted);
1104
+ }
1105
+
1106
+ .toast-actions .toast-btn:last-child:hover {
1107
+ background: var(--bg-hover);
1108
+ color: var(--text);
1109
+ }
1110
+
1111
+ @keyframes toast-in {
1112
+ from {
1113
+ opacity: 0;
1114
+ transform: translateY(10px);
1115
+ }
1116
+ to {
1117
+ opacity: 1;
1118
+ transform: translateY(0);
1119
+ }
1120
+ }
1121
+
1122
+ /* ======================= RESPONSIVE ======================= */
1123
+
1124
+ @media (max-width: 720px) {
1125
+ .sidebar {
1126
+ width: 220px;
1127
+ }
1128
+ .sidebar-actions {
1129
+ flex-direction: column;
1130
+ }
1131
+ }
1132
+
1133
+ @media (max-width: 540px) {
1134
+ .sidebar {
1135
+ width: 100%;
1136
+ max-height: 40vh;
1137
+ border-right: none;
1138
+ border-bottom: 1px solid var(--border);
1139
+ }
1140
+ .app-view {
1141
+ flex-direction: column;
1142
+ }
1143
+
1144
+ .msg-content img,
1145
+ .msg-content video {
1146
+ max-width: 100%;
1147
+ }
1148
+ }