atagen

malice

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