atagen

malice

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