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