atagen

malice

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