atagen

malice

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