atagen

malice

public
Star0
Watch0
d8624c214c044f548c0a9b7cbcae6d081c88cca8
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte2250 lines85.0 KB
1
<script lang="ts">
2
  import { onMount, tick } from 'svelte';
3
  import LoginPanel from './lib/LoginPanel.svelte';
4
  import MessageRow from './lib/MessageRow.svelte';
5
  import MxcAvatar from './lib/MxcAvatar.svelte';
6
  import PinButton from './lib/PinButton.svelte';
7
  import ContextMenu, { type MenuItem } from './lib/ContextMenu.svelte';
8
  import UserCard, { type UserAction } from './lib/UserCard.svelte';
9
  import { allowed, isMuted, parsePowerLevels, type PowerLevels } from './lib/permissions';
10
  import { moveBefore, pinnedFirst, sortSpaces } from './lib/rail-order';
11
  import ImageLightbox from './lib/ImageLightbox.svelte';
12
  import { lightbox } from './lib/lightbox';
13
  import SecurityPanel from './lib/SecurityPanel.svelte';
14
  import {
15
    closeRoom,
16
    createRoom,
17
    getEncryption,
18
    getMembers,
19
    getProfile,
20
    getRooms,
21
    getSession,
22
    getSpaceChildren,
23
    joinRoom,
24
    leaveRoom,
25
    logout,
26
    markRead,
27
    openRoom,
28
    paginateRoom,
29
    reactToMessage,
30
    runCommand,
31
    sendMessage,
32
    uploadAttachment,
33
    uploadAvatar,
34
    uploadRoomAvatar,
35
    editMessage
36
  } from './lib/api';
37
  import { isKnownCommand, parseCommand, splitTarget, unescapeCommand } from './lib/commands';
38
  import type { ParsedCommand } from './lib/commands';
39
  import {
40
    banners,
41
    blocked,
42
    connectEvents,
43
    connection,
44
    disconnectEvents,
45
    dismissBanner,
46
    encryption,
47
    membersByRoom,
48
    membersLoading,
49
    pushBanner,
50
    imagePacks,
51
    resetClientState,
52
    rooms,
53
    selectedRoomId,
54
    sessionUser,
55
    softLogout,
56
    timelines,
57
    verification
58
  } from './lib/store';
59
  import { discardPending, pendingByRoom, queueSend, resetPending, retryPending } from './lib/pending';
60
  import type { PendingMessage } from './lib/pending';
61
  import { insideOpenFence } from './lib/markdown';
62
  import { mentionQueryAt, mentionsFromHtml, rankPeople, resolveMentions } from './lib/mentions';
63
  import type { Mention, MentionQuery } from './lib/mentions';
64
  import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions';
65
  import {
66
    linkPreviews,
67
    loadUrlPreviewSettings,
68
    requestLinkPreview,
69
    saveUrlPreviewSettings,
70
    urlPreviewSettings
71
  } from './lib/link-previews';
72
  import { notifyTyping, stopTyping } from './lib/typing';
73
  import { formatDay } from './lib/format';
74
  import { lastSpaceRooms, lineHeight, markdownEnabled, messageSpacing, navFolded, railFolded } from './lib/appearance';
75
  import SettingsPanel from './lib/SettingsPanel.svelte';
76
  import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types';
77
  import type { MemberSummary, OwnProfile, Person, QuickReaction, ReplyReference, RoomSummary, SendState, TimelineEvent, TimelineItem } from './lib/types';
78
79
  let roomsLoading = false;
80
  let booted = false;
81
  let wasOnline = false;
82
  let search = '';
83
  let sidebarOpen = false;
84
  let membersOpen = false;
85
  let replyingTo: ReplyReference | null = null;
86
  let dialog: 'join' | 'create' | 'security' | 'settings' | null = null;
87
  let joinTarget = '';
88
  let joinBusy = false;
89
  let createName = '';
90
  let createTopic = '';
91
  let createBusy = false;
92
  let leaveBusy = false;
93
  let paginateBusy = false;
94
  let reacting = false;
95
  let composer = '';
96
  let drafts: Record<string, string> = {};
97
  let stickToBottom = true;
98
  let timelineEl: HTMLElement | null = null;
99
  let composerEl: HTMLTextAreaElement | null = null;
100
  let fileInput: HTMLInputElement | null = null;
101
  let avatarInput: HTMLInputElement | null = null;
102
  let uploadBusy = false;
103
  let uploadName: string | null = null;
104
  interface StagedAttachment {
105
    id: number;
106
    file: File;
107
    previewUrl: string | null;
108
  }
109
  let staged: Record<string, StagedAttachment[]> = {};
110
  let editing: { roomId: string; eventId: string; original: string; stash: string } | null = null;
111
  /** Everyone picked from the finder per room; only those whose name is still in the text get linked on send. */
112
  let pickedMentions: Record<string, Mention[]> = {};
113
  let mentionQuery: MentionQuery | null = null;
114
  let mentionIndex = 0;
115
  let nextStagedId = 1;
116
  const WARM_ROOM_LIMIT = 8;
117
  /** Rooms left open after switching away so coming back is instant, least recently viewed first. */
118
  let warmRooms: string[] = [];
119
  let openReady: Record<string, boolean> = {};
120
  let openFailed: Record<string, string> = {};
121
  let membersFor: string | null = null;
122
  let lastReadKey = '';
123
  let readTimer: number | null = null;
124
  let profile: OwnProfile | null = null;
125
  let profileMxc: string | null = null;
126
  let selectedSpaceId: string | null = null;
127
  let spaceChildIds: string[] | null = null;
128
  let spaceChildrenLoading = false;
129
  let spaceChildrenError: string | null = null;
130
  let avatarByUser: Record<string, string | null> = {};
131
132
  // account data is read from the local cache, which is empty on a fresh device until the first sync lands
133
  $: {
134
    const online = $connection === 'online';
135
    if (online && !wasOnline) {
136
      void loadQuickReactions();
137
      void loadUrlPreviewSettings();
138
    }
139
    wasOnline = online;
140
  }
141
  $: selectedRoom = $rooms.find((r) => r.room_id === $selectedRoomId) ?? null;
142
  $: roomPacks = packsForRoom($imagePacks, $selectedRoomId);
143
  $: previewsAllowed = selectedRoom !== null && (!selectedRoom.encrypted || $urlPreviewSettings.encrypted_rooms);
144
  $: loadPreview = previewsAllowed && $selectedRoomId ? previewLoader($selectedRoomId) : null;
145
  $: spaceRooms = $rooms.filter((r) => r.space);
146
  $: spaceParents = parentSpaceMap(spaceRooms);
147
  $: railSpaces = spaceRooms.filter((s) => !spaceParents.has(s.room_id));
148
  let railOverride: string[] | null = null;
149
  $: if (railOverride && sortSpaces(railSpaces, null).map((s) => s.room_id).join() === railOverride.join()) railOverride = null;
150
  $: orderedRail = sortSpaces(railSpaces, railOverride);
151
  $: pinnedRail = orderedRail.filter((s) => s.favourite);
152
  $: otherRail = orderedRail.filter((s) => !s.favourite);
153
  $: railSelected = selectedSpaceId ? topSpaceOf(selectedSpaceId, spaceParents) : null;
154
  $: invites = $rooms.filter((r) => r.membership === 'Invited');
155
  $: query = search.trim().toLowerCase();
156
  $: selectedSpace = selectedSpaceId ? ($rooms.find((r) => r.room_id === selectedSpaceId) ?? null) : null;
157
  // While a space's children load (or fail), show no channels rather than the
158
  // full list — listing everything would falsely imply it belongs to the space.
159
  $: baseRooms = selectedSpaceId ? (spaceChildIds ? $rooms.filter((r) => spaceChildIds?.includes(r.room_id)) : []) : $rooms;
160
  $: visibleRooms = query
161
    ? baseRooms.filter(
162
        (r) =>
163
          r.name.toLowerCase().includes(query) || r.room_id.toLowerCase().includes(query)
164
      )
165
    : baseRooms;
166
  $: directRooms = pinnedFirst(visibleRooms.filter((r) => r.direct && !r.space && r.membership !== 'Invited'));
167
  $: groupRooms = pinnedFirst(visibleRooms.filter((r) => !r.direct && !r.space && r.membership !== 'Invited'));
168
  $: spaceList = pinnedFirst(visibleRooms.filter((r) => r.space && r.membership !== 'Invited'));
169
  $: channelRooms = baseRooms.filter((r) => !r.space && r.membership !== 'Invited');
170
  $: recoveryBanner = $encryption && ($encryption.recovery === 'Disabled' || $encryption.recovery === 'Incomplete') ? $encryption : null;
171
  $: verificationBanner = $verification && $verification.kind !== 'Done' ? $verification : null;
172
  $: items = $selectedRoomId ? ($timelines[$selectedRoomId] ?? []) : [];
173
  $: currentStaged = $selectedRoomId ? (staged[$selectedRoomId] ?? []) : [];
174
  $: members = $selectedRoomId ? ($membersByRoom[$selectedRoomId] ?? []) : [];
175
  $: people = peopleIn(items, members);
176
  $: mentionCandidates = mentionQuery ? rankPeople(Object.values(people), mentionQuery.query, $sessionUser ?? null) : [];
177
  $: if (mentionIndex >= mentionCandidates.length) mentionIndex = 0;
178
  $: hasStart = items.some((i) => i.kind === 'start');
179
  $: grouped = buildGroups(items);
180
  $: lastSentId = lastOwnSent(items);
181
  $: pendingItems = $selectedRoomId ? ($pendingByRoom[$selectedRoomId] ?? []) : [];
182
  $: lastRealOwn = lastSenderIsOwn(items);
183
184
  function lastSenderIsOwn(list: TimelineItem[]): boolean {
185
    for (let i = list.length - 1; i >= 0; i -= 1) {
186
      const it = list[i];
187
      if (it.kind === 'event') return it.event.sender.user_id === $sessionUser;
188
    }
189
    return false;
190
  }
191
192
  function pendingShowSender(index: number): boolean {
193
    return index === 0 ? !lastRealOwn : false;
194
  }
195
196
  function pendingToEvent(p: PendingMessage): TimelineEvent {
197
    const state: SendState = p.status === 'failed' ? { kind: 'Failed', will_retry: false } : { kind: 'Sending' };
198
    return {
199
      item_id: `pending-${p.id}`,
200
      event_id: null,
201
      transaction_id: p.id,
202
      sender: {
203
        user_id: $sessionUser ?? '',
204
        display_name: profile?.display_name ?? null,
205
        avatar: null,
206
        name_ambiguous: false
207
      },
208
      timestamp_ms: p.createdAt,
209
      own: true,
210
      send_state: state,
211
      content: {
212
        kind: 'Message',
213
        message: { kind: 'Text', body: p.body, geo_uri: null, formatted_body: p.formatted, edited: false, media: null, link_previews: [] }
214
      },
215
      reply_to: p.replyTo,
216
      thread_root: null,
217
      thread_summary: null,
218
      reactions: [],
219
      read_by: [],
220
      editable: false
221
    };
222
  }
223
224
  interface Group {
225
    key: string;
226
    item: TimelineItem;
227
    showSender: boolean;
228
  }
229
230
  function lastOwnSent(list: TimelineItem[]): string | null {
231
    for (let i = list.length - 1; i >= 0; i--) {
232
      const item = list[i];
233
      if (item.kind === 'event' && item.event.own && item.event.send_state.kind === 'Sent') return item.event.item_id;
234
    }
235
    return null;
236
  }
237
238
  function buildGroups(list: TimelineItem[]): Group[] {
239
    const out: Group[] = [];
240
    let prevSender: string | null = null;
241
    let prevTs = 0;
242
    list.forEach((item, index) => {
243
      let showSender = true;
244
      if (item.kind === 'event') {
245
        const e = item.event;
246
        showSender =
247
          prevSender !== e.sender.user_id || Math.abs(e.timestamp_ms - prevTs) > 5 * 60 * 1000;
248
        prevSender = e.sender.user_id;
249
        prevTs = e.timestamp_ms;
250
        out.push({ key: e.item_id || e.event_id || `m-${index}`, item, showSender });
251
      } else {
252
        prevSender = null;
253
        out.push({ key: `${item.kind}-${index}`, item, showSender });
254
      }
255
    });
256
    return out;
257
  }
258
259
  function roomUnread(r: RoomSummary): number {
260
    return r.unread_messages + r.unread_mentions;
261
  }
262
263
  onMount(() => {
264
    void boot();
265
    return () => {
266
      disconnectEvents();
267
      stopTyping();
268
      if (readTimer !== null) window.clearTimeout(readTimer);
269
    };
270
  });
271
272
  async function boot(): Promise<void> {
273
    try {
274
      const session = await getSession();
275
      blocked.set(session.blocked ?? false);
276
      sessionUser.set(session.user_id);
277
      if (session.user_id) {
278
        softLogout.set(null);
279
        await refreshRooms();
280
        connectEvents();
281
        void loadProfile();
282
        void loadEncryption();
283
        void loadQuickReactions();
284
        void loadUrlPreviewSettings();
285
      } else {
286
        softLogout.set(session.soft_logout ?? null);
287
      }
288
    } catch (e) {
289
      pushBanner(e instanceof Error ? `Session check failed: ${e.message}` : 'Session check failed');
290
      sessionUser.set(null);
291
    } finally {
292
      booted = true;
293
    }
294
  }
295
296
  async function refreshRooms(): Promise<void> {
297
    roomsLoading = true;
298
    try {
299
      const res = await getRooms();
300
      rooms.set(res.rooms);
301
      pruneSpaceFilter();
302
    } catch (e) {
303
      pushBanner(e instanceof Error ? e.message : 'Could not load rooms');
304
    } finally {
305
      roomsLoading = false;
306
    }
307
  }
308
309
  async function loadProfile(): Promise<void> {
310
    try {
311
      const raw = await getProfile();
312
      profile = parseOwnProfile(raw);
313
      profileMxc = profile.avatar_url;
314
    } catch {
315
      profile = null;
316
    }
317
  }
318
319
  async function loadEncryption(): Promise<void> {
320
    try {
321
      const res = await getEncryption();
322
      const state = parseEncryptionState(res.state);
323
      if (state) encryption.set(state);
324
      const verificationState = parseVerificationState(res.verification);
325
      if (verificationState) verification.set(verificationState);
326
    } catch {
327
      // Encryption status also arrives over SSE; a failed first fetch is not fatal.
328
    }
329
  }
330
331
  function afterLogin(userId: string): void {
332
    sessionUser.set(userId);
333
    softLogout.set(null);
334
    blocked.set(false);
335
    void refreshRooms();
336
    connectEvents();
337
    void loadProfile();
338
    void loadEncryption();
339
    void loadQuickReactions();
340
    void loadUrlPreviewSettings();
341
  }
342
343
  async function doLogout(): Promise<void> {
344
    stopTyping();
345
    try {
346
      await logout();
347
    } catch (e) {
348
      pushBanner(e instanceof Error ? e.message : 'Logout failed');
349
      return;
350
    }
351
    disconnectEvents();
352
    resetClientState();
353
    softLogout.set(null);
354
    blocked.set(false);
355
    sessionUser.set(null);
356
    lightbox.set(null);
357
    composer = '';
358
    drafts = {};
359
    dialog = null;
360
    membersOpen = false;
361
    sidebarOpen = false;
362
    profile = null;
363
    profileMxc = null;
364
    selectedSpaceId = null;
365
    spaceChildIds = null;
366
    spaceChildrenError = null;
367
    openReady = {};
368
    openFailed = {};
369
    warmRooms = [];
370
    pickedMentions = {};
371
    mentionQuery = null;
372
    clearAllStaged();
373
    avatarByUser = {};
374
    resetPending();
375
  }
376
377
  /** Joined spaces that sit inside another joined space, keyed to one such parent. Either side of the link counts. */
378
  function parentSpaceMap(spaces: RoomSummary[]): Map<string, string> {
379
    const ids = new Set(spaces.map((s) => s.room_id));
380
    const parents = new Map<string, string>();
381
    for (const space of spaces) {
382
      for (const child of space.children) {
383
        if (child !== space.room_id && ids.has(child) && !parents.has(child)) parents.set(child, space.room_id);
384
      }
385
    }
386
    for (const space of spaces) {
387
      const parent = space.parent_spaces.find((id) => id !== space.room_id && ids.has(id));
388
      if (parent && !parents.has(space.room_id)) parents.set(space.room_id, parent);
389
    }
390
    for (const id of [...parents.keys()]) {
391
      const seen = new Set<string>([id]);
392
      let at = parents.get(id);
393
      while (at && !seen.has(at)) {
394
        seen.add(at);
395
        at = parents.get(at);
396
      }
397
      if (at) parents.delete(id);
398
    }
399
    return parents;
400
  }
401
402
  function topSpaceOf(id: string, parents: Map<string, string>): string {
403
    let at = id;
404
    while (parents.has(at)) at = parents.get(at)!;
405
    return at;
406
  }
407
408
  function pruneSpaceFilter(): void {
409
    if (!selectedSpaceId) return;
410
    if (!$rooms.some((r) => r.room_id === selectedSpaceId)) {
411
      selectedSpaceId = null;
412
      spaceChildIds = null;
413
      spaceChildrenError = null;
414
    }
415
  }
416
417
  async function selectHome(): Promise<void> {
418
    selectedSpaceId = null;
419
    spaceChildIds = null;
420
    spaceChildrenError = null;
421
    sidebarOpen = true;
422
  }
423
424
  async function selectSpace(spaceId: string): Promise<void> {
425
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
426
    stopTyping();
427
    selectedSpaceId = spaceId;
428
    spaceChildIds = null;
429
    spaceChildrenError = null;
430
    spaceChildrenLoading = true;
431
    const last = $lastSpaceRooms[spaceId];
432
    const resume = last && $rooms.some((r) => r.room_id === last && !r.space) ? last : null;
433
    if (resume) {
434
      void selectRoom(resume);
435
    } else {
436
      sidebarOpen = true;
437
      // A space is navigation, not a message timeline.
438
      selectedRoomId.set(null);
439
    }
440
    try {
441
      const res = await getSpaceChildren(spaceId);
442
      if (selectedSpaceId === spaceId) {
443
        spaceChildIds = res.room_ids ?? [];
444
        if (resume && !spaceChildIds.includes(resume) && $selectedRoomId === resume) {
445
          sidebarOpen = true;
446
          selectedRoomId.set(null);
447
        }
448
      }
449
    } catch (e) {
450
      if (selectedSpaceId === spaceId) {
451
        spaceChildrenError = e instanceof Error ? e.message : 'Could not load rooms in this space';
452
        spaceChildIds = [];
453
      }
454
    } finally {
455
      if (selectedSpaceId === spaceId) spaceChildrenLoading = false;
456
    }
457
  }
458
459
  async function selectRoom(roomId: string, peek = false): Promise<void> {
460
    peeking = peek ? roomId : null;
461
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
462
    if (roomId === $selectedRoomId && openReady[roomId]) {
463
      sidebarOpen = false;
464
      return;
465
    }
466
    stopTyping();
467
    const spaceId = selectedSpaceId;
468
    if (spaceId) lastSpaceRooms.update((all) => ({ ...all, [spaceId]: roomId }));
469
    selectedRoomId.set(roomId);
470
    composer = drafts[roomId] ?? '';
471
    replyingTo = null;
472
    editing = null;
473
    mentionQuery = null;
474
    stickToBottom = true;
475
    lastReadKey = '';
476
    sidebarOpen = false;
477
    touchWarmRoom(roomId);
478
    if (openReady[roomId]) {
479
      if (membersOpen) void loadMembers(roomId);
480
      await tick();
481
      scrollToBottom();
482
      queueReadReceipt();
483
      composerEl?.focus();
484
      return;
485
    }
486
    if (openFailed[roomId]) {
487
      const nextFailed = { ...openFailed };
488
      delete nextFailed[roomId];
489
      openFailed = nextFailed;
490
    }
491
    try {
492
      await openRoom(roomId);
493
      if (warmRooms.includes(roomId)) openReady = { ...openReady, [roomId]: true };
494
    } catch (e) {
495
      const message = e instanceof Error ? e.message : `Could not open room ${roomId}`;
496
      openFailed = { ...openFailed, [roomId]: message };
497
      pushBanner(message);
498
    }
499
    if (membersOpen) void loadMembers(roomId);
500
    await tick();
501
    scrollToBottom();
502
    queueReadReceipt();
503
    composerEl?.focus();
504
  }
505
506
  function touchWarmRoom(roomId: string): void {
507
    warmRooms = [...warmRooms.filter((id) => id !== roomId), roomId];
508
    while (warmRooms.length > WARM_ROOM_LIMIT) {
509
      const evicted = warmRooms[0];
510
      warmRooms = warmRooms.slice(1);
511
      forgetOpenRoom(evicted);
512
      closeRoom(evicted).catch(() => undefined);
513
    }
514
  }
515
516
  function forgetOpenRoom(roomId: string): void {
517
    warmRooms = warmRooms.filter((id) => id !== roomId);
518
    const nextReady = { ...openReady };
519
    delete nextReady[roomId];
520
    openReady = nextReady;
521
  }
522
523
  function scrollToBottom(): void {
524
    if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight;
525
  }
526
527
  let userScrollUntil = 0;
528
  let draggingScrollbar = false;
529
530
  function noteUserScroll(): void {
531
    userScrollUntil = performance.now() + 300;
532
  }
533
534
  function onTimelineKey(e: KeyboardEvent): void {
535
    if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) noteUserScroll();
536
  }
537
538
  function onTimelinePointer(e: PointerEvent): void {
539
    if (e.target === timelineEl) draggingScrollbar = true;
540
  }
541
542
  function onTimelineScroll(): void {
543
    if (!timelineEl) return;
544
    const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight;
545
    if (gap < 80) stickToBottom = true;
546
    else if (draggingScrollbar || performance.now() < userScrollUntil) stickToBottom = false;
547
  }
548
549
  function pinTimeline(node: HTMLElement) {
550
    const observer = new ResizeObserver(() => {
551
      if (stickToBottom) scrollToBottom();
552
    });
553
    observer.observe(node);
554
    if (node.parentElement) observer.observe(node.parentElement);
555
    return { destroy: () => observer.disconnect() };
556
  }
557
558
  $: void trackTimeline($selectedRoomId, items);
559
  async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> {
560
    if (!roomId || list.length === 0) return;
561
    if (roomId !== $selectedRoomId) return;
562
    await tick();
563
    if (stickToBottom) scrollToBottom();
564
    queueReadReceipt();
565
  }
566
567
  function queueReadReceipt(): void {
568
    if (readTimer !== null) window.clearTimeout(readTimer);
569
    readTimer = window.setTimeout(() => {
570
      readTimer = null;
571
      void sendReadReceipt();
572
    }, 800);
573
  }
574
575
  async function sendReadReceipt(): Promise<void> {
576
    const roomId = $selectedRoomId;
577
    if (!roomId || roomId === peeking) return;
578
    const list = $timelines[roomId] ?? [];
579
    for (let i = list.length - 1; i >= 0; i -= 1) {
580
      const entry = list[i];
581
      if (entry.kind === 'event' && entry.event.event_id) {
582
        const key = `${roomId}:${entry.event.event_id}`;
583
        if (key === lastReadKey) return;
584
        lastReadKey = key;
585
        try {
586
          await markRead(roomId, entry.event.event_id);
587
        } catch {
588
          return;
589
        }
590
        return;
591
      }
592
    }
593
  }
594
595
  function send(): void {
596
    if (editing) {
597
      submitEdit();
598
      return;
599
    }
600
    const roomId = $selectedRoomId;
601
    const body = composer.trim();
602
    const attachments = roomId ? (staged[roomId] ?? []) : [];
603
    if (!roomId || (!body && attachments.length === 0)) return;
604
    if (!openReady[roomId]) {
605
      pushBanner('Still opening this room — sending is disabled until the room is ready.');
606
      return;
607
    }
608
    if (attachments.length > 0 && uploadBusy) return;
609
    const command = parseCommand(body);
610
    if (command && !isKnownCommand(command.name)) {
611
      pushBanner(`Unknown command /${command.name}`);
612
      return;
613
    }
614
    if (command && attachments.length > 0) {
615
      if (command.name !== 'roomavatar' && command.name !== 'globalavatar') {
616
        pushBanner(`/${command.name} doesn't take attachments`);
617
        return;
618
      }
619
      if (command.args || attachments.length !== 1 || !attachments[0].file.type.startsWith('image/')) {
620
        pushBanner(`/${command.name} takes a single attached image`);
621
        return;
622
      }
623
    }
624
    composer = '';
625
    if (roomId in drafts) delete drafts[roomId];
626
    stickToBottom = true;
627
    const reply = replyingTo;
628
    replyingTo = null;
629
    const text = unescapeCommand(body);
630
    const mentions = resolveMentions(text, pickedMentions[roomId] ?? []);
631
    pickedMentions = { ...pickedMentions, [roomId]: [] };
632
    mentionQuery = null;
633
    if (command) {
634
      const image = attachments[0] ?? null;
635
      if (image) {
636
        const { [roomId]: _used, ...rest } = staged;
637
        staged = rest;
638
      }
639
      void execute(roomId, command, reply, mentions, image?.file ?? null).finally(() => {
640
        if (image?.previewUrl) URL.revokeObjectURL(image.previewUrl);
641
      });
642
    } else if (attachments.length === 0) {
643
      queueSend(roomId, text, reply, mentions, $markdownEnabled);
644
    } else {
645
      const { [roomId]: _sent, ...rest } = staged;
646
      staged = rest;
647
      void sendAttachments(roomId, text, reply, mentions, attachments);
648
    }
649
    if (peeking === roomId) stopPeeking();
650
    composerEl?.focus();
651
  }
652
653
  function lastOwnEventId(): string | null {
654
    for (let i = items.length - 1; i >= 0; i -= 1) {
655
      const entry = items[i];
656
      if (entry.kind === 'event' && entry.event.own && entry.event.event_id && entry.event.content.kind !== 'Redacted') {
657
        return entry.event.event_id;
658
      }
659
    }
660
    return null;
661
  }
662
663
  async function execute(
664
    roomId: string,
665
    command: ParsedCommand,
666
    reply: ReplyReference | null,
667
    mentions: Mention[],
668
    image: File | null
669
  ): Promise<void> {
670
    const { name, args } = command;
671
    const target = () => {
672
      const found = splitTarget(args, Object.values(people));
673
      if ('error' in found) throw new Error(found.error);
674
      return found;
675
    };
676
    const required = (what: string) => {
677
      if (!args) throw new Error(`/${name} needs ${what}`);
678
      return args;
679
    };
680
    try {
681
      switch (name) {
682
        case 'me':
683
        case 'notice':
684
          await sendMessage(roomId, required('something to say'), null, mentions, $markdownEnabled, name === 'me' ? 'emote' : 'notice');
685
          break;
686
        case 'msg': {
687
          const { user_id, rest } = target();
688
          const res = (await runCommand({ op: 'direct', user_id })) as { room_id: string };
689
          await refreshRooms();
690
          await selectRoom(res.room_id);
691
          if (rest) queueSend(res.room_id, rest, null, [], $markdownEnabled);
692
          break;
693
        }
694
        case 'join':
695
          await join(required('a room id or alias'));
696
          break;
697
        case 'leave':
698
          await leave();
699
          break;
700
        case 'invite':
701
          await runCommand({ op: 'invite', room_id: roomId, user_id: target().user_id });
702
          break;
703
        case 'disinvite':
704
        case 'kick':
705
        case 'ban':
706
        case 'unban': {
707
          const { user_id, rest } = target();
708
          const op = name === 'disinvite' ? 'kick' : name;
709
          await runCommand({ op, room_id: roomId, user_id, reason: rest || null });
710
          break;
711
        }
712
        case 'powerlevel': {
713
          const { user_id, rest } = target();
714
          const level = Number(rest);
715
          if (!rest || !Number.isInteger(level)) throw new Error('/powerlevel needs a whole number after the name');
716
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id, level });
717
          break;
718
        }
719
        case 'mute':
720
        case 'unmute':
721
          await runCommand({ op: 'mute', room_id: roomId, user_id: target().user_id, muted: name === 'mute' });
722
          break;
723
        case 'ignore':
724
        case 'unignore':
725
          await runCommand({ op: name, user_id: target().user_id });
726
          break;
727
        case 'roomnick':
728
          await runCommand({ op: 'set_room_display_name', room_id: roomId, name: args || null });
729
          break;
730
        case 'roomavatar':
731
          if (image) {
732
            await uploadRoomAvatar(roomId, image);
733
          } else if (args && !args.startsWith('mxc://')) {
734
            throw new Error('/roomavatar takes an mxc:// link, an attached image, or nothing to drop the override');
735
          } else {
736
            await runCommand({ op: 'set_room_avatar', room_id: roomId, mxc: args || null });
737
          }
738
          break;
739
        case 'delete': {
740
          const eventId = reply?.event_id ?? lastOwnEventId();
741
          if (!eventId) throw new Error('Nothing of yours to delete here');
742
          await runCommand({ op: 'redact', room_id: roomId, event_id: eventId, reason: args || null });
743
          break;
744
        }
745
        case 'globalnick':
746
          await runCommand({ op: 'set_display_name', name: required('a name') });
747
          await loadProfile();
748
          break;
749
        case 'globalavatar':
750
          if (image) {
751
            await uploadAvatar(image);
752
            await loadProfile();
753
          } else if (!args) {
754
            avatarInput?.click();
755
          } else if (args.startsWith('mxc://')) {
756
            await runCommand({ op: 'set_avatar', mxc: args });
757
            await loadProfile();
758
          } else {
759
            throw new Error('/globalavatar takes an mxc:// link, or nothing to pick a file');
760
          }
761
          break;
762
      }
763
    } catch (e) {
764
      pushBanner(e instanceof Error ? e.message : `/${name} failed`);
765
    }
766
  }
767
768
  async function onAvatarChosen(): Promise<void> {
769
    const file = avatarInput?.files?.[0];
770
    if (avatarInput) avatarInput.value = '';
771
    if (!file) return;
772
    try {
773
      await uploadAvatar(file);
774
      await loadProfile();
775
    } catch (e) {
776
      pushBanner(e instanceof Error ? e.message : 'Avatar upload failed');
777
    }
778
  }
779
780
  async function sendAttachments(
781
    roomId: string,
782
    body: string,
783
    reply: ReplyReference | null,
784
    mentions: Mention[],
785
    attachments: StagedAttachment[]
786
  ): Promise<void> {
787
    let first = true;
788
    uploadBusy = true;
789
    try {
790
      for (const attachment of attachments) {
791
        uploadName = attachment.file.name || 'attachment';
792
        try {
793
          if (first) await uploadAttachment(roomId, attachment.file, body || null, reply?.event_id ?? null, mentions, $markdownEnabled);
794
          else await uploadAttachment(roomId, attachment.file);
795
          first = false;
796
        } catch (e) {
797
          pushBanner(e instanceof Error ? e.message : 'Upload failed');
798
        }
799
        if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
800
      }
801
    } finally {
802
      uploadBusy = false;
803
      uploadName = null;
804
    }
805
  }
806
807
  function stageFiles(files: File[]): void {
808
    const roomId = $selectedRoomId;
809
    if (!roomId || !openReady[roomId]) return;
810
    const accepted: StagedAttachment[] = [];
811
    for (const file of files) {
812
      if (file.size === 0 || file.size > 20 * 1024 * 1024) {
813
        pushBanner(`${file.name || 'File'} must be between 1 byte and 20 MiB.`);
814
        continue;
815
      }
816
      const previewUrl = file.type.startsWith('image/') ? URL.createObjectURL(file) : null;
817
      accepted.push({ id: nextStagedId++, file, previewUrl });
818
    }
819
    if (accepted.length === 0) return;
820
    staged = { ...staged, [roomId]: [...(staged[roomId] ?? []), ...accepted] };
821
    composerEl?.focus();
822
  }
823
824
  function unstage(roomId: string, id: number): void {
825
    const list = staged[roomId] ?? [];
826
    const removed = list.find((a) => a.id === id);
827
    if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
828
    staged = { ...staged, [roomId]: list.filter((a) => a.id !== id) };
829
  }
830
831
  function clearAllStaged(): void {
832
    for (const list of Object.values(staged)) {
833
      for (const attachment of list) if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
834
    }
835
    staged = {};
836
  }
837
838
  function startEdit(eventId: string, body: string): void {
839
    const roomId = $selectedRoomId;
840
    if (!roomId) return;
841
    const stash = editing ? editing.stash : composer;
842
    editing = { roomId, eventId, original: body, stash };
843
    const entry = items.find((i) => i.kind === 'event' && i.event.event_id === eventId);
844
    if (entry?.kind === 'event' && entry.event.content.kind === 'Message') {
845
      const existing = mentionsFromHtml(entry.event.content.message.formatted_body);
846
      pickedMentions = { ...pickedMentions, [roomId]: [...(pickedMentions[roomId] ?? []), ...existing] };
847
    }
848
    composer = body;
849
    replyingTo = null;
850
    composerEl?.focus();
851
  }
852
853
  function cancelEdit(): void {
854
    if (!editing) return;
855
    composer = editing.stash;
856
    editing = null;
857
    composerEl?.focus();
858
  }
859
860
  function submitEdit(): void {
861
    if (!editing) return;
862
    const { roomId, eventId, original } = editing;
863
    const body = composer.trim();
864
    cancelEdit();
865
    if (!body || body === original.trim()) return;
866
    editMessage(roomId, eventId, body, resolveMentions(body, pickedMentions[roomId] ?? []), $markdownEnabled).catch((e) => pushBanner(e instanceof Error ? e.message : 'Edit failed'));
867
  }
868
869
  function editLastOwn(): boolean {
870
    for (let i = items.length - 1; i >= 0; i -= 1) {
871
      const entry = items[i];
872
      if (entry.kind !== 'event' || !entry.event.own) continue;
873
      const ev = entry.event;
874
      if (!ev.editable || !ev.event_id || ev.content.kind !== 'Message' || ev.content.message.kind !== 'Text') return false;
875
      startEdit(ev.event_id, ev.content.message.body);
876
      return true;
877
    }
878
    return false;
879
  }
880
881
  function startReply(target: ReplyReference): void {
882
    if (editing) cancelEdit();
883
    replyingTo = target;
884
    composerEl?.focus();
885
  }
886
887
  function jumpTo(eventId: string): void {
888
    const el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
889
    if (!el) {
890
      pushBanner('The original message is not loaded. Scroll up to load older messages.');
891
      return;
892
    }
893
    stickToBottom = false;
894
    el.scrollIntoView({ block: 'center', behavior: 'smooth' });
895
    el.classList.remove('flash');
896
    void el.offsetWidth;
897
    el.classList.add('flash');
898
  }
899
900
  let typedText = '';
901
  let typedRoom: string | null = null;
902
  $: trackTypingInput(composer, $selectedRoomId, openReady);
903
  function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void {
904
    const edited = roomId === typedRoom && text !== typedText;
905
    typedText = text;
906
    typedRoom = roomId;
907
    if (!roomId || !ready[roomId] || !text.trim()) {
908
      stopTyping();
909
    } else if (edited && roomId !== peeking) {
910
      notifyTyping(roomId);
911
    }
912
  }
913
914
  $: void trackPending($selectedRoomId, pendingItems);
915
  async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> {
916
    if (!roomId || list.length === 0) return;
917
    if (roomId !== $selectedRoomId) return;
918
    await tick();
919
    if (stickToBottom) scrollToBottom();
920
  }
921
922
  function updateMentionQuery(): void {
923
    const roomId = $selectedRoomId;
924
    const next = composerEl && roomId ? mentionQueryAt(composerEl.value, composerEl.selectionStart ?? composerEl.value.length) : null;
925
    if (next && !mentionQuery && roomId && !$membersByRoom[roomId]) void loadMembers(roomId);
926
    if (next?.start !== mentionQuery?.start) mentionIndex = 0;
927
    mentionQuery = next;
928
  }
929
930
  async function pickMention(person: Person): Promise<void> {
931
    const roomId = $selectedRoomId;
932
    if (!mentionQuery || !roomId || !composerEl) return;
933
    const caret = composerEl.selectionStart ?? composer.length;
934
    const inserted = `${person.name} `;
935
    composer = composer.slice(0, mentionQuery.start) + inserted + composer.slice(caret);
936
    const at = mentionQuery.start + inserted.length;
937
    pickedMentions = {
938
      ...pickedMentions,
939
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
940
    };
941
    mentionQuery = null;
942
    await tick();
943
    composerEl.focus();
944
    composerEl.setSelectionRange(at, at);
945
  }
946
947
  function onComposerKey(ev: KeyboardEvent): void {
948
    if (mentionQuery && mentionCandidates.length > 0) {
949
      if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
950
        ev.preventDefault();
951
        const step = ev.key === 'ArrowDown' ? 1 : -1;
952
        mentionIndex = (mentionIndex + step + mentionCandidates.length) % mentionCandidates.length;
953
        return;
954
      }
955
      if ((ev.key === 'Enter' && !ev.shiftKey) || ev.key === 'Tab') {
956
        ev.preventDefault();
957
        void pickMention(mentionCandidates[mentionIndex]);
958
        return;
959
      }
960
      if (ev.key === 'Escape') {
961
        ev.stopPropagation();
962
        mentionQuery = null;
963
        return;
964
      }
965
    }
966
    if (ev.key === 'Enter' && !ev.shiftKey && !insideOpenFence(composer, composerEl?.selectionStart ?? composer.length)) {
967
      ev.preventDefault();
968
      send();
969
    } else if (ev.key === 'Escape' && editing) {
970
      ev.stopPropagation();
971
      cancelEdit();
972
    } else if (ev.key === 'Escape' && replyingTo) {
973
      ev.stopPropagation();
974
      replyingTo = null;
975
    } else if (ev.key === 'ArrowUp' && !composer && !editing && editLastOwn()) {
976
      ev.preventDefault();
977
    }
978
  }
979
980
  function pickFiles(): void {
981
    const roomId = $selectedRoomId;
982
    if (!roomId || !openReady[roomId]) return;
983
    fileInput?.click();
984
  }
985
986
  function onFileChosen(): void {
987
    stageFiles(Array.from(fileInput?.files ?? []));
988
    if (fileInput) fileInput.value = '';
989
  }
990
991
  function onComposerPaste(ev: ClipboardEvent): void {
992
    const data = ev.clipboardData;
993
    // Office apps put a rendered image next to the copied text, so only take the image when there is no plain text.
994
    if (!data || data.types.includes('text/plain')) return;
995
    const images = Array.from(data.files).filter((f) => f.type.startsWith('image/'));
996
    if (images.length === 0) return;
997
    ev.preventDefault();
998
    stageFiles(images);
999
  }
1000
1001
  async function react(eventId: string, key: string, shortcode?: string): Promise<void> {
1002
    const roomId = $selectedRoomId;
1003
    if (!roomId || !eventId || reacting) return;
1004
    reacting = true;
1005
    try {
1006
      await reactToMessage(roomId, eventId, key, shortcode);
1007
    } catch (e) {
1008
      pushBanner(e instanceof Error ? e.message : 'Reaction failed');
1009
    } finally {
1010
      reacting = false;
1011
    }
1012
  }
1013
1014
  function previewLoader(roomId: string): (url: string) => void {
1015
    return (url) => requestLinkPreview(roomId, url);
1016
  }
1017
1018
  async function changeEncryptedPreviews(enabled: boolean): Promise<void> {
1019
    try {
1020
      await saveUrlPreviewSettings({ encrypted_rooms: enabled });
1021
    } catch (e) {
1022
      pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting');
1023
    }
1024
  }
1025
1026
  async function changeQuickReactions(list: QuickReaction[]): Promise<void> {
1027
    try {
1028
      await saveQuickReactions(list);
1029
    } catch (e) {
1030
      pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions');
1031
    }
1032
  }
1033
1034
  async function paginate(): Promise<void> {
1035
    const roomId = $selectedRoomId;
1036
    if (!roomId || paginateBusy) return;
1037
    paginateBusy = true;
1038
    try {
1039
      await paginateRoom(roomId);
1040
    } catch (e) {
1041
      pushBanner(e instanceof Error ? e.message : 'Loading older messages failed');
1042
    } finally {
1043
      paginateBusy = false;
1044
    }
1045
  }
1046
1047
  async function loadMembers(roomId: string): Promise<void> {
1048
    if (membersFor === roomId && $membersLoading) return;
1049
    membersFor = roomId;
1050
    membersLoading.set(true);
1051
    try {
1052
      const res = await getMembers(roomId);
1053
      membersByRoom.update((all) => ({ ...all, [roomId]: res.members }));
1054
      avatarByUser = { ...avatarByUser, ...avatarMap(res.members) };
1055
    } catch (e) {
1056
      pushBanner(e instanceof Error ? e.message : 'Could not load members');
1057
    } finally {
1058
      if (membersFor === roomId) membersLoading.set(false);
1059
    }
1060
  }
1061
1062
  function avatarMap(list: MemberSummary[]): Record<string, string | null> {
1063
    const next: Record<string, string | null> = {};
1064
    for (const member of list) next[member.user_id] = member.avatar;
1065
    return next;
1066
  }
1067
1068
  function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> {
1069
    const out: Record<string, Person> = {};
1070
    for (const item of list) {
1071
      if (item.kind !== 'event') continue;
1072
      const s = item.event.sender;
1073
      out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar };
1074
    }
1075
    for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar };
1076
    return out;
1077
  }
1078
1079
  function senderAvatarFor(userId: string): string | null {
1080
    return avatarByUser[userId] ?? null;
1081
  }
1082
1083
  function toggleMembers(): void {
1084
    membersOpen = !membersOpen;
1085
    if (membersOpen && $selectedRoomId) void loadMembers($selectedRoomId);
1086
  }
1087
1088
  async function join(target: string): Promise<void> {
1089
    const room = target.trim();
1090
    if (!room || joinBusy) return;
1091
    joinBusy = true;
1092
    try {
1093
      const res = await joinRoom(room);
1094
      joinTarget = '';
1095
      dialog = null;
1096
      await refreshRooms();
1097
      await selectRoom(res.room_id);
1098
    } catch (e) {
1099
      pushBanner(e instanceof Error ? e.message : 'Join failed');
1100
    } finally {
1101
      joinBusy = false;
1102
    }
1103
  }
1104
1105
  async function create(): Promise<void> {
1106
    const name = createName.trim();
1107
    if (!name || createBusy) return;
1108
    createBusy = true;
1109
    try {
1110
      const res = await createRoom(name, createTopic.trim() || undefined);
1111
      createName = '';
1112
      createTopic = '';
1113
      dialog = null;
1114
      await refreshRooms();
1115
      await selectRoom(res.room_id);
1116
    } catch (e) {
1117
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
1118
    } finally {
1119
      createBusy = false;
1120
    }
1121
  }
1122
1123
  async function leave(roomId: string | null = $selectedRoomId): Promise<void> {
1124
    if (!roomId || leaveBusy) return;
1125
    leaveBusy = true;
1126
    stopTyping();
1127
    try {
1128
      await leaveRoom(roomId);
1129
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
1130
      if (warmRooms.includes(roomId)) {
1131
        forgetOpenRoom(roomId);
1132
        closeRoom(roomId).catch(() => undefined);
1133
      }
1134
      await refreshRooms();
1135
    } catch (e) {
1136
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
1137
    } finally {
1138
      leaveBusy = false;
1139
    }
1140
  }
1141
1142
  function connectionClass(state: string): string {
1143
    if (state === 'online') return 'dot-online';
1144
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
1145
    return 'dot-off';
1146
  }
1147
1148
  let dragSpaceId: string | null = null;
1149
  let dropTarget: { id: string; after: boolean } | null = null;
1150
  let menu: { items: MenuItem[]; x: number; y: number } | null = null;
1151
  let userCard: { userId: string; x: number; y: number; confirm: 'kick' | 'ban' | null } | null = null;
1152
  let levelsByRoom: Record<string, PowerLevels | null> = {};
1153
  let peeking: string | null = null;
1154
1155
  $: roomLevels = $selectedRoomId ? (levelsByRoom[$selectedRoomId] ?? null) : null;
1156
1157
  function personFor(userId: string): Person {
1158
    return people[userId] ?? { user_id: userId, name: userId, avatar: avatarByUser[userId] ?? null };
1159
  }
1160
1161
  function memberFor(userId: string): MemberSummary | null {
1162
    return members.find((m) => m.user_id === userId) ?? null;
1163
  }
1164
1165
  async function loadLevels(roomId: string): Promise<void> {
1166
    try {
1167
      const levels = parsePowerLevels(await runCommand({ op: 'power_levels', room_id: roomId }));
1168
      levelsByRoom = { ...levelsByRoom, [roomId]: levels };
1169
    } catch {
1170
      levelsByRoom = { ...levelsByRoom, [roomId]: levelsByRoom[roomId] ?? null };
1171
    }
1172
  }
1173
1174
  async function openUser(userId: string, x: number, y: number, asMenu: boolean): Promise<void> {
1175
    const roomId = $selectedRoomId;
1176
    if (roomId && !(roomId in levelsByRoom)) await loadLevels(roomId);
1177
    else if (roomId) void loadLevels(roomId);
1178
    if (asMenu) menu = { items: userMenuItems(userId, x, y), x, y };
1179
    else userCard = { userId, x, y, confirm: null };
1180
  }
1181
1182
  function copyText(text: string): void {
1183
    navigator.clipboard.writeText(text).catch(() => pushBanner('Could not copy to the clipboard'));
1184
  }
1185
1186
  function userMenuItems(userId: string, x: number, y: number): MenuItem[] {
1187
    const own = userId === $sessionUser;
1188
    const member = memberFor(userId);
1189
    const items: MenuItem[] = [];
1190
    if (!own) items.push({ label: 'Message', action: () => void userAction(userId, { kind: 'message' }) });
1191
    items.push({ label: 'Mention', action: () => void userAction(userId, { kind: 'mention' }) });
1192
    items.push({ label: 'Copy user ID', action: () => copyText(userId) });
1193
    if (roomLevels && $sessionUser) {
1194
      const can = allowed(roomLevels, $sessionUser, userId);
1195
      const banned = member?.membership === 'Ban';
1196
      if (can.setLevel && !own) {
1197
        const muted = isMuted(roomLevels, userId);
1198
        items.push({ label: muted ? 'Unmute' : 'Mute', action: () => void userAction(userId, { kind: muted ? 'unmute' : 'mute' }) });
1199
      }
1200
      if (can.kick && !banned) items.push({ label: 'Kick…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'kick' }) });
1201
      if (can.ban && banned) items.push({ label: 'Unban', action: () => void userAction(userId, { kind: 'unban' }) });
1202
      if (can.ban && !banned) items.push({ label: 'Ban…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'ban' }) });
1203
      if (can.setLevel) items.push({ label: 'Power level…', action: () => (userCard = { userId, x, y, confirm: null }) });
1204
    }
1205
    if (!own) {
1206
      const kind = member?.ignored ? 'unignore' : 'ignore';
1207
      items.push({ label: member?.ignored ? 'Unignore' : 'Ignore', action: () => void userAction(userId, { kind }) });
1208
    }
1209
    return items;
1210
  }
1211
1212
  async function insertMention(person: Person): Promise<void> {
1213
    const roomId = $selectedRoomId;
1214
    if (!roomId) return;
1215
    const lead = composer && !/\s$/.test(composer) ? ' ' : '';
1216
    composer = `${composer}${lead}${person.name} `;
1217
    pickedMentions = {
1218
      ...pickedMentions,
1219
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
1220
    };
1221
    await tick();
1222
    composerEl?.focus();
1223
    composerEl?.setSelectionRange(composer.length, composer.length);
1224
  }
1225
1226
  async function userAction(userId: string, action: UserAction): Promise<void> {
1227
    const roomId = $selectedRoomId;
1228
    try {
1229
      switch (action.kind) {
1230
        case 'message': {
1231
          const res = (await runCommand({ op: 'direct', user_id: userId })) as { room_id: string };
1232
          await refreshRooms();
1233
          await selectRoom(res.room_id);
1234
          return;
1235
        }
1236
        case 'mention':
1237
          await insertMention(personFor(userId));
1238
          return;
1239
        case 'ignore':
1240
        case 'unignore':
1241
          await runCommand({ op: action.kind, user_id: userId });
1242
          if (roomId) void loadMembers(roomId);
1243
          return;
1244
      }
1245
      if (!roomId) return;
1246
      switch (action.kind) {
1247
        case 'kick':
1248
        case 'ban':
1249
          await runCommand({ op: action.kind, room_id: roomId, user_id: userId, reason: action.reason });
1250
          break;
1251
        case 'unban':
1252
          await runCommand({ op: 'unban', room_id: roomId, user_id: userId, reason: null });
1253
          break;
1254
        case 'mute':
1255
        case 'unmute':
1256
          await runCommand({ op: 'mute', room_id: roomId, user_id: userId, muted: action.kind === 'mute' });
1257
          break;
1258
        case 'power':
1259
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id: userId, level: action.level });
1260
          break;
1261
      }
1262
      void loadLevels(roomId);
1263
      void loadMembers(roomId);
1264
    } catch (e) {
1265
      pushBanner(e instanceof Error ? e.message : 'That action failed');
1266
    }
1267
  }
1268
1269
  function roomMenuItems(room: RoomSummary): MenuItem[] {
1270
    const items: MenuItem[] = room.space
1271
      ? [{ label: 'Open', action: () => void selectSpace(room.room_id) }]
1272
      : [
1273
          { label: 'Open', action: () => void selectRoom(room.room_id) },
1274
          { label: 'Peek', action: () => void selectRoom(room.room_id, true) }
1275
        ];
1276
    items.push({ label: room.favourite ? 'Unpin' : room.space ? 'Pin to top' : 'Pin', action: () => void togglePin(room) });
1277
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${room.canonical_alias ?? room.room_id}`) });
1278
    items.push({ label: 'Copy room ID', action: () => copyText(room.room_id) });
1279
    if (room.membership === 'Joined') items.push({ label: 'Leave', danger: true, action: () => void leave(room.room_id) });
1280
    return items;
1281
  }
1282
1283
  function openRoomMenu(ev: MouseEvent, room: RoomSummary): void {
1284
    menu = { items: roomMenuItems(room), x: ev.clientX, y: ev.clientY };
1285
  }
1286
1287
  function stopPeeking(): void {
1288
    peeking = null;
1289
    queueReadReceipt();
1290
  }
1291
1292
  async function togglePin(room: RoomSummary): Promise<void> {
1293
    try {
1294
      await runCommand({ op: 'set_favourite', room_id: room.room_id, favourite: !room.favourite });
1295
    } catch (e) {
1296
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin');
1297
    }
1298
  }
1299
1300
  function startRailDrag(ev: DragEvent, id: string): void {
1301
    dragSpaceId = id;
1302
    if (ev.dataTransfer) {
1303
      ev.dataTransfer.effectAllowed = 'move';
1304
      ev.dataTransfer.setData('text/plain', id);
1305
    }
1306
  }
1307
1308
  function overRailSpace(ev: DragEvent, space: RoomSummary): void {
1309
    const dragged = orderedRail.find((s) => s.room_id === dragSpaceId);
1310
    if (!dragged || dragged.room_id === space.room_id || dragged.favourite !== space.favourite) return;
1311
    ev.preventDefault();
1312
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1313
    dropTarget = { id: space.room_id, after: ev.clientY > rect.top + rect.height / 2 };
1314
  }
1315
1316
  async function dropRailSpace(): Promise<void> {
1317
    const moved = dragSpaceId;
1318
    const target = dropTarget;
1319
    dragSpaceId = null;
1320
    dropTarget = null;
1321
    if (!moved || !target) return;
1322
    const ids = orderedRail.map((s) => s.room_id);
1323
    const before = target.after ? (ids[ids.indexOf(target.id) + 1] ?? null) : target.id;
1324
    const order = moveBefore(ids, moved, before === moved ? null : before);
1325
    if (order.join() === ids.join()) return;
1326
    railOverride = order;
1327
    try {
1328
      await runCommand({ op: 'reorder_spaces', order });
1329
    } catch (e) {
1330
      railOverride = null;
1331
      pushBanner(e instanceof Error ? e.message : 'Could not reorder spaces');
1332
    }
1333
  }
1334
1335
  let roomMenuOpen = false;
1336
  let roomMenuEl: HTMLDivElement | null = null;
1337
1338
  function roomMenuAction(action: () => void): void {
1339
    roomMenuOpen = false;
1340
    action();
1341
  }
1342
1343
  function closeRoomMenuOutside(ev: PointerEvent): void {
1344
    if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false;
1345
  }
1346
1347
  function onKeydown(ev: KeyboardEvent): void {
1348
    if (ev.key === 'Escape') {
1349
      if (roomMenuOpen) roomMenuOpen = false;
1350
      else if (dialog) dialog = null;
1351
      else if (membersOpen && window.innerWidth < 1100) membersOpen = false;
1352
      else if (sidebarOpen) sidebarOpen = false;
1353
    }
1354
  }
1355
</script>
1356
1357
<svelte:window
1358
  on:keydown={onKeydown}
1359
  on:pointerdown={closeRoomMenuOutside}
1360
  on:pointerup={() => (draggingScrollbar = false)}
1361
/>
1362
1363
{#if !booted}
1364
  <div class="splash" role="status" aria-label="Loading Malice">
1365
    <div class="splash-mark" aria-hidden="true">M</div>
1366
    <p>Loading Malice…</p>
1367
  </div>
1368
{:else if $blocked}
1369
  <div class="splash" role="status" aria-label="Malice is open in another tab">
1370
    <div class="splash-mark" aria-hidden="true">M</div>
1371
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
1372
  </div>
1373
{:else if $sessionUser == null}
1374
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
1375
{:else}
1376
  <div
1377
    class="app"
1378
    class:nav-folded={$navFolded && selectedRoom}
1379
    class:rail-folded={$railFolded && selectedRoom}
1380
    class:members-open={selectedRoom && membersOpen}
1381
    style:--msg-gap={`${$messageSpacing}px`}
1382
    style:--msg-line-height={$lineHeight}
1383
  >
1384
    <nav class="rail" aria-label="Servers and spaces">
1385
      <button
1386
        type="button"
1387
        class="rail-btn"
1388
        class:active={selectedSpaceId === null}
1389
        title="Home — all channels"
1390
        aria-label="Home — all channels"
1391
        aria-pressed={selectedSpaceId === null}
1392
        on:click={() => void selectHome()}
1393
      >
1394
        <span aria-hidden="true">⌂</span>
1395
      </button>
1396
      {#each [pinnedRail, otherRail] as group}
1397
        {#if group.length > 0}
1398
          <div class="rail-sep" aria-hidden="true"></div>
1399
        {/if}
1400
        {#each group as space (space.room_id)}
1401
          <button
1402
            type="button"
1403
            class="rail-btn rail-space"
1404
            class:active={railSelected === space.room_id}
1405
            class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after}
1406
            class:drop-after={dropTarget?.id === space.room_id && dropTarget.after}
1407
            class:pinned={space.favourite}
1408
            title={space.name}
1409
            aria-label={`Show channels in space ${space.name}`}
1410
            aria-pressed={selectedSpaceId === space.room_id}
1411
            draggable="true"
1412
            on:click={() => void selectSpace(space.room_id)}
1413
            on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)}
1414
            on:dragstart={(ev) => startRailDrag(ev, space.room_id)}
1415
            on:dragover={(ev) => overRailSpace(ev, space)}
1416
            on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)}
1417
            on:drop|preventDefault={() => void dropRailSpace()}
1418
            on:dragend={() => ((dragSpaceId = null), (dropTarget = null))}
1419
          >
1420
            <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
1421
          </button>
1422
        {/each}
1423
      {/each}
1424
      <button
1425
        type="button"
1426
        class="rail-btn rail-add"
1427
        aria-label="Join or create a room"
1428
        on:click={() => {
1429
          dialog = 'join';
1430
        }}
1431
      >
1432
        <span aria-hidden="true">+</span>
1433
      </button>
1434
    </nav>
1435
1436
    {#if menu}
1437
      <ContextMenu items={menu.items} x={menu.x} y={menu.y} onClose={() => (menu = null)} />
1438
    {/if}
1439
    {#if userCard}
1440
      {#key userCard}
1441
        {@const cardUser = userCard.userId}
1442
        <UserCard
1443
          person={personFor(cardUser)}
1444
          member={memberFor(cardUser)}
1445
          levels={roomLevels}
1446
          self={$sessionUser ?? null}
1447
          x={userCard.x}
1448
          y={userCard.y}
1449
          confirm={userCard.confirm}
1450
          onAction={(action) => void userAction(cardUser, action)}
1451
          onClose={() => (userCard = null)}
1452
        />
1453
      {/key}
1454
    {/if}
1455
1456
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
1457
      <div class="side-search">
1458
        <label class="visually-hidden" for="room-search">Search rooms</label>
1459
        <input
1460
          id="room-search"
1461
          type="search"
1462
          placeholder="Search rooms"
1463
          bind:value={search}
1464
          autocomplete="off"
1465
        />
1466
        <button
1467
          type="button"
1468
          class="icon-btn"
1469
          title="Refresh rooms"
1470
          aria-label="Refresh rooms"
1471
          disabled={roomsLoading}
1472
          on:click={() => void refreshRooms()}
1473
        >
1474
          <span aria-hidden="true">⟳</span>
1475
        </button>
1476
      </div>
1477
      <div class="side-scroll">
1478
        {#if selectedSpace}
1479
          <div class="space-context">
1480
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={28} shape="rounded" />
1481
            <div class="space-context-text">
1482
              <strong>{selectedSpace.name}</strong>
1483
            </div>
1484
            {#if spaceParents.has(selectedSpace.room_id)}
1485
              {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
1486
              <button
1487
                type="button"
1488
                class="icon-btn"
1489
                title="Up to the parent space"
1490
                aria-label="Up to the parent space"
1491
                on:click={() => void selectSpace(parentId)}
1492
              >
1493
                <span aria-hidden="true">↑</span>
1494
              </button>
1495
            {/if}
1496
          </div>
1497
        {:else}
1498
          <div class="space-context">
1499
            <div class="space-context-text">
1500
              <strong>Home</strong>
1501
            </div>
1502
          </div>
1503
        {/if}
1504
        {#if roomsLoading && $rooms.length === 0}
1505
          <p class="side-note">Loading rooms…</p>
1506
        {:else if $rooms.length === 0}
1507
          <p class="side-note">No rooms yet</p>
1508
          <div class="side-cta">
1509
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
1510
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
1511
          </div>
1512
        {:else}
1513
          {#if selectedSpaceId && spaceChildrenLoading}
1514
            <p class="side-note">Loading channels…</p>
1515
          {:else if selectedSpaceId && spaceChildrenError}
1516
            <p class="side-note" role="alert">{spaceChildrenError}</p>
1517
            <div class="side-cta">
1518
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
1519
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1520
            </div>
1521
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
1522
            <p class="side-note">No channels</p>
1523
            <div class="side-cta">
1524
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
1525
            </div>
1526
          {:else}
1527
            {#if invites.length > 0 && !selectedSpaceId}
1528
              <h2 class="side-h">Invites</h2>
1529
              <ul class="room-list">
1530
                {#each invites as room (room.room_id)}
1531
                  <li>
1532
                    <button
1533
                      type="button"
1534
                      class="room-row"
1535
                      class:active={$selectedRoomId === room.room_id}
1536
                      on:click={() => void selectRoom(room.room_id)}
1537
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1538
                    >
1539
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1540
                      <span class="room-name">{room.name}</span>
1541
                      <span
1542
                        class="invite-join"
1543
                        role="button"
1544
                        tabindex="0"
1545
                        aria-label={`Join ${room.name}`}
1546
                        on:click|stopPropagation={() => void join(room.room_id)}
1547
                        on:keydown|stopPropagation={(ev) => {
1548
                          if (ev.key === 'Enter' || ev.key === ' ') {
1549
                            ev.preventDefault();
1550
                            void join(room.room_id);
1551
                          }
1552
                        }}
1553
                      >
1554
                        Join
1555
                      </span>
1556
                    </button>
1557
                  </li>
1558
                {/each}
1559
              </ul>
1560
            {/if}
1561
1562
            {#if directRooms.length > 0}
1563
              <h2 class="side-h">Direct messages</h2>
1564
              <ul class="room-list">
1565
                {#each directRooms as room (room.room_id)}
1566
                  <li class="room-item">
1567
                    <button
1568
                      type="button"
1569
                      class="room-row"
1570
                      class:active={$selectedRoomId === room.room_id}
1571
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
1572
                      on:click={() => void selectRoom(room.room_id)}
1573
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1574
                    >
1575
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
1576
                      <span class="room-name">{room.name}</span>
1577
                      {#if roomUnread(room) > 0}
1578
                        <span
1579
                          class="badge"
1580
                          class:mention={room.unread_mentions > 0}
1581
                          aria-label={`${roomUnread(room)} unread`}
1582
                        >
1583
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
1584
                        </span>
1585
                      {/if}
1586
                    </button>
1587
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
1588
                  </li>
1589
                {/each}
1590
              </ul>
1591
            {/if}
1592
1593
            {#if groupRooms.length > 0}
1594
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
1595
              <ul class="room-list">
1596
                {#each groupRooms as room (room.room_id)}
1597
                  <li class="room-item">
1598
                    <button
1599
                      type="button"
1600
                      class="room-row"
1601
                      class:active={$selectedRoomId === room.room_id}
1602
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
1603
                      on:click={() => void selectRoom(room.room_id)}
1604
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1605
                    >
1606
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1607
                      <span class="room-hash" aria-hidden="true">#</span>
1608
                      <span class="room-name">{room.name}</span>
1609
                      {#if roomUnread(room) > 0}
1610
                        <span
1611
                          class="badge"
1612
                          class:mention={room.unread_mentions > 0}
1613
                          aria-label={`${roomUnread(room)} unread`}
1614
                        >
1615
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
1616
                        </span>
1617
                      {/if}
1618
                    </button>
1619
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
1620
                  </li>
1621
                {/each}
1622
              </ul>
1623
            {/if}
1624
1625
            {#if spaceList.length > 0}
1626
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
1627
              <ul class="room-list">
1628
                {#each spaceList as room (room.room_id)}
1629
                  <li class="room-item">
1630
                    <button
1631
                      type="button"
1632
                      class="room-row"
1633
                      class:active={selectedSpaceId === room.room_id}
1634
                      aria-label={`Show channels in space ${room.name}`}
1635
                      on:click={() => void selectSpace(room.room_id)}
1636
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
1637
                    >
1638
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
1639
                      <span class="room-hash" aria-hidden="true">◇</span>
1640
                      <span class="room-name">{room.name}</span>
1641
                    </button>
1642
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
1643
                  </li>
1644
                {/each}
1645
              </ul>
1646
            {/if}
1647
1648
            {#if query && visibleRooms.length === 0}
1649
              <p class="side-note">No rooms match “{search.trim()}”.</p>
1650
            {/if}
1651
          {/if}
1652
        {/if}
1653
      </div>
1654
1655
      <div class="side-footer">
1656
        <div class="me" title={$sessionUser}>
1657
          {#if profileMxc}
1658
            <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={30} />
1659
          {:else}
1660
            <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
1661
          {/if}
1662
          <span class="me-id">{profile?.display_name && profile.display_name !== $sessionUser ? `${profile.display_name} (${$sessionUser})` : $sessionUser}</span>
1663
        </div>
1664
        <button
1665
          type="button"
1666
          class="icon-btn"
1667
          title="Encryption and verification"
1668
          aria-label="Encryption and verification"
1669
          on:click={() => (dialog = 'security')}
1670
        >
1671
          <span aria-hidden="true">🛡</span>
1672
        </button>
1673
        <button
1674
          type="button"
1675
          class="icon-btn"
1676
          title="Settings"
1677
          aria-label="Settings"
1678
          on:click={() => (dialog = 'settings')}
1679
        >
1680
          <span aria-hidden="true">⚙</span>
1681
        </button>
1682
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
1683
          <span aria-hidden="true">⏻</span>
1684
        </button>
1685
      </div>
1686
    </aside>
1687
    {#if sidebarOpen}
1688
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
1689
    {/if}
1690
1691
    <main class="chat">
1692
        {#if $banners.length > 0}
1693
          <div class="banners" aria-live="polite">
1694
            {#each $banners as banner (banner.id)}
1695
              <div class="banner" role="alert">
1696
                <span>{banner.message}</span>
1697
                <button
1698
                  type="button"
1699
                  aria-label="Dismiss error"
1700
                  on:click={() => dismissBanner(banner.id)}
1701
                >
1702
                  ✕
1703
                </button>
1704
              </div>
1705
            {/each}
1706
          </div>
1707
        {/if}
1708
      {#if !selectedRoom}
1709
        <div class="empty">
1710
          <div class="empty-mark" aria-hidden="true">◈</div>
1711
          {#if selectedSpace}
1712
            <h1>{selectedSpace.name}</h1>
1713
          {:else}
1714
            <h1>Welcome to Malice</h1>
1715
          {/if}
1716
          <div class="empty-cta">
1717
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
1718
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
1719
          </div>
1720
          <p class="conn-line">
1721
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1722
            {$connection}
1723
          </p>
1724
        </div>
1725
      {:else}
1726
        <header class="chat-head">
1727
          <button
1728
            type="button"
1729
            class="icon-btn only-mobile"
1730
            aria-label="Open room list"
1731
            on:click={() => (sidebarOpen = true)}
1732
          >
1733
            <span aria-hidden="true">☰</span>
1734
          </button>
1735
          <button
1736
            type="button"
1737
            class="icon-btn only-desktop pane-toggle"
1738
            aria-pressed={!$railFolded}
1739
            aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1740
            title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1741
            on:click={() => railFolded.update((v) => !v)}
1742
          >
1743
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1744
              <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1745
              <circle cx="7" cy="9" r="1.4" fill="currentColor" />
1746
              <circle cx="7" cy="13" r="1.4" fill="currentColor" />
1747
              <circle cx="7" cy="17" r="1.4" fill="currentColor" />
1748
            </svg>
1749
          </button>
1750
          <button
1751
            type="button"
1752
            class="icon-btn only-desktop pane-toggle"
1753
            aria-pressed={!$navFolded}
1754
            aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
1755
            title={$navFolded ? 'Show channels' : 'Hide channels'}
1756
            on:click={() => navFolded.update((v) => !v)}
1757
          >
1758
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1759
              <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
1760
              <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
1761
            </svg>
1762
          </button>
1763
          <div class="head-title">
1764
            <div class="head-room">
1765
              <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape={selectedRoom.space ? 'rounded' : 'circle'} />
1766
              <div class="head-room-text">
1767
                <h1>{selectedRoom.name}</h1>
1768
                <div class="head-meta">
1769
                  {#if selectedRoom.space}
1770
                    <span class="pill">space</span>
1771
                  {/if}
1772
                  {#if selectedRoom.encrypted}
1773
                    <span class="pill" title="End-to-end encrypted">🔒 encrypted</span>
1774
                  {/if}
1775
                  {#if selectedRoom.direct}
1776
                    <span class="pill">direct</span>
1777
                  {/if}
1778
                  <span class="conn" title={`Sync state: ${$connection}`}>
1779
                    <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
1780
                    {$connection}
1781
                  </span>
1782
                </div>
1783
              </div>
1784
            </div>
1785
          </div>
1786
          <div class="head-actions">
1787
            {#if peeking === selectedRoom.room_id}
1788
              <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}>
1789
                <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1790
                  <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" />
1791
                  <circle cx="12" cy="12" r="3" fill="currentColor" />
1792
                </svg>
1793
              </button>
1794
            {/if}
1795
            {#if selectedRoom.membership !== 'Joined'}
1796
              <button
1797
                type="button"
1798
                class="primary-btn"
1799
                disabled={joinBusy}
1800
                on:click={() => void join(selectedRoom.room_id)}
1801
              >
1802
                {joinBusy ? 'Joining…' : 'Join'}
1803
              </button>
1804
            {/if}
1805
            <button
1806
              type="button"
1807
              class="icon-btn"
1808
              aria-pressed={membersOpen}
1809
              aria-label={membersOpen ? 'Hide members' : 'Show members'}
1810
              title="Members"
1811
              on:click={toggleMembers}
1812
            >
1813
              <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
1814
                <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
1815
                <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
1816
              </svg>
1817
            </button>
1818
            <div class="room-menu-wrap" bind:this={roomMenuEl}>
1819
              <button
1820
                type="button"
1821
                class="icon-btn"
1822
                aria-haspopup="menu"
1823
                aria-expanded={roomMenuOpen}
1824
                aria-label="Room options"
1825
                title="Room options"
1826
                on:click={() => (roomMenuOpen = !roomMenuOpen)}
1827
              >
1828
                <span aria-hidden="true">⋯</span>
1829
              </button>
1830
              {#if roomMenuOpen}
1831
                <div class="room-menu" role="menu">
1832
                  <button type="button" role="menuitem" on:click={() => roomMenuAction(() => (dialog = 'security'))}>
1833
                    Security
1834
                  </button>
1835
                  {#if selectedRoom.membership === 'Joined'}
1836
                    <button
1837
                      type="button"
1838
                      role="menuitem"
1839
                      class="danger"
1840
                      disabled={leaveBusy}
1841
                      on:click={() => roomMenuAction(() => void leave())}
1842
                    >
1843
                      {leaveBusy ? 'Leaving…' : 'Leave room'}
1844
                    </button>
1845
                  {/if}
1846
                </div>
1847
              {/if}
1848
            </div>
1849
          </div>
1850
        </header>
1851
1852
1853
        {#if recoveryBanner}
1854
          <div class="sec-banner warn" role="status">
1855
            <span>Message history is locked</span>
1856
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
1857
          </div>
1858
        {/if}
1859
        {#if verificationBanner}
1860
          <div class="sec-banner" role="status">
1861
            {#if verificationBanner.kind === 'Incoming'}
1862
              <span>A device wants to verify this session</span>
1863
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
1864
            {:else if verificationBanner.kind === 'Comparison'}
1865
              <span>Verification codes ready</span>
1866
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
1867
            {:else if verificationBanner.kind === 'Waiting'}
1868
              <span>Verification started</span>
1869
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
1870
            {:else if verificationBanner.kind === 'Failed'}
1871
              <span>Verification failed: {verificationBanner.message}</span>
1872
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
1873
            {:else if verificationBanner.kind === 'Cancelled'}
1874
              <span>Verification cancelled: {verificationBanner.reason}</span>
1875
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
1876
            {:else}
1877
              <span>Verification in progress</span>
1878
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
1879
            {/if}
1880
          </div>
1881
        {/if}
1882
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
1883
          <p class="conn-banner error" role="alert">{openFailed[$selectedRoomId]}</p>
1884
        {/if}
1885
1886
        <!-- svelte-ignore a11y_no_static_element_interactions -->
1887
        <div
1888
          class="timeline"
1889
          bind:this={timelineEl}
1890
          on:scroll={onTimelineScroll}
1891
          on:wheel={noteUserScroll}
1892
          on:touchmove={noteUserScroll}
1893
          on:keydown={onTimelineKey}
1894
          on:pointerdown={onTimelinePointer}
1895
          aria-label={`Messages in ${selectedRoom.name}`}
1896
        >
1897
          <div class="timeline-inner" use:pinTimeline>
1898
            <div class="timeline-top">
1899
              {#if hasStart}
1900
                <p class="start-note">Beginning of history</p>
1901
              {:else}
1902
                <button type="button" class="ghost-btn" disabled={paginateBusy} on:click={() => void paginate()}>
1903
                  {paginateBusy ? 'Loading…' : 'Load older messages'}
1904
                </button>
1905
              {/if}
1906
            </div>
1907
            {#if grouped.length === 0}
1908
              <p class="side-note timeline-empty">No messages yet</p>
1909
            {:else}
1910
              {#each grouped as g (g.key)}
1911
                {#if g.item.kind === 'day'}
1912
                  <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div>
1913
                {:else if g.item.kind === 'readMarker'}
1914
                  <div class="new-row"><span>New</span></div>
1915
                {:else if g.item.kind === 'start'}
1916
                  <p class="start-note">Beginning of history</p>
1917
                {:else if g.item.kind === 'unknown'}
1918
                  <p class="unknown-note">Unsupported event ({g.item.label})</p>
1919
                {:else}
1920
                  <MessageRow
1921
                    itemId={g.key}
1922
                    event={g.item.event}
1923
                    showSender={g.showSender}
1924
                    senderAvatar={senderAvatarFor(g.item.event.sender.user_id) ?? g.item.event.sender.avatar}
1925
                    {reacting}
1926
                    onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
1927
                    quickReactions={$quickReactions}
1928
                    packs={roomPacks}
1929
                    linkPreviews={$linkPreviews}
1930
                    {loadPreview}
1931
                    onQuickChange={(list) => void changeQuickReactions(list)}
1932
                    {people}
1933
                    self={$sessionUser ?? null}
1934
                    onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
1935
                    onReply={selectedRoom.membership === 'Joined' ? startReply : null}
1936
                    onJump={jumpTo}
1937
                    onEdit={selectedRoom.membership === 'Joined' ? startEdit : null}
1938
                    editing={editing !== null && editing.eventId === g.item.event.event_id}
1939
                    showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0}
1940
                  />
1941
                {/if}
1942
              {/each}
1943
            {/if}
1944
            {#each pendingItems as p, i (p.id)}
1945
              <MessageRow
1946
                itemId={`pending-${p.id}`}
1947
                event={pendingToEvent(p)}
1948
                onJump={jumpTo}
1949
                showSender={pendingShowSender(i)}
1950
                senderAvatar={senderAvatarFor($sessionUser ?? '')}
1951
                {reacting}
1952
                onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
1953
                quickReactions={$quickReactions}
1954
                packs={roomPacks}
1955
                linkPreviews={$linkPreviews}
1956
                {loadPreview}
1957
                onQuickChange={(list) => void changeQuickReactions(list)}
1958
              />
1959
              {#if p.status === 'failed'}
1960
                <div class="pending-actions">
1961
                  <span class="pending-error" role="alert">{p.error}</span>
1962
                  <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button>
1963
                  <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button>
1964
                </div>
1965
              {/if}
1966
            {/each}
1967
          </div>
1968
        </div>
1969
1970
        {#if selectedRoom.membership === 'Joined'}
1971
          {#if editing}
1972
            <div class="reply-bar" role="status">
1973
              <span class="reply-bar-label">
1974
                Editing message
1975
                <span class="reply-bar-text">{editing.original}</span>
1976
              </span>
1977
              <button type="button" class="icon-btn" aria-label="Cancel edit" title="Cancel edit (Esc)" on:click={cancelEdit}>
1978
                <span aria-hidden="true">✕</span>
1979
              </button>
1980
            </div>
1981
          {:else if replyingTo && replyingTo.details.kind === 'Ready'}
1982
            <div class="reply-bar" role="status">
1983
              <span class="reply-bar-label">
1984
                Replying to <strong>{senderLabel(replyingTo.details.sender)}</strong>
1985
                <span class="reply-bar-text">{contentPreview(replyingTo.details.content)}</span>
1986
              </span>
1987
              <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}>
1988
                <span aria-hidden="true">✕</span>
1989
              </button>
1990
            </div>
1991
          {/if}
1992
          {#if $selectedRoomId && currentStaged.length > 0}
1993
            {@const stagedRoom = $selectedRoomId}
1994
            <ul class="staged" aria-label="Attachments to send">
1995
              {#each currentStaged as attachment (attachment.id)}
1996
                <li class="staged-item">
1997
                  {#if attachment.previewUrl}
1998
                    <img src={attachment.previewUrl} alt={attachment.file.name || 'Pasted image'} />
1999
                  {:else}
2000
                    <span class="staged-name">{attachment.file.name || 'attachment'}</span>
2001
                  {/if}
2002
                  <button
2003
                    type="button"
2004
                    class="icon-btn staged-remove"
2005
                    aria-label={`Remove ${attachment.file.name || 'attachment'}`}
2006
                    title="Remove"
2007
                    on:click={() => unstage(stagedRoom, attachment.id)}
2008
                  >
2009
                    <span aria-hidden="true">✕</span>
2010
                  </button>
2011
                </li>
2012
              {/each}
2013
            </ul>
2014
          {/if}
2015
          <form class="composer" class:replying={replyingTo || editing} class:staging={currentStaged.length > 0} on:submit|preventDefault={() => send()}>
2016
            <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label>
2017
            {#if mentionQuery && mentionCandidates.length > 0}
2018
              <ul class="mention-finder" role="listbox" aria-label="Mention someone">
2019
                {#each mentionCandidates as person, i (person.user_id)}
2020
                  <li
2021
                    role="option"
2022
                    aria-selected={i === mentionIndex}
2023
                    class:active={i === mentionIndex}
2024
                    on:pointerdown|preventDefault={() => void pickMention(person)}
2025
                    on:pointerenter={() => (mentionIndex = i)}
2026
                  >
2027
                    <MxcAvatar mxc={person.avatar} label={person.name} size={22} />
2028
                    <span class="mention-name">{person.name}</span>
2029
                    <span class="mention-id">{person.user_id}</span>
2030
                  </li>
2031
                {/each}
2032
              </ul>
2033
            {/if}
2034
            <input
2035
              type="file"
2036
              multiple
2037
              bind:this={fileInput}
2038
              class="visually-hidden"
2039
              aria-label="Attach a file"
2040
              on:change={() => void onFileChosen()}
2041
            />
2042
            <input
2043
              type="file"
2044
              accept="image/*"
2045
              bind:this={avatarInput}
2046
              class="visually-hidden"
2047
              aria-label="Choose a new avatar"
2048
              on:change={() => void onAvatarChosen()}
2049
            />
2050
            <button
2051
              type="button"
2052
              class="ghost-btn"
2053
              title="Attach an image or file"
2054
              aria-label="Attach an image or file"
2055
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2056
              on:click={pickFiles}
2057
            >
2058
              {uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : '📎'}
2059
            </button>
2060
            <textarea
2061
              id="composer"
2062
              bind:this={composerEl}
2063
              bind:value={composer}
2064
              rows="1"
2065
              placeholder={`Message ${selectedRoom.name}`}
2066
              aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`}
2067
              on:keydown={onComposerKey}
2068
              on:input={updateMentionQuery}
2069
              on:click={updateMentionQuery}
2070
              on:keyup={(e) => (e.key.startsWith('Arrow') && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') || e.key === 'Home' || e.key === 'End' ? updateMentionQuery() : undefined}
2071
              on:blur={() => (mentionQuery = null)}
2072
              on:paste={onComposerPaste}
2073
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2074
            ></textarea>
2075
            <button
2076
              type="button"
2077
              class="icon-btn md-toggle"
2078
              aria-pressed={$markdownEnabled}
2079
              aria-label={$markdownEnabled ? 'Turn markdown off' : 'Turn markdown on'}
2080
              title={$markdownEnabled ? 'Markdown on' : 'Markdown off'}
2081
              on:click={() => markdownEnabled.update((v) => !v)}
2082
            >
2083
              <svg viewBox="0 0 24 16" width="22" height="15" aria-hidden="true">
2084
                <rect x="1" y="1" width="22" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="1.6" />
2085
                <path d="M4.5 11.5v-7l2.75 3 2.75-3v7M15.5 4.5v6.5M13 8.5l2.5 2.75L18 8.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" />
2086
              </svg>
2087
            </button>
2088
            <button
2089
              type="submit"
2090
              class="primary-btn"
2091
              disabled={(!composer.trim() && currentStaged.length === 0) ||
2092
                !($selectedRoomId && openReady[$selectedRoomId]) ||
2093
                (currentStaged.length > 0 && uploadBusy)}
2094
              title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'}
2095
            >
2096
              Send
2097
            </button>
2098
          </form>
2099
        {:else}
2100
          <div class="join-bar">
2101
            <p>You are not a member of this room.</p>
2102
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
2103
              {joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`}
2104
            </button>
2105
          </div>
2106
        {/if}
2107
      {/if}
2108
    </main>
2109
2110
    {#if selectedRoom}
2111
      <aside class="members" aria-hidden={!membersOpen} aria-label={`Members of ${selectedRoom.name}`}>
2112
        <div class="members-head">
2113
          <h2>Members</h2>
2114
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
2115
            <span aria-hidden="true">✕</span>
2116
          </button>
2117
        </div>
2118
        {#if $membersLoading && members.length === 0}
2119
          <p class="side-note">Loading members…</p>
2120
        {:else if members.length === 0}
2121
          <p class="side-note">No members loaded.</p>
2122
          {#if $selectedRoomId}
2123
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
2124
              Retry
2125
            </button>
2126
          {/if}
2127
        {:else}
2128
          <ul class="member-list">
2129
            {#each members as member (member.user_id)}
2130
              <li>
2131
                <button
2132
                  type="button"
2133
                  class="member"
2134
                  on:click={(ev) => {
2135
                    const rect = ev.currentTarget.getBoundingClientRect();
2136
                    void openUser(member.user_id, rect.left - 308, rect.top, false);
2137
                  }}
2138
                  on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)}
2139
                >
2140
                  <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} size={30} />
2141
                  <span class="member-names">
2142
                    <span class="member-name">{member.display_name || member.name}</span>
2143
                    <span class="member-id">{member.user_id}</span>
2144
                  </span>
2145
                </button>
2146
              </li>
2147
            {/each}
2148
          </ul>
2149
        {/if}
2150
      </aside>
2151
    {/if}
2152
2153
    {#if dialog}
2154
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
2155
        {#if dialog === 'security'}
2156
          <SecurityPanel
2157
            encryptionState={$encryption}
2158
            verificationState={$verification}
2159
            onAction={() => void loadEncryption()}
2160
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
2161
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
2162
            on:close={() => (dialog = null)}
2163
          />
2164
        {:else if dialog === 'settings'}
2165
          <SettingsPanel
2166
            quick={$quickReactions}
2167
            packs={roomPacks}
2168
            onQuickChange={(list) => void changeQuickReactions(list)}
2169
            on:close={() => (dialog = null)}
2170
          />
2171
        {:else}
2172
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
2173
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
2174
              <button
2175
                type="button"
2176
                role="tab"
2177
                aria-selected={dialog === 'join'}
2178
                class:active={dialog === 'join'}
2179
                on:click={() => (dialog = 'join')}
2180
              >
2181
                Join
2182
              </button>
2183
              <button
2184
                type="button"
2185
                role="tab"
2186
                aria-selected={dialog === 'create'}
2187
                class:active={dialog === 'create'}
2188
                on:click={() => (dialog = 'create')}
2189
              >
2190
                Create
2191
              </button>
2192
              <button
2193
                type="button"
2194
                class="icon-btn modal-x"
2195
                aria-label="Close dialog"
2196
                on:click={() => (dialog = null)}
2197
              >
2198
                <span aria-hidden="true">✕</span>
2199
              </button>
2200
            </div>
2201
            {#if dialog === 'join'}
2202
              <form on:submit|preventDefault={() => void join(joinTarget)}>
2203
                <label class="field">
2204
                  <span>Room ID or alias</span>
2205
                  <input
2206
                    type="text"
2207
                    placeholder="!room:example.org or #alias:example.org"
2208
                    bind:value={joinTarget}
2209
                    required
2210
                    disabled={joinBusy}
2211
                  />
2212
                </label>
2213
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
2214
                  {joinBusy ? 'Joining…' : 'Join room'}
2215
                </button>
2216
              </form>
2217
            {:else}
2218
            <form on:submit|preventDefault={() => void create()}>
2219
              <label class="field">
2220
                <span>Room name</span>
2221
                <input
2222
                  type="text"
2223
                  placeholder="Weekend plans"
2224
                  bind:value={createName}
2225
                  required
2226
                  disabled={createBusy}
2227
                />
2228
              </label>
2229
              <label class="field">
2230
                <span>Topic (optional)</span>
2231
                <input
2232
                  type="text"
2233
                  placeholder="What should this room be about?"
2234
                  bind:value={createTopic}
2235
                  disabled={createBusy}
2236
                />
2237
              </label>
2238
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
2239
                {createBusy ? 'Creating…' : 'Create room'}
2240
              </button>
2241
            </form>
2242
            {/if}
2243
          </div>
2244
        {/if}
2245
      </div>
2246
    {/if}
2247
  </div>
2248
{/if}
2249
2250
<ImageLightbox />