atagen

malice

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