atagen

malice

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