atagen

malice

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