atagen

malice

public
Star0
Watch0
afba1feb41cebde51e0dd74fa483474fbf4d06ac
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/MessageRow.svelteSvelte789 lines33.0 KB
1
<svelte:options immutable />
2
3
<script lang="ts">
4
  import MediaAttachmentView from './MediaAttachmentView.svelte';
5
  import MxcAvatar from './MxcAvatar.svelte';
6
  import Emoji from './Emoji.svelte';
7
  import EmojiText from './EmojiText.svelte';
8
  import MessageText from './MessageText.svelte';
9
  import { longpress } from './longpress';
10
  import ReactionPicker from './ReactionPicker.svelte';
11
  import { backStack, instanceLayerId } from './back-stack';
12
  import LinkCard from './LinkCard.svelte';
13
  import { afterUpdate, onDestroy } from 'svelte';
14
  import { dissolve, expand, rowIn, rowOut, settleHeight } from './motion';
15
  import { selectedRow } from './selected-row';
16
  import { mediaUrl, messageMediaUrl } from './api';
17
  import { keywordMatcher } from './keywords';
18
  import type { ImagePack, LinkPreview, Person, QuickEntry, ReplyReference, SendState, TimelineContent, TimelineEvent } from './types';
19
  import { QUICK_REACTIONS_PER_ROW, senderLabel } from './types';
20
  import { quickColumns, quickGroups } from './quick-reactions-model';
21
  import { formatClock, formatDay, initialsOf, senderHue } from './format';
22
  import { findUrls } from './urls';
23
  import { mentionsFromHtml, resolveMentions, stripMarkdownPills } from './mentions';
24
25
  export let itemId: string;
26
  export let event: TimelineEvent;
27
  export let showSender: boolean;
28
  export let reacting: boolean;
29
  export let onReact: (eventId: string, key: string, shortcode?: string) => void;
30
  export let senderAvatar: string | null = null;
31
  export let quickReactions: QuickEntry[] = [];
32
  export let packs: ImagePack[] = [];
33
  export let onQuickChange: (list: QuickEntry[]) => void = () => {};
34
  export let linkPreviews: Record<string, LinkPreview | null> = {};
35
  export let loadPreview: ((url: string) => void) | null = null;
36
  export let people: Record<string, Person> = {};
37
  export let onReply: ((target: ReplyReference) => void) | null = null;
38
  export let onJump: ((eventId: string) => void) | null = null;
39
  export let onEdit: ((eventId: string, body: string) => void) | null = null;
40
  export let editing = false;
41
  export let showSent = true;
42
  export let readOnly = false;
43
  export let self: string | null = null;
44
  export let onUser: ((userId: string, x: number, y: number, menu: boolean) => void) | null = null;
45
  export let onCloneSticker: ((eventId: string, body: string, x: number, y: number) => void) | null = null;
46
  export let onMore: ((event: TimelineEvent, x: number, y: number) => void) | null = null;
47
  export let onOpenThread: ((rootEventId: string) => void) | null = null;
48
49
  $: lag = lagLabel(event);
50
  $: threadRoot = onOpenThread && interactive && event.event_id && !event.thread_root ? event.event_id : null;
51
  $: threadReplies = event.thread_summary?.reply_count ?? 0;
52
53
  function lagLabel(event: TimelineEvent): string | null {
54
    const lag = event.delivery_lag_ms;
55
    if (!lag) return null;
56
    if (lag < 60 * 60 * 1000) return `${Math.max(1, Math.floor(lag / 60000))}m`;
57
    if (lag < 24 * 60 * 60 * 1000) return `${Math.floor(lag / 3600000)}h`;
58
    return `${Math.floor(lag / 86400000)}d`;
59
  }
60
61
  function openUser(ev: Pick<MouseEvent, 'clientX' | 'clientY' | 'currentTarget'>, menu: boolean): void {
62
    if (!onUser) return;
63
    const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
64
    onUser(event.sender.user_id, menu ? ev.clientX : rect.left, menu ? ev.clientY : rect.bottom + 4, menu);
65
  }
66
67
  const PICKER_WIDTH = 320;
68
  const PICKER_HEIGHT = 380;
69
  const PICKER_MARGIN = 8;
70
  const MAX_READERS = 3;
71
  const STATE_LABELS: Record<string, string> = {
72
    'm.room.pinned_events': 'changed the pinned messages',
73
    'm.room.power_levels': 'changed the room permissions',
74
    'm.room.join_rules': 'changed who can join',
75
    'm.room.history_visibility': 'changed who can read history',
76
    'm.room.guest_access': 'changed guest access',
77
    'm.room.canonical_alias': 'changed the room address',
78
    'm.room.server_acl': 'changed the server access list',
79
    'm.space.child': 'changed the rooms in this space',
80
    'm.space.parent': 'changed the parent space',
81
    'im.ponies.room_emotes': 'updated a sticker pack'
82
  };
83
84
  const owner = Symbol();
85
  let row: HTMLDivElement;
86
  let pickerPop: HTMLDivElement | undefined;
87
  let hovered = false;
88
  let focused = false;
89
  let reactorKey: string | null = null;
90
  let reactorPinned = false;
91
  let pickerOpen = false;
92
  let pickerStyle = '';
93
94
  const MEMBERSHIP_LABELS: Record<string, string> = {
95
    Joined: 'joined the room',
96
    Left: 'left the room',
97
    Banned: 'was banned',
98
    Unbanned: 'was unbanned',
99
    Kicked: 'was kicked',
100
    KickedAndBanned: 'was kicked and banned',
101
    Invited: 'was invited',
102
    InvitationAccepted: 'accepted the invite',
103
    InvitationRejected: 'rejected the invite',
104
    InvitationRevoked: 'had the invite revoked',
105
    Knocked: 'requested to join',
106
    KnockAccepted: 'was let in',
107
    KnockRetracted: 'withdrew the request to join',
108
    KnockDenied: 'had the request to join denied'
109
  };
110
111
  $: name = event.sender.display_name ?? people[event.sender.user_id]?.name ?? event.sender.user_id;
112
  $: displayName = event.sender.name_ambiguous ? `${name} (${event.sender.user_id})` : name;
113
  $: readers = event.read_by.map((id) => people[id] ?? { user_id: id, name: id, avatar: null });
114
  $: interactive = event.content.kind === 'Message' || event.content.kind === 'Sticker' || event.content.kind === 'Poll';
115
  $: message = event.content.kind === 'Message' ? event.content.message : null;
116
  $: rawText = message ? (message.media ? message.media.caption : message.body) ?? '' : '';
117
  $: formattedBody = message?.formatted_body ?? null;
118
  $: hasMessage = message !== null;
119
  $: stripped = stripMarkdownPills(rawText);
120
  $: linked = hasMessage ? [...mentionsFromHtml(formattedBody), ...stripped.mentions] : [];
121
  $: nameOf = (id: string) => people[id]?.name ?? null;
122
  $: mentions = resolveMentions(stripped.text, linked);
123
  $: mentionsMe = self !== null && [...linked, ...mentions].some((m) => m.user_id === self);
124
  $: own = event.own;
125
  $: highlighted = event.highlight === true;
126
  $: keywordHit = !own && (highlighted || (hasMessage && ($keywordMatcher?.test(stripped.text) ?? false)));
127
  $: previews = findUrls(stripped.text);
128
  $: bundled = message ? message.link_previews : [];
129
  $: cards = previews
130
    .map((link) => ({ link, preview: bundled.find((b) => b.url === link.href) ?? linkPreviews[link.href] ?? null }))
131
    .filter((c) => c.preview && (c.preview.title || c.preview.description || c.preview.image));
132
  $: if (loadPreview) {
133
    for (const link of previews) {
134
      if (!bundled.some((b) => b.url === link.href) && !(link.href in linkPreviews)) loadPreview(link.href);
135
    }
136
  }
137
138
  $: sent = interactive && showSent && event.own && event.send_state.kind === 'Sent' && event.event_id !== null;
139
140
  let lastShape = '';
141
  let heightBefore: number | null = null;
142
  $: noteShape(`${event.content.kind}|${rawText}|${formattedBody}|${message?.edited}|${event.reply_to?.details.kind}|${showSender}`);
143
144
  function noteShape(shape: string): void {
145
    if (row && lastShape && shape !== lastShape) heightBefore = row.offsetHeight;
146
    lastShape = shape;
147
  }
148
149
  afterUpdate(() => {
150
    if (heightBefore === null) return;
151
    const from = heightBefore;
152
    heightBefore = null;
153
    requestAnimationFrame(() => row && settleHeight(row, from));
154
  });
155
156
  function sendLabel(state: SendState): string {
157
    if (state.kind === 'Failed') return state.will_retry ? 'failed — will retry' : 'failed — not delivered';
158
    return '';
159
  }
160
161
  $: selected = $selectedRow === owner;
162
  $: showActions = !readOnly && interactive && !!event.event_id && (selected || pickerOpen || ($selectedRow === null && (hovered || focused)));
163
164
  $: syncSelectionListeners(selected);
165
  $: syncPickerListeners(pickerOpen);
166
167
  const pickerLayer = instanceLayerId('reaction-picker');
168
  const dismissPicker = () => (pickerOpen = false);
169
  $: backStack.sync(pickerLayer, pickerOpen, dismissPicker);
170
  onDestroy(() => backStack.sync(pickerLayer, false, dismissPicker));
171
172
  function onEscape(e: KeyboardEvent) {
173
    if (e.key === 'Escape') select(false);
174
  }
175
176
  let selectionAttached = false;
177
  let pickerAttached = false;
178
179
  function syncSelectionListeners(on: boolean) {
180
    if (on === selectionAttached) return;
181
    selectionAttached = on;
182
    if (on) {
183
      window.addEventListener('pointerdown', deselectOutside);
184
      window.addEventListener('keydown', onEscape);
185
    } else {
186
      window.removeEventListener('pointerdown', deselectOutside);
187
      window.removeEventListener('keydown', onEscape);
188
    }
189
  }
190
191
  function syncPickerListeners(on: boolean) {
192
    if (on === pickerAttached) return;
193
    pickerAttached = on;
194
    const op = on ? 'addEventListener' : 'removeEventListener';
195
    window[op]('scroll', closeOnScroll, true);
196
    window[op]('resize', closePicker);
197
  }
198
199
  onDestroy(() => {
200
    syncSelectionListeners(false);
201
    syncPickerListeners(false);
202
    selectedRow.update((o) => (o === owner ? null : o));
203
  });
204
205
  function pinReactors(key: string) {
206
    reactorPinned = true;
207
    reactorKey = key;
208
  }
209
210
  function unpinReactors() {
211
    if (!reactorPinned) return;
212
    reactorPinned = false;
213
    reactorKey = null;
214
  }
215
216
  function holdMore(p: { clientX: number; clientY: number }) {
217
    if (readOnly || !interactive || !event.event_id) return;
218
    select(true);
219
    onMore?.(event, p.clientX, p.clientY);
220
  }
221
222
  function select(on: boolean) {
223
    selectedRow.update((o) => (on ? owner : o === owner ? null : o));
224
  }
225
226
  function toggleSelected(e: MouseEvent) {
227
    if (readOnly || !interactive || (e.target as Element).closest('a, button, input, video, audio, .picker-pop')) return;
228
    select(!selected);
229
  }
230
231
  function onRowKeydown(e: KeyboardEvent) {
232
    if (e.target !== row || readOnly || !interactive) return;
233
    if (e.key === 'Enter' || e.key === ' ') {
234
      e.preventDefault();
235
      select(!selected);
236
    }
237
  }
238
239
  function onFocusOut(e: FocusEvent) {
240
    if (!row.contains(e.relatedTarget as Node | null)) focused = false;
241
  }
242
243
  function deselectOutside(e: PointerEvent) {
244
    if (selected && !pickerOpen && !row.contains(e.target as Node)) select(false);
245
  }
246
247
  function openPicker(e: MouseEvent) {
248
    if (pickerOpen) {
249
      pickerOpen = false;
250
      return;
251
    }
252
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
253
    const height = Math.min(PICKER_HEIGHT, window.innerHeight - 2 * PICKER_MARGIN);
254
    const below = window.innerHeight - rect.bottom - PICKER_MARGIN >= height;
255
    const top = below ? rect.bottom + 4 : Math.max(PICKER_MARGIN, rect.top - height - 4);
256
    const maxLeft = window.innerWidth - PICKER_WIDTH - PICKER_MARGIN;
257
    const left = Math.max(PICKER_MARGIN, Math.min(rect.right - PICKER_WIDTH, maxLeft));
258
    pickerStyle = `top:${top}px;left:${left}px;height:${height}px`;
259
    select(true);
260
    pickerOpen = true;
261
  }
262
263
  function closePicker() {
264
    pickerOpen = false;
265
  }
266
267
  function isImageKey(key: string): boolean {
268
    return key.startsWith('mxc://') || packs.some((p) => p.images.some((i) => i.reaction_key === key));
269
  }
270
271
  function react(key: string, shortcode: string | null) {
272
    if (shortcode && isImageKey(key)) onReact(event.event_id ?? '', key, shortcode);
273
    else onReact(event.event_id ?? '', key);
274
  }
275
276
  function reply() {
277
    if (!event.event_id || !onReply) return;
278
    onReply({
279
      event_id: event.event_id,
280
      details: { kind: 'Ready', sender: event.sender, content: event.content, timestamp_ms: event.timestamp_ms }
281
    });
282
  }
283
284
  $: editableBody =
285
    event.own && event.editable && event.event_id && event.content.kind === 'Message' && event.content.message.kind === 'Text'
286
      ? event.content.message.body
287
      : null;
288
289
  function edit() {
290
    if (!event.event_id || editableBody === null || !onEdit) return;
291
    onEdit(event.event_id, editableBody);
292
  }
293
294
  function reactorNames(senders: string[]): string {
295
    const names = senders.map((id) => people[id]?.name ?? id);
296
    if (names.length <= 12) return names.join(', ');
297
    return `${names.slice(0, 12).join(', ')} and ${names.length - 12} more`;
298
  }
299
300
  function pick(key: string, shortcode: string | null) {
301
    pickerOpen = false;
302
    react(key, shortcode);
303
  }
304
305
  function closeOnScroll(e: Event) {
306
    if (pickerOpen && !pickerPop?.contains(e.target as Node)) pickerOpen = false;
307
  }
308
309
  function actorLabel(userId: string, name: string | null): string {
310
    return name ?? people[userId]?.name ?? userId;
311
  }
312
313
  function replyPreview(content: TimelineContent): string {
314
    if (content.kind === 'Message') return stripMarkdownPills(content.message.body).text;
315
    if (content.kind === 'Sticker') return content.body || 'Sticker';
316
    if (content.kind === 'Poll') return `Poll: ${content.question}`;
317
    if (content.kind === 'Redacted') return 'Message deleted';
318
    if (content.kind === 'UnableToDecrypt') return 'Unable to decrypt';
319
    return systemLine(content);
320
  }
321
322
  function systemLine(content: TimelineContent, actor = displayName): string {
323
    switch (content.kind) {
324
      case 'Redacted':
325
        return 'Message deleted';
326
      case 'UnableToDecrypt':
327
        return `Message from ${actor} could not be decrypted`;
328
      case 'Membership': {
329
        const who = actorLabel(content.user_id, content.display_name);
330
        return `${who} ${MEMBERSHIP_LABELS[content.change] ?? 'updated their membership'}`;
331
      }
332
      case 'Profile': {
333
        const who = actorLabel(content.user_id, null);
334
        const parts: string[] = [];
335
        if (content.display_name) {
336
          parts.push(
337
            content.display_name.new
338
              ? `changed their display name to "${content.display_name.new}"`
339
              : 'removed their display name'
340
          );
341
        }
342
        if (content.avatar) parts.push('changed their avatar');
343
        return `${who} ${parts.length > 0 ? parts.join(' and ') : 'updated their profile'}`;
344
      }
345
      case 'RoomName':
346
        return content.name
347
          ? `${actor} changed the room name to "${content.name}"`
348
          : `${actor} removed the room name`;
349
      case 'RoomTopic':
350
        return content.topic
351
          ? `${actor} changed the topic to "${content.topic}"`
352
          : `${actor} removed the topic`;
353
      case 'RoomAvatar':
354
        return content.avatar ? `${actor} changed the room avatar` : `${actor} removed the room avatar`;
355
      case 'EncryptionEnabled':
356
        return `${actor} enabled encryption in this room`;
357
      case 'RoomCreated':
358
        return `${actor} created the room`;
359
      case 'RoomUpgraded':
360
        return `${actor} upgraded the room to a new version`;
361
      case 'OtherState':
362
        return `${actor} ${STATE_LABELS[content.event_type] ?? `sent a state event (${content.event_type})`}`;
363
      case 'Other':
364
        return `${actor} sent an event (${content.event_type})`;
365
      default:
366
        return actor;
367
    }
368
  }
369
</script>
370
371
<!-- svelte-ignore a11y_no_noninteractive_tabindex a11y_no_noninteractive_element_interactions -->
372
<div
373
  class="msg"
374
  role="group"
375
  tabindex={interactive && !readOnly ? 0 : undefined}
376
  class:own={event.own}
377
  class:editing
378
  class:mentioned={mentionsMe || keywordHit}
379
  class:system={!interactive}
380
  class:has-readers={interactive && readers.length > 0}
381
  class:selected
382
  data-item={itemId}
383
  data-event={event.event_id}
384
  in:rowIn|global
385
  out:rowOut|global
386
  bind:this={row}
387
  on:click={toggleSelected}
388
  use:longpress={{ on: holdMore, allowSelection: true, ignore: 'a, button, input, img, video, audio, .text, .picker-pop' }}
389
  on:keydown={onRowKeydown}
390
  on:pointerenter={(e) => (hovered = e.pointerType === 'mouse')}
391
  on:pointerleave={() => (hovered = false)}
392
  on:focusin={() => (focused = true)}
393
  on:focusout={onFocusOut}
394
>
395
  {#if showActions && event.event_id}
396
    {@const quickRows = quickGroups(quickReactions)}
397
    <div class="actions" role="toolbar" aria-label={`Actions for message from ${displayName}`}>
398
      <div class="quick" style={`--quick-cols:${quickColumns(quickRows, QUICK_REACTIONS_PER_ROW)}`}>
399
      {#each quickRows as group, g}
400
        {#each group as r, i (r.key)}
401
          {@const label = r.shortcode ? `:${r.shortcode}:` : r.key}
402
          <button
403
            type="button"
404
            class:group-start={g > 0 && i === 0}
405
            title={`React ${label}`}
406
            aria-label={`React ${label} to message from ${displayName}`}
407
            disabled={reacting}
408
            on:click={() => react(r.key, r.shortcode)}
409
          >
410
            {#if r.key.startsWith('mxc://')}
411
              <img class="emote" src={mediaUrl(r.key, 64) ?? ''} alt="" />
412
            {:else}
413
              <Emoji emoji={r.key} size={18} />
414
            {/if}
415
          </button>
416
        {/each}
417
      {/each}
418
      </div>
419
      <button
420
        type="button"
421
        title="Add reaction"
422
        aria-label={`Add reaction to message from ${displayName}`}
423
        aria-haspopup="dialog"
424
        aria-expanded={pickerOpen}
425
        on:pointerdown|stopPropagation
426
        on:click={openPicker}
427
      >
428
        ☺+
429
      </button>
430
      {#if onCloneSticker && event.content.kind === 'Sticker'}
431
        {@const stickerBody = event.content.body}
432
        {@const stickerId = event.event_id}
433
        <button
434
          type="button"
435
          title="Clone sticker"
436
          aria-label="Clone sticker to one of your packs"
437
          on:click|stopPropagation={(ev) => onCloneSticker?.(stickerId, stickerBody, ev.clientX, ev.clientY)}
438
        >
439
          ⧉
440
        </button>
441
      {/if}
442
      {#if onReply}
443
        <button
444
          type="button"
445
          title="Reply"
446
          aria-label={`Reply to message from ${displayName}`}
447
          on:click|stopPropagation={reply}
448
        >
449
          ↩
450
        </button>
451
      {/if}
452
      {#if threadRoot}
453
        {@const root = threadRoot}
454
        <button
455
          type="button"
456
          title="Reply in thread"
457
          aria-label={`Reply in thread to message from ${displayName}`}
458
          on:click|stopPropagation={() => onOpenThread?.(root)}
459
        >
460
          <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M2.5 3h11v7h-6l-3 3v-3h-2z" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/><path d="M5 6h6M5 8h4" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
461
        </button>
462
      {/if}
463
      {#if onEdit && editableBody !== null}
464
        <button type="button" title="Edit" aria-label="Edit your message" on:click|stopPropagation={edit}>
465
          ✎
466
        </button>
467
      {/if}
468
      {#if onMore}
469
        <button
470
          type="button"
471
          title="More"
472
          aria-label={`More actions for message from ${displayName}`}
473
          aria-haspopup="menu"
474
          on:click|stopPropagation={(ev) => onMore?.(event, ev.clientX, ev.clientY)}
475
        >
476
          ⋯
477
        </button>
478
      {/if}
479
    </div>
480
    {#if pickerOpen}
481
      <div class="picker-pop" style={pickerStyle} bind:this={pickerPop}>
482
        <ReactionPicker {packs} quick={quickReactions} onPick={pick} {onQuickChange} onClose={closePicker} />
483
      </div>
484
    {/if}
485
  {/if}
486
  {#if event.reply_to}
487
    {@const target = event.reply_to.event_id}
488
    <div class="reply-line" class:linked={showSender}>
489
      <button
490
        type="button"
491
        class="reply-quote"
492
        disabled={!onJump}
493
        title="Jump to the original message"
494
        on:click|stopPropagation={() => onJump?.(target)}
495
      >
496
        {#if event.reply_to.details.kind === 'Ready'}
497
          <span class="reply-sender"><EmojiText text={event.reply_to.details.sender.display_name ?? people[event.reply_to.details.sender.user_id]?.name ?? senderLabel(event.reply_to.details.sender)} /></span>
498
          <span class="reply-text"><EmojiText text={replyPreview(event.reply_to.details.content)} /></span>
499
        {:else if event.reply_to.details.kind === 'Pending'}
500
          Loading reply…
501
        {:else}
502
          Reply unavailable
503
        {/if}
504
      </button>
505
    </div>
506
  {/if}
507
  {#if showSender}
508
    <button
509
      type="button"
510
      class="user-hit"
511
      disabled={!onUser}
512
      tabindex="-1"
513
      aria-hidden="true"
514
      on:click|stopPropagation={(ev) => openUser(ev, false)}
515
      on:contextmenu|preventDefault|stopPropagation={(ev) => openUser(ev, true)}
516
      use:longpress={(ev) => openUser(ev, true)}
517
    >
518
      {#if senderAvatar}
519
        <MxcAvatar mxc={senderAvatar} label={name} size={34} eager />
520
      {:else}
521
        <span class="avatar" style={`background:hsl(${senderHue(event.sender.user_id)} 35% 32%)`}>
522
          <span><EmojiText text={initialsOf(name)} /></span>
523
        </span>
524
      {/if}
525
    </button>
526
  {:else}
527
    <div class="avatar-spacer" aria-hidden="true">
528
      <span class="hover-time">{formatClock(event.timestamp_ms)}</span>
529
    </div>
530
  {/if}
531
  <div class="msg-body">
532
    {#if showSender}
533
      <div class="msg-head">
534
        <button
535
          type="button"
536
          class="sender"
537
          disabled={!onUser}
538
          style={`color:hsl(${senderHue(event.sender.user_id)} 70% var(--name-lightness))`}
539
          on:click|stopPropagation={(ev) => openUser(ev, false)}
540
          on:contextmenu|preventDefault|stopPropagation={(ev) => openUser(ev, true)}
541
          use:longpress={(ev) => openUser(ev, true)}
542
        >
543
          <EmojiText text={displayName} />
544
        </button>
545
        {#if lag}
546
          <span class="federation-lag" title="Possibly delayed by federation" aria-label={`Arrived ${lag} late, possibly delayed by federation`}>
547
            <span aria-hidden="true">◷</span><span>{lag}</span>
548
          </span>
549
        {/if}
550
        <time class="time" datetime={new Date(event.timestamp_ms).toISOString()}>
551
          {formatDay(event.timestamp_ms)} {formatClock(event.timestamp_ms)}
552
        </time>
553
        {#if event.content.kind === 'Message' && event.content.message.edited}
554
          <span class="edited" title="Edited" transition:dissolve>(edited)</span>
555
        {/if}
556
      </div>
557
    {/if}
558
559
    {#if event.content.kind === 'Message'}
560
      {@const m = event.content.message}
561
      {#if stripped.text}
562
        <div class="text" class:emote={m.kind === 'Emote'} class:notice={m.kind === 'Notice' || m.kind === 'ServerNotice'}>{#if m.kind === 'Emote'}* <EmojiText text={displayName} /> {/if}<MessageText text={stripped.text} html={m.formatted_body} jumbo={m.kind === 'Text'} {mentions} {self} {nameOf} />{#if m.edited && !showSender}<span class="edited" title="Edited" transition:dissolve>(edited)</span>{/if}</div>
563
      {/if}
564
      {#if m.media}
565
        <MediaAttachmentView attachment={m.media} />
566
      {/if}
567
      {#if cards.length > 0}
568
        <div class="link-previews" in:dissolve>
569
          {#each cards as card (card.link.href)}
570
            <div in:dissolve><LinkCard link={card.link} preview={card.preview} /></div>
571
          {/each}
572
        </div>
573
      {/if}
574
    {:else if event.content.kind === 'Sticker'}
575
      {#if event.content.media}
576
        <MediaAttachmentView attachment={event.content.media} />
577
      {:else if event.content.body}<p class="text"><EmojiText text={event.content.body} /></p>{/if}
578
    {:else if event.content.kind === 'Poll'}
579
      <p class="text"><EmojiText text={`📊 ${event.content.question}`} /></p>
580
    {:else}
581
      <p class="system-line"><EmojiText text={systemLine(event.content, displayName)} /></p>
582
    {/if}
583
584
    {#if interactive && event.reactions.length > 0}
585
      <div class="reactions" aria-label="Reactions" transition:expand>
586
        {#each event.reactions as r (r.key)}
587
          <button
588
            type="button"
589
            class="reaction"
590
            transition:expand={{ axis: 'x' }}
591
            class:mine={r.own}
592
            aria-label={`${r.shortcode ? `:${r.shortcode}:` : r.key.startsWith('mxc://') ? 'custom emote' : r.key}, ${r.count} reaction${r.count === 1 ? '' : 's'}`}
593
            disabled={readOnly || !event.event_id || reacting}
594
            aria-describedby={reactorKey === r.key ? `${itemId}-reactors-${r.key}` : undefined}
595
            on:pointerenter={(e) => e.pointerType === 'mouse' && (reactorKey = r.key)}
596
            on:pointerleave={() => !reactorPinned && (reactorKey = null)}
597
            use:longpress={() => pinReactors(r.key)}
598
            on:focus={() => (reactorKey = r.key)}
599
            on:blur={() => !reactorPinned && (reactorKey = null)}
600
            on:click={() => event.event_id && onReact(event.event_id, r.key)}
601
          >
602
            {#if r.image}
603
              <img class="emote" src={messageMediaUrl(r.image, 'Thumbnail')} alt={r.shortcode ?? ''} title={r.shortcode ?? ''} />
604
            {:else if r.key.startsWith('mxc://')}
605
              <img class="emote" src={mediaUrl(r.key, 64) ?? ''} alt="" />
606
            {:else}
607
              <Emoji emoji={r.key} size={16} />
608
            {/if}
609
            <span class="count">{r.count}</span>
610
            {#if reactorKey === r.key}
611
            <span class="reactors" role="tooltip" id={`${itemId}-reactors-${r.key}`}>
612
              <span class="reactors-key"><EmojiText text={r.shortcode ? `:${r.shortcode}:` : r.key.startsWith('mxc://') ? 'custom emote' : r.key} /></span>
613
              <EmojiText text={reactorNames(r.senders)} />
614
            </span>
615
            {/if}
616
          </button>
617
        {/each}
618
      </div>
619
    {/if}
620
    {#if threadRoot && threadReplies > 0}
621
      {@const root = threadRoot}
622
      {@const latest = event.thread_summary?.latest_event_timestamp_ms ?? null}
623
      <button type="button" class="thread-chip" transition:expand on:click|stopPropagation={() => onOpenThread?.(root)}>
624
        <span class="thread-count">{threadReplies} {threadReplies === 1 ? 'reply' : 'replies'}</span>
625
        {#if latest}<time datetime={new Date(latest).toISOString()}>{formatDay(latest)} {formatClock(latest)}</time>{/if}
626
      </button>
627
    {/if}
628
    {#if sent}<span class="sent-tick" title="Sent" aria-label="Sent" transition:dissolve>✓</span>{/if}
629
    {#if interactive && sendLabel(event.send_state)}
630
      <div class="msg-foot" transition:expand>
631
        <span class="sendstate" class:failed={event.send_state.kind === 'Failed'}>{sendLabel(event.send_state)}</span>
632
      </div>
633
    {/if}
634
    {#if interactive && readers.length > 0}
635
      {@const seenBy = `Seen by ${readers.map((r) => r.name).join(', ')}`}
636
      <div class="readby" transition:dissolve title={seenBy} aria-label={seenBy} role="img">
637
        {#each readers.slice(0, MAX_READERS) as r (r.user_id)}
638
          <MxcAvatar mxc={r.avatar} label={r.name} size={16} />
639
        {/each}
640
        {#if readers.length > MAX_READERS}<span class="more">+{readers.length - MAX_READERS}</span>{/if}
641
      </div>
642
    {/if}
643
  </div>
644
</div>
645
646
<svelte:window on:pointerdown={unpinReactors} />
647
648
<style>
649
  .msg { position: relative; display: flex; flex-wrap: wrap; gap: 0 10px; padding: var(--msg-gap, 3px) 0; }
650
  .reply-line { position: relative; flex: 0 0 100%; min-width: 0; padding-left: 44px; }
651
  .reply-line.linked::before { content: ''; position: absolute; left: 16px; top: 50%; bottom: -3px; width: 24px; border-left: 2px solid var(--border); border-top: 2px solid var(--border); border-top-left-radius: 8px; pointer-events: none; }
652
  .msg.selected { background: var(--hover-faint); }
653
  .msg.selected .hover-time { opacity: 1; }
654
  @media (hover: hover) {
655
    .msg:hover { background: var(--hover-faint); }
656
    .msg:hover .hover-time { opacity: 1; }
657
  }
658
  .msg-foot { display: flex; align-items: center; gap: 8px; }
659
  .thread-chip { display: inline-flex; align-items: baseline; gap: 8px; margin-top: 4px; padding: 3px 8px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-soft); color: var(--text); font: inherit; font-size: 12px; cursor: pointer; transition: border-color var(--pop), background var(--pop); }
660
  .thread-chip:hover { border-color: var(--accent); background: var(--hover-faint); }
661
  .thread-count { color: var(--accent); font-weight: 650; }
662
  .thread-chip time { color: var(--muted); font-size: 11px; }
663
  .sendstate { font-size: 11px; color: var(--muted); }
664
  .sent-tick { position: absolute; right: 12px; bottom: 4px; font-size: 11px; color: var(--muted); }
665
  .sendstate.failed { color: var(--danger); }
666
  .link-previews { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; max-width: 420px; }
667
  .avatar {
668
    flex: none;
669
    width: 34px; height: 34px;
670
    border-radius: 50%;
671
    display: grid; place-items: center;
672
    font-size: 12px; font-weight: 700; color: #fff;
673
  }
674
  .avatar-spacer { flex: none; width: 34px; padding-top: 2px; text-align: center; }
675
  .hover-time { opacity: 0; font-size: 10.5px; color: var(--muted); }
676
  .msg-body { min-width: 0; flex: 1; transition: padding-right var(--pop); }
677
  .msg-head { display: flex; align-items: baseline; gap: 8px; }
678
  .federation-lag { display: inline-flex; align-items: center; gap: 3px; color: var(--danger); font-size: 11px; font-weight: 650; }
679
  .federation-lag > span:last-child { display: inline-grid; place-items: center; min-width: 24px; height: 18px; padding: 0 4px; border: 1px solid currentColor; border-radius: 999px; }
680
  .sender { font-weight: 650; font-size: 13.5px; padding: 0; border: none; background: none; font-family: inherit; text-align: left; cursor: pointer; }
681
  .sender:hover { text-decoration: underline; }
682
  .user-hit { flex: none; align-self: flex-start; padding: 0; border: none; background: none; border-radius: 50%; cursor: pointer; }
683
  .time, .edited { color: var(--muted); font-size: 11.5px; }
684
  .text .edited { margin-left: 6px; }
685
  .msg.editing { background: color-mix(in srgb, var(--accent) 10%, transparent); }
686
  .msg.mentioned { background: color-mix(in srgb, var(--warn) 8%, transparent); box-shadow: inset 2px 0 0 var(--warn); }
687
  .reply-quote {
688
    display: flex; gap: 6px; align-items: baseline;
689
    max-width: min(100%, 520px);
690
    border: none;
691
    border-left: 2px solid var(--accent);
692
    padding: 2px 8px;
693
    margin: 2px 0 4px;
694
    color: var(--muted);
695
    font-size: 12.5px;
696
    text-align: left;
697
    background: var(--bg-soft);
698
    border-radius: 0 var(--r-sm) var(--r-sm) 0;
699
    cursor: pointer;
700
  }
701
  .reply-quote:disabled { cursor: default; }
702
  .reply-quote:hover:not(:disabled) { color: var(--text); }
703
  .reply-sender { flex: none; font-weight: 650; }
704
  .reply-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
705
  :global(.msg.flash) { animation: reply-flash 1.2s ease-out; }
706
  @keyframes -global-reply-flash { from { background: color-mix(in srgb, var(--accent) 22%, transparent); } }
707
  .text {
708
    margin: 1px 0 2px;
709
    font-size: 14px;
710
    line-height: var(--msg-line-height, 1.5);
711
    white-space: pre-wrap;
712
    overflow-wrap: anywhere;
713
  }
714
  .text.emote { font-style: italic; color: var(--muted); }
715
  .text.notice { color: var(--muted); }
716
  .system-line { color: var(--muted); font-size: 12.5px; font-style: italic; margin: 1px 0; }
717
  .msg.system { opacity: 0.85; --msg-gap: 1.5px; }
718
  .msg.system .avatar-spacer { height: 0; padding-top: 0; }
719
  .reactions { display: flex; flex-wrap: wrap; gap: 4px; margin-top: max(4px, var(--msg-gap, 3px)); }
720
  .reaction {
721
    display: inline-flex; align-items: center; gap: 4px;
722
    background: var(--bg-soft);
723
    border: 1px solid var(--border);
724
    border-radius: var(--r-sm);
725
    padding: 1px 8px;
726
    font-size: 13px;
727
    color: var(--text);
728
    cursor: pointer;
729
  }
730
  .reaction { position: relative; }
731
  .reactors {
732
    position: absolute;
733
    left: 0;
734
    bottom: calc(100% + 6px);
735
    z-index: 15;
736
    display: block;
737
    width: max-content;
738
    max-width: 260px;
739
    padding: 6px 9px;
740
    border: 1px solid var(--border);
741
    border-radius: var(--r-md);
742
    background: var(--panel-2);
743
    box-shadow: 0 6px 18px rgb(0 0 0 / 0.3);
744
    color: var(--text);
745
    font-size: 12px;
746
    line-height: 1.35;
747
    text-align: left;
748
    white-space: normal;
749
    pointer-events: none;
750
  }
751
  .reactors-key { display: block; color: var(--muted); font-size: 11px; }
752
  .reaction.mine { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, transparent); }
753
  .reaction:disabled { cursor: default; opacity: 0.85; }
754
  .msg.has-readers .msg-body { padding-right: 72px; }
755
  .readby { position: absolute; right: 12px; bottom: 4px; display: flex; align-items: center; }
756
  .readby > :global(* + *) { margin-left: -4px; }
757
  .readby :global(.mxc-avatar), .readby :global(.mxc-fallback) { box-shadow: 0 0 0 1.5px var(--bg); }
758
  .readby .more { margin-left: 3px; font-size: 10.5px; color: var(--muted); }
759
  .actions {
760
    position: absolute; top: -12px; right: 10px; z-index: 2;
761
    display: flex; align-items: flex-start; gap: 2px;
762
    padding: 2px;
763
    background: var(--bg-soft);
764
    border: 1px solid var(--border);
765
    border-radius: var(--r-md);
766
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
767
  }
768
  .quick { display: grid; grid-template-columns: repeat(var(--quick-cols, 8), auto); gap: 2px; }
769
  .quick:empty { display: none; }
770
  .quick .group-start { grid-column-start: 1; }
771
  .actions button {
772
    background: transparent;
773
    border: 1px solid transparent;
774
    border-radius: var(--r-sm);
775
    cursor: pointer;
776
    font-size: 14px;
777
    padding: 1px 5px;
778
  }
779
  .actions button:hover:not(:disabled) { border-color: var(--border); background: var(--hover); }
780
  .actions button:disabled { opacity: 0.4; cursor: default; }
781
  .emote { width: 1.3em; height: 1.3em; object-fit: contain; vertical-align: middle; }
782
  @media (pointer: coarse) {
783
    .actions button { min-width: 36px; min-height: 40px; font-size: 16px; }
784
    .actions { top: auto; bottom: calc(100% - 18px); right: 6px; flex-wrap: wrap; justify-content: flex-end; max-width: calc(100% - 12px); }
785
    .reaction::after, .sender::after, .thread-chip::after { content: ''; position: absolute; inset: -9px -2px; }
786
    .sender, .thread-chip { position: relative; }
787
  }
788
  .picker-pop { position: fixed; z-index: 60; width: 320px; max-width: calc(100vw - 16px); animation: pop-in var(--pop); }
789
</style>