atagen

malice

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