atagen

malice

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