atagen

malice

public
Star0
Watch0
35a820422568f7c14365c307cb9fa13dcedce3da
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte2703 lines106.3 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
  const rosterTried = new Set<string>();
1244
  $: fillMissingNames($selectedRoomId, items);
1245
  function fillMissingNames(roomId: string | null, list: TimelineItem[]): void {
1246
    if (!roomId || rosterTried.has(roomId) || $membersByRoom[roomId]) return;
1247
    if (!list.some((i) => i.kind === 'event' && !i.event.sender.display_name)) return;
1248
    rosterTried.add(roomId);
1249
    void loadMembers(roomId);
1250
  }
1251
1252
  function senderAvatarFor(userId: string): string | null {
1253
    return avatarByUser[userId] ?? null;
1254
  }
1255
1256
  function toggleMembers(): void {
1257
    membersOpen = !membersOpen;
1258
    if (membersOpen && $selectedRoomId) void loadMembers($selectedRoomId);
1259
  }
1260
1261
  async function join(target: string): Promise<void> {
1262
    const room = target.trim();
1263
    if (!room || joinBusy) return;
1264
    joinBusy = true;
1265
    try {
1266
      const res = await joinRoom(room);
1267
      joinTarget = '';
1268
      dialog = null;
1269
      await refreshRooms();
1270
      await selectRoom(res.room_id);
1271
    } catch (e) {
1272
      pushBanner(e instanceof Error ? e.message : 'Join failed');
1273
    } finally {
1274
      joinBusy = false;
1275
    }
1276
  }
1277
1278
  async function create(): Promise<void> {
1279
    const name = createName.trim();
1280
    if (!name || createBusy) return;
1281
    createBusy = true;
1282
    try {
1283
      const res = await createRoom(name, createTopic.trim() || undefined);
1284
      createName = '';
1285
      createTopic = '';
1286
      dialog = null;
1287
      await refreshRooms();
1288
      await selectRoom(res.room_id);
1289
    } catch (e) {
1290
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
1291
    } finally {
1292
      createBusy = false;
1293
    }
1294
  }
1295
1296
  async function leave(roomId: string | null = $selectedRoomId): Promise<void> {
1297
    if (!roomId || leaveBusy) return;
1298
    leaveBusy = true;
1299
    stopTyping();
1300
    try {
1301
      await leaveRoom(roomId);
1302
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
1303
      if (warmRooms.includes(roomId)) {
1304
        forgetOpenRoom(roomId);
1305
        closeRoom(roomId).catch(() => undefined);
1306
      }
1307
      await refreshRooms();
1308
    } catch (e) {
1309
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
1310
    } finally {
1311
      leaveBusy = false;
1312
    }
1313
  }
1314
1315
  function connectionClass(state: string): string {
1316
    if (state === 'online') return 'dot-online';
1317
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
1318
    return 'dot-off';
1319
  }
1320
1321
  let dragSpaceId: string | null = null;
1322
  let dropTarget: { id: string; after: boolean } | null = null;
1323
  let menu: { items: MenuItem[]; x: number; y: number; above?: boolean } | null = null;
1324
  let userCard: { userId: string; x: number; y: number; confirm: 'kick' | 'ban' | null } | null = null;
1325
  let levelsByRoom: Record<string, PowerLevels | null> = {};
1326
  let peeking: string | null = null;
1327
1328
  $: roomLevels = $selectedRoomId ? (levelsByRoom[$selectedRoomId] ?? null) : null;
1329
1330
  function personFor(userId: string): Person {
1331
    return people[userId] ?? { user_id: userId, name: userId, avatar: avatarByUser[userId] ?? null };
1332
  }
1333
1334
  function memberFor(userId: string): MemberSummary | null {
1335
    return members.find((m) => m.user_id === userId) ?? null;
1336
  }
1337
1338
  async function loadLevels(roomId: string): Promise<void> {
1339
    try {
1340
      const levels = parsePowerLevels(await runCommand({ op: 'power_levels', room_id: roomId }));
1341
      levelsByRoom = { ...levelsByRoom, [roomId]: levels };
1342
    } catch {
1343
      levelsByRoom = { ...levelsByRoom, [roomId]: levelsByRoom[roomId] ?? null };
1344
    }
1345
  }
1346
1347
  async function openUser(userId: string, x: number, y: number, asMenu: boolean): Promise<void> {
1348
    const roomId = $selectedRoomId;
1349
    if (roomId && !(roomId in levelsByRoom)) await loadLevels(roomId);
1350
    else if (roomId) void loadLevels(roomId);
1351
    if (asMenu) menu = { items: userMenuItems(userId, x, y), x, y };
1352
    else userCard = { userId, x, y, confirm: null };
1353
  }
1354
1355
  function copyText(text: string): void {
1356
    navigator.clipboard.writeText(text).catch(() => pushBanner('Could not copy to the clipboard'));
1357
  }
1358
1359
  function userMenuItems(userId: string, x: number, y: number): MenuItem[] {
1360
    const own = userId === $sessionUser;
1361
    const member = memberFor(userId);
1362
    const items: MenuItem[] = [];
1363
    if (!own) items.push({ label: 'Message', action: () => void userAction(userId, { kind: 'message' }) });
1364
    items.push({ label: 'Mention', action: () => void userAction(userId, { kind: 'mention' }) });
1365
    items.push({ label: 'Copy user ID', action: () => copyText(userId) });
1366
    const firstModeration = items.length;
1367
    if (roomLevels && $sessionUser) {
1368
      const can = allowed(roomLevels, $sessionUser, userId);
1369
      const banned = member?.membership === 'Ban';
1370
      if (can.setLevel && !own) {
1371
        const muted = isMuted(roomLevels, userId);
1372
        items.push({ label: muted ? 'Unmute' : 'Mute', action: () => void userAction(userId, { kind: muted ? 'unmute' : 'mute' }) });
1373
      }
1374
      if (can.kick && !banned) items.push({ label: 'Kick…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'kick' }) });
1375
      if (can.ban && banned) items.push({ label: 'Unban', action: () => void userAction(userId, { kind: 'unban' }) });
1376
      if (can.ban && !banned) items.push({ label: 'Ban…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'ban' }) });
1377
      if (can.setLevel) items.push({ label: 'Power level…', action: () => (userCard = { userId, x, y, confirm: null }) });
1378
    }
1379
    if (items[firstModeration]) items[firstModeration] = { ...items[firstModeration], divider: true };
1380
    if (!own) {
1381
      const kind = member?.ignored ? 'unignore' : 'ignore';
1382
      items.push({ label: member?.ignored ? 'Unignore' : 'Ignore', divider: true, action: () => void userAction(userId, { kind }) });
1383
    }
1384
    return items;
1385
  }
1386
1387
  async function insertMention(person: Person): Promise<void> {
1388
    const roomId = $selectedRoomId;
1389
    if (!roomId) return;
1390
    const lead = composer && !/\s$/.test(composer) ? ' ' : '';
1391
    composer = `${composer}${lead}${person.name} `;
1392
    pickedMentions = {
1393
      ...pickedMentions,
1394
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
1395
    };
1396
    await tick();
1397
    composerEl?.focus();
1398
    composerEl?.setSelectionRange(composer.length, composer.length);
1399
  }
1400
1401
  async function userAction(userId: string, action: UserAction): Promise<void> {
1402
    const roomId = $selectedRoomId;
1403
    try {
1404
      switch (action.kind) {
1405
        case 'message': {
1406
          const res = (await runCommand({ op: 'direct', user_id: userId })) as { room_id: string };
1407
          await refreshRooms();
1408
          await selectRoom(res.room_id);
1409
          return;
1410
        }
1411
        case 'mention':
1412
          await insertMention(personFor(userId));
1413
          return;
1414
        case 'ignore':
1415
        case 'unignore':
1416
          await runCommand({ op: action.kind, user_id: userId });
1417
          if (roomId) void loadMembers(roomId);
1418
          return;
1419
      }
1420
      if (!roomId) return;
1421
      switch (action.kind) {
1422
        case 'kick':
1423
        case 'ban':
1424
          await runCommand({ op: action.kind, room_id: roomId, user_id: userId, reason: action.reason });
1425
          break;
1426
        case 'unban':
1427
          await runCommand({ op: 'unban', room_id: roomId, user_id: userId, reason: null });
1428
          break;
1429
        case 'mute':
1430
        case 'unmute':
1431
          await runCommand({ op: 'mute', room_id: roomId, user_id: userId, muted: action.kind === 'mute' });
1432
          break;
1433
        case 'power':
1434
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id: userId, level: action.level });
1435
          break;
1436
      }
1437
      void loadLevels(roomId);
1438
      void loadMembers(roomId);
1439
    } catch (e) {
1440
      pushBanner(e instanceof Error ? e.message : 'That action failed');
1441
    }
1442
  }
1443
1444
  function roomMenuItems(room: RoomSummary): MenuItem[] {
1445
    const items: MenuItem[] = room.space
1446
      ? [{ label: 'Open', action: () => void selectSpace(room.room_id) }]
1447
      : [
1448
          { label: 'Open', action: () => void selectRoom(room.room_id) },
1449
          { label: 'Peek', action: () => void selectRoom(room.room_id, true) }
1450
        ];
1451
    items.push({ label: room.favourite ? 'Unpin' : room.space ? 'Pin to top' : 'Pin', action: () => void togglePin(room) });
1452
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${room.canonical_alias ?? room.room_id}`) });
1453
    items.push({ label: 'Copy room ID', action: () => copyText(room.room_id) });
1454
    if (room.membership === 'Joined') items.push({ label: 'Leave', danger: true, divider: true, action: () => void leave(room.room_id) });
1455
    return items;
1456
  }
1457
1458
  function openRoomMenu(ev: MouseEvent, room: RoomSummary): void {
1459
    menu = { items: roomMenuItems(room), x: ev.clientX, y: ev.clientY };
1460
  }
1461
1462
  function roomName(roomId: string): string {
1463
    return $rooms.find((r) => r.room_id === roomId)?.name ?? roomId;
1464
  }
1465
1466
  async function sendSticker(roomId: string, pack: ImagePack, image: PackImage): Promise<void> {
1467
    stickersOpen = false;
1468
    stickToBottom = true;
1469
    try {
1470
      await runCommand({ op: 'send_sticker', room_id: roomId, pack_id: pack.id, shortcode: image.shortcode });
1471
      if (peeking === roomId) stopPeeking();
1472
    } catch (e) {
1473
      pushBanner(e instanceof Error ? e.message : 'Could not send the sticker');
1474
    }
1475
  }
1476
1477
  async function runClone(request: CommandRequest, failure: string): Promise<void> {
1478
    try {
1479
      const res = (await runCommand(request)) as { skipped?: string[] } | undefined;
1480
      if (res?.skipped?.length) pushBanner(`Couldn't copy ${res.skipped.map((s) => `:${s}:`).join(', ')}`);
1481
    } catch (e) {
1482
      pushBanner(e instanceof Error ? e.message : failure);
1483
    }
1484
  }
1485
1486
  function openCloneImageMenu(pack: ImagePack, image: PackImage, x: number, y: number): void {
1487
    const items = editableChoices($imagePacks, roomName)
1488
      .filter((c) => c.pack?.id !== pack.id)
1489
      .map((choice) => ({
1490
        label: `Clone to ${choice.label}`,
1491
        action: () =>
1492
          void runClone({ op: 'clone_pack_image', from_pack: pack.id, shortcode: image.shortcode, to: choice.target }, 'Could not clone the sticker')
1493
      }));
1494
    menu = { items, x, y };
1495
  }
1496
1497
  function openClonePackMenu(pack: ImagePack, x: number, y: number): void {
1498
    const packRooms = $rooms.filter((r) => r.can_edit_packs && r.membership === 'Joined');
1499
    const items = clonePackDestinations(pack, packRooms, roomName).map((d) => ({
1500
      label: d.label,
1501
      action: () => void runClone({ op: 'clone_pack', from_pack: pack.id, to: d.target, display_name: d.display_name }, 'Could not clone the pack')
1502
    }));
1503
    menu = { items, x, y };
1504
  }
1505
1506
  function openCloneStickerMenu(eventId: string, body: string, x: number, y: number): void {
1507
    const roomId = $selectedRoomId;
1508
    if (!roomId) return;
1509
    const items = editableChoices($imagePacks, roomName).map((choice) => ({
1510
      label: `Clone to ${choice.label}`,
1511
      action: () => {
1512
        const taken = new Set(choice.pack?.images.map((i) => i.shortcode) ?? []);
1513
        void runClone(
1514
          { op: 'clone_sticker', room_id: roomId, event_id: eventId, to: choice.target, shortcode: shortcodeFor(body || 'sticker', taken) },
1515
          'Could not clone the sticker'
1516
        );
1517
      }
1518
    }));
1519
    menu = { items, x, y };
1520
  }
1521
1522
  async function openMessageMenu(event: TimelineEvent, x: number, y: number): Promise<void> {
1523
    const roomId = $selectedRoomId;
1524
    const eventId = event.event_id;
1525
    if (!roomId || !eventId) return;
1526
    if (!(roomId in levelsByRoom)) await loadLevels(roomId);
1527
    const joined = selectedRoom?.membership === 'Joined';
1528
    const content = event.content;
1529
    const items: MenuItem[] = [];
1530
    if (joined) {
1531
      items.push({
1532
        label: 'Reply',
1533
        action: () =>
1534
          startReply({
1535
            event_id: eventId,
1536
            details: { kind: 'Ready', sender: event.sender, content, timestamp_ms: event.timestamp_ms }
1537
          })
1538
      });
1539
    }
1540
    if (joined && event.own && event.editable && content.kind === 'Message' && content.message.kind === 'Text') {
1541
      const body = content.message.body;
1542
      items.push({ label: 'Edit', action: () => startEdit(eventId, body) });
1543
    }
1544
    if (content.kind === 'Message' && content.message.body) {
1545
      const body = content.message.body;
1546
      items.push({ label: 'Copy text', action: () => copyText(body) });
1547
    }
1548
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${roomId}/${eventId}`) });
1549
    if (joined && selectedRoom?.can_pin && content.kind !== 'Redacted') {
1550
      const pinned = selectedRoom.pinned_events.includes(eventId);
1551
      items.push({ label: pinned ? 'Unpin' : 'Pin', action: () => setPinned(eventId, !pinned) });
1552
    }
1553
    if (content.kind === 'Sticker') {
1554
      const body = content.body;
1555
      items.push({ label: 'Clone sticker…', action: () => openCloneStickerMenu(eventId, body, x, y) });
1556
    }
1557
    const me = $sessionUser;
1558
    if (joined && me && roomLevels && canRedact(roomLevels, me, event.sender.user_id) && content.kind !== 'Redacted') {
1559
      items.push({
1560
        label: 'Delete message…',
1561
        danger: true,
1562
        action: () =>
1563
          (menu = {
1564
            x,
1565
            y,
1566
            items: [
1567
              { label: 'Delete', danger: true, action: () => void runClone({ op: 'redact', room_id: roomId, event_id: eventId, reason: null }, 'Could not delete the message') },
1568
              { label: 'Cancel', action: () => undefined }
1569
            ]
1570
          })
1571
      });
1572
    }
1573
    if (!event.own) {
1574
      const person = userMenuItems(event.sender.user_id, x, y);
1575
      if (person[0]) person[0] = { ...person[0], divider: true };
1576
      items.push(...person);
1577
    }
1578
    menu = { items, x, y };
1579
  }
1580
1581
  function openAccountMenu(ev: MouseEvent): void {
1582
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1583
    menu = {
1584
      x: rect.left,
1585
      y: rect.top - 6,
1586
      above: true,
1587
      items: [
1588
        { label: 'Security', action: () => (dialog = 'security') },
1589
        { label: 'Settings', action: () => (dialog = 'settings') },
1590
        { label: 'Sticker and emoji packs', action: () => (dialog = 'packs') },
1591
        { label: 'Log out', danger: true, divider: true, action: () => void doLogout() }
1592
      ]
1593
    };
1594
  }
1595
1596
  let resizing = false;
1597
1598
  function startResize(ev: PointerEvent, pane: 'side' | 'members'): void {
1599
    if (ev.button !== 0) return;
1600
    ev.preventDefault();
1601
    const handle = ev.currentTarget as HTMLElement;
1602
    handle.setPointerCapture(ev.pointerId);
1603
    const store = pane === 'side' ? sideWidth : membersWidth;
1604
    const range = pane === 'side' ? SIDE_WIDTH : MEMBERS_WIDTH;
1605
    const startX = ev.clientX;
1606
    const startWidth = pane === 'side' ? $sideWidth : $membersWidth;
1607
    resizing = true;
1608
    const move = (e: PointerEvent) => {
1609
      const delta = pane === 'side' ? e.clientX - startX : startX - e.clientX;
1610
      store.set(Math.round(Math.min(range.max, Math.max(range.min, startWidth + delta))));
1611
    };
1612
    const end = () => {
1613
      resizing = false;
1614
      handle.removeEventListener('pointermove', move);
1615
      handle.removeEventListener('pointerup', end);
1616
      handle.removeEventListener('pointercancel', end);
1617
    };
1618
    handle.addEventListener('pointermove', move);
1619
    handle.addEventListener('pointerup', end);
1620
    handle.addEventListener('pointercancel', end);
1621
  }
1622
1623
  function resetWidth(pane: 'side' | 'members'): void {
1624
    if (pane === 'side') sideWidth.set(SIDE_WIDTH.default);
1625
    else membersWidth.set(MEMBERS_WIDTH.default);
1626
  }
1627
1628
  function stopPeeking(): void {
1629
    peeking = null;
1630
    queueReadReceipt();
1631
  }
1632
1633
  async function togglePin(room: RoomSummary): Promise<void> {
1634
    try {
1635
      await runCommand({ op: 'set_favourite', room_id: room.room_id, favourite: !room.favourite });
1636
    } catch (e) {
1637
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin');
1638
    }
1639
  }
1640
1641
  function startRailDrag(ev: DragEvent, id: string): void {
1642
    dragSpaceId = id;
1643
    if (ev.dataTransfer) {
1644
      ev.dataTransfer.effectAllowed = 'move';
1645
      ev.dataTransfer.setData('text/plain', id);
1646
    }
1647
  }
1648
1649
  function overRailSpace(ev: DragEvent, space: RoomSummary): void {
1650
    const dragged = orderedRail.find((s) => s.room_id === dragSpaceId);
1651
    if (!dragged || dragged.room_id === space.room_id || dragged.favourite !== space.favourite) return;
1652
    ev.preventDefault();
1653
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1654
    dropTarget = { id: space.room_id, after: ev.clientY > rect.top + rect.height / 2 };
1655
  }
1656
1657
  async function dropRailSpace(): Promise<void> {
1658
    const moved = dragSpaceId;
1659
    const target = dropTarget;
1660
    dragSpaceId = null;
1661
    dropTarget = null;
1662
    if (!moved || !target) return;
1663
    const ids = orderedRail.map((s) => s.room_id);
1664
    const before = target.after ? (ids[ids.indexOf(target.id) + 1] ?? null) : target.id;
1665
    const order = moveBefore(ids, moved, before === moved ? null : before);
1666
    if (order.join() === ids.join()) return;
1667
    railOverride = order;
1668
    try {
1669
      await runCommand({ op: 'reorder_spaces', order });
1670
    } catch (e) {
1671
      railOverride = null;
1672
      pushBanner(e instanceof Error ? e.message : 'Could not reorder spaces');
1673
    }
1674
  }
1675
1676
  let roomMenuOpen = false;
1677
  let roomMenuEl: HTMLDivElement | null = null;
1678
1679
  function roomMenuAction(action: () => void): void {
1680
    roomMenuOpen = false;
1681
    action();
1682
  }
1683
1684
  function closeRoomMenuOutside(ev: PointerEvent): void {
1685
    if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false;
1686
  }
1687
1688
  function onKeydown(ev: KeyboardEvent): void {
1689
    if (ev.key === 'Escape') {
1690
      if (roomMenuOpen) roomMenuOpen = false;
1691
      else if (dialog) dialog = null;
1692
      else if (membersOpen && window.innerWidth < 1100) membersOpen = false;
1693
      else if (sidebarOpen) sidebarOpen = false;
1694
    }
1695
  }
1696
</script>
1697
1698
<svelte:window
1699
  on:keydown={onKeydown}
1700
  on:pointerdown={closeRoomMenuOutside}
1701
  on:pointerup={() => (draggingScrollbar = false)}
1702
/>
1703
1704
{#if !booted}
1705
  <div class="splash" role="status" aria-label="Loading Malice">
1706
    <div class="splash-mark" aria-hidden="true">M</div>
1707
    <p>Loading Malice…</p>
1708
  </div>
1709
{:else if $blocked}
1710
  <div class="splash" role="status" aria-label="Malice is open in another tab">
1711
    <div class="splash-mark" aria-hidden="true">M</div>
1712
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
1713
  </div>
1714
{:else if $sessionUser == null}
1715
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
1716
{:else}
1717
  <div
1718
    class="app"
1719
    class:nav-folded={$navFolded && selectedRoom}
1720
    class:rail-folded={$railFolded && selectedRoom}
1721
    class:members-open={selectedRoom && membersOpen}
1722
    class:resizing
1723
    style:--side-open={`${$sideWidth}px`}
1724
    style:--members-open={`${$membersWidth}px`}
1725
    style:--msg-gap={`${$messageSpacing}px`}
1726
    style:--msg-line-height={$lineHeight}
1727
  >
1728
    <header class="chat-head">
1729
      <button
1730
        type="button"
1731
        class="icon-btn only-mobile"
1732
        aria-label="Open room list"
1733
        on:click={() => (sidebarOpen = true)}
1734
      >
1735
        <span aria-hidden="true">☰</span>
1736
      </button>
1737
      <button
1738
        type="button"
1739
        class="icon-btn only-desktop pane-toggle"
1740
        aria-pressed={!$railFolded}
1741
        aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1742
        title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1743
        on:click={() => railFolded.update((v) => !v)}
1744
      >
1745
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1746
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1747
          <circle cx="7" cy="9" r="1.4" fill="currentColor" />
1748
          <circle cx="7" cy="13" r="1.4" fill="currentColor" />
1749
          <circle cx="7" cy="17" r="1.4" fill="currentColor" />
1750
        </svg>
1751
      </button>
1752
      <button
1753
        type="button"
1754
        class="icon-btn only-desktop pane-toggle"
1755
        aria-pressed={!$navFolded}
1756
        aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
1757
        title={$navFolded ? 'Show channels' : 'Hide channels'}
1758
        on:click={() => navFolded.update((v) => !v)}
1759
      >
1760
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1761
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1762
          <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
1763
        </svg>
1764
      </button>
1765
      {#if selectedRoom}
1766
      <div class="head-title">
1767
        <div class="head-room">
1768
          <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape="rounded" />
1769
          <div class="head-room-text">
1770
            <h1>{selectedRoom.name}</h1>
1771
            <div class="head-meta">
1772
              {#if selectedRoom.space}
1773
                <span class="pill">space</span>
1774
              {/if}
1775
              {#if selectedRoom.encrypted}
1776
                <span class="pill" title="End-to-end encrypted">🔒 encrypted</span>
1777
              {/if}
1778
              {#if selectedRoom.direct}
1779
                <span class="pill">direct</span>
1780
              {/if}
1781
              {#if $connection !== 'online'}
1782
                <span class="conn" title={`Sync state: ${$connection}`}>
1783
                  <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1784
                  {$connection}
1785
                </span>
1786
              {/if}
1787
            </div>
1788
          </div>
1789
        </div>
1790
      </div>
1791
      {:else}
1792
      <div class="head-title">
1793
        <div class="head-room">
1794
          {#if selectedSpace}
1795
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={36} shape="rounded" />
1796
          {/if}
1797
          <div class="head-room-text">
1798
            <h1>{selectedSpace?.name ?? 'Home'}</h1>
1799
          </div>
1800
        </div>
1801
      </div>
1802
      {/if}
1803
      <div class="head-actions">
1804
        {#if selectedRoom}
1805
        {#if peeking === selectedRoom.room_id}
1806
          <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}>
1807
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1808
              <path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12z" fill="none" stroke="currentColor" stroke-width="2" />
1809
              <circle cx="12" cy="12" r="3" fill="currentColor" />
1810
            </svg>
1811
          </button>
1812
        {/if}
1813
        {#if selectedRoom.membership !== 'Joined'}
1814
          <button
1815
            type="button"
1816
            class="primary-btn"
1817
            disabled={joinBusy}
1818
            on:click={() => void join(selectedRoom.room_id)}
1819
          >
1820
            {joinBusy ? 'Joining…' : 'Join'}
1821
          </button>
1822
        {/if}
1823
        <button
1824
          type="button"
1825
          class="icon-btn"
1826
          aria-pressed={membersOpen}
1827
          aria-label={membersOpen ? 'Hide members' : 'Show members'}
1828
          title="Members"
1829
          on:click={toggleMembers}
1830
        >
1831
          <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1832
            <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
1833
            <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
1834
          </svg>
1835
        </button>
1836
        <div class="room-menu-wrap" bind:this={roomMenuEl}>
1837
          <button
1838
            type="button"
1839
            class="icon-btn"
1840
            aria-haspopup="menu"
1841
            aria-expanded={roomMenuOpen}
1842
            aria-label="Room options"
1843
            title="Room options"
1844
            on:click={() => (roomMenuOpen = !roomMenuOpen)}
1845
          >
1846
            <span aria-hidden="true">⋯</span>
1847
          </button>
1848
          {#if roomMenuOpen}
1849
            <div class="room-menu" role="menu">
1850
              <button type="button" role="menuitem" on:click={() => roomMenuAction(() => (dialog = 'security'))}>
1851
                Security
1852
              </button>
1853
              {#if selectedRoom.membership === 'Joined'}
1854
                <button
1855
                  type="button"
1856
                  role="menuitem"
1857
                  class="danger"
1858
                  disabled={leaveBusy}
1859
                  on:click={() => roomMenuAction(() => void leave())}
1860
                >
1861
                  {leaveBusy ? 'Leaving…' : 'Leave room'}
1862
                </button>
1863
              {/if}
1864
            </div>
1865
          {/if}
1866
        </div>
1867
        {/if}
1868
      </div>
1869
    </header>
1870
1871
    <nav class="rail" aria-label="Servers and spaces">
1872
      <button
1873
        type="button"
1874
        class="rail-btn"
1875
        class:active={selectedSpaceId === null}
1876
        title="Home — all channels"
1877
        aria-label="Home — all channels"
1878
        aria-pressed={selectedSpaceId === null}
1879
        on:click={() => void selectHome()}
1880
      >
1881
        <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true"><path d="M4 11l8-7 8 7v8a1 1 0 0 1-1 1h-4v-6H9v6H5a1 1 0 0 1-1-1z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
1882
      </button>
1883
      {#each [pinnedRail, otherRail] as group}
1884
        {#if group.length > 0}
1885
          <div class="rail-sep" aria-hidden="true"></div>
1886
        {/if}
1887
        {#each group as space (space.room_id)}
1888
          <button
1889
            type="button"
1890
            class="rail-btn rail-space"
1891
            class:active={railSelected === space.room_id}
1892
            class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after}
1893
            class:drop-after={dropTarget?.id === space.room_id && dropTarget.after}
1894
            class:pinned={space.favourite}
1895
            title={space.name}
1896
            aria-label={`Show channels in space ${space.name}`}
1897
            aria-pressed={selectedSpaceId === space.room_id}
1898
            draggable="true"
1899
            on:click={() => void selectSpace(space.room_id)}
1900
            on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)}
1901
            on:dragstart={(ev) => startRailDrag(ev, space.room_id)}
1902
            on:dragover={(ev) => overRailSpace(ev, space)}
1903
            on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)}
1904
            on:drop|preventDefault={() => void dropRailSpace()}
1905
            on:dragend={() => ((dragSpaceId = null), (dropTarget = null))}
1906
          >
1907
            <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
1908
          </button>
1909
        {/each}
1910
      {/each}
1911
      <button
1912
        type="button"
1913
        class="rail-btn rail-add"
1914
        aria-label="Join or create a room"
1915
        on:click={() => {
1916
          dialog = 'join';
1917
        }}
1918
      >
1919
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" /></svg>
1920
      </button>
1921
    </nav>
1922
1923
    {#if menu}
1924
      <ContextMenu items={menu.items} x={menu.x} y={menu.y} above={menu.above ?? false} onClose={() => (menu = null)} />
1925
    {/if}
1926
    {#if userCard}
1927
      {#key userCard}
1928
        {@const cardUser = userCard.userId}
1929
        <UserCard
1930
          person={personFor(cardUser)}
1931
          member={memberFor(cardUser)}
1932
          levels={roomLevels}
1933
          self={$sessionUser ?? null}
1934
          x={userCard.x}
1935
          y={userCard.y}
1936
          confirm={userCard.confirm}
1937
          onAction={(action) => void userAction(cardUser, action)}
1938
          onClose={() => (userCard = null)}
1939
        />
1940
      {/key}
1941
    {/if}
1942
1943
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
1944
      <!-- svelte-ignore a11y_no_static_element_interactions -->
1945
      <div class="pane-resize right" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'side')} on:dblclick={() => resetWidth('side')}></div>
1946
      <div class="side-search">
1947
        <label class="visually-hidden" for="room-search">Search rooms</label>
1948
        <input
1949
          id="room-search"
1950
          type="search"
1951
          placeholder="Search rooms"
1952
          bind:value={search}
1953
          autocomplete="off"
1954
        />
1955
        <button
1956
          type="button"
1957
          class="icon-btn"
1958
          title="Refresh rooms"
1959
          aria-label="Refresh rooms"
1960
          disabled={roomsLoading}
1961
          on:click={() => void refreshRooms()}
1962
        >
1963
          <span aria-hidden="true">⟳</span>
1964
        </button>
1965
      </div>
1966
      <div class="side-scroll">
1967
        {#if selectedSpace && spaceParents.has(selectedSpace.room_id)}
1968
          {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
1969
          <button type="button" class="room-row up-row" on:click={() => void selectSpace(parentId)}>
1970
            <span aria-hidden="true">↑</span>
1971
            <span class="room-name">{$rooms.find((r) => r.room_id === parentId)?.name ?? 'Parent space'}</span>
1972
          </button>
1973
        {/if}
1974
        {#if roomsLoading && $rooms.length === 0}
1975
          <p class="side-note">Loading rooms…</p>
1976
        {:else if $rooms.length === 0}
1977
          <p class="side-note">No rooms yet</p>
1978
          <div class="side-cta">
1979
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
1980
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
1981
          </div>
1982
        {:else}
1983
          {#if selectedSpaceId && spaceChildrenLoading}
1984
            <p class="side-note">Loading channels…</p>
1985
          {:else if selectedSpaceId && spaceChildrenError}
1986
            <p class="side-note" role="alert">{spaceChildrenError}</p>
1987
            <div class="side-cta">
1988
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
1989
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1990
            </div>
1991
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
1992
            <p class="side-note">No channels</p>
1993
            <div class="side-cta">
1994
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1995
            </div>
1996
          {:else}
1997
            {#if invites.length > 0 && !selectedSpaceId}
1998
              <h2 class="side-h">Invites</h2>
1999
              <ul class="room-list">
2000
                {#each invites as room (room.room_id)}
2001
                  <li>
2002
                    <button
2003
                      type="button"
2004
                      class="room-row"
2005
                      class:active={$selectedRoomId === room.room_id}
2006
                      on:click={() => void selectRoom(room.room_id)}
2007
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2008
                    >
2009
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2010
                      <span class="room-name">{room.name}</span>
2011
                      <span
2012
                        class="invite-join"
2013
                        role="button"
2014
                        tabindex="0"
2015
                        aria-label={`Join ${room.name}`}
2016
                        on:click|stopPropagation={() => void join(room.room_id)}
2017
                        on:keydown|stopPropagation={(ev) => {
2018
                          if (ev.key === 'Enter' || ev.key === ' ') {
2019
                            ev.preventDefault();
2020
                            void join(room.room_id);
2021
                          }
2022
                        }}
2023
                      >
2024
                        Join
2025
                      </span>
2026
                    </button>
2027
                  </li>
2028
                {/each}
2029
              </ul>
2030
            {/if}
2031
2032
            {#if directRooms.length > 0}
2033
              <h2 class="side-h">Direct messages</h2>
2034
              <ul class="room-list">
2035
                {#each directRooms as room (room.room_id)}
2036
                  <li class="room-item">
2037
                    <button
2038
                      type="button"
2039
                      class="room-row"
2040
                      class:active={$selectedRoomId === room.room_id}
2041
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2042
                      on:click={() => void selectRoom(room.room_id)}
2043
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2044
                    >
2045
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
2046
                      <span class="room-name">{room.name}</span>
2047
                      {#if roomUnread(room) > 0}
2048
                        <span
2049
                          class="badge"
2050
                          class:mention={room.unread_mentions > 0}
2051
                          aria-label={`${roomUnread(room)} unread`}
2052
                        >
2053
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2054
                        </span>
2055
                      {/if}
2056
                    </button>
2057
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2058
                  </li>
2059
                {/each}
2060
              </ul>
2061
            {/if}
2062
2063
            {#if groupRooms.length > 0}
2064
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
2065
              <ul class="room-list">
2066
                {#each groupRooms as room (room.room_id)}
2067
                  <li class="room-item">
2068
                    <button
2069
                      type="button"
2070
                      class="room-row"
2071
                      class:active={$selectedRoomId === room.room_id}
2072
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2073
                      on:click={() => void selectRoom(room.room_id)}
2074
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2075
                    >
2076
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2077
                      <span class="room-name">{room.name}</span>
2078
                      {#if roomUnread(room) > 0}
2079
                        <span
2080
                          class="badge"
2081
                          class:mention={room.unread_mentions > 0}
2082
                          aria-label={`${roomUnread(room)} unread`}
2083
                        >
2084
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2085
                        </span>
2086
                      {/if}
2087
                    </button>
2088
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2089
                  </li>
2090
                {/each}
2091
              </ul>
2092
            {/if}
2093
2094
            {#if spaceList.length > 0}
2095
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
2096
              <ul class="room-list">
2097
                {#each spaceList as room (room.room_id)}
2098
                  <li class="room-item">
2099
                    <button
2100
                      type="button"
2101
                      class="room-row"
2102
                      class:active={selectedSpaceId === room.room_id}
2103
                      aria-label={`Show channels in space ${room.name}`}
2104
                      on:click={() => void selectSpace(room.room_id)}
2105
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2106
                    >
2107
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2108
                      <span class="room-name">{room.name}</span>
2109
                    </button>
2110
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2111
                  </li>
2112
                {/each}
2113
              </ul>
2114
            {/if}
2115
2116
            {#if query && visibleRooms.length === 0}
2117
              <p class="side-note">No rooms match “{search.trim()}”.</p>
2118
            {/if}
2119
          {/if}
2120
        {/if}
2121
      </div>
2122
2123
    </aside>
2124
    <div class="account">
2125
      <button type="button" class="me-btn" title={$sessionUser} aria-haspopup="menu" on:click={openAccountMenu}>
2126
        {#if profileMxc}
2127
          <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={32} />
2128
        {:else}
2129
          <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
2130
        {/if}
2131
        <span class="me-names">
2132
          <span class="me-name">{profile?.display_name || $sessionUser}</span>
2133
          {#if profile?.display_name && profile.display_name !== $sessionUser}<span class="me-id">{$sessionUser}</span>{/if}
2134
        </span>
2135
      </button>
2136
      <div class="account-actions">
2137
        <button type="button" class="icon-btn" title="Encryption and verification" aria-label="Encryption and verification" on:click={() => (dialog = 'security')}>
2138
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path d="M12 3l8 3v6c0 4.5-3.4 8.2-8 9-4.6-.8-8-4.5-8-9V6z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
2139
        </button>
2140
        <button type="button" class="icon-btn" title="Settings" aria-label="Settings" on:click={() => (dialog = 'settings')}>
2141
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="1.8" /><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1L7 17M17 7l2.1-2.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2142
        </button>
2143
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
2144
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path d="M12 3v8M6.3 6.3a8 8 0 1 0 11.4 0" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2145
        </button>
2146
      </div>
2147
    </div>
2148
    {#if sidebarOpen}
2149
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
2150
    {/if}
2151
2152
    <main class="chat">
2153
        {#if $banners.length > 0}
2154
          <div class="banners" aria-live="polite">
2155
            {#each $banners as banner (banner.id)}
2156
              <div class="banner" role="alert">
2157
                <span>{banner.message}</span>
2158
                <button
2159
                  type="button"
2160
                  aria-label="Dismiss error"
2161
                  on:click={() => dismissBanner(banner.id)}
2162
                >
2163
                  ✕
2164
                </button>
2165
              </div>
2166
            {/each}
2167
          </div>
2168
        {/if}
2169
      {#if !selectedRoom}
2170
        <div class="empty">
2171
          <div class="empty-mark" aria-hidden="true">◈</div>
2172
          {#if selectedSpace}
2173
            <h1>{selectedSpace.name}</h1>
2174
          {:else}
2175
            <h1>Welcome to Malice</h1>
2176
          {/if}
2177
          <div class="empty-cta">
2178
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
2179
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
2180
          </div>
2181
          <p class="conn-line">
2182
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
2183
            {$connection}
2184
          </p>
2185
        </div>
2186
      {:else}
2187
        {#if pins.length}
2188
          <div class="pinned-strip" class:open={pinsExpanded}>
2189
            <div class="pinned-head">
2190
              <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M9 3h6l-1 6 4 4v2h-5v6l-1 1-1-1v-6H6v-2l4-4z" fill="currentColor" /></svg>
2191
              <button type="button" class="pinned-latest" title="Jump to pinned message" on:click={() => jumpToPin(pins[0].event_id ?? '')}>
2192
                <strong>{people[pins[0].sender.user_id]?.name ?? senderLabel(pins[0].sender)}</strong>
2193
                <span>{contentPreview(pins[0].content)}</span>
2194
              </button>
2195
              {#if pins.length > 1}
2196
                <button type="button" class="pinned-count" aria-expanded={pinsExpanded} on:click={() => (pinsExpanded = !pinsExpanded)}>
2197
                  {pins.length} pinned
2198
                  <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true"><path d="m6 9 6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" /></svg>
2199
                </button>
2200
              {/if}
2201
              {#if pinsExpanded && selectedRoom.can_pin}
2202
                <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pins[0].event_id ?? '', false)}>
2203
                  <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" /></svg>
2204
                </button>
2205
              {/if}
2206
            </div>
2207
            {#if pinsExpanded}
2208
              <ul class="pinned-list">
2209
                {#each pins.slice(1) as pin (pin.event_id)}
2210
                  <li>
2211
                    <button type="button" on:click={() => jumpToPin(pin.event_id ?? '')}>
2212
                      <strong>{people[pin.sender.user_id]?.name ?? senderLabel(pin.sender)}</strong>
2213
                      <span>{contentPreview(pin.content)}</span>
2214
                    </button>
2215
                    {#if selectedRoom.can_pin}
2216
                      <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pin.event_id ?? '', false)}>
2217
                        <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" /></svg>
2218
                      </button>
2219
                    {/if}
2220
                  </li>
2221
                {/each}
2222
              </ul>
2223
            {/if}
2224
          </div>
2225
        {/if}
2226
        {#if recoveryBanner}
2227
          <div class="sec-banner warn" role="status">
2228
            <span>Message history is locked</span>
2229
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
2230
          </div>
2231
        {/if}
2232
        {#if verificationBanner}
2233
          <div class="sec-banner" role="status">
2234
            {#if verificationBanner.kind === 'Incoming'}
2235
              <span>A device wants to verify this session</span>
2236
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
2237
            {:else if verificationBanner.kind === 'Comparison'}
2238
              <span>Verification codes ready</span>
2239
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
2240
            {:else if verificationBanner.kind === 'Waiting'}
2241
              <span>Verification started</span>
2242
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
2243
            {:else if verificationBanner.kind === 'Failed'}
2244
              <span>Verification failed: {verificationBanner.message}</span>
2245
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
2246
            {:else if verificationBanner.kind === 'Cancelled'}
2247
              <span>Verification cancelled: {verificationBanner.reason}</span>
2248
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2249
            {:else}
2250
              <span>Verification in progress</span>
2251
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2252
            {/if}
2253
          </div>
2254
        {/if}
2255
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
2256
          <p class="conn-banner error" role="alert">{openFailed[$selectedRoomId]}</p>
2257
        {/if}
2258
2259
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2260
        <div
2261
          class="timeline"
2262
          bind:this={timelineEl}
2263
          on:scroll={onTimelineScroll}
2264
          on:wheel={noteUserScroll}
2265
          on:touchmove={noteUserScroll}
2266
          on:keydown={onTimelineKey}
2267
          on:pointerdown={onTimelinePointer}
2268
          aria-label={`Messages in ${selectedRoom.name}`}
2269
        >
2270
          <div class="timeline-inner" use:pinTimeline>
2271
            <div class="timeline-top">
2272
              {#if hasStart}
2273
                <p class="start-note">Beginning of history</p>
2274
              {:else}
2275
                <button type="button" class="ghost-btn" disabled={paginateBusy} on:click={() => void paginate()}>
2276
                  {paginateBusy ? 'Loading…' : 'Load older messages'}
2277
                </button>
2278
              {/if}
2279
            </div>
2280
            {#if grouped.length === 0}
2281
              <p class="side-note timeline-empty">No messages yet</p>
2282
            {:else}
2283
              {#each grouped as g (g.key)}
2284
                {#if g.item.kind === 'day'}
2285
                  <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div>
2286
                {:else if g.item.kind === 'readMarker'}
2287
                  <div class="new-row"><span>New</span></div>
2288
                {:else if g.item.kind === 'start'}
2289
                  <p class="start-note">Beginning of history</p>
2290
                {:else if g.item.kind === 'unknown'}
2291
                  <p class="unknown-note">Unsupported event ({g.item.label})</p>
2292
                {:else}
2293
                  <MessageRow
2294
                    itemId={g.key}
2295
                    event={g.item.event}
2296
                    showSender={g.showSender}
2297
                    senderAvatar={senderAvatarFor(g.item.event.sender.user_id) ?? g.item.event.sender.avatar}
2298
                    {reacting}
2299
                    onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2300
                    quickReactions={$quickReactions}
2301
                    packs={roomPacks}
2302
                    linkPreviews={$linkPreviews}
2303
                    {loadPreview}
2304
                    onQuickChange={(list) => void changeQuickReactions(list)}
2305
                    {people}
2306
                    self={$sessionUser ?? null}
2307
                    onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2308
                    onCloneSticker={openCloneStickerMenu}
2309
                    onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2310
                    onReply={selectedRoom.membership === 'Joined' ? startReply : null}
2311
                    onJump={jumpTo}
2312
                    onEdit={selectedRoom.membership === 'Joined' ? startEdit : null}
2313
                    editing={editing !== null && editing.eventId === g.item.event.event_id}
2314
                    showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0}
2315
                  />
2316
                {/if}
2317
              {/each}
2318
            {/if}
2319
            {#each pendingItems as p, i (p.id)}
2320
              <MessageRow
2321
                itemId={`pending-${p.id}`}
2322
                event={pendingToEvent(p)}
2323
                onJump={jumpTo}
2324
                showSender={pendingShowSender(i)}
2325
                senderAvatar={senderAvatarFor($sessionUser ?? '')}
2326
                {reacting}
2327
                onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2328
                quickReactions={$quickReactions}
2329
                packs={roomPacks}
2330
                linkPreviews={$linkPreviews}
2331
                {loadPreview}
2332
                onQuickChange={(list) => void changeQuickReactions(list)}
2333
              />
2334
              {#if p.status === 'failed'}
2335
                <div class="pending-actions">
2336
                  <span class="pending-error" role="alert">{p.error}</span>
2337
                  <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button>
2338
                  <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button>
2339
                </div>
2340
              {/if}
2341
            {/each}
2342
          </div>
2343
        </div>
2344
2345
        {#if selectedRoom.membership === 'Joined'}
2346
          {#if editing}
2347
            <div class="reply-bar" role="status">
2348
              <span class="reply-bar-label">
2349
                Editing message
2350
                <span class="reply-bar-text">{editing.original}</span>
2351
              </span>
2352
              <button type="button" class="icon-btn" aria-label="Cancel edit" title="Cancel edit (Esc)" on:click={cancelEdit}>
2353
                <span aria-hidden="true">✕</span>
2354
              </button>
2355
            </div>
2356
          {:else if replyingTo && replyingTo.details.kind === 'Ready'}
2357
            <div class="reply-bar" role="status">
2358
              <span class="reply-bar-label">
2359
                Replying to <strong>{people[replyingTo.details.sender.user_id]?.name ?? senderLabel(replyingTo.details.sender)}</strong>
2360
                <span class="reply-bar-text">{contentPreview(replyingTo.details.content)}</span>
2361
              </span>
2362
              <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}>
2363
                <span aria-hidden="true">✕</span>
2364
              </button>
2365
            </div>
2366
          {/if}
2367
          {#if $selectedRoomId && currentStaged.length > 0}
2368
            {@const stagedRoom = $selectedRoomId}
2369
            <ul class="staged" aria-label="Attachments to send">
2370
              {#each currentStaged as attachment (attachment.id)}
2371
                <li class="staged-item">
2372
                  {#if attachment.previewUrl}
2373
                    <img src={attachment.previewUrl} alt={attachment.file.name || 'Pasted image'} />
2374
                  {:else}
2375
                    <span class="staged-name">{attachment.file.name || 'attachment'}</span>
2376
                  {/if}
2377
                  <button
2378
                    type="button"
2379
                    class="icon-btn staged-remove"
2380
                    aria-label={`Remove ${attachment.file.name || 'attachment'}`}
2381
                    title="Remove"
2382
                    on:click={() => unstage(stagedRoom, attachment.id)}
2383
                  >
2384
                    <span aria-hidden="true">✕</span>
2385
                  </button>
2386
                </li>
2387
              {/each}
2388
            </ul>
2389
          {/if}
2390
          <form class="composer" class:replying={replyingTo || editing} class:staging={currentStaged.length > 0} on:submit|preventDefault={() => send()}>
2391
            <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label>
2392
            <input
2393
              type="file"
2394
              multiple
2395
              bind:this={fileInput}
2396
              class="visually-hidden"
2397
              aria-label="Attach a file"
2398
              on:change={() => void onFileChosen()}
2399
            />
2400
            <input
2401
              type="file"
2402
              accept="image/*"
2403
              bind:this={avatarInput}
2404
              class="visually-hidden"
2405
              aria-label="Choose a new avatar"
2406
              on:change={() => void onAvatarChosen()}
2407
            />
2408
            <button
2409
              type="button"
2410
              class="icon-btn"
2411
              class:busy={uploadBusy}
2412
              title={uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : 'Attach an image or file'}
2413
              aria-label="Attach an image or file"
2414
              aria-busy={uploadBusy}
2415
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2416
              on:click={pickFiles}
2417
            >
2418
              <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true">
2419
                <path d="M20 11.5l-8.2 8.2a5 5 0 0 1-7-7L13 4.4a3.3 3.3 0 0 1 4.7 4.7l-8.2 8.2a1.7 1.7 0 0 1-2.4-2.4l7.5-7.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
2420
              </svg>
2421
            </button>
2422
            <button
2423
              type="button"
2424
              class="icon-btn sticker-btn"
2425
              title="Stickers"
2426
              aria-label="Stickers"
2427
              aria-expanded={stickersOpen}
2428
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2429
              on:click={() => (stickersOpen = !stickersOpen)}
2430
            >
2431
              <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true">
2432
                <path d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v7l-7 7H6a2 2 0 0 1-2-2z" fill="none" stroke="currentColor" stroke-width="1.8" />
2433
                <path d="M13 20v-5a2 2 0 0 1 2-2h5" fill="none" stroke="currentColor" stroke-width="1.8" />
2434
              </svg>
2435
            </button>
2436
            {#if stickersOpen && $selectedRoomId}
2437
              {@const stickerRoom = $selectedRoomId}
2438
              <div class="sticker-pop">
2439
                <StickerPicker
2440
                  packs={roomPacks}
2441
                  {roomName}
2442
                  onSend={(pack, image) => void sendSticker(stickerRoom, pack, image)}
2443
                  onClone={(pack, image, x, y) => openCloneImageMenu(pack, image, x, y)}
2444
                  onClonePack={(pack, x, y) => openClonePackMenu(pack, x, y)}
2445
                  onManage={() => ((stickersOpen = false), (dialog = 'packs'))}
2446
                  onClose={() => (stickersOpen = false)}
2447
                />
2448
              </div>
2449
            {/if}
2450
            <div class="composer-field">
2451
              {#if commandQuery !== null && commandCandidates.length > 0}
2452
                <ul class="mention-finder" role="listbox" aria-label="Commands">
2453
                  {#each commandCandidates as name, i (name)}
2454
                    <li
2455
                      role="option"
2456
                      aria-selected={i === commandIndex}
2457
                      class:active={i === commandIndex}
2458
                      on:pointerdown|preventDefault={() => void pickCommand(name)}
2459
                      on:pointerenter={() => (commandIndex = i)}
2460
                    >
2461
                      <span class="mention-name">/{name}</span>
2462
                      <span class="mention-id">{COMMAND_USAGE[name]}</span>
2463
                    </li>
2464
                  {/each}
2465
                </ul>
2466
              {/if}
2467
              {#if emoteQuery && emoteCandidates.length > 0}
2468
                <ul class="mention-finder" role="listbox" aria-label="Emotes">
2469
                  {#each emoteCandidates as candidate, i (candidate.kind + candidate.shortcode)}
2470
                    <li
2471
                      role="option"
2472
                      aria-selected={i === emoteIndex}
2473
                      class:active={i === emoteIndex}
2474
                      on:pointerdown|preventDefault={() => void pickEmote(candidate)}
2475
                      on:pointerenter={() => (emoteIndex = i)}
2476
                    >
2477
                      {#if candidate.kind === 'custom'}
2478
                        <img class="finder-emote" src={mediaUrl(candidate.mxc) ?? ''} alt="" />
2479
                      {:else}
2480
                        <span class="finder-emote"><EmojiText text={candidate.emoji} /></span>
2481
                      {/if}
2482
                      <span class="mention-name">:{candidate.shortcode}:</span>
2483
                    </li>
2484
                  {/each}
2485
                </ul>
2486
              {/if}
2487
              {#if mentionQuery && mentionCandidates.length > 0}
2488
                <ul class="mention-finder" role="listbox" aria-label="Mention someone">
2489
                  {#each mentionCandidates as person, i (person.user_id)}
2490
                    <li
2491
                      role="option"
2492
                      aria-selected={i === mentionIndex}
2493
                      class:active={i === mentionIndex}
2494
                      on:pointerdown|preventDefault={() => void pickMention(person)}
2495
                      on:pointerenter={() => (mentionIndex = i)}
2496
                    >
2497
                      <MxcAvatar mxc={person.avatar} label={person.name} size={22} />
2498
                      <span class="mention-name">{person.name}</span>
2499
                      <span class="mention-id">{person.user_id}</span>
2500
                    </li>
2501
                  {/each}
2502
                </ul>
2503
              {/if}
2504
            <div class="composer-marks" aria-hidden="true" bind:this={marksEl}>{#each composerMarks as part}{#if part.mark}<mark>{part.text}</mark>{:else}{part.text}{/if}{/each}&#8203;</div>
2505
            <textarea
2506
              id="composer"
2507
              bind:this={composerEl}
2508
              bind:value={composer}
2509
              rows="1"
2510
              placeholder={`Message ${selectedRoom.name}`}
2511
              aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`}
2512
              on:keydown={onComposerKey}
2513
              on:input={() => void onComposerInput()}
2514
              on:click={updateMentionQuery}
2515
              on:focus={ensureEmoji}
2516
              on:keyup={(e) => (e.key.startsWith('Arrow') && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') || e.key === 'Home' || e.key === 'End' ? updateMentionQuery() : undefined}
2517
              on:blur={() => ((mentionQuery = null), (commandQuery = null), (emoteQuery = null))}
2518
              on:paste={onComposerPaste}
2519
              on:scroll={() => marksEl && composerEl && (marksEl.scrollTop = composerEl.scrollTop)}
2520
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2521
            ></textarea>
2522
            </div>
2523
            <button
2524
              type="button"
2525
              class="icon-btn"
2526
              aria-pressed={$markdownEnabled}
2527
              aria-label={$markdownEnabled ? 'Turn markdown off' : 'Turn markdown on'}
2528
              title={$markdownEnabled ? 'Markdown on' : 'Markdown off'}
2529
              on:click={() => markdownEnabled.update((v) => !v)}
2530
            >
2531
              <svg viewBox="0 0 24 16" width="21" height="14" aria-hidden="true">
2532
                <rect x="1" y="1" width="22" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="1.6" />
2533
                <path d="M4.5 11.5v-7l2.75 3 2.75-3v7M15.5 4.5v6.5M13 8.5l2.5 2.75L18 8.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" />
2534
              </svg>
2535
            </button>
2536
            <button
2537
              type="submit"
2538
              class="primary-btn"
2539
              disabled={(!composer.trim() && currentStaged.length === 0) ||
2540
                !($selectedRoomId && openReady[$selectedRoomId]) ||
2541
                (currentStaged.length > 0 && uploadBusy)}
2542
              title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'}
2543
            >
2544
              Send
2545
            </button>
2546
          </form>
2547
        {:else}
2548
          <div class="join-bar">
2549
            <p>You are not a member of this room.</p>
2550
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
2551
              {joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`}
2552
            </button>
2553
          </div>
2554
        {/if}
2555
      {/if}
2556
    </main>
2557
2558
    {#if selectedRoom}
2559
      <aside class="members" aria-hidden={!membersOpen} aria-label={`Members of ${selectedRoom.name}`}>
2560
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2561
        <div class="pane-resize left" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'members')} on:dblclick={() => resetWidth('members')}></div>
2562
        <div class="members-head">
2563
          <h2>Members</h2>
2564
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
2565
            <span aria-hidden="true">✕</span>
2566
          </button>
2567
        </div>
2568
        {#if $membersLoading && members.length === 0}
2569
          <p class="side-note">Loading members…</p>
2570
        {:else if members.length === 0}
2571
          <p class="side-note">No members loaded.</p>
2572
          {#if $selectedRoomId}
2573
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
2574
              Retry
2575
            </button>
2576
          {/if}
2577
        {:else}
2578
          <ul class="member-list">
2579
            {#each members as member (member.user_id)}
2580
              <li>
2581
                <button
2582
                  type="button"
2583
                  class="member"
2584
                  on:click={(ev) => {
2585
                    const rect = ev.currentTarget.getBoundingClientRect();
2586
                    void openUser(member.user_id, rect.left - 308, rect.top, false);
2587
                  }}
2588
                  on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)}
2589
                >
2590
                  <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} seed={member.user_id} size={28} />
2591
                  <span class="member-names">
2592
                    <span class="member-name">{member.display_name || member.name}</span>
2593
                    <span class="member-id">{member.user_id}</span>
2594
                  </span>
2595
                </button>
2596
              </li>
2597
            {/each}
2598
          </ul>
2599
        {/if}
2600
      </aside>
2601
    {/if}
2602
2603
    {#if dialog}
2604
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
2605
        {#if dialog === 'security'}
2606
          <SecurityPanel
2607
            encryptionState={$encryption}
2608
            verificationState={$verification}
2609
            onAction={() => void loadEncryption()}
2610
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
2611
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
2612
            on:close={() => (dialog = null)}
2613
          />
2614
        {:else if dialog === 'settings'}
2615
          <SettingsPanel
2616
            quick={$quickReactions}
2617
            packs={roomPacks}
2618
            onQuickChange={(list) => void changeQuickReactions(list)}
2619
            on:close={() => (dialog = null)}
2620
            on:packs={() => (dialog = 'packs')}
2621
          />
2622
        {:else if dialog === 'packs'}
2623
          <PackManager packs={$imagePacks} rooms={$rooms} onError={pushBanner} on:close={() => (dialog = null)} />
2624
        {:else}
2625
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
2626
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
2627
              <button
2628
                type="button"
2629
                role="tab"
2630
                aria-selected={dialog === 'join'}
2631
                class:active={dialog === 'join'}
2632
                on:click={() => (dialog = 'join')}
2633
              >
2634
                Join
2635
              </button>
2636
              <button
2637
                type="button"
2638
                role="tab"
2639
                aria-selected={dialog === 'create'}
2640
                class:active={dialog === 'create'}
2641
                on:click={() => (dialog = 'create')}
2642
              >
2643
                Create
2644
              </button>
2645
              <button
2646
                type="button"
2647
                class="icon-btn modal-x"
2648
                aria-label="Close dialog"
2649
                on:click={() => (dialog = null)}
2650
              >
2651
                <span aria-hidden="true">✕</span>
2652
              </button>
2653
            </div>
2654
            {#if dialog === 'join'}
2655
              <form on:submit|preventDefault={() => void join(joinTarget)}>
2656
                <label class="field">
2657
                  <span>Room ID or alias</span>
2658
                  <input
2659
                    type="text"
2660
                    placeholder="!room:example.org or #alias:example.org"
2661
                    bind:value={joinTarget}
2662
                    required
2663
                    disabled={joinBusy}
2664
                  />
2665
                </label>
2666
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
2667
                  {joinBusy ? 'Joining…' : 'Join room'}
2668
                </button>
2669
              </form>
2670
            {:else}
2671
            <form on:submit|preventDefault={() => void create()}>
2672
              <label class="field">
2673
                <span>Room name</span>
2674
                <input
2675
                  type="text"
2676
                  placeholder="Weekend plans"
2677
                  bind:value={createName}
2678
                  required
2679
                  disabled={createBusy}
2680
                />
2681
              </label>
2682
              <label class="field">
2683
                <span>Topic (optional)</span>
2684
                <input
2685
                  type="text"
2686
                  placeholder="What should this room be about?"
2687
                  bind:value={createTopic}
2688
                  disabled={createBusy}
2689
                />
2690
              </label>
2691
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
2692
                {createBusy ? 'Creating…' : 'Create room'}
2693
              </button>
2694
            </form>
2695
            {/if}
2696
          </div>
2697
        {/if}
2698
      </div>
2699
    {/if}
2700
  </div>
2701
{/if}
2702
2703
<ImageLightbox />