atagen

malice

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