atagen

malice

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