atagen

malice

public
Star0
Watch0
df3c0f2b3da49cedd2da20209bd76e39695179bc
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte1422 lines51.2 KB
1
<script lang="ts">
2
  import { onMount, tick } from 'svelte';
3
  import LoginPanel from './lib/LoginPanel.svelte';
4
  import MessageRow from './lib/MessageRow.svelte';
5
  import MxcAvatar from './lib/MxcAvatar.svelte';
6
  import SecurityPanel from './lib/SecurityPanel.svelte';
7
  import {
8
    closeRoom,
9
    createRoom,
10
    getEncryption,
11
    getMembers,
12
    getProfile,
13
    getRooms,
14
    getSession,
15
    getSpaceChildren,
16
    joinRoom,
17
    leaveRoom,
18
    logout,
19
    markRead,
20
    openRoom,
21
    paginateRoom,
22
    reactToMessage,
23
    uploadAttachment
24
  } from './lib/api';
25
  import {
26
    banners,
27
    blocked,
28
    connectEvents,
29
    connection,
30
    disconnectEvents,
31
    dismissBanner,
32
    encryption,
33
    membersByRoom,
34
    membersLoading,
35
    pushBanner,
36
    imagePacks,
37
    resetClientState,
38
    rooms,
39
    selectedRoomId,
40
    sessionUser,
41
    softLogout,
42
    timelines,
43
    verification
44
  } from './lib/store';
45
  import { discardPending, pendingByRoom, queueSend, resetPending, retryPending } from './lib/pending';
46
  import type { PendingMessage } from './lib/pending';
47
  import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions';
48
  import {
49
    linkPreviews,
50
    loadUrlPreviewSettings,
51
    requestLinkPreview,
52
    saveUrlPreviewSettings,
53
    urlPreviewSettings
54
  } from './lib/link-previews';
55
  import { notifyTyping, stopTyping } from './lib/typing';
56
  import { formatDay } from './lib/format';
57
  import { lineHeight, messageSpacing, navFolded } from './lib/appearance';
58
  import SettingsPanel from './lib/SettingsPanel.svelte';
59
  import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types';
60
  import type { MemberSummary, OwnProfile, Person, QuickReaction, ReplyReference, RoomSummary, SendState, TimelineEvent, TimelineItem } from './lib/types';
61
62
  let roomsLoading = false;
63
  let booted = false;
64
  let wasOnline = false;
65
  let search = '';
66
  let sidebarOpen = false;
67
  let membersOpen = false;
68
  let replyingTo: ReplyReference | null = null;
69
  let dialog: 'join' | 'create' | 'security' | 'settings' | null = null;
70
  let joinTarget = '';
71
  let joinBusy = false;
72
  let createName = '';
73
  let createTopic = '';
74
  let createBusy = false;
75
  let leaveBusy = false;
76
  let paginateBusy = false;
77
  let reacting = false;
78
  let composer = '';
79
  let drafts: Record<string, string> = {};
80
  let stickToBottom = true;
81
  let timelineEl: HTMLElement | null = null;
82
  let composerEl: HTMLTextAreaElement | null = null;
83
  let fileInput: HTMLInputElement | null = null;
84
  let uploadBusy = false;
85
  let uploadName: string | null = null;
86
  let openedRoom: string | null = null;
87
  let openReady: Record<string, boolean> = {};
88
  let openFailed: Record<string, string> = {};
89
  let membersFor: string | null = null;
90
  let lastReadKey = '';
91
  let readTimer: number | null = null;
92
  let profile: OwnProfile | null = null;
93
  let profileMxc: string | null = null;
94
  let selectedSpaceId: string | null = null;
95
  let spaceChildIds: string[] | null = null;
96
  let spaceChildrenLoading = false;
97
  let spaceChildrenError: string | null = null;
98
  let avatarByUser: Record<string, string | null> = {};
99
100
  // account data is read from the local cache, which is empty on a fresh device until the first sync lands
101
  $: {
102
    const online = $connection === 'online';
103
    if (online && !wasOnline) {
104
      void loadQuickReactions();
105
      void loadUrlPreviewSettings();
106
    }
107
    wasOnline = online;
108
  }
109
  $: selectedRoom = $rooms.find((r) => r.room_id === $selectedRoomId) ?? null;
110
  $: roomPacks = packsForRoom($imagePacks, $selectedRoomId);
111
  $: previewsAllowed = selectedRoom !== null && (!selectedRoom.encrypted || $urlPreviewSettings.encrypted_rooms);
112
  $: loadPreview = previewsAllowed && $selectedRoomId ? previewLoader($selectedRoomId) : null;
113
  $: spaceRooms = $rooms.filter((r) => r.space);
114
  $: invites = $rooms.filter((r) => r.membership === 'Invited');
115
  $: query = search.trim().toLowerCase();
116
  $: selectedSpace = selectedSpaceId ? ($rooms.find((r) => r.room_id === selectedSpaceId) ?? null) : null;
117
  // While a space's children load (or fail), show no channels rather than the
118
  // full list — listing everything would falsely imply it belongs to the space.
119
  $: baseRooms = selectedSpaceId ? (spaceChildIds ? $rooms.filter((r) => spaceChildIds.includes(r.room_id)) : []) : $rooms;
120
  $: visibleRooms = query
121
    ? baseRooms.filter(
122
        (r) =>
123
          r.name.toLowerCase().includes(query) || r.room_id.toLowerCase().includes(query)
124
      )
125
    : baseRooms;
126
  $: directRooms = visibleRooms.filter((r) => r.direct && !r.space && r.membership !== 'Invited');
127
  $: groupRooms = visibleRooms.filter(
128
    (r) => !r.direct && !r.space && r.membership !== 'Invited'
129
  );
130
  $: spaceList = visibleRooms.filter((r) => r.space && r.membership !== 'Invited');
131
  $: channelRooms = baseRooms.filter((r) => !r.space && r.membership !== 'Invited');
132
  $: recoveryBanner = $encryption && ($encryption.recovery === 'Disabled' || $encryption.recovery === 'Incomplete') ? $encryption : null;
133
  $: verificationBanner = $verification && $verification.kind !== 'Done' ? $verification : null;
134
  $: items = $selectedRoomId ? ($timelines[$selectedRoomId] ?? []) : [];
135
  $: members = $selectedRoomId ? ($membersByRoom[$selectedRoomId] ?? []) : [];
136
  $: people = peopleIn(items, members);
137
  $: hasStart = items.some((i) => i.kind === 'start');
138
  $: grouped = buildGroups(items);
139
  $: lastSentId = lastOwnSent(items);
140
  $: pendingItems = $selectedRoomId ? ($pendingByRoom[$selectedRoomId] ?? []) : [];
141
  $: lastRealOwn = lastSenderIsOwn(items);
142
143
  function lastSenderIsOwn(list: TimelineItem[]): boolean {
144
    for (let i = list.length - 1; i >= 0; i -= 1) {
145
      const it = list[i];
146
      if (it.kind === 'event') return it.event.sender.user_id === $sessionUser;
147
    }
148
    return false;
149
  }
150
151
  function pendingShowSender(index: number): boolean {
152
    return index === 0 ? !lastRealOwn : false;
153
  }
154
155
  function pendingToEvent(p: PendingMessage): TimelineEvent {
156
    const state: SendState = p.status === 'failed' ? { kind: 'Failed', will_retry: false } : { kind: 'Sending' };
157
    return {
158
      item_id: `pending-${p.id}`,
159
      event_id: null,
160
      transaction_id: p.id,
161
      sender: {
162
        user_id: $sessionUser ?? '',
163
        display_name: profile?.display_name ?? null,
164
        avatar: null,
165
        name_ambiguous: false
166
      },
167
      timestamp_ms: p.createdAt,
168
      own: true,
169
      send_state: state,
170
      content: {
171
        kind: 'Message',
172
        message: { kind: 'Text', body: p.body, geo_uri: null, formatted_body: null, edited: false, media: null }
173
      },
174
      reply_to: p.replyTo,
175
      thread_root: null,
176
      thread_summary: null,
177
      reactions: [],
178
      read_by: [],
179
      editable: false
180
    };
181
  }
182
183
  interface Group {
184
    key: string;
185
    item: TimelineItem;
186
    showSender: boolean;
187
  }
188
189
  function lastOwnSent(list: TimelineItem[]): string | null {
190
    for (let i = list.length - 1; i >= 0; i--) {
191
      const item = list[i];
192
      if (item.kind === 'event' && item.event.own && item.event.send_state.kind === 'Sent') return item.event.item_id;
193
    }
194
    return null;
195
  }
196
197
  function buildGroups(list: TimelineItem[]): Group[] {
198
    const out: Group[] = [];
199
    let prevSender: string | null = null;
200
    let prevTs = 0;
201
    list.forEach((item, index) => {
202
      let showSender = true;
203
      if (item.kind === 'event') {
204
        const e = item.event;
205
        showSender =
206
          prevSender !== e.sender.user_id || Math.abs(e.timestamp_ms - prevTs) > 5 * 60 * 1000;
207
        prevSender = e.sender.user_id;
208
        prevTs = e.timestamp_ms;
209
        out.push({ key: e.item_id || e.event_id || `m-${index}`, item, showSender });
210
      } else {
211
        prevSender = null;
212
        out.push({ key: `${item.kind}-${index}`, item, showSender });
213
      }
214
    });
215
    return out;
216
  }
217
218
  function roomUnread(r: RoomSummary): number {
219
    return r.unread_messages + r.unread_mentions;
220
  }
221
222
  onMount(() => {
223
    void boot();
224
    return () => {
225
      disconnectEvents();
226
      stopTyping();
227
      if (readTimer !== null) window.clearTimeout(readTimer);
228
    };
229
  });
230
231
  async function boot(): Promise<void> {
232
    try {
233
      const session = await getSession();
234
      blocked.set(session.blocked ?? false);
235
      sessionUser.set(session.user_id);
236
      if (session.user_id) {
237
        softLogout.set(null);
238
        await refreshRooms();
239
        connectEvents();
240
        void loadProfile();
241
        void loadEncryption();
242
        void loadQuickReactions();
243
        void loadUrlPreviewSettings();
244
      } else {
245
        softLogout.set(session.soft_logout ?? null);
246
      }
247
    } catch (e) {
248
      pushBanner(e instanceof Error ? `Session check failed: ${e.message}` : 'Session check failed');
249
      sessionUser.set(null);
250
    } finally {
251
      booted = true;
252
    }
253
  }
254
255
  async function refreshRooms(): Promise<void> {
256
    roomsLoading = true;
257
    try {
258
      const res = await getRooms();
259
      rooms.set(res.rooms);
260
      pruneSpaceFilter();
261
    } catch (e) {
262
      pushBanner(e instanceof Error ? e.message : 'Could not load rooms');
263
    } finally {
264
      roomsLoading = false;
265
    }
266
  }
267
268
  async function loadProfile(): Promise<void> {
269
    try {
270
      const raw = await getProfile();
271
      profile = parseOwnProfile(raw);
272
      profileMxc = profile.avatar_url;
273
    } catch {
274
      profile = null;
275
    }
276
  }
277
278
  async function loadEncryption(): Promise<void> {
279
    try {
280
      const res = await getEncryption();
281
      const state = parseEncryptionState(res.state);
282
      if (state) encryption.set(state);
283
      const verificationState = parseVerificationState(res.verification);
284
      if (verificationState) verification.set(verificationState);
285
    } catch {
286
      // Encryption status also arrives over SSE; a failed first fetch is not fatal.
287
    }
288
  }
289
290
  function afterLogin(userId: string): void {
291
    sessionUser.set(userId);
292
    softLogout.set(null);
293
    blocked.set(false);
294
    void refreshRooms();
295
    connectEvents();
296
    void loadProfile();
297
    void loadEncryption();
298
    void loadQuickReactions();
299
    void loadUrlPreviewSettings();
300
  }
301
302
  async function doLogout(): Promise<void> {
303
    stopTyping();
304
    try {
305
      await logout();
306
    } catch (e) {
307
      pushBanner(e instanceof Error ? e.message : 'Logout failed');
308
      return;
309
    }
310
    disconnectEvents();
311
    resetClientState();
312
    softLogout.set(null);
313
    blocked.set(false);
314
    sessionUser.set(null);
315
    composer = '';
316
    drafts = {};
317
    dialog = null;
318
    membersOpen = false;
319
    sidebarOpen = false;
320
    profile = null;
321
    profileMxc = null;
322
    selectedSpaceId = null;
323
    spaceChildIds = null;
324
    spaceChildrenError = null;
325
    openReady = {};
326
    openFailed = {};
327
    avatarByUser = {};
328
    resetPending();
329
  }
330
331
  function pruneSpaceFilter(): void {
332
    if (!selectedSpaceId) return;
333
    if (!$rooms.some((r) => r.room_id === selectedSpaceId)) {
334
      selectedSpaceId = null;
335
      spaceChildIds = null;
336
      spaceChildrenError = null;
337
    }
338
  }
339
340
  async function selectHome(): Promise<void> {
341
    selectedSpaceId = null;
342
    spaceChildIds = null;
343
    spaceChildrenError = null;
344
    sidebarOpen = true;
345
  }
346
347
  async function selectSpace(spaceId: string): Promise<void> {
348
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
349
    stopTyping();
350
    const prev = openedRoom;
351
    if (prev) {
352
      openedRoom = null;
353
      closeRoom(prev).catch(() => undefined);
354
    }
355
    selectedSpaceId = spaceId;
356
    spaceChildIds = null;
357
    spaceChildrenError = null;
358
    spaceChildrenLoading = true;
359
    sidebarOpen = true;
360
    // A space is navigation, not a message timeline.
361
    selectedRoomId.set(null);
362
    try {
363
      const res = await getSpaceChildren(spaceId);
364
      if (selectedSpaceId === spaceId) spaceChildIds = res.room_ids ?? [];
365
    } catch (e) {
366
      if (selectedSpaceId === spaceId) {
367
        spaceChildrenError = e instanceof Error ? e.message : 'Could not load rooms in this space';
368
        spaceChildIds = [];
369
      }
370
    } finally {
371
      if (selectedSpaceId === spaceId) spaceChildrenLoading = false;
372
    }
373
  }
374
375
  async function selectRoom(roomId: string): Promise<void> {
376
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
377
    if (roomId === $selectedRoomId && openReady[roomId]) {
378
      sidebarOpen = false;
379
      return;
380
    }
381
    stopTyping();
382
    const prev = openedRoom;
383
    openedRoom = roomId;
384
    selectedRoomId.set(roomId);
385
    composer = drafts[roomId] ?? '';
386
    replyingTo = null;
387
    stickToBottom = true;
388
    lastReadKey = '';
389
    sidebarOpen = false;
390
    openReady = { ...openReady, [roomId]: false };
391
    if (openFailed[roomId]) {
392
      const nextFailed = { ...openFailed };
393
      delete nextFailed[roomId];
394
      openFailed = nextFailed;
395
    }
396
    try {
397
      await openRoom(roomId);
398
      openReady = { ...openReady, [roomId]: true };
399
    } catch (e) {
400
      const message = e instanceof Error ? e.message : `Could not open room ${roomId}`;
401
      openFailed = { ...openFailed, [roomId]: message };
402
      pushBanner(message);
403
    }
404
    if (membersOpen) void loadMembers(roomId);
405
    await tick();
406
    scrollToBottom();
407
    queueReadReceipt();
408
    composerEl?.focus();
409
  }
410
411
  function scrollToBottom(): void {
412
    if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight;
413
  }
414
415
  function onTimelineScroll(): void {
416
    if (!timelineEl) return;
417
    const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight;
418
    stickToBottom = gap < 80;
419
  }
420
421
  $: void trackTimeline($selectedRoomId, items);
422
  async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> {
423
    if (!roomId || list.length === 0) return;
424
    if (roomId !== $selectedRoomId) return;
425
    await tick();
426
    if (stickToBottom) scrollToBottom();
427
    queueReadReceipt();
428
  }
429
430
  function queueReadReceipt(): void {
431
    if (readTimer !== null) window.clearTimeout(readTimer);
432
    readTimer = window.setTimeout(() => {
433
      readTimer = null;
434
      void sendReadReceipt();
435
    }, 800);
436
  }
437
438
  async function sendReadReceipt(): Promise<void> {
439
    const roomId = $selectedRoomId;
440
    if (!roomId) return;
441
    const list = $timelines[roomId] ?? [];
442
    for (let i = list.length - 1; i >= 0; i -= 1) {
443
      const entry = list[i];
444
      if (entry.kind === 'event' && entry.event.event_id) {
445
        const key = `${roomId}:${entry.event.event_id}`;
446
        if (key === lastReadKey) return;
447
        lastReadKey = key;
448
        try {
449
          await markRead(roomId, entry.event.event_id);
450
        } catch {
451
          return;
452
        }
453
        return;
454
      }
455
    }
456
  }
457
458
  function send(): void {
459
    const roomId = $selectedRoomId;
460
    const body = composer.trim();
461
    if (!roomId || !body) return;
462
    if (!openReady[roomId]) {
463
      pushBanner('Still opening this room — sending is disabled until the room is ready.');
464
      return;
465
    }
466
    composer = '';
467
    if (roomId in drafts) delete drafts[roomId];
468
    stickToBottom = true;
469
    queueSend(roomId, body, replyingTo);
470
    replyingTo = null;
471
    composerEl?.focus();
472
  }
473
474
  function startReply(target: ReplyReference): void {
475
    replyingTo = target;
476
    composerEl?.focus();
477
  }
478
479
  function jumpTo(eventId: string): void {
480
    const el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
481
    if (!el) {
482
      pushBanner('The original message is not loaded. Scroll up to load older messages.');
483
      return;
484
    }
485
    stickToBottom = false;
486
    el.scrollIntoView({ block: 'center', behavior: 'smooth' });
487
    el.classList.remove('flash');
488
    void el.offsetWidth;
489
    el.classList.add('flash');
490
  }
491
492
  let typedText = '';
493
  let typedRoom: string | null = null;
494
  $: trackTypingInput(composer, $selectedRoomId, openReady);
495
  function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void {
496
    const edited = roomId === typedRoom && text !== typedText;
497
    typedText = text;
498
    typedRoom = roomId;
499
    if (!roomId || !ready[roomId] || !text.trim()) {
500
      stopTyping();
501
    } else if (edited) {
502
      notifyTyping(roomId);
503
    }
504
  }
505
506
  $: void trackPending($selectedRoomId, pendingItems);
507
  async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> {
508
    if (!roomId || list.length === 0) return;
509
    if (roomId !== $selectedRoomId) return;
510
    await tick();
511
    if (stickToBottom) scrollToBottom();
512
  }
513
514
  function onComposerKey(ev: KeyboardEvent): void {
515
    if (ev.key === 'Enter' && !ev.shiftKey) {
516
      ev.preventDefault();
517
      send();
518
    } else if (ev.key === 'Escape' && replyingTo) {
519
      ev.stopPropagation();
520
      replyingTo = null;
521
    }
522
  }
523
524
  async function upload(): Promise<void> {
525
    const roomId = $selectedRoomId;
526
    if (!roomId || uploadBusy || !openReady[roomId]) return;
527
    fileInput?.click();
528
  }
529
530
  async function onFileChosen(): Promise<void> {
531
    const file = fileInput?.files?.[0];
532
    if (file) await uploadFile(file);
533
    if (fileInput) fileInput.value = '';
534
  }
535
536
  function onComposerPaste(ev: ClipboardEvent): void {
537
    const data = ev.clipboardData;
538
    // Office apps put a rendered image next to the copied text, so only take the image when there is no plain text.
539
    if (!data || data.types.includes('text/plain')) return;
540
    const image = Array.from(data.files).find((f) => f.type.startsWith('image/'));
541
    if (!image) return;
542
    ev.preventDefault();
543
    void uploadFile(image);
544
  }
545
546
  async function uploadFile(file: File): Promise<void> {
547
    const roomId = $selectedRoomId;
548
    if (!roomId || uploadBusy || !openReady[roomId]) return;
549
    if (file.size === 0 || file.size > 20 * 1024 * 1024) {
550
      pushBanner('File must be between 1 byte and 20 MiB.');
551
      return;
552
    }
553
    uploadBusy = true;
554
    uploadName = file.name || 'attachment';
555
    try {
556
      await uploadAttachment(roomId, file);
557
      stickToBottom = true;
558
    } catch (e) {
559
      pushBanner(e instanceof Error ? e.message : 'Upload failed');
560
    } finally {
561
      uploadBusy = false;
562
      uploadName = null;
563
    }
564
  }
565
  async function react(eventId: string, key: string, shortcode?: string): Promise<void> {
566
    const roomId = $selectedRoomId;
567
    if (!roomId || !eventId || reacting) return;
568
    reacting = true;
569
    try {
570
      await reactToMessage(roomId, eventId, key, shortcode);
571
    } catch (e) {
572
      pushBanner(e instanceof Error ? e.message : 'Reaction failed');
573
    } finally {
574
      reacting = false;
575
    }
576
  }
577
578
  function previewLoader(roomId: string): (url: string) => void {
579
    return (url) => requestLinkPreview(roomId, url);
580
  }
581
582
  async function changeEncryptedPreviews(enabled: boolean): Promise<void> {
583
    try {
584
      await saveUrlPreviewSettings({ encrypted_rooms: enabled });
585
    } catch (e) {
586
      pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting');
587
    }
588
  }
589
590
  async function changeQuickReactions(list: QuickReaction[]): Promise<void> {
591
    try {
592
      await saveQuickReactions(list);
593
    } catch (e) {
594
      pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions');
595
    }
596
  }
597
598
  async function paginate(): Promise<void> {
599
    const roomId = $selectedRoomId;
600
    if (!roomId || paginateBusy) return;
601
    paginateBusy = true;
602
    try {
603
      await paginateRoom(roomId);
604
    } catch (e) {
605
      pushBanner(e instanceof Error ? e.message : 'Loading older messages failed');
606
    } finally {
607
      paginateBusy = false;
608
    }
609
  }
610
611
  async function loadMembers(roomId: string): Promise<void> {
612
    if (membersFor === roomId && $membersLoading) return;
613
    membersFor = roomId;
614
    membersLoading.set(true);
615
    try {
616
      const res = await getMembers(roomId);
617
      membersByRoom.update((all) => ({ ...all, [roomId]: res.members }));
618
      avatarByUser = { ...avatarByUser, ...avatarMap(res.members) };
619
    } catch (e) {
620
      pushBanner(e instanceof Error ? e.message : 'Could not load members');
621
    } finally {
622
      if (membersFor === roomId) membersLoading.set(false);
623
    }
624
  }
625
626
  function avatarMap(list: MemberSummary[]): Record<string, string | null> {
627
    const next: Record<string, string | null> = {};
628
    for (const member of list) next[member.user_id] = member.avatar;
629
    return next;
630
  }
631
632
  function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> {
633
    const out: Record<string, Person> = {};
634
    for (const item of list) {
635
      if (item.kind !== 'event') continue;
636
      const s = item.event.sender;
637
      out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar };
638
    }
639
    for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar };
640
    return out;
641
  }
642
643
  function senderAvatarFor(userId: string): string | null {
644
    return avatarByUser[userId] ?? null;
645
  }
646
647
  function toggleMembers(): void {
648
    membersOpen = !membersOpen;
649
    if (membersOpen && $selectedRoomId) void loadMembers($selectedRoomId);
650
  }
651
652
  async function join(target: string): Promise<void> {
653
    const room = target.trim();
654
    if (!room || joinBusy) return;
655
    joinBusy = true;
656
    try {
657
      const res = await joinRoom(room);
658
      joinTarget = '';
659
      dialog = null;
660
      await refreshRooms();
661
      await selectRoom(res.room_id);
662
    } catch (e) {
663
      pushBanner(e instanceof Error ? e.message : 'Join failed');
664
    } finally {
665
      joinBusy = false;
666
    }
667
  }
668
669
  async function create(): Promise<void> {
670
    const name = createName.trim();
671
    if (!name || createBusy) return;
672
    createBusy = true;
673
    try {
674
      const res = await createRoom(name, createTopic.trim() || undefined);
675
      createName = '';
676
      createTopic = '';
677
      dialog = null;
678
      await refreshRooms();
679
      await selectRoom(res.room_id);
680
    } catch (e) {
681
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
682
    } finally {
683
      createBusy = false;
684
    }
685
  }
686
687
  async function leave(): Promise<void> {
688
    const roomId = $selectedRoomId;
689
    if (!roomId || leaveBusy) return;
690
    leaveBusy = true;
691
    stopTyping();
692
    try {
693
      await leaveRoom(roomId);
694
      const prev = openedRoom;
695
      if (prev === roomId) openedRoom = null;
696
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
697
      if (prev) closeRoom(prev).catch(() => undefined);
698
      await refreshRooms();
699
    } catch (e) {
700
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
701
    } finally {
702
      leaveBusy = false;
703
    }
704
  }
705
706
  function connectionClass(state: string): string {
707
    if (state === 'online') return 'dot-online';
708
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
709
    return 'dot-off';
710
  }
711
712
  function onKeydown(ev: KeyboardEvent): void {
713
    if (ev.key === 'Escape') {
714
      if (dialog) dialog = null;
715
      else if (membersOpen && window.innerWidth < 1100) membersOpen = false;
716
      else if (sidebarOpen) sidebarOpen = false;
717
    }
718
  }
719
</script>
720
721
<svelte:window on:keydown={onKeydown} />
722
723
{#if !booted}
724
  <div class="splash" role="status" aria-label="Loading Malice">
725
    <div class="splash-mark" aria-hidden="true">M</div>
726
    <p>Loading Malice…</p>
727
  </div>
728
{:else if $blocked}
729
  <div class="splash" role="status" aria-label="Malice is open in another tab">
730
    <div class="splash-mark" aria-hidden="true">M</div>
731
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
732
  </div>
733
{:else if $sessionUser == null}
734
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
735
{:else}
736
  <div class="app" class:nav-folded={$navFolded && selectedRoom} style:--msg-gap={`${$messageSpacing}px`} style:--msg-line-height={$lineHeight}>
737
    <nav class="rail" aria-label="Servers and spaces">
738
      <button
739
        type="button"
740
        class="rail-btn"
741
        class:active={selectedSpaceId === null}
742
        title="Home — all channels"
743
        aria-label="Home — all channels"
744
        aria-pressed={selectedSpaceId === null}
745
        on:click={() => void selectHome()}
746
      >
747
        <span aria-hidden="true">⌂</span>
748
      </button>
749
      <div class="rail-sep" aria-hidden="true"></div>
750
      {#each spaceRooms as space (space.room_id)}
751
        <button
752
          type="button"
753
          class="rail-btn rail-space"
754
          class:active={selectedSpaceId === space.room_id}
755
          title={space.name}
756
          aria-label={`Show channels in space ${space.name}`}
757
          aria-pressed={selectedSpaceId === space.room_id}
758
          on:click={() => void selectSpace(space.room_id)}
759
        >
760
          <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
761
        </button>
762
      {/each}
763
      <button
764
        type="button"
765
        class="rail-btn rail-add"
766
        aria-label="Join or create a room"
767
        on:click={() => {
768
          dialog = 'join';
769
        }}
770
      >
771
        <span aria-hidden="true">+</span>
772
      </button>
773
    </nav>
774
775
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
776
      <div class="side-search">
777
        <label class="visually-hidden" for="room-search">Search rooms</label>
778
        <input
779
          id="room-search"
780
          type="search"
781
          placeholder="Search rooms"
782
          bind:value={search}
783
          autocomplete="off"
784
        />
785
        <button
786
          type="button"
787
          class="icon-btn"
788
          title="Refresh rooms"
789
          aria-label="Refresh rooms"
790
          disabled={roomsLoading}
791
          on:click={() => void refreshRooms()}
792
        >
793
          <span aria-hidden="true">⟳</span>
794
        </button>
795
      </div>
796
      <div class="side-scroll">
797
        {#if selectedSpace}
798
          <div class="space-context">
799
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={28} shape="rounded" />
800
            <div class="space-context-text">
801
              <strong>{selectedSpace.name}</strong>
802
              <span>Space — channels below</span>
803
            </div>
804
          </div>
805
        {:else}
806
          <div class="space-context">
807
            <div class="space-context-text">
808
              <strong>Home</strong>
809
              <span>All channels</span>
810
            </div>
811
          </div>
812
        {/if}
813
        {#if roomsLoading && $rooms.length === 0}
814
          <p class="side-note">Loading rooms…</p>
815
        {:else if $rooms.length === 0}
816
          <p class="side-note">No rooms yet. Join one or create your own.</p>
817
          <div class="side-cta">
818
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
819
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
820
          </div>
821
        {:else}
822
          {#if selectedSpaceId && spaceChildrenLoading}
823
            <p class="side-note">Loading channels in this space…</p>
824
          {:else if selectedSpaceId && spaceChildrenError}
825
            <p class="side-note" role="alert">{spaceChildrenError}</p>
826
            <div class="side-cta">
827
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
828
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
829
            </div>
830
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
831
            <p class="side-note">No channels found in this space yet.</p>
832
            <div class="side-cta">
833
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
834
            </div>
835
          {:else}
836
            {#if invites.length > 0 && !selectedSpaceId}
837
              <h2 class="side-h">Invites</h2>
838
              <ul class="room-list">
839
                {#each invites as room (room.room_id)}
840
                  <li>
841
                    <button
842
                      type="button"
843
                      class="room-row"
844
                      class:active={$selectedRoomId === room.room_id}
845
                      on:click={() => void selectRoom(room.room_id)}
846
                    >
847
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
848
                      <span class="room-name">{room.name}</span>
849
                      <span
850
                        class="invite-join"
851
                        role="button"
852
                        tabindex="0"
853
                        aria-label={`Join ${room.name}`}
854
                        on:click|stopPropagation={() => void join(room.room_id)}
855
                        on:keydown|stopPropagation={(ev) => {
856
                          if (ev.key === 'Enter' || ev.key === ' ') {
857
                            ev.preventDefault();
858
                            void join(room.room_id);
859
                          }
860
                        }}
861
                      >
862
                        Join
863
                      </span>
864
                    </button>
865
                  </li>
866
                {/each}
867
              </ul>
868
            {/if}
869
870
            {#if directRooms.length > 0}
871
              <h2 class="side-h">Direct messages</h2>
872
              <ul class="room-list">
873
                {#each directRooms as room (room.room_id)}
874
                  <li>
875
                    <button
876
                      type="button"
877
                      class="room-row"
878
                      class:active={$selectedRoomId === room.room_id}
879
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
880
                      on:click={() => void selectRoom(room.room_id)}
881
                    >
882
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
883
                      <span class="room-name">{room.name}</span>
884
                      {#if roomUnread(room) > 0}
885
                        <span
886
                          class="badge"
887
                          class:mention={room.unread_mentions > 0}
888
                          aria-label={`${roomUnread(room)} unread`}
889
                        >
890
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
891
                        </span>
892
                      {/if}
893
                    </button>
894
                  </li>
895
                {/each}
896
              </ul>
897
            {/if}
898
899
            {#if groupRooms.length > 0}
900
              <h2 class="side-h">{selectedSpace ? 'Channels in this space' : 'Rooms'}</h2>
901
              <ul class="room-list">
902
                {#each groupRooms as room (room.room_id)}
903
                  <li>
904
                    <button
905
                      type="button"
906
                      class="room-row"
907
                      class:active={$selectedRoomId === room.room_id}
908
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
909
                      on:click={() => void selectRoom(room.room_id)}
910
                    >
911
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
912
                      <span class="room-hash" aria-hidden="true">#</span>
913
                      <span class="room-name">{room.name}</span>
914
                      {#if roomUnread(room) > 0}
915
                        <span
916
                          class="badge"
917
                          class:mention={room.unread_mentions > 0}
918
                          aria-label={`${roomUnread(room)} unread`}
919
                        >
920
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
921
                        </span>
922
                      {/if}
923
                    </button>
924
                  </li>
925
                {/each}
926
              </ul>
927
            {/if}
928
929
            {#if !selectedSpaceId && spaceList.length > 0}
930
              <h2 class="side-h">Spaces</h2>
931
              <ul class="room-list">
932
                {#each spaceList as room (room.room_id)}
933
                  <li>
934
                    <button
935
                      type="button"
936
                      class="room-row"
937
                      class:active={selectedSpaceId === room.room_id}
938
                      aria-label={`Show channels in space ${room.name}`}
939
                      on:click={() => void selectSpace(room.room_id)}
940
                    >
941
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
942
                      <span class="room-hash" aria-hidden="true">◇</span>
943
                      <span class="room-name">{room.name}</span>
944
                    </button>
945
                  </li>
946
                {/each}
947
              </ul>
948
            {/if}
949
950
            {#if query && visibleRooms.length === 0}
951
              <p class="side-note">No rooms match “{search.trim()}”.</p>
952
            {/if}
953
          {/if}
954
        {/if}
955
      </div>
956
957
      <div class="side-footer">
958
        <div class="me" title={$sessionUser}>
959
          {#if profileMxc}
960
            <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={30} />
961
          {:else}
962
            <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
963
          {/if}
964
          <span class="me-id">{profile?.display_name && profile.display_name !== $sessionUser ? `${profile.display_name} (${$sessionUser})` : $sessionUser}</span>
965
        </div>
966
        <button
967
          type="button"
968
          class="icon-btn"
969
          title="Encryption and verification"
970
          aria-label="Encryption and verification"
971
          on:click={() => (dialog = 'security')}
972
        >
973
          <span aria-hidden="true">🛡</span>
974
        </button>
975
        <button
976
          type="button"
977
          class="icon-btn"
978
          title="Settings"
979
          aria-label="Settings"
980
          on:click={() => (dialog = 'settings')}
981
        >
982
          <span aria-hidden="true">⚙</span>
983
        </button>
984
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
985
          <span aria-hidden="true">⏻</span>
986
        </button>
987
      </div>
988
    </aside>
989
    {#if sidebarOpen}
990
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
991
    {/if}
992
993
    <main class="chat">
994
        {#if $banners.length > 0}
995
          <div class="banners" aria-live="polite">
996
            {#each $banners as banner (banner.id)}
997
              <div class="banner" role="alert">
998
                <span>{banner.message}</span>
999
                <button
1000
                  type="button"
1001
                  aria-label="Dismiss error"
1002
                  on:click={() => dismissBanner(banner.id)}
1003
                >
1004
                  ✕
1005
                </button>
1006
              </div>
1007
            {/each}
1008
          </div>
1009
        {/if}
1010
      {#if !selectedRoom}
1011
        <div class="empty">
1012
          <div class="empty-mark" aria-hidden="true">◈</div>
1013
          {#if selectedSpace}
1014
            <h1>{selectedSpace.name}</h1>
1015
            <p>Select a channel below to start chatting. Spaces group channels — they are not chat rooms.</p>
1016
          {:else}
1017
            <h1>Welcome to Malice</h1>
1018
            <p>Pick a room from the sidebar, or join one to get started.</p>
1019
          {/if}
1020
          <div class="empty-cta">
1021
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
1022
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
1023
          </div>
1024
          <p class="conn-line">
1025
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1026
            {$connection}
1027
          </p>
1028
        </div>
1029
      {:else}
1030
        <header class="chat-head">
1031
          <button
1032
            type="button"
1033
            class="icon-btn only-mobile"
1034
            aria-label="Open room list"
1035
            on:click={() => (sidebarOpen = true)}
1036
          >
1037
            <span aria-hidden="true">☰</span>
1038
          </button>
1039
          <button
1040
            type="button"
1041
            class="icon-btn only-desktop"
1042
            aria-pressed={!$navFolded}
1043
            aria-label={$navFolded ? 'Show spaces and rooms' : 'Hide spaces and rooms'}
1044
            title={$navFolded ? 'Show spaces and rooms' : 'Hide spaces and rooms'}
1045
            on:click={() => navFolded.update((v) => !v)}
1046
          >
1047
            <span aria-hidden="true">{$navFolded ? '»' : '«'}</span>
1048
          </button>
1049
          <div class="head-title">
1050
            <div class="head-room">
1051
              <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape={selectedRoom.space ? 'rounded' : 'circle'} />
1052
              <div class="head-room-text">
1053
                <h1>{selectedRoom.name}</h1>
1054
                <div class="head-meta">
1055
                  {#if selectedRoom.space}
1056
                    <span class="pill">space</span>
1057
                  {/if}
1058
                  {#if selectedRoom.encrypted}
1059
                    <span class="pill" title="End-to-end encrypted">🔒 encrypted</span>
1060
                  {/if}
1061
                  {#if selectedRoom.direct}
1062
                    <span class="pill">direct</span>
1063
                  {/if}
1064
                  <span class="conn" title={`Sync state: ${$connection}`}>
1065
                    <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1066
                    {$connection}
1067
                  </span>
1068
                </div>
1069
              </div>
1070
            </div>
1071
          </div>
1072
          <div class="head-actions">
1073
            <button
1074
              type="button"
1075
              class="ghost-btn"
1076
              aria-label="Encryption and verification"
1077
              title="Encryption and verification"
1078
              on:click={() => (dialog = 'security')}
1079
            >
1080
              🛡 Security
1081
            </button>
1082
            <button
1083
              type="button"
1084
              class="ghost-btn"
1085
              aria-pressed={membersOpen}
1086
              aria-label={membersOpen ? 'Hide members' : 'Show members'}
1087
              on:click={toggleMembers}
1088
            >
1089
              Members
1090
            </button>
1091
            {#if selectedRoom.membership === 'Joined'}
1092
              <button
1093
                type="button"
1094
                class="ghost-btn danger"
1095
                disabled={leaveBusy}
1096
                on:click={() => void leave()}
1097
              >
1098
                {leaveBusy ? 'Leaving…' : 'Leave'}
1099
              </button>
1100
            {:else}
1101
              <button
1102
                type="button"
1103
                class="primary-btn"
1104
                disabled={joinBusy}
1105
                on:click={() => void join(selectedRoom.room_id)}
1106
              >
1107
                {joinBusy ? 'Joining…' : 'Join'}
1108
              </button>
1109
            {/if}
1110
            <button
1111
              type="button"
1112
              class="icon-btn only-mobile"
1113
              aria-label="Toggle members"
1114
              on:click={toggleMembers}
1115
            >
1116
              <span aria-hidden="true">ⓘ</span>
1117
            </button>
1118
          </div>
1119
        </header>
1120
1121
1122
        {#if recoveryBanner}
1123
          <div class="sec-banner warn" role="status">
1124
            <span>Message history is locked — recovery is {recoveryBanner.recovery}. Enter your recovery key to decrypt.</span>
1125
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
1126
          </div>
1127
        {/if}
1128
        {#if verificationBanner}
1129
          <div class="sec-banner" role="status">
1130
            {#if verificationBanner.kind === 'Incoming'}
1131
              <span>A device wants to verify this session. Review the request to accept it.</span>
1132
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
1133
            {:else if verificationBanner.kind === 'Comparison'}
1134
              <span>Verification codes are ready — compare emojis and numbers.</span>
1135
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
1136
            {:else if verificationBanner.kind === 'Waiting'}
1137
              <span>Verification started — approve on your other device, then compare codes here.</span>
1138
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
1139
            {:else if verificationBanner.kind === 'Failed'}
1140
              <span>Verification failed: {verificationBanner.message}</span>
1141
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
1142
            {:else if verificationBanner.kind === 'Cancelled'}
1143
              <span>Verification cancelled: {verificationBanner.reason}</span>
1144
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
1145
            {:else}
1146
              <span>Verification in progress.</span>
1147
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
1148
            {/if}
1149
          </div>
1150
        {/if}
1151
        {#if $connection !== 'online'}
1152
          <p class="conn-banner" role="status">
1153
            Sync is {$connection}. New messages will appear when the connection recovers.
1154
          </p>
1155
        {/if}
1156
        {#if $selectedRoomId && !openReady[$selectedRoomId] && !openFailed[$selectedRoomId]}
1157
          <p class="conn-banner" role="status">Opening {selectedRoom.name}… sending is disabled until the room is ready.</p>
1158
        {/if}
1159
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
1160
          <p class="conn-banner error" role="alert">{openFailed[$selectedRoomId]}</p>
1161
        {/if}
1162
1163
        <div class="timeline" bind:this={timelineEl} on:scroll={onTimelineScroll} aria-label={`Messages in ${selectedRoom.name}`}>
1164
          <div class="timeline-top">
1165
            {#if hasStart}
1166
              <p class="start-note">This is the beginning of the visible history.</p>
1167
            {:else}
1168
              <button type="button" class="ghost-btn" disabled={paginateBusy} on:click={() => void paginate()}>
1169
                {paginateBusy ? 'Loading…' : 'Load older messages'}
1170
              </button>
1171
            {/if}
1172
          </div>
1173
          {#if grouped.length === 0}
1174
            <p class="side-note timeline-empty">No messages yet. Say hello!</p>
1175
          {:else}
1176
            {#each grouped as g (g.key)}
1177
              {#if g.item.kind === 'day'}
1178
                <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div>
1179
              {:else if g.item.kind === 'readMarker'}
1180
                <div class="new-row"><span>New</span></div>
1181
              {:else if g.item.kind === 'start'}
1182
                <p class="start-note">This is the beginning of the visible history.</p>
1183
              {:else if g.item.kind === 'unknown'}
1184
                <p class="unknown-note">Unsupported event ({g.item.label})</p>
1185
              {:else}
1186
                <MessageRow
1187
                  itemId={g.key}
1188
                  event={g.item.event}
1189
                  showSender={g.showSender}
1190
                  senderAvatar={senderAvatarFor(g.item.event.sender.user_id)}
1191
                  {reacting}
1192
                  onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
1193
                  quickReactions={$quickReactions}
1194
                  packs={roomPacks}
1195
                  linkPreviews={$linkPreviews}
1196
                  {loadPreview}
1197
                  onQuickChange={(list) => void changeQuickReactions(list)}
1198
                  {people}
1199
                  onReply={selectedRoom.membership === 'Joined' ? startReply : null}
1200
                  onJump={jumpTo}
1201
                  showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0}
1202
                />
1203
              {/if}
1204
            {/each}
1205
          {/if}
1206
          {#each pendingItems as p, i (p.id)}
1207
            <MessageRow
1208
              itemId={`pending-${p.id}`}
1209
              event={pendingToEvent(p)}
1210
              onJump={jumpTo}
1211
              showSender={pendingShowSender(i)}
1212
              senderAvatar={senderAvatarFor($sessionUser ?? '')}
1213
              {reacting}
1214
              onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
1215
              quickReactions={$quickReactions}
1216
              packs={roomPacks}
1217
              linkPreviews={$linkPreviews}
1218
              {loadPreview}
1219
              onQuickChange={(list) => void changeQuickReactions(list)}
1220
            />
1221
            {#if p.status === 'failed'}
1222
              <div class="pending-actions">
1223
                <span class="pending-error" role="alert">{p.error}</span>
1224
                <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button>
1225
                <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button>
1226
              </div>
1227
            {/if}
1228
          {/each}
1229
        </div>
1230
1231
        {#if selectedRoom.membership === 'Joined'}
1232
          {#if replyingTo && replyingTo.details.kind === 'Ready'}
1233
            <div class="reply-bar" role="status">
1234
              <span class="reply-bar-label">
1235
                Replying to <strong>{senderLabel(replyingTo.details.sender)}</strong>
1236
                <span class="reply-bar-text">{contentPreview(replyingTo.details.content)}</span>
1237
              </span>
1238
              <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}>
1239
                <span aria-hidden="true">✕</span>
1240
              </button>
1241
            </div>
1242
          {/if}
1243
          <form class="composer" class:replying={replyingTo} on:submit|preventDefault={() => send()}>
1244
            <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label>
1245
            <input
1246
              type="file"
1247
              bind:this={fileInput}
1248
              class="visually-hidden"
1249
              aria-label="Attach a file"
1250
              on:change={() => void onFileChosen()}
1251
            />
1252
            <button
1253
              type="button"
1254
              class="ghost-btn"
1255
              title="Attach an image or file"
1256
              aria-label="Attach an image or file"
1257
              disabled={!($selectedRoomId && openReady[$selectedRoomId]) || uploadBusy}
1258
              on:click={() => void upload()}
1259
            >
1260
              {uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : '📎'}
1261
            </button>
1262
            <textarea
1263
              id="composer"
1264
              bind:this={composerEl}
1265
              bind:value={composer}
1266
              rows="1"
1267
              placeholder={`Message ${selectedRoom.name}`}
1268
              aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`}
1269
              on:keydown={onComposerKey}
1270
              on:paste={onComposerPaste}
1271
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
1272
            ></textarea>
1273
            <button
1274
              type="submit"
1275
              class="primary-btn"
1276
              disabled={!composer.trim() || !($selectedRoomId && openReady[$selectedRoomId])}
1277
              title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'}
1278
            >
1279
              Send
1280
            </button>
1281
          </form>
1282
          <p class="composer-note">Sending and failed states show under your message.</p>
1283
        {:else}
1284
          <div class="join-bar">
1285
            <p>You are not a member of this room.</p>
1286
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
1287
              {joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`}
1288
            </button>
1289
          </div>
1290
        {/if}
1291
      {/if}
1292
    </main>
1293
1294
    {#if selectedRoom && membersOpen}
1295
      <aside class="members" aria-label={`Members of ${selectedRoom.name}`}>
1296
        <div class="members-head">
1297
          <h2>Members</h2>
1298
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
1299
            <span aria-hidden="true">✕</span>
1300
          </button>
1301
        </div>
1302
        {#if $membersLoading && members.length === 0}
1303
          <p class="side-note">Loading members…</p>
1304
        {:else if members.length === 0}
1305
          <p class="side-note">No members loaded.</p>
1306
          {#if $selectedRoomId}
1307
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
1308
              Retry
1309
            </button>
1310
          {/if}
1311
        {:else}
1312
          <ul class="member-list">
1313
            {#each members as member (member.user_id)}
1314
              <li class="member">
1315
                <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} size={30} />
1316
                <span class="member-names">
1317
                  <span class="member-name">{member.display_name || member.name}</span>
1318
                  <span class="member-id">{member.user_id}</span>
1319
                </span>
1320
              </li>
1321
            {/each}
1322
          </ul>
1323
        {/if}
1324
      </aside>
1325
    {/if}
1326
1327
    {#if dialog}
1328
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
1329
        {#if dialog === 'security'}
1330
          <SecurityPanel
1331
            encryptionState={$encryption}
1332
            verificationState={$verification}
1333
            onAction={() => void loadEncryption()}
1334
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
1335
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
1336
            on:close={() => (dialog = null)}
1337
          />
1338
        {:else if dialog === 'settings'}
1339
          <SettingsPanel
1340
            quick={$quickReactions}
1341
            packs={roomPacks}
1342
            onQuickChange={(list) => void changeQuickReactions(list)}
1343
            on:close={() => (dialog = null)}
1344
          />
1345
        {:else}
1346
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
1347
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
1348
              <button
1349
                type="button"
1350
                role="tab"
1351
                aria-selected={dialog === 'join'}
1352
                class:active={dialog === 'join'}
1353
                on:click={() => (dialog = 'join')}
1354
              >
1355
                Join
1356
              </button>
1357
              <button
1358
                type="button"
1359
                role="tab"
1360
                aria-selected={dialog === 'create'}
1361
                class:active={dialog === 'create'}
1362
                on:click={() => (dialog = 'create')}
1363
              >
1364
                Create
1365
              </button>
1366
              <button
1367
                type="button"
1368
                class="icon-btn modal-x"
1369
                aria-label="Close dialog"
1370
                on:click={() => (dialog = null)}
1371
              >
1372
                <span aria-hidden="true">✕</span>
1373
              </button>
1374
            </div>
1375
            {#if dialog === 'join'}
1376
              <form on:submit|preventDefault={() => void join(joinTarget)}>
1377
                <label class="field">
1378
                  <span>Room ID or alias</span>
1379
                  <input
1380
                    type="text"
1381
                    placeholder="!room:example.org or #alias:example.org"
1382
                    bind:value={joinTarget}
1383
                    required
1384
                    disabled={joinBusy}
1385
                  />
1386
                </label>
1387
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
1388
                  {joinBusy ? 'Joining…' : 'Join room'}
1389
                </button>
1390
              </form>
1391
            {:else}
1392
            <form on:submit|preventDefault={() => void create()}>
1393
              <label class="field">
1394
                <span>Room name</span>
1395
                <input
1396
                  type="text"
1397
                  placeholder="Weekend plans"
1398
                  bind:value={createName}
1399
                  required
1400
                  disabled={createBusy}
1401
                />
1402
              </label>
1403
              <label class="field">
1404
                <span>Topic (optional)</span>
1405
                <input
1406
                  type="text"
1407
                  placeholder="What should this room be about?"
1408
                  bind:value={createTopic}
1409
                  disabled={createBusy}
1410
                />
1411
              </label>
1412
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
1413
                {createBusy ? 'Creating…' : 'Create room'}
1414
              </button>
1415
            </form>
1416
            {/if}
1417
          </div>
1418
        {/if}
1419
      </div>
1420
    {/if}
1421
  </div>
1422
{/if}