atagen

malice

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