atagen

malice

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