atagen

malice

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