atagen

malice

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