atagen

malice

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