atagen

malice

public
Star0
Watch0
e4c64c36f1052d9c227ad62e5ed668935204b76d
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/MessageRow.svelteSvelte539 lines20.9 KB
1
<script lang="ts">
2
  import MediaAttachmentView from './MediaAttachmentView.svelte';
3
  import MxcAvatar from './MxcAvatar.svelte';
4
  import Emoji from './Emoji.svelte';
5
  import EmojiText from './EmojiText.svelte';
6
  import MessageText from './MessageText.svelte';
7
  import ReactionPicker from './ReactionPicker.svelte';
8
  import LinkCard from './LinkCard.svelte';
9
  import { mediaUrl, messageMediaUrl } from './api';
10
  import type { ImagePack, LinkPreview, Person, QuickReaction, ReplyReference, SendState, TimelineContent, TimelineEvent } from './types';
11
  import { senderLabel } from './types';
12
  import { formatClock, formatDay, initialsOf, senderHue } from './format';
13
  import { findUrls } from './urls';
14
  import { mentionsFromHtml, resolveMentions, stripMarkdownPills } from './mentions';
15
16
  export let itemId: string;
17
  export let event: TimelineEvent;
18
  export let showSender: boolean;
19
  export let reacting: boolean;
20
  export let onReact: (eventId: string, key: string, shortcode?: string) => void;
21
  export let senderAvatar: string | null = null;
22
  export let quickReactions: QuickReaction[] = [];
23
  export let packs: ImagePack[] = [];
24
  export let onQuickChange: (list: QuickReaction[]) => void = () => {};
25
  export let linkPreviews: Record<string, LinkPreview | null> = {};
26
  export let loadPreview: ((url: string) => void) | null = null;
27
  export let people: Record<string, Person> = {};
28
  export let onReply: ((target: ReplyReference) => void) | null = null;
29
  export let onJump: ((eventId: string) => void) | null = null;
30
  export let onEdit: ((eventId: string, body: string) => void) | null = null;
31
  export let editing = false;
32
  export let showSent = true;
33
  export let self: string | null = null;
34
35
  const PICKER_WIDTH = 320;
36
  const PICKER_HEIGHT = 380;
37
  const PICKER_MARGIN = 8;
38
  const MAX_READERS = 3;
39
40
  let row: HTMLDivElement;
41
  let pickerPop: HTMLDivElement | undefined;
42
  let selected = false;
43
  let pickerOpen = false;
44
  let pickerStyle = '';
45
46
  const MEMBERSHIP_LABELS: Record<string, string> = {
47
    Joined: 'joined the room',
48
    Left: 'left the room',
49
    Banned: 'was banned',
50
    Unbanned: 'was unbanned',
51
    Kicked: 'was kicked',
52
    KickedAndBanned: 'was kicked and banned',
53
    Invited: 'was invited',
54
    InvitationAccepted: 'accepted the invite',
55
    InvitationRejected: 'rejected the invite',
56
    InvitationRevoked: 'had the invite revoked',
57
    Knocked: 'requested to join',
58
    KnockAccepted: 'was let in',
59
    KnockRetracted: 'withdrew the request to join',
60
    KnockDenied: 'had the request to join denied'
61
  };
62
63
  $: name = senderLabel(event.sender);
64
  $: displayName = event.sender.name_ambiguous ? `${name} (${event.sender.user_id})` : name;
65
  $: readers = event.read_by.map((id) => people[id] ?? { user_id: id, name: id, avatar: null });
66
  $: interactive = event.content.kind === 'Message' || event.content.kind === 'Sticker' || event.content.kind === 'Poll';
67
  $: message = event.content.kind === 'Message' ? event.content.message : null;
68
  $: stripped = stripMarkdownPills(message ? (message.media ? message.media.caption : message.body) ?? '' : '');
69
  $: linked = message ? [...mentionsFromHtml(message.formatted_body), ...stripped.mentions] : [];
70
  $: mentions = resolveMentions(stripped.text, linked);
71
  $: mentionsMe = self !== null && [...linked, ...mentions].some((m) => m.user_id === self);
72
  $: previews = findUrls(stripped.text);
73
  $: bundled = message ? message.link_previews : [];
74
  $: cards = previews
75
    .map((link) => ({ link, preview: bundled.find((b) => b.url === link.href) ?? linkPreviews[link.href] ?? null }))
76
    .filter((c) => c.preview && (c.preview.title || c.preview.description || c.preview.image));
77
  $: if (loadPreview) {
78
    for (const link of previews) {
79
      if (!bundled.some((b) => b.url === link.href) && !(link.href in linkPreviews)) loadPreview(link.href);
80
    }
81
  }
82
83
  function sendLabel(state: SendState): string {
84
    if (state.kind === 'Failed') return state.will_retry ? 'failed — will retry' : 'failed — not delivered';
85
    if (state.kind === 'Sending') return 'sending…';
86
    if (showSent && event.own && state.kind === 'Sent' && event.event_id) return '✓ sent';
87
    return '';
88
  }
89
90
  function toggleSelected(e: MouseEvent) {
91
    if (!interactive || (e.target as Element).closest('a, button, input, video, audio, .picker-pop')) return;
92
    selected = !selected;
93
  }
94
95
  function deselectOutside(e: PointerEvent) {
96
    if (selected && !pickerOpen && !row.contains(e.target as Node)) selected = false;
97
  }
98
99
  function openPicker(e: MouseEvent) {
100
    if (pickerOpen) {
101
      pickerOpen = false;
102
      return;
103
    }
104
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
105
    const height = Math.min(PICKER_HEIGHT, window.innerHeight - 2 * PICKER_MARGIN);
106
    const below = window.innerHeight - rect.bottom - PICKER_MARGIN >= height;
107
    const top = below ? rect.bottom + 4 : Math.max(PICKER_MARGIN, rect.top - height - 4);
108
    const maxLeft = window.innerWidth - PICKER_WIDTH - PICKER_MARGIN;
109
    const left = Math.max(PICKER_MARGIN, Math.min(rect.right - PICKER_WIDTH, maxLeft));
110
    pickerStyle = `top:${top}px;left:${left}px;height:${height}px`;
111
    selected = true;
112
    pickerOpen = true;
113
  }
114
115
  function closePicker() {
116
    pickerOpen = false;
117
  }
118
119
  function isImageKey(key: string): boolean {
120
    return key.startsWith('mxc://') || packs.some((p) => p.images.some((i) => i.reaction_key === key));
121
  }
122
123
  function react(key: string, shortcode: string | null) {
124
    if (shortcode && isImageKey(key)) onReact(event.event_id ?? '', key, shortcode);
125
    else onReact(event.event_id ?? '', key);
126
  }
127
128
  function reply() {
129
    if (!event.event_id || !onReply) return;
130
    onReply({
131
      event_id: event.event_id,
132
      details: { kind: 'Ready', sender: event.sender, content: event.content, timestamp_ms: event.timestamp_ms }
133
    });
134
  }
135
136
  $: editableBody =
137
    event.own && event.editable && event.event_id && event.content.kind === 'Message' && event.content.message.kind === 'Text'
138
      ? event.content.message.body
139
      : null;
140
141
  function edit() {
142
    if (!event.event_id || editableBody === null || !onEdit) return;
143
    onEdit(event.event_id, editableBody);
144
  }
145
146
  function reactorNames(senders: string[]): string {
147
    const names = senders.map((id) => people[id]?.name ?? id);
148
    if (names.length <= 12) return names.join(', ');
149
    return `${names.slice(0, 12).join(', ')} and ${names.length - 12} more`;
150
  }
151
152
  function pick(key: string, shortcode: string | null) {
153
    pickerOpen = false;
154
    react(key, shortcode);
155
  }
156
157
  function closeOnScroll(e: Event) {
158
    if (pickerOpen && !pickerPop?.contains(e.target as Node)) pickerOpen = false;
159
  }
160
161
  function actorLabel(userId: string, name: string | null): string {
162
    return name ?? userId;
163
  }
164
165
  function replyPreview(content: TimelineContent): string {
166
    if (content.kind === 'Message') return stripMarkdownPills(content.message.body).text;
167
    if (content.kind === 'Sticker') return content.body || 'Sticker';
168
    if (content.kind === 'Poll') return `Poll: ${content.question}`;
169
    if (content.kind === 'Redacted') return 'Message deleted';
170
    if (content.kind === 'UnableToDecrypt') return 'Unable to decrypt';
171
    return systemLine(content);
172
  }
173
174
  function systemLine(content: TimelineContent): string {
175
    switch (content.kind) {
176
      case 'Redacted':
177
        return 'Message deleted';
178
      case 'UnableToDecrypt':
179
        return `Message from ${displayName} could not be decrypted`;
180
      case 'Membership': {
181
        const who = actorLabel(content.user_id, content.display_name);
182
        return `${who} ${MEMBERSHIP_LABELS[content.change] ?? 'updated their membership'}`;
183
      }
184
      case 'Profile': {
185
        const who = actorLabel(content.user_id, null);
186
        const parts: string[] = [];
187
        if (content.display_name) {
188
          parts.push(
189
            content.display_name.new
190
              ? `changed their display name to "${content.display_name.new}"`
191
              : 'removed their display name'
192
          );
193
        }
194
        if (content.avatar) parts.push('changed their avatar');
195
        return `${who} ${parts.length > 0 ? parts.join(' and ') : 'updated their profile'}`;
196
      }
197
      case 'RoomName':
198
        return content.name
199
          ? `${displayName} changed the room name to "${content.name}"`
200
          : `${displayName} removed the room name`;
201
      case 'RoomTopic':
202
        return content.topic
203
          ? `${displayName} changed the topic to "${content.topic}"`
204
          : `${displayName} removed the topic`;
205
      case 'RoomAvatar':
206
        return content.avatar ? `${displayName} changed the room avatar` : `${displayName} removed the room avatar`;
207
      case 'EncryptionEnabled':
208
        return `${displayName} enabled encryption in this room`;
209
      case 'RoomCreated':
210
        return `${displayName} created the room`;
211
      case 'RoomUpgraded':
212
        return `${displayName} upgraded the room to a new version`;
213
      case 'OtherState':
214
        return `${displayName} sent a state event (${content.event_type})`;
215
      case 'Other':
216
        return `${displayName} sent an event (${content.event_type})`;
217
      default:
218
        return displayName;
219
    }
220
  }
221
</script>
222
223
<svelte:window
224
  on:pointerdown={deselectOutside}
225
  on:keydown={(e) => e.key === 'Escape' && (selected = false)}
226
  on:scroll|capture={closeOnScroll}
227
  on:resize={closePicker}
228
/>
229
230
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
231
<div
232
  class="msg"
233
  class:own={event.own}
234
  class:editing
235
  class:mentioned={mentionsMe}
236
  class:system={!interactive}
237
  class:has-readers={interactive && readers.length > 0}
238
  class:selected
239
  data-item={itemId}
240
  data-event={event.event_id}
241
  bind:this={row}
242
  on:click={toggleSelected}
243
>
244
  {#if interactive && event.event_id}
245
    <div class="actions" role="toolbar" aria-label={`Actions for message from ${displayName}`}>
246
      {#each quickReactions as r (r.key)}
247
        {@const label = r.shortcode ? `:${r.shortcode}:` : r.key}
248
        <button
249
          type="button"
250
          title={`React ${label}`}
251
          aria-label={`React ${label} to message from ${displayName}`}
252
          disabled={reacting}
253
          on:click={() => react(r.key, r.shortcode)}
254
        >
255
          {#if r.key.startsWith('mxc://')}
256
            <img class="emote" src={mediaUrl(r.key) ?? ''} alt="" />
257
          {:else}
258
            <Emoji emoji={r.key} size={18} />
259
          {/if}
260
        </button>
261
      {/each}
262
      <button
263
        type="button"
264
        title="Add reaction"
265
        aria-label={`Add reaction to message from ${displayName}`}
266
        aria-haspopup="dialog"
267
        aria-expanded={pickerOpen}
268
        on:pointerdown|stopPropagation
269
        on:click={openPicker}
270
      >
271
        ☺+
272
      </button>
273
      {#if onReply}
274
        <button
275
          type="button"
276
          title="Reply"
277
          aria-label={`Reply to message from ${displayName}`}
278
          on:click|stopPropagation={reply}
279
        >
280
          ↩
281
        </button>
282
      {/if}
283
      {#if onEdit && editableBody !== null}
284
        <button type="button" title="Edit" aria-label="Edit your message" on:click|stopPropagation={edit}>
285
          ✎
286
        </button>
287
      {/if}
288
    </div>
289
    {#if pickerOpen}
290
      <div class="picker-pop" style={pickerStyle} bind:this={pickerPop}>
291
        <ReactionPicker {packs} quick={quickReactions} onPick={pick} {onQuickChange} onClose={closePicker} />
292
      </div>
293
    {/if}
294
  {/if}
295
  {#if showSender}
296
    {#if senderAvatar}
297
      <MxcAvatar mxc={senderAvatar} label={name} size={34} />
298
    {:else}
299
      <div
300
        class="avatar"
301
        aria-hidden="true"
302
        style={`background:hsl(${senderHue(event.sender.user_id)} 35% 32%)`}
303
      >
304
        {initialsOf(name)}
305
      </div>
306
    {/if}
307
  {:else}
308
    <div class="avatar-spacer" aria-hidden="true">
309
      <span class="hover-time">{formatClock(event.timestamp_ms)}</span>
310
    </div>
311
  {/if}
312
  <div class="msg-body">
313
    {#if showSender}
314
      <div class="msg-head">
315
        <span class="sender" style={`color:hsl(${senderHue(event.sender.user_id)} 70% var(--name-lightness))`}>
316
          {displayName}
317
        </span>
318
        <time class="time" datetime={new Date(event.timestamp_ms).toISOString()}>
319
          {formatDay(event.timestamp_ms)} {formatClock(event.timestamp_ms)}
320
        </time>
321
        {#if event.content.kind === 'Message' && event.content.message.edited}
322
          <span class="edited" title="Edited">(edited)</span>
323
        {/if}
324
      </div>
325
    {/if}
326
    {#if event.reply_to}
327
      {@const target = event.reply_to.event_id}
328
      <button
329
        type="button"
330
        class="reply-quote"
331
        disabled={!onJump}
332
        title="Jump to the original message"
333
        on:click|stopPropagation={() => onJump?.(target)}
334
      >
335
        {#if event.reply_to.details.kind === 'Ready'}
336
          <span class="reply-sender">{senderLabel(event.reply_to.details.sender)}</span>
337
          <span class="reply-text"><EmojiText text={replyPreview(event.reply_to.details.content)} /></span>
338
        {:else if event.reply_to.details.kind === 'Pending'}
339
          Loading reply…
340
        {:else}
341
          Reply unavailable
342
        {/if}
343
      </button>
344
    {/if}
345
346
    {#if event.content.kind === 'Message'}
347
      {@const m = event.content.message}
348
      {#if stripped.text}
349
        <div class="text" class:emote={m.kind === 'Emote'} class:notice={m.kind === 'Notice' || m.kind === 'ServerNotice'}>
350
          {#if m.kind === 'Emote'}* {displayName} {/if}<MessageText text={stripped.text} html={m.formatted_body} jumbo={m.kind === 'Text'} {mentions} {self} nameOf={(id) => people[id]?.name ?? null} />
351
          {#if m.edited && !showSender}<span class="edited" title="Edited">(edited)</span>{/if}
352
        </div>
353
      {/if}
354
      {#if m.media}
355
        <MediaAttachmentView attachment={m.media} />
356
      {/if}
357
      {#if cards.length > 0}
358
        <div class="link-previews">
359
          {#each cards as card (card.link.href)}
360
            <LinkCard link={card.link} preview={card.preview} />
361
          {/each}
362
        </div>
363
      {/if}
364
    {:else if event.content.kind === 'Sticker'}
365
      {#if event.content.body}<p class="text"><EmojiText text={event.content.body} /></p>{/if}
366
      {#if event.content.media}
367
        <MediaAttachmentView attachment={event.content.media} />
368
      {/if}
369
    {:else if event.content.kind === 'Poll'}
370
      <p class="text">📊 {event.content.question}</p>
371
    {:else}
372
      <p class="system-line">{systemLine(event.content)}</p>
373
    {/if}
374
375
    {#if interactive && event.reactions.length > 0}
376
      <div class="reactions" aria-label="Reactions">
377
        {#each event.reactions as r (r.key)}
378
          <button
379
            type="button"
380
            class="reaction"
381
            class:mine={r.own}
382
            aria-describedby={`${itemId}-reactors-${r.key}`}
383
            disabled={!event.event_id || reacting}
384
            on:click={() => event.event_id && onReact(event.event_id, r.key)}
385
          >
386
            {#if r.image}
387
              <img class="emote" src={messageMediaUrl(r.image, 'Thumbnail')} alt={r.shortcode ?? ''} title={r.shortcode ?? ''} />
388
            {:else if r.key.startsWith('mxc://')}
389
              <img class="emote" src={mediaUrl(r.key) ?? ''} alt="" />
390
            {:else}
391
              <Emoji emoji={r.key} size={16} />
392
            {/if}
393
            <span class="count">{r.count}</span>
394
            <span class="reactors" role="tooltip" id={`${itemId}-reactors-${r.key}`}>
395
              <span class="reactors-key">{r.shortcode ? `:${r.shortcode}:` : r.key.startsWith('mxc://') ? 'custom emote' : r.key}</span>
396
              {reactorNames(r.senders)}
397
            </span>
398
          </button>
399
        {/each}
400
      </div>
401
    {/if}
402
    {#if interactive && sendLabel(event.send_state)}
403
      <div class="msg-foot">
404
        <span class="sendstate" class:failed={event.send_state.kind === 'Failed'}>{sendLabel(event.send_state)}</span>
405
      </div>
406
    {/if}
407
    {#if interactive && readers.length > 0}
408
      {@const seenBy = `Seen by ${readers.map((r) => r.name).join(', ')}`}
409
      <div class="readby" title={seenBy} aria-label={seenBy} role="img">
410
        {#each readers.slice(0, MAX_READERS) as r (r.user_id)}
411
          <MxcAvatar mxc={r.avatar} label={r.name} size={16} />
412
        {/each}
413
        {#if readers.length > MAX_READERS}<span class="more">+{readers.length - MAX_READERS}</span>{/if}
414
      </div>
415
    {/if}
416
  </div>
417
</div>
418
419
<style>
420
  .msg { position: relative; display: flex; gap: 10px; padding: var(--msg-gap, 3px) 0; }
421
  .msg:hover, .msg.selected { background: var(--hover-faint); }
422
  .msg:hover .hover-time, .msg.selected .hover-time { opacity: 1; }
423
  .msg-foot { display: flex; align-items: center; gap: 8px; }
424
  .sendstate { font-size: 11px; color: var(--muted); }
425
  .sendstate.failed { color: var(--danger); }
426
  .link-previews { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; max-width: 420px; }
427
  .avatar {
428
    flex: none;
429
    width: 34px; height: 34px;
430
    border-radius: 50%;
431
    display: grid; place-items: center;
432
    font-size: 12px; font-weight: 700; color: #fff;
433
  }
434
  .avatar-spacer { flex: none; width: 34px; padding-top: 2px; text-align: center; }
435
  .hover-time { opacity: 0; font-size: 10.5px; color: var(--muted); }
436
  .msg-body { min-width: 0; flex: 1; }
437
  .msg-head { display: flex; align-items: baseline; gap: 8px; }
438
  .sender { font-weight: 650; font-size: 13.5px; }
439
  .time, .edited { color: var(--muted); font-size: 11.5px; }
440
  .text .edited { margin-left: 6px; }
441
  .msg.editing { background: color-mix(in srgb, var(--accent) 10%, transparent); }
442
  .msg.mentioned { background: color-mix(in srgb, var(--warn) 8%, transparent); box-shadow: inset 2px 0 0 var(--warn); }
443
  .reply-quote {
444
    display: flex; gap: 6px; align-items: baseline;
445
    max-width: min(100%, 520px);
446
    border: none;
447
    border-left: 2px solid var(--accent);
448
    padding: 2px 8px;
449
    margin: 2px 0 4px;
450
    color: var(--muted);
451
    font-size: 12.5px;
452
    text-align: left;
453
    background: var(--bg-soft);
454
    border-radius: 0 6px 6px 0;
455
    cursor: pointer;
456
  }
457
  .reply-quote:disabled { cursor: default; }
458
  .reply-quote:hover:not(:disabled) { color: var(--text); }
459
  .reply-sender { flex: none; font-weight: 650; }
460
  .reply-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
461
  :global(.msg.flash) { animation: reply-flash 1.2s ease-out; }
462
  @keyframes -global-reply-flash { from { background: color-mix(in srgb, var(--accent) 22%, transparent); } }
463
  .text {
464
    margin: 1px 0 2px;
465
    font-size: 14px;
466
    line-height: var(--msg-line-height, 1.5);
467
    white-space: pre-wrap;
468
    overflow-wrap: anywhere;
469
  }
470
  .text.emote { font-style: italic; color: var(--muted); }
471
  .text.notice { color: var(--muted); }
472
  .system-line { color: var(--muted); font-size: 12.5px; font-style: italic; margin: 1px 0; }
473
  .msg.system { opacity: 0.85; }
474
  .reactions { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
475
  .reaction {
476
    display: inline-flex; align-items: center; gap: 4px;
477
    background: var(--bg-soft);
478
    border: 1px solid var(--border);
479
    border-radius: 999px;
480
    padding: 1px 8px;
481
    font-size: 13px;
482
    color: var(--text);
483
    cursor: pointer;
484
  }
485
  .reaction { position: relative; }
486
  .reactors {
487
    position: absolute;
488
    left: 0;
489
    bottom: calc(100% + 6px);
490
    z-index: 15;
491
    display: none;
492
    width: max-content;
493
    max-width: 260px;
494
    padding: 6px 9px;
495
    border: 1px solid var(--border);
496
    border-radius: 8px;
497
    background: var(--panel-2);
498
    box-shadow: 0 6px 18px rgb(0 0 0 / 0.3);
499
    color: var(--text);
500
    font-size: 12px;
501
    line-height: 1.35;
502
    text-align: left;
503
    white-space: normal;
504
    pointer-events: none;
505
  }
506
  .reactors-key { display: block; color: var(--muted); font-size: 11px; }
507
  .reaction:hover .reactors, .reaction:focus-visible .reactors { display: block; }
508
  .reaction.mine { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, transparent); }
509
  .reaction:disabled { cursor: default; opacity: 0.85; }
510
  .msg.has-readers .msg-body { padding-right: 72px; }
511
  .readby { position: absolute; right: 12px; bottom: 4px; display: flex; align-items: center; }
512
  .readby > :global(* + *) { margin-left: -4px; }
513
  .readby :global(.mxc-avatar), .readby :global(.mxc-fallback) { box-shadow: 0 0 0 1.5px var(--bg); }
514
  .readby .more { margin-left: 3px; font-size: 10.5px; color: var(--muted); }
515
  .actions {
516
    position: absolute; top: -14px; right: 12px; z-index: 2;
517
    display: flex; gap: 2px;
518
    padding: 2px;
519
    background: var(--bg-soft);
520
    border: 1px solid var(--border);
521
    border-radius: 8px;
522
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
523
    opacity: 0;
524
    pointer-events: none;
525
  }
526
  .msg:hover .actions, .msg:focus-within .actions, .msg.selected .actions { opacity: 1; pointer-events: auto; }
527
  .actions button {
528
    background: transparent;
529
    border: 1px solid transparent;
530
    border-radius: 6px;
531
    cursor: pointer;
532
    font-size: 14px;
533
    padding: 1px 5px;
534
  }
535
  .actions button:hover:not(:disabled) { border-color: var(--border); background: var(--hover); }
536
  .actions button:disabled { opacity: 0.4; cursor: default; }
537
  .emote { width: 1.3em; height: 1.3em; object-fit: contain; vertical-align: middle; }
538
  .picker-pop { position: fixed; z-index: 60; width: 320px; max-width: calc(100vw - 16px); }
539
</style>