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