| 1 | <script lang="ts"> |
| 2 | import { onMount, tick } from 'svelte'; |
| 3 | import LoginPanel from './lib/LoginPanel.svelte'; |
| 4 | import MessageRow from './lib/MessageRow.svelte'; |
| 5 | import MxcAvatar from './lib/MxcAvatar.svelte'; |
| 6 | import PinButton from './lib/PinButton.svelte'; |
| 7 | import ContextMenu, { type MenuItem } from './lib/ContextMenu.svelte'; |
| 8 | import StickerPicker from './lib/StickerPicker.svelte'; |
| 9 | import PackManager from './lib/PackManager.svelte'; |
| 10 | import { clonePackDestinations, editableChoices, shortcodeFor } from './lib/packs'; |
| 11 | import type { CommandRequest } from './lib/transport'; |
| 12 | import UserCard, { type UserAction } from './lib/UserCard.svelte'; |
| 13 | import { allowed, isMuted, parsePowerLevels, type PowerLevels } from './lib/permissions'; |
| 14 | import { moveBefore, pinnedFirst, sortSpaces } from './lib/rail-order'; |
| 15 | import ImageLightbox from './lib/ImageLightbox.svelte'; |
| 16 | import { lightbox } from './lib/lightbox'; |
| 17 | import SecurityPanel from './lib/SecurityPanel.svelte'; |
| 18 | import { |
| 19 | closeRoom, |
| 20 | createRoom, |
| 21 | getEncryption, |
| 22 | getMembers, |
| 23 | getProfile, |
| 24 | getRooms, |
| 25 | getSession, |
| 26 | getSpaceChildren, |
| 27 | joinRoom, |
| 28 | leaveRoom, |
| 29 | logout, |
| 30 | markRead, |
| 31 | openRoom, |
| 32 | paginateRoom, |
| 33 | reactToMessage, |
| 34 | runCommand, |
| 35 | sendMessage, |
| 36 | uploadAttachment, |
| 37 | uploadAvatar, |
| 38 | uploadRoomAvatar, |
| 39 | editMessage |
| 40 | } from './lib/api'; |
| 41 | import { isKnownCommand, parseCommand, splitTarget, unescapeCommand } from './lib/commands'; |
| 42 | import type { ParsedCommand } from './lib/commands'; |
| 43 | import { |
| 44 | banners, |
| 45 | blocked, |
| 46 | connectEvents, |
| 47 | connection, |
| 48 | disconnectEvents, |
| 49 | dismissBanner, |
| 50 | encryption, |
| 51 | membersByRoom, |
| 52 | membersLoading, |
| 53 | pushBanner, |
| 54 | imagePacks, |
| 55 | resetClientState, |
| 56 | rooms, |
| 57 | selectedRoomId, |
| 58 | sessionUser, |
| 59 | softLogout, |
| 60 | timelines, |
| 61 | verification |
| 62 | } from './lib/store'; |
| 63 | import { discardPending, pendingByRoom, queueSend, resetPending, retryPending } from './lib/pending'; |
| 64 | import type { PendingMessage } from './lib/pending'; |
| 65 | import { insideOpenFence } from './lib/markdown'; |
| 66 | import { mentionQueryAt, mentionsFromHtml, rankPeople, resolveMentions } from './lib/mentions'; |
| 67 | import type { Mention, MentionQuery } from './lib/mentions'; |
| 68 | import { loadQuickReactions, quickReactions, saveQuickReactions } from './lib/quick-reactions'; |
| 69 | import { |
| 70 | linkPreviews, |
| 71 | loadUrlPreviewSettings, |
| 72 | requestLinkPreview, |
| 73 | saveUrlPreviewSettings, |
| 74 | urlPreviewSettings |
| 75 | } from './lib/link-previews'; |
| 76 | import { notifyTyping, stopTyping } from './lib/typing'; |
| 77 | import { formatDay } from './lib/format'; |
| 78 | import { lastSpaceRooms, lineHeight, markdownEnabled, messageSpacing, navFolded, railFolded } from './lib/appearance'; |
| 79 | import SettingsPanel from './lib/SettingsPanel.svelte'; |
| 80 | import { packsForRoom, parseEncryptionState, parseOwnProfile, parseVerificationState, contentPreview, senderLabel } from './lib/types'; |
| 81 | import type { ImagePack, MemberSummary, OwnProfile, PackImage, Person, QuickReaction, ReplyReference, RoomSummary, SendState, TimelineEvent, TimelineItem } from './lib/types'; |
| 82 | |
| 83 | let roomsLoading = false; |
| 84 | let booted = false; |
| 85 | let wasOnline = false; |
| 86 | let search = ''; |
| 87 | let sidebarOpen = false; |
| 88 | let membersOpen = false; |
| 89 | let replyingTo: ReplyReference | null = null; |
| 90 | let dialog: 'join' | 'create' | 'security' | 'settings' | 'packs' | null = null; |
| 91 | let stickersOpen = false; |
| 92 | let joinTarget = ''; |
| 93 | let joinBusy = false; |
| 94 | let createName = ''; |
| 95 | let createTopic = ''; |
| 96 | let createBusy = false; |
| 97 | let leaveBusy = false; |
| 98 | let paginateBusy = false; |
| 99 | let reacting = false; |
| 100 | let composer = ''; |
| 101 | let drafts: Record<string, string> = {}; |
| 102 | let stickToBottom = true; |
| 103 | let timelineEl: HTMLElement | null = null; |
| 104 | let composerEl: HTMLTextAreaElement | null = null; |
| 105 | let fileInput: HTMLInputElement | null = null; |
| 106 | let avatarInput: HTMLInputElement | null = null; |
| 107 | let uploadBusy = false; |
| 108 | let uploadName: string | null = null; |
| 109 | interface StagedAttachment { |
| 110 | id: number; |
| 111 | file: File; |
| 112 | previewUrl: string | null; |
| 113 | } |
| 114 | let staged: Record<string, StagedAttachment[]> = {}; |
| 115 | let editing: { roomId: string; eventId: string; original: string; stash: string } | null = null; |
| 116 | /** Everyone picked from the finder per room; only those whose name is still in the text get linked on send. */ |
| 117 | let pickedMentions: Record<string, Mention[]> = {}; |
| 118 | let mentionQuery: MentionQuery | null = null; |
| 119 | let mentionIndex = 0; |
| 120 | let nextStagedId = 1; |
| 121 | const WARM_ROOM_LIMIT = 8; |
| 122 | /** Rooms left open after switching away so coming back is instant, least recently viewed first. */ |
| 123 | let warmRooms: string[] = []; |
| 124 | let openReady: Record<string, boolean> = {}; |
| 125 | let openFailed: Record<string, string> = {}; |
| 126 | let membersFor: string | null = null; |
| 127 | let lastReadKey = ''; |
| 128 | let readTimer: number | null = null; |
| 129 | let profile: OwnProfile | null = null; |
| 130 | let profileMxc: string | null = null; |
| 131 | let selectedSpaceId: string | null = null; |
| 132 | let spaceChildIds: string[] | null = null; |
| 133 | let spaceChildrenLoading = false; |
| 134 | let spaceChildrenError: string | null = null; |
| 135 | let avatarByUser: Record<string, string | null> = {}; |
| 136 | |
| 137 | // account data is read from the local cache, which is empty on a fresh device until the first sync lands |
| 138 | $: { |
| 139 | const online = $connection === 'online'; |
| 140 | if (online && !wasOnline) { |
| 141 | void loadQuickReactions(); |
| 142 | void loadUrlPreviewSettings(); |
| 143 | } |
| 144 | wasOnline = online; |
| 145 | } |
| 146 | $: selectedRoom = $rooms.find((r) => r.room_id === $selectedRoomId) ?? null; |
| 147 | $: roomPacks = packsForRoom($imagePacks, $selectedRoomId); |
| 148 | $: previewsAllowed = selectedRoom !== null && (!selectedRoom.encrypted || $urlPreviewSettings.encrypted_rooms); |
| 149 | $: loadPreview = previewsAllowed && $selectedRoomId ? previewLoader($selectedRoomId) : null; |
| 150 | $: spaceRooms = $rooms.filter((r) => r.space); |
| 151 | $: spaceParents = parentSpaceMap(spaceRooms); |
| 152 | $: railSpaces = spaceRooms.filter((s) => !spaceParents.has(s.room_id)); |
| 153 | let railOverride: string[] | null = null; |
| 154 | $: if (railOverride && sortSpaces(railSpaces, null).map((s) => s.room_id).join() === railOverride.join()) railOverride = null; |
| 155 | $: orderedRail = sortSpaces(railSpaces, railOverride); |
| 156 | $: pinnedRail = orderedRail.filter((s) => s.favourite); |
| 157 | $: otherRail = orderedRail.filter((s) => !s.favourite); |
| 158 | $: railSelected = selectedSpaceId ? topSpaceOf(selectedSpaceId, spaceParents) : null; |
| 159 | $: invites = $rooms.filter((r) => r.membership === 'Invited'); |
| 160 | $: query = search.trim().toLowerCase(); |
| 161 | $: selectedSpace = selectedSpaceId ? ($rooms.find((r) => r.room_id === selectedSpaceId) ?? null) : null; |
| 162 | // While a space's children load (or fail), show no channels rather than the |
| 163 | // full list — listing everything would falsely imply it belongs to the space. |
| 164 | $: baseRooms = selectedSpaceId ? (spaceChildIds ? $rooms.filter((r) => spaceChildIds?.includes(r.room_id)) : []) : $rooms; |
| 165 | $: visibleRooms = query |
| 166 | ? baseRooms.filter( |
| 167 | (r) => |
| 168 | r.name.toLowerCase().includes(query) || r.room_id.toLowerCase().includes(query) |
| 169 | ) |
| 170 | : baseRooms; |
| 171 | $: directRooms = pinnedFirst(visibleRooms.filter((r) => r.direct && !r.space && r.membership !== 'Invited')); |
| 172 | $: groupRooms = pinnedFirst(visibleRooms.filter((r) => !r.direct && !r.space && r.membership !== 'Invited')); |
| 173 | $: spaceList = pinnedFirst(visibleRooms.filter((r) => r.space && r.membership !== 'Invited')); |
| 174 | $: channelRooms = baseRooms.filter((r) => !r.space && r.membership !== 'Invited'); |
| 175 | $: recoveryBanner = $encryption && ($encryption.recovery === 'Disabled' || $encryption.recovery === 'Incomplete') ? $encryption : null; |
| 176 | $: verificationBanner = $verification && $verification.kind !== 'Done' ? $verification : null; |
| 177 | $: items = $selectedRoomId ? ($timelines[$selectedRoomId] ?? []) : []; |
| 178 | $: currentStaged = $selectedRoomId ? (staged[$selectedRoomId] ?? []) : []; |
| 179 | $: members = $selectedRoomId ? ($membersByRoom[$selectedRoomId] ?? []) : []; |
| 180 | $: people = peopleIn(items, members); |
| 181 | $: mentionCandidates = mentionQuery ? rankPeople(Object.values(people), mentionQuery.query, $sessionUser ?? null) : []; |
| 182 | $: if (mentionIndex >= mentionCandidates.length) mentionIndex = 0; |
| 183 | $: hasStart = items.some((i) => i.kind === 'start'); |
| 184 | $: grouped = buildGroups(items); |
| 185 | $: lastSentId = lastOwnSent(items); |
| 186 | $: pendingItems = $selectedRoomId ? ($pendingByRoom[$selectedRoomId] ?? []) : []; |
| 187 | $: lastRealOwn = lastSenderIsOwn(items); |
| 188 | |
| 189 | function lastSenderIsOwn(list: TimelineItem[]): boolean { |
| 190 | for (let i = list.length - 1; i >= 0; i -= 1) { |
| 191 | const it = list[i]; |
| 192 | if (it.kind === 'event') return it.event.sender.user_id === $sessionUser; |
| 193 | } |
| 194 | return false; |
| 195 | } |
| 196 | |
| 197 | function pendingShowSender(index: number): boolean { |
| 198 | return index === 0 ? !lastRealOwn : false; |
| 199 | } |
| 200 | |
| 201 | function pendingToEvent(p: PendingMessage): TimelineEvent { |
| 202 | const state: SendState = p.status === 'failed' ? { kind: 'Failed', will_retry: false } : { kind: 'Sending' }; |
| 203 | return { |
| 204 | item_id: `pending-${p.id}`, |
| 205 | event_id: null, |
| 206 | transaction_id: p.id, |
| 207 | sender: { |
| 208 | user_id: $sessionUser ?? '', |
| 209 | display_name: profile?.display_name ?? null, |
| 210 | avatar: null, |
| 211 | name_ambiguous: false |
| 212 | }, |
| 213 | timestamp_ms: p.createdAt, |
| 214 | own: true, |
| 215 | send_state: state, |
| 216 | content: { |
| 217 | kind: 'Message', |
| 218 | message: { kind: 'Text', body: p.body, geo_uri: null, formatted_body: p.formatted, edited: false, media: null, link_previews: [] } |
| 219 | }, |
| 220 | reply_to: p.replyTo, |
| 221 | thread_root: null, |
| 222 | thread_summary: null, |
| 223 | reactions: [], |
| 224 | read_by: [], |
| 225 | editable: false |
| 226 | }; |
| 227 | } |
| 228 | |
| 229 | interface Group { |
| 230 | key: string; |
| 231 | item: TimelineItem; |
| 232 | showSender: boolean; |
| 233 | } |
| 234 | |
| 235 | function lastOwnSent(list: TimelineItem[]): string | null { |
| 236 | for (let i = list.length - 1; i >= 0; i--) { |
| 237 | const item = list[i]; |
| 238 | if (item.kind === 'event' && item.event.own && item.event.send_state.kind === 'Sent') return item.event.item_id; |
| 239 | } |
| 240 | return null; |
| 241 | } |
| 242 | |
| 243 | function buildGroups(list: TimelineItem[]): Group[] { |
| 244 | const out: Group[] = []; |
| 245 | let prevSender: string | null = null; |
| 246 | let prevTs = 0; |
| 247 | list.forEach((item, index) => { |
| 248 | let showSender = true; |
| 249 | if (item.kind === 'event') { |
| 250 | const e = item.event; |
| 251 | showSender = |
| 252 | prevSender !== e.sender.user_id || Math.abs(e.timestamp_ms - prevTs) > 5 * 60 * 1000; |
| 253 | prevSender = e.sender.user_id; |
| 254 | prevTs = e.timestamp_ms; |
| 255 | out.push({ key: e.item_id || e.event_id || `m-${index}`, item, showSender }); |
| 256 | } else { |
| 257 | prevSender = null; |
| 258 | out.push({ key: `${item.kind}-${index}`, item, showSender }); |
| 259 | } |
| 260 | }); |
| 261 | return out; |
| 262 | } |
| 263 | |
| 264 | function roomUnread(r: RoomSummary): number { |
| 265 | return r.unread_messages + r.unread_mentions; |
| 266 | } |
| 267 | |
| 268 | onMount(() => { |
| 269 | void boot(); |
| 270 | return () => { |
| 271 | disconnectEvents(); |
| 272 | stopTyping(); |
| 273 | if (readTimer !== null) window.clearTimeout(readTimer); |
| 274 | }; |
| 275 | }); |
| 276 | |
| 277 | async function boot(): Promise<void> { |
| 278 | try { |
| 279 | const session = await getSession(); |
| 280 | blocked.set(session.blocked ?? false); |
| 281 | sessionUser.set(session.user_id); |
| 282 | if (session.user_id) { |
| 283 | softLogout.set(null); |
| 284 | await refreshRooms(); |
| 285 | connectEvents(); |
| 286 | void loadProfile(); |
| 287 | void loadEncryption(); |
| 288 | void loadQuickReactions(); |
| 289 | void loadUrlPreviewSettings(); |
| 290 | } else { |
| 291 | softLogout.set(session.soft_logout ?? null); |
| 292 | } |
| 293 | } catch (e) { |
| 294 | pushBanner(e instanceof Error ? `Session check failed: ${e.message}` : 'Session check failed'); |
| 295 | sessionUser.set(null); |
| 296 | } finally { |
| 297 | booted = true; |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | async function refreshRooms(): Promise<void> { |
| 302 | roomsLoading = true; |
| 303 | try { |
| 304 | const res = await getRooms(); |
| 305 | rooms.set(res.rooms); |
| 306 | pruneSpaceFilter(); |
| 307 | } catch (e) { |
| 308 | pushBanner(e instanceof Error ? e.message : 'Could not load rooms'); |
| 309 | } finally { |
| 310 | roomsLoading = false; |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | async function loadProfile(): Promise<void> { |
| 315 | try { |
| 316 | const raw = await getProfile(); |
| 317 | profile = parseOwnProfile(raw); |
| 318 | profileMxc = profile.avatar_url; |
| 319 | } catch { |
| 320 | profile = null; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | async function loadEncryption(): Promise<void> { |
| 325 | try { |
| 326 | const res = await getEncryption(); |
| 327 | const state = parseEncryptionState(res.state); |
| 328 | if (state) encryption.set(state); |
| 329 | const verificationState = parseVerificationState(res.verification); |
| 330 | if (verificationState) verification.set(verificationState); |
| 331 | } catch { |
| 332 | // Encryption status also arrives over SSE; a failed first fetch is not fatal. |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | function afterLogin(userId: string): void { |
| 337 | sessionUser.set(userId); |
| 338 | softLogout.set(null); |
| 339 | blocked.set(false); |
| 340 | void refreshRooms(); |
| 341 | connectEvents(); |
| 342 | void loadProfile(); |
| 343 | void loadEncryption(); |
| 344 | void loadQuickReactions(); |
| 345 | void loadUrlPreviewSettings(); |
| 346 | } |
| 347 | |
| 348 | async function doLogout(): Promise<void> { |
| 349 | stopTyping(); |
| 350 | try { |
| 351 | await logout(); |
| 352 | } catch (e) { |
| 353 | pushBanner(e instanceof Error ? e.message : 'Logout failed'); |
| 354 | return; |
| 355 | } |
| 356 | disconnectEvents(); |
| 357 | resetClientState(); |
| 358 | softLogout.set(null); |
| 359 | blocked.set(false); |
| 360 | sessionUser.set(null); |
| 361 | lightbox.set(null); |
| 362 | composer = ''; |
| 363 | drafts = {}; |
| 364 | dialog = null; |
| 365 | membersOpen = false; |
| 366 | sidebarOpen = false; |
| 367 | profile = null; |
| 368 | profileMxc = null; |
| 369 | selectedSpaceId = null; |
| 370 | spaceChildIds = null; |
| 371 | spaceChildrenError = null; |
| 372 | openReady = {}; |
| 373 | openFailed = {}; |
| 374 | warmRooms = []; |
| 375 | pickedMentions = {}; |
| 376 | mentionQuery = null; |
| 377 | clearAllStaged(); |
| 378 | avatarByUser = {}; |
| 379 | resetPending(); |
| 380 | } |
| 381 | |
| 382 | /** Joined spaces that sit inside another joined space, keyed to one such parent. Either side of the link counts. */ |
| 383 | function parentSpaceMap(spaces: RoomSummary[]): Map<string, string> { |
| 384 | const ids = new Set(spaces.map((s) => s.room_id)); |
| 385 | const parents = new Map<string, string>(); |
| 386 | for (const space of spaces) { |
| 387 | for (const child of space.children) { |
| 388 | if (child !== space.room_id && ids.has(child) && !parents.has(child)) parents.set(child, space.room_id); |
| 389 | } |
| 390 | } |
| 391 | for (const space of spaces) { |
| 392 | const parent = space.parent_spaces.find((id) => id !== space.room_id && ids.has(id)); |
| 393 | if (parent && !parents.has(space.room_id)) parents.set(space.room_id, parent); |
| 394 | } |
| 395 | for (const id of [...parents.keys()]) { |
| 396 | const seen = new Set<string>([id]); |
| 397 | let at = parents.get(id); |
| 398 | while (at && !seen.has(at)) { |
| 399 | seen.add(at); |
| 400 | at = parents.get(at); |
| 401 | } |
| 402 | if (at) parents.delete(id); |
| 403 | } |
| 404 | return parents; |
| 405 | } |
| 406 | |
| 407 | function topSpaceOf(id: string, parents: Map<string, string>): string { |
| 408 | let at = id; |
| 409 | while (parents.has(at)) at = parents.get(at)!; |
| 410 | return at; |
| 411 | } |
| 412 | |
| 413 | function pruneSpaceFilter(): void { |
| 414 | if (!selectedSpaceId) return; |
| 415 | if (!$rooms.some((r) => r.room_id === selectedSpaceId)) { |
| 416 | selectedSpaceId = null; |
| 417 | spaceChildIds = null; |
| 418 | spaceChildrenError = null; |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | async function selectHome(): Promise<void> { |
| 423 | selectedSpaceId = null; |
| 424 | spaceChildIds = null; |
| 425 | spaceChildrenError = null; |
| 426 | sidebarOpen = true; |
| 427 | } |
| 428 | |
| 429 | async function selectSpace(spaceId: string): Promise<void> { |
| 430 | if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer; |
| 431 | stopTyping(); |
| 432 | selectedSpaceId = spaceId; |
| 433 | spaceChildIds = null; |
| 434 | spaceChildrenError = null; |
| 435 | spaceChildrenLoading = true; |
| 436 | const last = $lastSpaceRooms[spaceId]; |
| 437 | const resume = last && $rooms.some((r) => r.room_id === last && !r.space) ? last : null; |
| 438 | if (resume) { |
| 439 | void selectRoom(resume); |
| 440 | } else { |
| 441 | sidebarOpen = true; |
| 442 | // A space is navigation, not a message timeline. |
| 443 | selectedRoomId.set(null); |
| 444 | } |
| 445 | try { |
| 446 | const res = await getSpaceChildren(spaceId); |
| 447 | if (selectedSpaceId === spaceId) { |
| 448 | spaceChildIds = res.room_ids ?? []; |
| 449 | if (resume && !spaceChildIds.includes(resume) && $selectedRoomId === resume) { |
| 450 | sidebarOpen = true; |
| 451 | selectedRoomId.set(null); |
| 452 | } |
| 453 | } |
| 454 | } catch (e) { |
| 455 | if (selectedSpaceId === spaceId) { |
| 456 | spaceChildrenError = e instanceof Error ? e.message : 'Could not load rooms in this space'; |
| 457 | spaceChildIds = []; |
| 458 | } |
| 459 | } finally { |
| 460 | if (selectedSpaceId === spaceId) spaceChildrenLoading = false; |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | async function selectRoom(roomId: string, peek = false): Promise<void> { |
| 465 | peeking = peek ? roomId : null; |
| 466 | if ($selectedRoomId && composer.trim()) drafts[$selectedRoomId] = composer; |
| 467 | if (roomId === $selectedRoomId && openReady[roomId]) { |
| 468 | sidebarOpen = false; |
| 469 | return; |
| 470 | } |
| 471 | stopTyping(); |
| 472 | const spaceId = selectedSpaceId; |
| 473 | if (spaceId) lastSpaceRooms.update((all) => ({ ...all, [spaceId]: roomId })); |
| 474 | selectedRoomId.set(roomId); |
| 475 | composer = drafts[roomId] ?? ''; |
| 476 | replyingTo = null; |
| 477 | editing = null; |
| 478 | mentionQuery = null; |
| 479 | stickToBottom = true; |
| 480 | lastReadKey = ''; |
| 481 | sidebarOpen = false; |
| 482 | touchWarmRoom(roomId); |
| 483 | if (openReady[roomId]) { |
| 484 | if (membersOpen) void loadMembers(roomId); |
| 485 | await tick(); |
| 486 | scrollToBottom(); |
| 487 | queueReadReceipt(); |
| 488 | composerEl?.focus(); |
| 489 | return; |
| 490 | } |
| 491 | if (openFailed[roomId]) { |
| 492 | const nextFailed = { ...openFailed }; |
| 493 | delete nextFailed[roomId]; |
| 494 | openFailed = nextFailed; |
| 495 | } |
| 496 | try { |
| 497 | await openRoom(roomId); |
| 498 | if (warmRooms.includes(roomId)) openReady = { ...openReady, [roomId]: true }; |
| 499 | } catch (e) { |
| 500 | const message = e instanceof Error ? e.message : `Could not open room ${roomId}`; |
| 501 | openFailed = { ...openFailed, [roomId]: message }; |
| 502 | pushBanner(message); |
| 503 | } |
| 504 | if (membersOpen) void loadMembers(roomId); |
| 505 | await tick(); |
| 506 | scrollToBottom(); |
| 507 | queueReadReceipt(); |
| 508 | composerEl?.focus(); |
| 509 | } |
| 510 | |
| 511 | function touchWarmRoom(roomId: string): void { |
| 512 | warmRooms = [...warmRooms.filter((id) => id !== roomId), roomId]; |
| 513 | while (warmRooms.length > WARM_ROOM_LIMIT) { |
| 514 | const evicted = warmRooms[0]; |
| 515 | warmRooms = warmRooms.slice(1); |
| 516 | forgetOpenRoom(evicted); |
| 517 | closeRoom(evicted).catch(() => undefined); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | function forgetOpenRoom(roomId: string): void { |
| 522 | warmRooms = warmRooms.filter((id) => id !== roomId); |
| 523 | const nextReady = { ...openReady }; |
| 524 | delete nextReady[roomId]; |
| 525 | openReady = nextReady; |
| 526 | } |
| 527 | |
| 528 | function scrollToBottom(): void { |
| 529 | if (timelineEl) timelineEl.scrollTop = timelineEl.scrollHeight; |
| 530 | } |
| 531 | |
| 532 | let userScrollUntil = 0; |
| 533 | let draggingScrollbar = false; |
| 534 | |
| 535 | function noteUserScroll(): void { |
| 536 | userScrollUntil = performance.now() + 300; |
| 537 | } |
| 538 | |
| 539 | function onTimelineKey(e: KeyboardEvent): void { |
| 540 | if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) noteUserScroll(); |
| 541 | } |
| 542 | |
| 543 | function onTimelinePointer(e: PointerEvent): void { |
| 544 | if (e.target === timelineEl) draggingScrollbar = true; |
| 545 | } |
| 546 | |
| 547 | function onTimelineScroll(): void { |
| 548 | if (!timelineEl) return; |
| 549 | const gap = timelineEl.scrollHeight - timelineEl.scrollTop - timelineEl.clientHeight; |
| 550 | if (gap < 80) stickToBottom = true; |
| 551 | else if (draggingScrollbar || performance.now() < userScrollUntil) stickToBottom = false; |
| 552 | } |
| 553 | |
| 554 | function pinTimeline(node: HTMLElement) { |
| 555 | const observer = new ResizeObserver(() => { |
| 556 | if (stickToBottom) scrollToBottom(); |
| 557 | }); |
| 558 | observer.observe(node); |
| 559 | if (node.parentElement) observer.observe(node.parentElement); |
| 560 | return { destroy: () => observer.disconnect() }; |
| 561 | } |
| 562 | |
| 563 | $: void trackTimeline($selectedRoomId, items); |
| 564 | async function trackTimeline(roomId: string | null, list: TimelineItem[]): Promise<void> { |
| 565 | if (!roomId || list.length === 0) return; |
| 566 | if (roomId !== $selectedRoomId) return; |
| 567 | await tick(); |
| 568 | if (stickToBottom) scrollToBottom(); |
| 569 | queueReadReceipt(); |
| 570 | } |
| 571 | |
| 572 | function queueReadReceipt(): void { |
| 573 | if (readTimer !== null) window.clearTimeout(readTimer); |
| 574 | readTimer = window.setTimeout(() => { |
| 575 | readTimer = null; |
| 576 | void sendReadReceipt(); |
| 577 | }, 800); |
| 578 | } |
| 579 | |
| 580 | async function sendReadReceipt(): Promise<void> { |
| 581 | const roomId = $selectedRoomId; |
| 582 | if (!roomId || roomId === peeking) return; |
| 583 | const list = $timelines[roomId] ?? []; |
| 584 | for (let i = list.length - 1; i >= 0; i -= 1) { |
| 585 | const entry = list[i]; |
| 586 | if (entry.kind === 'event' && entry.event.event_id) { |
| 587 | const key = `${roomId}:${entry.event.event_id}`; |
| 588 | if (key === lastReadKey) return; |
| 589 | lastReadKey = key; |
| 590 | try { |
| 591 | await markRead(roomId, entry.event.event_id); |
| 592 | } catch { |
| 593 | return; |
| 594 | } |
| 595 | return; |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | function send(): void { |
| 601 | if (editing) { |
| 602 | submitEdit(); |
| 603 | return; |
| 604 | } |
| 605 | const roomId = $selectedRoomId; |
| 606 | const body = composer.trim(); |
| 607 | const attachments = roomId ? (staged[roomId] ?? []) : []; |
| 608 | if (!roomId || (!body && attachments.length === 0)) return; |
| 609 | if (!openReady[roomId]) { |
| 610 | pushBanner('Still opening this room — sending is disabled until the room is ready.'); |
| 611 | return; |
| 612 | } |
| 613 | if (attachments.length > 0 && uploadBusy) return; |
| 614 | const command = parseCommand(body); |
| 615 | if (command && !isKnownCommand(command.name)) { |
| 616 | pushBanner(`Unknown command /${command.name}`); |
| 617 | return; |
| 618 | } |
| 619 | if (command && attachments.length > 0) { |
| 620 | if (command.name !== 'roomavatar' && command.name !== 'globalavatar') { |
| 621 | pushBanner(`/${command.name} doesn't take attachments`); |
| 622 | return; |
| 623 | } |
| 624 | if (command.args || attachments.length !== 1 || !attachments[0].file.type.startsWith('image/')) { |
| 625 | pushBanner(`/${command.name} takes a single attached image`); |
| 626 | return; |
| 627 | } |
| 628 | } |
| 629 | composer = ''; |
| 630 | if (roomId in drafts) delete drafts[roomId]; |
| 631 | stickToBottom = true; |
| 632 | const reply = replyingTo; |
| 633 | replyingTo = null; |
| 634 | const text = unescapeCommand(body); |
| 635 | const mentions = resolveMentions(text, pickedMentions[roomId] ?? []); |
| 636 | pickedMentions = { ...pickedMentions, [roomId]: [] }; |
| 637 | mentionQuery = null; |
| 638 | if (command) { |
| 639 | const image = attachments[0] ?? null; |
| 640 | if (image) { |
| 641 | const { [roomId]: _used, ...rest } = staged; |
| 642 | staged = rest; |
| 643 | } |
| 644 | void execute(roomId, command, reply, mentions, image?.file ?? null).finally(() => { |
| 645 | if (image?.previewUrl) URL.revokeObjectURL(image.previewUrl); |
| 646 | }); |
| 647 | } else if (attachments.length === 0) { |
| 648 | queueSend(roomId, text, reply, mentions, $markdownEnabled); |
| 649 | } else { |
| 650 | const { [roomId]: _sent, ...rest } = staged; |
| 651 | staged = rest; |
| 652 | void sendAttachments(roomId, text, reply, mentions, attachments); |
| 653 | } |
| 654 | if (peeking === roomId) stopPeeking(); |
| 655 | composerEl?.focus(); |
| 656 | } |
| 657 | |
| 658 | function lastOwnEventId(): string | null { |
| 659 | for (let i = items.length - 1; i >= 0; i -= 1) { |
| 660 | const entry = items[i]; |
| 661 | if (entry.kind === 'event' && entry.event.own && entry.event.event_id && entry.event.content.kind !== 'Redacted') { |
| 662 | return entry.event.event_id; |
| 663 | } |
| 664 | } |
| 665 | return null; |
| 666 | } |
| 667 | |
| 668 | async function execute( |
| 669 | roomId: string, |
| 670 | command: ParsedCommand, |
| 671 | reply: ReplyReference | null, |
| 672 | mentions: Mention[], |
| 673 | image: File | null |
| 674 | ): Promise<void> { |
| 675 | const { name, args } = command; |
| 676 | const target = () => { |
| 677 | const found = splitTarget(args, Object.values(people)); |
| 678 | if ('error' in found) throw new Error(found.error); |
| 679 | return found; |
| 680 | }; |
| 681 | const required = (what: string) => { |
| 682 | if (!args) throw new Error(`/${name} needs ${what}`); |
| 683 | return args; |
| 684 | }; |
| 685 | try { |
| 686 | switch (name) { |
| 687 | case 'me': |
| 688 | case 'notice': |
| 689 | await sendMessage(roomId, required('something to say'), null, mentions, $markdownEnabled, name === 'me' ? 'emote' : 'notice'); |
| 690 | break; |
| 691 | case 'msg': { |
| 692 | const { user_id, rest } = target(); |
| 693 | const res = (await runCommand({ op: 'direct', user_id })) as { room_id: string }; |
| 694 | await refreshRooms(); |
| 695 | await selectRoom(res.room_id); |
| 696 | if (rest) queueSend(res.room_id, rest, null, [], $markdownEnabled); |
| 697 | break; |
| 698 | } |
| 699 | case 'join': |
| 700 | await join(required('a room id or alias')); |
| 701 | break; |
| 702 | case 'leave': |
| 703 | await leave(); |
| 704 | break; |
| 705 | case 'invite': |
| 706 | await runCommand({ op: 'invite', room_id: roomId, user_id: target().user_id }); |
| 707 | break; |
| 708 | case 'disinvite': |
| 709 | case 'kick': |
| 710 | case 'ban': |
| 711 | case 'unban': { |
| 712 | const { user_id, rest } = target(); |
| 713 | const op = name === 'disinvite' ? 'kick' : name; |
| 714 | await runCommand({ op, room_id: roomId, user_id, reason: rest || null }); |
| 715 | break; |
| 716 | } |
| 717 | case 'powerlevel': { |
| 718 | const { user_id, rest } = target(); |
| 719 | const level = Number(rest); |
| 720 | if (!rest || !Number.isInteger(level)) throw new Error('/powerlevel needs a whole number after the name'); |
| 721 | await runCommand({ op: 'set_power_level', room_id: roomId, user_id, level }); |
| 722 | break; |
| 723 | } |
| 724 | case 'mute': |
| 725 | case 'unmute': |
| 726 | await runCommand({ op: 'mute', room_id: roomId, user_id: target().user_id, muted: name === 'mute' }); |
| 727 | break; |
| 728 | case 'ignore': |
| 729 | case 'unignore': |
| 730 | await runCommand({ op: name, user_id: target().user_id }); |
| 731 | break; |
| 732 | case 'roomnick': |
| 733 | await runCommand({ op: 'set_room_display_name', room_id: roomId, name: args || null }); |
| 734 | break; |
| 735 | case 'roomavatar': |
| 736 | if (image) { |
| 737 | await uploadRoomAvatar(roomId, image); |
| 738 | } else if (args && !args.startsWith('mxc://')) { |
| 739 | throw new Error('/roomavatar takes an mxc:// link, an attached image, or nothing to drop the override'); |
| 740 | } else { |
| 741 | await runCommand({ op: 'set_room_avatar', room_id: roomId, mxc: args || null }); |
| 742 | } |
| 743 | break; |
| 744 | case 'delete': { |
| 745 | const eventId = reply?.event_id ?? lastOwnEventId(); |
| 746 | if (!eventId) throw new Error('Nothing of yours to delete here'); |
| 747 | await runCommand({ op: 'redact', room_id: roomId, event_id: eventId, reason: args || null }); |
| 748 | break; |
| 749 | } |
| 750 | case 'globalnick': |
| 751 | await runCommand({ op: 'set_display_name', name: required('a name') }); |
| 752 | await loadProfile(); |
| 753 | break; |
| 754 | case 'globalavatar': |
| 755 | if (image) { |
| 756 | await uploadAvatar(image); |
| 757 | await loadProfile(); |
| 758 | } else if (!args) { |
| 759 | avatarInput?.click(); |
| 760 | } else if (args.startsWith('mxc://')) { |
| 761 | await runCommand({ op: 'set_avatar', mxc: args }); |
| 762 | await loadProfile(); |
| 763 | } else { |
| 764 | throw new Error('/globalavatar takes an mxc:// link, or nothing to pick a file'); |
| 765 | } |
| 766 | break; |
| 767 | } |
| 768 | } catch (e) { |
| 769 | pushBanner(e instanceof Error ? e.message : `/${name} failed`); |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | async function onAvatarChosen(): Promise<void> { |
| 774 | const file = avatarInput?.files?.[0]; |
| 775 | if (avatarInput) avatarInput.value = ''; |
| 776 | if (!file) return; |
| 777 | try { |
| 778 | await uploadAvatar(file); |
| 779 | await loadProfile(); |
| 780 | } catch (e) { |
| 781 | pushBanner(e instanceof Error ? e.message : 'Avatar upload failed'); |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | async function sendAttachments( |
| 786 | roomId: string, |
| 787 | body: string, |
| 788 | reply: ReplyReference | null, |
| 789 | mentions: Mention[], |
| 790 | attachments: StagedAttachment[] |
| 791 | ): Promise<void> { |
| 792 | let first = true; |
| 793 | uploadBusy = true; |
| 794 | try { |
| 795 | for (const attachment of attachments) { |
| 796 | uploadName = attachment.file.name || 'attachment'; |
| 797 | try { |
| 798 | if (first) await uploadAttachment(roomId, attachment.file, body || null, reply?.event_id ?? null, mentions, $markdownEnabled); |
| 799 | else await uploadAttachment(roomId, attachment.file); |
| 800 | first = false; |
| 801 | } catch (e) { |
| 802 | pushBanner(e instanceof Error ? e.message : 'Upload failed'); |
| 803 | } |
| 804 | if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl); |
| 805 | } |
| 806 | } finally { |
| 807 | uploadBusy = false; |
| 808 | uploadName = null; |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | function stageFiles(files: File[]): void { |
| 813 | const roomId = $selectedRoomId; |
| 814 | if (!roomId || !openReady[roomId]) return; |
| 815 | const accepted: StagedAttachment[] = []; |
| 816 | for (const file of files) { |
| 817 | if (file.size === 0 || file.size > 20 * 1024 * 1024) { |
| 818 | pushBanner(`${file.name || 'File'} must be between 1 byte and 20 MiB.`); |
| 819 | continue; |
| 820 | } |
| 821 | const previewUrl = file.type.startsWith('image/') ? URL.createObjectURL(file) : null; |
| 822 | accepted.push({ id: nextStagedId++, file, previewUrl }); |
| 823 | } |
| 824 | if (accepted.length === 0) return; |
| 825 | staged = { ...staged, [roomId]: [...(staged[roomId] ?? []), ...accepted] }; |
| 826 | composerEl?.focus(); |
| 827 | } |
| 828 | |
| 829 | function unstage(roomId: string, id: number): void { |
| 830 | const list = staged[roomId] ?? []; |
| 831 | const removed = list.find((a) => a.id === id); |
| 832 | if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl); |
| 833 | staged = { ...staged, [roomId]: list.filter((a) => a.id !== id) }; |
| 834 | } |
| 835 | |
| 836 | function clearAllStaged(): void { |
| 837 | for (const list of Object.values(staged)) { |
| 838 | for (const attachment of list) if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl); |
| 839 | } |
| 840 | staged = {}; |
| 841 | } |
| 842 | |
| 843 | function startEdit(eventId: string, body: string): void { |
| 844 | const roomId = $selectedRoomId; |
| 845 | if (!roomId) return; |
| 846 | const stash = editing ? editing.stash : composer; |
| 847 | editing = { roomId, eventId, original: body, stash }; |
| 848 | const entry = items.find((i) => i.kind === 'event' && i.event.event_id === eventId); |
| 849 | if (entry?.kind === 'event' && entry.event.content.kind === 'Message') { |
| 850 | const existing = mentionsFromHtml(entry.event.content.message.formatted_body); |
| 851 | pickedMentions = { ...pickedMentions, [roomId]: [...(pickedMentions[roomId] ?? []), ...existing] }; |
| 852 | } |
| 853 | composer = body; |
| 854 | replyingTo = null; |
| 855 | composerEl?.focus(); |
| 856 | } |
| 857 | |
| 858 | function cancelEdit(): void { |
| 859 | if (!editing) return; |
| 860 | composer = editing.stash; |
| 861 | editing = null; |
| 862 | composerEl?.focus(); |
| 863 | } |
| 864 | |
| 865 | function submitEdit(): void { |
| 866 | if (!editing) return; |
| 867 | const { roomId, eventId, original } = editing; |
| 868 | const body = composer.trim(); |
| 869 | cancelEdit(); |
| 870 | if (!body || body === original.trim()) return; |
| 871 | editMessage(roomId, eventId, body, resolveMentions(body, pickedMentions[roomId] ?? []), $markdownEnabled).catch((e) => pushBanner(e instanceof Error ? e.message : 'Edit failed')); |
| 872 | } |
| 873 | |
| 874 | function editLastOwn(): boolean { |
| 875 | for (let i = items.length - 1; i >= 0; i -= 1) { |
| 876 | const entry = items[i]; |
| 877 | if (entry.kind !== 'event' || !entry.event.own) continue; |
| 878 | const ev = entry.event; |
| 879 | if (!ev.editable || !ev.event_id || ev.content.kind !== 'Message' || ev.content.message.kind !== 'Text') return false; |
| 880 | startEdit(ev.event_id, ev.content.message.body); |
| 881 | return true; |
| 882 | } |
| 883 | return false; |
| 884 | } |
| 885 | |
| 886 | function startReply(target: ReplyReference): void { |
| 887 | if (editing) cancelEdit(); |
| 888 | replyingTo = target; |
| 889 | composerEl?.focus(); |
| 890 | } |
| 891 | |
| 892 | function jumpTo(eventId: string): void { |
| 893 | const el = timelineEl?.querySelector<HTMLElement>(`[data-event="${CSS.escape(eventId)}"]`); |
| 894 | if (!el) { |
| 895 | pushBanner('The original message is not loaded. Scroll up to load older messages.'); |
| 896 | return; |
| 897 | } |
| 898 | stickToBottom = false; |
| 899 | el.scrollIntoView({ block: 'center', behavior: 'smooth' }); |
| 900 | el.classList.remove('flash'); |
| 901 | void el.offsetWidth; |
| 902 | el.classList.add('flash'); |
| 903 | } |
| 904 | |
| 905 | let typedText = ''; |
| 906 | let typedRoom: string | null = null; |
| 907 | $: trackTypingInput(composer, $selectedRoomId, openReady); |
| 908 | function trackTypingInput(text: string, roomId: string | null, ready: Record<string, boolean>): void { |
| 909 | const edited = roomId === typedRoom && text !== typedText; |
| 910 | typedText = text; |
| 911 | typedRoom = roomId; |
| 912 | if (!roomId || !ready[roomId] || !text.trim()) { |
| 913 | stopTyping(); |
| 914 | } else if (edited && roomId !== peeking) { |
| 915 | notifyTyping(roomId); |
| 916 | } |
| 917 | } |
| 918 | |
| 919 | $: void trackPending($selectedRoomId, pendingItems); |
| 920 | async function trackPending(roomId: string | null, list: PendingMessage[]): Promise<void> { |
| 921 | if (!roomId || list.length === 0) return; |
| 922 | if (roomId !== $selectedRoomId) return; |
| 923 | await tick(); |
| 924 | if (stickToBottom) scrollToBottom(); |
| 925 | } |
| 926 | |
| 927 | function updateMentionQuery(): void { |
| 928 | const roomId = $selectedRoomId; |
| 929 | const next = composerEl && roomId ? mentionQueryAt(composerEl.value, composerEl.selectionStart ?? composerEl.value.length) : null; |
| 930 | if (next && !mentionQuery && roomId && !$membersByRoom[roomId]) void loadMembers(roomId); |
| 931 | if (next?.start !== mentionQuery?.start) mentionIndex = 0; |
| 932 | mentionQuery = next; |
| 933 | } |
| 934 | |
| 935 | async function pickMention(person: Person): Promise<void> { |
| 936 | const roomId = $selectedRoomId; |
| 937 | if (!mentionQuery || !roomId || !composerEl) return; |
| 938 | const caret = composerEl.selectionStart ?? composer.length; |
| 939 | const inserted = `${person.name} `; |
| 940 | composer = composer.slice(0, mentionQuery.start) + inserted + composer.slice(caret); |
| 941 | const at = mentionQuery.start + inserted.length; |
| 942 | pickedMentions = { |
| 943 | ...pickedMentions, |
| 944 | [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }] |
| 945 | }; |
| 946 | mentionQuery = null; |
| 947 | await tick(); |
| 948 | composerEl.focus(); |
| 949 | composerEl.setSelectionRange(at, at); |
| 950 | } |
| 951 | |
| 952 | function onComposerKey(ev: KeyboardEvent): void { |
| 953 | if (mentionQuery && mentionCandidates.length > 0) { |
| 954 | if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') { |
| 955 | ev.preventDefault(); |
| 956 | const step = ev.key === 'ArrowDown' ? 1 : -1; |
| 957 | mentionIndex = (mentionIndex + step + mentionCandidates.length) % mentionCandidates.length; |
| 958 | return; |
| 959 | } |
| 960 | if ((ev.key === 'Enter' && !ev.shiftKey) || ev.key === 'Tab') { |
| 961 | ev.preventDefault(); |
| 962 | void pickMention(mentionCandidates[mentionIndex]); |
| 963 | return; |
| 964 | } |
| 965 | if (ev.key === 'Escape') { |
| 966 | ev.stopPropagation(); |
| 967 | mentionQuery = null; |
| 968 | return; |
| 969 | } |
| 970 | } |
| 971 | if (ev.key === 'Enter' && !ev.shiftKey && !insideOpenFence(composer, composerEl?.selectionStart ?? composer.length)) { |
| 972 | ev.preventDefault(); |
| 973 | send(); |
| 974 | } else if (ev.key === 'Escape' && editing) { |
| 975 | ev.stopPropagation(); |
| 976 | cancelEdit(); |
| 977 | } else if (ev.key === 'Escape' && replyingTo) { |
| 978 | ev.stopPropagation(); |
| 979 | replyingTo = null; |
| 980 | } else if (ev.key === 'ArrowUp' && !composer && !editing && editLastOwn()) { |
| 981 | ev.preventDefault(); |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | function pickFiles(): void { |
| 986 | const roomId = $selectedRoomId; |
| 987 | if (!roomId || !openReady[roomId]) return; |
| 988 | fileInput?.click(); |
| 989 | } |
| 990 | |
| 991 | function onFileChosen(): void { |
| 992 | stageFiles(Array.from(fileInput?.files ?? [])); |
| 993 | if (fileInput) fileInput.value = ''; |
| 994 | } |
| 995 | |
| 996 | function onComposerPaste(ev: ClipboardEvent): void { |
| 997 | const data = ev.clipboardData; |
| 998 | // Office apps put a rendered image next to the copied text, so only take the image when there is no plain text. |
| 999 | if (!data || data.types.includes('text/plain')) return; |
| 1000 | const images = Array.from(data.files).filter((f) => f.type.startsWith('image/')); |
| 1001 | if (images.length === 0) return; |
| 1002 | ev.preventDefault(); |
| 1003 | stageFiles(images); |
| 1004 | } |
| 1005 | |
| 1006 | async function react(eventId: string, key: string, shortcode?: string): Promise<void> { |
| 1007 | const roomId = $selectedRoomId; |
| 1008 | if (!roomId || !eventId || reacting) return; |
| 1009 | reacting = true; |
| 1010 | try { |
| 1011 | await reactToMessage(roomId, eventId, key, shortcode); |
| 1012 | } catch (e) { |
| 1013 | pushBanner(e instanceof Error ? e.message : 'Reaction failed'); |
| 1014 | } finally { |
| 1015 | reacting = false; |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | function previewLoader(roomId: string): (url: string) => void { |
| 1020 | return (url) => requestLinkPreview(roomId, url); |
| 1021 | } |
| 1022 | |
| 1023 | async function changeEncryptedPreviews(enabled: boolean): Promise<void> { |
| 1024 | try { |
| 1025 | await saveUrlPreviewSettings({ encrypted_rooms: enabled }); |
| 1026 | } catch (e) { |
| 1027 | pushBanner(e instanceof Error ? e.message : 'Could not save link preview setting'); |
| 1028 | } |
| 1029 | } |
| 1030 | |
| 1031 | async function changeQuickReactions(list: QuickReaction[]): Promise<void> { |
| 1032 | try { |
| 1033 | await saveQuickReactions(list); |
| 1034 | } catch (e) { |
| 1035 | pushBanner(e instanceof Error ? e.message : 'Could not save quick reactions'); |
| 1036 | } |
| 1037 | } |
| 1038 | |
| 1039 | async function paginate(): Promise<void> { |
| 1040 | const roomId = $selectedRoomId; |
| 1041 | if (!roomId || paginateBusy) return; |
| 1042 | paginateBusy = true; |
| 1043 | try { |
| 1044 | await paginateRoom(roomId); |
| 1045 | } catch (e) { |
| 1046 | pushBanner(e instanceof Error ? e.message : 'Loading older messages failed'); |
| 1047 | } finally { |
| 1048 | paginateBusy = false; |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | async function loadMembers(roomId: string): Promise<void> { |
| 1053 | if (membersFor === roomId && $membersLoading) return; |
| 1054 | membersFor = roomId; |
| 1055 | membersLoading.set(true); |
| 1056 | try { |
| 1057 | const res = await getMembers(roomId); |
| 1058 | membersByRoom.update((all) => ({ ...all, [roomId]: res.members })); |
| 1059 | avatarByUser = { ...avatarByUser, ...avatarMap(res.members) }; |
| 1060 | } catch (e) { |
| 1061 | pushBanner(e instanceof Error ? e.message : 'Could not load members'); |
| 1062 | } finally { |
| 1063 | if (membersFor === roomId) membersLoading.set(false); |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | function avatarMap(list: MemberSummary[]): Record<string, string | null> { |
| 1068 | const next: Record<string, string | null> = {}; |
| 1069 | for (const member of list) next[member.user_id] = member.avatar; |
| 1070 | return next; |
| 1071 | } |
| 1072 | |
| 1073 | function peopleIn(list: TimelineItem[], roster: MemberSummary[]): Record<string, Person> { |
| 1074 | const out: Record<string, Person> = {}; |
| 1075 | for (const item of list) { |
| 1076 | if (item.kind !== 'event') continue; |
| 1077 | const s = item.event.sender; |
| 1078 | out[s.user_id] = { user_id: s.user_id, name: senderLabel(s), avatar: s.avatar }; |
| 1079 | } |
| 1080 | for (const m of roster) out[m.user_id] = { user_id: m.user_id, name: m.name, avatar: m.avatar }; |
| 1081 | return out; |
| 1082 | } |
| 1083 | |
| 1084 | function senderAvatarFor(userId: string): string | null { |
| 1085 | return avatarByUser[userId] ?? null; |
| 1086 | } |
| 1087 | |
| 1088 | function toggleMembers(): void { |
| 1089 | membersOpen = !membersOpen; |
| 1090 | if (membersOpen && $selectedRoomId) void loadMembers($selectedRoomId); |
| 1091 | } |
| 1092 | |
| 1093 | async function join(target: string): Promise<void> { |
| 1094 | const room = target.trim(); |
| 1095 | if (!room || joinBusy) return; |
| 1096 | joinBusy = true; |
| 1097 | try { |
| 1098 | const res = await joinRoom(room); |
| 1099 | joinTarget = ''; |
| 1100 | dialog = null; |
| 1101 | await refreshRooms(); |
| 1102 | await selectRoom(res.room_id); |
| 1103 | } catch (e) { |
| 1104 | pushBanner(e instanceof Error ? e.message : 'Join failed'); |
| 1105 | } finally { |
| 1106 | joinBusy = false; |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | async function create(): Promise<void> { |
| 1111 | const name = createName.trim(); |
| 1112 | if (!name || createBusy) return; |
| 1113 | createBusy = true; |
| 1114 | try { |
| 1115 | const res = await createRoom(name, createTopic.trim() || undefined); |
| 1116 | createName = ''; |
| 1117 | createTopic = ''; |
| 1118 | dialog = null; |
| 1119 | await refreshRooms(); |
| 1120 | await selectRoom(res.room_id); |
| 1121 | } catch (e) { |
| 1122 | pushBanner(e instanceof Error ? e.message : 'Create room failed'); |
| 1123 | } finally { |
| 1124 | createBusy = false; |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | async function leave(roomId: string | null = $selectedRoomId): Promise<void> { |
| 1129 | if (!roomId || leaveBusy) return; |
| 1130 | leaveBusy = true; |
| 1131 | stopTyping(); |
| 1132 | try { |
| 1133 | await leaveRoom(roomId); |
| 1134 | if ($selectedRoomId === roomId) selectedRoomId.set(null); |
| 1135 | if (warmRooms.includes(roomId)) { |
| 1136 | forgetOpenRoom(roomId); |
| 1137 | closeRoom(roomId).catch(() => undefined); |
| 1138 | } |
| 1139 | await refreshRooms(); |
| 1140 | } catch (e) { |
| 1141 | pushBanner(e instanceof Error ? e.message : 'Leave failed'); |
| 1142 | } finally { |
| 1143 | leaveBusy = false; |
| 1144 | } |
| 1145 | } |
| 1146 | |
| 1147 | function connectionClass(state: string): string { |
| 1148 | if (state === 'online') return 'dot-online'; |
| 1149 | if (state === 'connecting' || state === 'reconnecting') return 'dot-busy'; |
| 1150 | return 'dot-off'; |
| 1151 | } |
| 1152 | |
| 1153 | let dragSpaceId: string | null = null; |
| 1154 | let dropTarget: { id: string; after: boolean } | null = null; |
| 1155 | let menu: { items: MenuItem[]; x: number; y: number } | null = null; |
| 1156 | let userCard: { userId: string; x: number; y: number; confirm: 'kick' | 'ban' | null } | null = null; |
| 1157 | let levelsByRoom: Record<string, PowerLevels | null> = {}; |
| 1158 | let peeking: string | null = null; |
| 1159 | |
| 1160 | $: roomLevels = $selectedRoomId ? (levelsByRoom[$selectedRoomId] ?? null) : null; |
| 1161 | |
| 1162 | function personFor(userId: string): Person { |
| 1163 | return people[userId] ?? { user_id: userId, name: userId, avatar: avatarByUser[userId] ?? null }; |
| 1164 | } |
| 1165 | |
| 1166 | function memberFor(userId: string): MemberSummary | null { |
| 1167 | return members.find((m) => m.user_id === userId) ?? null; |
| 1168 | } |
| 1169 | |
| 1170 | async function loadLevels(roomId: string): Promise<void> { |
| 1171 | try { |
| 1172 | const levels = parsePowerLevels(await runCommand({ op: 'power_levels', room_id: roomId })); |
| 1173 | levelsByRoom = { ...levelsByRoom, [roomId]: levels }; |
| 1174 | } catch { |
| 1175 | levelsByRoom = { ...levelsByRoom, [roomId]: levelsByRoom[roomId] ?? null }; |
| 1176 | } |
| 1177 | } |
| 1178 | |
| 1179 | async function openUser(userId: string, x: number, y: number, asMenu: boolean): Promise<void> { |
| 1180 | const roomId = $selectedRoomId; |
| 1181 | if (roomId && !(roomId in levelsByRoom)) await loadLevels(roomId); |
| 1182 | else if (roomId) void loadLevels(roomId); |
| 1183 | if (asMenu) menu = { items: userMenuItems(userId, x, y), x, y }; |
| 1184 | else userCard = { userId, x, y, confirm: null }; |
| 1185 | } |
| 1186 | |
| 1187 | function copyText(text: string): void { |
| 1188 | navigator.clipboard.writeText(text).catch(() => pushBanner('Could not copy to the clipboard')); |
| 1189 | } |
| 1190 | |
| 1191 | function userMenuItems(userId: string, x: number, y: number): MenuItem[] { |
| 1192 | const own = userId === $sessionUser; |
| 1193 | const member = memberFor(userId); |
| 1194 | const items: MenuItem[] = []; |
| 1195 | if (!own) items.push({ label: 'Message', action: () => void userAction(userId, { kind: 'message' }) }); |
| 1196 | items.push({ label: 'Mention', action: () => void userAction(userId, { kind: 'mention' }) }); |
| 1197 | items.push({ label: 'Copy user ID', action: () => copyText(userId) }); |
| 1198 | if (roomLevels && $sessionUser) { |
| 1199 | const can = allowed(roomLevels, $sessionUser, userId); |
| 1200 | const banned = member?.membership === 'Ban'; |
| 1201 | if (can.setLevel && !own) { |
| 1202 | const muted = isMuted(roomLevels, userId); |
| 1203 | items.push({ label: muted ? 'Unmute' : 'Mute', action: () => void userAction(userId, { kind: muted ? 'unmute' : 'mute' }) }); |
| 1204 | } |
| 1205 | if (can.kick && !banned) items.push({ label: 'Kick…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'kick' }) }); |
| 1206 | if (can.ban && banned) items.push({ label: 'Unban', action: () => void userAction(userId, { kind: 'unban' }) }); |
| 1207 | if (can.ban && !banned) items.push({ label: 'Ban…', danger: true, action: () => (userCard = { userId, x, y, confirm: 'ban' }) }); |
| 1208 | if (can.setLevel) items.push({ label: 'Power level…', action: () => (userCard = { userId, x, y, confirm: null }) }); |
| 1209 | } |
| 1210 | if (!own) { |
| 1211 | const kind = member?.ignored ? 'unignore' : 'ignore'; |
| 1212 | items.push({ label: member?.ignored ? 'Unignore' : 'Ignore', action: () => void userAction(userId, { kind }) }); |
| 1213 | } |
| 1214 | return items; |
| 1215 | } |
| 1216 | |
| 1217 | async function insertMention(person: Person): Promise<void> { |
| 1218 | const roomId = $selectedRoomId; |
| 1219 | if (!roomId) return; |
| 1220 | const lead = composer && !/\s$/.test(composer) ? ' ' : ''; |
| 1221 | composer = `${composer}${lead}${person.name} `; |
| 1222 | pickedMentions = { |
| 1223 | ...pickedMentions, |
| 1224 | [roomId]: [...(pickedMentions[roomId] ?? []), { user_id: person.user_id, text: person.name }] |
| 1225 | }; |
| 1226 | await tick(); |
| 1227 | composerEl?.focus(); |
| 1228 | composerEl?.setSelectionRange(composer.length, composer.length); |
| 1229 | } |
| 1230 | |
| 1231 | async function userAction(userId: string, action: UserAction): Promise<void> { |
| 1232 | const roomId = $selectedRoomId; |
| 1233 | try { |
| 1234 | switch (action.kind) { |
| 1235 | case 'message': { |
| 1236 | const res = (await runCommand({ op: 'direct', user_id: userId })) as { room_id: string }; |
| 1237 | await refreshRooms(); |
| 1238 | await selectRoom(res.room_id); |
| 1239 | return; |
| 1240 | } |
| 1241 | case 'mention': |
| 1242 | await insertMention(personFor(userId)); |
| 1243 | return; |
| 1244 | case 'ignore': |
| 1245 | case 'unignore': |
| 1246 | await runCommand({ op: action.kind, user_id: userId }); |
| 1247 | if (roomId) void loadMembers(roomId); |
| 1248 | return; |
| 1249 | } |
| 1250 | if (!roomId) return; |
| 1251 | switch (action.kind) { |
| 1252 | case 'kick': |
| 1253 | case 'ban': |
| 1254 | await runCommand({ op: action.kind, room_id: roomId, user_id: userId, reason: action.reason }); |
| 1255 | break; |
| 1256 | case 'unban': |
| 1257 | await runCommand({ op: 'unban', room_id: roomId, user_id: userId, reason: null }); |
| 1258 | break; |
| 1259 | case 'mute': |
| 1260 | case 'unmute': |
| 1261 | await runCommand({ op: 'mute', room_id: roomId, user_id: userId, muted: action.kind === 'mute' }); |
| 1262 | break; |
| 1263 | case 'power': |
| 1264 | await runCommand({ op: 'set_power_level', room_id: roomId, user_id: userId, level: action.level }); |
| 1265 | break; |
| 1266 | } |
| 1267 | void loadLevels(roomId); |
| 1268 | void loadMembers(roomId); |
| 1269 | } catch (e) { |
| 1270 | pushBanner(e instanceof Error ? e.message : 'That action failed'); |
| 1271 | } |
| 1272 | } |
| 1273 | |
| 1274 | function roomMenuItems(room: RoomSummary): MenuItem[] { |
| 1275 | const items: MenuItem[] = room.space |
| 1276 | ? [{ label: 'Open', action: () => void selectSpace(room.room_id) }] |
| 1277 | : [ |
| 1278 | { label: 'Open', action: () => void selectRoom(room.room_id) }, |
| 1279 | { label: 'Peek', action: () => void selectRoom(room.room_id, true) } |
| 1280 | ]; |
| 1281 | items.push({ label: room.favourite ? 'Unpin' : room.space ? 'Pin to top' : 'Pin', action: () => void togglePin(room) }); |
| 1282 | items.push({ label: 'Copy link', action: () => copyText(`https://matrix.to/#/${room.canonical_alias ?? room.room_id}`) }); |
| 1283 | items.push({ label: 'Copy room ID', action: () => copyText(room.room_id) }); |
| 1284 | if (room.membership === 'Joined') items.push({ label: 'Leave', danger: true, action: () => void leave(room.room_id) }); |
| 1285 | return items; |
| 1286 | } |
| 1287 | |
| 1288 | function openRoomMenu(ev: MouseEvent, room: RoomSummary): void { |
| 1289 | menu = { items: roomMenuItems(room), x: ev.clientX, y: ev.clientY }; |
| 1290 | } |
| 1291 | |
| 1292 | function roomName(roomId: string): string { |
| 1293 | return $rooms.find((r) => r.room_id === roomId)?.name ?? roomId; |
| 1294 | } |
| 1295 | |
| 1296 | async function sendSticker(roomId: string, pack: ImagePack, image: PackImage): Promise<void> { |
| 1297 | stickersOpen = false; |
| 1298 | stickToBottom = true; |
| 1299 | try { |
| 1300 | await runCommand({ op: 'send_sticker', room_id: roomId, pack_id: pack.id, shortcode: image.shortcode }); |
| 1301 | if (peeking === roomId) stopPeeking(); |
| 1302 | } catch (e) { |
| 1303 | pushBanner(e instanceof Error ? e.message : 'Could not send the sticker'); |
| 1304 | } |
| 1305 | } |
| 1306 | |
| 1307 | async function runClone(request: CommandRequest, failure: string): Promise<void> { |
| 1308 | try { |
| 1309 | const res = (await runCommand(request)) as { skipped?: string[] } | undefined; |
| 1310 | if (res?.skipped?.length) pushBanner(`Couldn't copy ${res.skipped.map((s) => `:${s}:`).join(', ')}`); |
| 1311 | } catch (e) { |
| 1312 | pushBanner(e instanceof Error ? e.message : failure); |
| 1313 | } |
| 1314 | } |
| 1315 | |
| 1316 | function openCloneImageMenu(pack: ImagePack, image: PackImage, x: number, y: number): void { |
| 1317 | const items = editableChoices($imagePacks, roomName) |
| 1318 | .filter((c) => c.pack?.id !== pack.id) |
| 1319 | .map((choice) => ({ |
| 1320 | label: `Clone to ${choice.label}`, |
| 1321 | action: () => |
| 1322 | void runClone({ op: 'clone_pack_image', from_pack: pack.id, shortcode: image.shortcode, to: choice.target }, 'Could not clone the sticker') |
| 1323 | })); |
| 1324 | menu = { items, x, y }; |
| 1325 | } |
| 1326 | |
| 1327 | function openClonePackMenu(pack: ImagePack, x: number, y: number): void { |
| 1328 | const packRooms = $rooms.filter((r) => r.can_edit_packs && r.membership === 'Joined'); |
| 1329 | const items = clonePackDestinations(pack, packRooms, roomName).map((d) => ({ |
| 1330 | label: d.label, |
| 1331 | action: () => void runClone({ op: 'clone_pack', from_pack: pack.id, to: d.target, display_name: d.display_name }, 'Could not clone the pack') |
| 1332 | })); |
| 1333 | menu = { items, x, y }; |
| 1334 | } |
| 1335 | |
| 1336 | function openCloneStickerMenu(eventId: string, body: string, x: number, y: number): void { |
| 1337 | const roomId = $selectedRoomId; |
| 1338 | if (!roomId) return; |
| 1339 | const items = editableChoices($imagePacks, roomName).map((choice) => ({ |
| 1340 | label: `Clone to ${choice.label}`, |
| 1341 | action: () => { |
| 1342 | const taken = new Set(choice.pack?.images.map((i) => i.shortcode) ?? []); |
| 1343 | void runClone( |
| 1344 | { op: 'clone_sticker', room_id: roomId, event_id: eventId, to: choice.target, shortcode: shortcodeFor(body || 'sticker', taken) }, |
| 1345 | 'Could not clone the sticker' |
| 1346 | ); |
| 1347 | } |
| 1348 | })); |
| 1349 | menu = { items, x, y }; |
| 1350 | } |
| 1351 | |
| 1352 | function stopPeeking(): void { |
| 1353 | peeking = null; |
| 1354 | queueReadReceipt(); |
| 1355 | } |
| 1356 | |
| 1357 | async function togglePin(room: RoomSummary): Promise<void> { |
| 1358 | try { |
| 1359 | await runCommand({ op: 'set_favourite', room_id: room.room_id, favourite: !room.favourite }); |
| 1360 | } catch (e) { |
| 1361 | pushBanner(e instanceof Error ? e.message : 'Could not change the pin'); |
| 1362 | } |
| 1363 | } |
| 1364 | |
| 1365 | function startRailDrag(ev: DragEvent, id: string): void { |
| 1366 | dragSpaceId = id; |
| 1367 | if (ev.dataTransfer) { |
| 1368 | ev.dataTransfer.effectAllowed = 'move'; |
| 1369 | ev.dataTransfer.setData('text/plain', id); |
| 1370 | } |
| 1371 | } |
| 1372 | |
| 1373 | function overRailSpace(ev: DragEvent, space: RoomSummary): void { |
| 1374 | const dragged = orderedRail.find((s) => s.room_id === dragSpaceId); |
| 1375 | if (!dragged || dragged.room_id === space.room_id || dragged.favourite !== space.favourite) return; |
| 1376 | ev.preventDefault(); |
| 1377 | const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect(); |
| 1378 | dropTarget = { id: space.room_id, after: ev.clientY > rect.top + rect.height / 2 }; |
| 1379 | } |
| 1380 | |
| 1381 | async function dropRailSpace(): Promise<void> { |
| 1382 | const moved = dragSpaceId; |
| 1383 | const target = dropTarget; |
| 1384 | dragSpaceId = null; |
| 1385 | dropTarget = null; |
| 1386 | if (!moved || !target) return; |
| 1387 | const ids = orderedRail.map((s) => s.room_id); |
| 1388 | const before = target.after ? (ids[ids.indexOf(target.id) + 1] ?? null) : target.id; |
| 1389 | const order = moveBefore(ids, moved, before === moved ? null : before); |
| 1390 | if (order.join() === ids.join()) return; |
| 1391 | railOverride = order; |
| 1392 | try { |
| 1393 | await runCommand({ op: 'reorder_spaces', order }); |
| 1394 | } catch (e) { |
| 1395 | railOverride = null; |
| 1396 | pushBanner(e instanceof Error ? e.message : 'Could not reorder spaces'); |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | let roomMenuOpen = false; |
| 1401 | let roomMenuEl: HTMLDivElement | null = null; |
| 1402 | |
| 1403 | function roomMenuAction(action: () => void): void { |
| 1404 | roomMenuOpen = false; |
| 1405 | action(); |
| 1406 | } |
| 1407 | |
| 1408 | function closeRoomMenuOutside(ev: PointerEvent): void { |
| 1409 | if (roomMenuOpen && !roomMenuEl?.contains(ev.target as Node)) roomMenuOpen = false; |
| 1410 | } |
| 1411 | |
| 1412 | function onKeydown(ev: KeyboardEvent): void { |
| 1413 | if (ev.key === 'Escape') { |
| 1414 | if (roomMenuOpen) roomMenuOpen = false; |
| 1415 | else if (dialog) dialog = null; |
| 1416 | else if (membersOpen && window.innerWidth < 1100) membersOpen = false; |
| 1417 | else if (sidebarOpen) sidebarOpen = false; |
| 1418 | } |
| 1419 | } |
| 1420 | </script> |
| 1421 | |
| 1422 | <svelte:window |
| 1423 | on:keydown={onKeydown} |
| 1424 | on:pointerdown={closeRoomMenuOutside} |
| 1425 | on:pointerup={() => (draggingScrollbar = false)} |
| 1426 | /> |
| 1427 | |
| 1428 | {#if !booted} |
| 1429 | <div class="splash" role="status" aria-label="Loading Malice"> |
| 1430 | <div class="splash-mark" aria-hidden="true">M</div> |
| 1431 | <p>Loading Malice…</p> |
| 1432 | </div> |
| 1433 | {:else if $blocked} |
| 1434 | <div class="splash" role="status" aria-label="Malice is open in another tab"> |
| 1435 | <div class="splash-mark" aria-hidden="true">M</div> |
| 1436 | <p>Malice is open in another tab. Close this tab or use that one instead.</p> |
| 1437 | </div> |
| 1438 | {:else if $sessionUser == null} |
| 1439 | <LoginPanel softLogout={$softLogout} on:done={(ev) => afterLogin(ev.detail)} /> |
| 1440 | {:else} |
| 1441 | <div |
| 1442 | class="app" |
| 1443 | class:nav-folded={$navFolded && selectedRoom} |
| 1444 | class:rail-folded={$railFolded && selectedRoom} |
| 1445 | class:members-open={selectedRoom && membersOpen} |
| 1446 | style:--msg-gap={`${$messageSpacing}px`} |
| 1447 | style:--msg-line-height={$lineHeight} |
| 1448 | > |
| 1449 | <nav class="rail" aria-label="Servers and spaces"> |
| 1450 | <button |
| 1451 | type="button" |
| 1452 | class="rail-btn" |
| 1453 | class:active={selectedSpaceId === null} |
| 1454 | title="Home — all channels" |
| 1455 | aria-label="Home — all channels" |
| 1456 | aria-pressed={selectedSpaceId === null} |
| 1457 | on:click={() => void selectHome()} |
| 1458 | > |
| 1459 | <span aria-hidden="true">⌂</span> |
| 1460 | </button> |
| 1461 | {#each [pinnedRail, otherRail] as group} |
| 1462 | {#if group.length > 0} |
| 1463 | <div class="rail-sep" aria-hidden="true"></div> |
| 1464 | {/if} |
| 1465 | {#each group as space (space.room_id)} |
| 1466 | <button |
| 1467 | type="button" |
| 1468 | class="rail-btn rail-space" |
| 1469 | class:active={railSelected === space.room_id} |
| 1470 | class:drop-before={dropTarget?.id === space.room_id && !dropTarget.after} |
| 1471 | class:drop-after={dropTarget?.id === space.room_id && dropTarget.after} |
| 1472 | class:pinned={space.favourite} |
| 1473 | title={space.name} |
| 1474 | aria-label={`Show channels in space ${space.name}`} |
| 1475 | aria-pressed={selectedSpaceId === space.room_id} |
| 1476 | draggable="true" |
| 1477 | on:click={() => void selectSpace(space.room_id)} |
| 1478 | on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, space)} |
| 1479 | on:dragstart={(ev) => startRailDrag(ev, space.room_id)} |
| 1480 | on:dragover={(ev) => overRailSpace(ev, space)} |
| 1481 | on:dragleave={() => dropTarget?.id === space.room_id && (dropTarget = null)} |
| 1482 | on:drop|preventDefault={() => void dropRailSpace()} |
| 1483 | on:dragend={() => ((dragSpaceId = null), (dropTarget = null))} |
| 1484 | > |
| 1485 | <MxcAvatar mxc={space.avatar} label={space.name} size={44} shape="rounded" /> |
| 1486 | </button> |
| 1487 | {/each} |
| 1488 | {/each} |
| 1489 | <button |
| 1490 | type="button" |
| 1491 | class="rail-btn rail-add" |
| 1492 | aria-label="Join or create a room" |
| 1493 | on:click={() => { |
| 1494 | dialog = 'join'; |
| 1495 | }} |
| 1496 | > |
| 1497 | <span aria-hidden="true">+</span> |
| 1498 | </button> |
| 1499 | </nav> |
| 1500 | |
| 1501 | {#if menu} |
| 1502 | <ContextMenu items={menu.items} x={menu.x} y={menu.y} onClose={() => (menu = null)} /> |
| 1503 | {/if} |
| 1504 | {#if userCard} |
| 1505 | {#key userCard} |
| 1506 | {@const cardUser = userCard.userId} |
| 1507 | <UserCard |
| 1508 | person={personFor(cardUser)} |
| 1509 | member={memberFor(cardUser)} |
| 1510 | levels={roomLevels} |
| 1511 | self={$sessionUser ?? null} |
| 1512 | x={userCard.x} |
| 1513 | y={userCard.y} |
| 1514 | confirm={userCard.confirm} |
| 1515 | onAction={(action) => void userAction(cardUser, action)} |
| 1516 | onClose={() => (userCard = null)} |
| 1517 | /> |
| 1518 | {/key} |
| 1519 | {/if} |
| 1520 | |
| 1521 | <aside class="sidebar" class:open={sidebarOpen} aria-label="Rooms"> |
| 1522 | <div class="side-search"> |
| 1523 | <label class="visually-hidden" for="room-search">Search rooms</label> |
| 1524 | <input |
| 1525 | id="room-search" |
| 1526 | type="search" |
| 1527 | placeholder="Search rooms" |
| 1528 | bind:value={search} |
| 1529 | autocomplete="off" |
| 1530 | /> |
| 1531 | <button |
| 1532 | type="button" |
| 1533 | class="icon-btn" |
| 1534 | title="Refresh rooms" |
| 1535 | aria-label="Refresh rooms" |
| 1536 | disabled={roomsLoading} |
| 1537 | on:click={() => void refreshRooms()} |
| 1538 | > |
| 1539 | <span aria-hidden="true">⟳</span> |
| 1540 | </button> |
| 1541 | </div> |
| 1542 | <div class="side-scroll"> |
| 1543 | {#if selectedSpace} |
| 1544 | <div class="space-context"> |
| 1545 | <MxcAvatar mxc={selectedSpace.avatar} label={selectedSpace.name} size={28} shape="rounded" /> |
| 1546 | <div class="space-context-text"> |
| 1547 | <strong>{selectedSpace.name}</strong> |
| 1548 | </div> |
| 1549 | {#if spaceParents.has(selectedSpace.room_id)} |
| 1550 | {@const parentId = spaceParents.get(selectedSpace.room_id) ?? ''} |
| 1551 | <button |
| 1552 | type="button" |
| 1553 | class="icon-btn" |
| 1554 | title="Up to the parent space" |
| 1555 | aria-label="Up to the parent space" |
| 1556 | on:click={() => void selectSpace(parentId)} |
| 1557 | > |
| 1558 | <span aria-hidden="true">↑</span> |
| 1559 | </button> |
| 1560 | {/if} |
| 1561 | </div> |
| 1562 | {:else} |
| 1563 | <div class="space-context"> |
| 1564 | <div class="space-context-text"> |
| 1565 | <strong>Home</strong> |
| 1566 | </div> |
| 1567 | </div> |
| 1568 | {/if} |
| 1569 | {#if roomsLoading && $rooms.length === 0} |
| 1570 | <p class="side-note">Loading rooms…</p> |
| 1571 | {:else if $rooms.length === 0} |
| 1572 | <p class="side-note">No rooms yet</p> |
| 1573 | <div class="side-cta"> |
| 1574 | <button type="button" on:click={() => (dialog = 'join')}>Join a room</button> |
| 1575 | <button type="button" on:click={() => (dialog = 'create')}>Create one</button> |
| 1576 | </div> |
| 1577 | {:else} |
| 1578 | {#if selectedSpaceId && spaceChildrenLoading} |
| 1579 | <p class="side-note">Loading channels…</p> |
| 1580 | {:else if selectedSpaceId && spaceChildrenError} |
| 1581 | <p class="side-note" role="alert">{spaceChildrenError}</p> |
| 1582 | <div class="side-cta"> |
| 1583 | <button type="button" on:click={() => selectedSpaceId && void selectSpace(selectedSpaceId)}>Retry</button> |
| 1584 | <button type="button" on:click={() => void selectHome()}>Back to Home</button> |
| 1585 | </div> |
| 1586 | {:else if selectedSpaceId && spaceChildIds && channelRooms.length === 0} |
| 1587 | <p class="side-note">No channels</p> |
| 1588 | <div class="side-cta"> |
| 1589 | <button type="button" on:click={() => void selectHome()}>Back to Home</button> |
| 1590 | </div> |
| 1591 | {:else} |
| 1592 | {#if invites.length > 0 && !selectedSpaceId} |
| 1593 | <h2 class="side-h">Invites</h2> |
| 1594 | <ul class="room-list"> |
| 1595 | {#each invites as room (room.room_id)} |
| 1596 | <li> |
| 1597 | <button |
| 1598 | type="button" |
| 1599 | class="room-row" |
| 1600 | class:active={$selectedRoomId === room.room_id} |
| 1601 | on:click={() => void selectRoom(room.room_id)} |
| 1602 | on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)} |
| 1603 | > |
| 1604 | <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" /> |
| 1605 | <span class="room-name">{room.name}</span> |
| 1606 | <span |
| 1607 | class="invite-join" |
| 1608 | role="button" |
| 1609 | tabindex="0" |
| 1610 | aria-label={`Join ${room.name}`} |
| 1611 | on:click|stopPropagation={() => void join(room.room_id)} |
| 1612 | on:keydown|stopPropagation={(ev) => { |
| 1613 | if (ev.key === 'Enter' || ev.key === ' ') { |
| 1614 | ev.preventDefault(); |
| 1615 | void join(room.room_id); |
| 1616 | } |
| 1617 | }} |
| 1618 | > |
| 1619 | Join |
| 1620 | </span> |
| 1621 | </button> |
| 1622 | </li> |
| 1623 | {/each} |
| 1624 | </ul> |
| 1625 | {/if} |
| 1626 | |
| 1627 | {#if directRooms.length > 0} |
| 1628 | <h2 class="side-h">Direct messages</h2> |
| 1629 | <ul class="room-list"> |
| 1630 | {#each directRooms as room (room.room_id)} |
| 1631 | <li class="room-item"> |
| 1632 | <button |
| 1633 | type="button" |
| 1634 | class="room-row" |
| 1635 | class:active={$selectedRoomId === room.room_id} |
| 1636 | aria-current={$selectedRoomId === room.room_id ? 'true' : undefined} |
| 1637 | on:click={() => void selectRoom(room.room_id)} |
| 1638 | on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)} |
| 1639 | > |
| 1640 | <MxcAvatar mxc={room.avatar} label={room.name} size={26} /> |
| 1641 | <span class="room-name">{room.name}</span> |
| 1642 | {#if roomUnread(room) > 0} |
| 1643 | <span |
| 1644 | class="badge" |
| 1645 | class:mention={room.unread_mentions > 0} |
| 1646 | aria-label={`${roomUnread(room)} unread`} |
| 1647 | > |
| 1648 | {roomUnread(room) > 99 ? '99+' : roomUnread(room)} |
| 1649 | </span> |
| 1650 | {/if} |
| 1651 | </button> |
| 1652 | <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} /> |
| 1653 | </li> |
| 1654 | {/each} |
| 1655 | </ul> |
| 1656 | {/if} |
| 1657 | |
| 1658 | {#if groupRooms.length > 0} |
| 1659 | <h2 class="side-h">{selectedSpace ? 'Channels' : 'Rooms'}</h2> |
| 1660 | <ul class="room-list"> |
| 1661 | {#each groupRooms as room (room.room_id)} |
| 1662 | <li class="room-item"> |
| 1663 | <button |
| 1664 | type="button" |
| 1665 | class="room-row" |
| 1666 | class:active={$selectedRoomId === room.room_id} |
| 1667 | aria-current={$selectedRoomId === room.room_id ? 'true' : undefined} |
| 1668 | on:click={() => void selectRoom(room.room_id)} |
| 1669 | on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)} |
| 1670 | > |
| 1671 | <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" /> |
| 1672 | <span class="room-hash" aria-hidden="true">#</span> |
| 1673 | <span class="room-name">{room.name}</span> |
| 1674 | {#if roomUnread(room) > 0} |
| 1675 | <span |
| 1676 | class="badge" |
| 1677 | class:mention={room.unread_mentions > 0} |
| 1678 | aria-label={`${roomUnread(room)} unread`} |
| 1679 | > |
| 1680 | {roomUnread(room) > 99 ? '99+' : roomUnread(room)} |
| 1681 | </span> |
| 1682 | {/if} |
| 1683 | </button> |
| 1684 | <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} /> |
| 1685 | </li> |
| 1686 | {/each} |
| 1687 | </ul> |
| 1688 | {/if} |
| 1689 | |
| 1690 | {#if spaceList.length > 0} |
| 1691 | <h2 class="side-h">{selectedSpace ? 'Subspaces' : 'Spaces'}</h2> |
| 1692 | <ul class="room-list"> |
| 1693 | {#each spaceList as room (room.room_id)} |
| 1694 | <li class="room-item"> |
| 1695 | <button |
| 1696 | type="button" |
| 1697 | class="room-row" |
| 1698 | class:active={selectedSpaceId === room.room_id} |
| 1699 | aria-label={`Show channels in space ${room.name}`} |
| 1700 | on:click={() => void selectSpace(room.room_id)} |
| 1701 | on:contextmenu|preventDefault={(ev) => openRoomMenu(ev, room)} |
| 1702 | > |
| 1703 | <MxcAvatar mxc={room.avatar} label={room.name} size={26} shape="rounded" /> |
| 1704 | <span class="room-hash" aria-hidden="true">◇</span> |
| 1705 | <span class="room-name">{room.name}</span> |
| 1706 | </button> |
| 1707 | <PinButton pinned={room.favourite} label={room.name} onToggle={() => void togglePin(room)} /> |
| 1708 | </li> |
| 1709 | {/each} |
| 1710 | </ul> |
| 1711 | {/if} |
| 1712 | |
| 1713 | {#if query && visibleRooms.length === 0} |
| 1714 | <p class="side-note">No rooms match “{search.trim()}”.</p> |
| 1715 | {/if} |
| 1716 | {/if} |
| 1717 | {/if} |
| 1718 | </div> |
| 1719 | |
| 1720 | <div class="side-footer"> |
| 1721 | <div class="me" title={$sessionUser}> |
| 1722 | {#if profileMxc} |
| 1723 | <MxcAvatar mxc={profileMxc} label={profile?.display_name ?? $sessionUser} size={30} /> |
| 1724 | {:else} |
| 1725 | <span class="me-avatar" aria-hidden="true">{$sessionUser.slice(1, 2).toUpperCase()}</span> |
| 1726 | {/if} |
| 1727 | <span class="me-id">{profile?.display_name && profile.display_name !== $sessionUser ? `${profile.display_name} (${$sessionUser})` : $sessionUser}</span> |
| 1728 | </div> |
| 1729 | <button |
| 1730 | type="button" |
| 1731 | class="icon-btn" |
| 1732 | title="Encryption and verification" |
| 1733 | aria-label="Encryption and verification" |
| 1734 | on:click={() => (dialog = 'security')} |
| 1735 | > |
| 1736 | <span aria-hidden="true">🛡</span> |
| 1737 | </button> |
| 1738 | <button |
| 1739 | type="button" |
| 1740 | class="icon-btn" |
| 1741 | title="Settings" |
| 1742 | aria-label="Settings" |
| 1743 | on:click={() => (dialog = 'settings')} |
| 1744 | > |
| 1745 | <span aria-hidden="true">⚙</span> |
| 1746 | </button> |
| 1747 | <button type="button" class="icon-btn" title="Log out" aria-label="Log out" on:click={() => void doLogout()}> |
| 1748 | <span aria-hidden="true">⏻</span> |
| 1749 | </button> |
| 1750 | </div> |
| 1751 | </aside> |
| 1752 | {#if sidebarOpen} |
| 1753 | <button type="button" class="scrim" aria-label="Close room list" on:click={() => (sidebarOpen = false)}></button> |
| 1754 | {/if} |
| 1755 | |
| 1756 | <main class="chat"> |
| 1757 | {#if $banners.length > 0} |
| 1758 | <div class="banners" aria-live="polite"> |
| 1759 | {#each $banners as banner (banner.id)} |
| 1760 | <div class="banner" role="alert"> |
| 1761 | <span>{banner.message}</span> |
| 1762 | <button |
| 1763 | type="button" |
| 1764 | aria-label="Dismiss error" |
| 1765 | on:click={() => dismissBanner(banner.id)} |
| 1766 | > |
| 1767 | ✕ |
| 1768 | </button> |
| 1769 | </div> |
| 1770 | {/each} |
| 1771 | </div> |
| 1772 | {/if} |
| 1773 | {#if !selectedRoom} |
| 1774 | <div class="empty"> |
| 1775 | <div class="empty-mark" aria-hidden="true">◈</div> |
| 1776 | {#if selectedSpace} |
| 1777 | <h1>{selectedSpace.name}</h1> |
| 1778 | {:else} |
| 1779 | <h1>Welcome to Malice</h1> |
| 1780 | {/if} |
| 1781 | <div class="empty-cta"> |
| 1782 | <button type="button" class="primary-btn" on:click={() => (dialog = 'join')}>Join a room</button> |
| 1783 | <button type="button" class="ghost-btn" on:click={() => (dialog = 'create')}>Create a room</button> |
| 1784 | </div> |
| 1785 | <p class="conn-line"> |
| 1786 | <span class="dot {connectionClass($connection)}" aria-hidden="true"></span> |
| 1787 | {$connection} |
| 1788 | </p> |
| 1789 | </div> |
| 1790 | {:else} |
| 1791 | <header class="chat-head"> |
| 1792 | <button |
| 1793 | type="button" |
| 1794 | class="icon-btn only-mobile" |
| 1795 | aria-label="Open room list" |
| 1796 | on:click={() => (sidebarOpen = true)} |
| 1797 | > |
| 1798 | <span aria-hidden="true">☰</span> |
| 1799 | </button> |
| 1800 | <button |
| 1801 | type="button" |
| 1802 | class="icon-btn only-desktop pane-toggle" |
| 1803 | aria-pressed={!$railFolded} |
| 1804 | aria-label={$railFolded ? 'Show spaces' : 'Hide spaces'} |
| 1805 | title={$railFolded ? 'Show spaces' : 'Hide spaces'} |
| 1806 | on:click={() => railFolded.update((v) => !v)} |
| 1807 | > |
| 1808 | <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"> |
| 1809 | <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" /> |
| 1810 | <circle cx="7" cy="9" r="1.4" fill="currentColor" /> |
| 1811 | <circle cx="7" cy="13" r="1.4" fill="currentColor" /> |
| 1812 | <circle cx="7" cy="17" r="1.4" fill="currentColor" /> |
| 1813 | </svg> |
| 1814 | </button> |
| 1815 | <button |
| 1816 | type="button" |
| 1817 | class="icon-btn only-desktop pane-toggle" |
| 1818 | aria-pressed={!$navFolded} |
| 1819 | aria-label={$navFolded ? 'Show channels' : 'Hide channels'} |
| 1820 | title={$navFolded ? 'Show channels' : 'Hide channels'} |
| 1821 | on:click={() => navFolded.update((v) => !v)} |
| 1822 | > |
| 1823 | <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"> |
| 1824 | <rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2" /> |
| 1825 | <path d="M10 4v16" stroke="currentColor" stroke-width="2" /> |
| 1826 | </svg> |
| 1827 | </button> |
| 1828 | <div class="head-title"> |
| 1829 | <div class="head-room"> |
| 1830 | <MxcAvatar mxc={selectedRoom.avatar} label={selectedRoom.name} size={36} shape={selectedRoom.space ? 'rounded' : 'circle'} /> |
| 1831 | <div class="head-room-text"> |
| 1832 | <h1>{selectedRoom.name}</h1> |
| 1833 | <div class="head-meta"> |
| 1834 | {#if selectedRoom.space} |
| 1835 | <span class="pill">space</span> |
| 1836 | {/if} |
| 1837 | {#if selectedRoom.encrypted} |
| 1838 | <span class="pill" title="End-to-end encrypted">🔒 encrypted</span> |
| 1839 | {/if} |
| 1840 | {#if selectedRoom.direct} |
| 1841 | <span class="pill">direct</span> |
| 1842 | {/if} |
| 1843 | <span class="conn" title={`Sync state: ${$connection}`}> |
| 1844 | <span class="dot {connectionClass($connection)}" aria-hidden="true"></span> |
| 1845 | {$connection} |
| 1846 | </span> |
| 1847 | </div> |
| 1848 | </div> |
| 1849 | </div> |
| 1850 | </div> |
| 1851 | <div class="head-actions"> |
| 1852 | {#if peeking === selectedRoom.room_id} |
| 1853 | <button type="button" class="icon-btn" aria-pressed="true" aria-label="Stop peeking" title="Stop peeking" on:click={stopPeeking}> |
| 1854 | <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"> |
| 1855 | <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" /> |
| 1856 | <circle cx="12" cy="12" r="3" fill="currentColor" /> |
| 1857 | </svg> |
| 1858 | </button> |
| 1859 | {/if} |
| 1860 | {#if selectedRoom.membership !== 'Joined'} |
| 1861 | <button |
| 1862 | type="button" |
| 1863 | class="primary-btn" |
| 1864 | disabled={joinBusy} |
| 1865 | on:click={() => void join(selectedRoom.room_id)} |
| 1866 | > |
| 1867 | {joinBusy ? 'Joining…' : 'Join'} |
| 1868 | </button> |
| 1869 | {/if} |
| 1870 | <button |
| 1871 | type="button" |
| 1872 | class="icon-btn" |
| 1873 | aria-pressed={membersOpen} |
| 1874 | aria-label={membersOpen ? 'Hide members' : 'Show members'} |
| 1875 | title="Members" |
| 1876 | on:click={toggleMembers} |
| 1877 | > |
| 1878 | <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"> |
| 1879 | <circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2" /> |
| 1880 | <path d="M4 20c0-4 3.6-6 8-6s8 2 8 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" /> |
| 1881 | </svg> |
| 1882 | </button> |
| 1883 | <div class="room-menu-wrap" bind:this={roomMenuEl}> |
| 1884 | <button |
| 1885 | type="button" |
| 1886 | class="icon-btn" |
| 1887 | aria-haspopup="menu" |
| 1888 | aria-expanded={roomMenuOpen} |
| 1889 | aria-label="Room options" |
| 1890 | title="Room options" |
| 1891 | on:click={() => (roomMenuOpen = !roomMenuOpen)} |
| 1892 | > |
| 1893 | <span aria-hidden="true">⋯</span> |
| 1894 | </button> |
| 1895 | {#if roomMenuOpen} |
| 1896 | <div class="room-menu" role="menu"> |
| 1897 | <button type="button" role="menuitem" on:click={() => roomMenuAction(() => (dialog = 'security'))}> |
| 1898 | Security |
| 1899 | </button> |
| 1900 | {#if selectedRoom.membership === 'Joined'} |
| 1901 | <button |
| 1902 | type="button" |
| 1903 | role="menuitem" |
| 1904 | class="danger" |
| 1905 | disabled={leaveBusy} |
| 1906 | on:click={() => roomMenuAction(() => void leave())} |
| 1907 | > |
| 1908 | {leaveBusy ? 'Leaving…' : 'Leave room'} |
| 1909 | </button> |
| 1910 | {/if} |
| 1911 | </div> |
| 1912 | {/if} |
| 1913 | </div> |
| 1914 | </div> |
| 1915 | </header> |
| 1916 | |
| 1917 | |
| 1918 | {#if recoveryBanner} |
| 1919 | <div class="sec-banner warn" role="status"> |
| 1920 | <span>Message history is locked</span> |
| 1921 | <button type="button" on:click={() => (dialog = 'security')}>Recover</button> |
| 1922 | </div> |
| 1923 | {/if} |
| 1924 | {#if verificationBanner} |
| 1925 | <div class="sec-banner" role="status"> |
| 1926 | {#if verificationBanner.kind === 'Incoming'} |
| 1927 | <span>A device wants to verify this session</span> |
| 1928 | <button type="button" on:click={() => (dialog = 'security')}>Review request</button> |
| 1929 | {:else if verificationBanner.kind === 'Comparison'} |
| 1930 | <span>Verification codes ready</span> |
| 1931 | <button type="button" on:click={() => (dialog = 'security')}>Compare codes</button> |
| 1932 | {:else if verificationBanner.kind === 'Waiting'} |
| 1933 | <span>Verification started</span> |
| 1934 | <button type="button" on:click={() => (dialog = 'security')}>Open verification</button> |
| 1935 | {:else if verificationBanner.kind === 'Failed'} |
| 1936 | <span>Verification failed: {verificationBanner.message}</span> |
| 1937 | <button type="button" on:click={() => (dialog = 'security')}>Try again</button> |
| 1938 | {:else if verificationBanner.kind === 'Cancelled'} |
| 1939 | <span>Verification cancelled: {verificationBanner.reason}</span> |
| 1940 | <button type="button" on:click={() => (dialog = 'security')}>Open security</button> |
| 1941 | {:else} |
| 1942 | <span>Verification in progress</span> |
| 1943 | <button type="button" on:click={() => (dialog = 'security')}>Open security</button> |
| 1944 | {/if} |
| 1945 | </div> |
| 1946 | {/if} |
| 1947 | {#if $selectedRoomId && openFailed[$selectedRoomId]} |
| 1948 | <p class="conn-banner error" role="alert">{openFailed[$selectedRoomId]}</p> |
| 1949 | {/if} |
| 1950 | |
| 1951 | <!-- svelte-ignore a11y_no_static_element_interactions --> |
| 1952 | <div |
| 1953 | class="timeline" |
| 1954 | bind:this={timelineEl} |
| 1955 | on:scroll={onTimelineScroll} |
| 1956 | on:wheel={noteUserScroll} |
| 1957 | on:touchmove={noteUserScroll} |
| 1958 | on:keydown={onTimelineKey} |
| 1959 | on:pointerdown={onTimelinePointer} |
| 1960 | aria-label={`Messages in ${selectedRoom.name}`} |
| 1961 | > |
| 1962 | <div class="timeline-inner" use:pinTimeline> |
| 1963 | <div class="timeline-top"> |
| 1964 | {#if hasStart} |
| 1965 | <p class="start-note">Beginning of history</p> |
| 1966 | {:else} |
| 1967 | <button type="button" class="ghost-btn" disabled={paginateBusy} on:click={() => void paginate()}> |
| 1968 | {paginateBusy ? 'Loading…' : 'Load older messages'} |
| 1969 | </button> |
| 1970 | {/if} |
| 1971 | </div> |
| 1972 | {#if grouped.length === 0} |
| 1973 | <p class="side-note timeline-empty">No messages yet</p> |
| 1974 | {:else} |
| 1975 | {#each grouped as g (g.key)} |
| 1976 | {#if g.item.kind === 'day'} |
| 1977 | <div class="day-row"><span>{formatDay(g.item.timestamp_ms)}</span></div> |
| 1978 | {:else if g.item.kind === 'readMarker'} |
| 1979 | <div class="new-row"><span>New</span></div> |
| 1980 | {:else if g.item.kind === 'start'} |
| 1981 | <p class="start-note">Beginning of history</p> |
| 1982 | {:else if g.item.kind === 'unknown'} |
| 1983 | <p class="unknown-note">Unsupported event ({g.item.label})</p> |
| 1984 | {:else} |
| 1985 | <MessageRow |
| 1986 | itemId={g.key} |
| 1987 | event={g.item.event} |
| 1988 | showSender={g.showSender} |
| 1989 | senderAvatar={senderAvatarFor(g.item.event.sender.user_id) ?? g.item.event.sender.avatar} |
| 1990 | {reacting} |
| 1991 | onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)} |
| 1992 | quickReactions={$quickReactions} |
| 1993 | packs={roomPacks} |
| 1994 | linkPreviews={$linkPreviews} |
| 1995 | {loadPreview} |
| 1996 | onQuickChange={(list) => void changeQuickReactions(list)} |
| 1997 | {people} |
| 1998 | self={$sessionUser ?? null} |
| 1999 | onUser={(userId, x, y, asMenu) => void openUser(userId, x, y, asMenu)} |
| 2000 | onCloneSticker={openCloneStickerMenu} |
| 2001 | onReply={selectedRoom.membership === 'Joined' ? startReply : null} |
| 2002 | onJump={jumpTo} |
| 2003 | onEdit={selectedRoom.membership === 'Joined' ? startEdit : null} |
| 2004 | editing={editing !== null && editing.eventId === g.item.event.event_id} |
| 2005 | showSent={g.item.event.item_id === lastSentId && pendingItems.length === 0} |
| 2006 | /> |
| 2007 | {/if} |
| 2008 | {/each} |
| 2009 | {/if} |
| 2010 | {#each pendingItems as p, i (p.id)} |
| 2011 | <MessageRow |
| 2012 | itemId={`pending-${p.id}`} |
| 2013 | event={pendingToEvent(p)} |
| 2014 | onJump={jumpTo} |
| 2015 | showSender={pendingShowSender(i)} |
| 2016 | senderAvatar={senderAvatarFor($sessionUser ?? '')} |
| 2017 | {reacting} |
| 2018 | onReact={(eventId, key, shortcode) => void react(eventId, key, shortcode)} |
| 2019 | quickReactions={$quickReactions} |
| 2020 | packs={roomPacks} |
| 2021 | linkPreviews={$linkPreviews} |
| 2022 | {loadPreview} |
| 2023 | onQuickChange={(list) => void changeQuickReactions(list)} |
| 2024 | /> |
| 2025 | {#if p.status === 'failed'} |
| 2026 | <div class="pending-actions"> |
| 2027 | <span class="pending-error" role="alert">{p.error}</span> |
| 2028 | <button type="button" class="ghost-btn" on:click={() => retryPending(p.id)}>Retry</button> |
| 2029 | <button type="button" class="ghost-btn danger" on:click={() => discardPending(p.id)}>Discard</button> |
| 2030 | </div> |
| 2031 | {/if} |
| 2032 | {/each} |
| 2033 | </div> |
| 2034 | </div> |
| 2035 | |
| 2036 | {#if selectedRoom.membership === 'Joined'} |
| 2037 | {#if editing} |
| 2038 | <div class="reply-bar" role="status"> |
| 2039 | <span class="reply-bar-label"> |
| 2040 | Editing message |
| 2041 | <span class="reply-bar-text">{editing.original}</span> |
| 2042 | </span> |
| 2043 | <button type="button" class="icon-btn" aria-label="Cancel edit" title="Cancel edit (Esc)" on:click={cancelEdit}> |
| 2044 | <span aria-hidden="true">✕</span> |
| 2045 | </button> |
| 2046 | </div> |
| 2047 | {:else if replyingTo && replyingTo.details.kind === 'Ready'} |
| 2048 | <div class="reply-bar" role="status"> |
| 2049 | <span class="reply-bar-label"> |
| 2050 | Replying to <strong>{senderLabel(replyingTo.details.sender)}</strong> |
| 2051 | <span class="reply-bar-text">{contentPreview(replyingTo.details.content)}</span> |
| 2052 | </span> |
| 2053 | <button type="button" class="icon-btn" aria-label="Cancel reply" title="Cancel reply (Esc)" on:click={() => (replyingTo = null)}> |
| 2054 | <span aria-hidden="true">✕</span> |
| 2055 | </button> |
| 2056 | </div> |
| 2057 | {/if} |
| 2058 | {#if $selectedRoomId && currentStaged.length > 0} |
| 2059 | {@const stagedRoom = $selectedRoomId} |
| 2060 | <ul class="staged" aria-label="Attachments to send"> |
| 2061 | {#each currentStaged as attachment (attachment.id)} |
| 2062 | <li class="staged-item"> |
| 2063 | {#if attachment.previewUrl} |
| 2064 | <img src={attachment.previewUrl} alt={attachment.file.name || 'Pasted image'} /> |
| 2065 | {:else} |
| 2066 | <span class="staged-name">{attachment.file.name || 'attachment'}</span> |
| 2067 | {/if} |
| 2068 | <button |
| 2069 | type="button" |
| 2070 | class="icon-btn staged-remove" |
| 2071 | aria-label={`Remove ${attachment.file.name || 'attachment'}`} |
| 2072 | title="Remove" |
| 2073 | on:click={() => unstage(stagedRoom, attachment.id)} |
| 2074 | > |
| 2075 | <span aria-hidden="true">✕</span> |
| 2076 | </button> |
| 2077 | </li> |
| 2078 | {/each} |
| 2079 | </ul> |
| 2080 | {/if} |
| 2081 | <form class="composer" class:replying={replyingTo || editing} class:staging={currentStaged.length > 0} on:submit|preventDefault={() => send()}> |
| 2082 | <label class="visually-hidden" for="composer">Message {selectedRoom.name}</label> |
| 2083 | {#if mentionQuery && mentionCandidates.length > 0} |
| 2084 | <ul class="mention-finder" role="listbox" aria-label="Mention someone"> |
| 2085 | {#each mentionCandidates as person, i (person.user_id)} |
| 2086 | <li |
| 2087 | role="option" |
| 2088 | aria-selected={i === mentionIndex} |
| 2089 | class:active={i === mentionIndex} |
| 2090 | on:pointerdown|preventDefault={() => void pickMention(person)} |
| 2091 | on:pointerenter={() => (mentionIndex = i)} |
| 2092 | > |
| 2093 | <MxcAvatar mxc={person.avatar} label={person.name} size={22} /> |
| 2094 | <span class="mention-name">{person.name}</span> |
| 2095 | <span class="mention-id">{person.user_id}</span> |
| 2096 | </li> |
| 2097 | {/each} |
| 2098 | </ul> |
| 2099 | {/if} |
| 2100 | <input |
| 2101 | type="file" |
| 2102 | multiple |
| 2103 | bind:this={fileInput} |
| 2104 | class="visually-hidden" |
| 2105 | aria-label="Attach a file" |
| 2106 | on:change={() => void onFileChosen()} |
| 2107 | /> |
| 2108 | <input |
| 2109 | type="file" |
| 2110 | accept="image/*" |
| 2111 | bind:this={avatarInput} |
| 2112 | class="visually-hidden" |
| 2113 | aria-label="Choose a new avatar" |
| 2114 | on:change={() => void onAvatarChosen()} |
| 2115 | /> |
| 2116 | <button |
| 2117 | type="button" |
| 2118 | class="ghost-btn" |
| 2119 | title="Attach an image or file" |
| 2120 | aria-label="Attach an image or file" |
| 2121 | disabled={!($selectedRoomId && openReady[$selectedRoomId])} |
| 2122 | on:click={pickFiles} |
| 2123 | > |
| 2124 | {uploadBusy ? `Uploading ${uploadName ?? 'file'}…` : '📎'} |
| 2125 | </button> |
| 2126 | <button |
| 2127 | type="button" |
| 2128 | class="icon-btn sticker-btn" |
| 2129 | title="Stickers" |
| 2130 | aria-label="Stickers" |
| 2131 | aria-expanded={stickersOpen} |
| 2132 | disabled={!($selectedRoomId && openReady[$selectedRoomId])} |
| 2133 | on:click={() => (stickersOpen = !stickersOpen)} |
| 2134 | > |
| 2135 | <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"> |
| 2136 | <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" /> |
| 2137 | <path d="M13 20v-5a2 2 0 0 1 2-2h5" fill="none" stroke="currentColor" stroke-width="1.8" /> |
| 2138 | </svg> |
| 2139 | </button> |
| 2140 | {#if stickersOpen && $selectedRoomId} |
| 2141 | {@const stickerRoom = $selectedRoomId} |
| 2142 | <div class="sticker-pop"> |
| 2143 | <StickerPicker |
| 2144 | packs={roomPacks} |
| 2145 | {roomName} |
| 2146 | onSend={(pack, image) => void sendSticker(stickerRoom, pack, image)} |
| 2147 | onClone={(pack, image, x, y) => openCloneImageMenu(pack, image, x, y)} |
| 2148 | onClonePack={(pack, x, y) => openClonePackMenu(pack, x, y)} |
| 2149 | onManage={() => ((stickersOpen = false), (dialog = 'packs'))} |
| 2150 | onClose={() => (stickersOpen = false)} |
| 2151 | /> |
| 2152 | </div> |
| 2153 | {/if} |
| 2154 | <textarea |
| 2155 | id="composer" |
| 2156 | bind:this={composerEl} |
| 2157 | bind:value={composer} |
| 2158 | rows="1" |
| 2159 | placeholder={`Message ${selectedRoom.name}`} |
| 2160 | aria-label={`Message ${selectedRoom.name}. Enter to send, Shift Enter for a new line.`} |
| 2161 | on:keydown={onComposerKey} |
| 2162 | on:input={updateMentionQuery} |
| 2163 | on:click={updateMentionQuery} |
| 2164 | on:keyup={(e) => (e.key.startsWith('Arrow') && e.key !== 'ArrowUp' && e.key !== 'ArrowDown') || e.key === 'Home' || e.key === 'End' ? updateMentionQuery() : undefined} |
| 2165 | on:blur={() => (mentionQuery = null)} |
| 2166 | on:paste={onComposerPaste} |
| 2167 | disabled={!($selectedRoomId && openReady[$selectedRoomId])} |
| 2168 | ></textarea> |
| 2169 | <button |
| 2170 | type="button" |
| 2171 | class="icon-btn md-toggle" |
| 2172 | aria-pressed={$markdownEnabled} |
| 2173 | aria-label={$markdownEnabled ? 'Turn markdown off' : 'Turn markdown on'} |
| 2174 | title={$markdownEnabled ? 'Markdown on' : 'Markdown off'} |
| 2175 | on:click={() => markdownEnabled.update((v) => !v)} |
| 2176 | > |
| 2177 | <svg viewBox="0 0 24 16" width="22" height="15" aria-hidden="true"> |
| 2178 | <rect x="1" y="1" width="22" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="1.6" /> |
| 2179 | <path d="M4.5 11.5v-7l2.75 3 2.75-3v7M15.5 4.5v6.5M13 8.5l2.5 2.75L18 8.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" /> |
| 2180 | </svg> |
| 2181 | </button> |
| 2182 | <button |
| 2183 | type="submit" |
| 2184 | class="primary-btn" |
| 2185 | disabled={(!composer.trim() && currentStaged.length === 0) || |
| 2186 | !($selectedRoomId && openReady[$selectedRoomId]) || |
| 2187 | (currentStaged.length > 0 && uploadBusy)} |
| 2188 | title={!($selectedRoomId && openReady[$selectedRoomId]) ? 'Waiting for the room to open' : 'Send message'} |
| 2189 | > |
| 2190 | Send |
| 2191 | </button> |
| 2192 | </form> |
| 2193 | {:else} |
| 2194 | <div class="join-bar"> |
| 2195 | <p>You are not a member of this room.</p> |
| 2196 | <button type="button" class="primary-btn" disabled={joinBusy} on:click={() => void join(selectedRoom.room_id)}> |
| 2197 | {joinBusy ? 'Joining…' : `Join ${selectedRoom.name}`} |
| 2198 | </button> |
| 2199 | </div> |
| 2200 | {/if} |
| 2201 | {/if} |
| 2202 | </main> |
| 2203 | |
| 2204 | {#if selectedRoom} |
| 2205 | <aside class="members" aria-hidden={!membersOpen} aria-label={`Members of ${selectedRoom.name}`}> |
| 2206 | <div class="members-head"> |
| 2207 | <h2>Members</h2> |
| 2208 | <button type="button" class="icon-btn" aria-label="Close members" on:click={() => (membersOpen = false)}> |
| 2209 | <span aria-hidden="true">✕</span> |
| 2210 | </button> |
| 2211 | </div> |
| 2212 | {#if $membersLoading && members.length === 0} |
| 2213 | <p class="side-note">Loading members…</p> |
| 2214 | {:else if members.length === 0} |
| 2215 | <p class="side-note">No members loaded.</p> |
| 2216 | {#if $selectedRoomId} |
| 2217 | <button type="button" class="ghost-btn" on:click={() => $selectedRoomId && void loadMembers($selectedRoomId)}> |
| 2218 | Retry |
| 2219 | </button> |
| 2220 | {/if} |
| 2221 | {:else} |
| 2222 | <ul class="member-list"> |
| 2223 | {#each members as member (member.user_id)} |
| 2224 | <li> |
| 2225 | <button |
| 2226 | type="button" |
| 2227 | class="member" |
| 2228 | on:click={(ev) => { |
| 2229 | const rect = ev.currentTarget.getBoundingClientRect(); |
| 2230 | void openUser(member.user_id, rect.left - 308, rect.top, false); |
| 2231 | }} |
| 2232 | on:contextmenu|preventDefault={(ev) => void openUser(member.user_id, ev.clientX, ev.clientY, true)} |
| 2233 | > |
| 2234 | <MxcAvatar mxc={member.avatar} label={member.display_name || member.name || member.user_id} size={30} /> |
| 2235 | <span class="member-names"> |
| 2236 | <span class="member-name">{member.display_name || member.name}</span> |
| 2237 | <span class="member-id">{member.user_id}</span> |
| 2238 | </span> |
| 2239 | </button> |
| 2240 | </li> |
| 2241 | {/each} |
| 2242 | </ul> |
| 2243 | {/if} |
| 2244 | </aside> |
| 2245 | {/if} |
| 2246 | |
| 2247 | {#if dialog} |
| 2248 | <div class="modal-wrap" role="presentation" on:click|self={() => (dialog = null)}> |
| 2249 | {#if dialog === 'security'} |
| 2250 | <SecurityPanel |
| 2251 | encryptionState={$encryption} |
| 2252 | verificationState={$verification} |
| 2253 | onAction={() => void loadEncryption()} |
| 2254 | encryptedPreviews={$urlPreviewSettings.encrypted_rooms} |
| 2255 | onEncryptedPreviews={(enabled) => void changeEncryptedPreviews(enabled)} |
| 2256 | on:close={() => (dialog = null)} |
| 2257 | /> |
| 2258 | {:else if dialog === 'settings'} |
| 2259 | <SettingsPanel |
| 2260 | quick={$quickReactions} |
| 2261 | packs={roomPacks} |
| 2262 | onQuickChange={(list) => void changeQuickReactions(list)} |
| 2263 | on:close={() => (dialog = null)} |
| 2264 | on:packs={() => (dialog = 'packs')} |
| 2265 | /> |
| 2266 | {:else if dialog === 'packs'} |
| 2267 | <PackManager packs={$imagePacks} rooms={$rooms} onError={pushBanner} on:close={() => (dialog = null)} /> |
| 2268 | {:else} |
| 2269 | <div class="modal" role="dialog" aria-modal="true" aria-label={dialog === 'join' ? 'Join a room' : 'Create a room'}> |
| 2270 | <div class="modal-tabs" role="tablist" aria-label="Room actions"> |
| 2271 | <button |
| 2272 | type="button" |
| 2273 | role="tab" |
| 2274 | aria-selected={dialog === 'join'} |
| 2275 | class:active={dialog === 'join'} |
| 2276 | on:click={() => (dialog = 'join')} |
| 2277 | > |
| 2278 | Join |
| 2279 | </button> |
| 2280 | <button |
| 2281 | type="button" |
| 2282 | role="tab" |
| 2283 | aria-selected={dialog === 'create'} |
| 2284 | class:active={dialog === 'create'} |
| 2285 | on:click={() => (dialog = 'create')} |
| 2286 | > |
| 2287 | Create |
| 2288 | </button> |
| 2289 | <button |
| 2290 | type="button" |
| 2291 | class="icon-btn modal-x" |
| 2292 | aria-label="Close dialog" |
| 2293 | on:click={() => (dialog = null)} |
| 2294 | > |
| 2295 | <span aria-hidden="true">✕</span> |
| 2296 | </button> |
| 2297 | </div> |
| 2298 | {#if dialog === 'join'} |
| 2299 | <form on:submit|preventDefault={() => void join(joinTarget)}> |
| 2300 | <label class="field"> |
| 2301 | <span>Room ID or alias</span> |
| 2302 | <input |
| 2303 | type="text" |
| 2304 | placeholder="!room:example.org or #alias:example.org" |
| 2305 | bind:value={joinTarget} |
| 2306 | required |
| 2307 | disabled={joinBusy} |
| 2308 | /> |
| 2309 | </label> |
| 2310 | <button type="submit" class="primary-btn wide" disabled={joinBusy || !joinTarget.trim()}> |
| 2311 | {joinBusy ? 'Joining…' : 'Join room'} |
| 2312 | </button> |
| 2313 | </form> |
| 2314 | {:else} |
| 2315 | <form on:submit|preventDefault={() => void create()}> |
| 2316 | <label class="field"> |
| 2317 | <span>Room name</span> |
| 2318 | <input |
| 2319 | type="text" |
| 2320 | placeholder="Weekend plans" |
| 2321 | bind:value={createName} |
| 2322 | required |
| 2323 | disabled={createBusy} |
| 2324 | /> |
| 2325 | </label> |
| 2326 | <label class="field"> |
| 2327 | <span>Topic (optional)</span> |
| 2328 | <input |
| 2329 | type="text" |
| 2330 | placeholder="What should this room be about?" |
| 2331 | bind:value={createTopic} |
| 2332 | disabled={createBusy} |
| 2333 | /> |
| 2334 | </label> |
| 2335 | <button type="submit" class="primary-btn wide" disabled={createBusy || !createName.trim()}> |
| 2336 | {createBusy ? 'Creating…' : 'Create room'} |
| 2337 | </button> |
| 2338 | </form> |
| 2339 | {/if} |
| 2340 | </div> |
| 2341 | {/if} |
| 2342 | </div> |
| 2343 | {/if} |
| 2344 | </div> |
| 2345 | {/if} |
| 2346 | |
| 2347 | <ImageLightbox /> |