atagen

malice

public
Star0
Watch0
77eddb6b710ffe2b884b8bdf7b0611041f7358e6
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte2415 lines91.4 KB
1
<script lang="ts">
2
  import { onMount, tick } from 'svelte';
3
  import LoginPanel from './lib/LoginPanel.svelte';
4
  import MessageRow from './lib/MessageRow.svelte';
5
  import MxcAvatar from './lib/MxcAvatar.svelte';
6
  import PinButton from './lib/PinButton.svelte';
7
  import ContextMenu, { type MenuItem } from './lib/ContextMenu.svelte';
8
  import StickerPicker from './lib/StickerPicker.svelte';
9
  import PackManager from './lib/PackManager.svelte';
10
  import { clonePackDestinations, editableChoices, shortcodeFor } from './lib/packs';
11
  import type { CommandRequest } from './lib/transport';
12
  import UserCard, { type UserAction } from './lib/UserCard.svelte';
13
  import { allowed, canRedact, 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
    <header class="chat-head">
1501
      <button
1502
        type="button"
1503
        class="icon-btn only-mobile"
1504
        aria-label="Open room list"
1505
        on:click={() => (sidebarOpen = true)}
1506
      >
1507
        <span aria-hidden="true">☰</span>
1508
      </button>
1509
      <button
1510
        type="button"
1511
        class="icon-btn only-desktop pane-toggle"
1512
        aria-pressed={!$railFolded}
1513
        aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1514
        title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1515
        on:click={() => railFolded.update((v) => !v)}
1516
      >
1517
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1518
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1519
          <circle cx="7" cy="9" r="1.4" fill="currentColor" />
1520
          <circle cx="7" cy="13" r="1.4" fill="currentColor" />
1521
          <circle cx="7" cy="17" r="1.4" fill="currentColor" />
1522
        </svg>
1523
      </button>
1524
      <button
1525
        type="button"
1526
        class="icon-btn only-desktop pane-toggle"
1527
        aria-pressed={!$navFolded}
1528
        aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
1529
        title={$navFolded ? 'Show channels' : 'Hide channels'}
1530
        on:click={() => navFolded.update((v) => !v)}
1531
      >
1532
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1533
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1534
          <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
1535
        </svg>
1536
      </button>
1537
      {#if selectedRoom}
1538
      <div class="head-title">
1539
        <div class="head-room">
1540
          <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape={selectedRoom.space ? 'rounded' : 'circle'} />
1541
          <div class="head-room-text">
1542
            <h1>{selectedRoom.name}</h1>
1543
            <div class="head-meta">
1544
              {#if selectedRoom.space}
1545
                <span class="pill">space</span>
1546
              {/if}
1547
              {#if selectedRoom.encrypted}
1548
                <span class="pill" title="End-to-end encrypted">🔒 encrypted</span>
1549
              {/if}
1550
              {#if selectedRoom.direct}
1551
                <span class="pill">direct</span>
1552
              {/if}
1553
              <span class="conn" title={`Sync state: ${$connection}`}>
1554
                <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1555
                {$connection}
1556
              </span>
1557
            </div>
1558
          </div>
1559
        </div>
1560
      </div>
1561
      {:else}
1562
      <div class="head-title">
1563
        <div class="head-room">
1564
          {#if selectedSpace}
1565
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={36} shape="rounded" />
1566
          {/if}
1567
          <div class="head-room-text">
1568
            <h1>{selectedSpace?.name ?? 'Home'}</h1>
1569
          </div>
1570
        </div>
1571
      </div>
1572
      {/if}
1573
      <div class="head-actions">
1574
        {#if selectedRoom}
1575
        {#if peeking === selectedRoom.room_id}
1576
          <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}>
1577
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1578
              <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" />
1579
              <circle cx="12" cy="12" r="3" fill="currentColor" />
1580
            </svg>
1581
          </button>
1582
        {/if}
1583
        {#if selectedRoom.membership !== 'Joined'}
1584
          <button
1585
            type="button"
1586
            class="primary-btn"
1587
            disabled={joinBusy}
1588
            on:click={() => void join(selectedRoom.room_id)}
1589
          >
1590
            {joinBusy ? 'Joining…' : 'Join'}
1591
          </button>
1592
        {/if}
1593
        <button
1594
          type="button"
1595
          class="icon-btn"
1596
          aria-pressed={membersOpen}
1597
          aria-label={membersOpen ? 'Hide members' : 'Show members'}
1598
          title="Members"
1599
          on:click={toggleMembers}
1600
        >
1601
          <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1602
            <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
1603
            <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
1604
          </svg>
1605
        </button>
1606
        <div class="room-menu-wrap" bind:this={roomMenuEl}>
1607
          <button
1608
            type="button"
1609
            class="icon-btn"
1610
            aria-haspopup="menu"
1611
            aria-expanded={roomMenuOpen}
1612
            aria-label="Room options"
1613
            title="Room options"
1614
            on:click={() => (roomMenuOpen = !roomMenuOpen)}
1615
          >
1616
            <span aria-hidden="true">⋯</span>
1617
          </button>
1618
          {#if roomMenuOpen}
1619
            <div class="room-menu" role="menu">
1620
              <button type="button" role="menuitem" on:click={() => roomMenuAction(() => (dialog = 'security'))}>
1621
                Security
1622
              </button>
1623
              {#if selectedRoom.membership === 'Joined'}
1624
                <button
1625
                  type="button"
1626
                  role="menuitem"
1627
                  class="danger"
1628
                  disabled={leaveBusy}
1629
                  on:click={() => roomMenuAction(() => void leave())}
1630
                >
1631
                  {leaveBusy ? 'Leaving…' : 'Leave room'}
1632
                </button>
1633
              {/if}
1634
            </div>
1635
          {/if}
1636
        </div>
1637
        {/if}
1638
      </div>
1639
    </header>
1640
1641
    <nav class="rail" aria-label="Servers and spaces">
1642
      <button
1643
        type="button"
1644
        class="rail-btn"
1645
        class:active={selectedSpaceId === null}
1646
        title="Home — all channels"
1647
        aria-label="Home — all channels"
1648
        aria-pressed={selectedSpaceId === null}
1649
        on:click={() => void selectHome()}
1650
      >
1651
        <span aria-hidden="true">⌂</span>
1652
      </button>
1653
      {#each [pinnedRail, otherRail] as group}
1654
        {#if group.length > 0}
1655
          <div class="rail-sep" aria-hidden="true"></div>
1656
        {/if}
1657
        {#each group as space (space.room_id)}
1658
          <button
1659
            type="button"
1660
            class="rail-btn rail-space"
1661
            class:active={railSelected === space.room_id}
1662
            class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after}
1663
            class:drop-after={dropTarget?.id === space.room_id && dropTarget.after}
1664
            class:pinned={space.favourite}
1665
            title={space.name}
1666
            aria-label={`Show channels in space ${space.name}`}
1667
            aria-pressed={selectedSpaceId === space.room_id}
1668
            draggable="true"
1669
            on:click={() => void selectSpace(space.room_id)}
1670
            on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)}
1671
            on:dragstart={(ev) => startRailDrag(ev, space.room_id)}
1672
            on:dragover={(ev) => overRailSpace(ev, space)}
1673
            on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)}
1674
            on:drop|preventDefault={() => void dropRailSpace()}
1675
            on:dragend={() => ((dragSpaceId = null), (dropTarget = null))}
1676
          >
1677
            <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
1678
          </button>
1679
        {/each}
1680
      {/each}
1681
      <button
1682
        type="button"
1683
        class="rail-btn rail-add"
1684
        aria-label="Join or create a room"
1685
        on:click={() => {
1686
          dialog = 'join';
1687
        }}
1688
      >
1689
        <span aria-hidden="true">+</span>
1690
      </button>
1691
    </nav>
1692
1693
    {#if menu}
1694
      <ContextMenu items={menu.items} x={menu.x} y={menu.y} onClose={() => (menu = null)} />
1695
    {/if}
1696
    {#if userCard}
1697
      {#key userCard}
1698
        {@const cardUser = userCard.userId}
1699
        <UserCard
1700
          person={personFor(cardUser)}
1701
          member={memberFor(cardUser)}
1702
          levels={roomLevels}
1703
          self={$sessionUser ?? null}
1704
          x={userCard.x}
1705
          y={userCard.y}
1706
          confirm={userCard.confirm}
1707
          onAction={(action) => void userAction(cardUser, action)}
1708
          onClose={() => (userCard = null)}
1709
        />
1710
      {/key}
1711
    {/if}
1712
1713
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
1714
      <div class="side-search">
1715
        <label class="visually-hidden" for="room-search">Search rooms</label>
1716
        <input
1717
          id="room-search"
1718
          type="search"
1719
          placeholder="Search rooms"
1720
          bind:value={search}
1721
          autocomplete="off"
1722
        />
1723
        <button
1724
          type="button"
1725
          class="icon-btn"
1726
          title="Refresh rooms"
1727
          aria-label="Refresh rooms"
1728
          disabled={roomsLoading}
1729
          on:click={() => void refreshRooms()}
1730
        >
1731
          <span aria-hidden="true">⟳</span>
1732
        </button>
1733
      </div>
1734
      <div class="side-scroll">
1735
        {#if selectedSpace}
1736
          <div class="space-context">
1737
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={28} shape="rounded" />
1738
            <div class="space-context-text">
1739
              <strong>{selectedSpace.name}</strong>
1740
            </div>
1741
            {#if spaceParents.has(selectedSpace.room_id)}
1742
              {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
1743
              <button
1744
                type="button"
1745
                class="icon-btn"
1746
                title="Up to the parent space"
1747
                aria-label="Up to the parent space"
1748
                on:click={() => void selectSpace(parentId)}
1749
              >
1750
                <span aria-hidden="true">↑</span>
1751
              </button>
1752
            {/if}
1753
          </div>
1754
        {:else}
1755
          <div class="space-context">
1756
            <div class="space-context-text">
1757
              <strong>Home</strong>
1758
            </div>
1759
          </div>
1760
        {/if}
1761
        {#if roomsLoading && $rooms.length === 0}
1762
          <p class="side-note">Loading rooms…</p>
1763
        {:else if $rooms.length === 0}
1764
          <p class="side-note">No rooms yet</p>
1765
          <div class="side-cta">
1766
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
1767
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
1768
          </div>
1769
        {:else}
1770
          {#if selectedSpaceId && spaceChildrenLoading}
1771
            <p class="side-note">Loading channels…</p>
1772
          {:else if selectedSpaceId && spaceChildrenError}
1773
            <p class="side-note" role="alert">{spaceChildrenError}</p>
1774
            <div class="side-cta">
1775
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
1776
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1777
            </div>
1778
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
1779
            <p class="side-note">No channels</p>
1780
            <div class="side-cta">
1781
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1782
            </div>
1783
          {:else}
1784
            {#if invites.length > 0 && !selectedSpaceId}
1785
              <h2 class="side-h">Invites</h2>
1786
              <ul class="room-list">
1787
                {#each invites as room (room.room_id)}
1788
                  <li>
1789
                    <button
1790
                      type="button"
1791
                      class="room-row"
1792
                      class:active={$selectedRoomId === room.room_id}
1793
                      on:click={() => void selectRoom(room.room_id)}
1794
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1795
                    >
1796
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1797
                      <span class="room-name">{room.name}</span>
1798
                      <span
1799
                        class="invite-join"
1800
                        role="button"
1801
                        tabindex="0"
1802
                        aria-label={`Join ${room.name}`}
1803
                        on:click|stopPropagation={() => void join(room.room_id)}
1804
                        on:keydown|stopPropagation={(ev) => {
1805
                          if (ev.key === 'Enter' || ev.key === ' ') {
1806
                            ev.preventDefault();
1807
                            void join(room.room_id);
1808
                          }
1809
                        }}
1810
                      >
1811
                        Join
1812
                      </span>
1813
                    </button>
1814
                  </li>
1815
                {/each}
1816
              </ul>
1817
            {/if}
1818
1819
            {#if directRooms.length > 0}
1820
              <h2 class="side-h">Direct messages</h2>
1821
              <ul class="room-list">
1822
                {#each directRooms as room (room.room_id)}
1823
                  <li class="room-item">
1824
                    <button
1825
                      type="button"
1826
                      class="room-row"
1827
                      class:active={$selectedRoomId === room.room_id}
1828
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
1829
                      on:click={() => void selectRoom(room.room_id)}
1830
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1831
                    >
1832
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
1833
                      <span class="room-name">{room.name}</span>
1834
                      {#if roomUnread(room) > 0}
1835
                        <span
1836
                          class="badge"
1837
                          class:mention={room.unread_mentions > 0}
1838
                          aria-label={`${roomUnread(room)} unread`}
1839
                        >
1840
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
1841
                        </span>
1842
                      {/if}
1843
                    </button>
1844
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
1845
                  </li>
1846
                {/each}
1847
              </ul>
1848
            {/if}
1849
1850
            {#if groupRooms.length > 0}
1851
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
1852
              <ul class="room-list">
1853
                {#each groupRooms as room (room.room_id)}
1854
                  <li class="room-item">
1855
                    <button
1856
                      type="button"
1857
                      class="room-row"
1858
                      class:active={$selectedRoomId === room.room_id}
1859
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
1860
                      on:click={() => void selectRoom(room.room_id)}
1861
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1862
                    >
1863
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1864
                      <span class="room-hash" aria-hidden="true">#</span>
1865
                      <span class="room-name">{room.name}</span>
1866
                      {#if roomUnread(room) > 0}
1867
                        <span
1868
                          class="badge"
1869
                          class:mention={room.unread_mentions > 0}
1870
                          aria-label={`${roomUnread(room)} unread`}
1871
                        >
1872
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
1873
                        </span>
1874
                      {/if}
1875
                    </button>
1876
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
1877
                  </li>
1878
                {/each}
1879
              </ul>
1880
            {/if}
1881
1882
            {#if spaceList.length > 0}
1883
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
1884
              <ul class="room-list">
1885
                {#each spaceList as room (room.room_id)}
1886
                  <li class="room-item">
1887
                    <button
1888
                      type="button"
1889
                      class="room-row"
1890
                      class:active={selectedSpaceId === room.room_id}
1891
                      aria-label={`Show channels in space ${room.name}`}
1892
                      on:click={() => void selectSpace(room.room_id)}
1893
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1894
                    >
1895
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1896
                      <span class="room-hash" aria-hidden="true">◇</span>
1897
                      <span class="room-name">{room.name}</span>
1898
                    </button>
1899
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
1900
                  </li>
1901
                {/each}
1902
              </ul>
1903
            {/if}
1904
1905
            {#if query && visibleRooms.length === 0}
1906
              <p class="side-note">No rooms match “{search.trim()}”.</p>
1907
            {/if}
1908
          {/if}
1909
        {/if}
1910
      </div>
1911
1912
      <div class="side-footer">
1913
        <div class="me" title={$sessionUser}>
1914
          {#if profileMxc}
1915
            <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={30} />
1916
          {:else}
1917
            <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
1918
          {/if}
1919
          <span class="me-id">{profile?.display_name && profile.display_name !== $sessionUser ? `${profile.display_name} (${$sessionUser})` : $sessionUser}</span>
1920
        </div>
1921
        <button
1922
          type="button"
1923
          class="icon-btn"
1924
          title="Encryption and verification"
1925
          aria-label="Encryption and verification"
1926
          on:click={() => (dialog = 'security')}
1927
        >
1928
          <span aria-hidden="true">🛡</span>
1929
        </button>
1930
        <button
1931
          type="button"
1932
          class="icon-btn"
1933
          title="Settings"
1934
          aria-label="Settings"
1935
          on:click={() => (dialog = 'settings')}
1936
        >
1937
          <span aria-hidden="true">⚙</span>
1938
        </button>
1939
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
1940
          <span aria-hidden="true">⏻</span>
1941
        </button>
1942
      </div>
1943
    </aside>
1944
    {#if sidebarOpen}
1945
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
1946
    {/if}
1947
1948
    <main class="chat">
1949
        {#if $banners.length > 0}
1950
          <div class="banners" aria-live="polite">
1951
            {#each $banners as banner (banner.id)}
1952
              <div class="banner" role="alert">
1953
                <span>{banner.message}</span>
1954
                <button
1955
                  type="button"
1956
                  aria-label="Dismiss error"
1957
                  on:click={() => dismissBanner(banner.id)}
1958
                >
1959
                  ✕
1960
                </button>
1961
              </div>
1962
            {/each}
1963
          </div>
1964
        {/if}
1965
      {#if !selectedRoom}
1966
        <div class="empty">
1967
          <div class="empty-mark" aria-hidden="true">◈</div>
1968
          {#if selectedSpace}
1969
            <h1>{selectedSpace.name}</h1>
1970
          {:else}
1971
            <h1>Welcome to Malice</h1>
1972
          {/if}
1973
          <div class="empty-cta">
1974
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
1975
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
1976
          </div>
1977
          <p class="conn-line">
1978
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1979
            {$connection}
1980
          </p>
1981
        </div>
1982
      {:else}
1983
1984
1985
        {#if recoveryBanner}
1986
          <div class="sec-banner warn" role="status">
1987
            <span>Message history is locked</span>
1988
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
1989
          </div>
1990
        {/if}
1991
        {#if verificationBanner}
1992
          <div class="sec-banner" role="status">
1993
            {#if verificationBanner.kind === 'Incoming'}
1994
              <span>A device wants to verify this session</span>
1995
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
1996
            {:else if verificationBanner.kind === 'Comparison'}
1997
              <span>Verification codes ready</span>
1998
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
1999
            {:else if verificationBanner.kind === 'Waiting'}
2000
              <span>Verification started</span>
2001
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
2002
            {:else if verificationBanner.kind === 'Failed'}
2003
              <span>Verification failed: {verificationBanner.message}</span>
2004
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
2005
            {:else if verificationBanner.kind === 'Cancelled'}
2006
              <span>Verification cancelled: {verificationBanner.reason}</span>
2007
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2008
            {:else}
2009
              <span>Verification in progress</span>
2010
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2011
            {/if}
2012
          </div>
2013
        {/if}
2014
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
2015
          <p class="conn-banner error" role="alert">{openFailed[$selectedRoomId]}</p>
2016
        {/if}
2017
2018
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2019
        <div
2020
          class="timeline"
2021
          bind:this={timelineEl}
2022
          on:scroll={onTimelineScroll}
2023
          on:wheel={noteUserScroll}
2024
          on:touchmove={noteUserScroll}
2025
          on:keydown={onTimelineKey}
2026
          on:pointerdown={onTimelinePointer}
2027
          aria-label={`Messages in ${selectedRoom.name}`}
2028
        >
2029
          <div class="timeline-inner" use:pinTimeline>
2030
            <div class="timeline-top">
2031
              {#if hasStart}
2032
                <p class="start-note">Beginning of history</p>
2033
              {:else}
2034
                <button type="button" class="ghost-btn" disabled={paginateBusy} on:click={() => void paginate()}>
2035
                  {paginateBusy ? 'Loading…' : 'Load older messages'}
2036
                </button>
2037
              {/if}
2038
            </div>
2039
            {#if grouped.length === 0}
2040
              <p class="side-note timeline-empty">No messages yet</p>
2041
            {:else}
2042
              {#each grouped as g (g.key)}
2043
                {#if g.item.kind === 'day'}
2044
                  <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div>
2045
                {:else if g.item.kind === 'readMarker'}
2046
                  <div class="new-row"><span>New</span></div>
2047
                {:else if g.item.kind === 'start'}
2048
                  <p class="start-note">Beginning of history</p>
2049
                {:else if g.item.kind === 'unknown'}
2050
                  <p class="unknown-note">Unsupported event ({g.item.label})</p>
2051
                {:else}
2052
                  <MessageRow
2053
                    itemId={g.key}
2054
                    event={g.item.event}
2055
                    showSender={g.showSender}
2056
                    senderAvatar={senderAvatarFor(g.item.event.sender.user_id) ?? g.item.event.sender.avatar}
2057
                    {reacting}
2058
                    onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2059
                    quickReactions={$quickReactions}
2060
                    packs={roomPacks}
2061
                    linkPreviews={$linkPreviews}
2062
                    {loadPreview}
2063
                    onQuickChange={(list) => void changeQuickReactions(list)}
2064
                    {people}
2065
                    self={$sessionUser ?? null}
2066
                    onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2067
                    onCloneSticker={openCloneStickerMenu}
2068
                    onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2069
                    onReply={selectedRoom.membership === 'Joined' ? startReply : null}
2070
                    onJump={jumpTo}
2071
                    onEdit={selectedRoom.membership === 'Joined' ? startEdit : null}
2072
                    editing={editing !== null && editing.eventId === g.item.event.event_id}
2073
                    showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0}
2074
                  />
2075
                {/if}
2076
              {/each}
2077
            {/if}
2078
            {#each pendingItems as p, i (p.id)}
2079
              <MessageRow
2080
                itemId={`pending-${p.id}`}
2081
                event={pendingToEvent(p)}
2082
                onJump={jumpTo}
2083
                showSender={pendingShowSender(i)}
2084
                senderAvatar={senderAvatarFor($sessionUser ?? '')}
2085
                {reacting}
2086
                onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2087
                quickReactions={$quickReactions}
2088
                packs={roomPacks}
2089
                linkPreviews={$linkPreviews}
2090
                {loadPreview}
2091
                onQuickChange={(list) => void changeQuickReactions(list)}
2092
              />
2093
              {#if p.status === 'failed'}
2094
                <div class="pending-actions">
2095
                  <span class="pending-error" role="alert">{p.error}</span>
2096
                  <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button>
2097
                  <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button>
2098
                </div>
2099
              {/if}
2100
            {/each}
2101
          </div>
2102
        </div>
2103
2104
        {#if selectedRoom.membership === 'Joined'}
2105
          {#if editing}
2106
            <div class="reply-bar" role="status">
2107
              <span class="reply-bar-label">
2108
                Editing message
2109
                <span class="reply-bar-text">{editing.original}</span>
2110
              </span>
2111
              <button type="button" class="icon-btn" aria-label="Cancel edit" title="Cancel edit (Esc)" on:click={cancelEdit}>
2112
                <span aria-hidden="true">✕</span>
2113
              </button>
2114
            </div>
2115
          {:else if replyingTo && replyingTo.details.kind === 'Ready'}
2116
            <div class="reply-bar" role="status">
2117
              <span class="reply-bar-label">
2118
                Replying to <strong>{senderLabel(replyingTo.details.sender)}</strong>
2119
                <span class="reply-bar-text">{contentPreview(replyingTo.details.content)}</span>
2120
              </span>
2121
              <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}>
2122
                <span aria-hidden="true">✕</span>
2123
              </button>
2124
            </div>
2125
          {/if}
2126
          {#if $selectedRoomId && currentStaged.length > 0}
2127
            {@const stagedRoom = $selectedRoomId}
2128
            <ul class="staged" aria-label="Attachments to send">
2129
              {#each currentStaged as attachment (attachment.id)}
2130
                <li class="staged-item">
2131
                  {#if attachment.previewUrl}
2132
                    <img src={attachment.previewUrl} alt={attachment.file.name || 'Pasted image'} />
2133
                  {:else}
2134
                    <span class="staged-name">{attachment.file.name || 'attachment'}</span>
2135
                  {/if}
2136
                  <button
2137
                    type="button"
2138
                    class="icon-btn staged-remove"
2139
                    aria-label={`Remove ${attachment.file.name || 'attachment'}`}
2140
                    title="Remove"
2141
                    on:click={() => unstage(stagedRoom, attachment.id)}
2142
                  >
2143
                    <span aria-hidden="true">✕</span>
2144
                  </button>
2145
                </li>
2146
              {/each}
2147
            </ul>
2148
          {/if}
2149
          <form class="composer" class:replying={replyingTo || editing} class:staging={currentStaged.length > 0} on:submit|preventDefault={() => send()}>
2150
            <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label>
2151
            {#if mentionQuery && mentionCandidates.length > 0}
2152
              <ul class="mention-finder" role="listbox" aria-label="Mention someone">
2153
                {#each mentionCandidates as person, i (person.user_id)}
2154
                  <li
2155
                    role="option"
2156
                    aria-selected={i === mentionIndex}
2157
                    class:active={i === mentionIndex}
2158
                    on:pointerdown|preventDefault={() => void pickMention(person)}
2159
                    on:pointerenter={() => (mentionIndex = i)}
2160
                  >
2161
                    <MxcAvatar mxc={person.avatar} label={person.name} size={22} />
2162
                    <span class="mention-name">{person.name}</span>
2163
                    <span class="mention-id">{person.user_id}</span>
2164
                  </li>
2165
                {/each}
2166
              </ul>
2167
            {/if}
2168
            <input
2169
              type="file"
2170
              multiple
2171
              bind:this={fileInput}
2172
              class="visually-hidden"
2173
              aria-label="Attach a file"
2174
              on:change={() => void onFileChosen()}
2175
            />
2176
            <input
2177
              type="file"
2178
              accept="image/*"
2179
              bind:this={avatarInput}
2180
              class="visually-hidden"
2181
              aria-label="Choose a new avatar"
2182
              on:change={() => void onAvatarChosen()}
2183
            />
2184
            <button
2185
              type="button"
2186
              class="ghost-btn"
2187
              title="Attach an image or file"
2188
              aria-label="Attach an image or file"
2189
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2190
              on:click={pickFiles}
2191
            >
2192
              {uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : '📎'}
2193
            </button>
2194
            <button
2195
              type="button"
2196
              class="icon-btn sticker-btn"
2197
              title="Stickers"
2198
              aria-label="Stickers"
2199
              aria-expanded={stickersOpen}
2200
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2201
              on:click={() => (stickersOpen = !stickersOpen)}
2202
            >
2203
              <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
2204
                <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" />
2205
                <path d="M13 20v-5a2 2 0 0 1 2-2h5" fill="none" stroke="currentColor" stroke-width="1.8" />
2206
              </svg>
2207
            </button>
2208
            {#if stickersOpen && $selectedRoomId}
2209
              {@const stickerRoom = $selectedRoomId}
2210
              <div class="sticker-pop">
2211
                <StickerPicker
2212
                  packs={roomPacks}
2213
                  {roomName}
2214
                  onSend={(pack, image) => void sendSticker(stickerRoom, pack, image)}
2215
                  onClone={(pack, image, x, y) => openCloneImageMenu(pack, image, x, y)}
2216
                  onClonePack={(pack, x, y) => openClonePackMenu(pack, x, y)}
2217
                  onManage={() => ((stickersOpen = false), (dialog = 'packs'))}
2218
                  onClose={() => (stickersOpen = false)}
2219
                />
2220
              </div>
2221
            {/if}
2222
            <textarea
2223
              id="composer"
2224
              bind:this={composerEl}
2225
              bind:value={composer}
2226
              rows="1"
2227
              placeholder={`Message ${selectedRoom.name}`}
2228
              aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`}
2229
              on:keydown={onComposerKey}
2230
              on:input={updateMentionQuery}
2231
              on:click={updateMentionQuery}
2232
              on:keyup={(e) => (e.key.startsWith('Arrow') && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') || e.key === 'Home' || e.key === 'End' ? updateMentionQuery() : undefined}
2233
              on:blur={() => (mentionQuery = null)}
2234
              on:paste={onComposerPaste}
2235
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2236
            ></textarea>
2237
            <button
2238
              type="button"
2239
              class="icon-btn md-toggle"
2240
              aria-pressed={$markdownEnabled}
2241
              aria-label={$markdownEnabled ? 'Turn markdown off' : 'Turn markdown on'}
2242
              title={$markdownEnabled ? 'Markdown on' : 'Markdown off'}
2243
              on:click={() => markdownEnabled.update((v) => !v)}
2244
            >
2245
              <svg viewBox="0 0 24 16" width="22" height="15" aria-hidden="true">
2246
                <rect x="1" y="1" width="22" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="1.6" />
2247
                <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" />
2248
              </svg>
2249
            </button>
2250
            <button
2251
              type="submit"
2252
              class="primary-btn"
2253
              disabled={(!composer.trim() && currentStaged.length === 0) ||
2254
                !($selectedRoomId && openReady[$selectedRoomId]) ||
2255
                (currentStaged.length > 0 && uploadBusy)}
2256
              title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'}
2257
            >
2258
              Send
2259
            </button>
2260
          </form>
2261
        {:else}
2262
          <div class="join-bar">
2263
            <p>You are not a member of this room.</p>
2264
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
2265
              {joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`}
2266
            </button>
2267
          </div>
2268
        {/if}
2269
      {/if}
2270
    </main>
2271
2272
    {#if selectedRoom}
2273
      <aside class="members" aria-hidden={!membersOpen} aria-label={`Members of ${selectedRoom.name}`}>
2274
        <div class="members-head">
2275
          <h2>Members</h2>
2276
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
2277
            <span aria-hidden="true">✕</span>
2278
          </button>
2279
        </div>
2280
        {#if $membersLoading && members.length === 0}
2281
          <p class="side-note">Loading members…</p>
2282
        {:else if members.length === 0}
2283
          <p class="side-note">No members loaded.</p>
2284
          {#if $selectedRoomId}
2285
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
2286
              Retry
2287
            </button>
2288
          {/if}
2289
        {:else}
2290
          <ul class="member-list">
2291
            {#each members as member (member.user_id)}
2292
              <li>
2293
                <button
2294
                  type="button"
2295
                  class="member"
2296
                  on:click={(ev) => {
2297
                    const rect = ev.currentTarget.getBoundingClientRect();
2298
                    void openUser(member.user_id, rect.left - 308, rect.top, false);
2299
                  }}
2300
                  on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)}
2301
                >
2302
                  <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} size={30} />
2303
                  <span class="member-names">
2304
                    <span class="member-name">{member.display_name || member.name}</span>
2305
                    <span class="member-id">{member.user_id}</span>
2306
                  </span>
2307
                </button>
2308
              </li>
2309
            {/each}
2310
          </ul>
2311
        {/if}
2312
      </aside>
2313
    {/if}
2314
2315
    {#if dialog}
2316
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
2317
        {#if dialog === 'security'}
2318
          <SecurityPanel
2319
            encryptionState={$encryption}
2320
            verificationState={$verification}
2321
            onAction={() => void loadEncryption()}
2322
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
2323
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
2324
            on:close={() => (dialog = null)}
2325
          />
2326
        {:else if dialog === 'settings'}
2327
          <SettingsPanel
2328
            quick={$quickReactions}
2329
            packs={roomPacks}
2330
            onQuickChange={(list) => void changeQuickReactions(list)}
2331
            on:close={() => (dialog = null)}
2332
            on:packs={() => (dialog = 'packs')}
2333
          />
2334
        {:else if dialog === 'packs'}
2335
          <PackManager packs={$imagePacks} rooms={$rooms} onError={pushBanner} on:close={() => (dialog = null)} />
2336
        {:else}
2337
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
2338
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
2339
              <button
2340
                type="button"
2341
                role="tab"
2342
                aria-selected={dialog === 'join'}
2343
                class:active={dialog === 'join'}
2344
                on:click={() => (dialog = 'join')}
2345
              >
2346
                Join
2347
              </button>
2348
              <button
2349
                type="button"
2350
                role="tab"
2351
                aria-selected={dialog === 'create'}
2352
                class:active={dialog === 'create'}
2353
                on:click={() => (dialog = 'create')}
2354
              >
2355
                Create
2356
              </button>
2357
              <button
2358
                type="button"
2359
                class="icon-btn modal-x"
2360
                aria-label="Close dialog"
2361
                on:click={() => (dialog = null)}
2362
              >
2363
                <span aria-hidden="true">✕</span>
2364
              </button>
2365
            </div>
2366
            {#if dialog === 'join'}
2367
              <form on:submit|preventDefault={() => void join(joinTarget)}>
2368
                <label class="field">
2369
                  <span>Room ID or alias</span>
2370
                  <input
2371
                    type="text"
2372
                    placeholder="!room:example.org or #alias:example.org"
2373
                    bind:value={joinTarget}
2374
                    required
2375
                    disabled={joinBusy}
2376
                  />
2377
                </label>
2378
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
2379
                  {joinBusy ? 'Joining…' : 'Join room'}
2380
                </button>
2381
              </form>
2382
            {:else}
2383
            <form on:submit|preventDefault={() => void create()}>
2384
              <label class="field">
2385
                <span>Room name</span>
2386
                <input
2387
                  type="text"
2388
                  placeholder="Weekend plans"
2389
                  bind:value={createName}
2390
                  required
2391
                  disabled={createBusy}
2392
                />
2393
              </label>
2394
              <label class="field">
2395
                <span>Topic (optional)</span>
2396
                <input
2397
                  type="text"
2398
                  placeholder="What should this room be about?"
2399
                  bind:value={createTopic}
2400
                  disabled={createBusy}
2401
                />
2402
              </label>
2403
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
2404
                {createBusy ? 'Creating…' : 'Create room'}
2405
              </button>
2406
            </form>
2407
            {/if}
2408
          </div>
2409
        {/if}
2410
      </div>
2411
    {/if}
2412
  </div>
2413
{/if}
2414
2415
<ImageLightbox />