atagen

malice

public
Star0
Watch0
e590609b63434b8b595b383f8124dea45191bd6e
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/MessageRow.svelteSvelte801 lines33.5 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 contextMore(ev: MouseEvent) {
223
    if (ev.defaultPrevented || ev.shiftKey || !onMore || readOnly || !interactive || !event.event_id) return;
224
    if ((ev.target as Element).closest('a[href], img, video, audio, input, textarea, .picker-pop')) return;
225
    const selection = window.getSelection();
226
    if (selection && !selection.isCollapsed && row.contains(selection.anchorNode)) return;
227
    ev.preventDefault();
228
    holdMore(ev);
229
  }
230
231
  function select(on: boolean) {
232
    selectedRow.update((o) => (on ? owner : o === owner ? null : o));
233
  }
234
235
  function toggleSelected(e: MouseEvent) {
236
    if (readOnly || !interactive || (e.target as Element).closest('a, button, input, video, audio, .picker-pop')) return;
237
    select(!selected);
238
  }
239
240
  function onRowKeydown(e: KeyboardEvent) {
241
    if (e.target !== row || readOnly || !interactive) return;
242
    if (e.key === 'Enter' || e.key === ' ') {
243
      e.preventDefault();
244
      select(!selected);
245
    }
246
  }
247
248
  function onFocusOut(e: FocusEvent) {
249
    if (!row.contains(e.relatedTarget as Node | null)) focused = false;
250
  }
251
252
  function deselectOutside(e: PointerEvent) {
253
    if (selected && !pickerOpen && !row.contains(e.target as Node)) select(false);
254
  }
255
256
  function openPicker(e: MouseEvent) {
257
    if (pickerOpen) {
258
      pickerOpen = false;
259
      return;
260
    }
261
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
262
    const height = Math.min(PICKER_HEIGHT, window.innerHeight - 2 * PICKER_MARGIN);
263
    const below = window.innerHeight - rect.bottom - PICKER_MARGIN >= height;
264
    const top = below ? rect.bottom + 4 : Math.max(PICKER_MARGIN, rect.top - height - 4);
265
    const maxLeft = window.innerWidth - PICKER_WIDTH - PICKER_MARGIN;
266
    const left = Math.max(PICKER_MARGIN, Math.min(rect.right - PICKER_WIDTH, maxLeft));
267
    pickerStyle = `top:${top}px;left:${left}px;height:${height}px`;
268
    select(true);
269
    pickerOpen = true;
270
  }
271
272
  function closePicker() {
273
    pickerOpen = false;
274
  }
275
276
  function isImageKey(key: string): boolean {
277
    return key.startsWith('mxc://') || packs.some((p) => p.images.some((i) => i.reaction_key === key));
278
  }
279
280
  function react(key: string, shortcode: string | null) {
281
    if (shortcode && isImageKey(key)) onReact(event.event_id ?? '', key, shortcode);
282
    else onReact(event.event_id ?? '', key);
283
    select(false);
284
  }
285
286
  function reply() {
287
    if (!event.event_id || !onReply) return;
288
    onReply({
289
      event_id: event.event_id,
290
      details: { kind: 'Ready', sender: event.sender, content: event.content, timestamp_ms: event.timestamp_ms }
291
    });
292
    select(false);
293
  }
294
295
  $: editableBody =
296
    event.own && event.editable && event.event_id && event.content.kind === 'Message' && event.content.message.kind === 'Text'
297
      ? event.content.message.body
298
      : null;
299
300
  function edit() {
301
    if (!event.event_id || editableBody === null || !onEdit) return;
302
    onEdit(event.event_id, editableBody);
303
    select(false);
304
  }
305
306
  function reactorNames(senders: string[]): string {
307
    const names = senders.map((id) => people[id]?.name ?? id);
308
    if (names.length <= 12) return names.join(', ');
309
    return `${names.slice(0, 12).join(', ')} and ${names.length - 12} more`;
310
  }
311
312
  function pick(key: string, shortcode: string | null) {
313
    pickerOpen = false;
314
    react(key, shortcode);
315
  }
316
317
  function closeOnScroll(e: Event) {
318
    if (pickerOpen && !pickerPop?.contains(e.target as Node)) pickerOpen = false;
319
  }
320
321
  function actorLabel(userId: string, name: string | null): string {
322
    return name ?? people[userId]?.name ?? userId;
323
  }
324
325
  function replyPreview(content: TimelineContent): string {
326
    if (content.kind === 'Message') return stripMarkdownPills(content.message.body).text;
327
    if (content.kind === 'Sticker') return content.body || 'Sticker';
328
    if (content.kind === 'Poll') return `Poll: ${content.question}`;
329
    if (content.kind === 'Redacted') return 'Message deleted';
330
    if (content.kind === 'UnableToDecrypt') return 'Unable to decrypt';
331
    return systemLine(content);
332
  }
333
334
  function systemLine(content: TimelineContent, actor = displayName): string {
335
    switch (content.kind) {
336
      case 'Redacted':
337
        return 'Message deleted';
338
      case 'UnableToDecrypt':
339
        return `Message from ${actor} could not be decrypted`;
340
      case 'Membership': {
341
        const who = actorLabel(content.user_id, content.display_name);
342
        return `${who} ${MEMBERSHIP_LABELS[content.change] ?? 'updated their membership'}`;
343
      }
344
      case 'Profile': {
345
        const who = actorLabel(content.user_id, null);
346
        const parts: string[] = [];
347
        if (content.display_name) {
348
          parts.push(
349
            content.display_name.new
350
              ? `changed their display name to "${content.display_name.new}"`
351
              : 'removed their display name'
352
          );
353
        }
354
        if (content.avatar) parts.push('changed their avatar');
355
        return `${who} ${parts.length > 0 ? parts.join(' and ') : 'updated their profile'}`;
356
      }
357
      case 'RoomName':
358
        return content.name
359
          ? `${actor} changed the room name to "${content.name}"`
360
          : `${actor} removed the room name`;
361
      case 'RoomTopic':
362
        return content.topic
363
          ? `${actor} changed the topic to "${content.topic}"`
364
          : `${actor} removed the topic`;
365
      case 'RoomAvatar':
366
        return content.avatar ? `${actor} changed the room avatar` : `${actor} removed the room avatar`;
367
      case 'EncryptionEnabled':
368
        return `${actor} enabled encryption in this room`;
369
      case 'RoomCreated':
370
        return `${actor} created the room`;
371
      case 'RoomUpgraded':
372
        return `${actor} upgraded the room to a new version`;
373
      case 'OtherState':
374
        return `${actor} ${STATE_LABELS[content.event_type] ?? `sent a state event (${content.event_type})`}`;
375
      case 'Other':
376
        return `${actor} sent an event (${content.event_type})`;
377
      default:
378
        return actor;
379
    }
380
  }
381
</script>
382
383
<!-- svelte-ignore a11y_no_noninteractive_tabindex a11y_no_noninteractive_element_interactions -->
384
<div
385
  class="msg"
386
  role="group"
387
  tabindex={interactive && !readOnly ? 0 : undefined}
388
  class:own={event.own}
389
  class:editing
390
  class:mentioned={mentionsMe || keywordHit}
391
  class:system={!interactive}
392
  class:selected
393
  data-item={itemId}
394
  data-event={event.event_id}
395
  in:rowIn|global
396
  out:rowOut|global
397
  bind:this={row}
398
  on:click={toggleSelected}
399
  on:contextmenu={contextMore}
400
  use:longpress={{ on: holdMore, allowSelection: true, ignore: 'a, button, input, img, video, audio, .text, .picker-pop' }}
401
  on:keydown={onRowKeydown}
402
  on:pointerenter={(e) => (hovered = e.pointerType === 'mouse')}
403
  on:pointerleave={() => (hovered = false)}
404
  on:focusin={() => (focused = true)}
405
  on:focusout={onFocusOut}
406
>
407
  {#if showActions && event.event_id}
408
    {@const quickRows = quickGroups(quickReactions)}
409
    <div class="actions" role="toolbar" aria-label={`Actions for message from ${displayName}`}>
410
      <div class="quick" style={`--quick-cols:${quickColumns(quickRows, QUICK_REACTIONS_PER_ROW)}`}>
411
      {#each quickRows as group, g}
412
        {#each group as r, i (r.key)}
413
          {@const label = r.shortcode ? `:${r.shortcode}:` : r.key}
414
          <button
415
            type="button"
416
            class:group-start={g > 0 && i === 0}
417
            title={`React ${label}`}
418
            aria-label={`React ${label} to message from ${displayName}`}
419
            disabled={reacting}
420
            on:click={() => react(r.key, r.shortcode)}
421
          >
422
            {#if r.key.startsWith('mxc://')}
423
              <img class="emote" src={mediaUrl(r.key, 64) ?? ''} alt="" />
424
            {:else}
425
              <Emoji emoji={r.key} size={18} />
426
            {/if}
427
          </button>
428
        {/each}
429
      {/each}
430
      </div>
431
      <button
432
        type="button"
433
        title="Add reaction"
434
        aria-label={`Add reaction to message from ${displayName}`}
435
        aria-haspopup="dialog"
436
        aria-expanded={pickerOpen}
437
        on:pointerdown|stopPropagation
438
        on:click={openPicker}
439
      >
440
        ☺+
441
      </button>
442
      {#if onCloneSticker && event.content.kind === 'Sticker'}
443
        {@const stickerBody = event.content.body}
444
        {@const stickerId = event.event_id}
445
        <button
446
          type="button"
447
          title="Clone sticker"
448
          aria-label="Clone sticker to one of your packs"
449
          on:click|stopPropagation={(ev) => onCloneSticker?.(stickerId, stickerBody, ev.clientX, ev.clientY)}
450
        >
451
          ⧉
452
        </button>
453
      {/if}
454
      {#if onReply}
455
        <button
456
          type="button"
457
          title="Reply"
458
          aria-label={`Reply to message from ${displayName}`}
459
          on:click|stopPropagation={reply}
460
        >
461
          ↩
462
        </button>
463
      {/if}
464
      {#if threadRoot}
465
        {@const root = threadRoot}
466
        <button
467
          type="button"
468
          title="Reply in thread"
469
          aria-label={`Reply in thread to message from ${displayName}`}
470
          on:click|stopPropagation={() => onOpenThread?.(root)}
471
        >
472
          <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>
473
        </button>
474
      {/if}
475
      {#if onEdit && editableBody !== null}
476
        <button type="button" title="Edit" aria-label="Edit your message" on:click|stopPropagation={edit}>
477
          ✎
478
        </button>
479
      {/if}
480
      {#if onMore}
481
        <button
482
          type="button"
483
          title="More"
484
          aria-label={`More actions for message from ${displayName}`}
485
          aria-haspopup="menu"
486
          on:click|stopPropagation={(ev) => onMore?.(event, ev.clientX, ev.clientY)}
487
        >
488
          ⋯
489
        </button>
490
      {/if}
491
    </div>
492
    {#if pickerOpen}
493
      <div class="picker-pop" style={pickerStyle} bind:this={pickerPop}>
494
        <ReactionPicker {packs} quick={quickReactions} onPick={pick} {onQuickChange} onClose={closePicker} />
495
      </div>
496
    {/if}
497
  {/if}
498
  {#if event.reply_to}
499
    {@const target = event.reply_to.event_id}
500
    <div class="reply-line" class:linked={showSender}>
501
      <button
502
        type="button"
503
        class="reply-quote"
504
        disabled={!onJump}
505
        title="Jump to the original message"
506
        on:click|stopPropagation={() => onJump?.(target)}
507
      >
508
        {#if event.reply_to.details.kind === 'Ready'}
509
          <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>
510
          <span class="reply-text"><EmojiText text={replyPreview(event.reply_to.details.content)} /></span>
511
        {:else if event.reply_to.details.kind === 'Pending'}
512
          Loading reply…
513
        {:else}
514
          Reply unavailable
515
        {/if}
516
      </button>
517
    </div>
518
  {/if}
519
  {#if showSender}
520
    <button
521
      type="button"
522
      class="user-hit"
523
      disabled={!onUser}
524
      tabindex="-1"
525
      aria-hidden="true"
526
      on:click|stopPropagation={(ev) => openUser(ev, false)}
527
      on:contextmenu|preventDefault|stopPropagation={(ev) => openUser(ev, true)}
528
      use:longpress={(ev) => openUser(ev, true)}
529
    >
530
      {#if senderAvatar}
531
        <MxcAvatar mxc={senderAvatar} label={name} size={34} eager />
532
      {:else}
533
        <span class="avatar" style={`background:hsl(${senderHue(event.sender.user_id)} 35% 32%)`}>
534
          <span><EmojiText text={initialsOf(name)} /></span>
535
        </span>
536
      {/if}
537
    </button>
538
  {:else}
539
    <div class="avatar-spacer" aria-hidden="true">
540
      <span class="hover-time">{formatClock(event.timestamp_ms)}</span>
541
    </div>
542
  {/if}
543
  <div class="msg-body">
544
    {#if showSender}
545
      <div class="msg-head">
546
        <button
547
          type="button"
548
          class="sender"
549
          disabled={!onUser}
550
          style={`color:hsl(${senderHue(event.sender.user_id)} 70% var(--name-lightness))`}
551
          on:click|stopPropagation={(ev) => openUser(ev, false)}
552
          on:contextmenu|preventDefault|stopPropagation={(ev) => openUser(ev, true)}
553
          use:longpress={(ev) => openUser(ev, true)}
554
        >
555
          <EmojiText text={displayName} />
556
        </button>
557
        {#if lag}
558
          <span class="federation-lag" title="Possibly delayed by federation" aria-label={`Arrived ${lag} late, possibly delayed by federation`}>
559
            <span aria-hidden="true">◷</span><span>{lag}</span>
560
          </span>
561
        {/if}
562
        <time class="time" datetime={new Date(event.timestamp_ms).toISOString()}>
563
          {formatDay(event.timestamp_ms)} {formatClock(event.timestamp_ms)}
564
        </time>
565
        {#if event.content.kind === 'Message' && event.content.message.edited}
566
          <span class="edited" title="Edited" transition:dissolve>(edited)</span>
567
        {/if}
568
      </div>
569
    {/if}
570
571
    {#if event.content.kind === 'Message'}
572
      {@const m = event.content.message}
573
      {#if stripped.text}
574
        <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>
575
      {/if}
576
      {#if m.media}
577
        <MediaAttachmentView attachment={m.media} />
578
      {/if}
579
      {#if cards.length > 0}
580
        <div class="link-previews" in:dissolve>
581
          {#each cards as card (card.link.href)}
582
            <div in:dissolve><LinkCard link={card.link} preview={card.preview} /></div>
583
          {/each}
584
        </div>
585
      {/if}
586
    {:else if event.content.kind === 'Sticker'}
587
      {#if event.content.media}
588
        <MediaAttachmentView attachment={event.content.media} />
589
      {:else if event.content.body}<p class="text"><EmojiText text={event.content.body} /></p>{/if}
590
    {:else if event.content.kind === 'Poll'}
591
      <p class="text"><EmojiText text={`📊 ${event.content.question}`} /></p>
592
    {:else}
593
      <p class="system-line"><EmojiText text={systemLine(event.content, displayName)} /></p>
594
    {/if}
595
596
    {#if interactive && event.reactions.length > 0}
597
      <div class="reactions" aria-label="Reactions" transition:expand>
598
        {#each event.reactions as r (r.key)}
599
          <button
600
            type="button"
601
            class="reaction"
602
            transition:expand={{ axis: 'x' }}
603
            class:mine={r.own}
604
            aria-label={`${r.shortcode ? `:${r.shortcode}:` : r.key.startsWith('mxc://') ? 'custom emote' : r.key}, ${r.count} reaction${r.count === 1 ? '' : 's'}`}
605
            disabled={readOnly || !event.event_id || reacting}
606
            aria-describedby={reactorKey === r.key ? `${itemId}-reactors-${r.key}` : undefined}
607
            on:pointerenter={(e) => e.pointerType === 'mouse' && (reactorKey = r.key)}
608
            on:pointerleave={() => !reactorPinned && (reactorKey = null)}
609
            use:longpress={() => pinReactors(r.key)}
610
            on:focus={() => (reactorKey = r.key)}
611
            on:blur={() => !reactorPinned && (reactorKey = null)}
612
            on:click={() => event.event_id && onReact(event.event_id, r.key)}
613
          >
614
            {#if r.image}
615
              <img class="emote" src={messageMediaUrl(r.image, 'Thumbnail')} alt={r.shortcode ?? ''} title={r.shortcode ?? ''} />
616
            {:else if r.key.startsWith('mxc://')}
617
              <img class="emote" src={mediaUrl(r.key, 64) ?? ''} alt="" />
618
            {:else}
619
              <Emoji emoji={r.key} size={16} />
620
            {/if}
621
            <span class="count">{r.count}</span>
622
            {#if reactorKey === r.key}
623
            <span class="reactors" role="tooltip" id={`${itemId}-reactors-${r.key}`}>
624
              <span class="reactors-key"><EmojiText text={r.shortcode ? `:${r.shortcode}:` : r.key.startsWith('mxc://') ? 'custom emote' : r.key} /></span>
625
              <EmojiText text={reactorNames(r.senders)} />
626
            </span>
627
            {/if}
628
          </button>
629
        {/each}
630
      </div>
631
    {/if}
632
    {#if threadRoot && threadReplies > 0}
633
      {@const root = threadRoot}
634
      {@const latest = event.thread_summary?.latest_event_timestamp_ms ?? null}
635
      <button type="button" class="thread-chip" transition:expand on:click|stopPropagation={() => onOpenThread?.(root)}>
636
        <span class="thread-count">{threadReplies} {threadReplies === 1 ? 'reply' : 'replies'}</span>
637
        {#if latest}<time datetime={new Date(latest).toISOString()}>{formatDay(latest)} {formatClock(latest)}</time>{/if}
638
      </button>
639
    {/if}
640
    {#if sent}<span class="sent-tick" title="Sent" aria-label="Sent" transition:dissolve>✓</span>{/if}
641
    {#if interactive && sendLabel(event.send_state)}
642
      <div class="msg-foot" transition:expand>
643
        <span class="sendstate" class:failed={event.send_state.kind === 'Failed'}>{sendLabel(event.send_state)}</span>
644
      </div>
645
    {/if}
646
    {#if interactive && readers.length > 0}
647
      {@const seenBy = `Seen by ${readers.map((r) => r.name).join(', ')}`}
648
      <div class="readby" transition:dissolve title={seenBy} aria-label={seenBy} role="img">
649
        {#each readers.slice(0, MAX_READERS) as r (r.user_id)}
650
          <MxcAvatar mxc={r.avatar} label={r.name} size={16} />
651
        {/each}
652
        {#if readers.length > MAX_READERS}<span class="more">+{readers.length - MAX_READERS}</span>{/if}
653
      </div>
654
    {/if}
655
  </div>
656
</div>
657
658
<svelte:window on:pointerdown={unpinReactors} />
659
660
<style>
661
  .msg { position: relative; display: flex; flex-wrap: wrap; gap: 0 10px; padding: var(--msg-gap, 3px) 0; }
662
  .reply-line { position: relative; flex: 0 0 100%; min-width: 0; padding-left: 44px; }
663
  .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; }
664
  .msg.selected { background: var(--hover-faint); }
665
  .msg.selected .hover-time { opacity: 1; }
666
  @media (hover: hover) {
667
    .msg:hover { background: var(--hover-faint); }
668
    .msg:hover .hover-time { opacity: 1; }
669
  }
670
  .msg-foot { display: flex; align-items: center; gap: 8px; }
671
  .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); }
672
  .thread-chip:hover { border-color: var(--accent); background: var(--hover-faint); }
673
  .thread-count { color: var(--accent); font-weight: 650; }
674
  .thread-chip time { color: var(--muted); font-size: 11px; }
675
  .sendstate { font-size: 11px; color: var(--muted); }
676
  .sent-tick { position: absolute; right: 12px; bottom: 4px; font-size: 11px; color: var(--muted); }
677
  .sendstate.failed { color: var(--danger); }
678
  .link-previews { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; max-width: 420px; }
679
  .avatar {
680
    flex: none;
681
    width: 34px; height: 34px;
682
    border-radius: 50%;
683
    display: grid; place-items: center;
684
    font-size: 12px; font-weight: 700; color: #fff;
685
  }
686
  .avatar-spacer { flex: none; width: 34px; padding-top: 2px; text-align: center; }
687
  .hover-time { opacity: 0; font-size: 10.5px; color: var(--muted); }
688
  .msg-body { min-width: 0; flex: 1; }
689
  .msg-head { display: flex; align-items: baseline; gap: 8px; }
690
  .federation-lag { display: inline-flex; align-items: center; gap: 3px; color: var(--danger); font-size: 11px; font-weight: 650; }
691
  .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; }
692
  .sender { font-weight: 650; font-size: 13.5px; padding: 0; border: none; background: none; font-family: inherit; text-align: left; cursor: pointer; }
693
  .sender:hover { text-decoration: underline; }
694
  .user-hit { flex: none; align-self: flex-start; padding: 0; border: none; background: none; border-radius: 50%; cursor: pointer; }
695
  .time, .edited { color: var(--muted); font-size: 11.5px; }
696
  .text .edited { margin-left: 6px; }
697
  .msg.editing { background: color-mix(in srgb, var(--accent) 10%, transparent); }
698
  .msg.mentioned { background: color-mix(in srgb, var(--warn) 8%, transparent); box-shadow: inset 2px 0 0 var(--warn); }
699
  .reply-quote {
700
    display: flex; gap: 6px; align-items: baseline;
701
    max-width: min(100%, 520px);
702
    border: none;
703
    border-left: 2px solid var(--accent);
704
    padding: 2px 8px;
705
    margin: 2px 0 4px;
706
    color: var(--muted);
707
    font-size: 12.5px;
708
    text-align: left;
709
    background: var(--bg-soft);
710
    border-radius: 0 var(--r-sm) var(--r-sm) 0;
711
    cursor: pointer;
712
  }
713
  .reply-quote:disabled { cursor: default; }
714
  .reply-quote:hover:not(:disabled) { color: var(--text); }
715
  .reply-sender { flex: none; font-weight: 650; }
716
  .reply-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
717
  :global(.msg.flash) { animation: reply-flash 1.2s ease-out; }
718
  @keyframes -global-reply-flash { from { background: color-mix(in srgb, var(--accent) 22%, transparent); } }
719
  .text {
720
    margin: 1px 0 2px;
721
    font-size: 14px;
722
    line-height: var(--msg-line-height, 1.5);
723
    white-space: pre-wrap;
724
    overflow-wrap: anywhere;
725
  }
726
  .text.emote { font-style: italic; color: var(--muted); }
727
  .text.notice { color: var(--muted); }
728
  .system-line { color: var(--muted); font-size: 12.5px; font-style: italic; margin: 1px 0; }
729
  .msg.system { opacity: 0.85; --msg-gap: 1.5px; }
730
  .msg.system .avatar-spacer { height: 0; padding-top: 0; }
731
  .reactions { display: flex; flex-wrap: wrap; gap: 4px; margin-top: max(4px, var(--msg-gap, 3px)); }
732
  .reaction {
733
    display: inline-flex; align-items: center; gap: 4px;
734
    background: var(--bg-soft);
735
    border: 1px solid var(--border);
736
    border-radius: var(--r-sm);
737
    padding: 1px 8px;
738
    font-size: 13px;
739
    color: var(--text);
740
    cursor: pointer;
741
  }
742
  .reaction { position: relative; }
743
  .reactors {
744
    position: absolute;
745
    left: 0;
746
    bottom: calc(100% + 6px);
747
    z-index: 15;
748
    display: block;
749
    width: max-content;
750
    max-width: 260px;
751
    padding: 6px 9px;
752
    border: 1px solid var(--border);
753
    border-radius: var(--r-md);
754
    background: var(--panel-2);
755
    box-shadow: 0 6px 18px rgb(0 0 0 / 0.3);
756
    color: var(--text);
757
    font-size: 12px;
758
    line-height: 1.35;
759
    text-align: left;
760
    white-space: normal;
761
    pointer-events: none;
762
  }
763
  .reactors-key { display: block; color: var(--muted); font-size: 11px; }
764
  .reaction.mine { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, transparent); }
765
  .reaction:disabled { cursor: default; opacity: 0.85; }
766
  .msg:not(.system) .msg-body { padding-right: 72px; }
767
  .readby { position: absolute; right: 12px; bottom: 4px; display: flex; align-items: center; }
768
  .readby > :global(* + *) { margin-left: -4px; }
769
  .readby :global(.mxc-avatar), .readby :global(.mxc-fallback) { box-shadow: 0 0 0 1.5px var(--bg); }
770
  .readby .more { margin-left: 3px; font-size: 10.5px; color: var(--muted); }
771
  .actions {
772
    position: absolute; bottom: calc(100% - 18px); right: 10px; z-index: 2;
773
    display: flex; align-items: flex-start; gap: 2px;
774
    padding: 2px;
775
    background: var(--bg-soft);
776
    border: 1px solid var(--border);
777
    border-radius: var(--r-md);
778
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
779
  }
780
  .quick { display: grid; grid-template-columns: repeat(var(--quick-cols, 8), auto); gap: 2px; }
781
  .quick:empty { display: none; }
782
  .quick .group-start { grid-column-start: 1; }
783
  .actions button {
784
    background: transparent;
785
    border: 1px solid transparent;
786
    border-radius: var(--r-sm);
787
    cursor: pointer;
788
    font-size: 14px;
789
    padding: 1px 5px;
790
  }
791
  .actions button:hover:not(:disabled) { border-color: var(--border); background: var(--hover); }
792
  .actions button:disabled { opacity: 0.4; cursor: default; }
793
  .emote { width: 1.3em; height: 1.3em; object-fit: contain; vertical-align: middle; }
794
  @media (pointer: coarse) {
795
    .actions button { min-width: 36px; min-height: 40px; font-size: 16px; }
796
    .actions { top: auto; bottom: calc(100% - 18px); right: 6px; flex-wrap: wrap; justify-content: flex-end; max-width: calc(100% - 12px); }
797
    .reaction::after, .sender::after, .thread-chip::after { content: ''; position: absolute; inset: -9px -2px; }
798
    .sender, .thread-chip { position: relative; }
799
  }
800
  .picker-pop { position: fixed; z-index: 60; width: 320px; max-width: calc(100vw - 16px); animation: pop-in var(--pop); }
801
</style>