atagen

malice

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