atagen

malice

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