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

Delete js

Browse files
Files changed (2) hide show
  1. js/app.js +0 -1299
  2. js/matrix-service.js +0 -574
js/app.js DELETED
@@ -1,1299 +0,0 @@
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 DELETED
@@ -1,574 +0,0 @@
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;