atagen

malice

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