atagen

malice

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