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