atagen

malice

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