atagen

malice

public
Star0
Watch0
d07bca5da4ae8096444c8411d8ca0c4bf01dee66
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte2796 lines111.9 KB
1
<script lang="ts">
2
  import { onMount, tick } from 'svelte';
3
  import { fade, fly } from 'svelte/transition';
4
  import LoginPanel from './lib/LoginPanel.svelte';
5
  import MentionsInbox from './lib/MentionsInbox.svelte';
6
  import MxcAvatar from './lib/MxcAvatar.svelte';
7
  import PinButton from './lib/PinButton.svelte';
8
  import ThreadPane from './lib/ThreadPane.svelte';
9
  import Composer from './lib/Composer.svelte';
10
  import SearchView from './lib/SearchView.svelte';
11
  import RoomTimelineRows from './lib/RoomTimelineRows.svelte';
12
  import type { ScopeOption } from './lib/search-model';
13
  import { releaseStaged, stageFiles as stageAttachments, type StagedAttachment, type StickerHandlers } from './lib/staging';
14
  import RoomThreads from './lib/RoomThreads.svelte';
15
  import { loadOlderThreads, loadPinnedThreads, openThread, showThread, syncThreadLists, threadsByRoom } from './lib/threads';
16
  import { threadMatches } from './lib/thread-index';
17
  import ContextMenu, { type MenuItem } from './lib/ContextMenu.svelte';
18
  import PackManager from './lib/PackManager.svelte';
19
  import PackCloneDialog from './lib/PackCloneDialog.svelte';
20
  import type { CloneSource } from './lib/pack-clone';
21
  import { allPacks, findSticker, reactionShortcode } from './lib/packs';
22
  import { disabledPackImages, loadPackPreferences } from './lib/pack-preferences';
23
  import { enabledPacks, enabledQuickReactions } from './lib/pack-preferences-model';
24
  import type { CommandRequest } from './lib/transport';
25
  import UserCard, { type UserAction } from './lib/UserCard.svelte';
26
  import { allowed, canRedact, groupMembers, isMuted, parsePowerLevels, type PowerLevels } from './lib/permissions';
27
  import { moveBefore, pinnedFirst, sortSpaces } from './lib/rail-order';
28
  import ImageLightbox from './lib/ImageLightbox.svelte';
29
  import { lightbox } from './lib/lightbox';
30
  import SecurityPanel from './lib/SecurityPanel.svelte';
31
  import {
32
    closeRoom,
33
    createRoom,
34
    getEncryption,
35
    getMembers,
36
    getProfile,
37
    getRooms,
38
    getSession,
39
    getSpaceChildren,
40
    fillHistoryGap,
41
    retryRecentHistory as requestRecentHistory,
42
    joinRoom,
43
    leaveRoom,
44
    logout,
45
    markRead,
46
    openRoom,
47
    paginateRoom,
48
    reactToMessage,
49
    runCommand,
50
    sendMessage,
51
    uploadAttachment,
52
    uploadAvatar,
53
    uploadRoomAvatar,
54
    editMessage
55
  } from './lib/api';
56
  import EmojiText from './lib/EmojiText.svelte';
57
  import { customEmotes, resolveEmotes } from './lib/emotes';
58
  import { isKnownCommand, parseCommand, splitTarget, unescapeCommand } from './lib/commands';
59
  import type { ParsedCommand } from './lib/commands';
60
  import {
61
    threadLists,
62
    banners,
63
    blocked,
64
    connectEvents,
65
    connection,
66
    disconnectEvents,
67
    dismissBanner,
68
    encryption,
69
    membersByRoom,
70
    membersLoading,
71
    mentionsSnapshot,
72
    pushBanner,
73
    imagePacks,
74
    markTimelineOpened,
75
    recentHistory,
76
    resetClientState,
77
    rooms,
78
    selectedRoomId,
79
    sessionUser,
80
    softLogout,
81
    threadTimelines,
82
    timelines,
83
    pinnedTimelines,
84
    pinnedTimelineVersions,
85
    verification
86
  } from './lib/store';
87
  import { discardPending, pendingByRoom, queueSend, resetPending, retryPending } from './lib/pending';
88
  import type { PendingMessage } from './lib/pending';
89
  import { TimelineViewport } from './lib/timeline-viewport';
90
  import { motionActive, motionDuration } from './lib/motion';
91
  import { mentionsFromHtml, resolveMentions } from './lib/mentions';
92
  import type { Mention } from './lib/mentions';
93
  import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions';
94
  import { loadKeywords } from './lib/keywords';
95
  import {
96
    linkPreviews,
97
    loadUrlPreviewSettings,
98
    requestLinkPreview,
99
    saveUrlPreviewSettings,
100
    urlPreviewSettings
101
  } from './lib/link-previews';
102
  import { notifyTyping, stopTyping } from './lib/typing';
103
  import {
104
    MEMBERS_WIDTH,
105
    SIDE_WIDTH,
106
    THREAD_WIDTH,
107
    lastSpaceRooms,
108
    lineHeight,
109
    membersWidth,
110
    messageSpacing,
111
    navFolded,
112
    railFolded,
113
    sideWidth,
114
    threadWidth
115
  } from './lib/appearance';
116
  import SettingsPanel from './lib/SettingsPanel.svelte';
117
  import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types';
118
  import type { ImagePack, MemberSummary, OwnProfile, PackImage, Person, QuickReaction, ReplyReference, RoomSummary, TimelineEvent, TimelineItem } from './lib/types';
119
120
  let roomsLoading = false;
121
  let booted = false;
122
  let wasOnline = false;
123
  let search = '';
124
  let sidebarOpen = false;
125
  let membersOpen = false;
126
  let replyingTo: ReplyReference | null = null;
127
  let dialog: 'join' | 'create' | 'security' | 'settings' | 'packs' | null = null;
128
  let cloneSource: CloneSource | null = null;
129
  let joinTarget = '';
130
  let joinBusy = false;
131
  let createName = '';
132
  let createTopic = '';
133
  let createBusy = false;
134
  let leaveBusy = false;
135
  let paginateBusy = false;
136
  let fillingGaps: Record<string, string> = {};
137
  let recentRetrying: Record<string, boolean> = {};
138
  let historyAccount: string | null | undefined;
139
  $: if ($sessionUser !== historyAccount) {
140
    historyAccount = $sessionUser;
141
    fillingGaps = {};
142
    recentRetrying = {};
143
  }
144
  let reacting = false;
145
  let composer = '';
146
  let drafts: Record<string, string> = {};
147
  let stickToBottom = true;
148
  let farFromLatest = false;
149
  let timelineEl: HTMLElement | null = null;
150
  let timelineRows: RoomTimelineRows | null = null;
151
  let timelineViewport: TimelineViewport | null = null;
152
  let composerRef: Composer | null = null;
153
  let avatarInput: HTMLInputElement | null = null;
154
  let uploadBusy = false;
155
  let uploadName: string | null = null;
156
  let staged: Record<string, StagedAttachment[]> = {};
157
  let editing: { roomId: string; eventId: string; original: string; stash: string } | null = null;
158
  /** Everyone picked from the finder per room; only those whose name is still in the text get linked on send. */
159
  let pickedMentions: Record<string, Mention[]> = {};
160
  const WARM_ROOM_LIMIT = 8;
161
  /** Rooms left open after switching away so coming back is instant, least recently viewed first. */
162
  let warmRooms: string[] = [];
163
  let openReady: Record<string, boolean> = {};
164
  let openFailed: Record<string, string> = {};
165
  let membersFor: string | null = null;
166
  let lastReadKey = '';
167
  let readTimer: number | null = null;
168
  let profile: OwnProfile | null = null;
169
  let profileMxc: string | null = null;
170
  let selectedSpaceId: string | null = null;
171
  let mentionsOpen = false;
172
  let searchOpen = false;
173
  let searchScopes: ScopeOption[] = [{ label: 'Everywhere', scope: { kind: 'all' } }];
174
  let spaceChildIds: string[] | null = null;
175
  let spaceChildrenLoading = false;
176
  let spaceChildrenError: string | null = null;
177
  let avatarByUser: Record<string, string | null> = {};
178
  let restoringRoute = false;
179
180
  // account data is read from the local cache, which is empty on a fresh device until the first sync lands
181
  $: {
182
    const online = $connection === 'online';
183
    if (online && !wasOnline) {
184
      void loadQuickReactions();
185
      void loadKeywords();
186
      void loadPinnedThreads();
187
      void loadPackPreferences();
188
      void loadUrlPreviewSettings();
189
    }
190
    wasOnline = online;
191
  }
192
  $: selectedRoom = $rooms.find((r) => r.room_id === $selectedRoomId) ?? null;
193
  $: recentState = $selectedRoomId ? $recentHistory[$selectedRoomId] : undefined;
194
  $: roomPacks = enabledPacks(packsForRoom($imagePacks, $selectedRoomId, $rooms), $disabledPackImages);
195
  $: roomEmotes = customEmotes(roomPacks);
196
  $: usableQuickReactions = enabledQuickReactions($quickReactions, allPacks($imagePacks), $disabledPackImages);
197
  $: previewsAllowed = selectedRoom !== null && (!selectedRoom.encrypted || $urlPreviewSettings.encrypted_rooms);
198
  $: loadPreview = previewsAllowed && $selectedRoomId ? previewLoader($selectedRoomId) : null;
199
  $: spaceRooms = $rooms.filter((r) => r.space);
200
  $: spaceParents = parentSpaceMap(spaceRooms);
201
  $: railSpaces = spaceRooms.filter((s) => !spaceParents.has(s.room_id));
202
  let railOverride: string[] | null = null;
203
  $: if (railOverride && sortSpaces(railSpaces, null).map((s) => s.room_id).join() === railOverride.join()) railOverride = null;
204
  $: orderedRail = sortSpaces(railSpaces, railOverride);
205
  $: pinnedRail = orderedRail.filter((s) => s.favourite);
206
  $: otherRail = orderedRail.filter((s) => !s.favourite);
207
  $: unreadSpaces = spacesWithUnread($rooms, spaceParents);
208
  $: homeUnread =
209
    ($mentionsSnapshot?.unread_count ?? 0) > 0 ||
210
    $rooms.some((r) => r.direct && !r.space && r.membership === 'Joined' && roomUnread(r) > 0);
211
  $: railSelected = selectedSpaceId ? topSpaceOf(selectedSpaceId, spaceParents) : null;
212
  $: invites = $rooms.filter((r) => r.membership === 'Invited');
213
  $: query = search.trim().toLowerCase();
214
  $: selectedSpace = selectedSpaceId ? ($rooms.find((r) => r.room_id === selectedSpaceId) ?? null) : null;
215
  // While a space's children load (or fail), show no channels rather than the
216
  // full list — listing everything would falsely imply it belongs to the space.
217
  $: baseRooms = selectedSpaceId ? (spaceChildIds ? $rooms.filter((r) => spaceChildIds?.includes(r.room_id)) : []) : $rooms;
218
  $: visibleRooms = query
219
    ? baseRooms.filter(
220
        (r) =>
221
          r.name.toLowerCase().includes(query) ||
222
          r.room_id.toLowerCase().includes(query) ||
223
          ($threadsByRoom[r.room_id] ?? []).some((t) => threadMatches(t, query))
224
      )
225
    : baseRooms;
226
  $: directRooms = pinnedFirst(visibleRooms.filter((r) => r.direct && !r.space && r.membership !== 'Invited'));
227
  $: groupRooms = pinnedFirst(visibleRooms.filter((r) => !r.direct && !r.space && r.membership !== 'Invited'));
228
  $: spaceList = pinnedFirst(visibleRooms.filter((r) => r.space && r.membership !== 'Invited'));
229
  $: channelRooms = baseRooms.filter((r) => !r.space && r.membership !== 'Invited');
230
  $: recoveryBanner = $encryption && ($encryption.recovery === 'Disabled' || $encryption.recovery === 'Incomplete') ? $encryption : null;
231
  $: verificationBanner = $verification && $verification.kind !== 'Done' ? $verification : null;
232
  $: items = $selectedRoomId ? ($timelines[$selectedRoomId] ?? []) : [];
233
  $: currentStaged = $selectedRoomId ? (staged[$selectedRoomId] ?? []) : [];
234
  $: members = $selectedRoomId ? ($membersByRoom[$selectedRoomId] ?? []) : [];
235
  $: memberGroups = groupMembers(members, roomLevels);
236
  $: people = peopleIn(items, members);
237
  $: hasStart = items.some((i) => i.kind === 'start');
238
  $: pendingItems = $selectedRoomId ? ($pendingByRoom[$selectedRoomId] ?? []) : [];
239
240
  function roomUnread(r: RoomSummary): number {
241
    return r.unread_messages + r.unread_mentions;
242
  }
243
244
  function recordRoute(spaceId: string | null, roomId: string | null, view?: string): void {
245
    if (restoringRoute) return;
246
    const url = new URL(window.location.href);
247
    url.searchParams.delete('space');
248
    url.searchParams.delete('room');
249
    url.searchParams.delete('view');
250
    if (view) url.searchParams.set('view', view);
251
    if (spaceId) url.searchParams.set('space', spaceId);
252
    if (roomId) url.searchParams.set('room', roomId);
253
    const next = `${url.pathname}${url.search}${url.hash}`;
254
    const current = `${window.location.pathname}${window.location.search}${window.location.hash}`;
255
    if (next !== current) window.history.pushState({ spaceId, roomId }, '', next);
256
  }
257
258
  async function restoreRoute(): Promise<void> {
259
    const url = new URL(window.location.href);
260
    const roomId = url.searchParams.get('room');
261
    const spaceId = url.searchParams.get('space');
262
    restoringRoute = true;
263
    try {
264
      if (url.searchParams.get('view') === 'mentions') {
265
        selectMentions();
266
      } else if (url.searchParams.get('view') === 'search') {
267
        selectSearch();
268
      } else if (roomId && $rooms.some((room) => room.room_id === roomId && !room.space)) {
269
        selectedSpaceId = spaceId && $rooms.some((room) => room.room_id === spaceId && room.space) ? spaceId : null;
270
        spaceChildrenError = null;
271
        spaceChildIds = selectedSpaceId ? (await getSpaceChildren(selectedSpaceId)).room_ids ?? [] : null;
272
        await selectRoom(roomId);
273
      } else if (spaceId && $rooms.some((room) => room.room_id === spaceId && room.space)) {
274
        await selectSpace(spaceId);
275
      } else {
276
        await selectHome();
277
      }
278
    } catch (e) {
279
      pushBanner(e instanceof Error ? e.message : 'Could not restore navigation');
280
    } finally {
281
      restoringRoute = false;
282
    }
283
  }
284
285
  function isEditable(target: EventTarget | null): boolean {
286
    if (!(target instanceof HTMLElement)) return false;
287
    return target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement || target.isContentEditable;
288
  }
289
290
  onMount(() => {
291
    const onPopState = () => void restoreRoute();
292
    const onAttention = () => queueReadReceipt();
293
    const hidePointer = (e: KeyboardEvent) => {
294
      if (e.ctrlKey || e.metaKey || e.altKey || !isEditable(e.target)) return;
295
      if (e.key.length === 1 || e.key === 'Backspace' || e.key === 'Delete' || e.key === 'Enter') {
296
        document.documentElement.classList.add('pointer-hidden');
297
      }
298
    };
299
    const showPointer = () => document.documentElement.classList.remove('pointer-hidden');
300
    const movePointer = (e: PointerEvent) => {
301
      if (e.movementX !== 0 || e.movementY !== 0) showPointer();
302
    };
303
    window.addEventListener('popstate', onPopState);
304
    window.addEventListener('focus', onAttention);
305
    document.addEventListener('visibilitychange', onAttention);
306
    window.addEventListener('keydown', hidePointer, true);
307
    window.addEventListener('pointermove', movePointer);
308
    window.addEventListener('pointerdown', showPointer);
309
    void boot();
310
    return () => {
311
      window.removeEventListener('popstate', onPopState);
312
      window.removeEventListener('focus', onAttention);
313
      document.removeEventListener('visibilitychange', onAttention);
314
      window.removeEventListener('keydown', hidePointer, true);
315
      window.removeEventListener('pointermove', movePointer);
316
      window.removeEventListener('pointerdown', showPointer);
317
      showPointer();
318
      disconnectEvents();
319
      stopTyping();
320
      if (readTimer !== null) window.clearTimeout(readTimer);
321
    };
322
  });
323
324
  async function boot(): Promise<void> {
325
    try {
326
      const session = await getSession();
327
      blocked.set(session.blocked ?? false);
328
      sessionUser.set(session.user_id);
329
      if (session.user_id) {
330
        softLogout.set(null);
331
        await refreshRooms();
332
        await restoreRoute();
333
        connectEvents();
334
        void loadProfile();
335
        void loadEncryption();
336
        void loadQuickReactions();
337
        void loadKeywords();
338
        void loadPinnedThreads();
339
        void loadPackPreferences();
340
        void loadUrlPreviewSettings();
341
      } else {
342
        softLogout.set(session.soft_logout ?? null);
343
      }
344
    } catch (e) {
345
      pushBanner(e instanceof Error ? `Session check failed: ${e.message}` : 'Session check failed');
346
      sessionUser.set(null);
347
    } finally {
348
      booted = true;
349
    }
350
  }
351
352
  async function refreshRooms(): Promise<void> {
353
    roomsLoading = true;
354
    try {
355
      const res = await getRooms();
356
      rooms.set(res.rooms);
357
      pruneSpaceFilter();
358
    } catch (e) {
359
      pushBanner(e instanceof Error ? e.message : 'Could not load rooms');
360
    } finally {
361
      roomsLoading = false;
362
    }
363
  }
364
365
  async function loadProfile(): Promise<void> {
366
    try {
367
      const raw = await getProfile();
368
      profile = parseOwnProfile(raw);
369
      profileMxc = profile.avatar_url;
370
    } catch {
371
      profile = null;
372
    }
373
  }
374
375
  async function loadEncryption(): Promise<void> {
376
    try {
377
      const res = await getEncryption();
378
      const state = parseEncryptionState(res.state);
379
      if (state) encryption.set(state);
380
      const verificationState = parseVerificationState(res.verification);
381
      if (verificationState) verification.set(verificationState);
382
    } catch {
383
      // Encryption status also arrives over SSE; a failed first fetch is not fatal.
384
    }
385
  }
386
387
  function afterLogin(userId: string): void {
388
    sessionUser.set(userId);
389
    softLogout.set(null);
390
    blocked.set(false);
391
    void refreshRooms();
392
    connectEvents();
393
    void loadProfile();
394
    void loadEncryption();
395
    void loadQuickReactions();
396
    void loadKeywords();
397
    void loadPinnedThreads();
398
    void loadPackPreferences();
399
    void loadUrlPreviewSettings();
400
  }
401
402
  async function doLogout(): Promise<void> {
403
    stopTyping();
404
    try {
405
      await logout();
406
    } catch (e) {
407
      pushBanner(e instanceof Error ? e.message : 'Logout failed');
408
      return;
409
    }
410
    disconnectEvents();
411
    resetClientState();
412
    softLogout.set(null);
413
    blocked.set(false);
414
    sessionUser.set(null);
415
    lightbox.set(null);
416
    composer = '';
417
    drafts = {};
418
    dialog = null;
419
    cloneSource = null;
420
    membersOpen = false;
421
    sidebarOpen = false;
422
    profile = null;
423
    profileMxc = null;
424
    mentionsOpen = false;
425
    searchOpen = false;
426
    selectedSpaceId = null;
427
    spaceChildIds = null;
428
    spaceChildrenError = null;
429
    openReady = {};
430
    openFailed = {};
431
    warmRooms = [];
432
    pickedMentions = {};
433
    composerRef?.closeFinders();
434
    clearAllStaged();
435
    avatarByUser = {};
436
    resetPending();
437
  }
438
439
  /** Joined spaces that sit inside another joined space, keyed to one such parent. Either side of the link counts. */
440
  function parentSpaceMap(spaces: RoomSummary[]): Map<string, string> {
441
    const ids = new Set(spaces.map((s) => s.room_id));
442
    const parents = new Map<string, string>();
443
    for (const space of spaces) {
444
      for (const child of space.children) {
445
        if (child !== space.room_id && ids.has(child) && !parents.has(child)) parents.set(child, space.room_id);
446
      }
447
    }
448
    for (const space of spaces) {
449
      const parent = space.parent_spaces.find((id) => id !== space.room_id && ids.has(id));
450
      if (parent && !parents.has(space.room_id)) parents.set(space.room_id, parent);
451
    }
452
    for (const id of [...parents.keys()]) {
453
      const seen = new Set<string>([id]);
454
      let at = parents.get(id);
455
      while (at && !seen.has(at)) {
456
        seen.add(at);
457
        at = parents.get(at);
458
      }
459
      if (at) parents.delete(id);
460
    }
461
    return parents;
462
  }
463
464
  function spacesWithUnread(all: RoomSummary[], parents: Map<string, string>): Set<string> {
465
    const spaces = all.filter((r) => r.space);
466
    const ids = new Set(spaces.map((s) => s.room_id));
467
    const out = new Set<string>();
468
    for (const room of all) {
469
      if (room.space || room.membership !== 'Joined' || roomUnread(room) === 0) continue;
470
      const owners = [...room.parent_spaces, ...spaces.filter((s) => s.children.includes(room.room_id)).map((s) => s.room_id)];
471
      for (const id of owners) if (ids.has(id)) out.add(topSpaceOf(id, parents));
472
    }
473
    return out;
474
  }
475
476
  function topSpaceOf(id: string, parents: Map<string, string>): string {
477
    let at = id;
478
    while (parents.has(at)) at = parents.get(at)!;
479
    return at;
480
  }
481
482
  function pruneSpaceFilter(): void {
483
    if (!selectedSpaceId) return;
484
    if (!$rooms.some((r) => r.room_id === selectedSpaceId)) {
485
      selectedSpaceId = null;
486
      spaceChildIds = null;
487
      spaceChildrenError = null;
488
    }
489
  }
490
491
  async function selectHome(): Promise<void> {
492
    mentionsOpen = false;
493
    searchOpen = false;
494
    selectedSpaceId = null;
495
    spaceChildIds = null;
496
    spaceChildrenError = null;
497
    if (window.innerWidth > 640) navFolded.set(false);
498
    sidebarOpen = true;
499
    recordRoute(null, null);
500
  }
501
502
  function stashDraft(): void {
503
    const roomId = $selectedRoomId;
504
    if (!roomId) return;
505
    if (composer.trim()) drafts[roomId] = composer;
506
    else delete drafts[roomId];
507
  }
508
509
  function selectMentions(): void {
510
    stashDraft();
511
    stopTyping();
512
    selectedSpaceId = null;
513
    spaceChildIds = null;
514
    spaceChildrenError = null;
515
    spaceChildrenLoading = false;
516
    selectedRoomId.set(null);
517
    replyingTo = null;
518
    editing = null;
519
    composerRef?.closeFinders();
520
    peeking = null;
521
    membersOpen = false;
522
    sidebarOpen = false;
523
    searchOpen = false;
524
    mentionsOpen = true;
525
    recordRoute(null, null, 'mentions');
526
  }
527
528
  function selectSearch(): void {
529
    const fromRoom = $selectedRoomId ? $rooms.find((r) => r.room_id === $selectedRoomId) ?? null : null;
530
    const options: ScopeOption[] = [];
531
    if (fromRoom) options.push({ label: fromRoom.name, scope: { kind: 'room', room_id: fromRoom.room_id } });
532
    if (selectedSpace && spaceChildIds) {
533
      const roomIds = spaceChildIds.filter((id) => $rooms.some((r) => r.room_id === id && !r.space));
534
      if (roomIds.length) options.push({ label: selectedSpace.name, scope: { kind: 'rooms', room_ids: roomIds } });
535
    }
536
    options.push({ label: 'Everywhere', scope: { kind: 'all' } });
537
    stashDraft();
538
    stopTyping();
539
    selectedRoomId.set(null);
540
    replyingTo = null;
541
    editing = null;
542
    composerRef?.closeFinders();
543
    peeking = null;
544
    membersOpen = false;
545
    sidebarOpen = false;
546
    mentionsOpen = false;
547
    searchScopes = options;
548
    searchOpen = true;
549
    recordRoute(selectedSpaceId, null, 'search');
550
  }
551
552
  function toggleChannelsPane(): void {
553
    if (window.innerWidth <= 640) sidebarOpen = !sidebarOpen;
554
    else navFolded.update((v) => !v);
555
  }
556
557
  async function selectSpace(spaceId: string): Promise<void> {
558
    mentionsOpen = false;
559
    searchOpen = false;
560
    stashDraft();
561
    stopTyping();
562
    selectedSpaceId = spaceId;
563
    spaceChildIds = null;
564
    spaceChildrenError = null;
565
    spaceChildrenLoading = true;
566
    const last = $lastSpaceRooms[spaceId];
567
    const resume = last && $rooms.some((r) => r.room_id === last && !r.space) ? last : null;
568
    if (resume) {
569
      void selectRoom(resume);
570
    } else {
571
      selectedRoomId.set(null);
572
    }
573
    try {
574
      const res = await getSpaceChildren(spaceId);
575
      if (selectedSpaceId === spaceId) {
576
        spaceChildIds = res.room_ids ?? [];
577
        const firstChannel = spaceChildIds
578
          .map((id) => $rooms.find((room) => room.room_id === id))
579
          .find((room) => room && !room.space);
580
        if ((!resume || !spaceChildIds.includes(resume)) && firstChannel) {
581
          await selectRoom(firstChannel.room_id);
582
        }
583
      }
584
    } catch (e) {
585
      if (selectedSpaceId === spaceId) {
586
        spaceChildrenError = e instanceof Error ? e.message : 'Could not load rooms in this space';
587
        spaceChildIds = [];
588
      }
589
    } finally {
590
      if (selectedSpaceId === spaceId) spaceChildrenLoading = false;
591
    }
592
  }
593
594
  async function selectRoom(roomId: string, peek = false): Promise<void> {
595
    mentionsOpen = false;
596
    searchOpen = false;
597
    peeking = peek ? roomId : null;
598
    stashDraft();
599
    if (roomId === $selectedRoomId && openReady[roomId]) {
600
      sidebarOpen = false;
601
      return;
602
    }
603
    stopTyping();
604
    const spaceId = selectedSpaceId;
605
    if (spaceId) lastSpaceRooms.update((all) => ({ ...all, [spaceId]: roomId }));
606
    selectedRoomId.set(roomId);
607
    recordRoute(selectedSpaceId, roomId);
608
    composer = drafts[roomId] ?? '';
609
    replyingTo = null;
610
    editing = null;
611
    composerRef?.closeFinders();
612
    stickToBottom = true;
613
    lastReadKey = '';
614
    sidebarOpen = false;
615
    touchWarmRoom(roomId);
616
    if (openReady[roomId]) {
617
      if (membersOpen) void loadMembers(roomId);
618
      await tick();
619
      scrollToBottom();
620
      queueReadReceipt();
621
      composerRef?.focus();
622
      return;
623
    }
624
    if (openFailed[roomId]) {
625
      const nextFailed = { ...openFailed };
626
      delete nextFailed[roomId];
627
      openFailed = nextFailed;
628
    }
629
    try {
630
      markTimelineOpened(roomId);
631
      await openRoom(roomId);
632
      if (warmRooms.includes(roomId)) openReady = { ...openReady, [roomId]: true };
633
    } catch (e) {
634
      const message = e instanceof Error ? e.message : `Could not open room ${roomId}`;
635
      openFailed = { ...openFailed, [roomId]: message };
636
      pushBanner(message);
637
    }
638
    if ($selectedRoomId !== roomId) return;
639
    if (membersOpen) void loadMembers(roomId);
640
    await tick();
641
    scrollToBottom();
642
    queueReadReceipt();
643
    composerRef?.focus();
644
  }
645
646
  function touchWarmRoom(roomId: string): void {
647
    warmRooms = [...warmRooms.filter((id) => id !== roomId), roomId];
648
    while (warmRooms.length > WARM_ROOM_LIMIT) {
649
      const evicted = warmRooms[0];
650
      warmRooms = warmRooms.slice(1);
651
      forgetOpenRoom(evicted);
652
      closeRoom(evicted).catch(() => undefined);
653
    }
654
  }
655
656
  function forgetOpenRoom(roomId: string): void {
657
    warmRooms = warmRooms.filter((id) => id !== roomId);
658
    const nextReady = { ...openReady };
659
    delete nextReady[roomId];
660
    openReady = nextReady;
661
  }
662
663
  function scrollToBottom(smooth = false): void {
664
    const reset = timelineRows?.resetToTail() ?? false;
665
    const scroll = () => {
666
      if (timelineViewport?.element === timelineEl) timelineViewport.scrollToBottom(smooth && !reset);
667
      else if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight;
668
    };
669
    if (reset) void tick().then(scroll);
670
    else scroll();
671
  }
672
673
  function jumpToLatest(): void {
674
    stickToBottom = true;
675
    scrollToBottom(true);
676
    queueReadReceipt();
677
  }
678
679
  function lastEventId(list: TimelineItem[]): string | null {
680
    for (let i = list.length - 1; i >= 0; i -= 1) {
681
      const item = list[i];
682
      if (item.kind === 'event') return item.event.item_id;
683
    }
684
    return null;
685
  }
686
687
  function countArrivals(list: TimelineItem[], seen: string | null): number {
688
    if (seen === null) return 0;
689
    const at = list.findIndex((item) => item.kind === 'event' && item.event.item_id === seen);
690
    if (at < 0) return 0;
691
    let count = 0;
692
    for (let i = at + 1; i < list.length; i += 1) {
693
      const item = list[i];
694
      if (item.kind === 'event' && !item.event.own) count += 1;
695
    }
696
    return count;
697
  }
698
699
  let seenLatest: string | null = null;
700
  $: if (stickToBottom) seenLatest = lastEventId(items);
701
  $: if (stickToBottom) farFromLatest = false;
702
  $: arrivals = stickToBottom ? 0 : countArrivals(items, seenLatest);
703
704
  function anchorGrowth(): void {
705
    timelineViewport?.capture();
706
    void tick().then(() => timelineViewport?.restore());
707
  }
708
709
  function noteUserScroll(): void {
710
    timelineViewport?.releaseScroll();
711
  }
712
713
  function onTimelineKey(e: KeyboardEvent): void {
714
    if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) noteUserScroll();
715
  }
716
717
  const WINDOW_EDGE = 600;
718
719
  function onTimelineScroll(): void {
720
    if (!timelineEl) return;
721
    if (timelineViewport?.consumeScroll()) return;
722
    const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight;
723
    const wasAtBottom = stickToBottom;
724
    stickToBottom = gap < 2 && (timelineRows?.atTail() ?? true);
725
    farFromLatest = gap > 240 || !(timelineRows?.atTail() ?? true);
726
    if (stickToBottom && !wasAtBottom) queueReadReceipt();
727
    timelineViewport?.capture();
728
    const grew = (timelineEl.scrollTop < WINDOW_EDGE && timelineRows?.grow('up')) || (gap < WINDOW_EDGE && timelineRows?.grow('down'));
729
    if (grew) anchorGrowth();
730
    else if (timelineEl.scrollTop < 80 && !hasStart && !paginateBusy) void paginate();
731
  }
732
733
  function pinTimeline(node: HTMLElement) {
734
    const viewport = new TimelineViewport(node.parentElement!, $selectedRoomId);
735
    timelineViewport = viewport;
736
    const observer = new ResizeObserver(() => {
737
      if (timelineViewport !== viewport || viewport.roomId !== $selectedRoomId) return;
738
      if (stickToBottom) viewport.scrollToBottom(!motionActive());
739
      else viewport.restore();
740
    });
741
    observer.observe(node);
742
    if (node.parentElement) observer.observe(node.parentElement);
743
    return { destroy: () => {
744
      observer.disconnect();
745
      viewport.releaseScroll();
746
      if (timelineViewport === viewport) timelineViewport = null;
747
    } };
748
  }
749
750
  $: void trackTimeline($selectedRoomId, items);
751
  async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> {
752
    if (!roomId || list.length === 0) return;
753
    if (roomId !== $selectedRoomId) return;
754
    await tick();
755
    if (roomId !== $selectedRoomId || timelineViewport?.roomId !== roomId) return;
756
    if (stickToBottom) timelineViewport.scrollToBottom(!motionActive());
757
    else timelineViewport.restore();
758
    queueReadReceipt();
759
  }
760
761
  function queueReadReceipt(): void {
762
    if (readTimer !== null) window.clearTimeout(readTimer);
763
    readTimer = window.setTimeout(() => {
764
      readTimer = null;
765
      void sendReadReceipt();
766
    }, 800);
767
  }
768
769
  async function sendReadReceipt(): Promise<void> {
770
    const roomId = $selectedRoomId;
771
    if (!roomId || roomId === peeking) return;
772
    if (document.hidden || !document.hasFocus() || !stickToBottom) return;
773
    const list = $timelines[roomId] ?? [];
774
    for (let i = list.length - 1; i >= 0; i -= 1) {
775
      const entry = list[i];
776
      if (entry.kind === 'event' && entry.event.event_id) {
777
        const key = `${roomId}:${entry.event.event_id}`;
778
        if (key === lastReadKey) return;
779
        lastReadKey = key;
780
        try {
781
          await markRead(roomId, entry.event.event_id);
782
        } catch {
783
          return;
784
        }
785
        return;
786
      }
787
    }
788
  }
789
790
  function send(): void {
791
    if (editing) {
792
      submitEdit();
793
      return;
794
    }
795
    const roomId = $selectedRoomId;
796
    const body = composer.trim();
797
    const attachments = roomId ? (staged[roomId] ?? []) : [];
798
    if (!roomId || (!body && attachments.length === 0)) return;
799
    if (!openReady[roomId]) {
800
      pushBanner('Still opening this room — sending is disabled until the room is ready.');
801
      return;
802
    }
803
    if (attachments.length > 0 && uploadBusy) return;
804
    const command = parseCommand(body);
805
    if (command && !isKnownCommand(command.name)) {
806
      pushBanner(`Unknown command /${command.name}`);
807
      return;
808
    }
809
    if (command && attachments.length > 0) {
810
      if (command.name !== 'roomavatar' && command.name !== 'globalavatar') {
811
        pushBanner(`/${command.name} doesn't take attachments`);
812
        return;
813
      }
814
      if (command.args || attachments.length !== 1 || !attachments[0].file.type.startsWith('image/')) {
815
        pushBanner(`/${command.name} takes a single attached image`);
816
        return;
817
      }
818
    }
819
    composer = '';
820
    if (roomId in drafts) delete drafts[roomId];
821
    stickToBottom = true;
822
    const reply = replyingTo;
823
    replyingTo = null;
824
    const text = unescapeCommand(body);
825
    const mentions = resolveMentions(text, pickedMentions[roomId] ?? []);
826
    pickedMentions = { ...pickedMentions, [roomId]: [] };
827
    composerRef?.closeFinders();
828
    if (command) {
829
      const image = attachments[0] ?? null;
830
      if (image) {
831
        const { [roomId]: _used, ...rest } = staged;
832
        staged = rest;
833
      }
834
      void execute(roomId, command, reply, mentions, image?.file ?? null).finally(() => {
835
        if (image?.previewUrl) URL.revokeObjectURL(image.previewUrl);
836
      });
837
    } else if (attachments.length === 0) {
838
      queueSend(roomId, text, reply, mentions, resolveEmotes(text, roomEmotes));
839
    } else {
840
      const { [roomId]: _sent, ...rest } = staged;
841
      staged = rest;
842
      void sendAttachments(roomId, text, reply, mentions, attachments);
843
    }
844
    if (peeking === roomId) stopPeeking();
845
    composerRef?.focus();
846
  }
847
848
  function lastOwnEventId(): string | null {
849
    for (let i = items.length - 1; i >= 0; i -= 1) {
850
      const entry = items[i];
851
      if (entry.kind === 'event' && entry.event.own && entry.event.event_id && entry.event.content.kind !== 'Redacted') {
852
        return entry.event.event_id;
853
      }
854
    }
855
    return null;
856
  }
857
858
  async function execute(
859
    roomId: string,
860
    command: ParsedCommand,
861
    reply: ReplyReference | null,
862
    mentions: Mention[],
863
    image: File | null
864
  ): Promise<void> {
865
    const { name, args } = command;
866
    const target = () => {
867
      const found = splitTarget(args, Object.values(people));
868
      if ('error' in found) throw new Error(found.error);
869
      return found;
870
    };
871
    const required = (what: string) => {
872
      if (!args) throw new Error(`/${name} needs ${what}`);
873
      return args;
874
    };
875
    try {
876
      switch (name) {
877
        case 'me':
878
        case 'notice': {
879
          const said = required('something to say');
880
          await sendMessage(roomId, said, null, mentions, name === 'me' ? 'emote' : 'notice', resolveEmotes(said, roomEmotes));
881
          break;
882
        }
883
        case 'sticker': {
884
          const { pack, sticker } = findSticker(enabledPacks(packsForRoom($imagePacks, roomId, $rooms), $disabledPackImages), required('a sticker name'));
885
          await runCommand({ op: 'send_sticker', room_id: roomId, pack_id: pack.id, shortcode: sticker.shortcode });
886
          break;
887
        }
888
        case 'msg': {
889
          const { user_id, rest } = target();
890
          const res = (await runCommand({ op: 'direct', user_id })) as { room_id: string };
891
          await refreshRooms();
892
          await selectRoom(res.room_id);
893
          if (rest) queueSend(res.room_id, rest);
894
          break;
895
        }
896
        case 'join':
897
          await join(required('a room id or alias'));
898
          break;
899
        case 'leave':
900
          await leave();
901
          break;
902
        case 'invite':
903
          await runCommand({ op: 'invite', room_id: roomId, user_id: target().user_id });
904
          break;
905
        case 'disinvite':
906
        case 'kick':
907
        case 'ban':
908
        case 'unban': {
909
          const { user_id, rest } = target();
910
          const op = name === 'disinvite' ? 'kick' : name;
911
          await runCommand({ op, room_id: roomId, user_id, reason: rest || null });
912
          break;
913
        }
914
        case 'powerlevel': {
915
          const { user_id, rest } = target();
916
          const level = Number(rest);
917
          if (!rest || !Number.isInteger(level)) throw new Error('/powerlevel needs a whole number after the name');
918
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id, level });
919
          break;
920
        }
921
        case 'mute':
922
        case 'unmute':
923
          await runCommand({ op: 'mute', room_id: roomId, user_id: target().user_id, muted: name === 'mute' });
924
          break;
925
        case 'ignore':
926
        case 'unignore':
927
          await runCommand({ op: name, user_id: target().user_id });
928
          break;
929
        case 'roomnick':
930
          await runCommand({ op: 'set_room_display_name', room_id: roomId, name: args || null });
931
          break;
932
        case 'roomavatar':
933
          if (image) {
934
            await uploadRoomAvatar(roomId, image);
935
          } else if (args && !args.startsWith('mxc://')) {
936
            throw new Error('/roomavatar takes an mxc:// link, an attached image, or nothing to drop the override');
937
          } else {
938
            await runCommand({ op: 'set_room_avatar', room_id: roomId, mxc: args || null });
939
          }
940
          break;
941
        case 'delete': {
942
          const eventId = reply?.event_id ?? lastOwnEventId();
943
          if (!eventId) throw new Error('Nothing of yours to delete here');
944
          await runCommand({ op: 'redact', room_id: roomId, event_id: eventId, reason: args || null });
945
          break;
946
        }
947
        case 'globalnick':
948
          await runCommand({ op: 'set_display_name', name: required('a name') });
949
          await loadProfile();
950
          break;
951
        case 'globalavatar':
952
          if (image) {
953
            await uploadAvatar(image);
954
            await loadProfile();
955
          } else if (!args) {
956
            avatarInput?.click();
957
          } else if (args.startsWith('mxc://')) {
958
            await runCommand({ op: 'set_avatar', mxc: args });
959
            await loadProfile();
960
          } else {
961
            throw new Error('/globalavatar takes an mxc:// link, or nothing to pick a file');
962
          }
963
          break;
964
      }
965
    } catch (e) {
966
      pushBanner(e instanceof Error ? e.message : `/${name} failed`);
967
    }
968
  }
969
970
  async function onAvatarChosen(): Promise<void> {
971
    const file = avatarInput?.files?.[0];
972
    if (avatarInput) avatarInput.value = '';
973
    if (!file) return;
974
    try {
975
      await uploadAvatar(file);
976
      await loadProfile();
977
    } catch (e) {
978
      pushBanner(e instanceof Error ? e.message : 'Avatar upload failed');
979
    }
980
  }
981
982
  async function sendAttachments(
983
    roomId: string,
984
    body: string,
985
    reply: ReplyReference | null,
986
    mentions: Mention[],
987
    attachments: StagedAttachment[]
988
  ): Promise<void> {
989
    let first = true;
990
    uploadBusy = true;
991
    try {
992
      for (const attachment of attachments) {
993
        uploadName = attachment.file.name || 'attachment';
994
        try {
995
          if (first) await uploadAttachment(roomId, attachment.file, body || null, reply?.event_id ?? null, mentions, resolveEmotes(body, roomEmotes));
996
          else await uploadAttachment(roomId, attachment.file);
997
          first = false;
998
        } catch (e) {
999
          pushBanner(e instanceof Error ? e.message : 'Upload failed');
1000
        }
1001
        if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
1002
      }
1003
    } finally {
1004
      uploadBusy = false;
1005
      uploadName = null;
1006
    }
1007
  }
1008
1009
  function stageFiles(files: File[]): void {
1010
    const roomId = $selectedRoomId;
1011
    if (!roomId || !openReady[roomId]) return;
1012
    const accepted = stageAttachments(files, pushBanner);
1013
    if (accepted.length === 0) return;
1014
    staged = { ...staged, [roomId]: [...(staged[roomId] ?? []), ...accepted] };
1015
    composerRef?.focus();
1016
  }
1017
1018
  function unstage(roomId: string, id: number): void {
1019
    const list = staged[roomId] ?? [];
1020
    const removed = list.find((a) => a.id === id);
1021
    if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
1022
    staged = { ...staged, [roomId]: list.filter((a) => a.id !== id) };
1023
  }
1024
1025
  function clearAllStaged(): void {
1026
    for (const list of Object.values(staged)) releaseStaged(list);
1027
    staged = {};
1028
  }
1029
1030
  function startEdit(eventId: string, body: string): void {
1031
    const roomId = $selectedRoomId;
1032
    if (!roomId) return;
1033
    const stash = editing ? editing.stash : composer;
1034
    editing = { roomId, eventId, original: body, stash };
1035
    const entry = items.find((i) => i.kind === 'event' && i.event.event_id === eventId);
1036
    if (entry?.kind === 'event' && entry.event.content.kind === 'Message') {
1037
      const existing = mentionsFromHtml(entry.event.content.message.formatted_body);
1038
      pickedMentions = { ...pickedMentions, [roomId]: [...(pickedMentions[roomId] ?? []), ...existing] };
1039
    }
1040
    composer = body;
1041
    replyingTo = null;
1042
    composerRef?.focus();
1043
  }
1044
1045
  function cancelEdit(): void {
1046
    if (!editing) return;
1047
    composer = editing.stash;
1048
    editing = null;
1049
    composerRef?.focus();
1050
  }
1051
1052
  function submitEdit(): void {
1053
    if (!editing) return;
1054
    const { roomId, eventId, original } = editing;
1055
    const body = composer.trim();
1056
    cancelEdit();
1057
    if (!body || body === original.trim()) return;
1058
    editMessage(roomId, eventId, body, resolveMentions(body, pickedMentions[roomId] ?? []), resolveEmotes(body, roomEmotes)).catch((e) => pushBanner(e instanceof Error ? e.message : 'Edit failed'));
1059
  }
1060
1061
  function editLastOwn(): boolean {
1062
    for (let i = items.length - 1; i >= 0; i -= 1) {
1063
      const entry = items[i];
1064
      if (entry.kind !== 'event' || !entry.event.own) continue;
1065
      const ev = entry.event;
1066
      if (!ev.editable || !ev.event_id || ev.content.kind !== 'Message' || ev.content.message.kind !== 'Text') return false;
1067
      startEdit(ev.event_id, ev.content.message.body);
1068
      return true;
1069
    }
1070
    return false;
1071
  }
1072
1073
  function startReply(target: ReplyReference): void {
1074
    if (editing) cancelEdit();
1075
    replyingTo = target;
1076
    composerRef?.focus();
1077
  }
1078
1079
  let pinnedOpenFor: string | null = null;
1080
  let pinnedCloseVersion = 0;
1081
  let pinsExpanded = false;
1082
  let pinPreview: TimelineEvent | null = null;
1083
  let pinJumpBusy = false;
1084
  $: syncPinned(selectedRoom?.room_id ?? null, (selectedRoom?.pinned_events.length ?? 0) > 0, $selectedRoomId ? $pinnedTimelineVersions[$selectedRoomId] ?? 0 : 0);
1085
  function syncPinned(roomId: string | null, hasPins: boolean, version: number): void {
1086
    const want = hasPins ? roomId : null;
1087
    if (want === pinnedOpenFor && version === pinnedCloseVersion) return;
1088
    if (pinnedOpenFor) runCommand({ op: 'close_pinned', room_id: pinnedOpenFor }).catch(() => undefined);
1089
    pinnedOpenFor = want;
1090
    pinnedCloseVersion = version;
1091
    pinsExpanded = false;
1092
    if (want) runCommand({ op: 'open_pinned', room_id: want }).catch(() => undefined);
1093
  }
1094
1095
  $: pins = pinnedList(selectedRoom, $pinnedTimelines);
1096
  function pinnedList(room: RoomSummary | null, all: Record<string, TimelineItem[]>): TimelineEvent[] {
1097
    if (!room || !room.pinned_events.length) return [];
1098
    const order = new Map(room.pinned_events.map((id, i) => [id, i]));
1099
    return (all[room.room_id] ?? [])
1100
      .flatMap((item) => (item.kind === 'event' && item.event.event_id && order.has(item.event.event_id) ? [item.event] : []))
1101
      .sort((a, b) => (order.get(b.event_id!) ?? 0) - (order.get(a.event_id!) ?? 0));
1102
  }
1103
1104
  function setPinned(eventId: string, pinned: boolean): void {
1105
    const roomId = $selectedRoomId;
1106
    if (!roomId) return;
1107
    runCommand({ op: 'set_pinned', room_id: roomId, event_id: eventId, pinned }).catch((e) =>
1108
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin')
1109
    );
1110
  }
1111
1112
  async function jumpToPin(eventId: string): Promise<void> {
1113
    const roomId = $selectedRoomId;
1114
    if (!roomId || !eventId || pinJumpBusy) return;
1115
    pinsExpanded = false;
1116
    const pinned = pins.find((event) => event.event_id === eventId) ?? null;
1117
    if (pinned?.thread_root) {
1118
      openThreadHere(pinned.thread_root, eventId);
1119
      return;
1120
    }
1121
    pinPreview = pinned;
1122
    pinJumpBusy = true;
1123
    try {
1124
      if (await loadEvent(roomId, eventId)) {
1125
        pinPreview = null;
1126
        await tick();
1127
        await jumpTo(eventId);
1128
        return;
1129
      }
1130
      pushBanner('Could not load that pinned message');
1131
    } catch (e) {
1132
      pushBanner(e instanceof Error ? e.message : 'Could not load that pinned message');
1133
    } finally {
1134
      pinJumpBusy = false;
1135
    }
1136
  }
1137
1138
  function loaded(roomId: string, eventId: string): boolean {
1139
    return ($timelines[roomId] ?? []).some((item) => item.kind === 'event' && item.event.event_id === eventId);
1140
  }
1141
1142
  async function loadEvent(roomId: string, eventId: string): Promise<boolean> {
1143
    let stalled = 0;
1144
    for (let attempt = 0; attempt < 200 && stalled < 3; attempt += 1) {
1145
      const list = $timelines[roomId] ?? [];
1146
      if (loaded(roomId, eventId)) return true;
1147
      if ($selectedRoomId !== roomId || list.some((item) => item.kind === 'start')) return false;
1148
      await paginateRoom(roomId);
1149
      await new Promise((resolve) => window.setTimeout(resolve, 180));
1150
      stalled = ($timelines[roomId] ?? []).length > list.length ? 0 : stalled + 1;
1151
    }
1152
    return loaded(roomId, eventId);
1153
  }
1154
1155
  let replyJumpBusy = false;
1156
1157
  async function jumpTo(eventId: string): Promise<void> {
1158
    let el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
1159
    let recentred = false;
1160
    if (!el && timelineRows?.has(eventId)) {
1161
      stickToBottom = false;
1162
      recentred = timelineRows.reveal(eventId);
1163
      await tick();
1164
      el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
1165
    }
1166
    const root = !el && $selectedRoomId ? threadHolding($selectedRoomId, eventId) : null;
1167
    if (root) {
1168
      openThreadHere(root, eventId);
1169
      return;
1170
    }
1171
    const roomId = $selectedRoomId;
1172
    if (!el && roomId && !loaded(roomId, eventId) && !replyJumpBusy) {
1173
      replyJumpBusy = true;
1174
      try {
1175
        if (await loadEvent(roomId, eventId)) {
1176
          await tick();
1177
          return jumpTo(eventId);
1178
        }
1179
      } catch (e) {
1180
        pushBanner(e instanceof Error ? e.message : 'Could not load the original message');
1181
        return;
1182
      } finally {
1183
        replyJumpBusy = false;
1184
      }
1185
    }
1186
    if (!el) {
1187
      pushBanner('Could not load the original message');
1188
      return;
1189
    }
1190
    stickToBottom = false;
1191
    timelineViewport?.releaseScroll();
1192
    el.scrollIntoView({ block: 'center', behavior: recentred ? 'instant' : 'smooth' });
1193
    if (recentred) timelineViewport?.capture();
1194
    el.classList.remove('flash');
1195
    void el.offsetWidth;
1196
    el.classList.add('flash');
1197
  }
1198
1199
  let typedText = '';
1200
  let typedRoom: string | null = null;
1201
  $: trackTypingInput(composer, $selectedRoomId, openReady);
1202
  function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void {
1203
    const edited = roomId === typedRoom && text !== typedText;
1204
    typedText = text;
1205
    typedRoom = roomId;
1206
    if (!roomId || !ready[roomId] || !text.trim()) {
1207
      stopTyping();
1208
    } else if (edited && roomId !== peeking) {
1209
      notifyTyping(roomId);
1210
    }
1211
  }
1212
1213
  $: void trackPending($selectedRoomId, pendingItems);
1214
  async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> {
1215
    if (!roomId) return;
1216
    if (roomId !== $selectedRoomId) return;
1217
    await tick();
1218
    if (roomId !== $selectedRoomId || timelineViewport?.roomId !== roomId) return;
1219
    if (stickToBottom) timelineViewport.scrollToBottom(true);
1220
    else timelineViewport.restore();
1221
  }
1222
1223
  async function react(eventId: string, key: string, shortcode?: string): Promise<void> {
1224
    const roomId = $selectedRoomId;
1225
    if (!roomId || !eventId || reacting) return;
1226
    reacting = true;
1227
    try {
1228
      await reactToMessage(roomId, eventId, key, reactionShortcode(key, shortcode, allPacks($imagePacks)));
1229
    } catch (e) {
1230
      pushBanner(e instanceof Error ? e.message : 'Reaction failed');
1231
    } finally {
1232
      reacting = false;
1233
    }
1234
  }
1235
1236
  function previewLoader(roomId: string): (url: string) => void {
1237
    return (url) => requestLinkPreview(roomId, url);
1238
  }
1239
1240
  async function changeEncryptedPreviews(enabled: boolean): Promise<void> {
1241
    try {
1242
      await saveUrlPreviewSettings({ encrypted_rooms: enabled });
1243
    } catch (e) {
1244
      pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting');
1245
    }
1246
  }
1247
1248
  async function changeQuickReactions(list: QuickReaction[]): Promise<void> {
1249
    try {
1250
      await saveQuickReactions(list);
1251
    } catch (e) {
1252
      pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions');
1253
    }
1254
  }
1255
1256
  async function paginate(): Promise<void> {
1257
    const roomId = $selectedRoomId;
1258
    if (!roomId || paginateBusy || $recentHistory[roomId] === 'Loading') return;
1259
    paginateBusy = true;
1260
    try {
1261
      await paginateRoom(roomId);
1262
    } catch (e) {
1263
      pushBanner(e instanceof Error ? e.message : 'Loading older messages failed');
1264
    } finally {
1265
      paginateBusy = false;
1266
    }
1267
  }
1268
1269
  async function fillGap(gapId: string): Promise<void> {
1270
    const roomId = $selectedRoomId;
1271
    if (!roomId || fillingGaps[roomId]) return;
1272
    fillingGaps = { ...fillingGaps, [roomId]: gapId };
1273
    try {
1274
      await fillHistoryGap(roomId, gapId);
1275
    } catch (e) {
1276
      pushBanner(e instanceof Error ? e.message : 'Loading the missing history failed');
1277
    } finally {
1278
      if (fillingGaps[roomId] === gapId) {
1279
        const { [roomId]: _done, ...rest } = fillingGaps;
1280
        fillingGaps = rest;
1281
      }
1282
    }
1283
  }
1284
1285
  async function retryRecentHistory(roomId: string): Promise<void> {
1286
    if (recentRetrying[roomId]) return;
1287
    recentRetrying = { ...recentRetrying, [roomId]: true };
1288
    try {
1289
      await requestRecentHistory(roomId);
1290
    } catch (e) {
1291
      pushBanner(e instanceof Error ? e.message : 'Loading recent history failed');
1292
    } finally {
1293
      const { [roomId]: _done, ...rest } = recentRetrying;
1294
      recentRetrying = rest;
1295
    }
1296
  }
1297
1298
  async function loadMembers(roomId: string): Promise<void> {
1299
    if (membersFor === roomId && $membersLoading) return;
1300
    membersFor = roomId;
1301
    membersLoading.set(true);
1302
    try {
1303
      const res = await getMembers(roomId);
1304
      membersByRoom.update((all) => ({ ...all, [roomId]: res.members }));
1305
      avatarByUser = { ...avatarByUser, ...avatarMap(res.members) };
1306
    } catch (e) {
1307
      pushBanner(e instanceof Error ? e.message : 'Could not load members');
1308
    } finally {
1309
      if (membersFor === roomId) membersLoading.set(false);
1310
    }
1311
  }
1312
1313
  function avatarMap(list: MemberSummary[]): Record<string, string | null> {
1314
    const next: Record<string, string | null> = {};
1315
    for (const member of list) next[member.user_id] = member.avatar;
1316
    return next;
1317
  }
1318
1319
  function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> {
1320
    const out: Record<string, Person> = {};
1321
    for (const item of list) {
1322
      if (item.kind !== 'event') continue;
1323
      const s = item.event.sender;
1324
      out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar };
1325
    }
1326
    for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar };
1327
    const prev = lastPeople;
1328
    const keys = Object.keys(out);
1329
    if (
1330
      Object.keys(prev).length === keys.length &&
1331
      keys.every((k) => prev[k] && prev[k].name === out[k].name && prev[k].avatar === out[k].avatar)
1332
    ) {
1333
      return prev;
1334
    }
1335
    lastPeople = out;
1336
    return out;
1337
  }
1338
1339
  let lastPeople: Record<string, Person> = {};
1340
1341
  function senderAvatarFor(userId: string): string | null {
1342
    return avatarByUser[userId] ?? null;
1343
  }
1344
1345
  $: threadView = $openThread && $openThread.room_id === $selectedRoomId ? $openThread : null;
1346
  $: if ($openThread && $openThread.room_id !== $selectedRoomId) void showThread(null);
1347
  let threadFolds: Record<string, boolean> = {};
1348
  const BOTH_PANES_MIN_WIDTH = 1300;
1349
  let viewportWidth = typeof window === 'undefined' ? BOTH_PANES_MIN_WIDTH : window.innerWidth;
1350
  let rightFront: 'thread' | 'members' = 'members';
1351
  $: bothPanesFit = viewportWidth >= BOTH_PANES_MIN_WIDTH;
1352
  $: threadShown = !!threadView && (bothPanesFit || !membersOpen || rightFront === 'thread');
1353
  $: membersShown = !!selectedRoom && membersOpen && (bothPanesFit || !threadView || rightFront === 'members');
1354
1355
  function openThreadHere(rootEventId: string, focusEventId?: string): void {
1356
    if (!$selectedRoomId) return;
1357
    rightFront = 'thread';
1358
    void showThread({ room_id: $selectedRoomId, root_event_id: rootEventId, focus_event_id: focusEventId });
1359
  }
1360
1361
  async function openLive(roomId: string, eventId: string, threadRoot: string | null): Promise<void> {
1362
    await selectRoom(roomId);
1363
    if ($selectedRoomId !== roomId) return;
1364
    if (threadRoot) {
1365
      openThreadHere(threadRoot, eventId);
1366
      return;
1367
    }
1368
    await tick();
1369
    await jumpTo(eventId);
1370
  }
1371
1372
  function threadHolding(roomId: string, eventId: string): string | null {
1373
    for (const [key, list] of Object.entries($threadTimelines)) {
1374
      const [room, root] = key.split('\u0000');
1375
      if (room === roomId && list.some((item) => item.kind === 'event' && item.event.event_id === eventId)) return root;
1376
    }
1377
    return null;
1378
  }
1379
1380
  async function openThreadIn(roomId: string, rootEventId: string): Promise<void> {
1381
    if ($selectedRoomId !== roomId) await selectRoom(roomId);
1382
    if ($selectedRoomId === roomId) openThreadHere(rootEventId);
1383
  }
1384
1385
  $: syncThreadLists([...new Set([...($selectedRoomId ? [$selectedRoomId] : []), ...Object.keys(threadFolds).filter((id) => threadFolds[id])])]);
1386
1387
  function threadFoldOpen(roomId: string, folds: Record<string, boolean>, q: string): boolean {
1388
    if (q) return ($threadsByRoom[roomId] ?? []).some((t) => threadMatches(t, q));
1389
    return !!folds[roomId];
1390
  }
1391
1392
  function toggleMembers(): void {
1393
    if (membersShown) {
1394
      membersOpen = false;
1395
    } else {
1396
      membersOpen = true;
1397
      rightFront = 'members';
1398
    }
1399
    if (membersOpen && $selectedRoomId) {
1400
      void loadMembers($selectedRoomId);
1401
      void loadLevels($selectedRoomId);
1402
    }
1403
  }
1404
1405
  async function join(target: string): Promise<void> {
1406
    const room = target.trim();
1407
    if (!room || joinBusy) return;
1408
    joinBusy = true;
1409
    try {
1410
      const res = await joinRoom(room);
1411
      joinTarget = '';
1412
      dialog = null;
1413
      await refreshRooms();
1414
      await selectRoom(res.room_id);
1415
    } catch (e) {
1416
      pushBanner(e instanceof Error ? e.message : 'Join failed');
1417
    } finally {
1418
      joinBusy = false;
1419
    }
1420
  }
1421
1422
  async function create(): Promise<void> {
1423
    const name = createName.trim();
1424
    if (!name || createBusy) return;
1425
    createBusy = true;
1426
    try {
1427
      const res = await createRoom(name, createTopic.trim() || undefined);
1428
      createName = '';
1429
      createTopic = '';
1430
      dialog = null;
1431
      await refreshRooms();
1432
      await selectRoom(res.room_id);
1433
    } catch (e) {
1434
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
1435
    } finally {
1436
      createBusy = false;
1437
    }
1438
  }
1439
1440
  async function leave(roomId: string | null = $selectedRoomId): Promise<void> {
1441
    if (!roomId || leaveBusy) return;
1442
    leaveBusy = true;
1443
    stopTyping();
1444
    try {
1445
      await leaveRoom(roomId);
1446
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
1447
      if (warmRooms.includes(roomId)) {
1448
        forgetOpenRoom(roomId);
1449
        closeRoom(roomId).catch(() => undefined);
1450
      }
1451
      await refreshRooms();
1452
    } catch (e) {
1453
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
1454
    } finally {
1455
      leaveBusy = false;
1456
    }
1457
  }
1458
1459
  function connectionClass(state: string): string {
1460
    if (state === 'online') return 'dot-online';
1461
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
1462
    return 'dot-off';
1463
  }
1464
1465
  let dragSpaceId: string | null = null;
1466
  let dropTarget: { id: string; after: boolean } | null = null;
1467
  let menu: { items: MenuItem[]; x: number; y: number; above?: boolean } | null = null;
1468
  let userCard: { userId: string; x: number; y: number; confirm: 'kick' | 'ban' | null } | null = null;
1469
  let levelsByRoom: Record<string, PowerLevels | null> = {};
1470
  let peeking: string | null = null;
1471
1472
  $: roomLevels = $selectedRoomId ? (levelsByRoom[$selectedRoomId] ?? null) : null;
1473
1474
  function personFor(userId: string): Person {
1475
    return people[userId] ?? { user_id: userId, name: userId, avatar: avatarByUser[userId] ?? null };
1476
  }
1477
1478
  function memberFor(userId: string): MemberSummary | null {
1479
    return members.find((m) => m.user_id === userId) ?? null;
1480
  }
1481
1482
  async function loadLevels(roomId: string): Promise<void> {
1483
    try {
1484
      const levels = parsePowerLevels(await runCommand({ op: 'power_levels', room_id: roomId }));
1485
      levelsByRoom = { ...levelsByRoom, [roomId]: levels };
1486
    } catch {
1487
      levelsByRoom = { ...levelsByRoom, [roomId]: levelsByRoom[roomId] ?? null };
1488
    }
1489
  }
1490
1491
  async function openUser(userId: string, x: number, y: number, asMenu: boolean): Promise<void> {
1492
    const roomId = $selectedRoomId;
1493
    if (roomId && !(roomId in levelsByRoom)) await loadLevels(roomId);
1494
    else if (roomId) void loadLevels(roomId);
1495
    if (asMenu) menu = { items: userMenuItems(userId, x, y), x, y };
1496
    else userCard = { userId, x, y, confirm: null };
1497
  }
1498
1499
  function copyText(text: string): void {
1500
    navigator.clipboard.writeText(text).catch(() => pushBanner('Could not copy to the clipboard'));
1501
  }
1502
1503
  function userMenuItems(userId: string, x: number, y: number): MenuItem[] {
1504
    const own = userId === $sessionUser;
1505
    const member = memberFor(userId);
1506
    const items: MenuItem[] = [];
1507
    if (!own) items.push({ label: 'Message', action: () => void userAction(userId, { kind: 'message' }) });
1508
    items.push({ label: 'Mention', action: () => void userAction(userId, { kind: 'mention' }) });
1509
    items.push({ label: 'Copy user ID', action: () => copyText(userId) });
1510
    const firstModeration = items.length;
1511
    if (roomLevels && $sessionUser) {
1512
      const can = allowed(roomLevels, $sessionUser, userId);
1513
      const banned = member?.membership === 'Ban';
1514
      if (can.setLevel && !own) {
1515
        const muted = isMuted(roomLevels, userId);
1516
        items.push({ label: muted ? 'Unmute' : 'Mute', action: () => void userAction(userId, { kind: muted ? 'unmute' : 'mute' }) });
1517
      }
1518
      if (can.kick && !banned) items.push({ label: 'Kick…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'kick' }) });
1519
      if (can.ban && banned) items.push({ label: 'Unban', action: () => void userAction(userId, { kind: 'unban' }) });
1520
      if (can.ban && !banned) items.push({ label: 'Ban…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'ban' }) });
1521
      if (can.setLevel) items.push({ label: 'Power level…', action: () => (userCard = { userId, x, y, confirm: null }) });
1522
    }
1523
    if (items[firstModeration]) items[firstModeration] = { ...items[firstModeration], divider: true };
1524
    if (!own) {
1525
      const kind = member?.ignored ? 'unignore' : 'ignore';
1526
      items.push({ label: member?.ignored ? 'Unignore' : 'Ignore', divider: true, action: () => void userAction(userId, { kind }) });
1527
    }
1528
    return items;
1529
  }
1530
1531
  async function insertMention(person: Person): Promise<void> {
1532
    const roomId = $selectedRoomId;
1533
    if (!roomId) return;
1534
    const lead = composer && !/\s$/.test(composer) ? ' ' : '';
1535
    composer = `${composer}${lead}${person.name} `;
1536
    pickedMentions = {
1537
      ...pickedMentions,
1538
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
1539
    };
1540
    await composerRef?.focusEnd();
1541
  }
1542
1543
  async function userAction(userId: string, action: UserAction): Promise<void> {
1544
    const roomId = $selectedRoomId;
1545
    try {
1546
      switch (action.kind) {
1547
        case 'message': {
1548
          const res = (await runCommand({ op: 'direct', user_id: userId })) as { room_id: string };
1549
          await refreshRooms();
1550
          await selectRoom(res.room_id);
1551
          return;
1552
        }
1553
        case 'mention':
1554
          await insertMention(personFor(userId));
1555
          return;
1556
        case 'ignore':
1557
        case 'unignore':
1558
          await runCommand({ op: action.kind, user_id: userId });
1559
          if (roomId) void loadMembers(roomId);
1560
          return;
1561
      }
1562
      if (!roomId) return;
1563
      switch (action.kind) {
1564
        case 'kick':
1565
        case 'ban':
1566
          await runCommand({ op: action.kind, room_id: roomId, user_id: userId, reason: action.reason });
1567
          break;
1568
        case 'unban':
1569
          await runCommand({ op: 'unban', room_id: roomId, user_id: userId, reason: null });
1570
          break;
1571
        case 'mute':
1572
        case 'unmute':
1573
          await runCommand({ op: 'mute', room_id: roomId, user_id: userId, muted: action.kind === 'mute' });
1574
          break;
1575
        case 'power':
1576
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id: userId, level: action.level });
1577
          break;
1578
      }
1579
      void loadLevels(roomId);
1580
      void loadMembers(roomId);
1581
    } catch (e) {
1582
      pushBanner(e instanceof Error ? e.message : 'That action failed');
1583
    }
1584
  }
1585
1586
  function roomMenuItems(room: RoomSummary): MenuItem[] {
1587
    const items: MenuItem[] = room.space
1588
      ? [{ label: 'Open', action: () => void selectSpace(room.room_id) }]
1589
      : [
1590
          { label: 'Open', action: () => void selectRoom(room.room_id) },
1591
          { label: 'Peek', action: () => void selectRoom(room.room_id, true) }
1592
        ];
1593
    items.push({ label: room.favourite ? 'Unpin' : room.space ? 'Pin to top' : 'Pin', action: () => void togglePin(room) });
1594
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${room.canonical_alias ?? room.room_id}`) });
1595
    items.push({ label: 'Copy room ID', action: () => copyText(room.room_id) });
1596
    if (room.membership === 'Joined') items.push({ label: 'Leave', danger: true, divider: true, action: () => void leave(room.room_id) });
1597
    return items;
1598
  }
1599
1600
  function openRoomMenu(ev: MouseEvent, room: RoomSummary): void {
1601
    menu = { items: roomMenuItems(room), x: ev.clientX, y: ev.clientY };
1602
  }
1603
1604
  function roomName(roomId: string): string {
1605
    return $rooms.find((r) => r.room_id === roomId)?.name ?? roomId;
1606
  }
1607
1608
  function roomStickers(roomId: string, threadRoot: string | null = null): StickerHandlers {
1609
    return {
1610
      onSend: (pack, image) => void sendSticker(roomId, pack, image, threadRoot),
1611
      onClone: (pack, image, x, y) => openCloneImageMenu(pack, image, x, y),
1612
      onClonePack: (pack, x, y) => openClonePackMenu(pack, x, y),
1613
      onManage: () => (dialog = 'packs'),
1614
      roomName
1615
    };
1616
  }
1617
1618
  async function sendSticker(roomId: string, pack: ImagePack, image: PackImage, threadRoot: string | null = null): Promise<void> {
1619
    if (!threadRoot) stickToBottom = true;
1620
    try {
1621
      await runCommand({ op: 'send_sticker', room_id: roomId, thread_root: threadRoot, pack_id: pack.id, shortcode: image.shortcode });
1622
      if (peeking === roomId) stopPeeking();
1623
    } catch (e) {
1624
      pushBanner(e instanceof Error ? e.message : 'Could not send the sticker');
1625
    }
1626
  }
1627
1628
  async function runClone(request: CommandRequest, failure: string): Promise<void> {
1629
    try {
1630
      const res = (await runCommand(request)) as { skipped?: string[] } | undefined;
1631
      if (res?.skipped?.length) pushBanner(`Couldn't copy ${res.skipped.map((s) => `:${s}:`).join(', ')}`);
1632
    } catch (e) {
1633
      pushBanner(e instanceof Error ? e.message : failure);
1634
    }
1635
  }
1636
1637
  function openCloneImageMenu(pack: ImagePack, image: PackImage, x: number, y: number): void {
1638
    menu = null;
1639
    cloneSource = { kind: 'image', pack, image };
1640
  }
1641
1642
  function openClonePackMenu(pack: ImagePack, x: number, y: number): void {
1643
    menu = null;
1644
    cloneSource = { kind: 'pack', pack };
1645
  }
1646
1647
  function openCloneStickerMenu(eventId: string, body: string, x: number, y: number): void {
1648
    const roomId = $selectedRoomId;
1649
    if (!roomId) return;
1650
    menu = null;
1651
    cloneSource = { kind: 'sticker', room_id: roomId, event_id: eventId, body };
1652
  }
1653
1654
  async function openMessageMenu(event: TimelineEvent, x: number, y: number): Promise<void> {
1655
    const roomId = $selectedRoomId;
1656
    const eventId = event.event_id;
1657
    if (!roomId || !eventId) return;
1658
    if (!(roomId in levelsByRoom)) await loadLevels(roomId);
1659
    const joined = selectedRoom?.membership === 'Joined';
1660
    const content = event.content;
1661
    const items: MenuItem[] = [];
1662
    if (joined) {
1663
      items.push({
1664
        label: 'Reply',
1665
        action: () =>
1666
          startReply({
1667
            event_id: eventId,
1668
            details: { kind: 'Ready', sender: event.sender, content, timestamp_ms: event.timestamp_ms }
1669
          })
1670
      });
1671
    }
1672
    if (joined && event.own && event.editable && content.kind === 'Message' && content.message.kind === 'Text') {
1673
      const body = content.message.body;
1674
      items.push({ label: 'Edit', action: () => startEdit(eventId, body) });
1675
    }
1676
    if (content.kind === 'Message' && content.message.body) {
1677
      const body = content.message.body;
1678
      items.push({ label: 'Copy text', action: () => copyText(body) });
1679
    }
1680
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${roomId}/${eventId}`) });
1681
    if (joined && selectedRoom?.can_pin && content.kind !== 'Redacted') {
1682
      const pinned = selectedRoom.pinned_events.includes(eventId);
1683
      items.push({ label: pinned ? 'Unpin' : 'Pin', action: () => setPinned(eventId, !pinned) });
1684
    }
1685
    if (content.kind === 'Sticker') {
1686
      const body = content.body;
1687
      items.push({ label: 'Clone sticker…', action: () => openCloneStickerMenu(eventId, body, x, y) });
1688
    }
1689
    const me = $sessionUser;
1690
    if (joined && me && roomLevels && canRedact(roomLevels, me, event.sender.user_id) && content.kind !== 'Redacted') {
1691
      items.push({
1692
        label: 'Delete message…',
1693
        danger: true,
1694
        action: () =>
1695
          (menu = {
1696
            x,
1697
            y,
1698
            items: [
1699
              { label: 'Delete', danger: true, action: () => void runClone({ op: 'redact', room_id: roomId, event_id: eventId, reason: null }, 'Could not delete the message') },
1700
              { label: 'Cancel', action: () => undefined }
1701
            ]
1702
          })
1703
      });
1704
    }
1705
    if (!event.own) {
1706
      const person = userMenuItems(event.sender.user_id, x, y);
1707
      if (person[0]) person[0] = { ...person[0], divider: true };
1708
      items.push(...person);
1709
    }
1710
    menu = { items, x, y };
1711
  }
1712
1713
  function openAccountMenu(ev: MouseEvent): void {
1714
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1715
    menu = {
1716
      x: rect.left,
1717
      y: rect.top - 6,
1718
      above: true,
1719
      items: [
1720
        { label: 'Security', action: () => (dialog = 'security') },
1721
        { label: 'Settings', action: () => (dialog = 'settings') },
1722
        { label: 'Sticker and emoji packs', action: () => (dialog = 'packs') },
1723
        { label: 'Log out', danger: true, divider: true, action: () => void doLogout() }
1724
      ]
1725
    };
1726
  }
1727
1728
  let resizing = false;
1729
1730
  function startResize(ev: PointerEvent, pane: 'side' | 'members' | 'thread'): void {
1731
    if (ev.button !== 0) return;
1732
    ev.preventDefault();
1733
    const handle = ev.currentTarget as HTMLElement;
1734
    handle.setPointerCapture(ev.pointerId);
1735
    const store = pane === 'side' ? sideWidth : pane === 'thread' ? threadWidth : membersWidth;
1736
    const range = pane === 'side' ? SIDE_WIDTH : pane === 'thread' ? THREAD_WIDTH : MEMBERS_WIDTH;
1737
    const startX = ev.clientX;
1738
    const startWidth = pane === 'side' ? $sideWidth : pane === 'thread' ? $threadWidth : $membersWidth;
1739
    resizing = true;
1740
    const move = (e: PointerEvent) => {
1741
      const delta = pane === 'side' ? e.clientX - startX : startX - e.clientX;
1742
      store.set(Math.round(Math.min(range.max, Math.max(range.min, startWidth + delta))));
1743
    };
1744
    const end = () => {
1745
      resizing = false;
1746
      handle.removeEventListener('pointermove', move);
1747
      handle.removeEventListener('pointerup', end);
1748
      handle.removeEventListener('pointercancel', end);
1749
    };
1750
    handle.addEventListener('pointermove', move);
1751
    handle.addEventListener('pointerup', end);
1752
    handle.addEventListener('pointercancel', end);
1753
  }
1754
1755
  function resetWidth(pane: 'side' | 'members' | 'thread'): void {
1756
    if (pane === 'side') sideWidth.set(SIDE_WIDTH.default);
1757
    else if (pane === 'thread') threadWidth.set(THREAD_WIDTH.default);
1758
    else membersWidth.set(MEMBERS_WIDTH.default);
1759
  }
1760
1761
  function stopPeeking(): void {
1762
    peeking = null;
1763
    queueReadReceipt();
1764
  }
1765
1766
  async function togglePin(room: RoomSummary): Promise<void> {
1767
    try {
1768
      await runCommand({ op: 'set_favourite', room_id: room.room_id, favourite: !room.favourite });
1769
    } catch (e) {
1770
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin');
1771
    }
1772
  }
1773
1774
  function startRailDrag(ev: DragEvent, id: string): void {
1775
    dragSpaceId = id;
1776
    if (ev.dataTransfer) {
1777
      ev.dataTransfer.effectAllowed = 'move';
1778
      ev.dataTransfer.setData('text/plain', id);
1779
    }
1780
  }
1781
1782
  function overRailSpace(ev: DragEvent, space: RoomSummary): void {
1783
    const dragged = orderedRail.find((s) => s.room_id === dragSpaceId);
1784
    if (!dragged || dragged.room_id === space.room_id || dragged.favourite !== space.favourite) return;
1785
    ev.preventDefault();
1786
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1787
    dropTarget = { id: space.room_id, after: ev.clientY > rect.top + rect.height / 2 };
1788
  }
1789
1790
  async function dropRailSpace(): Promise<void> {
1791
    const moved = dragSpaceId;
1792
    const target = dropTarget;
1793
    dragSpaceId = null;
1794
    dropTarget = null;
1795
    if (!moved || !target) return;
1796
    const ids = orderedRail.map((s) => s.room_id);
1797
    const before = target.after ? (ids[ids.indexOf(target.id) + 1] ?? null) : target.id;
1798
    const order = moveBefore(ids, moved, before === moved ? null : before);
1799
    if (order.join() === ids.join()) return;
1800
    railOverride = order;
1801
    try {
1802
      await runCommand({ op: 'reorder_spaces', order });
1803
    } catch (e) {
1804
      railOverride = null;
1805
      pushBanner(e instanceof Error ? e.message : 'Could not reorder spaces');
1806
    }
1807
  }
1808
1809
  let roomMenuOpen = false;
1810
  let roomMenuEl: HTMLDivElement | null = null;
1811
1812
  function roomMenuAction(action: () => void): void {
1813
    roomMenuOpen = false;
1814
    action();
1815
  }
1816
1817
  function closeRoomMenuOutside(ev: PointerEvent): void {
1818
    if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false;
1819
  }
1820
1821
  function onKeydown(ev: KeyboardEvent): void {
1822
    if (ev.key === 'Escape') {
1823
      if (roomMenuOpen) roomMenuOpen = false;
1824
      else if (dialog) dialog = null;
1825
      else if (membersShown && window.innerWidth < 1100) membersOpen = false;
1826
      else if (threadShown && window.innerWidth < 1100) void showThread(null);
1827
      else if (sidebarOpen) sidebarOpen = false;
1828
    }
1829
  }
1830
</script>
1831
1832
<svelte:window
1833
  bind:innerWidth={viewportWidth}
1834
  on:keydown={onKeydown}
1835
  on:pointerdown={closeRoomMenuOutside}
1836
/>
1837
1838
{#if !booted}
1839
  <div class="splash" role="status" aria-label="Loading Malice" out:fade={{ duration: motionDuration(260) }}>
1840
    <div class="splash-mark" aria-hidden="true">M</div>
1841
    <p>Loading Malice…</p>
1842
  </div>
1843
{:else if $blocked}
1844
  <div class="splash" role="status" aria-label="Malice is open in another tab" in:fade={{ duration: motionDuration(220) }}>
1845
    <div class="splash-mark" aria-hidden="true">M</div>
1846
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
1847
  </div>
1848
{:else if $sessionUser == null}
1849
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
1850
{:else}
1851
  <div
1852
    class="app"
1853
    in:fade={{ duration: motionDuration(220) }}
1854
    class:nav-folded={$navFolded}
1855
    class:rail-folded={$railFolded && (selectedRoom || mentionsOpen || searchOpen)}
1856
    class:members-open={membersShown}
1857
    class:thread-open={threadShown}
1858
    class:resizing
1859
    style:--side-open={`${$sideWidth}px`}
1860
    style:--members-open={`${$membersWidth}px`}
1861
    style:--thread-open={`${$threadWidth}px`}
1862
    style:--msg-gap={`${$messageSpacing}px`}
1863
    style:--msg-line-height={$lineHeight}
1864
  >
1865
    <header class="chat-head">
1866
      <button
1867
        type="button"
1868
        class="icon-btn only-mobile"
1869
        aria-label="Open room list"
1870
        on:click={() => (sidebarOpen = true)}
1871
      >
1872
        <span aria-hidden="true">☰</span>
1873
      </button>
1874
      <button
1875
        type="button"
1876
        class="icon-btn only-desktop pane-toggle"
1877
        aria-pressed={!$railFolded}
1878
        aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1879
        title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1880
        on:click={() => railFolded.update((v) => !v)}
1881
      >
1882
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1883
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1884
          <circle cx="7" cy="9" r="1.4" fill="currentColor" />
1885
          <circle cx="7" cy="13" r="1.4" fill="currentColor" />
1886
          <circle cx="7" cy="17" r="1.4" fill="currentColor" />
1887
        </svg>
1888
      </button>
1889
      <button
1890
        type="button"
1891
        class="icon-btn only-desktop pane-toggle"
1892
        aria-pressed={!$navFolded}
1893
        aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
1894
        title={$navFolded ? 'Show channels' : 'Hide channels'}
1895
        on:click={toggleChannelsPane}
1896
      >
1897
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1898
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1899
          <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
1900
        </svg>
1901
      </button>
1902
      {#if selectedRoom}
1903
      <div class="head-title">
1904
        <div class="head-room">
1905
          <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape="rounded" />
1906
          <div class="head-room-text">
1907
            <h1><EmojiText text={selectedRoom.name} /></h1>
1908
            <div class="head-meta">
1909
              {#if selectedRoom.space}
1910
                <span class="pill">space</span>
1911
              {/if}
1912
              {#if selectedRoom.encrypted}
1913
                <span class="pill" title="End-to-end encrypted"><EmojiText text="🔒 encrypted" /></span>
1914
              {/if}
1915
              {#if selectedRoom.direct}
1916
                <span class="pill">direct</span>
1917
              {/if}
1918
              {#if $connection !== 'online'}
1919
                <span class="conn" title={`Sync state: ${$connection}`}>
1920
                  <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1921
                  {$connection}
1922
                </span>
1923
              {/if}
1924
              {#if selectedRoom.topic}
1925
                <span class="head-topic" title={selectedRoom.topic}><EmojiText text={selectedRoom.topic} /></span>
1926
              {/if}
1927
            </div>
1928
          </div>
1929
        </div>
1930
      </div>
1931
      {:else}
1932
      <div class="head-title">
1933
        <div class="head-room">
1934
          {#if selectedSpace}
1935
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={36} shape="rounded" />
1936
          {/if}
1937
          <div class="head-room-text">
1938
            <h1><EmojiText text={mentionsOpen ? 'Mentions' : searchOpen ? 'Search' : selectedSpace?.name ?? 'Home'} /></h1>
1939
          </div>
1940
        </div>
1941
      </div>
1942
      {/if}
1943
      <div class="head-actions">
1944
        {#if selectedRoom}
1945
        {#if peeking === selectedRoom.room_id}
1946
          <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}>
1947
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1948
              <path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12z" fill="none" stroke="currentColor" stroke-width="2" />
1949
              <circle cx="12" cy="12" r="3" fill="currentColor" />
1950
            </svg>
1951
          </button>
1952
        {/if}
1953
        {#if selectedRoom.membership !== 'Joined'}
1954
          <button
1955
            type="button"
1956
            class="primary-btn"
1957
            disabled={joinBusy}
1958
            on:click={() => void join(selectedRoom.room_id)}
1959
          >
1960
            {joinBusy ? 'Joining…' : 'Join'}
1961
          </button>
1962
        {/if}
1963
        <button type="button" class="icon-btn" aria-label="Search messages" title="Search messages" on:click={selectSearch}>
1964
          <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6" fill="none" stroke="currentColor" stroke-width="1.8" /><path d="M15 15l5 5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
1965
        </button>
1966
        <button
1967
          type="button"
1968
          class="icon-btn"
1969
          aria-pressed={membersShown}
1970
          aria-label={membersShown ? 'Hide members' : 'Show members'}
1971
          title="Members"
1972
          on:click={toggleMembers}
1973
        >
1974
          <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1975
            <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
1976
            <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
1977
          </svg>
1978
        </button>
1979
        <div class="room-menu-wrap" bind:this={roomMenuEl}>
1980
          <button
1981
            type="button"
1982
            class="icon-btn"
1983
            aria-haspopup="menu"
1984
            aria-expanded={roomMenuOpen}
1985
            aria-label="Room options"
1986
            title="Room options"
1987
            on:click={() => (roomMenuOpen = !roomMenuOpen)}
1988
          >
1989
            <span aria-hidden="true">⋯</span>
1990
          </button>
1991
          {#if roomMenuOpen}
1992
            <div class="room-menu" role="menu">
1993
              {#if selectedRoom.membership === 'Joined'}
1994
                <button
1995
                  type="button"
1996
                  role="menuitem"
1997
                  class="danger"
1998
                  disabled={leaveBusy}
1999
                  on:click={() => roomMenuAction(() => void leave())}
2000
                >
2001
                  {leaveBusy ? 'Leaving…' : 'Leave room'}
2002
                </button>
2003
              {/if}
2004
            </div>
2005
          {/if}
2006
        </div>
2007
        {/if}
2008
      </div>
2009
    </header>
2010
2011
    <nav class="rail" aria-label="Servers and spaces">
2012
      <button
2013
        type="button"
2014
        class="rail-btn"
2015
        class:active={selectedSpaceId === null}
2016
        class:unread={homeUnread}
2017
        title="Home — all channels"
2018
        aria-label="Home — all channels"
2019
        aria-pressed={selectedSpaceId === null}
2020
        on:click={() => void selectHome()}
2021
      >
2022
        <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true"><path d="M4 11l8-7 8 7v8a1 1 0 0 1-1 1h-4v-6H9v6H5a1 1 0 0 1-1-1z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
2023
      </button>
2024
      {#each [pinnedRail, otherRail] as group}
2025
        {#if group.length > 0}
2026
          <div class="rail-sep" aria-hidden="true"></div>
2027
        {/if}
2028
        {#each group as space (space.room_id)}
2029
          <button
2030
            type="button"
2031
            class="rail-btn rail-space"
2032
            class:active={railSelected === space.room_id}
2033
            class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after}
2034
            class:drop-after={dropTarget?.id === space.room_id && dropTarget.after}
2035
            class:pinned={space.favourite}
2036
            class:unread={unreadSpaces.has(space.room_id)}
2037
            title={space.name}
2038
            aria-label={`Show channels in space ${space.name}`}
2039
            aria-pressed={selectedSpaceId === space.room_id}
2040
            draggable="true"
2041
            on:click={() => void selectSpace(space.room_id)}
2042
            on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)}
2043
            on:dragstart={(ev) => startRailDrag(ev, space.room_id)}
2044
            on:dragover={(ev) => overRailSpace(ev, space)}
2045
            on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)}
2046
            on:drop|preventDefault={() => void dropRailSpace()}
2047
            on:dragend={() => ((dragSpaceId = null), (dropTarget = null))}
2048
          >
2049
            <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
2050
          </button>
2051
        {/each}
2052
      {/each}
2053
      <button
2054
        type="button"
2055
        class="rail-btn rail-add"
2056
        aria-label="Join or create a room"
2057
        on:click={() => {
2058
          dialog = 'join';
2059
        }}
2060
      >
2061
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" /></svg>
2062
      </button>
2063
    </nav>
2064
2065
    {#if menu}
2066
      <ContextMenu items={menu.items} x={menu.x} y={menu.y} above={menu.above ?? false} onClose={() => (menu = null)} />
2067
    {/if}
2068
    {#if userCard}
2069
      {#key userCard}
2070
        {@const cardUser = userCard.userId}
2071
        <UserCard
2072
          person={personFor(cardUser)}
2073
          member={memberFor(cardUser)}
2074
          levels={roomLevels}
2075
          self={$sessionUser ?? null}
2076
          x={userCard.x}
2077
          y={userCard.y}
2078
          confirm={userCard.confirm}
2079
          onAction={(action) => void userAction(cardUser, action)}
2080
          onClose={() => (userCard = null)}
2081
        />
2082
      {/key}
2083
    {/if}
2084
2085
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
2086
      <!-- svelte-ignore a11y_no_static_element_interactions -->
2087
      <div class="pane-resize right" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'side')} on:dblclick={() => resetWidth('side')}></div>
2088
      <div class="side-search">
2089
        <label class="visually-hidden" for="room-search">Search rooms</label>
2090
        <input
2091
          id="room-search"
2092
          type="search"
2093
          placeholder="Search rooms"
2094
          bind:value={search}
2095
          autocomplete="off"
2096
        />
2097
        <button
2098
          type="button"
2099
          class="icon-btn"
2100
          title="Refresh rooms"
2101
          aria-label="Refresh rooms"
2102
          disabled={roomsLoading}
2103
          on:click={() => void refreshRooms()}
2104
        >
2105
          <span aria-hidden="true">⟳</span>
2106
        </button>
2107
      </div>
2108
      {#key selectedSpaceId ?? 'home'}
2109
      <div class="side-scroll" in:fly={{ y: 5, duration: motionDuration(180) }} out:fade={{ duration: motionDuration(120) }}>
2110
        {#if selectedSpace && spaceParents.has(selectedSpace.room_id)}
2111
          {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
2112
          <button type="button" class="room-row up-row" on:click={() => void selectSpace(parentId)}>
2113
            <span aria-hidden="true">↑</span>
2114
            <span class="room-name"><EmojiText text={$rooms.find((r) => r.room_id === parentId)?.name ?? 'Parent space'} /></span>
2115
          </button>
2116
        {/if}
2117
        {#if !selectedSpaceId}
2118
          <ul class="room-list">
2119
            <li>
2120
              <button type="button" class="room-row" class:active={mentionsOpen} on:click={selectMentions}>
2121
                <svg width="26" height="26" viewBox="0 0 26 26" aria-hidden="true"><text x="13" y="19" text-anchor="middle" fill="currentColor" font-size="22">@</text></svg>
2122
                <span class="room-name">Mentions</span>
2123
                {#if $mentionsSnapshot && $mentionsSnapshot.unread_count > 0}
2124
                  <span class="badge mention" aria-label={`${$mentionsSnapshot.unread_count} unread mentions`}>{$mentionsSnapshot.unread_count > 99 ? '99+' : $mentionsSnapshot.unread_count}</span>
2125
                {/if}
2126
              </button>
2127
            </li>
2128
          </ul>
2129
        {/if}
2130
        <ul class="room-list">
2131
          <li>
2132
            <button type="button" class="room-row" class:active={searchOpen} on:click={selectSearch}>
2133
              <svg width="26" height="26" viewBox="0 0 26 26" aria-hidden="true"><circle cx="11.5" cy="11.5" r="6" fill="none" stroke="currentColor" stroke-width="1.8" /><path d="M16 16l5 5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2134
              <span class="room-name">Search messages</span>
2135
            </button>
2136
          </li>
2137
        </ul>
2138
        {#if roomsLoading && $rooms.length === 0}
2139
          <p class="side-note">Loading rooms…</p>
2140
        {:else if $rooms.length === 0}
2141
          <p class="side-note">No rooms yet</p>
2142
          <div class="side-cta">
2143
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
2144
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
2145
          </div>
2146
        {:else}
2147
          {#if selectedSpaceId && spaceChildrenLoading}
2148
            <p class="side-note">Loading channels…</p>
2149
          {:else if selectedSpaceId && spaceChildrenError}
2150
            <p class="side-note" role="alert"><EmojiText text={spaceChildrenError} /></p>
2151
            <div class="side-cta">
2152
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
2153
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
2154
            </div>
2155
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
2156
            <p class="side-note">No channels</p>
2157
            <div class="side-cta">
2158
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
2159
            </div>
2160
          {:else}
2161
            {#if invites.length > 0 && !selectedSpaceId}
2162
              <h2 class="side-h">Invites</h2>
2163
              <ul class="room-list">
2164
                {#each invites as room (room.room_id)}
2165
                  <li>
2166
                    <button
2167
                      type="button"
2168
                      class="room-row"
2169
                      class:active={$selectedRoomId === room.room_id}
2170
                      on:click={() => void selectRoom(room.room_id)}
2171
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2172
                    >
2173
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2174
                      <span class="room-name"><EmojiText text={room.name} /></span>
2175
                      <span
2176
                        class="invite-join"
2177
                        role="button"
2178
                        tabindex="0"
2179
                        aria-label={`Join ${room.name}`}
2180
                        on:click|stopPropagation={() => void join(room.room_id)}
2181
                        on:keydown|stopPropagation={(ev) => {
2182
                          if (ev.key === 'Enter' || ev.key === ' ') {
2183
                            ev.preventDefault();
2184
                            void join(room.room_id);
2185
                          }
2186
                        }}
2187
                      >
2188
                        Join
2189
                      </span>
2190
                    </button>
2191
                  </li>
2192
                {/each}
2193
              </ul>
2194
            {/if}
2195
2196
            {#if directRooms.length > 0}
2197
              <h2 class="side-h">Direct messages</h2>
2198
              <ul class="room-list">
2199
                {#each directRooms as room (room.room_id)}
2200
                  <li class="room-item">
2201
                    <button
2202
                      type="button"
2203
                      class="room-row"
2204
                      class:active={$selectedRoomId === room.room_id}
2205
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2206
                      on:click={() => void selectRoom(room.room_id)}
2207
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2208
                    >
2209
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
2210
                      <span class="room-name"><EmojiText text={room.name} /></span>
2211
                      {#if roomUnread(room) > 0}
2212
                        <span
2213
                          class="badge"
2214
                          class:mention={room.unread_mentions > 0}
2215
                          aria-label={`${roomUnread(room)} unread`}
2216
                        >
2217
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2218
                        </span>
2219
                      {/if}
2220
                    </button>
2221
                    {#if ($threadsByRoom[room.room_id] ?? []).length}
2222
                      <button
2223
                        type="button"
2224
                        class="fold-btn"
2225
                        class:open={threadFoldOpen(room.room_id, threadFolds, query)}
2226
                        aria-expanded={threadFoldOpen(room.room_id, threadFolds, query)}
2227
                        aria-label={`Threads in ${room.name}`}
2228
                        title="Threads"
2229
                        on:click={() => (threadFolds = { ...threadFolds, [room.room_id]: !threadFolds[room.room_id] })}
2230
                      >
2231
                        <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="M3 2l4 3-4 3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
2232
                      </button>
2233
                    {/if}
2234
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2235
                  </li>
2236
                  {#if threadFoldOpen(room.room_id, threadFolds, query)}
2237
                    <li>
2238
                      <RoomThreads
2239
                        roomId={room.room_id}
2240
                        threads={$threadsByRoom[room.room_id] ?? []}
2241
                        history={$threadLists[room.room_id]?.history ?? null}
2242
                        onOlder={() => void loadOlderThreads(room.room_id)}
2243
                        {query}
2244
                        activeRoot={threadView?.room_id === room.room_id ? threadView.root_event_id : null}
2245
                        onOpen={(root) => void openThreadIn(room.room_id, root)}
2246
                      />
2247
                    </li>
2248
                  {/if}
2249
                {/each}
2250
              </ul>
2251
            {/if}
2252
2253
            {#if groupRooms.length > 0}
2254
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
2255
              <ul class="room-list">
2256
                {#each groupRooms as room (room.room_id)}
2257
                  <li class="room-item">
2258
                    <button
2259
                      type="button"
2260
                      class="room-row"
2261
                      class:active={$selectedRoomId === room.room_id}
2262
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2263
                      on:click={() => void selectRoom(room.room_id)}
2264
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2265
                    >
2266
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2267
                      <span class="room-name"><EmojiText text={room.name} /></span>
2268
                      {#if roomUnread(room) > 0}
2269
                        <span
2270
                          class="badge"
2271
                          class:mention={room.unread_mentions > 0}
2272
                          aria-label={`${roomUnread(room)} unread`}
2273
                        >
2274
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2275
                        </span>
2276
                      {/if}
2277
                    </button>
2278
                    {#if ($threadsByRoom[room.room_id] ?? []).length}
2279
                      <button
2280
                        type="button"
2281
                        class="fold-btn"
2282
                        class:open={threadFoldOpen(room.room_id, threadFolds, query)}
2283
                        aria-expanded={threadFoldOpen(room.room_id, threadFolds, query)}
2284
                        aria-label={`Threads in ${room.name}`}
2285
                        title="Threads"
2286
                        on:click={() => (threadFolds = { ...threadFolds, [room.room_id]: !threadFolds[room.room_id] })}
2287
                      >
2288
                        <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="M3 2l4 3-4 3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
2289
                      </button>
2290
                    {/if}
2291
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2292
                  </li>
2293
                  {#if threadFoldOpen(room.room_id, threadFolds, query)}
2294
                    <li>
2295
                      <RoomThreads
2296
                        roomId={room.room_id}
2297
                        threads={$threadsByRoom[room.room_id] ?? []}
2298
                        history={$threadLists[room.room_id]?.history ?? null}
2299
                        onOlder={() => void loadOlderThreads(room.room_id)}
2300
                        {query}
2301
                        activeRoot={threadView?.room_id === room.room_id ? threadView.root_event_id : null}
2302
                        onOpen={(root) => void openThreadIn(room.room_id, root)}
2303
                      />
2304
                    </li>
2305
                  {/if}
2306
                {/each}
2307
              </ul>
2308
            {/if}
2309
2310
            {#if spaceList.length > 0}
2311
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
2312
              <ul class="room-list">
2313
                {#each spaceList as room (room.room_id)}
2314
                  <li class="room-item">
2315
                    <button
2316
                      type="button"
2317
                      class="room-row"
2318
                      class:active={selectedSpaceId === room.room_id}
2319
                      aria-label={`Show channels in space ${room.name}`}
2320
                      on:click={() => void selectSpace(room.room_id)}
2321
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2322
                    >
2323
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2324
                      <span class="room-name"><EmojiText text={room.name} /></span>
2325
                    </button>
2326
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2327
                  </li>
2328
                {/each}
2329
              </ul>
2330
            {/if}
2331
2332
            {#if query && visibleRooms.length === 0}
2333
              <p class="side-note">No rooms match “<EmojiText text={search.trim()} />”.</p>
2334
            {/if}
2335
          {/if}
2336
        {/if}
2337
      </div>
2338
      {/key}
2339
2340
    </aside>
2341
    <div class="account">
2342
      <button type="button" class="me-btn" title={$sessionUser} aria-haspopup="menu" on:click={openAccountMenu}>
2343
        {#if profileMxc}
2344
          <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={32} />
2345
        {:else}
2346
          <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
2347
        {/if}
2348
        <span class="me-names">
2349
          <span class="me-name"><EmojiText text={profile?.display_name || $sessionUser} /></span>
2350
          {#if profile?.display_name && profile.display_name !== $sessionUser}<span class="me-id">{$sessionUser}</span>{/if}
2351
        </span>
2352
      </button>
2353
      <div class="account-actions">
2354
        <button type="button" class="icon-btn" title="Encryption and verification" aria-label="Encryption and verification" on:click={() => (dialog = 'security')}>
2355
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path d="M12 3l8 3v6c0 4.5-3.4 8.2-8 9-4.6-.8-8-4.5-8-9V6z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
2356
        </button>
2357
        <button type="button" class="icon-btn" title="Settings" aria-label="Settings" on:click={() => (dialog = 'settings')}>
2358
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="1.8" /><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1L7 17M17 7l2.1-2.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2359
        </button>
2360
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
2361
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path d="M12 3v8M6.3 6.3a8 8 0 1 0 11.4 0" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2362
        </button>
2363
      </div>
2364
    </div>
2365
    {#if sidebarOpen}
2366
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
2367
    {/if}
2368
2369
    <main class="chat">
2370
        {#if $banners.length > 0}
2371
          <div class="banners" aria-live="polite">
2372
            {#each $banners as banner (banner.id)}
2373
              <div class="banner" role="alert">
2374
                <span><EmojiText text={banner.message} /></span>
2375
                <button
2376
                  type="button"
2377
                  aria-label="Dismiss error"
2378
                  on:click={() => dismissBanner(banner.id)}
2379
                >
2380
                  ✕
2381
                </button>
2382
              </div>
2383
            {/each}
2384
          </div>
2385
        {/if}
2386
      {#key mentionsOpen ? 'mentions' : searchOpen ? 'search' : $selectedRoomId ?? 'home'}
2387
      <div class="chat-view">
2388
      {#if mentionsOpen && $sessionUser}
2389
        <MentionsInbox self={$sessionUser} onLive={(roomId, eventId, threadRoot) => void openLive(roomId, eventId, threadRoot)} />
2390
      {:else if searchOpen}
2391
        <SearchView scopes={searchScopes} self={$sessionUser ?? null} {roomName} onOpen={(roomId, eventId, threadRoot) => void openLive(roomId, eventId, threadRoot)} />
2392
      {:else if !selectedRoom}
2393
        <div class="empty" in:fade={{ duration: motionDuration(180) }}>
2394
          <div class="empty-mark" aria-hidden="true">◈</div>
2395
          {#if selectedSpace}
2396
            <h1><EmojiText text={selectedSpace.name} /></h1>
2397
          {:else}
2398
            <h1>Welcome to Malice</h1>
2399
          {/if}
2400
          <div class="empty-cta">
2401
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
2402
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
2403
          </div>
2404
          <p class="conn-line">
2405
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
2406
            {$connection}
2407
          </p>
2408
        </div>
2409
      {:else}
2410
        {#if pins.length}
2411
          <div class="pinned-strip" class:open={pinsExpanded}>
2412
            <div class="pinned-head">
2413
              <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M9 3h6l-1 6 4 4v2h-5v6l-1 1-1-1v-6H6v-2l4-4z" fill="currentColor" /></svg>
2414
              <button type="button" class="pinned-latest" title="Jump to pinned message" on:click={() => jumpToPin(pins[0].event_id ?? '')}>
2415
                <strong><EmojiText text={people[pins[0].sender.user_id]?.name ?? senderLabel(pins[0].sender)} /></strong>
2416
                <span><EmojiText text={contentPreview(pins[0].content)} /></span>
2417
              </button>
2418
              {#if pins.length > 1}
2419
                <button type="button" class="pinned-count" aria-expanded={pinsExpanded} on:click={() => (pinsExpanded = !pinsExpanded)}>
2420
                  {pins.length} pinned
2421
                  <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true"><path d="m6 9 6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" /></svg>
2422
                </button>
2423
              {/if}
2424
              {#if pinsExpanded && selectedRoom.can_pin}
2425
                <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pins[0].event_id ?? '', false)}>
2426
                  <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" /></svg>
2427
                </button>
2428
              {/if}
2429
            </div>
2430
            {#if pinsExpanded}
2431
              <ul class="pinned-list">
2432
                {#each pins.slice(1) as pin (pin.event_id)}
2433
                  <li>
2434
                    <button type="button" on:click={() => jumpToPin(pin.event_id ?? '')}>
2435
                      <strong><EmojiText text={people[pin.sender.user_id]?.name ?? senderLabel(pin.sender)} /></strong>
2436
                      <span><EmojiText text={contentPreview(pin.content)} /></span>
2437
                    </button>
2438
                    {#if selectedRoom.can_pin}
2439
                      <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pin.event_id ?? '', false)}>
2440
                        <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" /></svg>
2441
                      </button>
2442
                    {/if}
2443
                  </li>
2444
                {/each}
2445
              </ul>
2446
            {/if}
2447
          </div>
2448
        {/if}
2449
        {#if recoveryBanner}
2450
          <div class="sec-banner warn" role="status">
2451
            <span>Message history is locked</span>
2452
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
2453
          </div>
2454
        {/if}
2455
        {#if verificationBanner}
2456
          <div class="sec-banner" role="status">
2457
            {#if verificationBanner.kind === 'Incoming'}
2458
              <span>A device wants to verify this session</span>
2459
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
2460
            {:else if verificationBanner.kind === 'Comparison'}
2461
              <span>Verification codes ready</span>
2462
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
2463
            {:else if verificationBanner.kind === 'Waiting'}
2464
              <span>Verification started</span>
2465
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
2466
            {:else if verificationBanner.kind === 'Failed'}
2467
              <span>Verification failed: <EmojiText text={verificationBanner.message} /></span>
2468
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
2469
            {:else if verificationBanner.kind === 'Cancelled'}
2470
              <span>Verification cancelled: <EmojiText text={verificationBanner.reason} /></span>
2471
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2472
            {:else}
2473
              <span>Verification in progress</span>
2474
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2475
            {/if}
2476
          </div>
2477
        {/if}
2478
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
2479
          <p class="conn-banner error" role="alert"><EmojiText text={openFailed[$selectedRoomId]} /></p>
2480
        {/if}
2481
2482
        {#if pinPreview}
2483
          <div class="pin-preview" role="dialog" aria-label="Pinned message preview">
2484
            <div class="pin-preview-head">
2485
              <strong><EmojiText text={people[pinPreview.sender.user_id]?.name ?? senderLabel(pinPreview.sender)} /></strong>
2486
              <button type="button" class="icon-btn" aria-label="Close pinned message preview" on:click={() => (pinPreview = null)}>✕</button>
2487
            </div>
2488
            <p><EmojiText text={contentPreview(pinPreview.content)} /></p>
2489
            <button type="button" class="primary-btn" disabled={pinJumpBusy} on:click={() => void jumpToPin(pinPreview?.event_id ?? '')}>
2490
              {pinJumpBusy ? 'Loading message…' : 'Jump to message'}
2491
            </button>
2492
          </div>
2493
        {/if}
2494
2495
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2496
        <div
2497
          class="timeline"
2498
          in:fly={{ y: 6, duration: motionDuration(180) }}
2499
          out:fade={{ duration: motionDuration(120) }}
2500
          bind:this={timelineEl}
2501
          on:scroll={onTimelineScroll}
2502
          on:wheel={noteUserScroll}
2503
          on:touchmove={noteUserScroll}
2504
          on:keydown={onTimelineKey}
2505
          on:pointerdown={noteUserScroll}
2506
          aria-label={`Messages in ${selectedRoom.name}`}
2507
        >
2508
          <div class="timeline-inner" use:pinTimeline>
2509
            <RoomTimelineRows
2510
              bind:this={timelineRows}
2511
              following={stickToBottom}
2512
              {items}
2513
              pending={pendingItems}
2514
              joined={selectedRoom.membership === 'Joined'}
2515
              self={$sessionUser ?? null}
2516
              selfName={profile?.display_name ?? null}
2517
              {people}
2518
              {senderAvatarFor}
2519
              {reacting}
2520
              quickReactions={usableQuickReactions}
2521
              packs={roomPacks}
2522
              linkPreviews={$linkPreviews}
2523
              {loadPreview}
2524
              editingEventId={editing?.eventId ?? null}
2525
              {recentState}
2526
              recentRetrying={!!recentRetrying[selectedRoom.room_id]}
2527
              paginating={paginateBusy}
2528
              fillingGap={fillingGaps[selectedRoom.room_id] ?? null}
2529
              onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2530
              onQuickChange={(list) => void changeQuickReactions(list)}
2531
              onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2532
              onCloneSticker={openCloneStickerMenu}
2533
              onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2534
              onOpenThread={openThreadHere}
2535
              onReply={startReply}
2536
              onJump={(eventId) => void jumpTo(eventId)}
2537
              onEdit={startEdit}
2538
              onPaginate={() => void paginate()}
2539
              onGrew={anchorGrowth}
2540
              onFillGap={(gapId) => void fillGap(gapId)}
2541
              onRetryRecent={() => void retryRecentHistory(selectedRoom.room_id)}
2542
              onRetryPending={retryPending}
2543
              onDiscardPending={discardPending}
2544
            />
2545
          </div>
2546
          <div class="jump-anchor">
2547
            {#if !stickToBottom && (farFromLatest || arrivals > 0)}
2548
              <button
2549
                type="button"
2550
                class="jump-latest"
2551
                aria-label="Jump to latest messages"
2552
                transition:fly={{ y: 8, duration: motionDuration(150) }}
2553
                on:click={jumpToLatest}
2554
              >
2555
                <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M6 13l6 6 6-6" /></svg>
2556
                {#if arrivals > 0}<span class="jump-count">{arrivals > 99 ? '99+' : arrivals}</span>{/if}
2557
              </button>
2558
            {/if}
2559
          </div>
2560
        </div>
2561
2562
        {#if selectedRoom.membership === 'Joined'}
2563
          <input
2564
            type="file"
2565
            accept="image/*"
2566
            bind:this={avatarInput}
2567
            class="visually-hidden"
2568
            aria-label="Choose a new avatar"
2569
            on:change={() => void onAvatarChosen()}
2570
          />
2571
          <Composer
2572
            bind:this={composerRef}
2573
            bind:value={composer}
2574
            inputId="composer"
2575
            label={`Message ${selectedRoom.name}`}
2576
            placeholder={`Message ${selectedRoom.name}`}
2577
            ready={!!($selectedRoomId && openReady[$selectedRoomId])}
2578
            picked={($selectedRoomId && pickedMentions[$selectedRoomId]) || []}
2579
            onPick={(mention) => $selectedRoomId && (pickedMentions = { ...pickedMentions, [$selectedRoomId]: [...(pickedMentions[$selectedRoomId] ?? []), mention] })}
2580
            staged={currentStaged}
2581
            onStage={stageFiles}
2582
            onUnstage={(id) => $selectedRoomId && unstage($selectedRoomId, id)}
2583
            {uploadBusy}
2584
            {uploadName}
2585
            editing={editing ? { original: editing.original } : null}
2586
            onCancelEdit={cancelEdit}
2587
            {replyingTo}
2588
            onCancelReply={() => (replyingTo = null)}
2589
            {people}
2590
            self={$sessionUser ?? null}
2591
            emotes={roomEmotes}
2592
            packs={roomPacks}
2593
            stickers={$selectedRoomId ? roomStickers($selectedRoomId) : null}
2594
            commands
2595
            onSubmit={send}
2596
            onEditLast={editLastOwn}
2597
            onMentionStart={() => $selectedRoomId && !$membersByRoom[$selectedRoomId] && void loadMembers($selectedRoomId)}
2598
          />
2599
        {:else}
2600
          <div class="join-bar">
2601
            <p>You are not a member of this room.</p>
2602
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
2603
              <EmojiText text={joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`} />
2604
            </button>
2605
          </div>
2606
        {/if}
2607
      {/if}
2608
      </div>
2609
      {/key}
2610
    </main>
2611
2612
    {#if selectedRoom}
2613
      <aside class="thread" aria-hidden={!threadShown} aria-label={`Thread in ${selectedRoom.name}`}>
2614
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2615
        <div class="pane-resize left" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'thread')} on:dblclick={() => resetWidth('thread')}></div>
2616
        {#if threadView}
2617
          <ThreadPane
2618
            roomId={threadView.room_id}
2619
            rootEventId={threadView.root_event_id}
2620
            roomName={selectedRoom.name}
2621
            joined={selectedRoom.membership === 'Joined'}
2622
            self={$sessionUser ?? null}
2623
            {people}
2624
            {senderAvatarFor}
2625
            quickReactions={usableQuickReactions}
2626
            packs={roomPacks}
2627
            linkPreviews={$linkPreviews}
2628
            {loadPreview}
2629
            onQuickChange={(list) => void changeQuickReactions(list)}
2630
            onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2631
            onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2632
            onMentionStart={() => !$membersByRoom[threadView.room_id] && void loadMembers(threadView.room_id)}
2633
            focusEventId={threadView.focus_event_id ?? null}
2634
            stickers={roomStickers(threadView.room_id, threadView.root_event_id)}
2635
            onClose={() => void showThread(null)}
2636
          />
2637
        {/if}
2638
      </aside>
2639
      <aside class="members" aria-hidden={!membersShown} aria-label={`Members of ${selectedRoom.name}`}>
2640
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2641
        <div class="pane-resize left" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'members')} on:dblclick={() => resetWidth('members')}></div>
2642
        <div class="members-head">
2643
          <h2>Members</h2>
2644
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
2645
            <span aria-hidden="true">✕</span>
2646
          </button>
2647
        </div>
2648
        {#if $membersLoading && members.length === 0}
2649
          <p class="side-note">Loading members…</p>
2650
        {:else if members.length === 0}
2651
          <p class="side-note">No members loaded.</p>
2652
          {#if $selectedRoomId}
2653
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
2654
              Retry
2655
            </button>
2656
          {/if}
2657
        {:else}
2658
          <ul class="member-list">
2659
            {#each memberGroups as group (group.label)}
2660
              <li class="member-group">
2661
                <h3 class="member-group-label">{group.label}<span>{group.members.length}</span></h3>
2662
                <ul class="member-group-list">
2663
                  {#each group.members as member (member.user_id)}
2664
                    <li>
2665
                      <button
2666
                        type="button"
2667
                        class="member"
2668
                        on:click={(ev) => {
2669
                          const rect = ev.currentTarget.getBoundingClientRect();
2670
                          void openUser(member.user_id, rect.left - 308, rect.top, false);
2671
                        }}
2672
                        on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)}
2673
                      >
2674
                        <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} seed={member.user_id} size={28} />
2675
                        <span class="member-names">
2676
                          <span class="member-name"><EmojiText text={member.display_name || member.name} /></span>
2677
                          <span class="member-id">{member.user_id}</span>
2678
                        </span>
2679
                      </button>
2680
                    </li>
2681
                  {/each}
2682
                </ul>
2683
              </li>
2684
            {/each}
2685
          </ul>
2686
        {/if}
2687
      </aside>
2688
    {/if}
2689
2690
    {#if cloneSource}
2691
      <div class="modal-wrap" role="presentation" on:click|self={() => (cloneSource = null)}>
2692
        <PackCloneDialog source={cloneSource} packs={$imagePacks} rooms={$rooms} onError={pushBanner} onClose={() => (cloneSource = null)} />
2693
      </div>
2694
    {/if}
2695
2696
    {#if dialog}
2697
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
2698
        {#if dialog === 'security'}
2699
          <SecurityPanel
2700
            encryptionState={$encryption}
2701
            verificationState={$verification}
2702
            onAction={() => void loadEncryption()}
2703
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
2704
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
2705
            on:close={() => (dialog = null)}
2706
          />
2707
        {:else if dialog === 'settings'}
2708
          <SettingsPanel
2709
            quick={$quickReactions}
2710
            packs={roomPacks}
2711
            onQuickChange={(list) => void changeQuickReactions(list)}
2712
            on:close={() => (dialog = null)}
2713
            on:packs={() => (dialog = 'packs')}
2714
          />
2715
        {:else if dialog === 'packs'}
2716
          <PackManager packs={$imagePacks} rooms={$rooms} onError={pushBanner} on:close={() => (dialog = null)} />
2717
        {:else}
2718
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
2719
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
2720
              <button
2721
                type="button"
2722
                role="tab"
2723
                aria-selected={dialog === 'join'}
2724
                class:active={dialog === 'join'}
2725
                on:click={() => (dialog = 'join')}
2726
              >
2727
                Join
2728
              </button>
2729
              <button
2730
                type="button"
2731
                role="tab"
2732
                aria-selected={dialog === 'create'}
2733
                class:active={dialog === 'create'}
2734
                on:click={() => (dialog = 'create')}
2735
              >
2736
                Create
2737
              </button>
2738
              <button
2739
                type="button"
2740
                class="icon-btn modal-x"
2741
                aria-label="Close dialog"
2742
                on:click={() => (dialog = null)}
2743
              >
2744
                <span aria-hidden="true">✕</span>
2745
              </button>
2746
            </div>
2747
            {#if dialog === 'join'}
2748
              <form on:submit|preventDefault={() => void join(joinTarget)}>
2749
                <label class="field">
2750
                  <span>Room ID or alias</span>
2751
                  <input
2752
                    type="text"
2753
                    placeholder="!room:example.org or #alias:example.org"
2754
                    bind:value={joinTarget}
2755
                    required
2756
                    disabled={joinBusy}
2757
                  />
2758
                </label>
2759
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
2760
                  {joinBusy ? 'Joining…' : 'Join room'}
2761
                </button>
2762
              </form>
2763
            {:else}
2764
            <form on:submit|preventDefault={() => void create()}>
2765
              <label class="field">
2766
                <span>Room name</span>
2767
                <input
2768
                  type="text"
2769
                  placeholder="Weekend plans"
2770
                  bind:value={createName}
2771
                  required
2772
                  disabled={createBusy}
2773
                />
2774
              </label>
2775
              <label class="field">
2776
                <span>Topic (optional)</span>
2777
                <input
2778
                  type="text"
2779
                  placeholder="What should this room be about?"
2780
                  bind:value={createTopic}
2781
                  disabled={createBusy}
2782
                />
2783
              </label>
2784
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
2785
                {createBusy ? 'Creating…' : 'Create room'}
2786
              </button>
2787
            </form>
2788
            {/if}
2789
          </div>
2790
        {/if}
2791
      </div>
2792
    {/if}
2793
  </div>
2794
{/if}
2795
2796
<ImageLightbox />