atagen

malice

public
Star0
Watch0
e8b4da01b15cf4d776538d0e320821016aff30d8
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/App.svelteSvelte3009 lines120.7 KB
1
<script lang="ts">
2
  import { onMount, tick } from 'svelte';
3
  import { fade, fly } from 'svelte/transition';
4
  import LoginPanel from './lib/LoginPanel.svelte';
5
  import MessageRow from './lib/MessageRow.svelte';
6
  import MentionsInbox from './lib/MentionsInbox.svelte';
7
  import HistoryRepairPanel from './lib/HistoryRepairPanel.svelte';
8
  import type { HistoryRepairPolicy, HistoryRepairReport } from './lib/repair-model';
9
  import MxcAvatar from './lib/MxcAvatar.svelte';
10
  import PinButton from './lib/PinButton.svelte';
11
  import ContextMenu, { type MenuItem } from './lib/ContextMenu.svelte';
12
  import StickerPicker from './lib/StickerPicker.svelte';
13
  import PackManager from './lib/PackManager.svelte';
14
  import PackCloneDialog from './lib/PackCloneDialog.svelte';
15
  import type { CloneSource } from './lib/pack-clone';
16
  import { allPacks, findSticker, reactionShortcode } from './lib/packs';
17
  import { disabledPackImages, loadPackPreferences } from './lib/pack-preferences';
18
  import { enabledPacks, enabledQuickReactions } from './lib/pack-preferences-model';
19
  import type { CommandRequest } from './lib/transport';
20
  import UserCard, { type UserAction } from './lib/UserCard.svelte';
21
  import { allowed, canRedact, groupMembers, isMuted, parsePowerLevels, type PowerLevels } from './lib/permissions';
22
  import { moveBefore, pinnedFirst, sortSpaces } from './lib/rail-order';
23
  import ImageLightbox from './lib/ImageLightbox.svelte';
24
  import { lightbox } from './lib/lightbox';
25
  import SecurityPanel from './lib/SecurityPanel.svelte';
26
  import {
27
    closeRoom,
28
    createRoom,
29
    getEncryption,
30
    getMembers,
31
    getProfile,
32
    getRooms,
33
    getSession,
34
    getSpaceChildren,
35
    historyRepair,
36
    continueHistoryRepair,
37
    cancelHistoryRepair,
38
    startRecentHistory,
39
    joinRoom,
40
    leaveRoom,
41
    logout,
42
    markRead,
43
    openRoom,
44
    paginateRoom,
45
    reactToMessage,
46
    runCommand,
47
    sendMessage,
48
    uploadAttachment,
49
    uploadAvatar,
50
    uploadRoomAvatar,
51
    editMessage,
52
    mediaUrl
53
  } from './lib/api';
54
  import EmojiText from './lib/EmojiText.svelte';
55
  import { loadEmoji, type EmojiEntry } from './lib/emoji';
56
  import { completeShortcode, customEmotes, emoteQueryAt, rankEmotes, resolveEmotes, type EmoteCandidate, type EmoteQuery } from './lib/emotes';
57
  import { COMMAND_USAGE, commandQueryAt, isKnownCommand, matchCommands, parseCommand, splitTarget, unescapeCommand } from './lib/commands';
58
  import type { CommandName } from './lib/commands';
59
  import type { ParsedCommand } from './lib/commands';
60
  import {
61
    banners,
62
    blocked,
63
    connectEvents,
64
    connection,
65
    disconnectEvents,
66
    dismissBanner,
67
    encryption,
68
    membersByRoom,
69
    membersLoading,
70
    mentionsSnapshot,
71
    pushBanner,
72
    imagePacks,
73
    historyRepairs,
74
    publishHistoryRepair,
75
    resetClientState,
76
    rooms,
77
    selectedRoomId,
78
    sessionUser,
79
    softLogout,
80
    timelines,
81
    pinnedTimelines,
82
    pinnedTimelineVersions,
83
    verification
84
  } from './lib/store';
85
  import { discardPending, pendingByRoom, queueSend, resetPending, retryPending } from './lib/pending';
86
  import type { PendingMessage } from './lib/pending';
87
  import { insideOpenFence } from './lib/markdown';
88
  import { TimelineViewport } from './lib/timeline-viewport';
89
  import ComposerText from './lib/ComposerText.svelte';
90
  import { markMentions } from './lib/composer-marks';
91
  import { mentionQueryAt, mentionsFromHtml, rankPeople, resolveMentions } from './lib/mentions';
92
  import type { Mention, MentionQuery } from './lib/mentions';
93
  import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions';
94
  import {
95
    linkPreviews,
96
    loadUrlPreviewSettings,
97
    requestLinkPreview,
98
    saveUrlPreviewSettings,
99
    urlPreviewSettings
100
  } from './lib/link-previews';
101
  import { notifyTyping, stopTyping } from './lib/typing';
102
  import { formatDay } from './lib/format';
103
  import {
104
    MEMBERS_WIDTH,
105
    SIDE_WIDTH,
106
    lastSpaceRooms,
107
    lineHeight,
108
    membersWidth,
109
    messageSpacing,
110
    navFolded,
111
    railFolded,
112
    sideWidth
113
  } from './lib/appearance';
114
  import SettingsPanel from './lib/SettingsPanel.svelte';
115
  import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types';
116
  import type { ImagePack, MemberSummary, OwnProfile, PackImage, Person, QuickReaction, ReplyReference, RoomSummary, SendState, TimelineEvent, TimelineItem } from './lib/types';
117
118
  let roomsLoading = false;
119
  let booted = false;
120
  let wasOnline = false;
121
  let search = '';
122
  let sidebarOpen = false;
123
  let membersOpen = false;
124
  let replyingTo: ReplyReference | null = null;
125
  let dialog: 'join' | 'create' | 'security' | 'settings' | 'packs' | null = null;
126
  let stickersOpen = false;
127
  let cloneSource: CloneSource | null = null;
128
  let joinTarget = '';
129
  let joinBusy = false;
130
  let createName = '';
131
  let createTopic = '';
132
  let createBusy = false;
133
  let leaveBusy = false;
134
  let paginateBusy = false;
135
  let reacting = false;
136
  let composer = '';
137
  let drafts: Record<string, string> = {};
138
  let stickToBottom = true;
139
  let timelineEl: HTMLElement | null = null;
140
  let timelineViewport: TimelineViewport | null = null;
141
  let composerEl: HTMLTextAreaElement | null = null;
142
  let marksEl: HTMLDivElement | null = null;
143
  let composerComposing = false;
144
  $: composerMarks = markMentions(
145
    composer,
146
    ($selectedRoomId && pickedMentions[$selectedRoomId]) || [],
147
    resolveEmotes(composer, roomEmotes).map((e) => `:${e.shortcode}:`)
148
  );
149
  let fileInput: HTMLInputElement | null = null;
150
  let avatarInput: HTMLInputElement | null = null;
151
  let uploadBusy = false;
152
  let uploadName: string | null = null;
153
  interface StagedAttachment {
154
    id: number;
155
    file: File;
156
    previewUrl: string | null;
157
  }
158
  let staged: Record<string, StagedAttachment[]> = {};
159
  let editing: { roomId: string; eventId: string; original: string; stash: string } | null = null;
160
  /** Everyone picked from the finder per room; only those whose name is still in the text get linked on send. */
161
  let pickedMentions: Record<string, Mention[]> = {};
162
  let mentionQuery: MentionQuery | null = null;
163
  let mentionIndex = 0;
164
  let nextStagedId = 1;
165
  const WARM_ROOM_LIMIT = 8;
166
  /** Rooms left open after switching away so coming back is instant, least recently viewed first. */
167
  let warmRooms: string[] = [];
168
  let openReady: Record<string, boolean> = {};
169
  let openFailed: Record<string, string> = {};
170
  let membersFor: string | null = null;
171
  let lastReadKey = '';
172
  let readTimer: number | null = null;
173
  let profile: OwnProfile | null = null;
174
  let profileMxc: string | null = null;
175
  let selectedSpaceId: string | null = null;
176
  let mentionsOpen = false;
177
  let spaceChildIds: string[] | null = null;
178
  let spaceChildrenLoading = false;
179
  let spaceChildrenError: string | null = null;
180
  let avatarByUser: Record<string, string | null> = {};
181
  let restoringRoute = false;
182
  let repairPanels: Record<string, boolean> = {};
183
  let repairBusy: Record<string, boolean> = {};
184
  let repairCancelling: Record<string, boolean> = {};
185
  let repairErrors: Record<string, string | null> = {};
186
  let repairJumps: Record<string, { previous: HistoryRepairReport | null }> = {};
187
  let repairAccount: string | null | undefined;
188
  let repairEpoch = 0;
189
  $: if ($sessionUser !== repairAccount) {
190
    repairAccount = $sessionUser;
191
    repairEpoch++;
192
    repairPanels = {};
193
    repairBusy = {};
194
    repairCancelling = {};
195
    repairErrors = {};
196
    repairJumps = {};
197
  }
198
  $: currentRepair = $selectedRoomId ? $historyRepairs[$selectedRoomId] ?? null : null;
199
  $: currentRepairActive = !!($selectedRoomId && repairBusy[$selectedRoomId]) || repairActive(currentRepair);
200
  $: maybeJumpAfterRepair($selectedRoomId, currentRepair, repairJumps);
201
  $: settleRepairCancellation($historyRepairs, repairBusy);
202
203
  function repairActive(report: HistoryRepairReport | null | undefined): boolean {
204
    return report?.phase === 'FetchingRecent' || report?.phase === 'Bridging';
205
  }
206
207
  function settleRepairCancellation(reports: Record<string, HistoryRepairReport>, busy: Record<string, boolean>): void {
208
    for (const [roomId, report] of Object.entries(reports)) {
209
      if (repairCancelling[roomId] && !busy[roomId] && !repairActive(report)) {
210
        repairCancelling = { ...repairCancelling, [roomId]: false };
211
      }
212
    }
213
  }
214
215
  function maybeJumpAfterRepair(roomId: string | null, report: HistoryRepairReport | null, jumps: typeof repairJumps): void {
216
    if (!roomId || roomId !== $selectedRoomId || !report?.recent_available || !jumps[roomId] || report === jumps[roomId].previous) return;
217
    const next = { ...repairJumps };
218
    delete next[roomId];
219
    repairJumps = next;
220
    stickToBottom = true;
221
    const epoch = repairEpoch;
222
    void tick().then(() => {
223
      if (epoch === repairEpoch && $selectedRoomId === roomId) scrollToBottom();
224
    });
225
  }
226
227
  async function showHistoryRepair(roomId: string): Promise<void> {
228
    if ($selectedRoomId !== roomId) await selectRoom(roomId);
229
    if ($selectedRoomId === roomId) repairPanels = { ...repairPanels, [roomId]: true };
230
  }
231
232
  async function runHistoryRepair(roomId: string, action: 'start' | 'continue' | 'recent', policy: HistoryRepairPolicy | null = null): Promise<void> {
233
    if (!$sessionUser || repairBusy[roomId] || repairActive($historyRepairs[roomId]) || repairCancelling[roomId]) return;
234
    const account = $sessionUser;
235
    const epoch = repairEpoch;
236
    repairPanels = { ...repairPanels, [roomId]: true };
237
    repairBusy = { ...repairBusy, [roomId]: true };
238
    repairErrors = { ...repairErrors, [roomId]: null };
239
    if (action !== 'continue') repairJumps = { ...repairJumps, [roomId]: { previous: $historyRepairs[roomId] ?? null } };
240
    try {
241
      if (!openReady[roomId]) {
242
        await openRoom(roomId);
243
        if ($sessionUser !== account || epoch !== repairEpoch) return;
244
        openReady = { ...openReady, [roomId]: true };
245
        const failures = { ...openFailed };
246
        delete failures[roomId];
247
        openFailed = failures;
248
        touchWarmRoom(roomId);
249
      }
250
      if (repairCancelling[roomId]) return;
251
      const report = action === 'continue' ? await continueHistoryRepair(roomId)
252
        : action === 'recent' ? await startRecentHistory(roomId) : await historyRepair(roomId, policy);
253
      if ($sessionUser !== account || epoch !== repairEpoch) return;
254
      if (report.room_id !== roomId) throw new Error('History repair returned a different room');
255
      publishHistoryRepair(report, account);
256
      maybeJumpAfterRepair(roomId, report, repairJumps);
257
    } catch (cause) {
258
      if ($sessionUser === account && epoch === repairEpoch) {
259
        repairErrors = { ...repairErrors, [roomId]: cause instanceof Error ? cause.message : 'Could not repair history' };
260
      }
261
    } finally {
262
      if ($sessionUser === account && epoch === repairEpoch) {
263
        repairBusy = { ...repairBusy, [roomId]: false };
264
        repairCancelling = { ...repairCancelling, [roomId]: false };
265
        if (repairJumps[roomId]) {
266
          const next = { ...repairJumps };
267
          delete next[roomId];
268
          repairJumps = next;
269
        }
270
      }
271
    }
272
  }
273
274
  async function cancelRoomRepair(roomId: string): Promise<void> {
275
    if (!$sessionUser || repairCancelling[roomId]) return;
276
    const account = $sessionUser;
277
    const epoch = repairEpoch;
278
    repairCancelling = { ...repairCancelling, [roomId]: true };
279
    try {
280
      await cancelHistoryRepair(roomId);
281
      if ($sessionUser === account && epoch === repairEpoch && !repairBusy[roomId] && !repairActive($historyRepairs[roomId])) {
282
        repairCancelling = { ...repairCancelling, [roomId]: false };
283
      }
284
    } catch (cause) {
285
      if ($sessionUser === account && epoch === repairEpoch) {
286
        repairCancelling = { ...repairCancelling, [roomId]: false };
287
        repairErrors = { ...repairErrors, [roomId]: cause instanceof Error ? cause.message : 'Could not cancel history repair' };
288
      }
289
    }
290
  }
291
292
  function motionDuration(ms: number): number {
293
    return typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : ms;
294
  }
295
296
  // account data is read from the local cache, which is empty on a fresh device until the first sync lands
297
  $: {
298
    const online = $connection === 'online';
299
    if (online && !wasOnline) {
300
      void loadQuickReactions();
301
      void loadPackPreferences();
302
      void loadUrlPreviewSettings();
303
    }
304
    wasOnline = online;
305
  }
306
  $: selectedRoom = $rooms.find((r) => r.room_id === $selectedRoomId) ?? null;
307
  $: roomPacks = enabledPacks(packsForRoom($imagePacks, $selectedRoomId, $rooms), $disabledPackImages);
308
  $: roomEmotes = customEmotes(roomPacks);
309
  $: usableQuickReactions = enabledQuickReactions($quickReactions, allPacks($imagePacks), $disabledPackImages);
310
  $: previewsAllowed = selectedRoom !== null && (!selectedRoom.encrypted || $urlPreviewSettings.encrypted_rooms);
311
  $: loadPreview = previewsAllowed && $selectedRoomId ? previewLoader($selectedRoomId) : null;
312
  $: spaceRooms = $rooms.filter((r) => r.space);
313
  $: spaceParents = parentSpaceMap(spaceRooms);
314
  $: railSpaces = spaceRooms.filter((s) => !spaceParents.has(s.room_id));
315
  let railOverride: string[] | null = null;
316
  $: if (railOverride && sortSpaces(railSpaces, null).map((s) => s.room_id).join() === railOverride.join()) railOverride = null;
317
  $: orderedRail = sortSpaces(railSpaces, railOverride);
318
  $: pinnedRail = orderedRail.filter((s) => s.favourite);
319
  $: otherRail = orderedRail.filter((s) => !s.favourite);
320
  $: railSelected = selectedSpaceId ? topSpaceOf(selectedSpaceId, spaceParents) : null;
321
  $: invites = $rooms.filter((r) => r.membership === 'Invited');
322
  $: query = search.trim().toLowerCase();
323
  $: selectedSpace = selectedSpaceId ? ($rooms.find((r) => r.room_id === selectedSpaceId) ?? null) : null;
324
  // While a space's children load (or fail), show no channels rather than the
325
  // full list — listing everything would falsely imply it belongs to the space.
326
  $: baseRooms = selectedSpaceId ? (spaceChildIds ? $rooms.filter((r) => spaceChildIds?.includes(r.room_id)) : []) : $rooms;
327
  $: visibleRooms = query
328
    ? baseRooms.filter(
329
        (r) =>
330
          r.name.toLowerCase().includes(query) || r.room_id.toLowerCase().includes(query)
331
      )
332
    : baseRooms;
333
  $: directRooms = pinnedFirst(visibleRooms.filter((r) => r.direct && !r.space && r.membership !== 'Invited'));
334
  $: groupRooms = pinnedFirst(visibleRooms.filter((r) => !r.direct && !r.space && r.membership !== 'Invited'));
335
  $: spaceList = pinnedFirst(visibleRooms.filter((r) => r.space && r.membership !== 'Invited'));
336
  $: channelRooms = baseRooms.filter((r) => !r.space && r.membership !== 'Invited');
337
  $: recoveryBanner = $encryption && ($encryption.recovery === 'Disabled' || $encryption.recovery === 'Incomplete') ? $encryption : null;
338
  $: verificationBanner = $verification && $verification.kind !== 'Done' ? $verification : null;
339
  $: items = $selectedRoomId ? ($timelines[$selectedRoomId] ?? []) : [];
340
  $: currentStaged = $selectedRoomId ? (staged[$selectedRoomId] ?? []) : [];
341
  $: members = $selectedRoomId ? ($membersByRoom[$selectedRoomId] ?? []) : [];
342
  $: memberGroups = groupMembers(members, roomLevels);
343
  $: people = peopleIn(items, members);
344
  $: mentionCandidates = mentionQuery ? rankPeople(Object.values(people), mentionQuery.query, $sessionUser ?? null) : [];
345
  $: if (mentionIndex >= mentionCandidates.length) mentionIndex = 0;
346
  $: hasStart = items.some((i) => i.kind === 'start');
347
  $: grouped = buildGroups(items);
348
  $: lastSentId = lastOwnSent(items);
349
  $: pendingItems = $selectedRoomId ? ($pendingByRoom[$selectedRoomId] ?? []) : [];
350
  $: lastRealOwn = lastSenderIsOwn(items);
351
352
  function lastSenderIsOwn(list: TimelineItem[]): boolean {
353
    for (let i = list.length - 1; i >= 0; i -= 1) {
354
      const it = list[i];
355
      if (it.kind === 'event') return it.event.sender.user_id === $sessionUser;
356
    }
357
    return false;
358
  }
359
360
  function pendingShowSender(index: number): boolean {
361
    return index === 0 ? !lastRealOwn : false;
362
  }
363
364
  function pendingToEvent(p: PendingMessage): TimelineEvent {
365
    const state: SendState = p.status === 'failed' ? { kind: 'Failed', will_retry: false } : { kind: 'Sending' };
366
    return {
367
      item_id: `pending-${p.id}`,
368
      event_id: null,
369
      transaction_id: p.id,
370
      sender: {
371
        user_id: $sessionUser ?? '',
372
        display_name: profile?.display_name ?? null,
373
        avatar: null,
374
        name_ambiguous: false
375
      },
376
      timestamp_ms: p.createdAt,
377
      own: true,
378
      send_state: state,
379
      content: {
380
        kind: 'Message',
381
        message: { kind: 'Text', body: p.body, geo_uri: null, formatted_body: p.formatted, edited: false, media: null, link_previews: [] }
382
      },
383
      reply_to: p.replyTo,
384
      thread_root: null,
385
      thread_summary: null,
386
      reactions: [],
387
      read_by: [],
388
      editable: false
389
    };
390
  }
391
392
  interface Group {
393
    key: string;
394
    item: TimelineItem;
395
    showSender: boolean;
396
  }
397
398
  function lastOwnSent(list: TimelineItem[]): string | null {
399
    for (let i = list.length - 1; i >= 0; i--) {
400
      const item = list[i];
401
      if (item.kind === 'event' && item.event.own && item.event.send_state.kind === 'Sent') return item.event.item_id;
402
    }
403
    return null;
404
  }
405
406
  function buildGroups(list: TimelineItem[]): Group[] {
407
    const out: Group[] = [];
408
    let prevSender: string | null = null;
409
    let prevTs = 0;
410
    list.forEach((item, index) => {
411
      let showSender = true;
412
      if (item.kind === 'event') {
413
        const e = item.event;
414
        showSender =
415
          prevSender !== e.sender.user_id || Math.abs(e.timestamp_ms - prevTs) > 5 * 60 * 1000;
416
        prevSender = e.sender.user_id;
417
        prevTs = e.timestamp_ms;
418
        out.push({ key: e.item_id || e.event_id || `m-${index}`, item, showSender });
419
      } else {
420
        prevSender = null;
421
        out.push({ key: `${item.kind}-${index}`, item, showSender });
422
      }
423
    });
424
    return out;
425
  }
426
427
  function roomUnread(r: RoomSummary): number {
428
    return r.unread_messages + r.unread_mentions;
429
  }
430
431
  function recordRoute(spaceId: string | null, roomId: string | null, view?: string): void {
432
    if (restoringRoute) return;
433
    const url = new URL(window.location.href);
434
    url.searchParams.delete('space');
435
    url.searchParams.delete('room');
436
    url.searchParams.delete('view');
437
    if (view) url.searchParams.set('view', view);
438
    if (spaceId) url.searchParams.set('space', spaceId);
439
    if (roomId) url.searchParams.set('room', roomId);
440
    const next = `${url.pathname}${url.search}${url.hash}`;
441
    const current = `${window.location.pathname}${window.location.search}${window.location.hash}`;
442
    if (next !== current) window.history.pushState({ spaceId, roomId }, '', next);
443
  }
444
445
  async function restoreRoute(): Promise<void> {
446
    const url = new URL(window.location.href);
447
    const roomId = url.searchParams.get('room');
448
    const spaceId = url.searchParams.get('space');
449
    restoringRoute = true;
450
    try {
451
      if (url.searchParams.get('view') === 'mentions') {
452
        selectMentions();
453
      } else if (roomId && $rooms.some((room) => room.room_id === roomId && !room.space)) {
454
        selectedSpaceId = spaceId && $rooms.some((room) => room.room_id === spaceId && room.space) ? spaceId : null;
455
        spaceChildrenError = null;
456
        spaceChildIds = selectedSpaceId ? (await getSpaceChildren(selectedSpaceId)).room_ids ?? [] : null;
457
        await selectRoom(roomId);
458
      } else if (spaceId && $rooms.some((room) => room.room_id === spaceId && room.space)) {
459
        await selectSpace(spaceId);
460
      } else {
461
        await selectHome();
462
      }
463
    } catch (e) {
464
      pushBanner(e instanceof Error ? e.message : 'Could not restore navigation');
465
    } finally {
466
      restoringRoute = false;
467
    }
468
  }
469
470
  onMount(() => {
471
    const onPopState = () => void restoreRoute();
472
    window.addEventListener('popstate', onPopState);
473
    void boot();
474
    return () => {
475
      window.removeEventListener('popstate', onPopState);
476
      disconnectEvents();
477
      stopTyping();
478
      if (readTimer !== null) window.clearTimeout(readTimer);
479
    };
480
  });
481
482
  async function boot(): Promise<void> {
483
    try {
484
      const session = await getSession();
485
      blocked.set(session.blocked ?? false);
486
      sessionUser.set(session.user_id);
487
      if (session.user_id) {
488
        softLogout.set(null);
489
        await refreshRooms();
490
        await restoreRoute();
491
        connectEvents();
492
        void loadProfile();
493
        void loadEncryption();
494
        void loadQuickReactions();
495
        void loadPackPreferences();
496
        void loadUrlPreviewSettings();
497
      } else {
498
        softLogout.set(session.soft_logout ?? null);
499
      }
500
    } catch (e) {
501
      pushBanner(e instanceof Error ? `Session check failed: ${e.message}` : 'Session check failed');
502
      sessionUser.set(null);
503
    } finally {
504
      booted = true;
505
    }
506
  }
507
508
  async function refreshRooms(): Promise<void> {
509
    roomsLoading = true;
510
    try {
511
      const res = await getRooms();
512
      rooms.set(res.rooms);
513
      pruneSpaceFilter();
514
    } catch (e) {
515
      pushBanner(e instanceof Error ? e.message : 'Could not load rooms');
516
    } finally {
517
      roomsLoading = false;
518
    }
519
  }
520
521
  async function loadProfile(): Promise<void> {
522
    try {
523
      const raw = await getProfile();
524
      profile = parseOwnProfile(raw);
525
      profileMxc = profile.avatar_url;
526
    } catch {
527
      profile = null;
528
    }
529
  }
530
531
  async function loadEncryption(): Promise<void> {
532
    try {
533
      const res = await getEncryption();
534
      const state = parseEncryptionState(res.state);
535
      if (state) encryption.set(state);
536
      const verificationState = parseVerificationState(res.verification);
537
      if (verificationState) verification.set(verificationState);
538
    } catch {
539
      // Encryption status also arrives over SSE; a failed first fetch is not fatal.
540
    }
541
  }
542
543
  function afterLogin(userId: string): void {
544
    sessionUser.set(userId);
545
    softLogout.set(null);
546
    blocked.set(false);
547
    void refreshRooms();
548
    connectEvents();
549
    void loadProfile();
550
    void loadEncryption();
551
    void loadQuickReactions();
552
    void loadPackPreferences();
553
    void loadUrlPreviewSettings();
554
  }
555
556
  async function doLogout(): Promise<void> {
557
    stopTyping();
558
    try {
559
      await logout();
560
    } catch (e) {
561
      pushBanner(e instanceof Error ? e.message : 'Logout failed');
562
      return;
563
    }
564
    disconnectEvents();
565
    resetClientState();
566
    softLogout.set(null);
567
    blocked.set(false);
568
    sessionUser.set(null);
569
    lightbox.set(null);
570
    composer = '';
571
    drafts = {};
572
    dialog = null;
573
    cloneSource = null;
574
    membersOpen = false;
575
    sidebarOpen = false;
576
    profile = null;
577
    profileMxc = null;
578
    mentionsOpen = false;
579
    selectedSpaceId = null;
580
    spaceChildIds = null;
581
    spaceChildrenError = null;
582
    openReady = {};
583
    openFailed = {};
584
    warmRooms = [];
585
    pickedMentions = {};
586
    mentionQuery = null;
587
    clearAllStaged();
588
    avatarByUser = {};
589
    resetPending();
590
  }
591
592
  /** Joined spaces that sit inside another joined space, keyed to one such parent. Either side of the link counts. */
593
  function parentSpaceMap(spaces: RoomSummary[]): Map<string, string> {
594
    const ids = new Set(spaces.map((s) => s.room_id));
595
    const parents = new Map<string, string>();
596
    for (const space of spaces) {
597
      for (const child of space.children) {
598
        if (child !== space.room_id && ids.has(child) && !parents.has(child)) parents.set(child, space.room_id);
599
      }
600
    }
601
    for (const space of spaces) {
602
      const parent = space.parent_spaces.find((id) => id !== space.room_id && ids.has(id));
603
      if (parent && !parents.has(space.room_id)) parents.set(space.room_id, parent);
604
    }
605
    for (const id of [...parents.keys()]) {
606
      const seen = new Set<string>([id]);
607
      let at = parents.get(id);
608
      while (at && !seen.has(at)) {
609
        seen.add(at);
610
        at = parents.get(at);
611
      }
612
      if (at) parents.delete(id);
613
    }
614
    return parents;
615
  }
616
617
  function topSpaceOf(id: string, parents: Map<string, string>): string {
618
    let at = id;
619
    while (parents.has(at)) at = parents.get(at)!;
620
    return at;
621
  }
622
623
  function pruneSpaceFilter(): void {
624
    if (!selectedSpaceId) return;
625
    if (!$rooms.some((r) => r.room_id === selectedSpaceId)) {
626
      selectedSpaceId = null;
627
      spaceChildIds = null;
628
      spaceChildrenError = null;
629
    }
630
  }
631
632
  async function selectHome(): Promise<void> {
633
    mentionsOpen = false;
634
    selectedSpaceId = null;
635
    spaceChildIds = null;
636
    spaceChildrenError = null;
637
    if (window.innerWidth > 640) navFolded.set(false);
638
    sidebarOpen = true;
639
    recordRoute(null, null);
640
  }
641
642
  function selectMentions(): void {
643
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
644
    stopTyping();
645
    selectedSpaceId = null;
646
    spaceChildIds = null;
647
    spaceChildrenError = null;
648
    spaceChildrenLoading = false;
649
    selectedRoomId.set(null);
650
    replyingTo = null;
651
    editing = null;
652
    mentionQuery = null;
653
    peeking = null;
654
    membersOpen = false;
655
    sidebarOpen = false;
656
    mentionsOpen = true;
657
    recordRoute(null, null, 'mentions');
658
  }
659
660
  function toggleChannelsPane(): void {
661
    if (window.innerWidth <= 640) sidebarOpen = !sidebarOpen;
662
    else navFolded.update((v) => !v);
663
  }
664
665
  async function selectSpace(spaceId: string): Promise<void> {
666
    mentionsOpen = false;
667
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
668
    stopTyping();
669
    selectedSpaceId = spaceId;
670
    spaceChildIds = null;
671
    spaceChildrenError = null;
672
    spaceChildrenLoading = true;
673
    const last = $lastSpaceRooms[spaceId];
674
    const resume = last && $rooms.some((r) => r.room_id === last && !r.space) ? last : null;
675
    if (resume) {
676
      void selectRoom(resume);
677
    } else {
678
      selectedRoomId.set(null);
679
    }
680
    try {
681
      const res = await getSpaceChildren(spaceId);
682
      if (selectedSpaceId === spaceId) {
683
        spaceChildIds = res.room_ids ?? [];
684
        const firstChannel = spaceChildIds
685
          .map((id) => $rooms.find((room) => room.room_id === id))
686
          .find((room) => room && !room.space);
687
        if ((!resume || !spaceChildIds.includes(resume)) && firstChannel) {
688
          await selectRoom(firstChannel.room_id);
689
        }
690
      }
691
    } catch (e) {
692
      if (selectedSpaceId === spaceId) {
693
        spaceChildrenError = e instanceof Error ? e.message : 'Could not load rooms in this space';
694
        spaceChildIds = [];
695
      }
696
    } finally {
697
      if (selectedSpaceId === spaceId) spaceChildrenLoading = false;
698
    }
699
  }
700
701
  async function selectRoom(roomId: string, peek = false): Promise<void> {
702
    mentionsOpen = false;
703
    peeking = peek ? roomId : null;
704
    if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer;
705
    if (roomId === $selectedRoomId && openReady[roomId]) {
706
      sidebarOpen = false;
707
      return;
708
    }
709
    stopTyping();
710
    const spaceId = selectedSpaceId;
711
    if (spaceId) lastSpaceRooms.update((all) => ({ ...all, [spaceId]: roomId }));
712
    selectedRoomId.set(roomId);
713
    recordRoute(selectedSpaceId, roomId);
714
    composer = drafts[roomId] ?? '';
715
    replyingTo = null;
716
    editing = null;
717
    mentionQuery = null;
718
    stickToBottom = true;
719
    lastReadKey = '';
720
    sidebarOpen = false;
721
    touchWarmRoom(roomId);
722
    if (openReady[roomId]) {
723
      if (membersOpen) void loadMembers(roomId);
724
      await tick();
725
      scrollToBottom();
726
      queueReadReceipt();
727
      composerEl?.focus();
728
      return;
729
    }
730
    if (openFailed[roomId]) {
731
      const nextFailed = { ...openFailed };
732
      delete nextFailed[roomId];
733
      openFailed = nextFailed;
734
    }
735
    try {
736
      await openRoom(roomId);
737
      if (warmRooms.includes(roomId)) openReady = { ...openReady, [roomId]: true };
738
    } catch (e) {
739
      const message = e instanceof Error ? e.message : `Could not open room ${roomId}`;
740
      openFailed = { ...openFailed, [roomId]: message };
741
      pushBanner(message);
742
    }
743
    if (membersOpen) void loadMembers(roomId);
744
    await tick();
745
    scrollToBottom();
746
    queueReadReceipt();
747
    composerEl?.focus();
748
  }
749
750
  function touchWarmRoom(roomId: string): void {
751
    warmRooms = [...warmRooms.filter((id) => id !== roomId), roomId];
752
    while (warmRooms.length > WARM_ROOM_LIMIT) {
753
      const evicted = warmRooms[0];
754
      warmRooms = warmRooms.slice(1);
755
      forgetOpenRoom(evicted);
756
      closeRoom(evicted).catch(() => undefined);
757
    }
758
  }
759
760
  function forgetOpenRoom(roomId: string): void {
761
    warmRooms = warmRooms.filter((id) => id !== roomId);
762
    const nextReady = { ...openReady };
763
    delete nextReady[roomId];
764
    openReady = nextReady;
765
  }
766
767
  function scrollToBottom(): void {
768
    if (timelineViewport?.element === timelineEl) timelineViewport.scrollToBottom();
769
    else if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight;
770
  }
771
772
  function noteUserScroll(): void {
773
    timelineViewport?.releaseScroll();
774
    if ($selectedRoomId && repairJumps[$selectedRoomId]) {
775
      const next = { ...repairJumps };
776
      delete next[$selectedRoomId];
777
      repairJumps = next;
778
    }
779
  }
780
781
  function syncComposer(node: HTMLTextAreaElement) {
782
    const sync = () => {
783
      if (!marksEl) return;
784
      marksEl.style.width = `${node.clientWidth}px`;
785
      marksEl.scrollTop = node.scrollTop;
786
      marksEl.scrollLeft = node.scrollLeft;
787
    };
788
    const observer = new ResizeObserver(sync);
789
    observer.observe(node);
790
    node.addEventListener('scroll', sync);
791
    return { destroy: () => {
792
      observer.disconnect();
793
      node.removeEventListener('scroll', sync);
794
    } };
795
  }
796
797
  function onTimelineKey(e: KeyboardEvent): void {
798
    if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) noteUserScroll();
799
  }
800
801
  function onTimelineScroll(): void {
802
    if (!timelineEl) return;
803
    if (timelineViewport?.consumeScroll()) return;
804
    const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight;
805
    stickToBottom = gap < 2;
806
    timelineViewport?.capture();
807
    if (timelineEl.scrollTop < 80 && !hasStart && !paginateBusy) void paginate();
808
  }
809
810
  function pinTimeline(node: HTMLElement) {
811
    const viewport = new TimelineViewport(node.parentElement!, $selectedRoomId);
812
    timelineViewport = viewport;
813
    const observer = new ResizeObserver(() => {
814
      if (timelineViewport !== viewport || viewport.roomId !== $selectedRoomId) return;
815
      if (stickToBottom) viewport.scrollToBottom(true);
816
      else viewport.restore();
817
    });
818
    observer.observe(node);
819
    if (node.parentElement) observer.observe(node.parentElement);
820
    return { destroy: () => {
821
      observer.disconnect();
822
      viewport.releaseScroll();
823
      if (timelineViewport === viewport) timelineViewport = null;
824
    } };
825
  }
826
827
  $: void trackTimeline($selectedRoomId, items);
828
  async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> {
829
    if (!roomId || list.length === 0) return;
830
    if (roomId !== $selectedRoomId) return;
831
    await tick();
832
    if (roomId !== $selectedRoomId || timelineViewport?.roomId !== roomId) return;
833
    if (stickToBottom) timelineViewport.scrollToBottom(true);
834
    else timelineViewport.restore();
835
    queueReadReceipt();
836
  }
837
838
  function queueReadReceipt(): void {
839
    if (readTimer !== null) window.clearTimeout(readTimer);
840
    readTimer = window.setTimeout(() => {
841
      readTimer = null;
842
      void sendReadReceipt();
843
    }, 800);
844
  }
845
846
  async function sendReadReceipt(): Promise<void> {
847
    const roomId = $selectedRoomId;
848
    if (!roomId || roomId === peeking) return;
849
    const list = $timelines[roomId] ?? [];
850
    for (let i = list.length - 1; i >= 0; i -= 1) {
851
      const entry = list[i];
852
      if (entry.kind === 'event' && entry.event.event_id) {
853
        const key = `${roomId}:${entry.event.event_id}`;
854
        if (key === lastReadKey) return;
855
        lastReadKey = key;
856
        try {
857
          await markRead(roomId, entry.event.event_id);
858
        } catch {
859
          return;
860
        }
861
        return;
862
      }
863
    }
864
  }
865
866
  function send(): void {
867
    if (editing) {
868
      submitEdit();
869
      return;
870
    }
871
    const roomId = $selectedRoomId;
872
    const body = composer.trim();
873
    const attachments = roomId ? (staged[roomId] ?? []) : [];
874
    if (!roomId || (!body && attachments.length === 0)) return;
875
    if (!openReady[roomId]) {
876
      pushBanner('Still opening this room — sending is disabled until the room is ready.');
877
      return;
878
    }
879
    if (attachments.length > 0 && uploadBusy) return;
880
    const command = parseCommand(body);
881
    if (command && !isKnownCommand(command.name)) {
882
      pushBanner(`Unknown command /${command.name}`);
883
      return;
884
    }
885
    if (command && attachments.length > 0) {
886
      if (command.name !== 'roomavatar' && command.name !== 'globalavatar') {
887
        pushBanner(`/${command.name} doesn't take attachments`);
888
        return;
889
      }
890
      if (command.args || attachments.length !== 1 || !attachments[0].file.type.startsWith('image/')) {
891
        pushBanner(`/${command.name} takes a single attached image`);
892
        return;
893
      }
894
    }
895
    composer = '';
896
    if (roomId in drafts) delete drafts[roomId];
897
    stickToBottom = true;
898
    const reply = replyingTo;
899
    replyingTo = null;
900
    const text = unescapeCommand(body);
901
    const mentions = resolveMentions(text, pickedMentions[roomId] ?? []);
902
    pickedMentions = { ...pickedMentions, [roomId]: [] };
903
    mentionQuery = null;
904
    if (command) {
905
      const image = attachments[0] ?? null;
906
      if (image) {
907
        const { [roomId]: _used, ...rest } = staged;
908
        staged = rest;
909
      }
910
      void execute(roomId, command, reply, mentions, image?.file ?? null).finally(() => {
911
        if (image?.previewUrl) URL.revokeObjectURL(image.previewUrl);
912
      });
913
    } else if (attachments.length === 0) {
914
      queueSend(roomId, text, reply, mentions, resolveEmotes(text, roomEmotes));
915
    } else {
916
      const { [roomId]: _sent, ...rest } = staged;
917
      staged = rest;
918
      void sendAttachments(roomId, text, reply, mentions, attachments);
919
    }
920
    if (peeking === roomId) stopPeeking();
921
    composerEl?.focus();
922
  }
923
924
  function lastOwnEventId(): string | null {
925
    for (let i = items.length - 1; i >= 0; i -= 1) {
926
      const entry = items[i];
927
      if (entry.kind === 'event' && entry.event.own && entry.event.event_id && entry.event.content.kind !== 'Redacted') {
928
        return entry.event.event_id;
929
      }
930
    }
931
    return null;
932
  }
933
934
  async function execute(
935
    roomId: string,
936
    command: ParsedCommand,
937
    reply: ReplyReference | null,
938
    mentions: Mention[],
939
    image: File | null
940
  ): Promise<void> {
941
    const { name, args } = command;
942
    const target = () => {
943
      const found = splitTarget(args, Object.values(people));
944
      if ('error' in found) throw new Error(found.error);
945
      return found;
946
    };
947
    const required = (what: string) => {
948
      if (!args) throw new Error(`/${name} needs ${what}`);
949
      return args;
950
    };
951
    try {
952
      switch (name) {
953
        case 'me':
954
        case 'notice': {
955
          const said = required('something to say');
956
          await sendMessage(roomId, said, null, mentions, name === 'me' ? 'emote' : 'notice', resolveEmotes(said, roomEmotes));
957
          break;
958
        }
959
        case 'sticker': {
960
          const { pack, sticker } = findSticker(enabledPacks(packsForRoom($imagePacks, roomId, $rooms), $disabledPackImages), required('a sticker name'));
961
          await runCommand({ op: 'send_sticker', room_id: roomId, pack_id: pack.id, shortcode: sticker.shortcode });
962
          break;
963
        }
964
        case 'msg': {
965
          const { user_id, rest } = target();
966
          const res = (await runCommand({ op: 'direct', user_id })) as { room_id: string };
967
          await refreshRooms();
968
          await selectRoom(res.room_id);
969
          if (rest) queueSend(res.room_id, rest);
970
          break;
971
        }
972
        case 'join':
973
          await join(required('a room id or alias'));
974
          break;
975
        case 'leave':
976
          await leave();
977
          break;
978
        case 'invite':
979
          await runCommand({ op: 'invite', room_id: roomId, user_id: target().user_id });
980
          break;
981
        case 'disinvite':
982
        case 'kick':
983
        case 'ban':
984
        case 'unban': {
985
          const { user_id, rest } = target();
986
          const op = name === 'disinvite' ? 'kick' : name;
987
          await runCommand({ op, room_id: roomId, user_id, reason: rest || null });
988
          break;
989
        }
990
        case 'powerlevel': {
991
          const { user_id, rest } = target();
992
          const level = Number(rest);
993
          if (!rest || !Number.isInteger(level)) throw new Error('/powerlevel needs a whole number after the name');
994
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id, level });
995
          break;
996
        }
997
        case 'mute':
998
        case 'unmute':
999
          await runCommand({ op: 'mute', room_id: roomId, user_id: target().user_id, muted: name === 'mute' });
1000
          break;
1001
        case 'ignore':
1002
        case 'unignore':
1003
          await runCommand({ op: name, user_id: target().user_id });
1004
          break;
1005
        case 'roomnick':
1006
          await runCommand({ op: 'set_room_display_name', room_id: roomId, name: args || null });
1007
          break;
1008
        case 'roomavatar':
1009
          if (image) {
1010
            await uploadRoomAvatar(roomId, image);
1011
          } else if (args && !args.startsWith('mxc://')) {
1012
            throw new Error('/roomavatar takes an mxc:// link, an attached image, or nothing to drop the override');
1013
          } else {
1014
            await runCommand({ op: 'set_room_avatar', room_id: roomId, mxc: args || null });
1015
          }
1016
          break;
1017
        case 'delete': {
1018
          const eventId = reply?.event_id ?? lastOwnEventId();
1019
          if (!eventId) throw new Error('Nothing of yours to delete here');
1020
          await runCommand({ op: 'redact', room_id: roomId, event_id: eventId, reason: args || null });
1021
          break;
1022
        }
1023
        case 'globalnick':
1024
          await runCommand({ op: 'set_display_name', name: required('a name') });
1025
          await loadProfile();
1026
          break;
1027
        case 'globalavatar':
1028
          if (image) {
1029
            await uploadAvatar(image);
1030
            await loadProfile();
1031
          } else if (!args) {
1032
            avatarInput?.click();
1033
          } else if (args.startsWith('mxc://')) {
1034
            await runCommand({ op: 'set_avatar', mxc: args });
1035
            await loadProfile();
1036
          } else {
1037
            throw new Error('/globalavatar takes an mxc:// link, or nothing to pick a file');
1038
          }
1039
          break;
1040
      }
1041
    } catch (e) {
1042
      pushBanner(e instanceof Error ? e.message : `/${name} failed`);
1043
    }
1044
  }
1045
1046
  async function onAvatarChosen(): Promise<void> {
1047
    const file = avatarInput?.files?.[0];
1048
    if (avatarInput) avatarInput.value = '';
1049
    if (!file) return;
1050
    try {
1051
      await uploadAvatar(file);
1052
      await loadProfile();
1053
    } catch (e) {
1054
      pushBanner(e instanceof Error ? e.message : 'Avatar upload failed');
1055
    }
1056
  }
1057
1058
  async function sendAttachments(
1059
    roomId: string,
1060
    body: string,
1061
    reply: ReplyReference | null,
1062
    mentions: Mention[],
1063
    attachments: StagedAttachment[]
1064
  ): Promise<void> {
1065
    let first = true;
1066
    uploadBusy = true;
1067
    try {
1068
      for (const attachment of attachments) {
1069
        uploadName = attachment.file.name || 'attachment';
1070
        try {
1071
          if (first) await uploadAttachment(roomId, attachment.file, body || null, reply?.event_id ?? null, mentions, resolveEmotes(body, roomEmotes));
1072
          else await uploadAttachment(roomId, attachment.file);
1073
          first = false;
1074
        } catch (e) {
1075
          pushBanner(e instanceof Error ? e.message : 'Upload failed');
1076
        }
1077
        if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
1078
      }
1079
    } finally {
1080
      uploadBusy = false;
1081
      uploadName = null;
1082
    }
1083
  }
1084
1085
  function stageFiles(files: File[]): void {
1086
    const roomId = $selectedRoomId;
1087
    if (!roomId || !openReady[roomId]) return;
1088
    const accepted: StagedAttachment[] = [];
1089
    for (const file of files) {
1090
      if (file.size === 0 || file.size > 20 * 1024 * 1024) {
1091
        pushBanner(`${file.name || 'File'} must be between 1 byte and 20 MiB.`);
1092
        continue;
1093
      }
1094
      const previewUrl = file.type.startsWith('image/') ? URL.createObjectURL(file) : null;
1095
      accepted.push({ id: nextStagedId++, file, previewUrl });
1096
    }
1097
    if (accepted.length === 0) return;
1098
    staged = { ...staged, [roomId]: [...(staged[roomId] ?? []), ...accepted] };
1099
    composerEl?.focus();
1100
  }
1101
1102
  function unstage(roomId: string, id: number): void {
1103
    const list = staged[roomId] ?? [];
1104
    const removed = list.find((a) => a.id === id);
1105
    if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
1106
    staged = { ...staged, [roomId]: list.filter((a) => a.id !== id) };
1107
  }
1108
1109
  function clearAllStaged(): void {
1110
    for (const list of Object.values(staged)) {
1111
      for (const attachment of list) if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
1112
    }
1113
    staged = {};
1114
  }
1115
1116
  function startEdit(eventId: string, body: string): void {
1117
    const roomId = $selectedRoomId;
1118
    if (!roomId) return;
1119
    const stash = editing ? editing.stash : composer;
1120
    editing = { roomId, eventId, original: body, stash };
1121
    const entry = items.find((i) => i.kind === 'event' && i.event.event_id === eventId);
1122
    if (entry?.kind === 'event' && entry.event.content.kind === 'Message') {
1123
      const existing = mentionsFromHtml(entry.event.content.message.formatted_body);
1124
      pickedMentions = { ...pickedMentions, [roomId]: [...(pickedMentions[roomId] ?? []), ...existing] };
1125
    }
1126
    composer = body;
1127
    replyingTo = null;
1128
    composerEl?.focus();
1129
  }
1130
1131
  function cancelEdit(): void {
1132
    if (!editing) return;
1133
    composer = editing.stash;
1134
    editing = null;
1135
    composerEl?.focus();
1136
  }
1137
1138
  function submitEdit(): void {
1139
    if (!editing) return;
1140
    const { roomId, eventId, original } = editing;
1141
    const body = composer.trim();
1142
    cancelEdit();
1143
    if (!body || body === original.trim()) return;
1144
    editMessage(roomId, eventId, body, resolveMentions(body, pickedMentions[roomId] ?? []), resolveEmotes(body, roomEmotes)).catch((e) => pushBanner(e instanceof Error ? e.message : 'Edit failed'));
1145
  }
1146
1147
  function editLastOwn(): boolean {
1148
    for (let i = items.length - 1; i >= 0; i -= 1) {
1149
      const entry = items[i];
1150
      if (entry.kind !== 'event' || !entry.event.own) continue;
1151
      const ev = entry.event;
1152
      if (!ev.editable || !ev.event_id || ev.content.kind !== 'Message' || ev.content.message.kind !== 'Text') return false;
1153
      startEdit(ev.event_id, ev.content.message.body);
1154
      return true;
1155
    }
1156
    return false;
1157
  }
1158
1159
  function startReply(target: ReplyReference): void {
1160
    if (editing) cancelEdit();
1161
    replyingTo = target;
1162
    composerEl?.focus();
1163
  }
1164
1165
  let pinnedOpenFor: string | null = null;
1166
  let pinnedCloseVersion = 0;
1167
  let pinsExpanded = false;
1168
  let pinPreview: TimelineEvent | null = null;
1169
  let pinJumpBusy = false;
1170
  $: syncPinned(selectedRoom?.room_id ?? null, (selectedRoom?.pinned_events.length ?? 0) > 0, $selectedRoomId ? $pinnedTimelineVersions[$selectedRoomId] ?? 0 : 0, currentRepairActive);
1171
  function syncPinned(roomId: string | null, hasPins: boolean, version: number, repairing: boolean): void {
1172
    const want = hasPins ? roomId : null;
1173
    if (want === pinnedOpenFor && version === pinnedCloseVersion) return;
1174
    if (want && repairing) return;
1175
    if (pinnedOpenFor) runCommand({ op: 'close_pinned', room_id: pinnedOpenFor }).catch(() => undefined);
1176
    pinnedOpenFor = want;
1177
    pinnedCloseVersion = version;
1178
    pinsExpanded = false;
1179
    if (want) runCommand({ op: 'open_pinned', room_id: want }).catch(() => undefined);
1180
  }
1181
1182
  $: pins = pinnedList(selectedRoom, $pinnedTimelines);
1183
  function pinnedList(room: RoomSummary | null, all: Record<string, TimelineItem[]>): TimelineEvent[] {
1184
    if (!room || !room.pinned_events.length) return [];
1185
    const order = new Map(room.pinned_events.map((id, i) => [id, i]));
1186
    return (all[room.room_id] ?? [])
1187
      .flatMap((item) => (item.kind === 'event' && item.event.event_id && order.has(item.event.event_id) ? [item.event] : []))
1188
      .sort((a, b) => (order.get(b.event_id!) ?? 0) - (order.get(a.event_id!) ?? 0));
1189
  }
1190
1191
  function setPinned(eventId: string, pinned: boolean): void {
1192
    const roomId = $selectedRoomId;
1193
    if (!roomId) return;
1194
    runCommand({ op: 'set_pinned', room_id: roomId, event_id: eventId, pinned }).catch((e) =>
1195
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin')
1196
    );
1197
  }
1198
1199
  async function jumpToPin(eventId: string): Promise<void> {
1200
    const roomId = $selectedRoomId;
1201
    if (!roomId || !eventId || pinJumpBusy) return;
1202
    pinsExpanded = false;
1203
    pinPreview = pins.find((event) => event.event_id === eventId) ?? null;
1204
    pinJumpBusy = true;
1205
    try {
1206
      for (let attempt = 0; attempt < 24; attempt += 1) {
1207
        if (($timelines[roomId] ?? []).some((item) => item.kind === 'event' && item.event.event_id === eventId)) {
1208
          pinPreview = null;
1209
          await tick();
1210
          jumpTo(eventId);
1211
          return;
1212
        }
1213
        await paginateRoom(roomId);
1214
        await new Promise((resolve) => window.setTimeout(resolve, 180));
1215
      }
1216
      pushBanner('Could not load that pinned message');
1217
    } catch (e) {
1218
      pushBanner(e instanceof Error ? e.message : 'Could not load that pinned message');
1219
    } finally {
1220
      pinJumpBusy = false;
1221
    }
1222
  }
1223
1224
  function jumpTo(eventId: string): void {
1225
    const el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`);
1226
    if (!el) {
1227
      pushBanner('The original message is not loaded. Scroll up to load older messages.');
1228
      return;
1229
    }
1230
    stickToBottom = false;
1231
    timelineViewport?.releaseScroll();
1232
    el.scrollIntoView({ block: 'center', behavior: 'smooth' });
1233
    el.classList.remove('flash');
1234
    void el.offsetWidth;
1235
    el.classList.add('flash');
1236
  }
1237
1238
  let typedText = '';
1239
  let typedRoom: string | null = null;
1240
  $: trackTypingInput(composer, $selectedRoomId, openReady);
1241
  function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void {
1242
    const edited = roomId === typedRoom && text !== typedText;
1243
    typedText = text;
1244
    typedRoom = roomId;
1245
    if (!roomId || !ready[roomId] || !text.trim()) {
1246
      stopTyping();
1247
    } else if (edited && roomId !== peeking) {
1248
      notifyTyping(roomId);
1249
    }
1250
  }
1251
1252
  $: void trackPending($selectedRoomId, pendingItems);
1253
  async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> {
1254
    if (!roomId) return;
1255
    if (roomId !== $selectedRoomId) return;
1256
    await tick();
1257
    if (roomId !== $selectedRoomId || timelineViewport?.roomId !== roomId) return;
1258
    if (stickToBottom) timelineViewport.scrollToBottom(true);
1259
    else timelineViewport.restore();
1260
  }
1261
1262
  let commandQuery: string | null = null;
1263
  let commandIndex = 0;
1264
  $: commandCandidates = commandQuery === null ? [] : matchCommands(commandQuery);
1265
  $: if (commandIndex >= commandCandidates.length) commandIndex = 0;
1266
1267
  async function pickCommand(name: CommandName): Promise<void> {
1268
    if (!composerEl) return;
1269
    const caret = composerEl.selectionStart ?? composer.length;
1270
    const rest = composer.slice(caret).replace(/^\S*/, '');
1271
    composer = `/${name}${rest.startsWith(' ') ? rest : ` ${rest}`}`;
1272
    commandQuery = null;
1273
    await tick();
1274
    const at = name.length + 2;
1275
    composerEl.focus();
1276
    composerEl.setSelectionRange(at, at);
1277
  }
1278
1279
  let emoteQuery: EmoteQuery | null = null;
1280
  let emoteIndex = 0;
1281
  let emojiList: EmojiEntry[] = [];
1282
  $: emoteCandidates = emoteQuery ? rankEmotes(emoteQuery.query, roomEmotes, emojiList) : [];
1283
  $: if (emoteIndex >= emoteCandidates.length) emoteIndex = 0;
1284
1285
  function ensureEmoji(): void {
1286
    if (emojiList.length) return;
1287
    loadEmoji()
1288
      .then((groups) => (emojiList = groups.flatMap((g) => g.emojis)))
1289
      .catch(() => undefined);
1290
  }
1291
1292
  async function onComposerInput(): Promise<void> {
1293
    if (composerEl && composer.includes(':')) {
1294
      ensureEmoji();
1295
      const done = completeShortcode(composerEl.value, composerEl.selectionStart ?? composerEl.value.length, emojiList);
1296
      if (done) {
1297
        composer = done.text;
1298
        await tick();
1299
        composerEl.setSelectionRange(done.caret, done.caret);
1300
      }
1301
    }
1302
    updateMentionQuery();
1303
  }
1304
1305
  async function pickEmote(candidate: EmoteCandidate): Promise<void> {
1306
    if (!emoteQuery || !composerEl) return;
1307
    const caret = composerEl.selectionStart ?? composer.length;
1308
    const inserted = candidate.kind === 'emoji' ? candidate.emoji : `:${candidate.shortcode}: `;
1309
    composer = composer.slice(0, emoteQuery.start) + inserted + composer.slice(caret);
1310
    const at = emoteQuery.start + inserted.length;
1311
    emoteQuery = null;
1312
    await tick();
1313
    composerEl.focus();
1314
    composerEl.setSelectionRange(at, at);
1315
  }
1316
1317
  function updateMentionQuery(): void {
1318
    const roomId = $selectedRoomId;
1319
    const nextEmote = composerEl ? emoteQueryAt(composerEl.value, composerEl.selectionStart ?? composerEl.value.length) : null;
1320
    if (nextEmote?.start !== emoteQuery?.start) emoteIndex = 0;
1321
    emoteQuery = nextEmote;
1322
    const nextCommand = composerEl ? commandQueryAt(composerEl.value, composerEl.selectionStart ?? composerEl.value.length) : null;
1323
    if (nextCommand !== commandQuery) commandIndex = 0;
1324
    commandQuery = nextCommand;
1325
    const next = composerEl && roomId ? mentionQueryAt(composerEl.value, composerEl.selectionStart ?? composerEl.value.length) : null;
1326
    if (next && !mentionQuery && roomId && !$membersByRoom[roomId]) void loadMembers(roomId);
1327
    if (next?.start !== mentionQuery?.start) mentionIndex = 0;
1328
    mentionQuery = next;
1329
  }
1330
1331
  async function pickMention(person: Person): Promise<void> {
1332
    const roomId = $selectedRoomId;
1333
    if (!mentionQuery || !roomId || !composerEl) return;
1334
    const caret = composerEl.selectionStart ?? composer.length;
1335
    const inserted = `${person.name} `;
1336
    composer = composer.slice(0, mentionQuery.start) + inserted + composer.slice(caret);
1337
    const at = mentionQuery.start + inserted.length;
1338
    pickedMentions = {
1339
      ...pickedMentions,
1340
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
1341
    };
1342
    mentionQuery = null;
1343
    await tick();
1344
    composerEl.focus();
1345
    composerEl.setSelectionRange(at, at);
1346
  }
1347
1348
  function onComposerKey(ev: KeyboardEvent): void {
1349
    if (ev.isComposing || composerComposing) return;
1350
    if (emoteQuery && emoteCandidates.length > 0) {
1351
      if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
1352
        ev.preventDefault();
1353
        const step = ev.key === 'ArrowDown' ? 1 : -1;
1354
        emoteIndex = (emoteIndex + step + emoteCandidates.length) % emoteCandidates.length;
1355
        return;
1356
      }
1357
      if ((ev.key === 'Enter' && !ev.shiftKey) || ev.key === 'Tab') {
1358
        ev.preventDefault();
1359
        void pickEmote(emoteCandidates[emoteIndex]);
1360
        return;
1361
      }
1362
      if (ev.key === 'Escape') {
1363
        ev.stopPropagation();
1364
        emoteQuery = null;
1365
        return;
1366
      }
1367
    }
1368
    if (commandQuery !== null && commandCandidates.length > 0) {
1369
      if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
1370
        ev.preventDefault();
1371
        const step = ev.key === 'ArrowDown' ? 1 : -1;
1372
        commandIndex = (commandIndex + step + commandCandidates.length) % commandCandidates.length;
1373
        return;
1374
      }
1375
      const exact = commandCandidates.length === 1 && commandCandidates[0] === commandQuery;
1376
      if (ev.key === 'Tab' || (ev.key === 'Enter' && !ev.shiftKey && !exact)) {
1377
        ev.preventDefault();
1378
        void pickCommand(commandCandidates[commandIndex]);
1379
        return;
1380
      }
1381
      if (ev.key === 'Escape') {
1382
        ev.stopPropagation();
1383
        commandQuery = null;
1384
        return;
1385
      }
1386
    }
1387
    if (mentionQuery && mentionCandidates.length > 0) {
1388
      if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
1389
        ev.preventDefault();
1390
        const step = ev.key === 'ArrowDown' ? 1 : -1;
1391
        mentionIndex = (mentionIndex + step + mentionCandidates.length) % mentionCandidates.length;
1392
        return;
1393
      }
1394
      if ((ev.key === 'Enter' && !ev.shiftKey) || ev.key === 'Tab') {
1395
        ev.preventDefault();
1396
        void pickMention(mentionCandidates[mentionIndex]);
1397
        return;
1398
      }
1399
      if (ev.key === 'Escape') {
1400
        ev.stopPropagation();
1401
        mentionQuery = null;
1402
        return;
1403
      }
1404
    }
1405
    if (ev.key === 'Enter' && !ev.shiftKey && !insideOpenFence(composer, composerEl?.selectionStart ?? composer.length)) {
1406
      ev.preventDefault();
1407
      send();
1408
    } else if (ev.key === 'Escape' && editing) {
1409
      ev.stopPropagation();
1410
      cancelEdit();
1411
    } else if (ev.key === 'Escape' && replyingTo) {
1412
      ev.stopPropagation();
1413
      replyingTo = null;
1414
    } else if (ev.key === 'ArrowUp' && !composer && !editing && editLastOwn()) {
1415
      ev.preventDefault();
1416
    }
1417
  }
1418
1419
  function pickFiles(): void {
1420
    const roomId = $selectedRoomId;
1421
    if (!roomId || !openReady[roomId]) return;
1422
    fileInput?.click();
1423
  }
1424
1425
  function onFileChosen(): void {
1426
    stageFiles(Array.from(fileInput?.files ?? []));
1427
    if (fileInput) fileInput.value = '';
1428
  }
1429
1430
  function onComposerPaste(ev: ClipboardEvent): void {
1431
    const data = ev.clipboardData;
1432
    // Office apps put a rendered image next to the copied text, so only take the image when there is no plain text.
1433
    if (!data || data.types.includes('text/plain')) return;
1434
    const images = Array.from(data.files).filter((f) => f.type.startsWith('image/'));
1435
    if (images.length === 0) return;
1436
    ev.preventDefault();
1437
    stageFiles(images);
1438
  }
1439
1440
  async function react(eventId: string, key: string, shortcode?: string): Promise<void> {
1441
    const roomId = $selectedRoomId;
1442
    if (!roomId || !eventId || reacting) return;
1443
    reacting = true;
1444
    try {
1445
      await reactToMessage(roomId, eventId, key, reactionShortcode(key, shortcode, allPacks($imagePacks)));
1446
    } catch (e) {
1447
      pushBanner(e instanceof Error ? e.message : 'Reaction failed');
1448
    } finally {
1449
      reacting = false;
1450
    }
1451
  }
1452
1453
  function previewLoader(roomId: string): (url: string) => void {
1454
    return (url) => requestLinkPreview(roomId, url);
1455
  }
1456
1457
  async function changeEncryptedPreviews(enabled: boolean): Promise<void> {
1458
    try {
1459
      await saveUrlPreviewSettings({ encrypted_rooms: enabled });
1460
    } catch (e) {
1461
      pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting');
1462
    }
1463
  }
1464
1465
  async function changeQuickReactions(list: QuickReaction[]): Promise<void> {
1466
    try {
1467
      await saveQuickReactions(list);
1468
    } catch (e) {
1469
      pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions');
1470
    }
1471
  }
1472
1473
  async function paginate(): Promise<void> {
1474
    const roomId = $selectedRoomId;
1475
    if (!roomId || paginateBusy || currentRepairActive) return;
1476
    paginateBusy = true;
1477
    try {
1478
      await paginateRoom(roomId);
1479
    } catch (e) {
1480
      pushBanner(e instanceof Error ? e.message : 'Loading older messages failed');
1481
    } finally {
1482
      paginateBusy = false;
1483
    }
1484
  }
1485
1486
  async function loadMembers(roomId: string): Promise<void> {
1487
    if (membersFor === roomId && $membersLoading) return;
1488
    membersFor = roomId;
1489
    membersLoading.set(true);
1490
    try {
1491
      const res = await getMembers(roomId);
1492
      membersByRoom.update((all) => ({ ...all, [roomId]: res.members }));
1493
      avatarByUser = { ...avatarByUser, ...avatarMap(res.members) };
1494
    } catch (e) {
1495
      pushBanner(e instanceof Error ? e.message : 'Could not load members');
1496
    } finally {
1497
      if (membersFor === roomId) membersLoading.set(false);
1498
    }
1499
  }
1500
1501
  function avatarMap(list: MemberSummary[]): Record<string, string | null> {
1502
    const next: Record<string, string | null> = {};
1503
    for (const member of list) next[member.user_id] = member.avatar;
1504
    return next;
1505
  }
1506
1507
  function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> {
1508
    const out: Record<string, Person> = {};
1509
    for (const item of list) {
1510
      if (item.kind !== 'event') continue;
1511
      const s = item.event.sender;
1512
      out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar };
1513
    }
1514
    for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar };
1515
    return out;
1516
  }
1517
1518
  function senderAvatarFor(userId: string): string | null {
1519
    return avatarByUser[userId] ?? null;
1520
  }
1521
1522
  function toggleMembers(): void {
1523
    membersOpen = !membersOpen;
1524
    if (membersOpen && $selectedRoomId) {
1525
      void loadMembers($selectedRoomId);
1526
      void loadLevels($selectedRoomId);
1527
    }
1528
  }
1529
1530
  async function join(target: string): Promise<void> {
1531
    const room = target.trim();
1532
    if (!room || joinBusy) return;
1533
    joinBusy = true;
1534
    try {
1535
      const res = await joinRoom(room);
1536
      joinTarget = '';
1537
      dialog = null;
1538
      await refreshRooms();
1539
      await selectRoom(res.room_id);
1540
    } catch (e) {
1541
      pushBanner(e instanceof Error ? e.message : 'Join failed');
1542
    } finally {
1543
      joinBusy = false;
1544
    }
1545
  }
1546
1547
  async function create(): Promise<void> {
1548
    const name = createName.trim();
1549
    if (!name || createBusy) return;
1550
    createBusy = true;
1551
    try {
1552
      const res = await createRoom(name, createTopic.trim() || undefined);
1553
      createName = '';
1554
      createTopic = '';
1555
      dialog = null;
1556
      await refreshRooms();
1557
      await selectRoom(res.room_id);
1558
    } catch (e) {
1559
      pushBanner(e instanceof Error ? e.message : 'Create room failed');
1560
    } finally {
1561
      createBusy = false;
1562
    }
1563
  }
1564
1565
  async function leave(roomId: string | null = $selectedRoomId): Promise<void> {
1566
    if (!roomId || leaveBusy) return;
1567
    leaveBusy = true;
1568
    stopTyping();
1569
    try {
1570
      await leaveRoom(roomId);
1571
      if ($selectedRoomId === roomId) selectedRoomId.set(null);
1572
      if (warmRooms.includes(roomId)) {
1573
        forgetOpenRoom(roomId);
1574
        closeRoom(roomId).catch(() => undefined);
1575
      }
1576
      await refreshRooms();
1577
    } catch (e) {
1578
      pushBanner(e instanceof Error ? e.message : 'Leave failed');
1579
    } finally {
1580
      leaveBusy = false;
1581
    }
1582
  }
1583
1584
  function connectionClass(state: string): string {
1585
    if (state === 'online') return 'dot-online';
1586
    if (state === 'connecting' || state === 'reconnecting') return 'dot-busy';
1587
    return 'dot-off';
1588
  }
1589
1590
  let dragSpaceId: string | null = null;
1591
  let dropTarget: { id: string; after: boolean } | null = null;
1592
  let menu: { items: MenuItem[]; x: number; y: number; above?: boolean } | null = null;
1593
  let userCard: { userId: string; x: number; y: number; confirm: 'kick' | 'ban' | null } | null = null;
1594
  let levelsByRoom: Record<string, PowerLevels | null> = {};
1595
  let peeking: string | null = null;
1596
1597
  $: roomLevels = $selectedRoomId ? (levelsByRoom[$selectedRoomId] ?? null) : null;
1598
1599
  function personFor(userId: string): Person {
1600
    return people[userId] ?? { user_id: userId, name: userId, avatar: avatarByUser[userId] ?? null };
1601
  }
1602
1603
  function memberFor(userId: string): MemberSummary | null {
1604
    return members.find((m) => m.user_id === userId) ?? null;
1605
  }
1606
1607
  async function loadLevels(roomId: string): Promise<void> {
1608
    try {
1609
      const levels = parsePowerLevels(await runCommand({ op: 'power_levels', room_id: roomId }));
1610
      levelsByRoom = { ...levelsByRoom, [roomId]: levels };
1611
    } catch {
1612
      levelsByRoom = { ...levelsByRoom, [roomId]: levelsByRoom[roomId] ?? null };
1613
    }
1614
  }
1615
1616
  async function openUser(userId: string, x: number, y: number, asMenu: boolean): Promise<void> {
1617
    const roomId = $selectedRoomId;
1618
    if (roomId && !(roomId in levelsByRoom)) await loadLevels(roomId);
1619
    else if (roomId) void loadLevels(roomId);
1620
    if (asMenu) menu = { items: userMenuItems(userId, x, y), x, y };
1621
    else userCard = { userId, x, y, confirm: null };
1622
  }
1623
1624
  function copyText(text: string): void {
1625
    navigator.clipboard.writeText(text).catch(() => pushBanner('Could not copy to the clipboard'));
1626
  }
1627
1628
  function userMenuItems(userId: string, x: number, y: number): MenuItem[] {
1629
    const own = userId === $sessionUser;
1630
    const member = memberFor(userId);
1631
    const items: MenuItem[] = [];
1632
    if (!own) items.push({ label: 'Message', action: () => void userAction(userId, { kind: 'message' }) });
1633
    items.push({ label: 'Mention', action: () => void userAction(userId, { kind: 'mention' }) });
1634
    items.push({ label: 'Copy user ID', action: () => copyText(userId) });
1635
    const firstModeration = items.length;
1636
    if (roomLevels && $sessionUser) {
1637
      const can = allowed(roomLevels, $sessionUser, userId);
1638
      const banned = member?.membership === 'Ban';
1639
      if (can.setLevel && !own) {
1640
        const muted = isMuted(roomLevels, userId);
1641
        items.push({ label: muted ? 'Unmute' : 'Mute', action: () => void userAction(userId, { kind: muted ? 'unmute' : 'mute' }) });
1642
      }
1643
      if (can.kick && !banned) items.push({ label: 'Kick…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'kick' }) });
1644
      if (can.ban && banned) items.push({ label: 'Unban', action: () => void userAction(userId, { kind: 'unban' }) });
1645
      if (can.ban && !banned) items.push({ label: 'Ban…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'ban' }) });
1646
      if (can.setLevel) items.push({ label: 'Power level…', action: () => (userCard = { userId, x, y, confirm: null }) });
1647
    }
1648
    if (items[firstModeration]) items[firstModeration] = { ...items[firstModeration], divider: true };
1649
    if (!own) {
1650
      const kind = member?.ignored ? 'unignore' : 'ignore';
1651
      items.push({ label: member?.ignored ? 'Unignore' : 'Ignore', divider: true, action: () => void userAction(userId, { kind }) });
1652
    }
1653
    return items;
1654
  }
1655
1656
  async function insertMention(person: Person): Promise<void> {
1657
    const roomId = $selectedRoomId;
1658
    if (!roomId) return;
1659
    const lead = composer && !/\s$/.test(composer) ? ' ' : '';
1660
    composer = `${composer}${lead}${person.name} `;
1661
    pickedMentions = {
1662
      ...pickedMentions,
1663
      [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }]
1664
    };
1665
    await tick();
1666
    composerEl?.focus();
1667
    composerEl?.setSelectionRange(composer.length, composer.length);
1668
  }
1669
1670
  async function userAction(userId: string, action: UserAction): Promise<void> {
1671
    const roomId = $selectedRoomId;
1672
    try {
1673
      switch (action.kind) {
1674
        case 'message': {
1675
          const res = (await runCommand({ op: 'direct', user_id: userId })) as { room_id: string };
1676
          await refreshRooms();
1677
          await selectRoom(res.room_id);
1678
          return;
1679
        }
1680
        case 'mention':
1681
          await insertMention(personFor(userId));
1682
          return;
1683
        case 'ignore':
1684
        case 'unignore':
1685
          await runCommand({ op: action.kind, user_id: userId });
1686
          if (roomId) void loadMembers(roomId);
1687
          return;
1688
      }
1689
      if (!roomId) return;
1690
      switch (action.kind) {
1691
        case 'kick':
1692
        case 'ban':
1693
          await runCommand({ op: action.kind, room_id: roomId, user_id: userId, reason: action.reason });
1694
          break;
1695
        case 'unban':
1696
          await runCommand({ op: 'unban', room_id: roomId, user_id: userId, reason: null });
1697
          break;
1698
        case 'mute':
1699
        case 'unmute':
1700
          await runCommand({ op: 'mute', room_id: roomId, user_id: userId, muted: action.kind === 'mute' });
1701
          break;
1702
        case 'power':
1703
          await runCommand({ op: 'set_power_level', room_id: roomId, user_id: userId, level: action.level });
1704
          break;
1705
      }
1706
      void loadLevels(roomId);
1707
      void loadMembers(roomId);
1708
    } catch (e) {
1709
      pushBanner(e instanceof Error ? e.message : 'That action failed');
1710
    }
1711
  }
1712
1713
  function roomMenuItems(room: RoomSummary): MenuItem[] {
1714
    const items: MenuItem[] = room.space
1715
      ? [{ label: 'Open', action: () => void selectSpace(room.room_id) }]
1716
      : [
1717
          { label: 'Open', action: () => void selectRoom(room.room_id) },
1718
          { label: 'Peek', action: () => void selectRoom(room.room_id, true) }
1719
        ];
1720
    items.push({ label: room.favourite ? 'Unpin' : room.space ? 'Pin to top' : 'Pin', action: () => void togglePin(room) });
1721
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${room.canonical_alias ?? room.room_id}`) });
1722
    items.push({ label: 'Copy room ID', action: () => copyText(room.room_id) });
1723
    if (!room.space && room.membership === 'Joined') {
1724
      items.push({ label: 'Repair message history', action: () => void showHistoryRepair(room.room_id) });
1725
    }
1726
    if (room.membership === 'Joined') items.push({ label: 'Leave', danger: true, divider: true, action: () => void leave(room.room_id) });
1727
    return items;
1728
  }
1729
1730
  function openRoomMenu(ev: MouseEvent, room: RoomSummary): void {
1731
    menu = { items: roomMenuItems(room), x: ev.clientX, y: ev.clientY };
1732
  }
1733
1734
  function roomName(roomId: string): string {
1735
    return $rooms.find((r) => r.room_id === roomId)?.name ?? roomId;
1736
  }
1737
1738
  async function sendSticker(roomId: string, pack: ImagePack, image: PackImage): Promise<void> {
1739
    stickersOpen = false;
1740
    stickToBottom = true;
1741
    try {
1742
      await runCommand({ op: 'send_sticker', room_id: roomId, pack_id: pack.id, shortcode: image.shortcode });
1743
      if (peeking === roomId) stopPeeking();
1744
    } catch (e) {
1745
      pushBanner(e instanceof Error ? e.message : 'Could not send the sticker');
1746
    }
1747
  }
1748
1749
  async function runClone(request: CommandRequest, failure: string): Promise<void> {
1750
    try {
1751
      const res = (await runCommand(request)) as { skipped?: string[] } | undefined;
1752
      if (res?.skipped?.length) pushBanner(`Couldn't copy ${res.skipped.map((s) => `:${s}:`).join(', ')}`);
1753
    } catch (e) {
1754
      pushBanner(e instanceof Error ? e.message : failure);
1755
    }
1756
  }
1757
1758
  function openCloneImageMenu(pack: ImagePack, image: PackImage, x: number, y: number): void {
1759
    stickersOpen = false;
1760
    menu = null;
1761
    cloneSource = { kind: 'image', pack, image };
1762
  }
1763
1764
  function openClonePackMenu(pack: ImagePack, x: number, y: number): void {
1765
    stickersOpen = false;
1766
    menu = null;
1767
    cloneSource = { kind: 'pack', pack };
1768
  }
1769
1770
  function openCloneStickerMenu(eventId: string, body: string, x: number, y: number): void {
1771
    const roomId = $selectedRoomId;
1772
    if (!roomId) return;
1773
    menu = null;
1774
    cloneSource = { kind: 'sticker', room_id: roomId, event_id: eventId, body };
1775
  }
1776
1777
  async function openMessageMenu(event: TimelineEvent, x: number, y: number): Promise<void> {
1778
    const roomId = $selectedRoomId;
1779
    const eventId = event.event_id;
1780
    if (!roomId || !eventId) return;
1781
    if (!(roomId in levelsByRoom)) await loadLevels(roomId);
1782
    const joined = selectedRoom?.membership === 'Joined';
1783
    const content = event.content;
1784
    const items: MenuItem[] = [];
1785
    if (joined) {
1786
      items.push({
1787
        label: 'Reply',
1788
        action: () =>
1789
          startReply({
1790
            event_id: eventId,
1791
            details: { kind: 'Ready', sender: event.sender, content, timestamp_ms: event.timestamp_ms }
1792
          })
1793
      });
1794
    }
1795
    if (joined && event.own && event.editable && content.kind === 'Message' && content.message.kind === 'Text') {
1796
      const body = content.message.body;
1797
      items.push({ label: 'Edit', action: () => startEdit(eventId, body) });
1798
    }
1799
    if (content.kind === 'Message' && content.message.body) {
1800
      const body = content.message.body;
1801
      items.push({ label: 'Copy text', action: () => copyText(body) });
1802
    }
1803
    items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${roomId}/${eventId}`) });
1804
    if (joined && selectedRoom?.can_pin && content.kind !== 'Redacted') {
1805
      const pinned = selectedRoom.pinned_events.includes(eventId);
1806
      items.push({ label: pinned ? 'Unpin' : 'Pin', action: () => setPinned(eventId, !pinned) });
1807
    }
1808
    if (content.kind === 'Sticker') {
1809
      const body = content.body;
1810
      items.push({ label: 'Clone sticker…', action: () => openCloneStickerMenu(eventId, body, x, y) });
1811
    }
1812
    const me = $sessionUser;
1813
    if (joined && me && roomLevels && canRedact(roomLevels, me, event.sender.user_id) && content.kind !== 'Redacted') {
1814
      items.push({
1815
        label: 'Delete message…',
1816
        danger: true,
1817
        action: () =>
1818
          (menu = {
1819
            x,
1820
            y,
1821
            items: [
1822
              { label: 'Delete', danger: true, action: () => void runClone({ op: 'redact', room_id: roomId, event_id: eventId, reason: null }, 'Could not delete the message') },
1823
              { label: 'Cancel', action: () => undefined }
1824
            ]
1825
          })
1826
      });
1827
    }
1828
    if (!event.own) {
1829
      const person = userMenuItems(event.sender.user_id, x, y);
1830
      if (person[0]) person[0] = { ...person[0], divider: true };
1831
      items.push(...person);
1832
    }
1833
    menu = { items, x, y };
1834
  }
1835
1836
  function openAccountMenu(ev: MouseEvent): void {
1837
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1838
    menu = {
1839
      x: rect.left,
1840
      y: rect.top - 6,
1841
      above: true,
1842
      items: [
1843
        { label: 'Security', action: () => (dialog = 'security') },
1844
        { label: 'Settings', action: () => (dialog = 'settings') },
1845
        { label: 'Sticker and emoji packs', action: () => (dialog = 'packs') },
1846
        { label: 'Log out', danger: true, divider: true, action: () => void doLogout() }
1847
      ]
1848
    };
1849
  }
1850
1851
  let resizing = false;
1852
1853
  function startResize(ev: PointerEvent, pane: 'side' | 'members'): void {
1854
    if (ev.button !== 0) return;
1855
    ev.preventDefault();
1856
    const handle = ev.currentTarget as HTMLElement;
1857
    handle.setPointerCapture(ev.pointerId);
1858
    const store = pane === 'side' ? sideWidth : membersWidth;
1859
    const range = pane === 'side' ? SIDE_WIDTH : MEMBERS_WIDTH;
1860
    const startX = ev.clientX;
1861
    const startWidth = pane === 'side' ? $sideWidth : $membersWidth;
1862
    resizing = true;
1863
    const move = (e: PointerEvent) => {
1864
      const delta = pane === 'side' ? e.clientX - startX : startX - e.clientX;
1865
      store.set(Math.round(Math.min(range.max, Math.max(range.min, startWidth + delta))));
1866
    };
1867
    const end = () => {
1868
      resizing = false;
1869
      handle.removeEventListener('pointermove', move);
1870
      handle.removeEventListener('pointerup', end);
1871
      handle.removeEventListener('pointercancel', end);
1872
    };
1873
    handle.addEventListener('pointermove', move);
1874
    handle.addEventListener('pointerup', end);
1875
    handle.addEventListener('pointercancel', end);
1876
  }
1877
1878
  function resetWidth(pane: 'side' | 'members'): void {
1879
    if (pane === 'side') sideWidth.set(SIDE_WIDTH.default);
1880
    else membersWidth.set(MEMBERS_WIDTH.default);
1881
  }
1882
1883
  function stopPeeking(): void {
1884
    peeking = null;
1885
    queueReadReceipt();
1886
  }
1887
1888
  async function togglePin(room: RoomSummary): Promise<void> {
1889
    try {
1890
      await runCommand({ op: 'set_favourite', room_id: room.room_id, favourite: !room.favourite });
1891
    } catch (e) {
1892
      pushBanner(e instanceof Error ? e.message : 'Could not change the pin');
1893
    }
1894
  }
1895
1896
  function startRailDrag(ev: DragEvent, id: string): void {
1897
    dragSpaceId = id;
1898
    if (ev.dataTransfer) {
1899
      ev.dataTransfer.effectAllowed = 'move';
1900
      ev.dataTransfer.setData('text/plain', id);
1901
    }
1902
  }
1903
1904
  function overRailSpace(ev: DragEvent, space: RoomSummary): void {
1905
    const dragged = orderedRail.find((s) => s.room_id === dragSpaceId);
1906
    if (!dragged || dragged.room_id === space.room_id || dragged.favourite !== space.favourite) return;
1907
    ev.preventDefault();
1908
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
1909
    dropTarget = { id: space.room_id, after: ev.clientY > rect.top + rect.height / 2 };
1910
  }
1911
1912
  async function dropRailSpace(): Promise<void> {
1913
    const moved = dragSpaceId;
1914
    const target = dropTarget;
1915
    dragSpaceId = null;
1916
    dropTarget = null;
1917
    if (!moved || !target) return;
1918
    const ids = orderedRail.map((s) => s.room_id);
1919
    const before = target.after ? (ids[ids.indexOf(target.id) + 1] ?? null) : target.id;
1920
    const order = moveBefore(ids, moved, before === moved ? null : before);
1921
    if (order.join() === ids.join()) return;
1922
    railOverride = order;
1923
    try {
1924
      await runCommand({ op: 'reorder_spaces', order });
1925
    } catch (e) {
1926
      railOverride = null;
1927
      pushBanner(e instanceof Error ? e.message : 'Could not reorder spaces');
1928
    }
1929
  }
1930
1931
  let roomMenuOpen = false;
1932
  let roomMenuEl: HTMLDivElement | null = null;
1933
1934
  function roomMenuAction(action: () => void): void {
1935
    roomMenuOpen = false;
1936
    action();
1937
  }
1938
1939
  function closeRoomMenuOutside(ev: PointerEvent): void {
1940
    if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false;
1941
  }
1942
1943
  function onKeydown(ev: KeyboardEvent): void {
1944
    if (ev.key === 'Escape') {
1945
      if (roomMenuOpen) roomMenuOpen = false;
1946
      else if (dialog) dialog = null;
1947
      else if (membersOpen && window.innerWidth < 1100) membersOpen = false;
1948
      else if (sidebarOpen) sidebarOpen = false;
1949
    }
1950
  }
1951
</script>
1952
1953
<svelte:window
1954
  on:keydown={onKeydown}
1955
  on:pointerdown={closeRoomMenuOutside}
1956
/>
1957
1958
{#if !booted}
1959
  <div class="splash" role="status" aria-label="Loading Malice" out:fade={{ duration: motionDuration(260) }}>
1960
    <div class="splash-mark" aria-hidden="true">M</div>
1961
    <p>Loading Malice…</p>
1962
  </div>
1963
{:else if $blocked}
1964
  <div class="splash" role="status" aria-label="Malice is open in another tab" in:fade={{ duration: motionDuration(220) }}>
1965
    <div class="splash-mark" aria-hidden="true">M</div>
1966
    <p>Malice is open in another tab. Close this tab or use that one instead.</p>
1967
  </div>
1968
{:else if $sessionUser == null}
1969
  <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} />
1970
{:else}
1971
  <div
1972
    class="app"
1973
    in:fade={{ duration: motionDuration(220) }}
1974
    class:nav-folded={$navFolded}
1975
    class:rail-folded={$railFolded && selectedRoom}
1976
    class:members-open={selectedRoom && membersOpen}
1977
    class:resizing
1978
    style:--side-open={`${$sideWidth}px`}
1979
    style:--members-open={`${$membersWidth}px`}
1980
    style:--msg-gap={`${$messageSpacing}px`}
1981
    style:--msg-line-height={$lineHeight}
1982
  >
1983
    <header class="chat-head">
1984
      <button
1985
        type="button"
1986
        class="icon-btn only-mobile"
1987
        aria-label="Open room list"
1988
        on:click={() => (sidebarOpen = true)}
1989
      >
1990
        <span aria-hidden="true">☰</span>
1991
      </button>
1992
      <button
1993
        type="button"
1994
        class="icon-btn only-desktop pane-toggle"
1995
        aria-pressed={!$railFolded}
1996
        aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'}
1997
        title={$railFolded ? 'Show spaces' : 'Hide spaces'}
1998
        on:click={() => railFolded.update((v) => !v)}
1999
      >
2000
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
2001
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
2002
          <circle cx="7" cy="9" r="1.4" fill="currentColor" />
2003
          <circle cx="7" cy="13" r="1.4" fill="currentColor" />
2004
          <circle cx="7" cy="17" r="1.4" fill="currentColor" />
2005
        </svg>
2006
      </button>
2007
      <button
2008
        type="button"
2009
        class="icon-btn only-desktop pane-toggle"
2010
        aria-pressed={!$navFolded}
2011
        aria-label={$navFolded ? 'Show channels' : 'Hide channels'}
2012
        title={$navFolded ? 'Show channels' : 'Hide channels'}
2013
        on:click={toggleChannelsPane}
2014
      >
2015
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
2016
          <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
2017
          <path d="M10 4v16" stroke="currentColor" stroke-width="2" />
2018
        </svg>
2019
      </button>
2020
      {#if selectedRoom}
2021
      <div class="head-title">
2022
        <div class="head-room">
2023
          <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape="rounded" />
2024
          <div class="head-room-text">
2025
            <h1><EmojiText text={selectedRoom.name} /></h1>
2026
            <div class="head-meta">
2027
              {#if selectedRoom.space}
2028
                <span class="pill">space</span>
2029
              {/if}
2030
              {#if selectedRoom.encrypted}
2031
                <span class="pill" title="End-to-end encrypted"><EmojiText text="🔒 encrypted" /></span>
2032
              {/if}
2033
              {#if selectedRoom.direct}
2034
                <span class="pill">direct</span>
2035
              {/if}
2036
              {#if $connection !== 'online'}
2037
                <span class="conn" title={`Sync state: ${$connection}`}>
2038
                  <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
2039
                  {$connection}
2040
                </span>
2041
              {/if}
2042
            </div>
2043
          </div>
2044
        </div>
2045
      </div>
2046
      {:else}
2047
      <div class="head-title">
2048
        <div class="head-room">
2049
          {#if selectedSpace}
2050
            <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={36} shape="rounded" />
2051
          {/if}
2052
          <div class="head-room-text">
2053
            <h1><EmojiText text={mentionsOpen ? 'Mentions' : selectedSpace?.name ?? 'Home'} /></h1>
2054
          </div>
2055
        </div>
2056
      </div>
2057
      {/if}
2058
      <div class="head-actions">
2059
        {#if selectedRoom}
2060
        {#if peeking === selectedRoom.room_id}
2061
          <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}>
2062
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
2063
              <path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12z" fill="none" stroke="currentColor" stroke-width="2" />
2064
              <circle cx="12" cy="12" r="3" fill="currentColor" />
2065
            </svg>
2066
          </button>
2067
        {/if}
2068
        {#if selectedRoom.membership !== 'Joined'}
2069
          <button
2070
            type="button"
2071
            class="primary-btn"
2072
            disabled={joinBusy}
2073
            on:click={() => void join(selectedRoom.room_id)}
2074
          >
2075
            {joinBusy ? 'Joining…' : 'Join'}
2076
          </button>
2077
        {/if}
2078
        <button
2079
          type="button"
2080
          class="icon-btn"
2081
          aria-pressed={membersOpen}
2082
          aria-label={membersOpen ? 'Hide members' : 'Show members'}
2083
          title="Members"
2084
          on:click={toggleMembers}
2085
        >
2086
          <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
2087
            <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" />
2088
            <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
2089
          </svg>
2090
        </button>
2091
        <div class="room-menu-wrap" bind:this={roomMenuEl}>
2092
          <button
2093
            type="button"
2094
            class="icon-btn"
2095
            aria-haspopup="menu"
2096
            aria-expanded={roomMenuOpen}
2097
            aria-label="Room options"
2098
            title="Room options"
2099
            on:click={() => (roomMenuOpen = !roomMenuOpen)}
2100
          >
2101
            <span aria-hidden="true">⋯</span>
2102
          </button>
2103
          {#if roomMenuOpen}
2104
            <div class="room-menu" role="menu">
2105
              {#if selectedRoom.membership === 'Joined'}
2106
                <button type="button" role="menuitem" on:click={() => roomMenuAction(() => void showHistoryRepair(selectedRoom.room_id))}>
2107
                  Repair message history
2108
                </button>
2109
                <button
2110
                  type="button"
2111
                  role="menuitem"
2112
                  class="danger"
2113
                  disabled={leaveBusy}
2114
                  on:click={() => roomMenuAction(() => void leave())}
2115
                >
2116
                  {leaveBusy ? 'Leaving…' : 'Leave room'}
2117
                </button>
2118
              {/if}
2119
            </div>
2120
          {/if}
2121
        </div>
2122
        {/if}
2123
      </div>
2124
    </header>
2125
2126
    <nav class="rail" aria-label="Servers and spaces">
2127
      <button
2128
        type="button"
2129
        class="rail-btn"
2130
        class:active={selectedSpaceId === null}
2131
        title="Home — all channels"
2132
        aria-label="Home — all channels"
2133
        aria-pressed={selectedSpaceId === null}
2134
        on:click={() => void selectHome()}
2135
      >
2136
        <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true"><path d="M4 11l8-7 8 7v8a1 1 0 0 1-1 1h-4v-6H9v6H5a1 1 0 0 1-1-1z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
2137
      </button>
2138
      {#each [pinnedRail, otherRail] as group}
2139
        {#if group.length > 0}
2140
          <div class="rail-sep" aria-hidden="true"></div>
2141
        {/if}
2142
        {#each group as space (space.room_id)}
2143
          <button
2144
            type="button"
2145
            class="rail-btn rail-space"
2146
            class:active={railSelected === space.room_id}
2147
            class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after}
2148
            class:drop-after={dropTarget?.id === space.room_id && dropTarget.after}
2149
            class:pinned={space.favourite}
2150
            title={space.name}
2151
            aria-label={`Show channels in space ${space.name}`}
2152
            aria-pressed={selectedSpaceId === space.room_id}
2153
            draggable="true"
2154
            on:click={() => void selectSpace(space.room_id)}
2155
            on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)}
2156
            on:dragstart={(ev) => startRailDrag(ev, space.room_id)}
2157
            on:dragover={(ev) => overRailSpace(ev, space)}
2158
            on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)}
2159
            on:drop|preventDefault={() => void dropRailSpace()}
2160
            on:dragend={() => ((dragSpaceId = null), (dropTarget = null))}
2161
          >
2162
            <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" />
2163
          </button>
2164
        {/each}
2165
      {/each}
2166
      <button
2167
        type="button"
2168
        class="rail-btn rail-add"
2169
        aria-label="Join or create a room"
2170
        on:click={() => {
2171
          dialog = 'join';
2172
        }}
2173
      >
2174
        <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" /></svg>
2175
      </button>
2176
    </nav>
2177
2178
    {#if menu}
2179
      <ContextMenu items={menu.items} x={menu.x} y={menu.y} above={menu.above ?? false} onClose={() => (menu = null)} />
2180
    {/if}
2181
    {#if userCard}
2182
      {#key userCard}
2183
        {@const cardUser = userCard.userId}
2184
        <UserCard
2185
          person={personFor(cardUser)}
2186
          member={memberFor(cardUser)}
2187
          levels={roomLevels}
2188
          self={$sessionUser ?? null}
2189
          x={userCard.x}
2190
          y={userCard.y}
2191
          confirm={userCard.confirm}
2192
          onAction={(action) => void userAction(cardUser, action)}
2193
          onClose={() => (userCard = null)}
2194
        />
2195
      {/key}
2196
    {/if}
2197
2198
    <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms">
2199
      <!-- svelte-ignore a11y_no_static_element_interactions -->
2200
      <div class="pane-resize right" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'side')} on:dblclick={() => resetWidth('side')}></div>
2201
      <div class="side-search">
2202
        <label class="visually-hidden" for="room-search">Search rooms</label>
2203
        <input
2204
          id="room-search"
2205
          type="search"
2206
          placeholder="Search rooms"
2207
          bind:value={search}
2208
          autocomplete="off"
2209
        />
2210
        <button
2211
          type="button"
2212
          class="icon-btn"
2213
          title="Refresh rooms"
2214
          aria-label="Refresh rooms"
2215
          disabled={roomsLoading}
2216
          on:click={() => void refreshRooms()}
2217
        >
2218
          <span aria-hidden="true">⟳</span>
2219
        </button>
2220
      </div>
2221
      {#key selectedSpaceId ?? 'home'}
2222
      <div class="side-scroll" in:fly={{ y: 5, duration: motionDuration(180) }} out:fade={{ duration: motionDuration(120) }}>
2223
        {#if selectedSpace && spaceParents.has(selectedSpace.room_id)}
2224
          {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''}
2225
          <button type="button" class="room-row up-row" on:click={() => void selectSpace(parentId)}>
2226
            <span aria-hidden="true">↑</span>
2227
            <span class="room-name"><EmojiText text={$rooms.find((r) => r.room_id === parentId)?.name ?? 'Parent space'} /></span>
2228
          </button>
2229
        {/if}
2230
        {#if !selectedSpaceId}
2231
          <ul class="room-list">
2232
            <li>
2233
              <button type="button" class="room-row" class:active={mentionsOpen} on:click={selectMentions}>
2234
                <svg width="26" height="26" viewBox="0 0 26 26" aria-hidden="true"><text x="13" y="19" text-anchor="middle" fill="currentColor" font-size="22">@</text></svg>
2235
                <span class="room-name">Mentions</span>
2236
                {#if $mentionsSnapshot && $mentionsSnapshot.unread_count > 0}
2237
                  <span class="badge mention" aria-label={`${$mentionsSnapshot.unread_count} unread mentions`}>{$mentionsSnapshot.unread_count > 99 ? '99+' : $mentionsSnapshot.unread_count}</span>
2238
                {/if}
2239
              </button>
2240
            </li>
2241
          </ul>
2242
        {/if}
2243
        {#if roomsLoading && $rooms.length === 0}
2244
          <p class="side-note">Loading rooms…</p>
2245
        {:else if $rooms.length === 0}
2246
          <p class="side-note">No rooms yet</p>
2247
          <div class="side-cta">
2248
            <button type="button" on:click={() => (dialog = 'join')}>Join a room</button>
2249
            <button type="button" on:click={() => (dialog = 'create')}>Create one</button>
2250
          </div>
2251
        {:else}
2252
          {#if selectedSpaceId && spaceChildrenLoading}
2253
            <p class="side-note">Loading channels…</p>
2254
          {:else if selectedSpaceId && spaceChildrenError}
2255
            <p class="side-note" role="alert"><EmojiText text={spaceChildrenError} /></p>
2256
            <div class="side-cta">
2257
              <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button>
2258
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
2259
            </div>
2260
          {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0}
2261
            <p class="side-note">No channels</p>
2262
            <div class="side-cta">
2263
              <button type="button" on:click={() => void selectHome()}>Back to Home</button>
2264
            </div>
2265
          {:else}
2266
            {#if invites.length > 0 && !selectedSpaceId}
2267
              <h2 class="side-h">Invites</h2>
2268
              <ul class="room-list">
2269
                {#each invites as room (room.room_id)}
2270
                  <li>
2271
                    <button
2272
                      type="button"
2273
                      class="room-row"
2274
                      class:active={$selectedRoomId === room.room_id}
2275
                      on:click={() => void selectRoom(room.room_id)}
2276
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2277
                    >
2278
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2279
                      <span class="room-name"><EmojiText text={room.name} /></span>
2280
                      <span
2281
                        class="invite-join"
2282
                        role="button"
2283
                        tabindex="0"
2284
                        aria-label={`Join ${room.name}`}
2285
                        on:click|stopPropagation={() => void join(room.room_id)}
2286
                        on:keydown|stopPropagation={(ev) => {
2287
                          if (ev.key === 'Enter' || ev.key === ' ') {
2288
                            ev.preventDefault();
2289
                            void join(room.room_id);
2290
                          }
2291
                        }}
2292
                      >
2293
                        Join
2294
                      </span>
2295
                    </button>
2296
                  </li>
2297
                {/each}
2298
              </ul>
2299
            {/if}
2300
2301
            {#if directRooms.length > 0}
2302
              <h2 class="side-h">Direct messages</h2>
2303
              <ul class="room-list">
2304
                {#each directRooms as room (room.room_id)}
2305
                  <li class="room-item">
2306
                    <button
2307
                      type="button"
2308
                      class="room-row"
2309
                      class:active={$selectedRoomId === room.room_id}
2310
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2311
                      on:click={() => void selectRoom(room.room_id)}
2312
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2313
                    >
2314
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} />
2315
                      <span class="room-name"><EmojiText text={room.name} /></span>
2316
                      {#if roomUnread(room) > 0}
2317
                        <span
2318
                          class="badge"
2319
                          class:mention={room.unread_mentions > 0}
2320
                          aria-label={`${roomUnread(room)} unread`}
2321
                        >
2322
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2323
                        </span>
2324
                      {/if}
2325
                    </button>
2326
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2327
                  </li>
2328
                {/each}
2329
              </ul>
2330
            {/if}
2331
2332
            {#if groupRooms.length > 0}
2333
              <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2>
2334
              <ul class="room-list">
2335
                {#each groupRooms as room (room.room_id)}
2336
                  <li class="room-item">
2337
                    <button
2338
                      type="button"
2339
                      class="room-row"
2340
                      class:active={$selectedRoomId === room.room_id}
2341
                      aria-current={$selectedRoomId === room.room_id ? 'true' : undefined}
2342
                      on:click={() => void selectRoom(room.room_id)}
2343
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2344
                    >
2345
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2346
                      <span class="room-name"><EmojiText text={room.name} /></span>
2347
                      {#if roomUnread(room) > 0}
2348
                        <span
2349
                          class="badge"
2350
                          class:mention={room.unread_mentions > 0}
2351
                          aria-label={`${roomUnread(room)} unread`}
2352
                        >
2353
                          {roomUnread(room) > 99 ? '99+' : roomUnread(room)}
2354
                        </span>
2355
                      {/if}
2356
                    </button>
2357
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2358
                  </li>
2359
                {/each}
2360
              </ul>
2361
            {/if}
2362
2363
            {#if spaceList.length > 0}
2364
              <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2>
2365
              <ul class="room-list">
2366
                {#each spaceList as room (room.room_id)}
2367
                  <li class="room-item">
2368
                    <button
2369
                      type="button"
2370
                      class="room-row"
2371
                      class:active={selectedSpaceId === room.room_id}
2372
                      aria-label={`Show channels in space ${room.name}`}
2373
                      on:click={() => void selectSpace(room.room_id)}
2374
                      on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)}
2375
                    >
2376
                      <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" />
2377
                      <span class="room-name"><EmojiText text={room.name} /></span>
2378
                    </button>
2379
                    <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} />
2380
                  </li>
2381
                {/each}
2382
              </ul>
2383
            {/if}
2384
2385
            {#if query && visibleRooms.length === 0}
2386
              <p class="side-note">No rooms match “<EmojiText text={search.trim()} />”.</p>
2387
            {/if}
2388
          {/if}
2389
        {/if}
2390
      </div>
2391
      {/key}
2392
2393
    </aside>
2394
    <div class="account">
2395
      <button type="button" class="me-btn" title={$sessionUser} aria-haspopup="menu" on:click={openAccountMenu}>
2396
        {#if profileMxc}
2397
          <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={32} />
2398
        {:else}
2399
          <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span>
2400
        {/if}
2401
        <span class="me-names">
2402
          <span class="me-name"><EmojiText text={profile?.display_name || $sessionUser} /></span>
2403
          {#if profile?.display_name && profile.display_name !== $sessionUser}<span class="me-id">{$sessionUser}</span>{/if}
2404
        </span>
2405
      </button>
2406
      <div class="account-actions">
2407
        <button type="button" class="icon-btn" title="Encryption and verification" aria-label="Encryption and verification" on:click={() => (dialog = 'security')}>
2408
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path d="M12 3l8 3v6c0 4.5-3.4 8.2-8 9-4.6-.8-8-4.5-8-9V6z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" /></svg>
2409
        </button>
2410
        <button type="button" class="icon-btn" title="Settings" aria-label="Settings" on:click={() => (dialog = 'settings')}>
2411
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="1.8" /><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1L7 17M17 7l2.1-2.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2412
        </button>
2413
        <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}>
2414
          <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path d="M12 3v8M6.3 6.3a8 8 0 1 0 11.4 0" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" /></svg>
2415
        </button>
2416
      </div>
2417
    </div>
2418
    {#if sidebarOpen}
2419
      <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button>
2420
    {/if}
2421
2422
    <main class="chat">
2423
        {#if $banners.length > 0}
2424
          <div class="banners" aria-live="polite">
2425
            {#each $banners as banner (banner.id)}
2426
              <div class="banner" role="alert">
2427
                <span><EmojiText text={banner.message} /></span>
2428
                <button
2429
                  type="button"
2430
                  aria-label="Dismiss error"
2431
                  on:click={() => dismissBanner(banner.id)}
2432
                >
2433
                  ✕
2434
                </button>
2435
              </div>
2436
            {/each}
2437
          </div>
2438
        {/if}
2439
      {#key mentionsOpen ? 'mentions' : $selectedRoomId ?? 'home'}
2440
      <div class="chat-view">
2441
      {#if mentionsOpen && $sessionUser}
2442
        <MentionsInbox self={$sessionUser} onLive={(roomId) => void selectRoom(roomId)} />
2443
      {:else if !selectedRoom}
2444
        <div class="empty" in:fade={{ duration: motionDuration(180) }}>
2445
          <div class="empty-mark" aria-hidden="true">◈</div>
2446
          {#if selectedSpace}
2447
            <h1><EmojiText text={selectedSpace.name} /></h1>
2448
          {:else}
2449
            <h1>Welcome to Malice</h1>
2450
          {/if}
2451
          <div class="empty-cta">
2452
            <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button>
2453
            <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button>
2454
          </div>
2455
          <p class="conn-line">
2456
            <span class="dot {connectionClass($connection)}" aria-hidden="true"></span>
2457
            {$connection}
2458
          </p>
2459
        </div>
2460
      {:else}
2461
        {#if repairPanels[selectedRoom.room_id] ?? !!currentRepair}
2462
          <HistoryRepairPanel
2463
            report={currentRepair}
2464
            busy={!!repairBusy[selectedRoom.room_id]}
2465
            cancelling={!!repairCancelling[selectedRoom.room_id]}
2466
            error={repairErrors[selectedRoom.room_id] ?? null}
2467
            onStart={(policy) => void runHistoryRepair(selectedRoom.room_id, 'start', policy)}
2468
            onCancel={() => void cancelRoomRepair(selectedRoom.room_id)}
2469
            onContinue={() => void runHistoryRepair(selectedRoom.room_id, 'continue')}
2470
            onRecent={() => void runHistoryRepair(selectedRoom.room_id, 'recent')}
2471
            onClose={() => (repairPanels = { ...repairPanels, [selectedRoom.room_id]: false })}
2472
          />
2473
        {/if}
2474
        {#if pins.length}
2475
          <div class="pinned-strip" class:open={pinsExpanded}>
2476
            <div class="pinned-head">
2477
              <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M9 3h6l-1 6 4 4v2h-5v6l-1 1-1-1v-6H6v-2l4-4z" fill="currentColor" /></svg>
2478
              <button type="button" class="pinned-latest" title="Jump to pinned message" on:click={() => jumpToPin(pins[0].event_id ?? '')}>
2479
                <strong><EmojiText text={people[pins[0].sender.user_id]?.name ?? senderLabel(pins[0].sender)} /></strong>
2480
                <span><EmojiText text={contentPreview(pins[0].content)} /></span>
2481
              </button>
2482
              {#if pins.length > 1}
2483
                <button type="button" class="pinned-count" aria-expanded={pinsExpanded} on:click={() => (pinsExpanded = !pinsExpanded)}>
2484
                  {pins.length} pinned
2485
                  <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true"><path d="m6 9 6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" /></svg>
2486
                </button>
2487
              {/if}
2488
              {#if pinsExpanded && selectedRoom.can_pin}
2489
                <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pins[0].event_id ?? '', false)}>
2490
                  <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" /></svg>
2491
                </button>
2492
              {/if}
2493
            </div>
2494
            {#if pinsExpanded}
2495
              <ul class="pinned-list">
2496
                {#each pins.slice(1) as pin (pin.event_id)}
2497
                  <li>
2498
                    <button type="button" on:click={() => jumpToPin(pin.event_id ?? '')}>
2499
                      <strong><EmojiText text={people[pin.sender.user_id]?.name ?? senderLabel(pin.sender)} /></strong>
2500
                      <span><EmojiText text={contentPreview(pin.content)} /></span>
2501
                    </button>
2502
                    {#if selectedRoom.can_pin}
2503
                      <button type="button" class="icon-btn" aria-label="Unpin" title="Unpin" on:click={() => setPinned(pin.event_id ?? '', false)}>
2504
                        <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2" /></svg>
2505
                      </button>
2506
                    {/if}
2507
                  </li>
2508
                {/each}
2509
              </ul>
2510
            {/if}
2511
          </div>
2512
        {/if}
2513
        {#if recoveryBanner}
2514
          <div class="sec-banner warn" role="status">
2515
            <span>Message history is locked</span>
2516
            <button type="button" on:click={() => (dialog = 'security')}>Recover</button>
2517
          </div>
2518
        {/if}
2519
        {#if verificationBanner}
2520
          <div class="sec-banner" role="status">
2521
            {#if verificationBanner.kind === 'Incoming'}
2522
              <span>A device wants to verify this session</span>
2523
              <button type="button" on:click={() => (dialog = 'security')}>Review request</button>
2524
            {:else if verificationBanner.kind === 'Comparison'}
2525
              <span>Verification codes ready</span>
2526
              <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button>
2527
            {:else if verificationBanner.kind === 'Waiting'}
2528
              <span>Verification started</span>
2529
              <button type="button" on:click={() => (dialog = 'security')}>Open verification</button>
2530
            {:else if verificationBanner.kind === 'Failed'}
2531
              <span>Verification failed: <EmojiText text={verificationBanner.message} /></span>
2532
              <button type="button" on:click={() => (dialog = 'security')}>Try again</button>
2533
            {:else if verificationBanner.kind === 'Cancelled'}
2534
              <span>Verification cancelled: <EmojiText text={verificationBanner.reason} /></span>
2535
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2536
            {:else}
2537
              <span>Verification in progress</span>
2538
              <button type="button" on:click={() => (dialog = 'security')}>Open security</button>
2539
            {/if}
2540
          </div>
2541
        {/if}
2542
        {#if $selectedRoomId && openFailed[$selectedRoomId]}
2543
          <p class="conn-banner error" role="alert"><EmojiText text={openFailed[$selectedRoomId]} /></p>
2544
        {/if}
2545
2546
        {#if pinPreview}
2547
          <div class="pin-preview" role="dialog" aria-label="Pinned message preview">
2548
            <div class="pin-preview-head">
2549
              <strong><EmojiText text={people[pinPreview.sender.user_id]?.name ?? senderLabel(pinPreview.sender)} /></strong>
2550
              <button type="button" class="icon-btn" aria-label="Close pinned message preview" on:click={() => (pinPreview = null)}>✕</button>
2551
            </div>
2552
            <p><EmojiText text={contentPreview(pinPreview.content)} /></p>
2553
            <button type="button" class="primary-btn" disabled={pinJumpBusy} on:click={() => void jumpToPin(pinPreview?.event_id ?? '')}>
2554
              {pinJumpBusy ? 'Loading message…' : 'Jump to message'}
2555
            </button>
2556
          </div>
2557
        {/if}
2558
2559
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2560
        <div
2561
          class="timeline"
2562
          in:fly={{ y: 6, duration: motionDuration(180) }}
2563
          out:fade={{ duration: motionDuration(120) }}
2564
          bind:this={timelineEl}
2565
          on:scroll={onTimelineScroll}
2566
          on:wheel={noteUserScroll}
2567
          on:touchmove={noteUserScroll}
2568
          on:keydown={onTimelineKey}
2569
          on:pointerdown={noteUserScroll}
2570
          aria-label={`Messages in ${selectedRoom.name}`}
2571
        >
2572
          <div class="timeline-inner" use:pinTimeline>
2573
            <div class="timeline-top">
2574
              {#if hasStart}
2575
                <p class="start-note">Beginning of history</p>
2576
              {:else}
2577
                <button type="button" class="ghost-btn" disabled={paginateBusy || currentRepairActive} on:click={() => void paginate()}>
2578
                  {paginateBusy ? 'Loading…' : 'Load older messages'}
2579
                </button>
2580
              {/if}
2581
            </div>
2582
            {#if grouped.length === 0}
2583
              <p class="side-note timeline-empty">No messages yet</p>
2584
            {:else}
2585
              {#each grouped as g (g.key)}
2586
                {#if g.item.kind === 'day'}
2587
                  <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div>
2588
                {:else if g.item.kind === 'readMarker'}
2589
                  <div class="new-row"><span>New</span></div>
2590
                {:else if g.item.kind === 'start'}
2591
                  <p class="start-note">Beginning of history</p>
2592
                {:else if g.item.kind === 'unknown'}
2593
                  <p class="unknown-note">Unsupported event ({g.item.label})</p>
2594
                {:else}
2595
                  <MessageRow
2596
                    itemId={g.key}
2597
                    event={g.item.event}
2598
                    showSender={g.showSender}
2599
                    senderAvatar={senderAvatarFor(g.item.event.sender.user_id) ?? g.item.event.sender.avatar}
2600
                    {reacting}
2601
                    onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2602
                    quickReactions={usableQuickReactions}
2603
                    packs={roomPacks}
2604
                    linkPreviews={$linkPreviews}
2605
                    {loadPreview}
2606
                    onQuickChange={(list) => void changeQuickReactions(list)}
2607
                    {people}
2608
                    self={$sessionUser ?? null}
2609
                    onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)}
2610
                    onCloneSticker={openCloneStickerMenu}
2611
                    onMore={(ev, x, y) => void openMessageMenu(ev, x, y)}
2612
                    onReply={selectedRoom.membership === 'Joined' ? startReply : null}
2613
                    onJump={jumpTo}
2614
                    onEdit={selectedRoom.membership === 'Joined' ? startEdit : null}
2615
                    editing={editing !== null && editing.eventId === g.item.event.event_id}
2616
                    showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0}
2617
                  />
2618
                {/if}
2619
              {/each}
2620
            {/if}
2621
            {#each pendingItems as p, i (p.id)}
2622
              <MessageRow
2623
                itemId={`pending-${p.id}`}
2624
                event={pendingToEvent(p)}
2625
                onJump={jumpTo}
2626
                showSender={pendingShowSender(i)}
2627
                senderAvatar={senderAvatarFor($sessionUser ?? '')}
2628
                {reacting}
2629
                onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)}
2630
                quickReactions={usableQuickReactions}
2631
                packs={roomPacks}
2632
                linkPreviews={$linkPreviews}
2633
                {loadPreview}
2634
                onQuickChange={(list) => void changeQuickReactions(list)}
2635
              />
2636
              {#if p.status === 'failed'}
2637
                <div class="pending-actions">
2638
                  <span class="pending-error" role="alert"><EmojiText text={p.error ?? ''} /></span>
2639
                  <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button>
2640
                  <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button>
2641
                </div>
2642
              {/if}
2643
            {/each}
2644
          </div>
2645
        </div>
2646
2647
        {#if selectedRoom.membership === 'Joined'}
2648
          {#if editing}
2649
            <div class="reply-bar" role="status">
2650
              <span class="reply-bar-label">
2651
                Editing message
2652
                <span class="reply-bar-text"><EmojiText text={editing.original} /></span>
2653
              </span>
2654
              <button type="button" class="icon-btn" aria-label="Cancel edit" title="Cancel edit (Esc)" on:click={cancelEdit}>
2655
                <span aria-hidden="true">✕</span>
2656
              </button>
2657
            </div>
2658
          {:else if replyingTo && replyingTo.details.kind === 'Ready'}
2659
            <div class="reply-bar" role="status">
2660
              <span class="reply-bar-label">
2661
                Replying to <strong><EmojiText text={people[replyingTo.details.sender.user_id]?.name ?? senderLabel(replyingTo.details.sender)} /></strong>
2662
                <span class="reply-bar-text"><EmojiText text={contentPreview(replyingTo.details.content)} /></span>
2663
              </span>
2664
              <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}>
2665
                <span aria-hidden="true">✕</span>
2666
              </button>
2667
            </div>
2668
          {/if}
2669
          {#if $selectedRoomId && currentStaged.length > 0}
2670
            {@const stagedRoom = $selectedRoomId}
2671
            <ul class="staged" aria-label="Attachments to send">
2672
              {#each currentStaged as attachment (attachment.id)}
2673
                <li class="staged-item">
2674
                  {#if attachment.previewUrl}
2675
                    <img src={attachment.previewUrl} alt={attachment.file.name || 'Pasted image'} />
2676
                  {:else}
2677
                    <span class="staged-name"><EmojiText text={attachment.file.name || 'attachment'} /></span>
2678
                  {/if}
2679
                  <button
2680
                    type="button"
2681
                    class="icon-btn staged-remove"
2682
                    aria-label={`Remove ${attachment.file.name || 'attachment'}`}
2683
                    title="Remove"
2684
                    on:click={() => unstage(stagedRoom, attachment.id)}
2685
                  >
2686
                    <span aria-hidden="true">✕</span>
2687
                  </button>
2688
                </li>
2689
              {/each}
2690
            </ul>
2691
          {/if}
2692
          <form class="composer" class:replying={replyingTo || editing} class:staging={currentStaged.length > 0} on:submit|preventDefault={() => send()}>
2693
            <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label>
2694
            <input
2695
              type="file"
2696
              multiple
2697
              bind:this={fileInput}
2698
              class="visually-hidden"
2699
              aria-label="Attach a file"
2700
              on:change={() => void onFileChosen()}
2701
            />
2702
            <input
2703
              type="file"
2704
              accept="image/*"
2705
              bind:this={avatarInput}
2706
              class="visually-hidden"
2707
              aria-label="Choose a new avatar"
2708
              on:change={() => void onAvatarChosen()}
2709
            />
2710
            <button
2711
              type="button"
2712
              class="icon-btn"
2713
              class:busy={uploadBusy}
2714
              title={uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : 'Attach an image or file'}
2715
              aria-label="Attach an image or file"
2716
              aria-busy={uploadBusy}
2717
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2718
              on:click={pickFiles}
2719
            >
2720
              <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true">
2721
                <path d="M20 11.5l-8.2 8.2a5 5 0 0 1-7-7L13 4.4a3.3 3.3 0 0 1 4.7 4.7l-8.2 8.2a1.7 1.7 0 0 1-2.4-2.4l7.5-7.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
2722
              </svg>
2723
            </button>
2724
            <button
2725
              type="button"
2726
              class="icon-btn sticker-btn"
2727
              title="Stickers"
2728
              aria-label="Stickers"
2729
              aria-expanded={stickersOpen}
2730
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2731
              on:click={() => (stickersOpen = !stickersOpen)}
2732
            >
2733
              <svg viewBox="0 0 24 24" width="19" height="19" aria-hidden="true">
2734
                <path d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v7l-7 7H6a2 2 0 0 1-2-2z" fill="none" stroke="currentColor" stroke-width="1.8" />
2735
                <path d="M13 20v-5a2 2 0 0 1 2-2h5" fill="none" stroke="currentColor" stroke-width="1.8" />
2736
              </svg>
2737
            </button>
2738
            {#if stickersOpen && $selectedRoomId}
2739
              {@const stickerRoom = $selectedRoomId}
2740
              <div class="sticker-pop">
2741
                <StickerPicker
2742
                  packs={roomPacks}
2743
                  {roomName}
2744
                  onSend={(pack, image) => void sendSticker(stickerRoom, pack, image)}
2745
                  onClone={(pack, image, x, y) => openCloneImageMenu(pack, image, x, y)}
2746
                  onClonePack={(pack, x, y) => openClonePackMenu(pack, x, y)}
2747
                  onManage={() => ((stickersOpen = false), (dialog = 'packs'))}
2748
                  onClose={() => (stickersOpen = false)}
2749
                />
2750
              </div>
2751
            {/if}
2752
            <div class="composer-field" class:composing={composerComposing}>
2753
              {#if commandQuery !== null && commandCandidates.length > 0}
2754
                <ul class="mention-finder" role="listbox" aria-label="Commands">
2755
                  {#each commandCandidates as name, i (name)}
2756
                    <li
2757
                      role="option"
2758
                      aria-selected={i === commandIndex}
2759
                      class:active={i === commandIndex}
2760
                      on:pointerdown|preventDefault={() => void pickCommand(name)}
2761
                      on:pointerenter={() => (commandIndex = i)}
2762
                    >
2763
                      <span class="mention-name">/{name}</span>
2764
                      <span class="mention-id">{COMMAND_USAGE[name]}</span>
2765
                    </li>
2766
                  {/each}
2767
                </ul>
2768
              {/if}
2769
              {#if emoteQuery && emoteCandidates.length > 0}
2770
                <ul class="mention-finder" role="listbox" aria-label="Emotes">
2771
                  {#each emoteCandidates as candidate, i (candidate.kind + candidate.shortcode)}
2772
                    <li
2773
                      role="option"
2774
                      aria-selected={i === emoteIndex}
2775
                      class:active={i === emoteIndex}
2776
                      on:pointerdown|preventDefault={() => void pickEmote(candidate)}
2777
                      on:pointerenter={() => (emoteIndex = i)}
2778
                    >
2779
                      {#if candidate.kind === 'custom'}
2780
                        <img class="finder-emote" src={mediaUrl(candidate.mxc) ?? ''} alt="" />
2781
                      {:else}
2782
                        <span class="finder-emote"><EmojiText text={candidate.emoji} /></span>
2783
                      {/if}
2784
                      <span class="mention-name">:{candidate.shortcode}:</span>
2785
                    </li>
2786
                  {/each}
2787
                </ul>
2788
              {/if}
2789
              {#if mentionQuery && mentionCandidates.length > 0}
2790
                <ul class="mention-finder" role="listbox" aria-label="Mention someone">
2791
                  {#each mentionCandidates as person, i (person.user_id)}
2792
                    <li
2793
                      role="option"
2794
                      aria-selected={i === mentionIndex}
2795
                      class:active={i === mentionIndex}
2796
                      on:pointerdown|preventDefault={() => void pickMention(person)}
2797
                      on:pointerenter={() => (mentionIndex = i)}
2798
                    >
2799
                      <MxcAvatar mxc={person.avatar} label={person.name} size={22} />
2800
                      <span class="mention-name"><EmojiText text={person.name} /></span>
2801
                      <span class="mention-id">{person.user_id}</span>
2802
                    </li>
2803
                  {/each}
2804
                </ul>
2805
              {/if}
2806
            <div class="composer-marks" aria-hidden="true" bind:this={marksEl}>{#each composerMarks as part}{#if part.mark}<mark><ComposerText text={part.text} /></mark>{:else}<ComposerText text={part.text} />{/if}{/each}&#8203;</div>
2807
            <textarea
2808
              id="composer"
2809
              bind:this={composerEl}
2810
              bind:value={composer}
2811
              use:syncComposer
2812
              rows="1"
2813
              placeholder={`Message ${selectedRoom.name}`}
2814
              aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`}
2815
              on:keydown={onComposerKey}
2816
              on:input={() => void onComposerInput()}
2817
              on:compositionstart={() => (composerComposing = true)}
2818
              on:compositionend={() => (composerComposing = false)}
2819
              on:click={updateMentionQuery}
2820
              on:focus={ensureEmoji}
2821
              on:keyup={(e) => (e.key.startsWith('Arrow') && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') || e.key === 'Home' || e.key === 'End' ? updateMentionQuery() : undefined}
2822
              on:blur={() => ((mentionQuery = null), (commandQuery = null), (emoteQuery = null), (composerComposing = false))}
2823
              on:paste={onComposerPaste}
2824
              disabled={!($selectedRoomId && openReady[$selectedRoomId])}
2825
            ></textarea>
2826
            </div>
2827
            <button
2828
              type="submit"
2829
              class="primary-btn"
2830
              disabled={(!composer.trim() && currentStaged.length === 0) ||
2831
                !($selectedRoomId && openReady[$selectedRoomId]) ||
2832
                (currentStaged.length > 0 && uploadBusy)}
2833
              title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'}
2834
            >
2835
              Send
2836
            </button>
2837
          </form>
2838
        {:else}
2839
          <div class="join-bar">
2840
            <p>You are not a member of this room.</p>
2841
            <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}>
2842
              <EmojiText text={joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`} />
2843
            </button>
2844
          </div>
2845
        {/if}
2846
      {/if}
2847
      </div>
2848
      {/key}
2849
    </main>
2850
2851
    {#if selectedRoom}
2852
      <aside class="members" aria-hidden={!membersOpen} aria-label={`Members of ${selectedRoom.name}`}>
2853
        <!-- svelte-ignore a11y_no_static_element_interactions -->
2854
        <div class="pane-resize left" title="Drag to resize" on:pointerdown={(e) => startResize(e, 'members')} on:dblclick={() => resetWidth('members')}></div>
2855
        <div class="members-head">
2856
          <h2>Members</h2>
2857
          <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}>
2858
            <span aria-hidden="true">✕</span>
2859
          </button>
2860
        </div>
2861
        {#if $membersLoading && members.length === 0}
2862
          <p class="side-note">Loading members…</p>
2863
        {:else if members.length === 0}
2864
          <p class="side-note">No members loaded.</p>
2865
          {#if $selectedRoomId}
2866
            <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}>
2867
              Retry
2868
            </button>
2869
          {/if}
2870
        {:else}
2871
          <ul class="member-list">
2872
            {#each memberGroups as group (group.label)}
2873
              <li class="member-group">
2874
                <h3 class="member-group-label">{group.label}<span>{group.members.length}</span></h3>
2875
                <ul class="member-group-list">
2876
                  {#each group.members as member (member.user_id)}
2877
                    <li>
2878
                      <button
2879
                        type="button"
2880
                        class="member"
2881
                        on:click={(ev) => {
2882
                          const rect = ev.currentTarget.getBoundingClientRect();
2883
                          void openUser(member.user_id, rect.left - 308, rect.top, false);
2884
                        }}
2885
                        on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)}
2886
                      >
2887
                        <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} seed={member.user_id} size={28} />
2888
                        <span class="member-names">
2889
                          <span class="member-name"><EmojiText text={member.display_name || member.name} /></span>
2890
                          <span class="member-id">{member.user_id}</span>
2891
                        </span>
2892
                      </button>
2893
                    </li>
2894
                  {/each}
2895
                </ul>
2896
              </li>
2897
            {/each}
2898
          </ul>
2899
        {/if}
2900
      </aside>
2901
    {/if}
2902
2903
    {#if cloneSource}
2904
      <div class="modal-wrap" role="presentation" on:click|self={() => (cloneSource = null)}>
2905
        <PackCloneDialog source={cloneSource} packs={$imagePacks} rooms={$rooms} onError={pushBanner} onClose={() => (cloneSource = null)} />
2906
      </div>
2907
    {/if}
2908
2909
    {#if dialog}
2910
      <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}>
2911
        {#if dialog === 'security'}
2912
          <SecurityPanel
2913
            encryptionState={$encryption}
2914
            verificationState={$verification}
2915
            onAction={() => void loadEncryption()}
2916
            encryptedPreviews={$urlPreviewSettings.encrypted_rooms}
2917
            onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)}
2918
            on:close={() => (dialog = null)}
2919
          />
2920
        {:else if dialog === 'settings'}
2921
          <SettingsPanel
2922
            quick={$quickReactions}
2923
            packs={roomPacks}
2924
            onQuickChange={(list) => void changeQuickReactions(list)}
2925
            on:close={() => (dialog = null)}
2926
            on:packs={() => (dialog = 'packs')}
2927
          />
2928
        {:else if dialog === 'packs'}
2929
          <PackManager packs={$imagePacks} rooms={$rooms} onError={pushBanner} on:close={() => (dialog = null)} />
2930
        {:else}
2931
          <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}>
2932
            <div class="modal-tabs" role="tablist" aria-label="Room actions">
2933
              <button
2934
                type="button"
2935
                role="tab"
2936
                aria-selected={dialog === 'join'}
2937
                class:active={dialog === 'join'}
2938
                on:click={() => (dialog = 'join')}
2939
              >
2940
                Join
2941
              </button>
2942
              <button
2943
                type="button"
2944
                role="tab"
2945
                aria-selected={dialog === 'create'}
2946
                class:active={dialog === 'create'}
2947
                on:click={() => (dialog = 'create')}
2948
              >
2949
                Create
2950
              </button>
2951
              <button
2952
                type="button"
2953
                class="icon-btn modal-x"
2954
                aria-label="Close dialog"
2955
                on:click={() => (dialog = null)}
2956
              >
2957
                <span aria-hidden="true">✕</span>
2958
              </button>
2959
            </div>
2960
            {#if dialog === 'join'}
2961
              <form on:submit|preventDefault={() => void join(joinTarget)}>
2962
                <label class="field">
2963
                  <span>Room ID or alias</span>
2964
                  <input
2965
                    type="text"
2966
                    placeholder="!room:example.org or #alias:example.org"
2967
                    bind:value={joinTarget}
2968
                    required
2969
                    disabled={joinBusy}
2970
                  />
2971
                </label>
2972
                <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}>
2973
                  {joinBusy ? 'Joining…' : 'Join room'}
2974
                </button>
2975
              </form>
2976
            {:else}
2977
            <form on:submit|preventDefault={() => void create()}>
2978
              <label class="field">
2979
                <span>Room name</span>
2980
                <input
2981
                  type="text"
2982
                  placeholder="Weekend plans"
2983
                  bind:value={createName}
2984
                  required
2985
                  disabled={createBusy}
2986
                />
2987
              </label>
2988
              <label class="field">
2989
                <span>Topic (optional)</span>
2990
                <input
2991
                  type="text"
2992
                  placeholder="What should this room be about?"
2993
                  bind:value={createTopic}
2994
                  disabled={createBusy}
2995
                />
2996
              </label>
2997
              <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}>
2998
                {createBusy ? 'Creating…' : 'Create room'}
2999
              </button>
3000
            </form>
3001
            {/if}
3002
          </div>
3003
        {/if}
3004
      </div>
3005
    {/if}
3006
  </div>
3007
{/if}
3008
3009
<ImageLightbox />