atagen

malice

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