atagen

malice

public
Star0
Watch0
544a170ead2c7f632e7957c1ed729ba50c80ec51
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/MessageRow.svelteSvelte411 lines15.3 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 ReactionPicker from './ReactionPicker.svelte';
7
  import { mediaUrl } from './api';
8
  import type { ImagePack, QuickReaction, SendState, TimelineContent, TimelineEvent } from './types';
9
  import { senderLabel } from './types';
10
  import { formatClock, formatDay, initialsOf, senderHue } from './format';
11
  import { findUrls } from './urls';
12
13
  export let itemId: string;
14
  export let event: TimelineEvent;
15
  export let showSender: boolean;
16
  export let reacting: boolean;
17
  export let onReact: (eventId: string, key: string) => void;
18
  export let senderAvatar: string | null = null;
19
  export let quickReactions: QuickReaction[] = [];
20
  export let packs: ImagePack[] = [];
21
  export let onQuickChange: (list: QuickReaction[]) => void = () => {};
22
23
  const PICKER_WIDTH = 320;
24
  const PICKER_HEIGHT = 380;
25
  const PICKER_MARGIN = 8;
26
27
  let row: HTMLDivElement;
28
  let pickerPop: HTMLDivElement | undefined;
29
  let selected = false;
30
  let pickerOpen = false;
31
  let pickerStyle = '';
32
33
  const MEMBERSHIP_LABELS: Record<string, string> = {
34
    Joined: 'joined the room',
35
    Left: 'left the room',
36
    Banned: 'was banned',
37
    Unbanned: 'was unbanned',
38
    Kicked: 'was kicked',
39
    KickedAndBanned: 'was kicked and banned',
40
    Invited: 'was invited',
41
    InvitationAccepted: 'accepted the invite',
42
    InvitationRejected: 'rejected the invite',
43
    InvitationRevoked: 'had the invite revoked',
44
    Knocked: 'requested to join',
45
    KnockAccepted: 'was let in',
46
    KnockRetracted: 'withdrew the request to join',
47
    KnockDenied: 'had the request to join denied'
48
  };
49
50
  $: name = senderLabel(event.sender);
51
  $: displayName = event.sender.name_ambiguous ? `${name} (${event.sender.user_id})` : name;
52
  $: interactive = event.content.kind === 'Message' || event.content.kind === 'Sticker' || event.content.kind === 'Poll';
53
  $: previews = event.content.kind === 'Message' ? findUrls(event.content.message.body) : [];
54
55
  function sendLabel(state: SendState): string {
56
    if (state.kind === 'Failed') return state.will_retry ? 'failed — will retry' : 'failed — not delivered';
57
    if (state.kind === 'Sending') return 'sending…';
58
    if (event.own && state.kind === 'Sent' && event.event_id) return '✓ sent';
59
    return '';
60
  }
61
62
  function toggleSelected(e: MouseEvent) {
63
    if (!interactive || (e.target as Element).closest('a, button, input, video, audio, .picker-pop')) return;
64
    selected = !selected;
65
  }
66
67
  function deselectOutside(e: PointerEvent) {
68
    if (selected && !pickerOpen && !row.contains(e.target as Node)) selected = false;
69
  }
70
71
  function openPicker(e: MouseEvent) {
72
    if (pickerOpen) {
73
      pickerOpen = false;
74
      return;
75
    }
76
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
77
    const height = Math.min(PICKER_HEIGHT, window.innerHeight - 2 * PICKER_MARGIN);
78
    const below = window.innerHeight - rect.bottom - PICKER_MARGIN >= height;
79
    const top = below ? rect.bottom + 4 : Math.max(PICKER_MARGIN, rect.top - height - 4);
80
    const maxLeft = window.innerWidth - PICKER_WIDTH - PICKER_MARGIN;
81
    const left = Math.max(PICKER_MARGIN, Math.min(rect.right - PICKER_WIDTH, maxLeft));
82
    pickerStyle = `top:${top}px;left:${left}px;height:${height}px`;
83
    selected = true;
84
    pickerOpen = true;
85
  }
86
87
  function closePicker() {
88
    pickerOpen = false;
89
  }
90
91
  function pick(key: string) {
92
    pickerOpen = false;
93
    onReact(event.event_id ?? '', key);
94
  }
95
96
  function closeOnScroll(e: Event) {
97
    if (pickerOpen && !pickerPop?.contains(e.target as Node)) pickerOpen = false;
98
  }
99
100
  function actorLabel(userId: string, name: string | null): string {
101
    return name ?? userId;
102
  }
103
104
  function replyPreview(content: TimelineContent): string {
105
    if (content.kind === 'Message') return content.message.body;
106
    if (content.kind === 'Sticker') return content.body || 'Sticker';
107
    if (content.kind === 'Poll') return `Poll: ${content.question}`;
108
    if (content.kind === 'Redacted') return 'Message deleted';
109
    if (content.kind === 'UnableToDecrypt') return 'Unable to decrypt';
110
    return systemLine(content);
111
  }
112
113
  function systemLine(content: TimelineContent): string {
114
    switch (content.kind) {
115
      case 'Redacted':
116
        return 'Message deleted';
117
      case 'UnableToDecrypt':
118
        return `Message from ${displayName} could not be decrypted`;
119
      case 'Membership': {
120
        const who = actorLabel(content.user_id, content.display_name);
121
        return `${who} ${MEMBERSHIP_LABELS[content.change] ?? 'updated their membership'}`;
122
      }
123
      case 'Profile': {
124
        const who = actorLabel(content.user_id, null);
125
        const parts: string[] = [];
126
        if (content.display_name) {
127
          parts.push(
128
            content.display_name.new
129
              ? `changed their display name to "${content.display_name.new}"`
130
              : 'removed their display name'
131
          );
132
        }
133
        if (content.avatar) parts.push('changed their avatar');
134
        return `${who} ${parts.length > 0 ? parts.join(' and ') : 'updated their profile'}`;
135
      }
136
      case 'RoomName':
137
        return content.name
138
          ? `${displayName} changed the room name to "${content.name}"`
139
          : `${displayName} removed the room name`;
140
      case 'RoomTopic':
141
        return content.topic
142
          ? `${displayName} changed the topic to "${content.topic}"`
143
          : `${displayName} removed the topic`;
144
      case 'RoomAvatar':
145
        return content.avatar ? `${displayName} changed the room avatar` : `${displayName} removed the room avatar`;
146
      case 'EncryptionEnabled':
147
        return `${displayName} enabled encryption in this room`;
148
      case 'RoomCreated':
149
        return `${displayName} created the room`;
150
      case 'RoomUpgraded':
151
        return `${displayName} upgraded the room to a new version`;
152
      case 'OtherState':
153
        return `${displayName} sent a state event (${content.event_type})`;
154
      case 'Other':
155
        return `${displayName} sent an event (${content.event_type})`;
156
      default:
157
        return displayName;
158
    }
159
  }
160
</script>
161
162
<svelte:window
163
  on:pointerdown={deselectOutside}
164
  on:keydown={(e) => e.key === 'Escape' && (selected = false)}
165
  on:scroll|capture={closeOnScroll}
166
  on:resize={closePicker}
167
/>
168
169
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
170
<div
171
  class="msg"
172
  class:own={event.own}
173
  class:system={!interactive}
174
  class:selected
175
  data-item={itemId}
176
  bind:this={row}
177
  on:click={toggleSelected}
178
>
179
  {#if interactive && event.event_id}
180
    <div class="actions" role="toolbar" aria-label={`Actions for message from ${displayName}`}>
181
      {#each quickReactions as r (r.key)}
182
        {@const label = r.shortcode ? `:${r.shortcode}:` : r.key}
183
        <button
184
          type="button"
185
          title={`React ${label}`}
186
          aria-label={`React ${label} to message from ${displayName}`}
187
          disabled={reacting}
188
          on:click={() => onReact(event.event_id ?? '', r.key)}
189
        >
190
          {#if r.key.startsWith('mxc://')}
191
            <img class="emote" src={mediaUrl(r.key) ?? ''} alt="" />
192
          {:else}
193
            <Emoji emoji={r.key} size={18} />
194
          {/if}
195
        </button>
196
      {/each}
197
      <button
198
        type="button"
199
        title="Add reaction"
200
        aria-label={`Add reaction to message from ${displayName}`}
201
        aria-haspopup="dialog"
202
        aria-expanded={pickerOpen}
203
        on:pointerdown|stopPropagation
204
        on:click={openPicker}
205
      >
206
        ☺+
207
      </button>
208
    </div>
209
    {#if pickerOpen}
210
      <div class="picker-pop" style={pickerStyle} bind:this={pickerPop}>
211
        <ReactionPicker {packs} quick={quickReactions} onPick={(key) => pick(key)} {onQuickChange} onClose={closePicker} />
212
      </div>
213
    {/if}
214
  {/if}
215
  {#if showSender}
216
    {#if senderAvatar}
217
      <MxcAvatar mxc={senderAvatar} label={name} size={34} />
218
    {:else}
219
      <div
220
        class="avatar"
221
        aria-hidden="true"
222
        style={`background:hsl(${senderHue(event.sender.user_id)} 35% 32%)`}
223
      >
224
        {initialsOf(name)}
225
      </div>
226
    {/if}
227
  {:else}
228
    <div class="avatar-spacer" aria-hidden="true">
229
      <span class="hover-time">{formatClock(event.timestamp_ms)}</span>
230
    </div>
231
  {/if}
232
  <div class="msg-body">
233
    {#if showSender}
234
      <div class="msg-head">
235
        <span class="sender" style={`color:hsl(${senderHue(event.sender.user_id)} 70% 72%)`}>
236
          {displayName}
237
        </span>
238
        <time class="time" datetime={new Date(event.timestamp_ms).toISOString()}>
239
          {formatDay(event.timestamp_ms)} {formatClock(event.timestamp_ms)}
240
        </time>
241
        {#if event.content.kind === 'Message' && event.content.message.edited}
242
          <span class="edited" title="Edited">(edited)</span>
243
        {/if}
244
      </div>
245
    {/if}
246
    {#if event.reply_to}
247
      <div class="reply-quote">
248
        {#if event.reply_to.details.kind === 'Ready'}
249
          Replying to {senderLabel(event.reply_to.details.sender)}: <EmojiText text={replyPreview(event.reply_to.details.content)} />
250
        {:else if event.reply_to.details.kind === 'Pending'}
251
          Loading reply…
252
        {:else}
253
          Reply unavailable
254
        {/if}
255
      </div>
256
    {/if}
257
258
    {#if event.content.kind === 'Message'}
259
      {@const m = event.content.message}
260
      <p class="text" class:emote={m.kind === 'Emote'} class:notice={m.kind === 'Notice' || m.kind === 'ServerNotice'}>
261
        {#if m.kind === 'Emote'}* {displayName} {/if}<EmojiText text={m.body} jumbo={m.kind === 'Text'} />
262
      </p>
263
      {#if m.media}
264
        <MediaAttachmentView attachment={m.media} />
265
      {/if}
266
      {#if previews.length > 0}
267
        <div class="link-previews">
268
          {#each previews as preview (preview.href)}
269
            <a class="link-card" href={preview.href} target="_blank" rel="noopener noreferrer">
270
              <span class="link-host">{preview.hostname}</span>
271
              {#if preview.path}<span class="link-path">{preview.path}</span>{/if}
272
              <span class="link-url">{preview.display}</span>
273
            </a>
274
          {/each}
275
        </div>
276
      {/if}
277
    {:else if event.content.kind === 'Sticker'}
278
      {#if event.content.body}<p class="text"><EmojiText text={event.content.body} /></p>{/if}
279
      {#if event.content.media}
280
        <MediaAttachmentView attachment={event.content.media} />
281
      {/if}
282
    {:else if event.content.kind === 'Poll'}
283
      <p class="text">📊 {event.content.question}</p>
284
    {:else}
285
      <p class="system-line">{systemLine(event.content)}</p>
286
    {/if}
287
288
    {#if interactive && event.reactions.length > 0}
289
      <div class="reactions" aria-label="Reactions">
290
        {#each event.reactions as r (r.key)}
291
          <button
292
            type="button"
293
            class="reaction"
294
            class:mine={r.own}
295
            title={r.own ? 'You reacted — activate to remove' : `${r.count} reaction${r.count === 1 ? '' : 's'}`}
296
            disabled={!event.event_id || reacting}
297
            on:click={() => event.event_id && onReact(event.event_id, r.key)}
298
          >
299
            {#if r.key.startsWith('mxc://')}
300
              <img class="emote" src={mediaUrl(r.key) ?? ''} alt="" />
301
            {:else}
302
              <Emoji emoji={r.key} size={16} />
303
            {/if}
304
            <span class="count">{r.count}</span>
305
          </button>
306
        {/each}
307
      </div>
308
    {/if}
309
    {#if interactive && (sendLabel(event.send_state) || event.read_by.length > 0)}
310
      <div class="msg-foot">
311
        {#if sendLabel(event.send_state)}
312
          <span class="sendstate" class:failed={event.send_state.kind === 'Failed'}>{sendLabel(event.send_state)}</span>
313
        {/if}
314
        {#if event.read_by.length > 0}
315
          <span class="readby" title={event.read_by.join(', ')}>✓✓ {event.read_by.length}</span>
316
        {/if}
317
      </div>
318
    {/if}
319
  </div>
320
</div>
321
322
<style>
323
  .msg { position: relative; display: flex; gap: 10px; padding: 3px 0; }
324
  .msg:hover, .msg.selected { background: rgba(255, 255, 255, 0.018); }
325
  .msg:hover .hover-time, .msg.selected .hover-time { opacity: 1; }
326
  .msg-foot { display: flex; align-items: center; gap: 8px; }
327
  .sendstate { font-size: 11px; color: var(--muted); }
328
  .sendstate.failed { color: var(--danger); }
329
  .link-previews { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; max-width: 420px; }
330
  .link-card {
331
    display: flex; flex-direction: column; gap: 1px;
332
    border: 1px solid var(--border); border-radius: 8px;
333
    background: var(--bg-soft); padding: 8px 10px;
334
    text-decoration: none; color: var(--text);
335
  }
336
  .link-card:hover { border-color: var(--accent); }
337
  .link-host { font-size: 12.5px; font-weight: 650; }
338
  .link-path { font-size: 12px; color: var(--muted); overflow-wrap: anywhere; }
339
  .link-url { font-size: 11.5px; color: var(--accent); overflow-wrap: anywhere; }
340
  .avatar {
341
    flex: none;
342
    width: 34px; height: 34px;
343
    border-radius: 50%;
344
    display: grid; place-items: center;
345
    font-size: 12px; font-weight: 700; color: #fff;
346
  }
347
  .avatar-spacer { flex: none; width: 34px; padding-top: 2px; text-align: center; }
348
  .hover-time { opacity: 0; font-size: 10.5px; color: var(--muted); }
349
  .msg-body { min-width: 0; flex: 1; }
350
  .msg-head { display: flex; align-items: baseline; gap: 8px; }
351
  .sender { font-weight: 650; font-size: 13.5px; }
352
  .time, .edited { color: var(--muted); font-size: 11.5px; }
353
  .reply-quote {
354
    border-left: 2px solid var(--accent);
355
    padding: 2px 8px;
356
    margin: 2px 0 4px;
357
    color: var(--muted);
358
    font-size: 12.5px;
359
    background: var(--bg-soft);
360
    border-radius: 0 6px 6px 0;
361
  }
362
  .text {
363
    margin: 1px 0 2px;
364
    font-size: 14px;
365
    line-height: 1.5;
366
    white-space: pre-wrap;
367
    overflow-wrap: anywhere;
368
  }
369
  .text.emote { font-style: italic; color: var(--muted); }
370
  .text.notice { color: var(--muted); }
371
  .system-line { color: var(--muted); font-size: 12.5px; font-style: italic; margin: 1px 0; }
372
  .msg.system { opacity: 0.85; }
373
  .reactions { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
374
  .reaction {
375
    display: inline-flex; align-items: center; gap: 4px;
376
    background: var(--bg-soft);
377
    border: 1px solid var(--border);
378
    border-radius: 999px;
379
    padding: 1px 8px;
380
    font-size: 13px;
381
    color: var(--text);
382
    cursor: pointer;
383
  }
384
  .reaction.mine { border-color: var(--accent); background: rgba(88, 101, 242, 0.16); }
385
  .reaction:disabled { cursor: default; opacity: 0.85; }
386
  .readby { font-size: 11px; color: var(--muted); }
387
  .actions {
388
    position: absolute; top: -14px; right: 12px; z-index: 2;
389
    display: flex; gap: 2px;
390
    padding: 2px;
391
    background: var(--bg-soft);
392
    border: 1px solid var(--border);
393
    border-radius: 8px;
394
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
395
    opacity: 0;
396
    pointer-events: none;
397
  }
398
  .msg:hover .actions, .msg:focus-within .actions, .msg.selected .actions { opacity: 1; pointer-events: auto; }
399
  .actions button {
400
    background: transparent;
401
    border: 1px solid transparent;
402
    border-radius: 6px;
403
    cursor: pointer;
404
    font-size: 14px;
405
    padding: 1px 5px;
406
  }
407
  .actions button:hover:not(:disabled) { border-color: var(--border); background: rgba(255, 255, 255, 0.06); }
408
  .actions button:disabled { opacity: 0.4; cursor: default; }
409
  .emote { width: 1.3em; height: 1.3em; object-fit: contain; vertical-align: middle; }
410
  .picker-pop { position: fixed; z-index: 60; width: 320px; max-width: calc(100vw - 16px); }
411
</style>