atagen

malice

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