atagen

malice

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