atagen

malice

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