atagen

malice

public
Star0
Watch0
bcf2234c33f6ac03e7f81b83504fe8d3842d7911
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/MediaAttachmentView.svelteSvelte197 lines7.7 KB
1
<script lang="ts">
2
  import { onDestroy } from 'svelte';
3
  import type { MediaAttachment } from './types';
4
  import { messageMediaUrl } from './api';
5
  import { lightbox } from './lightbox';
6
  import Emoji from './Emoji.svelte';
7
  import EmojiText from './EmojiText.svelte';
8
9
  export let attachment: MediaAttachment;
10
11
  const PREVIEWABLE = new Set(['Image', 'Sticker']);
12
  const RETRY_DELAYS = [1000, 3000, 10000];
13
  const MAX_W = 420;
14
  const MAX_H = 320;
15
16
  // Encrypted media often has no fetchable thumbnail, so request the bounded
17
  // full bytes directly instead of flashing a broken thumbnail first.
18
  $: fullUrl = messageMediaUrl(attachment.id, 'Full');
19
  $: thumbUrl = messageMediaUrl(attachment.id, 'Thumbnail');
20
  $: previewable = PREVIEWABLE.has(attachment.kind);
21
  $: sized = !!attachment.width && !!attachment.height;
22
  $: frame = frameSize(attachment.width, attachment.height);
23
  $: gaveUp = fullFailed && retryTimer === null && retryCount >= RETRY_DELAYS.length;
24
25
  let fullFailed = false;
26
  let loaded = false;
27
  let mediaId: string | null = null;
28
  let retryCount = 0;
29
  let retryToken = '';
30
  let retryTimer: ReturnType<typeof setTimeout> | null = null;
31
32
  $: previewUrl = retryToken ? `${fullUrl}&retry=${retryToken}` : fullUrl;
33
  $: if (attachment.id !== mediaId) resetPreview(attachment.id);
34
35
  function clearRetry(): void {
36
    if (retryTimer !== null) clearTimeout(retryTimer);
37
    retryTimer = null;
38
  }
39
40
  function resetPreview(id: string): void {
41
    clearRetry();
42
    mediaId = id;
43
    retryCount = 0;
44
    retryToken = '';
45
    fullFailed = false;
46
    loaded = false;
47
  }
48
49
  function retryPreview(resetBudget = false): void {
50
    clearRetry();
51
    if (resetBudget) retryCount = 0;
52
    retryCount += 1;
53
    retryToken = `${Date.now()}-${retryCount}`;
54
    fullFailed = false;
55
    loaded = false;
56
  }
57
58
  function previewFailed(): void {
59
    fullFailed = true;
60
    loaded = false;
61
    if (retryTimer !== null || retryCount >= RETRY_DELAYS.length) return;
62
    retryTimer = setTimeout(() => retryPreview(), RETRY_DELAYS[retryCount]);
63
  }
64
65
  onDestroy(clearRetry);
66
67
  function openLightbox(ev: MouseEvent): void {
68
    if (ev.button !== 0 || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.altKey) return;
69
    ev.preventDefault();
70
    lightbox.set({ src: fullUrl, alt: attachment.caption || attachment.filename, filename: attachment.filename, mxc: attachment.mxc });
71
  }
72
73
  function frameSize(width: number | null, height: number | null): string {
74
    if (!width || !height) return 'width:240px;height:160px';
75
    const scale = Math.min(1, MAX_W / width, MAX_H / height);
76
    return `width:${Math.max(1, Math.round(width * scale))}px;aspect-ratio:${width}/${height}`;
77
  }
78
79
  function sizeLabel(): string {
80
    if (typeof attachment.size_bytes !== 'number') return '';
81
    const bytes = attachment.size_bytes;
82
    if (bytes < 1024) return `${bytes} B`;
83
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
84
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
85
  }
86
87
  function durationLabel(): string {
88
    if (typeof attachment.duration_ms !== 'number') return '';
89
    const totalSeconds = Math.round(attachment.duration_ms / 1000);
90
    const minutes = Math.floor(totalSeconds / 60);
91
    const seconds = totalSeconds % 60;
92
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
93
  }
94
</script>
95
96
<svelte:window on:online={() => { if (fullFailed) retryPreview(true); }} />
97
98
{#if previewable && !gaveUp}
99
  <figure class="media-figure">
100
    <a class="media-frame" class:loaded class:natural={!sized && loaded} style={sized || !loaded ? frame : undefined} href={fullUrl} target="_blank" rel="noopener noreferrer" title={attachment.filename} on:click={openLightbox}>
101
      <img
102
        class="media-image"
103
        class:loaded
104
        src={previewUrl}
105
        alt={attachment.caption || attachment.filename}
106
        loading="lazy"
107
        on:load={() => ((loaded = true), (fullFailed = false))}
108
        on:error={previewFailed}
109
      />
110
    </a>
111
    {#if attachment.kind !== 'Sticker'}
112
      <figcaption class="media-caption">
113
        {#if attachment.caption && attachment.caption !== attachment.filename}
114
          <span><EmojiText text={attachment.caption} /></span>
115
        {:else}
116
          <span><EmojiText text={attachment.filename} /></span>
117
        {/if}
118
        {#if sizeLabel()}<span class="media-size"> · {sizeLabel()}</span>{/if}
119
      </figcaption>
120
    {/if}
121
  </figure>
122
{:else if previewable}
123
  <div class="media-file">
124
    <span class="file-icon" aria-hidden="true"><Emoji emoji="🖼️" size={18} /></span>
125
    <a href={fullUrl} target="_blank" rel="noopener noreferrer"><EmojiText text={attachment.caption || attachment.filename} /></a>
126
    <span class="media-size">Preview unavailable</span>
127
    <button type="button" class="ghost-btn" on:click={() => retryPreview(true)}>Retry</button>
128
  </div>
129
{:else if attachment.kind === 'Video'}
130
  <div class="media-block">
131
    <!-- svelte-ignore a11y-media-has-caption -->
132
    <video class="media-video" controls preload="metadata" poster={attachment.has_thumbnail ? thumbUrl : undefined}>
133
      <source src={fullUrl} type={attachment.mimetype ?? undefined} />
134
      Your browser cannot play this video.
135
    </video>
136
    <div class="media-caption">
137
      <a href={fullUrl} target="_blank" rel="noopener noreferrer"><EmojiText text={attachment.caption || attachment.filename} /></a>
138
      {#if durationLabel()}<span class="media-size"> · {durationLabel()}</span>{/if}
139
      {#if sizeLabel()}<span class="media-size"> · {sizeLabel()}</span>{/if}
140
    </div>
141
  </div>
142
{:else if attachment.kind === 'Audio'}
143
  <div class="media-block">
144
    <!-- svelte-ignore a11y-media-has-caption -->
145
    <audio class="media-audio" controls preload="metadata" src={fullUrl}></audio>
146
    <div class="media-caption">
147
      <span><EmojiText text={attachment.caption || attachment.filename} /></span>
148
      {#if durationLabel()}<span class="media-size"> · {durationLabel()}</span>{/if}
149
      {#if sizeLabel()}<span class="media-size"> · {sizeLabel()}</span>{/if}
150
    </div>
151
  </div>
152
{:else}
153
  <div class="media-file">
154
    <span class="file-icon" aria-hidden="true"><Emoji emoji="📎" size={18} /></span>
155
    <a href={fullUrl} target="_blank" rel="noopener noreferrer" download={attachment.filename}>
156
      <EmojiText text={attachment.caption || attachment.filename} />
157
    </a>
158
    {#if sizeLabel()}<span class="media-size">{sizeLabel()}</span>{/if}
159
  </div>
160
{/if}
161
162
<style>
163
  .media-figure { margin: 6px 0 2px; max-width: 420px; }
164
  .media-frame {
165
    display: block;
166
    max-width: 100%;
167
    border-radius: var(--r-md);
168
    border: 1px solid var(--border);
169
    background: var(--bg-soft);
170
    overflow: hidden;
171
  }
172
  .media-frame.loaded { border-color: transparent; background: none; }
173
  .media-frame.natural { display: inline-block; }
174
  .natural .media-image { width: auto; height: auto; max-width: 100%; max-height: 320px; }
175
  .media-image { display: block; width: 100%; height: 100%; object-fit: contain; opacity: 0; }
176
  .media-image.loaded { opacity: 1; }
177
  .media-video { display: block; max-width: 100%; max-height: 320px; border-radius: var(--r-md); background: #000; }
178
  .media-audio { display: block; width: 100%; max-width: 420px; margin-top: 6px; }
179
  .media-block { margin: 6px 0 2px; max-width: 420px; }
180
  .media-caption { font-size: 12px; color: var(--muted); margin-top: 4px; display: flex; gap: 4px; flex-wrap: wrap; }
181
  .media-caption a { color: var(--text); }
182
  .media-size { opacity: 0.85; }
183
  .media-file {
184
    display: inline-flex;
185
    align-items: center;
186
    gap: 8px;
187
    flex-wrap: wrap;
188
    margin: 6px 0 2px;
189
    padding: 6px 12px;
190
    border: 1px solid var(--border);
191
    border-radius: var(--r-md);
192
    background: var(--bg-soft);
193
    max-width: 100%;
194
  }
195
  .media-file a { color: var(--text); overflow-wrap: anywhere; }
196
  .file-icon { font-size: 15px; }
197
</style>