atagen

malice

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