atagen

malice

public
Star0
Watch0
919753ab134c5206e6e1c9c74e13eecdbde4eb32
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte2684 lines107.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 { mentionsFromHtml, resolveMentions } from './lib/mentions';
91
  import type { Mention } from './lib/mentions';
92
  import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions';
93
  import { loadKeywords } from './lib/keywords';
94
  import {
95
    linkPreviews,
96
    loadUrlPreviewSettings,
97
    requestLinkPreview,
98
    saveUrlPreviewSettings,
99
    urlPreviewSettings
100
  } from './lib/link-previews';
101
  import { notifyTyping, stopTyping } from './lib/typing';
102
  import {
103
    MEMBERS_WIDTH,
104
    SIDE_WIDTH,
105
    THREAD_WIDTH,
106
    lastSpaceRooms,
107
    lineHeight,
108
    membersWidth,
109
    messageSpacing,
110
    navFolded,
111
    railFolded,
112
    sideWidth,
113
    threadWidth
114
  } from './lib/appearance';
115
  import SettingsPanel from './lib/SettingsPanel.svelte';
116
  import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types';
117
  import type { ImagePack, MemberSummary, OwnProfile, PackImage, Person, QuickReaction, ReplyReference, RoomSummary, TimelineEvent, TimelineItem } from './lib/types';
118
119
  let roomsLoading = false;
120
  let booted = false;
121
  let wasOnline = false;
122
  let search = '';
123
  let sidebarOpen = false;
124
  let membersOpen = false;
125
  let replyingTo: ReplyReference | null = null;
126
  let dialog: 'join' | 'create' | 'security' | 'settings' | 'packs' | null = null;
127
  let cloneSource: CloneSource | null = null;
128
  let joinTarget = '';
129
  let joinBusy = false;
130
  let createName = '';
131
  let createTopic = '';
132
  let createBusy = false;
133
  let leaveBusy = false;
134
  let paginateBusy = false;
135
  let fillingGaps: Record<string, string> = {};
136
  let recentRetrying: Record<string, boolean> = {};
137
  let historyAccount: string | null | undefined;
138
  $: if ($sessionUser !== historyAccount) {
139
    historyAccount = $sessionUser;
140
    fillingGaps = {};
141
    recentRetrying = {};
142
  }
143
  let reacting = false;
144
  let composer = '';
145
  let drafts: Record<string, string> = {};
146
  let stickToBottom = true;
147
  let timelineEl: HTMLElement | null = null;
148
  let timelineViewport: TimelineViewport | null = null;
149
  let composerRef: Composer | null = null;
150
  let avatarInput: HTMLInputElement | null = null;
151
  let uploadBusy = false;
152
  let uploadName: string | null = null;
153
  let staged: Record<string, StagedAttachment[]> = {};
154
  let editing: { roomId: string; eventId: string; original: string; stash: string } | null = null;
155
  /** Everyone picked from the finder per room; only those whose name is still in the text get linked on send. */
156
  let pickedMentions: Record<string, Mention[]> = {};
157
  const WARM_ROOM_LIMIT = 8;
158
  /** Rooms left open after switching away so coming back is instant, least recently viewed first. */
159
  let warmRooms: string[] = [];
160
  let openReady: Record<string, boolean> = {};
161
  let openFailed: Record<string, string> = {};
162
  let membersFor: string | null = null;
163
  let lastReadKey = '';
164
  let readTimer: number | null = null;
165
  let profile: OwnProfile | null = null;
166
  let profileMxc: string | null = null;
167
  let selectedSpaceId: string | null = null;
168
  let mentionsOpen = false;
169
  let searchOpen = false;
170
  let searchScopes: ScopeOption[] = [{ label: 'Everywhere', scope: { kind: 'all' } }];
171
  let spaceChildIds: string[] | null = null;
172
  let spaceChildrenLoading = false;
173
  let spaceChildrenError: string | null = null;
174
  let avatarByUser: Record<string, string | null> = {};
175
  let restoringRoute = false;
176
  function motionDuration(ms: number): number {
177
    return typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : ms;
178
  }
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(): void {
664
    if (timelineViewport?.element === timelineEl) timelineViewport.scrollToBottom();
665
    else if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight;
666
  }
667
668
  function noteUserScroll(): void {
669
    timelineViewport?.releaseScroll();
670
  }
671
672
  function onTimelineKey(e: KeyboardEvent): void {
673
    if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) noteUserScroll();
674
  }
675
676
  function onTimelineScroll(): void {
677
    if (!timelineEl) return;
678
    if (timelineViewport?.consumeScroll()) return;
679
    const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight;
680
    const wasAtBottom = stickToBottom;
681
    stickToBottom = gap < 2;
682
    if (stickToBottom && !wasAtBottom) queueReadReceipt();
683
    timelineViewport?.capture();
684
    if (timelineEl.scrollTop < 80 && !hasStart && !paginateBusy) void paginate();
685
  }
686
687
  function pinTimeline(node: HTMLElement) {
688
    const viewport = new TimelineViewport(node.parentElement!, $selectedRoomId);
689
    timelineViewport = viewport;
690
    const observer = new ResizeObserver(() => {
691
      if (timelineViewport !== viewport || viewport.roomId !== $selectedRoomId) return;
692
      if (stickToBottom) viewport.scrollToBottom(true);
693
      else viewport.restore();
694
    });
695
    observer.observe(node);
696
    if (node.parentElement) observer.observe(node.parentElement);
697
    return { destroy: () => {
698
      observer.disconnect();
699
      viewport.releaseScroll();
700
      if (timelineViewport === viewport) timelineViewport = null;
701
    } };
702
  }
703
704
  $: void trackTimeline($selectedRoomId, items);
705
  async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> {
706
    if (!roomId || list.length === 0) return;
707
    if (roomId !== $selectedRoomId) return;
708
    await tick();
709
    if (roomId !== $selectedRoomId || timelineViewport?.roomId !== roomId) return;
710
    if (stickToBottom) timelineViewport.scrollToBottom(true);
711
    else timelineViewport.restore();
712
    queueReadReceipt();
713
  }
714
715
  function queueReadReceipt(): void {
716
    if (readTimer !== null) window.clearTimeout(readTimer);
717
    readTimer = window.setTimeout(() => {
718
      readTimer = null;
719
      void sendReadReceipt();
720
    }, 800);
721
  }
722
723
  async function sendReadReceipt(): Promise<void> {
724
    const roomId = $selectedRoomId;
725
    if (!roomId || roomId === peeking) return;
726
    if (document.hidden || !document.hasFocus() || !stickToBottom) return;
727
    const list = $timelines[roomId] ?? [];
728
    for (let i = list.length - 1; i >= 0; i -= 1) {
729
      const entry = list[i];
730
      if (entry.kind === 'event' && entry.event.event_id) {
731
        const key = `${roomId}:${entry.event.event_id}`;
732
        if (key === lastReadKey) return;
733
        lastReadKey = key;
734
        try {
735
          await markRead(roomId, entry.event.event_id);
736
        } catch {
737
          return;
738
        }
739
        return;
740
      }
741
    }
742
  }
743
744
  function send(): void {
745
    if (editing) {
746
      submitEdit();
747
      return;
748
    }
749
    const roomId = $selectedRoomId;
750
    const body = composer.trim();
751
    const attachments = roomId ? (staged[roomId] ?? []) : [];
752
    if (!roomId || (!body && attachments.length === 0)) return;
753
    if (!openReady[roomId]) {
754
      pushBanner('Still opening this room — sending is disabled until the room is ready.');
755
      return;
756
    }
757
    if (attachments.length > 0 && uploadBusy) return;
758
    const command = parseCommand(body);
759
    if (command && !isKnownCommand(command.name)) {
760
      pushBanner(`Unknown command /${command.name}`);
761
      return;
762
    }
763
    if (command && attachments.length > 0) {
764
      if (command.name !== 'roomavatar' && command.name !== 'globalavatar') {
765
        pushBanner(`/${command.name} doesn't take attachments`);
766
        return;
767
      }
768
      if (command.args || attachments.length !== 1 || !attachments[0].file.type.startsWith('image/')) {
769
        pushBanner(`/${command.name} takes a single attached image`);
770
        return;
771
      }
772
    }
773
    composer = '';
774
    if (roomId in drafts) delete drafts[roomId];
775
    stickToBottom = true;
776
    const reply = replyingTo;
777
    replyingTo = null;
778
    const text = unescapeCommand(body);
779
    const mentions = resolveMentions(text, pickedMentions[roomId] ?? []);
780
    pickedMentions = { ...pickedMentions, [roomId]: [] };
781
    composerRef?.closeFinders();
782
    if (command) {
783
      const image = attachments[0] ?? null;
784
      if (image) {
785
        const { [roomId]: _used, ...rest } = staged;
786
        staged = rest;
787
      }
788
      void execute(roomId, command, reply, mentions, image?.file ?? null).finally(() => {
789
        if (image?.previewUrl) URL.revokeObjectURL(image.previewUrl);
790
      });
791
    } else if (attachments.length === 0) {
792
      queueSend(roomId, text, reply, mentions, resolveEmotes(text, roomEmotes));
793
    } else {
794
      const { [roomId]: _sent, ...rest } = staged;
795
      staged = rest;
796
      void sendAttachments(roomId, text, reply, mentions, attachments);
797
    }
798
    if (peeking === roomId) stopPeeking();
799
    composerRef?.focus();
800
  }
801
802
  function lastOwnEventId(): string | null {
803
    for (let i = items.length - 1; i >= 0; i -= 1) {
804
      const entry = items[i];
805
      if (entry.kind === 'event' && entry.event.own && entry.event.event_id && entry.event.content.kind !== 'Redacted') {
806
        return entry.event.event_id;
807
      }
808
    }
809
    return null;
810
  }
811
812
  async function execute(
813
    roomId: string,
814
    command: ParsedCommand,
815
    reply: ReplyReference | null,
816
    mentions: Mention[],
817
    image: File | null
818
  ): Promise<void> {
819
    const { name, args } = command;
820
    const target = () => {
821
      const found = splitTarget(args, Object.values(people));
822
      if ('error' in found) throw new Error(found.error);
823
      return found;
824
    };
825
    const required = (what: string) => {
826
      if (!args) throw new Error(`/${name} needs ${what}`);
827
      return args;
828
    };
829
    try {
830
      switch (name) {
831
        case 'me':
832
        case 'notice': {
833
          const said = required('something to say');
834
          await sendMessage(roomId, said, null, mentions, name === 'me' ? 'emote' : 'notice', resolveEmotes(said, roomEmotes));
835
          break;
836
        }
837
        case 'sticker': {
838
          const { pack, sticker } = findSticker(enabledPacks(packsForRoom($imagePacks, roomId, $rooms), $disabledPackImages), required('a sticker name'));
839
          await runCommand({ op: 'send_sticker', room_id: roomId, pack_id: pack.id, shortcode: sticker.shortcode });
840
          break;
841
        }
842
        case 'msg': {
843
          const { user_id, rest } = target();
844
          const res = (await runCommand({ op: 'direct', user_id })) as { room_id: string };
845
          await refreshRooms();
846
          await selectRoom(res.room_id);
847
          if (rest) queueSend(res.room_id, rest);
848
          break;
849
        }
850
        case 'join':
851
          await join(required('a room id or alias'));
852
          break;
853
        case 'leave':
854
          await leave();
855
          break;
856
        case 'invite':
857
          await runCommand({ op: 'invite', room_id: roomId, user_id: target().user_id });
858
          break;
859
        case 'disinvite':
860
        case 'kick':
861
        case 'ban':
862
        case 'unban': {
863
          const { user_id, rest } = target();
864
          const op = name === 'disinvite' ? 'kick' : name;
865
          await runCommand({ op, room_id: roomId, user_id, reason: rest || null });
866
          break;
867
        }
868
        case 'powerlevel': {
869
          const { user_id, rest } = target();
870
          const level = Number(rest);
871
          if (!rest || !Number.isInteger(level)) throw new Error('/powerlevel needs a whole number after the name');
872
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id, level });
873
          break;
874
        }
875
        case 'mute':
876
        case 'unmute':
877
          await runCommand({ op: 'mute', room_id: roomId, user_id: target().user_id, muted: name === 'mute' });
878
          break;
879
        case 'ignore':
880
        case 'unignore':
881
          await runCommand({ op: name, user_id: target().user_id });
882
          break;
883
        case 'roomnick':
884
          await runCommand({ op: 'set_room_display_name', room_id: roomId, name: args || null });
885
          break;
886
        case 'roomavatar':
887
          if (image) {
888
            await uploadRoomAvatar(roomId, image);
889
          } else if (args && !args.startsWith('mxc://')) {
890
            throw new Error('/roomavatar takes an mxc:// link, an attached image, or nothing to drop the override');
891
          } else {
892
            await runCommand({ op: 'set_room_avatar', room_id: roomId, mxc: args || null });
893
          }
894
          break;
895
        case 'delete': {
896
          const eventId = reply?.event_id ?? lastOwnEventId();
897
          if (!eventId) throw new Error('Nothing of yours to delete here');
898
          await runCommand({ op: 'redact', room_id: roomId, event_id: eventId, reason: args || null });
899
          break;
900
        }
901
        case 'globalnick':
902
          await runCommand({ op: 'set_display_name', name: required('a name') });
903
          await loadProfile();
904
          break;
905
        case 'globalavatar':
906
          if (image) {
907
            await uploadAvatar(image);
908
            await loadProfile();
909
          } else if (!args) {
910
            avatarInput?.click();
911
          } else if (args.startsWith('mxc://')) {
912
            await runCommand({ op: 'set_avatar', mxc: args });
913
            await loadProfile();
914
          } else {
915
            throw new Error('/globalavatar takes an mxc:// link, or nothing to pick a file');
916
          }
917
          break;
918
      }
919
    } catch (e) {
920
      pushBanner(e instanceof Error ? e.message : `/${name} failed`);
921
    }
922
  }
923
924
  async function onAvatarChosen(): Promise<void> {
925
    const file = avatarInput?.files?.[0];
926
    if (avatarInput) avatarInput.value = '';
927
    if (!file) return;
928
    try {
929
      await uploadAvatar(file);
930
      await loadProfile();
931
    } catch (e) {
932
      pushBanner(e instanceof Error ? e.message : 'Avatar upload failed');
933
    }
934
  }
935
936
  async function sendAttachments(
937
    roomId: string,
938
    body: string,
939
    reply: ReplyReference | null,
940
    mentions: Mention[],
941
    attachments: StagedAttachment[]
942
  ): Promise<void> {
943
    let first = true;
944
    uploadBusy = true;
945
    try {
946
      for (const attachment of attachments) {
947
        uploadName = attachment.file.name || 'attachment';
948
        try {
949
          if (first) await uploadAttachment(roomId, attachment.file, body || null, reply?.event_id ?? null, mentions, resolveEmotes(body, roomEmotes));
950
          else await uploadAttachment(roomId, attachment.file);
951
          first = false;
952
        } catch (e) {
953
          pushBanner(e instanceof Error ? e.message : 'Upload failed');
954
        }
955
        if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
956
      }
957
    } finally {
958
      uploadBusy = false;
959
      uploadName = null;
960
    }
961
  }
962
963
  function stageFiles(files: File[]): void {
964
    const roomId = $selectedRoomId;
965
    if (!roomId || !openReady[roomId]) return;
966
    const accepted = stageAttachments(files, pushBanner);
967
    if (accepted.length === 0) return;
968
    staged = { ...staged, [roomId]: [...(staged[roomId] ?? []), ...accepted] };
969
    composerRef?.focus();
970
  }
971
972
  function unstage(roomId: string, id: number): void {
973
    const list = staged[roomId] ?? [];
974
    const removed = list.find((a) => a.id === id);
975
    if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
976
    staged = { ...staged, [roomId]: list.filter((a) => a.id !== id) };
977
  }
978
979
  function clearAllStaged(): void {
980
    for (const list of Object.values(staged)) releaseStaged(list);
981
    staged = {};
982
  }
983
984
  function startEdit(eventId: string, body: string): void {
985
    const roomId = $selectedRoomId;
986
    if (!roomId) return;
987
    const stash = editing ? editing.stash : composer;
988
    editing = { roomId, eventId, original: body, stash };
989
    const entry = items.find((i) => i.kind === 'event' && i.event.event_id === eventId);
990
    if (entry?.kind === 'event' && entry.event.content.kind === 'Message') {
991
      const existing = mentionsFromHtml(entry.event.content.message.formatted_body);
992
      pickedMentions = { ...pickedMentions, [roomId]: [...(pickedMentions[roomId] ?? []), ...existing] };
993
    }
994
    composer = body;
995
    replyingTo = null;
996
    composerRef?.focus();
997
  }
998
999
  function cancelEdit(): void {
1000
    if (!editing) return;
1001
    composer = editing.stash;
1002
    editing = null;
1003
    composerRef?.focus();
1004
  }
1005
1006
  function submitEdit(): void {
1007
    if (!editing) return;
1008
    const { roomId, eventId, original } = editing;
1009
    const body = composer.trim();
1010
    cancelEdit();
1011
    if (!body || body === original.trim()) return;
1012
    editMessage(roomId, eventId, body, resolveMentions(body, pickedMentions[roomId] ?? []), resolveEmotes(body, roomEmotes)).catch((e) => pushBanner(e instanceof Error ? e.message : 'Edit failed'));
1013
  }
1014
1015
  function editLastOwn(): boolean {
1016
    for (let i = items.length - 1; i >= 0; i -= 1) {
1017
      const entry = items[i];
1018
      if (entry.kind !== 'event' || !entry.event.own) continue;
1019
      const ev = entry.event;
1020
      if (!ev.editable || !ev.event_id || ev.content.kind !== 'Message' || ev.content.message.kind !== 'Text') return false;
1021
      startEdit(ev.event_id, ev.content.message.body);
1022
      return true;
1023
    }
1024
    return false;
1025
  }
1026
1027
  function startReply(target: ReplyReference): void {
1028
    if (editing) cancelEdit();
1029
    replyingTo = target;
1030
    composerRef?.focus();
1031
  }
1032
1033
  let pinnedOpenFor: string | null = null;
1034
  let pinnedCloseVersion = 0;
1035
  let pinsExpanded = false;
1036
  let pinPreview: TimelineEvent | null = null;
1037
  let pinJumpBusy = false;
1038
  $: syncPinned(selectedRoom?.room_id ?? null, (selectedRoom?.pinned_events.length ?? 0) > 0, $selectedRoomId ? $pinnedTimelineVersions[$selectedRoomId] ?? 0 : 0);
1039
  function syncPinned(roomId: string | null, hasPins: boolean, version: number): void {
1040
    const want = hasPins ? roomId : null;
1041
    if (want === pinnedOpenFor && version === pinnedCloseVersion) return;
1042
    if (pinnedOpenFor) runCommand({ op: 'close_pinned', room_id: pinnedOpenFor }).catch(() => undefined);
1043
    pinnedOpenFor = want;
1044
    pinnedCloseVersion = version;
1045
    pinsExpanded = false;
1046
    if (want) runCommand({ op: 'open_pinned', room_id: want }).catch(() => undefined);
1047
  }
1048
1049
  $: pins = pinnedList(selectedRoom, $pinnedTimelines);
1050
  function pinnedList(room: RoomSummary | null, all: Record<string, TimelineItem[]>): TimelineEvent[] {
1051
    if (!room || !room.pinned_events.length) return [];
1052
    const order = new Map(room.pinned_events.map((id, i) => [id, i]));
1053
    return (all[room.room_id] ?? [])
1054
      .flatMap((item) => (item.kind === 'event' && item.event.event_id && order.has(item.event.event_id) ? [item.event] : []))
1055
      .sort((a, b) => (order.get(b.event_id!) ?? 0) - (order.get(a.event_id!) ?? 0));
1056
  }
1057
1058
  function setPinned(eventId: string, pinned: boolean): void {
1059
    const roomId = $selectedRoomId;
1060
    if (!roomId) return;
1061
    runCommand({ op: 'set_pinned', room_id: roomId, event_id: eventId, pinned }).catch((e) =>
1062
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin')
1063
    );
1064
  }
1065
1066
  async function jumpToPin(eventId: string): Promise<void> {
1067
    const roomId = $selectedRoomId;
1068
    if (!roomId || !eventId || pinJumpBusy) return;
1069
    pinsExpanded = false;
1070
    const pinned = pins.find((event) => event.event_id === eventId) ?? null;
1071
    if (pinned?.thread_root) {
1072
      openThreadHere(pinned.thread_root, eventId);
1073
      return;
1074
    }
1075
    pinPreview = pinned;
1076
    pinJumpBusy = true;
1077
    try {
1078
      for (let attempt = 0; attempt < 24; attempt += 1) {
1079
        if (($timelines[roomId] ?? []).some((item) => item.kind === 'event' && item.event.event_id === eventId)) {
1080
          pinPreview = null;
1081
          await tick();
1082
          jumpTo(eventId);
1083
          return;
1084
        }
1085
        await paginateRoom(roomId);
1086
        await new Promise((resolve) => window.setTimeout(resolve, 180));
1087
      }
1088
      pushBanner('Could not load that pinned message');
1089
    } catch (e) {
1090
      pushBanner(e instanceof Error ? e.message : 'Could not load that pinned message');
1091
    } finally {
1092
      pinJumpBusy = false;
1093
    }
1094
  }
1095
1096
  function jumpTo(eventId: string): void {
1097
    const el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
1098
    const root = !el && $selectedRoomId ? threadHolding($selectedRoomId, eventId) : null;
1099
    if (root) {
1100
      openThreadHere(root, eventId);
1101
      return;
1102
    }
1103
    if (!el) {
1104
      pushBanner('The original message is not loaded. Scroll up to load older messages.');
1105
      return;
1106
    }
1107
    stickToBottom = false;
1108
    timelineViewport?.releaseScroll();
1109
    el.scrollIntoView({ block: 'center', behavior: 'smooth' });
1110
    el.classList.remove('flash');
1111
    void el.offsetWidth;
1112
    el.classList.add('flash');
1113
  }
1114
1115
  let typedText = '';
1116
  let typedRoom: string | null = null;
1117
  $: trackTypingInput(composer, $selectedRoomId, openReady);
1118
  function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void {
1119
    const edited = roomId === typedRoom && text !== typedText;
1120
    typedText = text;
1121
    typedRoom = roomId;
1122
    if (!roomId || !ready[roomId] || !text.trim()) {
1123
      stopTyping();
1124
    } else if (edited && roomId !== peeking) {
1125
      notifyTyping(roomId);
1126
    }
1127
  }
1128
1129
  $: void trackPending($selectedRoomId, pendingItems);
1130
  async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> {
1131
    if (!roomId) return;
1132
    if (roomId !== $selectedRoomId) return;
1133
    await tick();
1134
    if (roomId !== $selectedRoomId || timelineViewport?.roomId !== roomId) return;
1135
    if (stickToBottom) timelineViewport.scrollToBottom(true);
1136
    else timelineViewport.restore();
1137
  }
1138
1139
  async function react(eventId: string, key: string, shortcode?: string): Promise<void> {
1140
    const roomId = $selectedRoomId;
1141
    if (!roomId || !eventId || reacting) return;
1142
    reacting = true;
1143
    try {
1144
      await reactToMessage(roomId, eventId, key, reactionShortcode(key, shortcode, allPacks($imagePacks)));
1145
    } catch (e) {
1146
      pushBanner(e instanceof Error ? e.message : 'Reaction failed');
1147
    } finally {
1148
      reacting = false;
1149
    }
1150
  }
1151
1152
  function previewLoader(roomId: string): (url: string) => void {
1153
    return (url) => requestLinkPreview(roomId, url);
1154
  }
1155
1156
  async function changeEncryptedPreviews(enabled: boolean): Promise<void> {
1157
    try {
1158
      await saveUrlPreviewSettings({ encrypted_rooms: enabled });
1159
    } catch (e) {
1160
      pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting');
1161
    }
1162
  }
1163
1164
  async function changeQuickReactions(list: QuickReaction[]): Promise<void> {
1165
    try {
1166
      await saveQuickReactions(list);
1167
    } catch (e) {
1168
      pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions');
1169
    }
1170
  }
1171
1172
  async function paginate(): Promise<void> {
1173
    const roomId = $selectedRoomId;
1174
    if (!roomId || paginateBusy || $recentHistory[roomId] === 'Loading') return;
1175
    paginateBusy = true;
1176
    try {
1177
      await paginateRoom(roomId);
1178
    } catch (e) {
1179
      pushBanner(e instanceof Error ? e.message : 'Loading older messages failed');
1180
    } finally {
1181
      paginateBusy = false;
1182
    }
1183
  }
1184
1185
  async function fillGap(gapId: string): Promise<void> {
1186
    const roomId = $selectedRoomId;
1187
    if (!roomId || fillingGaps[roomId]) return;
1188
    fillingGaps = { ...fillingGaps, [roomId]: gapId };
1189
    try {
1190
      await fillHistoryGap(roomId, gapId);
1191
    } catch (e) {
1192
      pushBanner(e instanceof Error ? e.message : 'Loading the missing history failed');
1193
    } finally {
1194
      if (fillingGaps[roomId] === gapId) {
1195
        const { [roomId]: _done, ...rest } = fillingGaps;
1196
        fillingGaps = rest;
1197
      }
1198
    }
1199
  }
1200
1201
  async function retryRecentHistory(roomId: string): Promise<void> {
1202
    if (recentRetrying[roomId]) return;
1203
    recentRetrying = { ...recentRetrying, [roomId]: true };
1204
    try {
1205
      await requestRecentHistory(roomId);
1206
    } catch (e) {
1207
      pushBanner(e instanceof Error ? e.message : 'Loading recent history failed');
1208
    } finally {
1209
      const { [roomId]: _done, ...rest } = recentRetrying;
1210
      recentRetrying = rest;
1211
    }
1212
  }
1213
1214
  async function loadMembers(roomId: string): Promise<void> {
1215
    if (membersFor === roomId && $membersLoading) return;
1216
    membersFor = roomId;
1217
    membersLoading.set(true);
1218
    try {
1219
      const res = await getMembers(roomId);
1220
      membersByRoom.update((all) => ({ ...all, [roomId]: res.members }));
1221
      avatarByUser = { ...avatarByUser, ...avatarMap(res.members) };
1222
    } catch (e) {
1223
      pushBanner(e instanceof Error ? e.message : 'Could not load members');
1224
    } finally {
1225
      if (membersFor === roomId) membersLoading.set(false);
1226
    }
1227
  }
1228
1229
  function avatarMap(list: MemberSummary[]): Record<string, string | null> {
1230
    const next: Record<string, string | null> = {};
1231
    for (const member of list) next[member.user_id] = member.avatar;
1232
    return next;
1233
  }
1234
1235
  function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> {
1236
    const out: Record<string, Person> = {};
1237
    for (const item of list) {
1238
      if (item.kind !== 'event') continue;
1239
      const s = item.event.sender;
1240
      out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar };
1241
    }
1242
    for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar };
1243
    return out;
1244
  }
1245
1246
  function senderAvatarFor(userId: string): string | null {
1247
    return avatarByUser[userId] ?? null;
1248
  }
1249
1250
  $: threadView = $openThread && $openThread.room_id === $selectedRoomId ? $openThread : null;
1251
  $: if ($openThread && $openThread.room_id !== $selectedRoomId) void showThread(null);
1252
  let threadFolds: Record<string, boolean> = {};
1253
  const BOTH_PANES_MIN_WIDTH = 1300;
1254
  let viewportWidth = typeof window === 'undefined' ? BOTH_PANES_MIN_WIDTH : window.innerWidth;
1255
  let rightFront: 'thread' | 'members' = 'members';
1256
  $: bothPanesFit = viewportWidth >= BOTH_PANES_MIN_WIDTH;
1257
  $: threadShown = !!threadView && (bothPanesFit || !membersOpen || rightFront === 'thread');
1258
  $: membersShown = !!selectedRoom && membersOpen && (bothPanesFit || !threadView || rightFront === 'members');
1259
1260
  function openThreadHere(rootEventId: string, focusEventId?: string): void {
1261
    if (!$selectedRoomId) return;
1262
    rightFront = 'thread';
1263
    void showThread({ room_id: $selectedRoomId, root_event_id: rootEventId, focus_event_id: focusEventId });
1264
  }
1265
1266
  async function openLive(roomId: string, eventId: string, threadRoot: string | null): Promise<void> {
1267
    await selectRoom(roomId);
1268
    if ($selectedRoomId !== roomId) return;
1269
    if (threadRoot) {
1270
      openThreadHere(threadRoot, eventId);
1271
      return;
1272
    }
1273
    await tick();
1274
    if (timelineEl?.querySelector(`[data-event="${CSS.escape(eventId)}"]`)) jumpTo(eventId);
1275
  }
1276
1277
  function threadHolding(roomId: string, eventId: string): string | null {
1278
    for (const [key, list] of Object.entries($threadTimelines)) {
1279
      const [room, root] = key.split('\u0000');
1280
      if (room === roomId && list.some((item) => item.kind === 'event' && item.event.event_id === eventId)) return root;
1281
    }
1282
    return null;
1283
  }
1284
1285
  async function openThreadIn(roomId: string, rootEventId: string): Promise<void> {
1286
    if ($selectedRoomId !== roomId) await selectRoom(roomId);
1287
    if ($selectedRoomId === roomId) openThreadHere(rootEventId);
1288
  }
1289
1290
  $: syncThreadLists([...new Set([...($selectedRoomId ? [$selectedRoomId] : []), ...Object.keys(threadFolds).filter((id) => threadFolds[id])])]);
1291
1292
  function threadFoldOpen(roomId: string, folds: Record<string, boolean>, q: string): boolean {
1293
    if (q) return ($threadsByRoom[roomId] ?? []).some((t) => threadMatches(t, q));
1294
    return !!folds[roomId];
1295
  }
1296
1297
  function toggleMembers(): void {
1298
    if (membersShown) {
1299
      membersOpen = false;
1300
    } else {
1301
      membersOpen = true;
1302
      rightFront = 'members';
1303
    }
1304
    if (membersOpen && $selectedRoomId) {
1305
      void loadMembers($selectedRoomId);
1306
      void loadLevels($selectedRoomId);
1307
    }
1308
  }
1309
1310
  async function join(target: string): Promise<void> {
1311
    const room = target.trim();
1312
    if (!room || joinBusy) return;
1313
    joinBusy = true;
1314
    try {
1315
      const res = await joinRoom(room);
1316
      joinTarget = '';
1317
      dialog = null;
1318
      await refreshRooms();
1319
      await selectRoom(res.room_id);
1320
    } catch (e) {
1321
      pushBanner(e instanceof Error ? e.message : 'Join failed');
1322
    } finally {
1323
      joinBusy = false;
1324
    }
1325
  }
1326
1327
  async function create(): Promise<void> {
1328
    const name = createName.trim();
1329
    if (!name || createBusy) return;
1330
    createBusy = true;
1331
    try {
1332
      const res = await createRoom(name, createTopic.trim() || undefined);
1333
      createName = '';
1334
      createTopic = '';
1335
      dialog = null;
1336
      await refreshRooms();
1337
      await selectRoom(res.room_id);
1338
    } catch (e) {
1339
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
1340
    } finally {
1341
      createBusy = false;
1342
    }
1343
  }
1344
1345
  async function leave(roomId: string | null = $selectedRoomId): Promise<void> {
1346
    if (!roomId || leaveBusy) return;
1347
    leaveBusy = true;
1348
    stopTyping();
1349
    try {
1350
      await leaveRoom(roomId);
1351
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
1352
      if (warmRooms.includes(roomId)) {
1353
        forgetOpenRoom(roomId);
1354
        closeRoom(roomId).catch(() => undefined);
1355
      }
1356
      await refreshRooms();
1357
    } catch (e) {
1358
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
1359
    } finally {
1360
      leaveBusy = false;
1361
    }
1362
  }
1363
1364
  function connectionClass(state: string): string {
1365
    if (state === 'online') return 'dot-online';
1366
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
1367
    return 'dot-off';
1368
  }
1369
1370
  let dragSpaceId: string | null = null;
1371
  let dropTarget: { id: string; after: boolean } | null = null;
1372
  let menu: { items: MenuItem[]; x: number; y: number; above?: boolean } | null = null;
1373
  let userCard: { userId: string; x: number; y: number; confirm: 'kick' | 'ban' | null } | null = null;
1374
  let levelsByRoom: Record<string, PowerLevels | null> = {};
1375
  let peeking: string | null = null;
1376
1377
  $: roomLevels = $selectedRoomId ? (levelsByRoom[$selectedRoomId] ?? null) : null;
1378
1379
  function personFor(userId: string): Person {
1380
    return people[userId] ?? { user_id: userId, name: userId, avatar: avatarByUser[userId] ?? null };
1381
  }
1382
1383
  function memberFor(userId: string): MemberSummary | null {
1384
    return members.find((m) => m.user_id === userId) ?? null;
1385
  }
1386
1387
  async function loadLevels(roomId: string): Promise<void> {
1388
    try {
1389
      const levels = parsePowerLevels(await runCommand({ op: 'power_levels', room_id: roomId }));
1390
      levelsByRoom = { ...levelsByRoom, [roomId]: levels };
1391
    } catch {
1392
      levelsByRoom = { ...levelsByRoom, [roomId]: levelsByRoom[roomId] ?? null };
1393
    }
1394
  }
1395
1396
  async function openUser(userId: string, x: number, y: number, asMenu: boolean): Promise<void> {
1397
    const roomId = $selectedRoomId;
1398
    if (roomId && !(roomId in levelsByRoom)) await loadLevels(roomId);
1399
    else if (roomId) void loadLevels(roomId);
1400
    if (asMenu) menu = { items: userMenuItems(userId, x, y), x, y };
1401
    else userCard = { userId, x, y, confirm: null };
1402
  }
1403
1404
  function copyText(text: string): void {
1405
    navigator.clipboard.writeText(text).catch(() => pushBanner('Could not copy to the clipboard'));
1406
  }
1407
1408
  function userMenuItems(userId: string, x: number, y: number): MenuItem[] {
1409
    const own = userId === $sessionUser;
1410
    const member = memberFor(userId);
1411
    const items: MenuItem[] = [];
1412
    if (!own) items.push({ label: 'Message', action: () => void userAction(userId, { kind: 'message' }) });
1413
    items.push({ label: 'Mention', action: () => void userAction(userId, { kind: 'mention' }) });
1414
    items.push({ label: 'Copy user ID', action: () => copyText(userId) });
1415
    const firstModeration = items.length;
1416
    if (roomLevels && $sessionUser) {
1417
      const can = allowed(roomLevels, $sessionUser, userId);
1418
      const banned = member?.membership === 'Ban';
1419
      if (can.setLevel && !own) {
1420
        const muted = isMuted(roomLevels, userId);
1421
        items.push({ label: muted ? 'Unmute' : 'Mute', action: () => void userAction(userId, { kind: muted ? 'unmute' : 'mute' }) });
1422
      }
1423
      if (can.kick && !banned) items.push({ label: 'Kick…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'kick' }) });
1424
      if (can.ban && banned) items.push({ label: 'Unban', action: () => void userAction(userId, { kind: 'unban' }) });
1425
      if (can.ban && !banned) items.push({ label: 'Ban…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'ban' }) });
1426
      if (can.setLevel) items.push({ label: 'Power level…', action: () => (userCard = { userId, x, y, confirm: null }) });
1427
    }
1428
    if (items[firstModeration]) items[firstModeration] = { ...items[firstModeration], divider: true };
1429
    if (!own) {
1430
      const kind = member?.ignored ? 'unignore' : 'ignore';
1431
      items.push({ label: member?.ignored ? 'Unignore' : 'Ignore', divider: true, action: () => void userAction(userId, { kind }) });
1432
    }
1433
    return items;
1434
  }
1435
1436
  async function insertMention(person: Person): Promise<void> {
1437
    const roomId = $selectedRoomId;
1438
    if (!roomId) return;
1439
    const lead = composer && !/\s$/.test(composer) ? ' ' : '';
1440
    composer = `${composer}${lead}${person.name} `;
1441
    pickedMentions = {
1442
      ...pickedMentions,
1443
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
1444
    };
1445
    await composerRef?.focusEnd();
1446
  }
1447
1448
  async function userAction(userId: string, action: UserAction): Promise<void> {
1449
    const roomId = $selectedRoomId;
1450
    try {
1451
      switch (action.kind) {
1452
        case 'message': {
1453
          const res = (await runCommand({ op: 'direct', user_id: userId })) as { room_id: string };
1454
          await refreshRooms();
1455
          await selectRoom(res.room_id);
1456
          return;
1457
        }
1458
        case 'mention':
1459
          await insertMention(personFor(userId));
1460
          return;
1461
        case 'ignore':
1462
        case 'unignore':
1463
          await runCommand({ op: action.kind, user_id: userId });
1464
          if (roomId) void loadMembers(roomId);
1465
          return;
1466
      }
1467
      if (!roomId) return;
1468
      switch (action.kind) {
1469
        case 'kick':
1470
        case 'ban':
1471
          await runCommand({ op: action.kind, room_id: roomId, user_id: userId, reason: action.reason });
1472
          break;
1473
        case 'unban':
1474
          await runCommand({ op: 'unban', room_id: roomId, user_id: userId, reason: null });
1475
          break;
1476
        case 'mute':
1477
        case 'unmute':
1478
          await runCommand({ op: 'mute', room_id: roomId, user_id: userId, muted: action.kind === 'mute' });
1479
          break;
1480
        case 'power':
1481
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id: userId, level: action.level });
1482
          break;
1483
      }
1484
      void loadLevels(roomId);
1485
      void loadMembers(roomId);
1486
    } catch (e) {
1487
      pushBanner(e instanceof Error ? e.message : 'That action failed');
1488
    }
1489
  }
1490
1491
  function roomMenuItems(room: RoomSummary): MenuItem[] {
1492
    const items: MenuItem[] = room.space
1493
      ? [{ label: 'Open', action: () => void selectSpace(room.room_id) }]
1494
      : [
1495
          { label: 'Open', action: () => void selectRoom(room.room_id) },
1496
          { label: 'Peek', action: () => void selectRoom(room.room_id, true) }
1497
        ];
1498
    items.push({ label: room.favourite ? 'Unpin' : room.space ? 'Pin to top' : 'Pin', action: () => void togglePin(room) });
1499
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${room.canonical_alias ?? room.room_id}`) });
1500
    items.push({ label: 'Copy room ID', action: () => copyText(room.room_id) });
1501
    if (room.membership === 'Joined') items.push({ label: 'Leave', danger: true, divider: true, action: () => void leave(room.room_id) });
1502
    return items;
1503
  }
1504
1505
  function openRoomMenu(ev: MouseEvent, room: RoomSummary): void {
1506
    menu = { items: roomMenuItems(room), x: ev.clientX, y: ev.clientY };
1507
  }
1508
1509
  function roomName(roomId: string): string {
1510
    return $rooms.find((r) => r.room_id === roomId)?.name ?? roomId;
1511
  }
1512
1513
  function roomStickers(roomId: string, threadRoot: string | null = null): StickerHandlers {
1514
    return {
1515
      onSend: (pack, image) => void sendSticker(roomId, pack, image, threadRoot),
1516
      onClone: (pack, image, x, y) => openCloneImageMenu(pack, image, x, y),
1517
      onClonePack: (pack, x, y) => openClonePackMenu(pack, x, y),
1518
      onManage: () => (dialog = 'packs'),
1519
      roomName
1520
    };
1521
  }
1522
1523
  async function sendSticker(roomId: string, pack: ImagePack, image: PackImage, threadRoot: string | null = null): Promise<void> {
1524
    if (!threadRoot) stickToBottom = true;
1525
    try {
1526
      await runCommand({ op: 'send_sticker', room_id: roomId, thread_root: threadRoot, pack_id: pack.id, shortcode: image.shortcode });
1527
      if (peeking === roomId) stopPeeking();
1528
    } catch (e) {
1529
      pushBanner(e instanceof Error ? e.message : 'Could not send the sticker');
1530
    }
1531
  }
1532
1533
  async function runClone(request: CommandRequest, failure: string): Promise<void> {
1534
    try {
1535
      const res = (await runCommand(request)) as { skipped?: string[] } | undefined;
1536
      if (res?.skipped?.length) pushBanner(`Couldn't copy ${res.skipped.map((s) => `:${s}:`).join(', ')}`);
1537
    } catch (e) {
1538
      pushBanner(e instanceof Error ? e.message : failure);
1539
    }
1540
  }
1541
1542
  function openCloneImageMenu(pack: ImagePack, image: PackImage, x: number, y: number): void {
1543
    menu = null;
1544
    cloneSource = { kind: 'image', pack, image };
1545
  }
1546
1547
  function openClonePackMenu(pack: ImagePack, x: number, y: number): void {
1548
    menu = null;
1549
    cloneSource = { kind: 'pack', pack };
1550
  }
1551
1552
  function openCloneStickerMenu(eventId: string, body: string, x: number, y: number): void {
1553
    const roomId = $selectedRoomId;
1554
    if (!roomId) return;
1555
    menu = null;
1556
    cloneSource = { kind: 'sticker', room_id: roomId, event_id: eventId, body };
1557
  }
1558
1559
  async function openMessageMenu(event: TimelineEvent, x: number, y: number): Promise<void> {
1560
    const roomId = $selectedRoomId;
1561
    const eventId = event.event_id;
1562
    if (!roomId || !eventId) return;
1563
    if (!(roomId in levelsByRoom)) await loadLevels(roomId);
1564
    const joined = selectedRoom?.membership === 'Joined';
1565
    const content = event.content;
1566
    const items: MenuItem[] = [];
1567
    if (joined) {
1568
      items.push({
1569
        label: 'Reply',
1570
        action: () =>
1571
          startReply({
1572
            event_id: eventId,
1573
            details: { kind: 'Ready', sender: event.sender, content, timestamp_ms: event.timestamp_ms }
1574
          })
1575
      });
1576
    }
1577
    if (joined && event.own && event.editable && content.kind === 'Message' && content.message.kind === 'Text') {
1578
      const body = content.message.body;
1579
      items.push({ label: 'Edit', action: () => startEdit(eventId, body) });
1580
    }
1581
    if (content.kind === 'Message' && content.message.body) {
1582
      const body = content.message.body;
1583
      items.push({ label: 'Copy text', action: () => copyText(body) });
1584
    }
1585
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${roomId}/${eventId}`) });
1586
    if (joined && selectedRoom?.can_pin && content.kind !== 'Redacted') {
1587
      const pinned = selectedRoom.pinned_events.includes(eventId);
1588
      items.push({ label: pinned ? 'Unpin' : 'Pin', action: () => setPinned(eventId, !pinned) });
1589
    }
1590
    if (content.kind === 'Sticker') {
1591
      const body = content.body;
1592
      items.push({ label: 'Clone sticker…', action: () => openCloneStickerMenu(eventId, body, x, y) });
1593
    }
1594
    const me = $sessionUser;
1595
    if (joined && me && roomLevels && canRedact(roomLevels, me, event.sender.user_id) && content.kind !== 'Redacted') {
1596
      items.push({
1597
        label: 'Delete message…',
1598
        danger: true,
1599
        action: () =>
1600
          (menu = {
1601
            x,
1602
            y,
1603
            items: [
1604
              { label: 'Delete', danger: true, action: () => void runClone({ op: 'redact', room_id: roomId, event_id: eventId, reason: null }, 'Could not delete the message') },
1605
              { label: 'Cancel', action: () => undefined }
1606
            ]
1607
          })
1608
      });
1609
    }
1610
    if (!event.own) {
1611
      const person = userMenuItems(event.sender.user_id, x, y);
1612
      if (person[0]) person[0] = { ...person[0], divider: true };
1613
      items.push(...person);
1614
    }
1615
    menu = { items, x, y };
1616
  }
1617
1618
  function openAccountMenu(ev: MouseEvent): void {
1619
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1620
    menu = {
1621
      x: rect.left,
1622
      y: rect.top - 6,
1623
      above: true,
1624
      items: [
1625
        { label: 'Security', action: () => (dialog = 'security') },
1626
        { label: 'Settings', action: () => (dialog = 'settings') },
1627
        { label: 'Sticker and emoji packs', action: () => (dialog = 'packs') },
1628
        { label: 'Log out', danger: true, divider: true, action: () => void doLogout() }
1629
      ]
1630
    };
1631
  }
1632
1633
  let resizing = false;
1634
1635
  function startResize(ev: PointerEvent, pane: 'side' | 'members' | 'thread'): void {
1636
    if (ev.button !== 0) return;
1637
    ev.preventDefault();
1638
    const handle = ev.currentTarget as HTMLElement;
1639
    handle.setPointerCapture(ev.pointerId);
1640
    const store = pane === 'side' ? sideWidth : pane === 'thread' ? threadWidth : membersWidth;
1641
    const range = pane === 'side' ? SIDE_WIDTH : pane === 'thread' ? THREAD_WIDTH : MEMBERS_WIDTH;
1642
    const startX = ev.clientX;
1643
    const startWidth = pane === 'side' ? $sideWidth : pane === 'thread' ? $threadWidth : $membersWidth;
1644
    resizing = true;
1645
    const move = (e: PointerEvent) => {
1646
      const delta = pane === 'side' ? e.clientX - startX : startX - e.clientX;
1647
      store.set(Math.round(Math.min(range.max, Math.max(range.min, startWidth + delta))));
1648
    };
1649
    const end = () => {
1650
      resizing = false;
1651
      handle.removeEventListener('pointermove', move);
1652
      handle.removeEventListener('pointerup', end);
1653
      handle.removeEventListener('pointercancel', end);
1654
    };
1655
    handle.addEventListener('pointermove', move);
1656
    handle.addEventListener('pointerup', end);
1657
    handle.addEventListener('pointercancel', end);
1658
  }
1659
1660
  function resetWidth(pane: 'side' | 'members' | 'thread'): void {
1661
    if (pane === 'side') sideWidth.set(SIDE_WIDTH.default);
1662
    else if (pane === 'thread') threadWidth.set(THREAD_WIDTH.default);
1663
    else membersWidth.set(MEMBERS_WIDTH.default);
1664
  }
1665
1666
  function stopPeeking(): void {
1667
    peeking = null;
1668
    queueReadReceipt();
1669
  }
1670
1671
  async function togglePin(room: RoomSummary): Promise<void> {
1672
    try {
1673
      await runCommand({ op: 'set_favourite', room_id: room.room_id, favourite: !room.favourite });
1674
    } catch (e) {
1675
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin');
1676
    }
1677
  }
1678
1679
  function startRailDrag(ev: DragEvent, id: string): void {
1680
    dragSpaceId = id;
1681
    if (ev.dataTransfer) {
1682
      ev.dataTransfer.effectAllowed = 'move';
1683
      ev.dataTransfer.setData('text/plain', id);
1684
    }
1685
  }
1686
1687
  function overRailSpace(ev: DragEvent, space: RoomSummary): void {
1688
    const dragged = orderedRail.find((s) => s.room_id === dragSpaceId);
1689
    if (!dragged || dragged.room_id === space.room_id || dragged.favourite !== space.favourite) return;
1690
    ev.preventDefault();
1691
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1692
    dropTarget = { id: space.room_id, after: ev.clientY > rect.top + rect.height / 2 };
1693
  }
1694
1695
  async function dropRailSpace(): Promise<void> {
1696
    const moved = dragSpaceId;
1697
    const target = dropTarget;
1698
    dragSpaceId = null;
1699
    dropTarget = null;
1700
    if (!moved || !target) return;
1701
    const ids = orderedRail.map((s) => s.room_id);
1702
    const before = target.after ? (ids[ids.indexOf(target.id) + 1] ?? null) : target.id;
1703
    const order = moveBefore(ids, moved, before === moved ? null : before);
1704
    if (order.join() === ids.join()) return;
1705
    railOverride = order;
1706
    try {
1707
      await runCommand({ op: 'reorder_spaces', order });
1708
    } catch (e) {
1709
      railOverride = null;
1710
      pushBanner(e instanceof Error ? e.message : 'Could not reorder spaces');
1711
    }
1712
  }
1713
1714
  let roomMenuOpen = false;
1715
  let roomMenuEl: HTMLDivElement | null = null;
1716
1717
  function roomMenuAction(action: () => void): void {
1718
    roomMenuOpen = false;
1719
    action();
1720
  }
1721
1722
  function closeRoomMenuOutside(ev: PointerEvent): void {
1723
    if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false;
1724
  }
1725
1726
  function onKeydown(ev: KeyboardEvent): void {
1727
    if (ev.key === 'Escape') {
1728
      if (roomMenuOpen) roomMenuOpen = false;
1729
      else if (dialog) dialog = null;
1730
      else if (membersShown && window.innerWidth < 1100) membersOpen = false;
1731
      else if (threadShown && window.innerWidth < 1100) void showThread(null);
1732
      else if (sidebarOpen) sidebarOpen = false;
1733
    }
1734
  }
1735
</script>
1736
1737
<svelte:window
1738
  bind:innerWidth={viewportWidth}
1739
  on:keydown={onKeydown}
1740
  on:pointerdown={closeRoomMenuOutside}
1741
/>
1742
1743
{#if !booted}
1744
  <div class="splash" role="status" aria-label="Loading Malice" out:fade={{ duration: motionDuration(260) }}>
1745
    <div class="splash-mark" aria-hidden="true">M</div>
1746
    <p>Loading Malice…</p>
1747
  </div>
1748
{:else if $blocked}
1749
  <div class="splash" role="status" aria-label="Malice is open in another tab" in:fade={{ duration: motionDuration(220) }}>
1750
    <div class="splash-mark" aria-hidden="true">M</div>
1751
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
1752
  </div>
1753
{:else if $sessionUser == null}
1754
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
1755
{:else}
1756
  <div
1757
    class="app"
1758
    in:fade={{ duration: motionDuration(220) }}
1759
    class:nav-folded={$navFolded}
1760
    class:rail-folded={$railFolded && (selectedRoom || mentionsOpen || searchOpen)}
1761
    class:members-open={membersShown}
1762
    class:thread-open={threadShown}
1763
    class:resizing
1764
    style:--side-open={`${$sideWidth}px`}
1765
    style:--members-open={`${$membersWidth}px`}
1766
    style:--thread-open={`${$threadWidth}px`}
1767
    style:--msg-gap={`${$messageSpacing}px`}
1768
    style:--msg-line-height={$lineHeight}
1769
  >
1770
    <header class="chat-head">
1771
      <button
1772
        type="button"
1773
        class="icon-btn only-mobile"
1774
        aria-label="Open room list"
1775
        on:click={() => (sidebarOpen = true)}
1776
      >
1777
        <span aria-hidden="true">☰</span>
1778
      </button>
1779
      <button
1780
        type="button"
1781
        class="icon-btn only-desktop pane-toggle"
1782
        aria-pressed={!$railFolded}
1783
        aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1784
        title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1785
        on:click={() => railFolded.update((v) => !v)}
1786
      >
1787
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1788
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1789
          <circle cx="7" cy="9" r="1.4" fill="currentColor" />
1790
          <circle cx="7" cy="13" r="1.4" fill="currentColor" />
1791
          <circle cx="7" cy="17" r="1.4" fill="currentColor" />
1792
        </svg>
1793
      </button>
1794
      <button
1795
        type="button"
1796
        class="icon-btn only-desktop pane-toggle"
1797
        aria-pressed={!$navFolded}
1798
        aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
1799
        title={$navFolded ? 'Show channels' : 'Hide channels'}
1800
        on:click={toggleChannelsPane}
1801
      >
1802
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1803
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1804
          <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
1805
        </svg>
1806
      </button>
1807
      {#if selectedRoom}
1808
      <div class="head-title">
1809
        <div class="head-room">
1810
          <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape="rounded" />
1811
          <div class="head-room-text">
1812
            <h1><EmojiText text={selectedRoom.name} /></h1>
1813
            <div class="head-meta">
1814
              {#if selectedRoom.space}
1815
                <span class="pill">space</span>
1816
              {/if}
1817
              {#if selectedRoom.encrypted}
1818
                <span class="pill" title="End-to-end encrypted"><EmojiText text="🔒 encrypted" /></span>
1819
              {/if}
1820
              {#if selectedRoom.direct}
1821
                <span class="pill">direct</span>
1822
              {/if}
1823
              {#if $connection !== 'online'}
1824
                <span class="conn" title={`Sync state: ${$connection}`}>
1825
                  <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1826
                  {$connection}
1827
                </span>
1828
              {/if}
1829
              {#if selectedRoom.topic}
1830
                <span class="head-topic" title={selectedRoom.topic}><EmojiText text={selectedRoom.topic} /></span>
1831
              {/if}
1832
            </div>
1833
          </div>
1834
        </div>
1835
      </div>
1836
      {:else}
1837
      <div class="head-title">
1838
        <div class="head-room">
1839
          {#if selectedSpace}
1840
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={36} shape="rounded" />
1841
          {/if}
1842
          <div class="head-room-text">
1843
            <h1><EmojiText text={mentionsOpen ? 'Mentions' : searchOpen ? 'Search' : selectedSpace?.name ?? 'Home'} /></h1>
1844
          </div>
1845
        </div>
1846
      </div>
1847
      {/if}
1848
      <div class="head-actions">
1849
        {#if selectedRoom}
1850
        {#if peeking === selectedRoom.room_id}
1851
          <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}>
1852
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1853
              <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" />
1854
              <circle cx="12" cy="12" r="3" fill="currentColor" />
1855
            </svg>
1856
          </button>
1857
        {/if}
1858
        {#if selectedRoom.membership !== 'Joined'}
1859
          <button
1860
            type="button"
1861
            class="primary-btn"
1862
            disabled={joinBusy}
1863
            on:click={() => void join(selectedRoom.room_id)}
1864
          >
1865
            {joinBusy ? 'Joining…' : 'Join'}
1866
          </button>
1867
        {/if}
1868
        <button type="button" class="icon-btn" aria-label="Search messages" title="Search messages" on:click={selectSearch}>
1869
          <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>
1870
        </button>
1871
        <button
1872
          type="button"
1873
          class="icon-btn"
1874
          aria-pressed={membersShown}
1875
          aria-label={membersShown ? 'Hide members' : 'Show members'}
1876
          title="Members"
1877
          on:click={toggleMembers}
1878
        >
1879
          <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1880
            <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
1881
            <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
1882
          </svg>
1883
        </button>
1884
        <div class="room-menu-wrap" bind:this={roomMenuEl}>
1885
          <button
1886
            type="button"
1887
            class="icon-btn"
1888
            aria-haspopup="menu"
1889
            aria-expanded={roomMenuOpen}
1890
            aria-label="Room options"
1891
            title="Room options"
1892
            on:click={() => (roomMenuOpen = !roomMenuOpen)}
1893
          >
1894
            <span aria-hidden="true">⋯</span>
1895
          </button>
1896
          {#if roomMenuOpen}
1897
            <div class="room-menu" role="menu">
1898
              {#if selectedRoom.membership === 'Joined'}
1899
                <button
1900
                  type="button"
1901
                  role="menuitem"
1902
                  class="danger"
1903
                  disabled={leaveBusy}
1904
                  on:click={() => roomMenuAction(() => void leave())}
1905
                >
1906
                  {leaveBusy ? 'Leaving…' : 'Leave room'}
1907
                </button>
1908
              {/if}
1909
            </div>
1910
          {/if}
1911
        </div>
1912
        {/if}
1913
      </div>
1914
    </header>
1915
1916
    <nav class="rail" aria-label="Servers and spaces">
1917
      <button
1918
        type="button"
1919
        class="rail-btn"
1920
        class:active={selectedSpaceId === null}
1921
        class:unread={homeUnread}
1922
        title="Home — all channels"
1923
        aria-label="Home — all channels"
1924
        aria-pressed={selectedSpaceId === null}
1925
        on:click={() => void selectHome()}
1926
      >
1927
        <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>
1928
      </button>
1929
      {#each [pinnedRail, otherRail] as group}
1930
        {#if group.length > 0}
1931
          <div class="rail-sep" aria-hidden="true"></div>
1932
        {/if}
1933
        {#each group as space (space.room_id)}
1934
          <button
1935
            type="button"
1936
            class="rail-btn rail-space"
1937
            class:active={railSelected === space.room_id}
1938
            class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after}
1939
            class:drop-after={dropTarget?.id === space.room_id && dropTarget.after}
1940
            class:pinned={space.favourite}
1941
            class:unread={unreadSpaces.has(space.room_id)}
1942
            title={space.name}
1943
            aria-label={`Show channels in space ${space.name}`}
1944
            aria-pressed={selectedSpaceId === space.room_id}
1945
            draggable="true"
1946
            on:click={() => void selectSpace(space.room_id)}
1947
            on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)}
1948
            on:dragstart={(ev) => startRailDrag(ev, space.room_id)}
1949
            on:dragover={(ev) => overRailSpace(ev, space)}
1950
            on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)}
1951
            on:drop|preventDefault={() => void dropRailSpace()}
1952
            on:dragend={() => ((dragSpaceId = null), (dropTarget = null))}
1953
          >
1954
            <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
1955
          </button>
1956
        {/each}
1957
      {/each}
1958
      <button
1959
        type="button"
1960
        class="rail-btn rail-add"
1961
        aria-label="Join or create a room"
1962
        on:click={() => {
1963
          dialog = 'join';
1964
        }}
1965
      >
1966
        <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>
1967
      </button>
1968
    </nav>
1969
1970
    {#if menu}
1971
      <ContextMenu items={menu.items} x={menu.x} y={menu.y} above={menu.above ?? false} onClose={() => (menu = null)} />
1972
    {/if}
1973
    {#if userCard}
1974
      {#key userCard}
1975
        {@const cardUser = userCard.userId}
1976
        <UserCard
1977
          person={personFor(cardUser)}
1978
          member={memberFor(cardUser)}
1979
          levels={roomLevels}
1980
          self={$sessionUser ?? null}
1981
          x={userCard.x}
1982
          y={userCard.y}
1983
          confirm={userCard.confirm}
1984
          onAction={(action) => void userAction(cardUser, action)}
1985
          onClose={() => (userCard = null)}
1986
        />
1987
      {/key}
1988
    {/if}
1989
1990
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
1991
      <!-- svelte-ignore a11y_no_static_element_interactions -->
1992
      <div class="pane-resize right" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'side')} on:dblclick={() => resetWidth('side')}></div>
1993
      <div class="side-search">
1994
        <label class="visually-hidden" for="room-search">Search rooms</label>
1995
        <input
1996
          id="room-search"
1997
          type="search"
1998
          placeholder="Search rooms"
1999
          bind:value={search}
2000
          autocomplete="off"
2001
        />
2002
        <button
2003
          type="button"
2004
          class="icon-btn"
2005
          title="Refresh rooms"
2006
          aria-label="Refresh rooms"
2007
          disabled={roomsLoading}
2008
          on:click={() => void refreshRooms()}
2009
        >
2010
          <span aria-hidden="true">⟳</span>
2011
        </button>
2012
      </div>
2013
      {#key selectedSpaceId ?? 'home'}
2014
      <div class="side-scroll" in:fly={{ y: 5, duration: motionDuration(180) }} out:fade={{ duration: motionDuration(120) }}>
2015
        {#if selectedSpace && spaceParents.has(selectedSpace.room_id)}
2016
          {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
2017
          <button type="button" class="room-row up-row" on:click={() => void selectSpace(parentId)}>
2018
            <span aria-hidden="true">↑</span>
2019
            <span class="room-name"><EmojiText text={$rooms.find((r) => r.room_id === parentId)?.name ?? 'Parent space'} /></span>
2020
          </button>
2021
        {/if}
2022
        {#if !selectedSpaceId}
2023
          <ul class="room-list">
2024
            <li>
2025
              <button type="button" class="room-row" class:active={mentionsOpen} on:click={selectMentions}>
2026
                <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>
2027
                <span class="room-name">Mentions</span>
2028
                {#if $mentionsSnapshot && $mentionsSnapshot.unread_count > 0}
2029
                  <span class="badge mention" aria-label={`${$mentionsSnapshot.unread_count} unread mentions`}>{$mentionsSnapshot.unread_count > 99 ? '99+' : $mentionsSnapshot.unread_count}</span>
2030
                {/if}
2031
              </button>
2032
            </li>
2033
          </ul>
2034
        {/if}
2035
        <ul class="room-list">
2036
          <li>
2037
            <button type="button" class="room-row" class:active={searchOpen} on:click={selectSearch}>
2038
              <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>
2039
              <span class="room-name">Search messages</span>
2040
            </button>
2041
          </li>
2042
        </ul>
2043
        {#if roomsLoading && $rooms.length === 0}
2044
          <p class="side-note">Loading rooms…</p>
2045
        {:else if $rooms.length === 0}
2046
          <p class="side-note">No rooms yet</p>
2047
          <div class="side-cta">
2048
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
2049
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
2050
          </div>
2051
        {:else}
2052
          {#if selectedSpaceId && spaceChildrenLoading}
2053
            <p class="side-note">Loading channels…</p>
2054
          {:else if selectedSpaceId && spaceChildrenError}
2055
            <p class="side-note" role="alert"><EmojiText text={spaceChildrenError} /></p>
2056
            <div class="side-cta">
2057
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
2058
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
2059
            </div>
2060
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
2061
            <p class="side-note">No channels</p>
2062
            <div class="side-cta">
2063
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
2064
            </div>
2065
          {:else}
2066
            {#if invites.length > 0 && !selectedSpaceId}
2067
              <h2 class="side-h">Invites</h2>
2068
              <ul class="room-list">
2069
                {#each invites as room (room.room_id)}
2070
                  <li>
2071
                    <button
2072
                      type="button"
2073
                      class="room-row"
2074
                      class:active={$selectedRoomId === room.room_id}
2075
                      on:click={() => void selectRoom(room.room_id)}
2076
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2077
                    >
2078
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2079
                      <span class="room-name"><EmojiText text={room.name} /></span>
2080
                      <span
2081
                        class="invite-join"
2082
                        role="button"
2083
                        tabindex="0"
2084
                        aria-label={`Join ${room.name}`}
2085
                        on:click|stopPropagation={() => void join(room.room_id)}
2086
                        on:keydown|stopPropagation={(ev) => {
2087
                          if (ev.key === 'Enter' || ev.key === ' ') {
2088
                            ev.preventDefault();
2089
                            void join(room.room_id);
2090
                          }
2091
                        }}
2092
                      >
2093
                        Join
2094
                      </span>
2095
                    </button>
2096
                  </li>
2097
                {/each}
2098
              </ul>
2099
            {/if}
2100
2101
            {#if directRooms.length > 0}
2102
              <h2 class="side-h">Direct messages</h2>
2103
              <ul class="room-list">
2104
                {#each directRooms as room (room.room_id)}
2105
                  <li class="room-item">
2106
                    <button
2107
                      type="button"
2108
                      class="room-row"
2109
                      class:active={$selectedRoomId === room.room_id}
2110
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2111
                      on:click={() => void selectRoom(room.room_id)}
2112
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2113
                    >
2114
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
2115
                      <span class="room-name"><EmojiText text={room.name} /></span>
2116
                      {#if roomUnread(room) > 0}
2117
                        <span
2118
                          class="badge"
2119
                          class:mention={room.unread_mentions > 0}
2120
                          aria-label={`${roomUnread(room)} unread`}
2121
                        >
2122
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2123
                        </span>
2124
                      {/if}
2125
                    </button>
2126
                    {#if ($threadsByRoom[room.room_id] ?? []).length}
2127
                      <button
2128
                        type="button"
2129
                        class="fold-btn"
2130
                        class:open={threadFoldOpen(room.room_id, threadFolds, query)}
2131
                        aria-expanded={threadFoldOpen(room.room_id, threadFolds, query)}
2132
                        aria-label={`Threads in ${room.name}`}
2133
                        title="Threads"
2134
                        on:click={() => (threadFolds = { ...threadFolds, [room.room_id]: !threadFolds[room.room_id] })}
2135
                      >
2136
                        <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>
2137
                      </button>
2138
                    {/if}
2139
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2140
                  </li>
2141
                  {#if threadFoldOpen(room.room_id, threadFolds, query)}
2142
                    <li>
2143
                      <RoomThreads
2144
                        roomId={room.room_id}
2145
                        threads={$threadsByRoom[room.room_id] ?? []}
2146
                        history={$threadLists[room.room_id]?.history ?? null}
2147
                        onOlder={() => void loadOlderThreads(room.room_id)}
2148
                        {query}
2149
                        activeRoot={threadView?.room_id === room.room_id ? threadView.root_event_id : null}
2150
                        onOpen={(root) => void openThreadIn(room.room_id, root)}
2151
                      />
2152
                    </li>
2153
                  {/if}
2154
                {/each}
2155
              </ul>
2156
            {/if}
2157
2158
            {#if groupRooms.length > 0}
2159
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
2160
              <ul class="room-list">
2161
                {#each groupRooms as room (room.room_id)}
2162
                  <li class="room-item">
2163
                    <button
2164
                      type="button"
2165
                      class="room-row"
2166
                      class:active={$selectedRoomId === room.room_id}
2167
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2168
                      on:click={() => void selectRoom(room.room_id)}
2169
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2170
                    >
2171
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2172
                      <span class="room-name"><EmojiText text={room.name} /></span>
2173
                      {#if roomUnread(room) > 0}
2174
                        <span
2175
                          class="badge"
2176
                          class:mention={room.unread_mentions > 0}
2177
                          aria-label={`${roomUnread(room)} unread`}
2178
                        >
2179
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2180
                        </span>
2181
                      {/if}
2182
                    </button>
2183
                    {#if ($threadsByRoom[room.room_id] ?? []).length}
2184
                      <button
2185
                        type="button"
2186
                        class="fold-btn"
2187
                        class:open={threadFoldOpen(room.room_id, threadFolds, query)}
2188
                        aria-expanded={threadFoldOpen(room.room_id, threadFolds, query)}
2189
                        aria-label={`Threads in ${room.name}`}
2190
                        title="Threads"
2191
                        on:click={() => (threadFolds = { ...threadFolds, [room.room_id]: !threadFolds[room.room_id] })}
2192
                      >
2193
                        <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>
2194
                      </button>
2195
                    {/if}
2196
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2197
                  </li>
2198
                  {#if threadFoldOpen(room.room_id, threadFolds, query)}
2199
                    <li>
2200
                      <RoomThreads
2201
                        roomId={room.room_id}
2202
                        threads={$threadsByRoom[room.room_id] ?? []}
2203
                        history={$threadLists[room.room_id]?.history ?? null}
2204
                        onOlder={() => void loadOlderThreads(room.room_id)}
2205
                        {query}
2206
                        activeRoot={threadView?.room_id === room.room_id ? threadView.root_event_id : null}
2207
                        onOpen={(root) => void openThreadIn(room.room_id, root)}
2208
                      />
2209
                    </li>
2210
                  {/if}
2211
                {/each}
2212
              </ul>
2213
            {/if}
2214
2215
            {#if spaceList.length > 0}
2216
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
2217
              <ul class="room-list">
2218
                {#each spaceList as room (room.room_id)}
2219
                  <li class="room-item">
2220
                    <button
2221
                      type="button"
2222
                      class="room-row"
2223
                      class:active={selectedSpaceId === room.room_id}
2224
                      aria-label={`Show channels in space ${room.name}`}
2225
                      on:click={() => void selectSpace(room.room_id)}
2226
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2227
                    >
2228
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2229
                      <span class="room-name"><EmojiText text={room.name} /></span>
2230
                    </button>
2231
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2232
                  </li>
2233
                {/each}
2234
              </ul>
2235
            {/if}
2236
2237
            {#if query && visibleRooms.length === 0}
2238
              <p class="side-note">No rooms match “<EmojiText text={search.trim()} />”.</p>
2239
            {/if}
2240
          {/if}
2241
        {/if}
2242
      </div>
2243
      {/key}
2244
2245
    </aside>
2246
    <div class="account">
2247
      <button type="button" class="me-btn" title={$sessionUser} aria-haspopup="menu" on:click={openAccountMenu}>
2248
        {#if profileMxc}
2249
          <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={32} />
2250
        {:else}
2251
          <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
2252
        {/if}
2253
        <span class="me-names">
2254
          <span class="me-name"><EmojiText text={profile?.display_name || $sessionUser} /></span>
2255
          {#if profile?.display_name && profile.display_name !== $sessionUser}<span class="me-id">{$sessionUser}</span>{/if}
2256
        </span>
2257
      </button>
2258
      <div class="account-actions">
2259
        <button type="button" class="icon-btn" title="Encryption and verification" aria-label="Encryption and verification" on:click={() => (dialog = 'security')}>
2260
          <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>
2261
        </button>
2262
        <button type="button" class="icon-btn" title="Settings" aria-label="Settings" on:click={() => (dialog = 'settings')}>
2263
          <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>
2264
        </button>
2265
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
2266
          <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>
2267
        </button>
2268
      </div>
2269
    </div>
2270
    {#if sidebarOpen}
2271
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
2272
    {/if}
2273
2274
    <main class="chat">
2275
        {#if $banners.length > 0}
2276
          <div class="banners" aria-live="polite">
2277
            {#each $banners as banner (banner.id)}
2278
              <div class="banner" role="alert">
2279
                <span><EmojiText text={banner.message} /></span>
2280
                <button
2281
                  type="button"
2282
                  aria-label="Dismiss error"
2283
                  on:click={() => dismissBanner(banner.id)}
2284
                >
2285
                  ✕
2286
                </button>
2287
              </div>
2288
            {/each}
2289
          </div>
2290
        {/if}
2291
      {#key mentionsOpen ? 'mentions' : searchOpen ? 'search' : $selectedRoomId ?? 'home'}
2292
      <div class="chat-view">
2293
      {#if mentionsOpen && $sessionUser}
2294
        <MentionsInbox self={$sessionUser} onLive={(roomId, eventId, threadRoot) => void openLive(roomId, eventId, threadRoot)} />
2295
      {:else if searchOpen}
2296
        <SearchView scopes={searchScopes} self={$sessionUser ?? null} {roomName} onOpen={(roomId, eventId, threadRoot) => void openLive(roomId, eventId, threadRoot)} />
2297
      {:else if !selectedRoom}
2298
        <div class="empty" in:fade={{ duration: motionDuration(180) }}>
2299
          <div class="empty-mark" aria-hidden="true">◈</div>
2300
          {#if selectedSpace}
2301
            <h1><EmojiText text={selectedSpace.name} /></h1>
2302
          {:else}
2303
            <h1>Welcome to Malice</h1>
2304
          {/if}
2305
          <div class="empty-cta">
2306
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
2307
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
2308
          </div>
2309
          <p class="conn-line">
2310
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
2311
            {$connection}
2312
          </p>
2313
        </div>
2314
      {:else}
2315
        {#if pins.length}
2316
          <div class="pinned-strip" class:open={pinsExpanded}>
2317
            <div class="pinned-head">
2318
              <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>
2319
              <button type="button" class="pinned-latest" title="Jump to pinned message" on:click={() => jumpToPin(pins[0].event_id ?? '')}>
2320
                <strong><EmojiText text={people[pins[0].sender.user_id]?.name ?? senderLabel(pins[0].sender)} /></strong>
2321
                <span><EmojiText text={contentPreview(pins[0].content)} /></span>
2322
              </button>
2323
              {#if pins.length > 1}
2324
                <button type="button" class="pinned-count" aria-expanded={pinsExpanded} on:click={() => (pinsExpanded = !pinsExpanded)}>
2325
                  {pins.length} pinned
2326
                  <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>
2327
                </button>
2328
              {/if}
2329
              {#if pinsExpanded && selectedRoom.can_pin}
2330
                <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pins[0].event_id ?? '', false)}>
2331
                  <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>
2332
                </button>
2333
              {/if}
2334
            </div>
2335
            {#if pinsExpanded}
2336
              <ul class="pinned-list">
2337
                {#each pins.slice(1) as pin (pin.event_id)}
2338
                  <li>
2339
                    <button type="button" on:click={() => jumpToPin(pin.event_id ?? '')}>
2340
                      <strong><EmojiText text={people[pin.sender.user_id]?.name ?? senderLabel(pin.sender)} /></strong>
2341
                      <span><EmojiText text={contentPreview(pin.content)} /></span>
2342
                    </button>
2343
                    {#if selectedRoom.can_pin}
2344
                      <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pin.event_id ?? '', false)}>
2345
                        <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>
2346
                      </button>
2347
                    {/if}
2348
                  </li>
2349
                {/each}
2350
              </ul>
2351
            {/if}
2352
          </div>
2353
        {/if}
2354
        {#if recoveryBanner}
2355
          <div class="sec-banner warn" role="status">
2356
            <span>Message history is locked</span>
2357
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
2358
          </div>
2359
        {/if}
2360
        {#if verificationBanner}
2361
          <div class="sec-banner" role="status">
2362
            {#if verificationBanner.kind === 'Incoming'}
2363
              <span>A device wants to verify this session</span>
2364
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
2365
            {:else if verificationBanner.kind === 'Comparison'}
2366
              <span>Verification codes ready</span>
2367
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
2368
            {:else if verificationBanner.kind === 'Waiting'}
2369
              <span>Verification started</span>
2370
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
2371
            {:else if verificationBanner.kind === 'Failed'}
2372
              <span>Verification failed: <EmojiText text={verificationBanner.message} /></span>
2373
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
2374
            {:else if verificationBanner.kind === 'Cancelled'}
2375
              <span>Verification cancelled: <EmojiText text={verificationBanner.reason} /></span>
2376
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2377
            {:else}
2378
              <span>Verification in progress</span>
2379
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2380
            {/if}
2381
          </div>
2382
        {/if}
2383
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
2384
          <p class="conn-banner error" role="alert"><EmojiText text={openFailed[$selectedRoomId]} /></p>
2385
        {/if}
2386
2387
        {#if pinPreview}
2388
          <div class="pin-preview" role="dialog" aria-label="Pinned message preview">
2389
            <div class="pin-preview-head">
2390
              <strong><EmojiText text={people[pinPreview.sender.user_id]?.name ?? senderLabel(pinPreview.sender)} /></strong>
2391
              <button type="button" class="icon-btn" aria-label="Close pinned message preview" on:click={() => (pinPreview = null)}>✕</button>
2392
            </div>
2393
            <p><EmojiText text={contentPreview(pinPreview.content)} /></p>
2394
            <button type="button" class="primary-btn" disabled={pinJumpBusy} on:click={() => void jumpToPin(pinPreview?.event_id ?? '')}>
2395
              {pinJumpBusy ? 'Loading message…' : 'Jump to message'}
2396
            </button>
2397
          </div>
2398
        {/if}
2399
2400
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2401
        <div
2402
          class="timeline"
2403
          in:fly={{ y: 6, duration: motionDuration(180) }}
2404
          out:fade={{ duration: motionDuration(120) }}
2405
          bind:this={timelineEl}
2406
          on:scroll={onTimelineScroll}
2407
          on:wheel={noteUserScroll}
2408
          on:touchmove={noteUserScroll}
2409
          on:keydown={onTimelineKey}
2410
          on:pointerdown={noteUserScroll}
2411
          aria-label={`Messages in ${selectedRoom.name}`}
2412
        >
2413
          <div class="timeline-inner" use:pinTimeline>
2414
            <RoomTimelineRows
2415
              {items}
2416
              pending={pendingItems}
2417
              joined={selectedRoom.membership === 'Joined'}
2418
              self={$sessionUser ?? null}
2419
              selfName={profile?.display_name ?? null}
2420
              {people}
2421
              {senderAvatarFor}
2422
              {reacting}
2423
              quickReactions={usableQuickReactions}
2424
              packs={roomPacks}
2425
              linkPreviews={$linkPreviews}
2426
              {loadPreview}
2427
              editingEventId={editing?.eventId ?? null}
2428
              {recentState}
2429
              recentRetrying={!!recentRetrying[selectedRoom.room_id]}
2430
              paginating={paginateBusy}
2431
              fillingGap={fillingGaps[selectedRoom.room_id] ?? null}
2432
              onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2433
              onQuickChange={(list) => void changeQuickReactions(list)}
2434
              onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2435
              onCloneSticker={openCloneStickerMenu}
2436
              onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2437
              onOpenThread={openThreadHere}
2438
              onReply={startReply}
2439
              onJump={jumpTo}
2440
              onEdit={startEdit}
2441
              onPaginate={() => void paginate()}
2442
              onFillGap={(gapId) => void fillGap(gapId)}
2443
              onRetryRecent={() => void retryRecentHistory(selectedRoom.room_id)}
2444
              onRetryPending={retryPending}
2445
              onDiscardPending={discardPending}
2446
            />
2447
          </div>
2448
        </div>
2449
2450
        {#if selectedRoom.membership === 'Joined'}
2451
          <input
2452
            type="file"
2453
            accept="image/*"
2454
            bind:this={avatarInput}
2455
            class="visually-hidden"
2456
            aria-label="Choose a new avatar"
2457
            on:change={() => void onAvatarChosen()}
2458
          />
2459
          <Composer
2460
            bind:this={composerRef}
2461
            bind:value={composer}
2462
            inputId="composer"
2463
            label={`Message ${selectedRoom.name}`}
2464
            placeholder={`Message ${selectedRoom.name}`}
2465
            ready={!!($selectedRoomId && openReady[$selectedRoomId])}
2466
            picked={($selectedRoomId && pickedMentions[$selectedRoomId]) || []}
2467
            onPick={(mention) => $selectedRoomId && (pickedMentions = { ...pickedMentions, [$selectedRoomId]: [...(pickedMentions[$selectedRoomId] ?? []), mention] })}
2468
            staged={currentStaged}
2469
            onStage={stageFiles}
2470
            onUnstage={(id) => $selectedRoomId && unstage($selectedRoomId, id)}
2471
            {uploadBusy}
2472
            {uploadName}
2473
            editing={editing ? { original: editing.original } : null}
2474
            onCancelEdit={cancelEdit}
2475
            {replyingTo}
2476
            onCancelReply={() => (replyingTo = null)}
2477
            {people}
2478
            self={$sessionUser ?? null}
2479
            emotes={roomEmotes}
2480
            packs={roomPacks}
2481
            stickers={$selectedRoomId ? roomStickers($selectedRoomId) : null}
2482
            commands
2483
            onSubmit={send}
2484
            onEditLast={editLastOwn}
2485
            onMentionStart={() => $selectedRoomId && !$membersByRoom[$selectedRoomId] && void loadMembers($selectedRoomId)}
2486
          />
2487
        {:else}
2488
          <div class="join-bar">
2489
            <p>You are not a member of this room.</p>
2490
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
2491
              <EmojiText text={joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`} />
2492
            </button>
2493
          </div>
2494
        {/if}
2495
      {/if}
2496
      </div>
2497
      {/key}
2498
    </main>
2499
2500
    {#if selectedRoom}
2501
      <aside class="thread" aria-hidden={!threadShown} aria-label={`Thread in ${selectedRoom.name}`}>
2502
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2503
        <div class="pane-resize left" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'thread')} on:dblclick={() => resetWidth('thread')}></div>
2504
        {#if threadView}
2505
          <ThreadPane
2506
            roomId={threadView.room_id}
2507
            rootEventId={threadView.root_event_id}
2508
            roomName={selectedRoom.name}
2509
            joined={selectedRoom.membership === 'Joined'}
2510
            self={$sessionUser ?? null}
2511
            {people}
2512
            {senderAvatarFor}
2513
            quickReactions={usableQuickReactions}
2514
            packs={roomPacks}
2515
            linkPreviews={$linkPreviews}
2516
            {loadPreview}
2517
            onQuickChange={(list) => void changeQuickReactions(list)}
2518
            onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2519
            onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2520
            onMentionStart={() => !$membersByRoom[threadView.room_id] && void loadMembers(threadView.room_id)}
2521
            focusEventId={threadView.focus_event_id ?? null}
2522
            stickers={roomStickers(threadView.room_id, threadView.root_event_id)}
2523
            onClose={() => void showThread(null)}
2524
          />
2525
        {/if}
2526
      </aside>
2527
      <aside class="members" aria-hidden={!membersShown} aria-label={`Members of ${selectedRoom.name}`}>
2528
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2529
        <div class="pane-resize left" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'members')} on:dblclick={() => resetWidth('members')}></div>
2530
        <div class="members-head">
2531
          <h2>Members</h2>
2532
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
2533
            <span aria-hidden="true">✕</span>
2534
          </button>
2535
        </div>
2536
        {#if $membersLoading && members.length === 0}
2537
          <p class="side-note">Loading members…</p>
2538
        {:else if members.length === 0}
2539
          <p class="side-note">No members loaded.</p>
2540
          {#if $selectedRoomId}
2541
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
2542
              Retry
2543
            </button>
2544
          {/if}
2545
        {:else}
2546
          <ul class="member-list">
2547
            {#each memberGroups as group (group.label)}
2548
              <li class="member-group">
2549
                <h3 class="member-group-label">{group.label}<span>{group.members.length}</span></h3>
2550
                <ul class="member-group-list">
2551
                  {#each group.members as member (member.user_id)}
2552
                    <li>
2553
                      <button
2554
                        type="button"
2555
                        class="member"
2556
                        on:click={(ev) => {
2557
                          const rect = ev.currentTarget.getBoundingClientRect();
2558
                          void openUser(member.user_id, rect.left - 308, rect.top, false);
2559
                        }}
2560
                        on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)}
2561
                      >
2562
                        <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} seed={member.user_id} size={28} />
2563
                        <span class="member-names">
2564
                          <span class="member-name"><EmojiText text={member.display_name || member.name} /></span>
2565
                          <span class="member-id">{member.user_id}</span>
2566
                        </span>
2567
                      </button>
2568
                    </li>
2569
                  {/each}
2570
                </ul>
2571
              </li>
2572
            {/each}
2573
          </ul>
2574
        {/if}
2575
      </aside>
2576
    {/if}
2577
2578
    {#if cloneSource}
2579
      <div class="modal-wrap" role="presentation" on:click|self={() => (cloneSource = null)}>
2580
        <PackCloneDialog source={cloneSource} packs={$imagePacks} rooms={$rooms} onError={pushBanner} onClose={() => (cloneSource = null)} />
2581
      </div>
2582
    {/if}
2583
2584
    {#if dialog}
2585
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
2586
        {#if dialog === 'security'}
2587
          <SecurityPanel
2588
            encryptionState={$encryption}
2589
            verificationState={$verification}
2590
            onAction={() => void loadEncryption()}
2591
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
2592
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
2593
            on:close={() => (dialog = null)}
2594
          />
2595
        {:else if dialog === 'settings'}
2596
          <SettingsPanel
2597
            quick={$quickReactions}
2598
            packs={roomPacks}
2599
            onQuickChange={(list) => void changeQuickReactions(list)}
2600
            on:close={() => (dialog = null)}
2601
            on:packs={() => (dialog = 'packs')}
2602
          />
2603
        {:else if dialog === 'packs'}
2604
          <PackManager packs={$imagePacks} rooms={$rooms} onError={pushBanner} on:close={() => (dialog = null)} />
2605
        {:else}
2606
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
2607
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
2608
              <button
2609
                type="button"
2610
                role="tab"
2611
                aria-selected={dialog === 'join'}
2612
                class:active={dialog === 'join'}
2613
                on:click={() => (dialog = 'join')}
2614
              >
2615
                Join
2616
              </button>
2617
              <button
2618
                type="button"
2619
                role="tab"
2620
                aria-selected={dialog === 'create'}
2621
                class:active={dialog === 'create'}
2622
                on:click={() => (dialog = 'create')}
2623
              >
2624
                Create
2625
              </button>
2626
              <button
2627
                type="button"
2628
                class="icon-btn modal-x"
2629
                aria-label="Close dialog"
2630
                on:click={() => (dialog = null)}
2631
              >
2632
                <span aria-hidden="true">✕</span>
2633
              </button>
2634
            </div>
2635
            {#if dialog === 'join'}
2636
              <form on:submit|preventDefault={() => void join(joinTarget)}>
2637
                <label class="field">
2638
                  <span>Room ID or alias</span>
2639
                  <input
2640
                    type="text"
2641
                    placeholder="!room:example.org or #alias:example.org"
2642
                    bind:value={joinTarget}
2643
                    required
2644
                    disabled={joinBusy}
2645
                  />
2646
                </label>
2647
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
2648
                  {joinBusy ? 'Joining…' : 'Join room'}
2649
                </button>
2650
              </form>
2651
            {:else}
2652
            <form on:submit|preventDefault={() => void create()}>
2653
              <label class="field">
2654
                <span>Room name</span>
2655
                <input
2656
                  type="text"
2657
                  placeholder="Weekend plans"
2658
                  bind:value={createName}
2659
                  required
2660
                  disabled={createBusy}
2661
                />
2662
              </label>
2663
              <label class="field">
2664
                <span>Topic (optional)</span>
2665
                <input
2666
                  type="text"
2667
                  placeholder="What should this room be about?"
2668
                  bind:value={createTopic}
2669
                  disabled={createBusy}
2670
                />
2671
              </label>
2672
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
2673
                {createBusy ? 'Creating…' : 'Create room'}
2674
              </button>
2675
            </form>
2676
            {/if}
2677
          </div>
2678
        {/if}
2679
      </div>
2680
    {/if}
2681
  </div>
2682
{/if}
2683
2684
<ImageLightbox />