atagen

malice

public
Star0
Watch0
7371424b2f055abe9920fadad7d1e66fc85462c2
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte1946 lines71.5 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 ImageLightbox from './lib/ImageLightbox.svelte';
7
  import { lightbox } from './lib/lightbox';
8
  import SecurityPanel from './lib/SecurityPanel.svelte';
9
  import {
10
    closeRoom,
11
    createRoom,
12
    getEncryption,
13
    getMembers,
14
    getProfile,
15
    getRooms,
16
    getSession,
17
    getSpaceChildren,
18
    joinRoom,
19
    leaveRoom,
20
    logout,
21
    markRead,
22
    openRoom,
23
    paginateRoom,
24
    reactToMessage,
25
    runCommand,
26
    sendMessage,
27
    uploadAttachment,
28
    uploadAvatar,
29
    editMessage
30
  } from './lib/api';
31
  import { isKnownCommand, parseCommand, splitTarget, unescapeCommand } from './lib/commands';
32
  import type { ParsedCommand } from './lib/commands';
33
  import {
34
    banners,
35
    blocked,
36
    connectEvents,
37
    connection,
38
    disconnectEvents,
39
    dismissBanner,
40
    encryption,
41
    membersByRoom,
42
    membersLoading,
43
    pushBanner,
44
    imagePacks,
45
    resetClientState,
46
    rooms,
47
    selectedRoomId,
48
    sessionUser,
49
    softLogout,
50
    timelines,
51
    verification
52
  } from './lib/store';
53
  import { discardPending, pendingByRoom, queueSend, resetPending, retryPending } from './lib/pending';
54
  import type { PendingMessage } from './lib/pending';
55
  import { insideOpenFence } from './lib/markdown';
56
  import { mentionQueryAt, mentionsFromHtml, rankPeople, resolveMentions } from './lib/mentions';
57
  import type { Mention, MentionQuery } from './lib/mentions';
58
  import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions';
59
  import {
60
    linkPreviews,
61
    loadUrlPreviewSettings,
62
    requestLinkPreview,
63
    saveUrlPreviewSettings,
64
    urlPreviewSettings
65
  } from './lib/link-previews';
66
  import { notifyTyping, stopTyping } from './lib/typing';
67
  import { formatDay } from './lib/format';
68
  import { lastSpaceRooms, lineHeight, markdownEnabled, messageSpacing, navFolded, railFolded } from './lib/appearance';
69
  import SettingsPanel from './lib/SettingsPanel.svelte';
70
  import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types';
71
  import type { MemberSummary, OwnProfile, Person, QuickReaction, ReplyReference, RoomSummary, SendState, TimelineEvent, TimelineItem } from './lib/types';
72
73
  let roomsLoading = false;
74
  let booted = false;
75
  let wasOnline = false;
76
  let search = '';
77
  let sidebarOpen = false;
78
  let membersOpen = false;
79
  let replyingTo: ReplyReference | null = null;
80
  let dialog: 'join' | 'create' | 'security' | 'settings' | null = null;
81
  let joinTarget = '';
82
  let joinBusy = false;
83
  let createName = '';
84
  let createTopic = '';
85
  let createBusy = false;
86
  let leaveBusy = false;
87
  let paginateBusy = false;
88
  let reacting = false;
89
  let composer = '';
90
  let drafts: Record<string, string> = {};
91
  let stickToBottom = true;
92
  let timelineEl: HTMLElement | null = null;
93
  let composerEl: HTMLTextAreaElement | null = null;
94
  let fileInput: HTMLInputElement | null = null;
95
  let avatarInput: HTMLInputElement | null = null;
96
  let uploadBusy = false;
97
  let uploadName: string | null = null;
98
  interface StagedAttachment {
99
    id: number;
100
    file: File;
101
    previewUrl: string | null;
102
  }
103
  let staged: Record<string, StagedAttachment[]> = {};
104
  let editing: { roomId: string; eventId: string; original: string; stash: string } | null = null;
105
  /** Everyone picked from the finder per room; only those whose name is still in the text get linked on send. */
106
  let pickedMentions: Record<string, Mention[]> = {};
107
  let mentionQuery: MentionQuery | null = null;
108
  let mentionIndex = 0;
109
  let nextStagedId = 1;
110
  const WARM_ROOM_LIMIT = 8;
111
  /** Rooms left open after switching away so coming back is instant, least recently viewed first. */
112
  let warmRooms: string[] = [];
113
  let openReady: Record<string, boolean> = {};
114
  let openFailed: Record<string, string> = {};
115
  let membersFor: string | null = null;
116
  let lastReadKey = '';
117
  let readTimer: number | null = null;
118
  let profile: OwnProfile | null = null;
119
  let profileMxc: string | null = null;
120
  let selectedSpaceId: string | null = null;
121
  let spaceChildIds: string[] | null = null;
122
  let spaceChildrenLoading = false;
123
  let spaceChildrenError: string | null = null;
124
  let avatarByUser: Record<string, string | null> = {};
125
126
  // account data is read from the local cache, which is empty on a fresh device until the first sync lands
127
  $: {
128
    const online = $connection === 'online';
129
    if (online && !wasOnline) {
130
      void loadQuickReactions();
131
      void loadUrlPreviewSettings();
132
    }
133
    wasOnline = online;
134
  }
135
  $: selectedRoom = $rooms.find((r) => r.room_id === $selectedRoomId) ?? null;
136
  $: roomPacks = packsForRoom($imagePacks, $selectedRoomId);
137
  $: previewsAllowed = selectedRoom !== null && (!selectedRoom.encrypted || $urlPreviewSettings.encrypted_rooms);
138
  $: loadPreview = previewsAllowed && $selectedRoomId ? previewLoader($selectedRoomId) : null;
139
  $: spaceRooms = $rooms.filter((r) => r.space);
140
  $: spaceParents = parentSpaceMap(spaceRooms);
141
  $: railSpaces = spaceRooms.filter((s) => !spaceParents.has(s.room_id));
142
  $: railSelected = selectedSpaceId ? topSpaceOf(selectedSpaceId, spaceParents) : null;
143
  $: invites = $rooms.filter((r) => r.membership === 'Invited');
144
  $: query = search.trim().toLowerCase();
145
  $: selectedSpace = selectedSpaceId ? ($rooms.find((r) => r.room_id === selectedSpaceId) ?? null) : null;
146
  // While a space's children load (or fail), show no channels rather than the
147
  // full list — listing everything would falsely imply it belongs to the space.
148
  $: baseRooms = selectedSpaceId ? (spaceChildIds ? $rooms.filter((r) => spaceChildIds?.includes(r.room_id)) : []) : $rooms;
149
  $: visibleRooms = query
150
    ? baseRooms.filter(
151
        (r) =>
152
          r.name.toLowerCase().includes(query) || r.room_id.toLowerCase().includes(query)
153
      )
154
    : baseRooms;
155
  $: directRooms = visibleRooms.filter((r) => r.direct && !r.space && r.membership !== 'Invited');
156
  $: groupRooms = visibleRooms.filter(
157
    (r) => !r.direct && !r.space && r.membership !== 'Invited'
158
  );
159
  $: spaceList = visibleRooms.filter((r) => r.space && r.membership !== 'Invited');
160
  $: channelRooms = baseRooms.filter((r) => !r.space && r.membership !== 'Invited');
161
  $: recoveryBanner = $encryption && ($encryption.recovery === 'Disabled' || $encryption.recovery === 'Incomplete') ? $encryption : null;
162
  $: verificationBanner = $verification && $verification.kind !== 'Done' ? $verification : null;
163
  $: items = $selectedRoomId ? ($timelines[$selectedRoomId] ?? []) : [];
164
  $: currentStaged = $selectedRoomId ? (staged[$selectedRoomId] ?? []) : [];
165
  $: members = $selectedRoomId ? ($membersByRoom[$selectedRoomId] ?? []) : [];
166
  $: people = peopleIn(items, members);
167
  $: mentionCandidates = mentionQuery ? rankPeople(Object.values(people), mentionQuery.query, $sessionUser ?? null) : [];
168
  $: if (mentionIndex >= mentionCandidates.length) mentionIndex = 0;
169
  $: hasStart = items.some((i) => i.kind === 'start');
170
  $: grouped = buildGroups(items);
171
  $: lastSentId = lastOwnSent(items);
172
  $: pendingItems = $selectedRoomId ? ($pendingByRoom[$selectedRoomId] ?? []) : [];
173
  $: lastRealOwn = lastSenderIsOwn(items);
174
175
  function lastSenderIsOwn(list: TimelineItem[]): boolean {
176
    for (let i = list.length - 1; i >= 0; i -= 1) {
177
      const it = list[i];
178
      if (it.kind === 'event') return it.event.sender.user_id === $sessionUser;
179
    }
180
    return false;
181
  }
182
183
  function pendingShowSender(index: number): boolean {
184
    return index === 0 ? !lastRealOwn : false;
185
  }
186
187
  function pendingToEvent(p: PendingMessage): TimelineEvent {
188
    const state: SendState = p.status === 'failed' ? { kind: 'Failed', will_retry: false } : { kind: 'Sending' };
189
    return {
190
      item_id: `pending-${p.id}`,
191
      event_id: null,
192
      transaction_id: p.id,
193
      sender: {
194
        user_id: $sessionUser ?? '',
195
        display_name: profile?.display_name ?? null,
196
        avatar: null,
197
        name_ambiguous: false
198
      },
199
      timestamp_ms: p.createdAt,
200
      own: true,
201
      send_state: state,
202
      content: {
203
        kind: 'Message',
204
        message: { kind: 'Text', body: p.body, geo_uri: null, formatted_body: p.formatted, edited: false, media: null, link_previews: [] }
205
      },
206
      reply_to: p.replyTo,
207
      thread_root: null,
208
      thread_summary: null,
209
      reactions: [],
210
      read_by: [],
211
      editable: false
212
    };
213
  }
214
215
  interface Group {
216
    key: string;
217
    item: TimelineItem;
218
    showSender: boolean;
219
  }
220
221
  function lastOwnSent(list: TimelineItem[]): string | null {
222
    for (let i = list.length - 1; i >= 0; i--) {
223
      const item = list[i];
224
      if (item.kind === 'event' && item.event.own && item.event.send_state.kind === 'Sent') return item.event.item_id;
225
    }
226
    return null;
227
  }
228
229
  function buildGroups(list: TimelineItem[]): Group[] {
230
    const out: Group[] = [];
231
    let prevSender: string | null = null;
232
    let prevTs = 0;
233
    list.forEach((item, index) => {
234
      let showSender = true;
235
      if (item.kind === 'event') {
236
        const e = item.event;
237
        showSender =
238
          prevSender !== e.sender.user_id || Math.abs(e.timestamp_ms - prevTs) > 5 * 60 * 1000;
239
        prevSender = e.sender.user_id;
240
        prevTs = e.timestamp_ms;
241
        out.push({ key: e.item_id || e.event_id || `m-${index}`, item, showSender });
242
      } else {
243
        prevSender = null;
244
        out.push({ key: `${item.kind}-${index}`, item, showSender });
245
      }
246
    });
247
    return out;
248
  }
249
250
  function roomUnread(r: RoomSummary): number {
251
    return r.unread_messages + r.unread_mentions;
252
  }
253
254
  onMount(() => {
255
    void boot();
256
    return () => {
257
      disconnectEvents();
258
      stopTyping();
259
      if (readTimer !== null) window.clearTimeout(readTimer);
260
    };
261
  });
262
263
  async function boot(): Promise<void> {
264
    try {
265
      const session = await getSession();
266
      blocked.set(session.blocked ?? false);
267
      sessionUser.set(session.user_id);
268
      if (session.user_id) {
269
        softLogout.set(null);
270
        await refreshRooms();
271
        connectEvents();
272
        void loadProfile();
273
        void loadEncryption();
274
        void loadQuickReactions();
275
        void loadUrlPreviewSettings();
276
      } else {
277
        softLogout.set(session.soft_logout ?? null);
278
      }
279
    } catch (e) {
280
      pushBanner(e instanceof Error ? `Session check failed: ${e.message}` : 'Session check failed');
281
      sessionUser.set(null);
282
    } finally {
283
      booted = true;
284
    }
285
  }
286
287
  async function refreshRooms(): Promise<void> {
288
    roomsLoading = true;
289
    try {
290
      const res = await getRooms();
291
      rooms.set(res.rooms);
292
      pruneSpaceFilter();
293
    } catch (e) {
294
      pushBanner(e instanceof Error ? e.message : 'Could not load rooms');
295
    } finally {
296
      roomsLoading = false;
297
    }
298
  }
299
300
  async function loadProfile(): Promise<void> {
301
    try {
302
      const raw = await getProfile();
303
      profile = parseOwnProfile(raw);
304
      profileMxc = profile.avatar_url;
305
    } catch {
306
      profile = null;
307
    }
308
  }
309
310
  async function loadEncryption(): Promise<void> {
311
    try {
312
      const res = await getEncryption();
313
      const state = parseEncryptionState(res.state);
314
      if (state) encryption.set(state);
315
      const verificationState = parseVerificationState(res.verification);
316
      if (verificationState) verification.set(verificationState);
317
    } catch {
318
      // Encryption status also arrives over SSE; a failed first fetch is not fatal.
319
    }
320
  }
321
322
  function afterLogin(userId: string): void {
323
    sessionUser.set(userId);
324
    softLogout.set(null);
325
    blocked.set(false);
326
    void refreshRooms();
327
    connectEvents();
328
    void loadProfile();
329
    void loadEncryption();
330
    void loadQuickReactions();
331
    void loadUrlPreviewSettings();
332
  }
333
334
  async function doLogout(): Promise<void> {
335
    stopTyping();
336
    try {
337
      await logout();
338
    } catch (e) {
339
      pushBanner(e instanceof Error ? e.message : 'Logout failed');
340
      return;
341
    }
342
    disconnectEvents();
343
    resetClientState();
344
    softLogout.set(null);
345
    blocked.set(false);
346
    sessionUser.set(null);
347
    lightbox.set(null);
348
    composer = '';
349
    drafts = {};
350
    dialog = null;
351
    membersOpen = false;
352
    sidebarOpen = false;
353
    profile = null;
354
    profileMxc = null;
355
    selectedSpaceId = null;
356
    spaceChildIds = null;
357
    spaceChildrenError = null;
358
    openReady = {};
359
    openFailed = {};
360
    warmRooms = [];
361
    pickedMentions = {};
362
    mentionQuery = null;
363
    clearAllStaged();
364
    avatarByUser = {};
365
    resetPending();
366
  }
367
368
  /** Joined spaces that sit inside another joined space, keyed to one such parent. Either side of the link counts. */
369
  function parentSpaceMap(spaces: RoomSummary[]): Map<string, string> {
370
    const ids = new Set(spaces.map((s) => s.room_id));
371
    const parents = new Map<string, string>();
372
    for (const space of spaces) {
373
      for (const child of space.children) {
374
        if (child !== space.room_id && ids.has(child) && !parents.has(child)) parents.set(child, space.room_id);
375
      }
376
    }
377
    for (const space of spaces) {
378
      const parent = space.parent_spaces.find((id) => id !== space.room_id && ids.has(id));
379
      if (parent && !parents.has(space.room_id)) parents.set(space.room_id, parent);
380
    }
381
    for (const id of [...parents.keys()]) {
382
      const seen = new Set<string>([id]);
383
      let at = parents.get(id);
384
      while (at && !seen.has(at)) {
385
        seen.add(at);
386
        at = parents.get(at);
387
      }
388
      if (at) parents.delete(id);
389
    }
390
    return parents;
391
  }
392
393
  function topSpaceOf(id: string, parents: Map<string, string>): string {
394
    let at = id;
395
    while (parents.has(at)) at = parents.get(at)!;
396
    return at;
397
  }
398
399
  function pruneSpaceFilter(): void {
400
    if (!selectedSpaceId) return;
401
    if (!$rooms.some((r) => r.room_id === selectedSpaceId)) {
402
      selectedSpaceId = null;
403
      spaceChildIds = null;
404
      spaceChildrenError = null;
405
    }
406
  }
407
408
  async function selectHome(): Promise<void> {
409
    selectedSpaceId = null;
410
    spaceChildIds = null;
411
    spaceChildrenError = null;
412
    sidebarOpen = true;
413
  }
414
415
  async function selectSpace(spaceId: string): Promise<void> {
416
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
417
    stopTyping();
418
    selectedSpaceId = spaceId;
419
    spaceChildIds = null;
420
    spaceChildrenError = null;
421
    spaceChildrenLoading = true;
422
    const last = $lastSpaceRooms[spaceId];
423
    const resume = last && $rooms.some((r) => r.room_id === last && !r.space) ? last : null;
424
    if (resume) {
425
      void selectRoom(resume);
426
    } else {
427
      sidebarOpen = true;
428
      // A space is navigation, not a message timeline.
429
      selectedRoomId.set(null);
430
    }
431
    try {
432
      const res = await getSpaceChildren(spaceId);
433
      if (selectedSpaceId === spaceId) {
434
        spaceChildIds = res.room_ids ?? [];
435
        if (resume && !spaceChildIds.includes(resume) && $selectedRoomId === resume) {
436
          sidebarOpen = true;
437
          selectedRoomId.set(null);
438
        }
439
      }
440
    } catch (e) {
441
      if (selectedSpaceId === spaceId) {
442
        spaceChildrenError = e instanceof Error ? e.message : 'Could not load rooms in this space';
443
        spaceChildIds = [];
444
      }
445
    } finally {
446
      if (selectedSpaceId === spaceId) spaceChildrenLoading = false;
447
    }
448
  }
449
450
  async function selectRoom(roomId: string): Promise<void> {
451
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
452
    if (roomId === $selectedRoomId && openReady[roomId]) {
453
      sidebarOpen = false;
454
      return;
455
    }
456
    stopTyping();
457
    const spaceId = selectedSpaceId;
458
    if (spaceId) lastSpaceRooms.update((all) => ({ ...all, [spaceId]: roomId }));
459
    selectedRoomId.set(roomId);
460
    composer = drafts[roomId] ?? '';
461
    replyingTo = null;
462
    editing = null;
463
    mentionQuery = null;
464
    stickToBottom = true;
465
    lastReadKey = '';
466
    sidebarOpen = false;
467
    touchWarmRoom(roomId);
468
    if (openReady[roomId]) {
469
      if (membersOpen) void loadMembers(roomId);
470
      await tick();
471
      scrollToBottom();
472
      queueReadReceipt();
473
      composerEl?.focus();
474
      return;
475
    }
476
    if (openFailed[roomId]) {
477
      const nextFailed = { ...openFailed };
478
      delete nextFailed[roomId];
479
      openFailed = nextFailed;
480
    }
481
    try {
482
      await openRoom(roomId);
483
      if (warmRooms.includes(roomId)) openReady = { ...openReady, [roomId]: true };
484
    } catch (e) {
485
      const message = e instanceof Error ? e.message : `Could not open room ${roomId}`;
486
      openFailed = { ...openFailed, [roomId]: message };
487
      pushBanner(message);
488
    }
489
    if (membersOpen) void loadMembers(roomId);
490
    await tick();
491
    scrollToBottom();
492
    queueReadReceipt();
493
    composerEl?.focus();
494
  }
495
496
  function touchWarmRoom(roomId: string): void {
497
    warmRooms = [...warmRooms.filter((id) => id !== roomId), roomId];
498
    while (warmRooms.length > WARM_ROOM_LIMIT) {
499
      const evicted = warmRooms[0];
500
      warmRooms = warmRooms.slice(1);
501
      forgetOpenRoom(evicted);
502
      closeRoom(evicted).catch(() => undefined);
503
    }
504
  }
505
506
  function forgetOpenRoom(roomId: string): void {
507
    warmRooms = warmRooms.filter((id) => id !== roomId);
508
    const nextReady = { ...openReady };
509
    delete nextReady[roomId];
510
    openReady = nextReady;
511
  }
512
513
  function scrollToBottom(): void {
514
    if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight;
515
  }
516
517
  let userScrollUntil = 0;
518
  let draggingScrollbar = false;
519
520
  function noteUserScroll(): void {
521
    userScrollUntil = performance.now() + 300;
522
  }
523
524
  function onTimelineKey(e: KeyboardEvent): void {
525
    if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) noteUserScroll();
526
  }
527
528
  function onTimelinePointer(e: PointerEvent): void {
529
    if (e.target === timelineEl) draggingScrollbar = true;
530
  }
531
532
  function onTimelineScroll(): void {
533
    if (!timelineEl) return;
534
    const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight;
535
    if (gap < 80) stickToBottom = true;
536
    else if (draggingScrollbar || performance.now() < userScrollUntil) stickToBottom = false;
537
  }
538
539
  function pinTimeline(node: HTMLElement) {
540
    const observer = new ResizeObserver(() => {
541
      if (stickToBottom) scrollToBottom();
542
    });
543
    observer.observe(node);
544
    if (node.parentElement) observer.observe(node.parentElement);
545
    return { destroy: () => observer.disconnect() };
546
  }
547
548
  $: void trackTimeline($selectedRoomId, items);
549
  async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> {
550
    if (!roomId || list.length === 0) return;
551
    if (roomId !== $selectedRoomId) return;
552
    await tick();
553
    if (stickToBottom) scrollToBottom();
554
    queueReadReceipt();
555
  }
556
557
  function queueReadReceipt(): void {
558
    if (readTimer !== null) window.clearTimeout(readTimer);
559
    readTimer = window.setTimeout(() => {
560
      readTimer = null;
561
      void sendReadReceipt();
562
    }, 800);
563
  }
564
565
  async function sendReadReceipt(): Promise<void> {
566
    const roomId = $selectedRoomId;
567
    if (!roomId) return;
568
    const list = $timelines[roomId] ?? [];
569
    for (let i = list.length - 1; i >= 0; i -= 1) {
570
      const entry = list[i];
571
      if (entry.kind === 'event' && entry.event.event_id) {
572
        const key = `${roomId}:${entry.event.event_id}`;
573
        if (key === lastReadKey) return;
574
        lastReadKey = key;
575
        try {
576
          await markRead(roomId, entry.event.event_id);
577
        } catch {
578
          return;
579
        }
580
        return;
581
      }
582
    }
583
  }
584
585
  function send(): void {
586
    if (editing) {
587
      submitEdit();
588
      return;
589
    }
590
    const roomId = $selectedRoomId;
591
    const body = composer.trim();
592
    const attachments = roomId ? (staged[roomId] ?? []) : [];
593
    if (!roomId || (!body && attachments.length === 0)) return;
594
    if (!openReady[roomId]) {
595
      pushBanner('Still opening this room — sending is disabled until the room is ready.');
596
      return;
597
    }
598
    if (attachments.length > 0 && uploadBusy) return;
599
    const command = attachments.length === 0 ? parseCommand(body) : null;
600
    if (command && !isKnownCommand(command.name)) {
601
      pushBanner(`Unknown command /${command.name}`);
602
      return;
603
    }
604
    composer = '';
605
    if (roomId in drafts) delete drafts[roomId];
606
    stickToBottom = true;
607
    const reply = replyingTo;
608
    replyingTo = null;
609
    const text = unescapeCommand(body);
610
    const mentions = resolveMentions(text, pickedMentions[roomId] ?? []);
611
    pickedMentions = { ...pickedMentions, [roomId]: [] };
612
    mentionQuery = null;
613
    if (command) {
614
      void execute(roomId, command, reply, mentions);
615
    } else if (attachments.length === 0) {
616
      queueSend(roomId, text, reply, mentions, $markdownEnabled);
617
    } else {
618
      const { [roomId]: _sent, ...rest } = staged;
619
      staged = rest;
620
      void sendAttachments(roomId, text, reply, mentions, attachments);
621
    }
622
    composerEl?.focus();
623
  }
624
625
  function lastOwnEventId(): string | null {
626
    for (let i = items.length - 1; i >= 0; i -= 1) {
627
      const entry = items[i];
628
      if (entry.kind === 'event' && entry.event.own && entry.event.event_id && entry.event.content.kind !== 'Redacted') {
629
        return entry.event.event_id;
630
      }
631
    }
632
    return null;
633
  }
634
635
  async function execute(roomId: string, command: ParsedCommand, reply: ReplyReference | null, mentions: Mention[]): Promise<void> {
636
    const { name, args } = command;
637
    const target = () => {
638
      const found = splitTarget(args, Object.values(people));
639
      if ('error' in found) throw new Error(found.error);
640
      return found;
641
    };
642
    const required = (what: string) => {
643
      if (!args) throw new Error(`/${name} needs ${what}`);
644
      return args;
645
    };
646
    try {
647
      switch (name) {
648
        case 'me':
649
          await sendMessage(roomId, required('something to say'), null, mentions, $markdownEnabled, true);
650
          break;
651
        case 'msg': {
652
          const { user_id, rest } = target();
653
          const res = (await runCommand({ op: 'direct', user_id })) as { room_id: string };
654
          await refreshRooms();
655
          await selectRoom(res.room_id);
656
          if (rest) queueSend(res.room_id, rest, null, [], $markdownEnabled);
657
          break;
658
        }
659
        case 'join':
660
          await join(required('a room id or alias'));
661
          break;
662
        case 'leave':
663
          await leave();
664
          break;
665
        case 'invite':
666
          await runCommand({ op: 'invite', room_id: roomId, user_id: target().user_id });
667
          break;
668
        case 'disinvite':
669
        case 'kick':
670
        case 'ban':
671
        case 'unban': {
672
          const { user_id, rest } = target();
673
          const op = name === 'disinvite' ? 'kick' : name;
674
          await runCommand({ op, room_id: roomId, user_id, reason: rest || null });
675
          break;
676
        }
677
        case 'powerlevel': {
678
          const { user_id, rest } = target();
679
          const level = Number(rest);
680
          if (!rest || !Number.isInteger(level)) throw new Error('/powerlevel needs a whole number after the name');
681
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id, level });
682
          break;
683
        }
684
        case 'delete': {
685
          const eventId = reply?.event_id ?? lastOwnEventId();
686
          if (!eventId) throw new Error('Nothing of yours to delete here');
687
          await runCommand({ op: 'redact', room_id: roomId, event_id: eventId, reason: args || null });
688
          break;
689
        }
690
        case 'globalnick':
691
          await runCommand({ op: 'set_display_name', name: required('a name') });
692
          await loadProfile();
693
          break;
694
        case 'globalavatar':
695
          if (!args) {
696
            avatarInput?.click();
697
          } else if (args.startsWith('mxc://')) {
698
            await runCommand({ op: 'set_avatar', mxc: args });
699
            await loadProfile();
700
          } else {
701
            throw new Error('/globalavatar takes an mxc:// link, or nothing to pick a file');
702
          }
703
          break;
704
      }
705
    } catch (e) {
706
      pushBanner(e instanceof Error ? e.message : `/${name} failed`);
707
    }
708
  }
709
710
  async function onAvatarChosen(): Promise<void> {
711
    const file = avatarInput?.files?.[0];
712
    if (avatarInput) avatarInput.value = '';
713
    if (!file) return;
714
    try {
715
      await uploadAvatar(file);
716
      await loadProfile();
717
    } catch (e) {
718
      pushBanner(e instanceof Error ? e.message : 'Avatar upload failed');
719
    }
720
  }
721
722
  async function sendAttachments(
723
    roomId: string,
724
    body: string,
725
    reply: ReplyReference | null,
726
    mentions: Mention[],
727
    attachments: StagedAttachment[]
728
  ): Promise<void> {
729
    let first = true;
730
    uploadBusy = true;
731
    try {
732
      for (const attachment of attachments) {
733
        uploadName = attachment.file.name || 'attachment';
734
        try {
735
          if (first) await uploadAttachment(roomId, attachment.file, body || null, reply?.event_id ?? null, mentions, $markdownEnabled);
736
          else await uploadAttachment(roomId, attachment.file);
737
          first = false;
738
        } catch (e) {
739
          pushBanner(e instanceof Error ? e.message : 'Upload failed');
740
        }
741
        if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
742
      }
743
    } finally {
744
      uploadBusy = false;
745
      uploadName = null;
746
    }
747
  }
748
749
  function stageFiles(files: File[]): void {
750
    const roomId = $selectedRoomId;
751
    if (!roomId || !openReady[roomId]) return;
752
    const accepted: StagedAttachment[] = [];
753
    for (const file of files) {
754
      if (file.size === 0 || file.size > 20 * 1024 * 1024) {
755
        pushBanner(`${file.name || 'File'} must be between 1 byte and 20 MiB.`);
756
        continue;
757
      }
758
      const previewUrl = file.type.startsWith('image/') ? URL.createObjectURL(file) : null;
759
      accepted.push({ id: nextStagedId++, file, previewUrl });
760
    }
761
    if (accepted.length === 0) return;
762
    staged = { ...staged, [roomId]: [...(staged[roomId] ?? []), ...accepted] };
763
    composerEl?.focus();
764
  }
765
766
  function unstage(roomId: string, id: number): void {
767
    const list = staged[roomId] ?? [];
768
    const removed = list.find((a) => a.id === id);
769
    if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
770
    staged = { ...staged, [roomId]: list.filter((a) => a.id !== id) };
771
  }
772
773
  function clearAllStaged(): void {
774
    for (const list of Object.values(staged)) {
775
      for (const attachment of list) if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
776
    }
777
    staged = {};
778
  }
779
780
  function startEdit(eventId: string, body: string): void {
781
    const roomId = $selectedRoomId;
782
    if (!roomId) return;
783
    const stash = editing ? editing.stash : composer;
784
    editing = { roomId, eventId, original: body, stash };
785
    const entry = items.find((i) => i.kind === 'event' && i.event.event_id === eventId);
786
    if (entry?.kind === 'event' && entry.event.content.kind === 'Message') {
787
      const existing = mentionsFromHtml(entry.event.content.message.formatted_body);
788
      pickedMentions = { ...pickedMentions, [roomId]: [...(pickedMentions[roomId] ?? []), ...existing] };
789
    }
790
    composer = body;
791
    replyingTo = null;
792
    composerEl?.focus();
793
  }
794
795
  function cancelEdit(): void {
796
    if (!editing) return;
797
    composer = editing.stash;
798
    editing = null;
799
    composerEl?.focus();
800
  }
801
802
  function submitEdit(): void {
803
    if (!editing) return;
804
    const { roomId, eventId, original } = editing;
805
    const body = composer.trim();
806
    cancelEdit();
807
    if (!body || body === original.trim()) return;
808
    editMessage(roomId, eventId, body, resolveMentions(body, pickedMentions[roomId] ?? []), $markdownEnabled).catch((e) => pushBanner(e instanceof Error ? e.message : 'Edit failed'));
809
  }
810
811
  function editLastOwn(): boolean {
812
    for (let i = items.length - 1; i >= 0; i -= 1) {
813
      const entry = items[i];
814
      if (entry.kind !== 'event' || !entry.event.own) continue;
815
      const ev = entry.event;
816
      if (!ev.editable || !ev.event_id || ev.content.kind !== 'Message' || ev.content.message.kind !== 'Text') return false;
817
      startEdit(ev.event_id, ev.content.message.body);
818
      return true;
819
    }
820
    return false;
821
  }
822
823
  function startReply(target: ReplyReference): void {
824
    if (editing) cancelEdit();
825
    replyingTo = target;
826
    composerEl?.focus();
827
  }
828
829
  function jumpTo(eventId: string): void {
830
    const el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
831
    if (!el) {
832
      pushBanner('The original message is not loaded. Scroll up to load older messages.');
833
      return;
834
    }
835
    stickToBottom = false;
836
    el.scrollIntoView({ block: 'center', behavior: 'smooth' });
837
    el.classList.remove('flash');
838
    void el.offsetWidth;
839
    el.classList.add('flash');
840
  }
841
842
  let typedText = '';
843
  let typedRoom: string | null = null;
844
  $: trackTypingInput(composer, $selectedRoomId, openReady);
845
  function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void {
846
    const edited = roomId === typedRoom && text !== typedText;
847
    typedText = text;
848
    typedRoom = roomId;
849
    if (!roomId || !ready[roomId] || !text.trim()) {
850
      stopTyping();
851
    } else if (edited) {
852
      notifyTyping(roomId);
853
    }
854
  }
855
856
  $: void trackPending($selectedRoomId, pendingItems);
857
  async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> {
858
    if (!roomId || list.length === 0) return;
859
    if (roomId !== $selectedRoomId) return;
860
    await tick();
861
    if (stickToBottom) scrollToBottom();
862
  }
863
864
  function updateMentionQuery(): void {
865
    const roomId = $selectedRoomId;
866
    const next = composerEl && roomId ? mentionQueryAt(composerEl.value, composerEl.selectionStart ?? composerEl.value.length) : null;
867
    if (next && !mentionQuery && roomId && !$membersByRoom[roomId]) void loadMembers(roomId);
868
    if (next?.start !== mentionQuery?.start) mentionIndex = 0;
869
    mentionQuery = next;
870
  }
871
872
  async function pickMention(person: Person): Promise<void> {
873
    const roomId = $selectedRoomId;
874
    if (!mentionQuery || !roomId || !composerEl) return;
875
    const caret = composerEl.selectionStart ?? composer.length;
876
    const inserted = `${person.name} `;
877
    composer = composer.slice(0, mentionQuery.start) + inserted + composer.slice(caret);
878
    const at = mentionQuery.start + inserted.length;
879
    pickedMentions = {
880
      ...pickedMentions,
881
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
882
    };
883
    mentionQuery = null;
884
    await tick();
885
    composerEl.focus();
886
    composerEl.setSelectionRange(at, at);
887
  }
888
889
  function onComposerKey(ev: KeyboardEvent): void {
890
    if (mentionQuery && mentionCandidates.length > 0) {
891
      if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
892
        ev.preventDefault();
893
        const step = ev.key === 'ArrowDown' ? 1 : -1;
894
        mentionIndex = (mentionIndex + step + mentionCandidates.length) % mentionCandidates.length;
895
        return;
896
      }
897
      if ((ev.key === 'Enter' && !ev.shiftKey) || ev.key === 'Tab') {
898
        ev.preventDefault();
899
        void pickMention(mentionCandidates[mentionIndex]);
900
        return;
901
      }
902
      if (ev.key === 'Escape') {
903
        ev.stopPropagation();
904
        mentionQuery = null;
905
        return;
906
      }
907
    }
908
    if (ev.key === 'Enter' && !ev.shiftKey && !insideOpenFence(composer, composerEl?.selectionStart ?? composer.length)) {
909
      ev.preventDefault();
910
      send();
911
    } else if (ev.key === 'Escape' && editing) {
912
      ev.stopPropagation();
913
      cancelEdit();
914
    } else if (ev.key === 'Escape' && replyingTo) {
915
      ev.stopPropagation();
916
      replyingTo = null;
917
    } else if (ev.key === 'ArrowUp' && !composer && !editing && editLastOwn()) {
918
      ev.preventDefault();
919
    }
920
  }
921
922
  function pickFiles(): void {
923
    const roomId = $selectedRoomId;
924
    if (!roomId || !openReady[roomId]) return;
925
    fileInput?.click();
926
  }
927
928
  function onFileChosen(): void {
929
    stageFiles(Array.from(fileInput?.files ?? []));
930
    if (fileInput) fileInput.value = '';
931
  }
932
933
  function onComposerPaste(ev: ClipboardEvent): void {
934
    const data = ev.clipboardData;
935
    // Office apps put a rendered image next to the copied text, so only take the image when there is no plain text.
936
    if (!data || data.types.includes('text/plain')) return;
937
    const images = Array.from(data.files).filter((f) => f.type.startsWith('image/'));
938
    if (images.length === 0) return;
939
    ev.preventDefault();
940
    stageFiles(images);
941
  }
942
943
  async function react(eventId: string, key: string, shortcode?: string): Promise<void> {
944
    const roomId = $selectedRoomId;
945
    if (!roomId || !eventId || reacting) return;
946
    reacting = true;
947
    try {
948
      await reactToMessage(roomId, eventId, key, shortcode);
949
    } catch (e) {
950
      pushBanner(e instanceof Error ? e.message : 'Reaction failed');
951
    } finally {
952
      reacting = false;
953
    }
954
  }
955
956
  function previewLoader(roomId: string): (url: string) => void {
957
    return (url) => requestLinkPreview(roomId, url);
958
  }
959
960
  async function changeEncryptedPreviews(enabled: boolean): Promise<void> {
961
    try {
962
      await saveUrlPreviewSettings({ encrypted_rooms: enabled });
963
    } catch (e) {
964
      pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting');
965
    }
966
  }
967
968
  async function changeQuickReactions(list: QuickReaction[]): Promise<void> {
969
    try {
970
      await saveQuickReactions(list);
971
    } catch (e) {
972
      pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions');
973
    }
974
  }
975
976
  async function paginate(): Promise<void> {
977
    const roomId = $selectedRoomId;
978
    if (!roomId || paginateBusy) return;
979
    paginateBusy = true;
980
    try {
981
      await paginateRoom(roomId);
982
    } catch (e) {
983
      pushBanner(e instanceof Error ? e.message : 'Loading older messages failed');
984
    } finally {
985
      paginateBusy = false;
986
    }
987
  }
988
989
  async function loadMembers(roomId: string): Promise<void> {
990
    if (membersFor === roomId && $membersLoading) return;
991
    membersFor = roomId;
992
    membersLoading.set(true);
993
    try {
994
      const res = await getMembers(roomId);
995
      membersByRoom.update((all) => ({ ...all, [roomId]: res.members }));
996
      avatarByUser = { ...avatarByUser, ...avatarMap(res.members) };
997
    } catch (e) {
998
      pushBanner(e instanceof Error ? e.message : 'Could not load members');
999
    } finally {
1000
      if (membersFor === roomId) membersLoading.set(false);
1001
    }
1002
  }
1003
1004
  function avatarMap(list: MemberSummary[]): Record<string, string | null> {
1005
    const next: Record<string, string | null> = {};
1006
    for (const member of list) next[member.user_id] = member.avatar;
1007
    return next;
1008
  }
1009
1010
  function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> {
1011
    const out: Record<string, Person> = {};
1012
    for (const item of list) {
1013
      if (item.kind !== 'event') continue;
1014
      const s = item.event.sender;
1015
      out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar };
1016
    }
1017
    for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar };
1018
    return out;
1019
  }
1020
1021
  function senderAvatarFor(userId: string): string | null {
1022
    return avatarByUser[userId] ?? null;
1023
  }
1024
1025
  function toggleMembers(): void {
1026
    membersOpen = !membersOpen;
1027
    if (membersOpen && $selectedRoomId) void loadMembers($selectedRoomId);
1028
  }
1029
1030
  async function join(target: string): Promise<void> {
1031
    const room = target.trim();
1032
    if (!room || joinBusy) return;
1033
    joinBusy = true;
1034
    try {
1035
      const res = await joinRoom(room);
1036
      joinTarget = '';
1037
      dialog = null;
1038
      await refreshRooms();
1039
      await selectRoom(res.room_id);
1040
    } catch (e) {
1041
      pushBanner(e instanceof Error ? e.message : 'Join failed');
1042
    } finally {
1043
      joinBusy = false;
1044
    }
1045
  }
1046
1047
  async function create(): Promise<void> {
1048
    const name = createName.trim();
1049
    if (!name || createBusy) return;
1050
    createBusy = true;
1051
    try {
1052
      const res = await createRoom(name, createTopic.trim() || undefined);
1053
      createName = '';
1054
      createTopic = '';
1055
      dialog = null;
1056
      await refreshRooms();
1057
      await selectRoom(res.room_id);
1058
    } catch (e) {
1059
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
1060
    } finally {
1061
      createBusy = false;
1062
    }
1063
  }
1064
1065
  async function leave(): Promise<void> {
1066
    const roomId = $selectedRoomId;
1067
    if (!roomId || leaveBusy) return;
1068
    leaveBusy = true;
1069
    stopTyping();
1070
    try {
1071
      await leaveRoom(roomId);
1072
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
1073
      if (warmRooms.includes(roomId)) {
1074
        forgetOpenRoom(roomId);
1075
        closeRoom(roomId).catch(() => undefined);
1076
      }
1077
      await refreshRooms();
1078
    } catch (e) {
1079
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
1080
    } finally {
1081
      leaveBusy = false;
1082
    }
1083
  }
1084
1085
  function connectionClass(state: string): string {
1086
    if (state === 'online') return 'dot-online';
1087
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
1088
    return 'dot-off';
1089
  }
1090
1091
  let roomMenuOpen = false;
1092
  let roomMenuEl: HTMLDivElement | null = null;
1093
1094
  function roomMenuAction(action: () => void): void {
1095
    roomMenuOpen = false;
1096
    action();
1097
  }
1098
1099
  function closeRoomMenuOutside(ev: PointerEvent): void {
1100
    if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false;
1101
  }
1102
1103
  function onKeydown(ev: KeyboardEvent): void {
1104
    if (ev.key === 'Escape') {
1105
      if (roomMenuOpen) roomMenuOpen = false;
1106
      else if (dialog) dialog = null;
1107
      else if (membersOpen && window.innerWidth < 1100) membersOpen = false;
1108
      else if (sidebarOpen) sidebarOpen = false;
1109
    }
1110
  }
1111
</script>
1112
1113
<svelte:window
1114
  on:keydown={onKeydown}
1115
  on:pointerdown={closeRoomMenuOutside}
1116
  on:pointerup={() => (draggingScrollbar = false)}
1117
/>
1118
1119
{#if !booted}
1120
  <div class="splash" role="status" aria-label="Loading Malice">
1121
    <div class="splash-mark" aria-hidden="true">M</div>
1122
    <p>Loading Malice…</p>
1123
  </div>
1124
{:else if $blocked}
1125
  <div class="splash" role="status" aria-label="Malice is open in another tab">
1126
    <div class="splash-mark" aria-hidden="true">M</div>
1127
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
1128
  </div>
1129
{:else if $sessionUser == null}
1130
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
1131
{:else}
1132
  <div
1133
    class="app"
1134
    class:nav-folded={$navFolded && selectedRoom}
1135
    class:rail-folded={$railFolded && selectedRoom}
1136
    class:members-open={selectedRoom && membersOpen}
1137
    style:--msg-gap={`${$messageSpacing}px`}
1138
    style:--msg-line-height={$lineHeight}
1139
  >
1140
    <nav class="rail" aria-label="Servers and spaces">
1141
      <button
1142
        type="button"
1143
        class="rail-btn"
1144
        class:active={selectedSpaceId === null}
1145
        title="Home — all channels"
1146
        aria-label="Home — all channels"
1147
        aria-pressed={selectedSpaceId === null}
1148
        on:click={() => void selectHome()}
1149
      >
1150
        <span aria-hidden="true">⌂</span>
1151
      </button>
1152
      <div class="rail-sep" aria-hidden="true"></div>
1153
      {#each railSpaces as space (space.room_id)}
1154
        <button
1155
          type="button"
1156
          class="rail-btn rail-space"
1157
          class:active={railSelected === space.room_id}
1158
          title={space.name}
1159
          aria-label={`Show channels in space ${space.name}`}
1160
          aria-pressed={selectedSpaceId === space.room_id}
1161
          on:click={() => void selectSpace(space.room_id)}
1162
        >
1163
          <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
1164
        </button>
1165
      {/each}
1166
      <button
1167
        type="button"
1168
        class="rail-btn rail-add"
1169
        aria-label="Join or create a room"
1170
        on:click={() => {
1171
          dialog = 'join';
1172
        }}
1173
      >
1174
        <span aria-hidden="true">+</span>
1175
      </button>
1176
    </nav>
1177
1178
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
1179
      <div class="side-search">
1180
        <label class="visually-hidden" for="room-search">Search rooms</label>
1181
        <input
1182
          id="room-search"
1183
          type="search"
1184
          placeholder="Search rooms"
1185
          bind:value={search}
1186
          autocomplete="off"
1187
        />
1188
        <button
1189
          type="button"
1190
          class="icon-btn"
1191
          title="Refresh rooms"
1192
          aria-label="Refresh rooms"
1193
          disabled={roomsLoading}
1194
          on:click={() => void refreshRooms()}
1195
        >
1196
          <span aria-hidden="true">⟳</span>
1197
        </button>
1198
      </div>
1199
      <div class="side-scroll">
1200
        {#if selectedSpace}
1201
          <div class="space-context">
1202
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={28} shape="rounded" />
1203
            <div class="space-context-text">
1204
              <strong>{selectedSpace.name}</strong>
1205
            </div>
1206
            {#if spaceParents.has(selectedSpace.room_id)}
1207
              {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
1208
              <button
1209
                type="button"
1210
                class="icon-btn"
1211
                title="Up to the parent space"
1212
                aria-label="Up to the parent space"
1213
                on:click={() => void selectSpace(parentId)}
1214
              >
1215
                <span aria-hidden="true">↑</span>
1216
              </button>
1217
            {/if}
1218
          </div>
1219
        {:else}
1220
          <div class="space-context">
1221
            <div class="space-context-text">
1222
              <strong>Home</strong>
1223
            </div>
1224
          </div>
1225
        {/if}
1226
        {#if roomsLoading && $rooms.length === 0}
1227
          <p class="side-note">Loading rooms…</p>
1228
        {:else if $rooms.length === 0}
1229
          <p class="side-note">No rooms yet</p>
1230
          <div class="side-cta">
1231
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
1232
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
1233
          </div>
1234
        {:else}
1235
          {#if selectedSpaceId && spaceChildrenLoading}
1236
            <p class="side-note">Loading channels…</p>
1237
          {:else if selectedSpaceId && spaceChildrenError}
1238
            <p class="side-note" role="alert">{spaceChildrenError}</p>
1239
            <div class="side-cta">
1240
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
1241
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1242
            </div>
1243
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
1244
            <p class="side-note">No channels</p>
1245
            <div class="side-cta">
1246
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1247
            </div>
1248
          {:else}
1249
            {#if invites.length > 0 && !selectedSpaceId}
1250
              <h2 class="side-h">Invites</h2>
1251
              <ul class="room-list">
1252
                {#each invites as room (room.room_id)}
1253
                  <li>
1254
                    <button
1255
                      type="button"
1256
                      class="room-row"
1257
                      class:active={$selectedRoomId === room.room_id}
1258
                      on:click={() => void selectRoom(room.room_id)}
1259
                    >
1260
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1261
                      <span class="room-name">{room.name}</span>
1262
                      <span
1263
                        class="invite-join"
1264
                        role="button"
1265
                        tabindex="0"
1266
                        aria-label={`Join ${room.name}`}
1267
                        on:click|stopPropagation={() => void join(room.room_id)}
1268
                        on:keydown|stopPropagation={(ev) => {
1269
                          if (ev.key === 'Enter' || ev.key === ' ') {
1270
                            ev.preventDefault();
1271
                            void join(room.room_id);
1272
                          }
1273
                        }}
1274
                      >
1275
                        Join
1276
                      </span>
1277
                    </button>
1278
                  </li>
1279
                {/each}
1280
              </ul>
1281
            {/if}
1282
1283
            {#if directRooms.length > 0}
1284
              <h2 class="side-h">Direct messages</h2>
1285
              <ul class="room-list">
1286
                {#each directRooms as room (room.room_id)}
1287
                  <li>
1288
                    <button
1289
                      type="button"
1290
                      class="room-row"
1291
                      class:active={$selectedRoomId === room.room_id}
1292
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
1293
                      on:click={() => void selectRoom(room.room_id)}
1294
                    >
1295
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
1296
                      <span class="room-name">{room.name}</span>
1297
                      {#if roomUnread(room) > 0}
1298
                        <span
1299
                          class="badge"
1300
                          class:mention={room.unread_mentions > 0}
1301
                          aria-label={`${roomUnread(room)} unread`}
1302
                        >
1303
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
1304
                        </span>
1305
                      {/if}
1306
                    </button>
1307
                  </li>
1308
                {/each}
1309
              </ul>
1310
            {/if}
1311
1312
            {#if groupRooms.length > 0}
1313
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
1314
              <ul class="room-list">
1315
                {#each groupRooms as room (room.room_id)}
1316
                  <li>
1317
                    <button
1318
                      type="button"
1319
                      class="room-row"
1320
                      class:active={$selectedRoomId === room.room_id}
1321
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
1322
                      on:click={() => void selectRoom(room.room_id)}
1323
                    >
1324
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1325
                      <span class="room-hash" aria-hidden="true">#</span>
1326
                      <span class="room-name">{room.name}</span>
1327
                      {#if roomUnread(room) > 0}
1328
                        <span
1329
                          class="badge"
1330
                          class:mention={room.unread_mentions > 0}
1331
                          aria-label={`${roomUnread(room)} unread`}
1332
                        >
1333
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
1334
                        </span>
1335
                      {/if}
1336
                    </button>
1337
                  </li>
1338
                {/each}
1339
              </ul>
1340
            {/if}
1341
1342
            {#if spaceList.length > 0}
1343
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
1344
              <ul class="room-list">
1345
                {#each spaceList as room (room.room_id)}
1346
                  <li>
1347
                    <button
1348
                      type="button"
1349
                      class="room-row"
1350
                      class:active={selectedSpaceId === room.room_id}
1351
                      aria-label={`Show channels in space ${room.name}`}
1352
                      on:click={() => void selectSpace(room.room_id)}
1353
                    >
1354
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1355
                      <span class="room-hash" aria-hidden="true">◇</span>
1356
                      <span class="room-name">{room.name}</span>
1357
                    </button>
1358
                  </li>
1359
                {/each}
1360
              </ul>
1361
            {/if}
1362
1363
            {#if query && visibleRooms.length === 0}
1364
              <p class="side-note">No rooms match “{search.trim()}”.</p>
1365
            {/if}
1366
          {/if}
1367
        {/if}
1368
      </div>
1369
1370
      <div class="side-footer">
1371
        <div class="me" title={$sessionUser}>
1372
          {#if profileMxc}
1373
            <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={30} />
1374
          {:else}
1375
            <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
1376
          {/if}
1377
          <span class="me-id">{profile?.display_name && profile.display_name !== $sessionUser ? `${profile.display_name} (${$sessionUser})` : $sessionUser}</span>
1378
        </div>
1379
        <button
1380
          type="button"
1381
          class="icon-btn"
1382
          title="Encryption and verification"
1383
          aria-label="Encryption and verification"
1384
          on:click={() => (dialog = 'security')}
1385
        >
1386
          <span aria-hidden="true">🛡</span>
1387
        </button>
1388
        <button
1389
          type="button"
1390
          class="icon-btn"
1391
          title="Settings"
1392
          aria-label="Settings"
1393
          on:click={() => (dialog = 'settings')}
1394
        >
1395
          <span aria-hidden="true">⚙</span>
1396
        </button>
1397
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
1398
          <span aria-hidden="true">⏻</span>
1399
        </button>
1400
      </div>
1401
    </aside>
1402
    {#if sidebarOpen}
1403
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
1404
    {/if}
1405
1406
    <main class="chat">
1407
        {#if $banners.length > 0}
1408
          <div class="banners" aria-live="polite">
1409
            {#each $banners as banner (banner.id)}
1410
              <div class="banner" role="alert">
1411
                <span>{banner.message}</span>
1412
                <button
1413
                  type="button"
1414
                  aria-label="Dismiss error"
1415
                  on:click={() => dismissBanner(banner.id)}
1416
                >
1417
                  ✕
1418
                </button>
1419
              </div>
1420
            {/each}
1421
          </div>
1422
        {/if}
1423
      {#if !selectedRoom}
1424
        <div class="empty">
1425
          <div class="empty-mark" aria-hidden="true">◈</div>
1426
          {#if selectedSpace}
1427
            <h1>{selectedSpace.name}</h1>
1428
          {:else}
1429
            <h1>Welcome to Malice</h1>
1430
          {/if}
1431
          <div class="empty-cta">
1432
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
1433
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
1434
          </div>
1435
          <p class="conn-line">
1436
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1437
            {$connection}
1438
          </p>
1439
        </div>
1440
      {:else}
1441
        <header class="chat-head">
1442
          <button
1443
            type="button"
1444
            class="icon-btn only-mobile"
1445
            aria-label="Open room list"
1446
            on:click={() => (sidebarOpen = true)}
1447
          >
1448
            <span aria-hidden="true">☰</span>
1449
          </button>
1450
          <button
1451
            type="button"
1452
            class="icon-btn only-desktop pane-toggle"
1453
            aria-pressed={!$railFolded}
1454
            aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1455
            title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1456
            on:click={() => railFolded.update((v) => !v)}
1457
          >
1458
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1459
              <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1460
              <circle cx="7" cy="9" r="1.4" fill="currentColor" />
1461
              <circle cx="7" cy="13" r="1.4" fill="currentColor" />
1462
              <circle cx="7" cy="17" r="1.4" fill="currentColor" />
1463
            </svg>
1464
          </button>
1465
          <button
1466
            type="button"
1467
            class="icon-btn only-desktop pane-toggle"
1468
            aria-pressed={!$navFolded}
1469
            aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
1470
            title={$navFolded ? 'Show channels' : 'Hide channels'}
1471
            on:click={() => navFolded.update((v) => !v)}
1472
          >
1473
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1474
              <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1475
              <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
1476
            </svg>
1477
          </button>
1478
          <div class="head-title">
1479
            <div class="head-room">
1480
              <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape={selectedRoom.space ? 'rounded' : 'circle'} />
1481
              <div class="head-room-text">
1482
                <h1>{selectedRoom.name}</h1>
1483
                <div class="head-meta">
1484
                  {#if selectedRoom.space}
1485
                    <span class="pill">space</span>
1486
                  {/if}
1487
                  {#if selectedRoom.encrypted}
1488
                    <span class="pill" title="End-to-end encrypted">🔒 encrypted</span>
1489
                  {/if}
1490
                  {#if selectedRoom.direct}
1491
                    <span class="pill">direct</span>
1492
                  {/if}
1493
                  <span class="conn" title={`Sync state: ${$connection}`}>
1494
                    <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1495
                    {$connection}
1496
                  </span>
1497
                </div>
1498
              </div>
1499
            </div>
1500
          </div>
1501
          <div class="head-actions">
1502
            {#if selectedRoom.membership !== 'Joined'}
1503
              <button
1504
                type="button"
1505
                class="primary-btn"
1506
                disabled={joinBusy}
1507
                on:click={() => void join(selectedRoom.room_id)}
1508
              >
1509
                {joinBusy ? 'Joining…' : 'Join'}
1510
              </button>
1511
            {/if}
1512
            <button
1513
              type="button"
1514
              class="icon-btn"
1515
              aria-pressed={membersOpen}
1516
              aria-label={membersOpen ? 'Hide members' : 'Show members'}
1517
              title="Members"
1518
              on:click={toggleMembers}
1519
            >
1520
              <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1521
                <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
1522
                <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
1523
              </svg>
1524
            </button>
1525
            <div class="room-menu-wrap" bind:this={roomMenuEl}>
1526
              <button
1527
                type="button"
1528
                class="icon-btn"
1529
                aria-haspopup="menu"
1530
                aria-expanded={roomMenuOpen}
1531
                aria-label="Room options"
1532
                title="Room options"
1533
                on:click={() => (roomMenuOpen = !roomMenuOpen)}
1534
              >
1535
                <span aria-hidden="true">⋯</span>
1536
              </button>
1537
              {#if roomMenuOpen}
1538
                <div class="room-menu" role="menu">
1539
                  <button type="button" role="menuitem" on:click={() => roomMenuAction(() => (dialog = 'security'))}>
1540
                    Security
1541
                  </button>
1542
                  {#if selectedRoom.membership === 'Joined'}
1543
                    <button
1544
                      type="button"
1545
                      role="menuitem"
1546
                      class="danger"
1547
                      disabled={leaveBusy}
1548
                      on:click={() => roomMenuAction(() => void leave())}
1549
                    >
1550
                      {leaveBusy ? 'Leaving…' : 'Leave room'}
1551
                    </button>
1552
                  {/if}
1553
                </div>
1554
              {/if}
1555
            </div>
1556
          </div>
1557
        </header>
1558
1559
1560
        {#if recoveryBanner}
1561
          <div class="sec-banner warn" role="status">
1562
            <span>Message history is locked</span>
1563
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
1564
          </div>
1565
        {/if}
1566
        {#if verificationBanner}
1567
          <div class="sec-banner" role="status">
1568
            {#if verificationBanner.kind === 'Incoming'}
1569
              <span>A device wants to verify this session</span>
1570
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
1571
            {:else if verificationBanner.kind === 'Comparison'}
1572
              <span>Verification codes ready</span>
1573
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
1574
            {:else if verificationBanner.kind === 'Waiting'}
1575
              <span>Verification started</span>
1576
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
1577
            {:else if verificationBanner.kind === 'Failed'}
1578
              <span>Verification failed: {verificationBanner.message}</span>
1579
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
1580
            {:else if verificationBanner.kind === 'Cancelled'}
1581
              <span>Verification cancelled: {verificationBanner.reason}</span>
1582
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
1583
            {:else}
1584
              <span>Verification in progress</span>
1585
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
1586
            {/if}
1587
          </div>
1588
        {/if}
1589
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
1590
          <p class="conn-banner error" role="alert">{openFailed[$selectedRoomId]}</p>
1591
        {/if}
1592
1593
        <!-- svelte-ignore a11y_no_static_element_interactions -->
1594
        <div
1595
          class="timeline"
1596
          bind:this={timelineEl}
1597
          on:scroll={onTimelineScroll}
1598
          on:wheel={noteUserScroll}
1599
          on:touchmove={noteUserScroll}
1600
          on:keydown={onTimelineKey}
1601
          on:pointerdown={onTimelinePointer}
1602
          aria-label={`Messages in ${selectedRoom.name}`}
1603
        >
1604
          <div class="timeline-inner" use:pinTimeline>
1605
            <div class="timeline-top">
1606
              {#if hasStart}
1607
                <p class="start-note">Beginning of history</p>
1608
              {:else}
1609
                <button type="button" class="ghost-btn" disabled={paginateBusy} on:click={() => void paginate()}>
1610
                  {paginateBusy ? 'Loading…' : 'Load older messages'}
1611
                </button>
1612
              {/if}
1613
            </div>
1614
            {#if grouped.length === 0}
1615
              <p class="side-note timeline-empty">No messages yet</p>
1616
            {:else}
1617
              {#each grouped as g (g.key)}
1618
                {#if g.item.kind === 'day'}
1619
                  <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div>
1620
                {:else if g.item.kind === 'readMarker'}
1621
                  <div class="new-row"><span>New</span></div>
1622
                {:else if g.item.kind === 'start'}
1623
                  <p class="start-note">Beginning of history</p>
1624
                {:else if g.item.kind === 'unknown'}
1625
                  <p class="unknown-note">Unsupported event ({g.item.label})</p>
1626
                {:else}
1627
                  <MessageRow
1628
                    itemId={g.key}
1629
                    event={g.item.event}
1630
                    showSender={g.showSender}
1631
                    senderAvatar={senderAvatarFor(g.item.event.sender.user_id) ?? g.item.event.sender.avatar}
1632
                    {reacting}
1633
                    onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
1634
                    quickReactions={$quickReactions}
1635
                    packs={roomPacks}
1636
                    linkPreviews={$linkPreviews}
1637
                    {loadPreview}
1638
                    onQuickChange={(list) => void changeQuickReactions(list)}
1639
                    {people}
1640
                    self={$sessionUser ?? null}
1641
                    onReply={selectedRoom.membership === 'Joined' ? startReply : null}
1642
                    onJump={jumpTo}
1643
                    onEdit={selectedRoom.membership === 'Joined' ? startEdit : null}
1644
                    editing={editing !== null && editing.eventId === g.item.event.event_id}
1645
                    showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0}
1646
                  />
1647
                {/if}
1648
              {/each}
1649
            {/if}
1650
            {#each pendingItems as p, i (p.id)}
1651
              <MessageRow
1652
                itemId={`pending-${p.id}`}
1653
                event={pendingToEvent(p)}
1654
                onJump={jumpTo}
1655
                showSender={pendingShowSender(i)}
1656
                senderAvatar={senderAvatarFor($sessionUser ?? '')}
1657
                {reacting}
1658
                onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
1659
                quickReactions={$quickReactions}
1660
                packs={roomPacks}
1661
                linkPreviews={$linkPreviews}
1662
                {loadPreview}
1663
                onQuickChange={(list) => void changeQuickReactions(list)}
1664
              />
1665
              {#if p.status === 'failed'}
1666
                <div class="pending-actions">
1667
                  <span class="pending-error" role="alert">{p.error}</span>
1668
                  <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button>
1669
                  <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button>
1670
                </div>
1671
              {/if}
1672
            {/each}
1673
          </div>
1674
        </div>
1675
1676
        {#if selectedRoom.membership === 'Joined'}
1677
          {#if editing}
1678
            <div class="reply-bar" role="status">
1679
              <span class="reply-bar-label">
1680
                Editing message
1681
                <span class="reply-bar-text">{editing.original}</span>
1682
              </span>
1683
              <button type="button" class="icon-btn" aria-label="Cancel edit" title="Cancel edit (Esc)" on:click={cancelEdit}>
1684
                <span aria-hidden="true">✕</span>
1685
              </button>
1686
            </div>
1687
          {:else if replyingTo && replyingTo.details.kind === 'Ready'}
1688
            <div class="reply-bar" role="status">
1689
              <span class="reply-bar-label">
1690
                Replying to <strong>{senderLabel(replyingTo.details.sender)}</strong>
1691
                <span class="reply-bar-text">{contentPreview(replyingTo.details.content)}</span>
1692
              </span>
1693
              <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}>
1694
                <span aria-hidden="true">✕</span>
1695
              </button>
1696
            </div>
1697
          {/if}
1698
          {#if $selectedRoomId && currentStaged.length > 0}
1699
            {@const stagedRoom = $selectedRoomId}
1700
            <ul class="staged" aria-label="Attachments to send">
1701
              {#each currentStaged as attachment (attachment.id)}
1702
                <li class="staged-item">
1703
                  {#if attachment.previewUrl}
1704
                    <img src={attachment.previewUrl} alt={attachment.file.name || 'Pasted image'} />
1705
                  {:else}
1706
                    <span class="staged-name">{attachment.file.name || 'attachment'}</span>
1707
                  {/if}
1708
                  <button
1709
                    type="button"
1710
                    class="icon-btn staged-remove"
1711
                    aria-label={`Remove ${attachment.file.name || 'attachment'}`}
1712
                    title="Remove"
1713
                    on:click={() => unstage(stagedRoom, attachment.id)}
1714
                  >
1715
                    <span aria-hidden="true">✕</span>
1716
                  </button>
1717
                </li>
1718
              {/each}
1719
            </ul>
1720
          {/if}
1721
          <form class="composer" class:replying={replyingTo || editing} class:staging={currentStaged.length > 0} on:submit|preventDefault={() => send()}>
1722
            <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label>
1723
            {#if mentionQuery && mentionCandidates.length > 0}
1724
              <ul class="mention-finder" role="listbox" aria-label="Mention someone">
1725
                {#each mentionCandidates as person, i (person.user_id)}
1726
                  <li
1727
                    role="option"
1728
                    aria-selected={i === mentionIndex}
1729
                    class:active={i === mentionIndex}
1730
                    on:pointerdown|preventDefault={() => void pickMention(person)}
1731
                    on:pointerenter={() => (mentionIndex = i)}
1732
                  >
1733
                    <MxcAvatar mxc={person.avatar} label={person.name} size={22} />
1734
                    <span class="mention-name">{person.name}</span>
1735
                    <span class="mention-id">{person.user_id}</span>
1736
                  </li>
1737
                {/each}
1738
              </ul>
1739
            {/if}
1740
            <input
1741
              type="file"
1742
              multiple
1743
              bind:this={fileInput}
1744
              class="visually-hidden"
1745
              aria-label="Attach a file"
1746
              on:change={() => void onFileChosen()}
1747
            />
1748
            <input
1749
              type="file"
1750
              accept="image/*"
1751
              bind:this={avatarInput}
1752
              class="visually-hidden"
1753
              aria-label="Choose a new avatar"
1754
              on:change={() => void onAvatarChosen()}
1755
            />
1756
            <button
1757
              type="button"
1758
              class="ghost-btn"
1759
              title="Attach an image or file"
1760
              aria-label="Attach an image or file"
1761
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
1762
              on:click={pickFiles}
1763
            >
1764
              {uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : '📎'}
1765
            </button>
1766
            <textarea
1767
              id="composer"
1768
              bind:this={composerEl}
1769
              bind:value={composer}
1770
              rows="1"
1771
              placeholder={`Message ${selectedRoom.name}`}
1772
              aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`}
1773
              on:keydown={onComposerKey}
1774
              on:input={updateMentionQuery}
1775
              on:click={updateMentionQuery}
1776
              on:keyup={(e) => (e.key.startsWith('Arrow') && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') || e.key === 'Home' || e.key === 'End' ? updateMentionQuery() : undefined}
1777
              on:blur={() => (mentionQuery = null)}
1778
              on:paste={onComposerPaste}
1779
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
1780
            ></textarea>
1781
            <button
1782
              type="button"
1783
              class="icon-btn md-toggle"
1784
              aria-pressed={$markdownEnabled}
1785
              aria-label={$markdownEnabled ? 'Turn markdown off' : 'Turn markdown on'}
1786
              title={$markdownEnabled ? 'Markdown on' : 'Markdown off'}
1787
              on:click={() => markdownEnabled.update((v) => !v)}
1788
            >
1789
              <svg viewBox="0 0 24 16" width="22" height="15" aria-hidden="true">
1790
                <rect x="1" y="1" width="22" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="1.6" />
1791
                <path d="M4.5 11.5v-7l2.75 3 2.75-3v7M15.5 4.5v6.5M13 8.5l2.5 2.75L18 8.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" />
1792
              </svg>
1793
            </button>
1794
            <button
1795
              type="submit"
1796
              class="primary-btn"
1797
              disabled={(!composer.trim() && currentStaged.length === 0) ||
1798
                !($selectedRoomId && openReady[$selectedRoomId]) ||
1799
                (currentStaged.length > 0 && uploadBusy)}
1800
              title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'}
1801
            >
1802
              Send
1803
            </button>
1804
          </form>
1805
        {:else}
1806
          <div class="join-bar">
1807
            <p>You are not a member of this room.</p>
1808
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
1809
              {joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`}
1810
            </button>
1811
          </div>
1812
        {/if}
1813
      {/if}
1814
    </main>
1815
1816
    {#if selectedRoom}
1817
      <aside class="members" aria-hidden={!membersOpen} aria-label={`Members of ${selectedRoom.name}`}>
1818
        <div class="members-head">
1819
          <h2>Members</h2>
1820
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
1821
            <span aria-hidden="true">✕</span>
1822
          </button>
1823
        </div>
1824
        {#if $membersLoading && members.length === 0}
1825
          <p class="side-note">Loading members…</p>
1826
        {:else if members.length === 0}
1827
          <p class="side-note">No members loaded.</p>
1828
          {#if $selectedRoomId}
1829
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
1830
              Retry
1831
            </button>
1832
          {/if}
1833
        {:else}
1834
          <ul class="member-list">
1835
            {#each members as member (member.user_id)}
1836
              <li class="member">
1837
                <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} size={30} />
1838
                <span class="member-names">
1839
                  <span class="member-name">{member.display_name || member.name}</span>
1840
                  <span class="member-id">{member.user_id}</span>
1841
                </span>
1842
              </li>
1843
            {/each}
1844
          </ul>
1845
        {/if}
1846
      </aside>
1847
    {/if}
1848
1849
    {#if dialog}
1850
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
1851
        {#if dialog === 'security'}
1852
          <SecurityPanel
1853
            encryptionState={$encryption}
1854
            verificationState={$verification}
1855
            onAction={() => void loadEncryption()}
1856
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
1857
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
1858
            on:close={() => (dialog = null)}
1859
          />
1860
        {:else if dialog === 'settings'}
1861
          <SettingsPanel
1862
            quick={$quickReactions}
1863
            packs={roomPacks}
1864
            onQuickChange={(list) => void changeQuickReactions(list)}
1865
            on:close={() => (dialog = null)}
1866
          />
1867
        {:else}
1868
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
1869
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
1870
              <button
1871
                type="button"
1872
                role="tab"
1873
                aria-selected={dialog === 'join'}
1874
                class:active={dialog === 'join'}
1875
                on:click={() => (dialog = 'join')}
1876
              >
1877
                Join
1878
              </button>
1879
              <button
1880
                type="button"
1881
                role="tab"
1882
                aria-selected={dialog === 'create'}
1883
                class:active={dialog === 'create'}
1884
                on:click={() => (dialog = 'create')}
1885
              >
1886
                Create
1887
              </button>
1888
              <button
1889
                type="button"
1890
                class="icon-btn modal-x"
1891
                aria-label="Close dialog"
1892
                on:click={() => (dialog = null)}
1893
              >
1894
                <span aria-hidden="true">✕</span>
1895
              </button>
1896
            </div>
1897
            {#if dialog === 'join'}
1898
              <form on:submit|preventDefault={() => void join(joinTarget)}>
1899
                <label class="field">
1900
                  <span>Room ID or alias</span>
1901
                  <input
1902
                    type="text"
1903
                    placeholder="!room:example.org or #alias:example.org"
1904
                    bind:value={joinTarget}
1905
                    required
1906
                    disabled={joinBusy}
1907
                  />
1908
                </label>
1909
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
1910
                  {joinBusy ? 'Joining…' : 'Join room'}
1911
                </button>
1912
              </form>
1913
            {:else}
1914
            <form on:submit|preventDefault={() => void create()}>
1915
              <label class="field">
1916
                <span>Room name</span>
1917
                <input
1918
                  type="text"
1919
                  placeholder="Weekend plans"
1920
                  bind:value={createName}
1921
                  required
1922
                  disabled={createBusy}
1923
                />
1924
              </label>
1925
              <label class="field">
1926
                <span>Topic (optional)</span>
1927
                <input
1928
                  type="text"
1929
                  placeholder="What should this room be about?"
1930
                  bind:value={createTopic}
1931
                  disabled={createBusy}
1932
                />
1933
              </label>
1934
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
1935
                {createBusy ? 'Creating…' : 'Create room'}
1936
              </button>
1937
            </form>
1938
            {/if}
1939
          </div>
1940
        {/if}
1941
      </div>
1942
    {/if}
1943
  </div>
1944
{/if}
1945
1946
<ImageLightbox />