atagen

malice

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