atagen

malice

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