Files
beavergram/frontend/src/lib/components/profile/SharedMedia.svelte
T

425 lines
10 KiB
Svelte

<script lang="ts">
import { untrack } from "svelte";
import { downloadMedia } from "#lib/api/download.js";
import { getChatMedia } from "#lib/api/endpoints.js";
import {
type InlineMedia,
loadMediaItem,
type ViewerItem,
visualKind,
} from "#lib/api/media.js";
import type { MediaView } from "#lib/api/types.js";
import MediaViewer from "#lib/components/MediaViewer.svelte";
import ContextMenu from "#lib/components/ui/ContextMenu.svelte";
import ContextMenuItem from "#lib/components/ui/ContextMenuItem.svelte";
import EmptyState from "#lib/components/ui/EmptyState.svelte";
import Icon from "#lib/components/ui/Icon.svelte";
import Spinner from "#lib/components/ui/Spinner.svelte";
import { formatListDate } from "#lib/format/datetime.js";
import { formatBytes, mediaKindLabel } from "#lib/format/media.js";
import { poster } from "#lib/media/poster.js";
import { accounts } from "#lib/stores/accounts.svelte.js";
import { shareUi } from "#lib/stores/shares.svelte.js";
import { toasts } from "#lib/stores/toasts.svelte.js";
import { ui } from "#lib/stores/ui.svelte.js";
import { isMobile } from "#lib/viewport.js";
import { goto } from "$app/navigation";
interface Props {
chatId: number;
kinds: string[];
layout: "grid" | "list";
}
let { chatId, kinds, layout }: Props = $props();
const PAGE = 60;
let items = $state<MediaView[]>([]);
let loading = $state(false);
let done = $state(false);
let viewerOpen = $state(false);
let viewerIndex = $state(0);
const previews = $state<Record<number, InlineMedia>>({});
let token = 0;
const viewerItems = $derived<ViewerItem[]>(
items.map((item) => ({
downloaded: item.downloaded,
fileName: item.file_name,
fileSize: item.file_size,
kind: item.kind,
mediaId: item.id,
messageId: item.message_id,
mime: item.mime,
}))
);
function displayName(item: MediaView): string {
return item.file_name ?? mediaKindLabel(item.kind) ?? "Файл";
}
async function save(item: MediaView) {
try {
await downloadMedia(item.id);
} catch {
toasts.error("Не удалось скачать файл");
}
}
function share(item: MediaView) {
shareUi.share({ kind: "media", mediaId: item.id }, displayName(item));
}
async function loadMore() {
if (loading || done) {
return;
}
const current = token;
loading = true;
try {
const batch = await getChatMedia(chatId, kinds, {
limit: PAGE,
offset: items.length,
});
if (current !== token) {
return;
}
items = [...items, ...batch];
if (batch.length < PAGE) {
done = true;
}
} finally {
if (current === token) {
loading = false;
}
}
}
$effect(() => {
const _id = chatId;
if (accounts.selectedId === null) {
return;
}
untrack(() => {
token += 1;
items = [];
done = false;
loading = false;
for (const key of Object.keys(previews)) {
delete previews[Number(key)];
}
loadMore().catch(() => undefined);
});
});
$effect(() => {
if (layout !== "grid") {
return;
}
const list = items;
let active = true;
untrack(() => {
for (const item of list) {
if (!(item.downloaded && previews[item.id] === undefined)) {
continue;
}
previews[item.id] = {
kind: item.kind,
mediaId: item.id,
state: "not-downloaded",
};
loadMediaItem({
downloaded: item.downloaded,
duration: null,
file_name: item.file_name,
file_size: item.file_size,
height: null,
id: item.id,
kind: item.kind,
message_id: item.message_id,
mime: item.mime,
ttl_seconds: item.ttl_seconds,
width: null,
}).then((result) => {
if (active) {
previews[item.id] = result;
}
});
}
});
return () => {
active = false;
};
});
function open(index: number) {
viewerIndex = index;
viewerOpen = true;
}
function jump(messageId: number) {
ui.requestJump(chatId, messageId);
goto(`/app/${chatId}`);
if (isMobile()) {
ui.closePanel();
}
}
function preview(item: MediaView): InlineMedia | undefined {
return previews[item.id];
}
</script>
{#if items.length === 0}
{#if loading}
<div class="center"><Spinner /></div>
{:else}
<EmptyState title="Пусто" />
{/if}
{:else if layout === "grid"}
<div class="grid">
{#each items as item, index (item.id)}
<ContextMenu>
{#snippet children({
props,
})}
<button
{...props}
class="tile"
onclick={() => open(index)}
tabindex="0"
type="button"
>
{#if preview(item)?.state === "ready"}
{@const ready = preview(item) as Extract<
InlineMedia,
{ state: "ready" }
>}
{#if visualKind(item.kind) === "video"}
<video
muted
playsinline
preload="metadata"
src={ready.url}
use:poster
></video>
<span class="play"><Icon name="play" size="1.5rem" /></span>
{:else}
<img alt="" src={ready.url}>
{/if}
{:else}
<span class="ph"
><Icon name={item.kind === "photo" ? "photo" : "video"} /></span
>
{/if}
</button>
{/snippet}
{#snippet menu()}
<ContextMenuItem icon="open-in-new-tab" onselect={() => open(index)}
>Открыть на весь экран</ContextMenuItem
>
<ContextMenuItem icon="reply" onselect={() => jump(item.message_id)}
>Перейти к сообщению</ContextMenuItem
>
{#if item.downloaded}
<ContextMenuItem icon="download" onselect={() => save(item)}
>Скачать файл</ContextMenuItem
>
<ContextMenuItem icon="allow-share" onselect={() => share(item)}
>Доступ по ссылке</ContextMenuItem
>
{/if}
{/snippet}
</ContextMenu>
{/each}
</div>
{:else}
<ul class="list">
{#each items as item, index (item.id)}
<li>
<ContextMenu>
{#snippet children({
props,
})}
<button
{...props}
onclick={() => open(index)}
tabindex="0"
type="button"
>
<span class="file-icon"><Icon name="document" /></span>
<span class="meta">
<span class="name">{displayName(item)}</span>
<span class="sub">
{formatListDate(item.created_at)}
{#if item.file_size}
· {formatBytes(item.file_size)}
{/if}
</span>
</span>
</button>
{/snippet}
{#snippet menu()}
<ContextMenuItem icon="open-in-new-tab" onselect={() => open(index)}
>Открыть</ContextMenuItem
>
<ContextMenuItem icon="reply" onselect={() => jump(item.message_id)}
>Перейти к сообщению</ContextMenuItem
>
{#if item.downloaded}
<ContextMenuItem icon="download" onselect={() => save(item)}
>Скачать файл</ContextMenuItem
>
<ContextMenuItem icon="allow-share" onselect={() => share(item)}
>Доступ по ссылке</ContextMenuItem
>
{/if}
{/snippet}
</ContextMenu>
</li>
{/each}
</ul>
{/if}
{#if !done && items.length > 0}
<button
class="more"
disabled={loading}
onclick={() => loadMore()}
type="button"
>
{loading ? "Загрузка…" : "Показать ещё"}
</button>
{/if}
<MediaViewer
{chatId}
items={viewerItems}
bind:index={viewerIndex}
bind:open={viewerOpen}
/>
<style lang="scss">
.center {
display: flex;
justify-content: center;
padding: 2rem 0;
}
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.125rem;
padding: 0.125rem;
}
.tile {
position: relative;
aspect-ratio: 1;
padding: 0;
border: 0;
cursor: pointer;
background-color: var(--color-background-secondary);
}
.tile img,
.tile video {
width: 100%;
height: 100%;
object-fit: cover;
}
.play {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: var(--color-white);
text-shadow: 0 0 4px rgb(0 0 0 / 50%);
}
.ph {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
color: var(--color-text-secondary);
}
.list {
display: flex;
flex-direction: column;
margin: 0;
padding: 0.5rem;
list-style: none;
}
.list button {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.5rem;
border: 0;
border-radius: 0.5rem;
text-align: left;
cursor: pointer;
background: transparent;
&:hover {
background-color: var(--color-background-secondary);
}
}
.file-icon {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 2.5rem;
height: 2.5rem;
border-radius: 50%;
color: var(--color-white);
background-color: var(--color-primary);
}
.meta {
display: flex;
flex-direction: column;
min-width: 0;
}
.name {
overflow: hidden;
font-size: 0.9375rem;
color: var(--color-text);
text-overflow: ellipsis;
white-space: nowrap;
}
.sub {
font-size: 0.8125rem;
color: var(--color-text-secondary);
}
.more {
width: calc(100% - 1rem);
margin: 0.5rem;
padding: 0.5rem;
border: 0;
border-radius: 0.5rem;
font-size: 0.875rem;
color: var(--color-primary);
cursor: pointer;
background-color: var(--color-background-secondary);
}
</style>