atagen

malice

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