atagen

malice

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