atagen

malice

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