atagen

malice

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