atagen

malice

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