feat(frontend,backend): storage panel with weight rows and trash, heavy media streams by url in the viewer

This commit is contained in:
hh committed 2026-10-14 03:09:37 +02:00
1 parent f2c245707a
commit 55634984fd
19 files changed
+1822 -24

No files matched your search

+58 -10
View File
@@ -1,10 +1,14 @@
<script lang="ts">
import { Dialog } from "bits-ui";
import { untrack } from "svelte";
import { type MediaResult, requestMedia } from "#lib/api/client.js";
import { type MediaResult, mediaUrl, requestMedia } from "#lib/api/client.js";
import { downloadMedia } from "#lib/api/download.js";
import { fetchMedia, getMessageMedia } from "#lib/api/endpoints.js";
import { isPreviewable, type ViewerItem } from "#lib/api/media.js";
import {
isPreviewable,
isStreamable,
type ViewerItem,
} from "#lib/api/media.js";
import Button from "#lib/components/ui/Button.svelte";
import ContextMenu from "#lib/components/ui/ContextMenu.svelte";
import ContextMenuItem from "#lib/components/ui/ContextMenuItem.svelte";
@@ -19,6 +23,7 @@
chatId: number;
index: number;
items: ViewerItem[];
ontrash?: (item: ViewerItem) => void;
open: boolean;
}
@@ -27,14 +32,18 @@
index = $bindable(),
chatId,
items,
ontrash,
}: Props = $props();
const STREAM_BYTES = 32 * 1024 * 1024;
let kind = $state("");
let messageId = $state<number | null>(null);
let currentMediaId = $state<number | null>(null);
let fileName = $state<string | null>(null);
let fileSize = $state<number | null>(null);
let fileOnly = $state(false);
let streamed = $state(false);
let result = $state<MediaResult | null>(null);
let loading = $state(false);
let saving = $state(false);
@@ -55,33 +64,51 @@
const title = $derived(fileName ?? mediaKindLabel(kind) ?? "Медиа");
function revoke() {
if (result?.state === "ready" && result.url) {
if (result?.state === "ready" && result.url && !streamed) {
URL.revokeObjectURL(result.url);
}
}
function streamSource(
item: ViewerItem,
mediaId: number | null,
size: number | null
): string | null {
if (item.src) {
return item.src;
}
const heavy = size !== null && size > STREAM_BYTES;
return mediaId !== null && heavy && isStreamable(kind, item.mime)
? mediaUrl(mediaId)
: null;
}
async function load(item: ViewerItem) {
revoke();
loading = true;
result = null;
currentMediaId = null;
fileOnly = false;
streamed = false;
({ kind, messageId, fileName, fileSize } = item);
token += 1;
const current = token;
try {
let { mediaId, downloaded, mime: mimeType } = item;
let { fileName: name, fileSize: size } = item;
if (mediaId === null) {
if (mediaId === null && !item.src) {
const meta = await getMessageMedia(chatId, item.messageId);
({ id: mediaId, downloaded, kind, mime: mimeType } = meta);
({ file_name: name, file_size: size } = meta);
}
const plainFile = downloaded && !isPreviewable(kind, mimeType);
const source = downloaded ? streamSource(item, mediaId, size) : null;
let next: MediaResult;
if (plainFile) {
next = { mime: mimeType, state: "ready", url: "" };
} else if (downloaded) {
} else if (source !== null) {
next = { mime: mimeType, state: "ready", url: source };
} else if (downloaded && mediaId !== null) {
next = await requestMedia(mediaId);
} else {
next = { state: "not-downloaded" } as MediaResult;
@@ -92,6 +119,7 @@
fileName = name;
fileSize = size;
fileOnly = plainFile;
streamed = source !== null && !plainFile;
}
} catch {
if (current === token) {
@@ -136,6 +164,14 @@
}
}
function trash() {
const item = items[index];
if (item && ontrash) {
open = false;
ontrash(item);
}
}
function step(delta: number) {
const next = index + delta;
if (next >= 0 && next < items.length) {
@@ -214,6 +250,16 @@
>
<Icon name="allow-share" size="1.375rem" />
</button>
{#if ontrash}
<button
aria-label="В корзину"
class="media-action"
onclick={trash}
type="button"
>
<Icon name="delete" size="1.375rem" />
</button>
{/if}
{/if}
<Dialog.Close aria-label="Закрыть" class="media-close">
<Icon name="close" size="1.5rem" />
@@ -234,7 +280,7 @@
class="media-video"
controls
playsinline
preload="auto"
preload={streamed ? "metadata" : "auto"}
src={result.url}
use:poster
></video>
@@ -248,10 +294,12 @@
{#if fileSize}
<p class="file-size">{formatBytes(fileSize)}</p>
{/if}
<button class="media-download" onclick={save} type="button">
<Icon name="download" />
Скачать файл
</button>
{#if currentMediaId !== null}
<button class="media-download" onclick={save} type="button">
<Icon name="download" />
Скачать файл
</button>
{/if}
</div>
{:else if result?.state === "not-downloaded"}
<div class="media-message">
+41 -10
View File
@@ -2,6 +2,8 @@
import AlertsPanel from "#lib/components/alerts/AlertsPanel.svelte";
import AnnotationsPanel from "#lib/components/annotations/AnnotationsPanel.svelte";
import BotsPanel from "#lib/components/bots/BotsPanel.svelte";
import StoragePanel from "#lib/components/disk/StoragePanel.svelte";
import TrashPanel from "#lib/components/disk/TrashPanel.svelte";
import JobsPanel from "#lib/components/jobs/JobsPanel.svelte";
import PolicyEditor from "#lib/components/policy/PolicyEditor.svelte";
import AnalyticsPanel from "#lib/components/presence/AnalyticsPanel.svelte";
@@ -16,6 +18,7 @@
import Button from "#lib/components/ui/Button.svelte";
import Icon from "#lib/components/ui/Icon.svelte";
import WatchesPanel from "#lib/components/watches/WatchesPanel.svelte";
import { accounts } from "#lib/stores/accounts.svelte.js";
import { type RightPanel, ui } from "#lib/stores/ui.svelte.js";
const titles: Record<RightPanel, string> = {
@@ -23,7 +26,7 @@
annotations: "Заметки",
bots: "Боты",
callbacks: "Callback-данные",
jobs: "Данные и хранилище",
jobs: "Бэкфилл и задачи",
links: "Ссылки",
policy: "Политика захвата",
presence: "Аналитика",
@@ -31,23 +34,43 @@
reactions: "Реакции",
search: "Поиск",
shares: "Файлы по ссылке",
storage: "Хранилище",
"storage-trash": "Корзина",
stories: "Сторис",
"stories-all": "Все сторис",
versions: "Версии",
watches: "Отслеживания",
};
const parents: Partial<Record<RightPanel, RightPanel>> = {
"storage-trash": "storage",
};
const parent = $derived(ui.rightPanel ? parents[ui.rightPanel] : undefined);
</script>
<header class="right-header">
<Button
aria-label="Закрыть"
onclick={() => ui.closePanel()}
round
smaller
variant="translucent"
>
<Icon name="close" />
</Button>
{#if parent}
<Button
aria-label="Назад"
onclick={() => ui.openPanel(parent)}
round
smaller
variant="translucent"
>
<Icon name="arrow-left" />
</Button>
{:else}
<Button
aria-label="Закрыть"
onclick={() => ui.closePanel()}
round
smaller
variant="translucent"
>
<Icon name="close" />
</Button>
{/if}
<h2>{ui.rightPanel ? titles[ui.rightPanel] : ""}</h2>
</header>
@@ -82,6 +105,14 @@
<SharesPanel />
{:else if ui.rightPanel === "bots"}
<BotsPanel />
{:else if ui.rightPanel === "storage"}
{#key accounts.selectedId}
<StoragePanel />
{/key}
{:else if ui.rightPanel === "storage-trash"}
{#key accounts.selectedId}
<TrashPanel />
{/key}
{/if}
</div>
@@ -0,0 +1,67 @@
<script lang="ts">
import type { Snippet } from "svelte";
interface Props {
children: Snippet;
note?: string;
title: string;
warn?: boolean;
}
let { title, note, warn = false, children }: Props = $props();
</script>
<div class="bar">
<div class="info">
<div class="title">{title}</div>
{#if note}
<div class="note" class:warn>{note}</div>
{/if}
</div>
{@render children()}
</div>
<style lang="scss">
.bar {
position: sticky;
z-index: 1;
bottom: 0;
display: flex;
gap: 0.5rem;
align-items: center;
min-height: 4rem;
padding: 0.625rem 0.75rem calc(0.625rem + env(safe-area-inset-bottom)) 1rem;
border-top: 1px solid var(--color-borders);
background-color: var(--color-background);
box-shadow: 0 -0.5rem 1.5rem var(--color-light-shadow);
}
.bar :global(.Button) {
gap: 0.375rem;
padding-inline: 0.875rem;
}
.info {
flex: 1;
min-width: 0;
}
.title {
font-size: 0.9375rem;
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
}
.note {
margin-top: 0.125rem;
font-size: 0.8125rem;
color: var(--color-text-secondary);
&.warn {
color: var(--color-storage-warning);
}
}
</style>
@@ -0,0 +1,622 @@
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { SvelteSet } from "svelte/reactivity";
import { mediaUrl } from "#lib/api/client.js";
import { downloadMedia } from "#lib/api/download.js";
import {
getStorageFiles,
getStorageSummary,
moveToTrash,
restoreFromTrash,
} from "#lib/api/endpoints.js";
import { forgetMedia, type ViewerItem } from "#lib/api/media.js";
import type {
StorageFile,
StorageGroupName,
StorageSummary,
TrashOutcome,
} from "#lib/api/types.js";
import SelectionBar from "#lib/components/disk/SelectionBar.svelte";
import StorageRow from "#lib/components/disk/StorageRow.svelte";
import MediaViewer from "#lib/components/MediaViewer.svelte";
import Button from "#lib/components/ui/Button.svelte";
import ContextMenuItem from "#lib/components/ui/ContextMenuItem.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 } from "#lib/format/media.js";
import {
filesLabel,
GROUP_LABELS,
messagesLabel,
} from "#lib/format/storage.js";
import { chats } from "#lib/stores/chats.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";
const PAGE = 30;
const UNDO_MS = 12_000;
let summary = $state<StorageSummary | null>(null);
let files = $state<StorageFile[]>([]);
let group = $state<StorageGroupName | null>(null);
let loading = $state(false);
let failed = $state(false);
let done = $state(false);
let busy = $state(false);
let undo = $state<TrashOutcome | null>(null);
let viewerOpen = $state(false);
let viewerIndex = $state(0);
const selected = new SvelteSet<number>();
let token = 0;
let undoTimer: ReturnType<typeof setTimeout> | undefined;
const heaviest = $derived(files[0]?.file_size ?? 0);
const chosen = $derived(files.filter((file) => selected.has(file.media_id)));
const chosenBytes = $derived(
chosen.reduce((sum, file) => sum + file.file_size, 0)
);
const chosenGone = $derived(
chosen.filter((file) => !file.refetchable).length
);
const segments = $derived(
summary?.groups.filter((item) => item.bytes > 0) ?? []
);
const viewerItems = $derived<ViewerItem[]>(
files.map((file) => ({
downloaded: true,
fileName: file.file_name,
fileSize: file.file_size,
kind: file.kind,
mediaId: file.media_id,
messageId: file.message_id,
mime: file.mime,
}))
);
function chatTitle(chatId: number): string {
return chats.byId(chatId)?.title ?? `Чат ${chatId}`;
}
function tail(file: StorageFile): string {
return file.refs > 1 ? messagesLabel(file.refs) : formatListDate(file.date);
}
async function loadSummary() {
try {
summary = await getStorageSummary();
} catch {
failed = true;
}
}
async function loadMore() {
if (loading || done) {
return;
}
const current = token;
loading = true;
failed = false;
try {
const batch = await getStorageFiles(group, {
limit: PAGE,
offset: files.length,
});
if (current !== token) {
return;
}
chats.ensureMany(batch.map((file) => file.chat_id));
files = [...files, ...batch];
done = batch.length < PAGE;
} catch {
if (current === token) {
failed = true;
}
} finally {
if (current === token) {
loading = false;
}
}
}
function reload() {
token += 1;
files = [];
done = false;
loading = false;
selected.clear();
loadSummary();
loadMore();
}
function toggle(mediaId: number) {
hideUndo();
if (!selected.delete(mediaId)) {
selected.add(mediaId);
}
}
function hideUndo() {
clearTimeout(undoTimer);
undo = null;
}
function showUndo(outcome: TrashOutcome) {
hideUndo();
if (outcome.files > 0) {
undo = outcome;
undoTimer = setTimeout(hideUndo, UNDO_MS);
}
}
async function trash(mediaIds: number[]) {
if (busy || mediaIds.length === 0) {
return;
}
busy = true;
try {
const outcome = await moveToTrash(mediaIds);
const moved = new Set(
mediaIds.filter((id) => !outcome.blocked.includes(id))
);
for (const file of files) {
if (moved.has(file.media_id)) {
forgetMedia(file.chat_id, file.message_id, file.media_id);
}
}
files = files.filter((file) => !moved.has(file.media_id));
selected.clear();
showUndo(outcome);
if (outcome.blocked.length > 0) {
toasts.error("Файл занят в сторис или аватаре и остался на диске");
}
await loadSummary();
} catch {
toasts.error("Не удалось переместить в корзину");
} finally {
busy = false;
}
}
async function restoreLast() {
if (undo === null) {
return;
}
const { keys } = undo;
hideUndo();
try {
await restoreFromTrash(keys);
reload();
} catch {
toasts.error("Не удалось вернуть файлы");
}
}
async function save(file: StorageFile) {
try {
await downloadMedia(file.media_id);
} catch {
toasts.error("Не удалось скачать файл");
}
}
function open(index: number) {
viewerIndex = index;
viewerOpen = true;
}
function jump(file: StorageFile) {
ui.requestJump(file.chat_id, file.message_id);
goto(`/app/${file.chat_id}`);
if (isMobile()) {
ui.closePanel();
}
}
function pick(next: StorageGroupName) {
group = group === next ? null : next;
reload();
}
onMount(reload);
onDestroy(() => clearTimeout(undoTimer));
</script>
<div class="storage">
{#if summary}
<section class="summary">
<div class="hero">
<span class="total">{formatBytes(summary.bytes) || "0 B"}</span>
<span class="count">{filesLabel(summary.files)} на диске</span>
</div>
{#if segments.length > 0}
<div class="stack">
{#each segments as item (item.group)}
<span
title="{GROUP_LABELS[item.group]}: {formatBytes(item.bytes)}"
style:background-color="var(--color-storage-{item.group})"
style:flex-grow={item.bytes}
></span>
{/each}
</div>
{/if}
<div class="legend">
{#each summary.groups as item (item.group)}
<button
aria-pressed={group === item.group}
class="chip"
disabled={item.files === 0}
onclick={() => pick(item.group)}
type="button"
class:on={group === item.group}
>
<span
class="dot"
style:background-color="var(--color-storage-{item.group})"
></span>
{GROUP_LABELS[item.group]}
<span class="value">{formatBytes(item.bytes) || "0"}</span>
</button>
{/each}
</div>
</section>
<button
class="trash-link"
onclick={() => ui.openPanel("storage-trash")}
type="button"
>
<Icon name="delete" size="1.375rem" />
<span class="label">Корзина</span>
<span class="value">
{summary.trash_files > 0
? `${filesLabel(summary.trash_files)} · ${formatBytes(summary.trash_bytes)}`
: "пусто"}
</span>
<Icon name="next" size="1.125rem" />
</button>
{/if}
<div class="section-title">
<h3>Самые тяжёлые</h3>
{#if summary && group === null && summary.heavy_files > 0}
<span>
{filesLabel(summary.heavy_files)}
крупнее {formatBytes(summary.heavy_threshold)}
= {formatBytes(summary.heavy_bytes)}
</span>
{/if}
</div>
<div class="list">
{#each files as file, index (file.media_id)}
<StorageRow
fileName={file.file_name}
kind={file.kind}
mime={file.mime}
onopen={() => open(index)}
ontoggle={() => toggle(file.media_id)}
refetchable={file.refetchable}
selected={selected.has(file.media_id)}
size={file.file_size}
src={mediaUrl(file.media_id)}
sub={chatTitle(file.chat_id)}
tail={tail(file)}
weight={heaviest > 0 ? file.file_size / heaviest : 0}
>
{#snippet menu()}
<ContextMenuItem icon="open-in-new-tab" onselect={() => open(index)}>
Открыть
</ContextMenuItem>
<ContextMenuItem icon="reply" onselect={() => jump(file)}>
Перейти к сообщению
</ContextMenuItem>
<ContextMenuItem icon="download" onselect={() => save(file)}>
Скачать файл
</ContextMenuItem>
<ContextMenuItem
icon="delete"
onselect={() => trash([file.media_id])}
>
В корзину
</ContextMenuItem>
{/snippet}
</StorageRow>
{/each}
{#if loading}
<div class="state"><Spinner /></div>
{:else if failed}
<div class="state">
<p>Не удалось загрузить хранилище.</p>
<Button onclick={reload} smaller variant="text">Повторить</Button>
</div>
{:else if files.length === 0}
<div class="state">
<p>
{group === null
? "На диске нет скачанных файлов."
: "В этой группе нет файлов."}
</p>
</div>
{:else if !done}
<button class="more" onclick={loadMore} type="button">
Показать ещё
</button>
{/if}
</div>
{#if chosen.length > 0}
<SelectionBar
note={chosenGone > 0 ? `${chosenGone} не скачать заново` : undefined}
title="{filesLabel(chosen.length)} · {formatBytes(chosenBytes)}"
warn
>
<Button onclick={() => selected.clear()} smaller variant="text">
Снять
</Button>
<Button
disabled={busy}
loading={busy}
onclick={() => trash([...selected])}
pill
smaller
>
<Icon name="delete" size="1.25rem" />
<span>В корзину</span>
</Button>
</SelectionBar>
{:else if undo}
<SelectionBar
note="{formatBytes(undo.bytes)} освободится через 7 дней"
title="{filesLabel(undo.files)} в корзине"
>
<Button onclick={restoreLast} smaller variant="text">
<Icon name="undo" size="1.25rem" />
<span>Вернуть</span>
</Button>
</SelectionBar>
{/if}
</div>
<MediaViewer
chatId={files[viewerIndex]?.chat_id ?? 0}
items={viewerItems}
ontrash={(item) => {
if (item.mediaId !== null) {
trash([item.mediaId]);
}
}}
bind:index={viewerIndex}
bind:open={viewerOpen}
/>
<style lang="scss">
.storage {
display: flex;
flex-direction: column;
min-height: 100%;
}
.summary {
padding: 1rem 1rem 0.875rem;
}
.hero {
display: flex;
flex-wrap: wrap;
gap: 0 0.625rem;
align-items: baseline;
}
.total {
font-size: 1.875rem;
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
line-height: 1.2;
letter-spacing: -0.01em;
}
.count {
font-size: 0.875rem;
font-variant-numeric: tabular-nums;
color: var(--color-text-secondary);
}
.stack {
display: flex;
gap: 2px;
height: 0.625rem;
margin-top: 0.875rem;
span {
min-width: 0.1875rem;
border-radius: 2px;
&:first-child {
border-start-start-radius: 0.3125rem;
border-end-start-radius: 0.3125rem;
}
&:last-child {
border-start-end-radius: 0.3125rem;
border-end-end-radius: 0.3125rem;
}
}
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 0.375rem 0.25rem;
margin-top: 0.75rem;
}
.chip {
cursor: pointer;
display: inline-flex;
gap: 0.375rem;
align-items: center;
height: 1.75rem;
padding: 0 0.5625rem 0 0.4375rem;
border: 0;
border-radius: 0.875rem;
font: inherit;
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
color: var(--color-text);
background-color: var(--color-chat-hover);
transition:
background-color 0.15s ease-out,
box-shadow 0.15s ease-out;
&.on {
background-color: var(--color-primary-tint);
box-shadow: inset 0 0 0 1px var(--color-primary);
}
&:disabled {
cursor: default;
opacity: 0.5;
}
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 1px;
}
@media (hover: hover) {
&:not(:disabled, .on):hover {
background-color: var(--color-background-secondary-accent);
}
}
}
.dot {
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
}
.value {
color: var(--color-text-secondary);
}
.trash-link {
cursor: pointer;
display: flex;
flex-shrink: 0;
gap: 1rem;
align-items: center;
width: 100%;
height: 3.25rem;
padding: 0 1rem 0 1.125rem;
border: 0;
border-top: 1px solid var(--color-borders);
border-bottom: 1px solid var(--color-borders);
font: inherit;
font-size: 0.9375rem;
color: var(--color-text);
text-align: start;
background: none;
:global(.icon) {
color: var(--color-text-secondary);
}
.label {
flex: 1;
}
.value {
font-size: 0.8125rem;
font-variant-numeric: tabular-nums;
}
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: -2px;
}
@media (hover: hover) {
&:hover {
background-color: var(--color-chat-hover);
}
}
}
.section-title {
display: flex;
gap: 0.75rem;
align-items: baseline;
justify-content: space-between;
padding: 0.875rem 1rem 0.375rem;
font-size: 0.8125rem;
font-variant-numeric: tabular-nums;
color: var(--color-text-secondary);
h3 {
margin: 0;
font-size: inherit;
font-weight: var(--font-weight-medium);
color: var(--color-primary);
white-space: nowrap;
}
}
.list {
flex: 1;
padding-bottom: 0.5rem;
}
.state {
display: flex;
flex-direction: column;
gap: 0.25rem;
align-items: center;
padding: 2rem 1rem;
font-size: 0.9375rem;
color: var(--color-text-secondary);
text-align: center;
p {
margin: 0;
}
}
.more {
cursor: pointer;
width: calc(100% - 1rem);
margin: 0.5rem;
padding: 0.5rem;
border: 0;
border-radius: 0.5rem;
font: inherit;
font-size: 0.875rem;
color: var(--color-primary);
background-color: var(--color-background-secondary);
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 1px;
}
}
</style>
@@ -0,0 +1,250 @@
<script lang="ts">
import type { Snippet } from "svelte";
import StorageThumb from "#lib/components/disk/StorageThumb.svelte";
import ContextMenu from "#lib/components/ui/ContextMenu.svelte";
import Icon from "#lib/components/ui/Icon.svelte";
import { formatBytes } from "#lib/format/media.js";
import { groupOf } from "#lib/format/storage.js";
interface Props {
fileName: string;
kind: string;
lead?: string;
menu: Snippet;
mime: string | null;
onopen: () => void;
ontoggle: () => void;
refetchable: boolean;
selected: boolean;
size: number | null;
src: string;
sub: string;
tail?: string;
weight: number;
}
let {
fileName,
kind,
mime,
src,
lead,
sub,
tail,
size,
weight,
refetchable,
selected,
onopen,
ontoggle,
menu,
}: Props = $props();
const MIN_WEIGHT = 0.02;
const width = $derived(`${Math.max(MIN_WEIGHT, Math.min(1, weight)) * 100}%`);
</script>
<div
class="row"
style:--group="var(--color-storage-{groupOf(kind)})"
class:selected
>
<span class="check">
<input
aria-label="Выбрать {fileName}"
checked={selected}
onchange={ontoggle}
type="checkbox"
>
<span class="circle"><Icon name="check" size="0.875rem" /></span>
</span>
<ContextMenu {menu}>
{#snippet children({
props,
})}
<button {...props} class="main" onclick={onopen} type="button">
<StorageThumb {fileName} {kind} {mime} {src} />
<span class="text">
<span class="name">{fileName}</span>
<span class="sub">
{#if lead}
<span class="rigid">{`${lead} · `}</span>
{/if}
<span class="fluid">{sub}</span>
{#if tail}
<span class="rigid">{` · ${tail}`}</span>
{/if}
</span>
{#if !refetchable}
<span class="gone">Не скачать заново</span>
{/if}
</span>
<span class="size">{formatBytes(size)}</span>
<span class="weight"><span style:width></span></span>
</button>
{/snippet}
</ContextMenu>
</div>
<style lang="scss">
.row {
display: flex;
align-items: center;
padding-left: 0.4375rem;
&.selected {
background-color: var(--color-chat-hover);
}
@media (hover: hover) {
&:hover {
background-color: var(--color-chat-hover);
}
}
}
.check {
cursor: pointer;
position: relative;
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 2.5rem;
height: 2.5rem;
input {
cursor: pointer;
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
}
}
.circle {
display: flex;
align-items: center;
justify-content: center;
width: 1.375rem;
height: 1.375rem;
border: 2px solid var(--color-borders-input);
border-radius: 50%;
color: transparent;
transition:
background-color 0.15s ease-out,
border-color 0.15s ease-out;
input:checked + & {
border-color: var(--color-primary);
color: var(--color-white);
background-color: var(--color-primary);
}
input:focus-visible + & {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
}
.main {
cursor: pointer;
display: grid;
flex: 1;
grid-template-columns: 3rem minmax(0, 1fr) auto;
column-gap: 0.75rem;
align-items: center;
min-width: 0;
padding: 0.5rem 1rem 0.625rem 0.3125rem;
border: 0;
font: inherit;
color: var(--color-text);
text-align: start;
background: none;
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: -2px;
}
}
.text {
display: flex;
flex-direction: column;
min-width: 0;
}
.name,
.fluid {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sub {
display: flex;
min-width: 0;
}
.rigid {
flex-shrink: 0;
white-space: pre;
}
.name {
font-size: 0.9375rem;
}
.sub,
.gone {
margin-top: 0.125rem;
font-size: 0.8125rem;
color: var(--color-text-secondary);
}
.gone {
color: var(--color-storage-warning);
}
.size {
font-size: 0.9375rem;
font-weight: var(--font-weight-medium);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.weight {
grid-column: 2 / 4;
height: 0.1875rem;
margin-top: 0.4375rem;
border-radius: 0.125rem;
background-color: rgba(var(--color-text-secondary-rgb), 0.16);
span {
display: block;
height: 100%;
border-radius: inherit;
background-color: var(--group);
transition: width 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
}
</style>
@@ -0,0 +1,144 @@
<script lang="ts">
import { visible } from "#lib/actions/visible.js";
import { visualKind } from "#lib/api/media.js";
import Icon from "#lib/components/ui/Icon.svelte";
import { fileExtension, groupOf } from "#lib/format/storage.js";
import { poster } from "#lib/media/poster.js";
interface Props {
fileName: string;
kind: string;
mime: string | null;
src: string;
}
let { src, kind, mime, fileName }: Props = $props();
const GLYPHS: Record<string, string> = {
audio: "volume-2",
other: "photo",
video: "video",
voice: "microphone",
};
let near = $state(false);
let shown = $state(false);
let failed = $state(false);
const group = $derived(groupOf(kind));
const extension = $derived(group === "file" ? fileExtension(fileName) : "");
const glyph = $derived(
kind === "video_note" ? "video" : (GLYPHS[group] ?? "document")
);
const preview = $derived.by(() => {
if (mime?.startsWith("image/") || kind === "photo") {
return "image";
}
if (mime?.startsWith("video/") || visualKind(kind) === "video") {
return "video";
}
return "none";
});
const loadable = $derived(near && !failed);
</script>
<span
class="thumb"
style:--group="var(--color-storage-{group})"
use:visible={() => {
near = true;
}}
>
{#if extension}
<span class="extension">{extension}</span>
{:else}
<Icon name={glyph} size="1.375rem" />
{/if}
{#if loadable && preview === "image"}
<!-- biome-ignore lint/a11y/noNoninteractiveElementInteractions: onload is not a user interaction -->
<img
alt=""
decoding="async"
onerror={() => {
failed = true;
}}
onload={() => {
shown = true;
}}
{src}
class:shown
>
{:else if loadable && preview === "video"}
<video
muted
onerror={() => {
failed = true;
}}
onloadeddata={() => {
shown = true;
}}
playsinline
preload="metadata"
{src}
class:shown
use:poster
></video>
{#if shown}
<span class="play"><Icon name="play" size="1.125rem" /></span>
{/if}
{/if}
</span>
<style lang="scss">
.thumb {
position: relative;
overflow: hidden;
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 3rem;
height: 3rem;
border-radius: 0.5rem;
color: var(--color-white);
background-color: color-mix(
in srgb,
var(--group) var(--storage-tile-mix),
black
);
}
.extension {
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.04em;
}
img,
video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
object-fit: cover;
transition: opacity 0.2s ease-out;
&.shown {
opacity: 1;
}
}
.play {
position: absolute;
display: flex;
text-shadow: 0 0 0.375rem rgb(0 0 0 / 70%);
}
</style>
@@ -0,0 +1,421 @@
<script lang="ts">
import { Dialog } from "bits-ui";
import { onMount } from "svelte";
import { SvelteSet } from "svelte/reactivity";
import { trashedUrl } from "#lib/api/client.js";
import {
getTrash,
purgeTrash,
restoreFromTrash,
} from "#lib/api/endpoints.js";
import type { ViewerItem } from "#lib/api/media.js";
import type { TrashItem } from "#lib/api/types.js";
import SelectionBar from "#lib/components/disk/SelectionBar.svelte";
import StorageRow from "#lib/components/disk/StorageRow.svelte";
import MediaViewer from "#lib/components/MediaViewer.svelte";
import Button from "#lib/components/ui/Button.svelte";
import ContextMenuItem from "#lib/components/ui/ContextMenuItem.svelte";
import Icon from "#lib/components/ui/Icon.svelte";
import Spinner from "#lib/components/ui/Spinner.svelte";
import { formatBytes } from "#lib/format/media.js";
import { plural } from "#lib/format/shares.js";
import { filesLabel, purgeLabel } from "#lib/format/storage.js";
import { chats } from "#lib/stores/chats.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";
let items = $state<TrashItem[]>([]);
let loading = $state(true);
let failed = $state(false);
let busy = $state(false);
let doomed = $state<TrashItem[] | null>(null);
let viewerOpen = $state(false);
let viewerIndex = $state(0);
const selected = new SvelteSet<string>();
const heaviest = $derived(
Math.max(0, ...items.map((item) => item.file_size ?? 0))
);
const totalBytes = $derived(bytesOf(items));
const chosen = $derived(
items.filter((item) => selected.has(item.storage_key))
);
const chosenGone = $derived(
chosen.filter((item) => !item.refetchable).length
);
const doomedGone = $derived(
doomed?.filter((item) => !item.refetchable).length ?? 0
);
const viewerItems = $derived<ViewerItem[]>(
items.map((item) => ({
downloaded: true,
fileName: item.file_name,
fileSize: item.file_size,
kind: item.kind,
mediaId: null,
messageId: item.message_id,
mime: item.mime,
src: trashedUrl(item.storage_key),
}))
);
function bytesOf(list: TrashItem[]): number {
return list.reduce((sum, item) => sum + (item.file_size ?? 0), 0);
}
function chatTitle(chatId: number): string {
return chats.byId(chatId)?.title ?? `Чат ${chatId}`;
}
async function load() {
loading = true;
failed = false;
try {
items = await getTrash();
chats.ensureMany(items.map((item) => item.chat_id));
} catch {
failed = true;
} finally {
loading = false;
}
}
function toggle(key: string) {
if (!selected.delete(key)) {
selected.add(key);
}
}
function drop(keys: string[]) {
const gone = new Set(keys);
items = items.filter((item) => !gone.has(item.storage_key));
selected.clear();
}
async function restore(list: TrashItem[]) {
if (busy || list.length === 0) {
return;
}
busy = true;
const keys = list.map((item) => item.storage_key);
try {
await restoreFromTrash(keys);
drop(keys);
} catch {
toasts.error("Не удалось вернуть файлы");
} finally {
busy = false;
}
}
async function purge() {
if (busy || doomed === null) {
return;
}
busy = true;
const keys = doomed.map((item) => item.storage_key);
try {
await purgeTrash(keys);
drop(keys);
doomed = null;
} catch {
toasts.error("Не удалось удалить файлы");
} finally {
busy = false;
}
}
function open(index: number) {
viewerIndex = index;
viewerOpen = true;
}
function jump(item: TrashItem) {
ui.requestJump(item.chat_id, item.message_id);
goto(`/app/${item.chat_id}`);
if (isMobile()) {
ui.closePanel();
}
}
onMount(load);
</script>
<div class="trash">
<p class="note">
Файлы лежат здесь 7 дней, потом удаляются с диска. До этого их можно
вернуть.
</p>
{#if items.length > 0}
<button
class="clear"
onclick={() => {
doomed = items;
}}
type="button"
>
<Icon name="delete" size="1.375rem" />
<span class="label">Очистить корзину</span>
<span class="value">{formatBytes(totalBytes)}</span>
</button>
{/if}
<div class="list">
{#each items as item, index (item.storage_key)}
<StorageRow
fileName={item.file_name}
kind={item.kind}
lead={purgeLabel(item.purge_at)}
mime={item.mime}
onopen={() => open(index)}
ontoggle={() => toggle(item.storage_key)}
refetchable={item.refetchable}
selected={selected.has(item.storage_key)}
size={item.file_size}
src={trashedUrl(item.storage_key)}
sub={chatTitle(item.chat_id)}
weight={heaviest > 0 ? (item.file_size ?? 0) / heaviest : 0}
>
{#snippet menu()}
<ContextMenuItem icon="open-in-new-tab" onselect={() => open(index)}>
Открыть
</ContextMenuItem>
<ContextMenuItem icon="undo" onselect={() => restore([item])}>
Вернуть
</ContextMenuItem>
<ContextMenuItem icon="reply" onselect={() => jump(item)}>
Перейти к сообщению
</ContextMenuItem>
<ContextMenuItem
icon="delete"
onselect={() => {
doomed = [item];
}}
>
Удалить насовсем
</ContextMenuItem>
{/snippet}
</StorageRow>
{/each}
{#if loading}
<div class="state"><Spinner /></div>
{:else if failed}
<div class="state">
<p>Не удалось загрузить корзину.</p>
<Button onclick={load} smaller variant="text">Повторить</Button>
</div>
{:else if items.length === 0}
<div class="state"><p>Корзина пуста.</p></div>
{/if}
</div>
{#if chosen.length > 0}
<SelectionBar
note={chosenGone > 0 ? `${chosenGone} не скачать заново` : undefined}
title="{filesLabel(chosen.length)} · {formatBytes(bytesOf(chosen))}"
warn
>
<Button
onclick={() => {
doomed = chosen;
}}
pill
smaller
variant="danger"
>
Удалить
</Button>
<Button
disabled={busy}
loading={busy}
onclick={() => restore(chosen)}
pill
smaller
>
<Icon name="undo" size="1.25rem" />
<span>Вернуть</span>
</Button>
</SelectionBar>
{/if}
</div>
<Dialog.Root
onOpenChange={(next) => {
if (!next) {
doomed = null;
}
}}
open={doomed !== null}
>
<Dialog.Portal>
<Dialog.Overlay class="dialog-overlay" />
<Dialog.Content class="dialog-content">
<header class="dialog-head">
<Dialog.Title class="dialog-title">
{doomed?.length === items.length
? "Очистить корзину?"
: "Удалить насовсем?"}
</Dialog.Title>
<Dialog.Close aria-label="Закрыть" class="dialog-close">
<Icon name="close" size="1.25rem" />
</Dialog.Close>
</header>
{#if doomed}
<div class="dialog-body">
<p class="confirm">
{filesLabel(doomed.length)}, {formatBytes(bytesOf(doomed))},
{plural(
doomed.length,
"будет удалён",
"будут удалены",
"будут удалены"
)}
с диска.
{#if doomedGone < doomed.length}
{doomedGone === 0 ? "Потом их" : "Остальные потом"}
можно скачать из Telegram заново.
{/if}
</p>
{#if doomedGone > 0}
<p class="confirm warn">
<Icon name="warning" size="1.25rem" />
<span>
{filesLabel(doomedGone)}
скачать заново нельзя: в Telegram
{doomedGone === 1 ? "его" : "их"}
уже нет.
</span>
</p>
{/if}
</div>
{/if}
<div class="dialog-actions">
<Dialog.Close>
{#snippet child({
props,
})}
<Button {...props} pill variant="text">Отмена</Button>
{/snippet}
</Dialog.Close>
<Button
disabled={busy}
loading={busy}
onclick={purge}
pill
variant="danger"
>
Удалить
</Button>
</div>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
<MediaViewer
chatId={items[viewerIndex]?.chat_id ?? 0}
items={viewerItems}
bind:index={viewerIndex}
bind:open={viewerOpen}
/>
<style lang="scss">
.trash {
display: flex;
flex-direction: column;
min-height: 100%;
}
.note {
margin: 0;
padding: 0.75rem 1rem;
font-size: 0.8125rem;
line-height: 1.4;
color: var(--color-text-secondary);
}
.clear {
cursor: pointer;
display: flex;
flex-shrink: 0;
gap: 0.875rem;
align-items: center;
width: 100%;
height: 3rem;
padding: 0 1rem 0 1.125rem;
border: 0;
border-bottom: 1px solid var(--color-borders);
font: inherit;
font-size: 0.9375rem;
color: var(--color-error);
text-align: start;
background: none;
.label {
flex: 1;
}
.value {
font-size: 0.8125rem;
font-variant-numeric: tabular-nums;
color: var(--color-text-secondary);
}
&:focus-visible {
outline: 2px solid var(--color-error);
outline-offset: -2px;
}
@media (hover: hover) {
&:hover {
background-color: var(--color-chat-hover);
}
}
}
.list {
flex: 1;
padding: 0.25rem 0 0.5rem;
}
.state {
display: flex;
flex-direction: column;
gap: 0.25rem;
align-items: center;
padding: 2rem 1rem;
font-size: 0.9375rem;
color: var(--color-text-secondary);
text-align: center;
p {
margin: 0;
}
}
.confirm {
margin: 0;
font-size: 0.9375rem;
line-height: 1.45;
&.warn {
display: flex;
gap: 0.625rem;
align-items: flex-start;
margin-top: 0.75rem;
color: var(--color-storage-warning);
}
}
</style>
@@ -43,10 +43,15 @@
onclick={() => ui.openPanel("policy")}
/>
<SettingsItem
icon="data"
label="Данные и хранилище"
icon="cloud-download"
label="Бэкфилл и задачи"
onclick={() => ui.openPanel("jobs")}
/>
<SettingsItem
icon="data"
label="Хранилище"
onclick={() => ui.openPanel("storage")}
/>
<SettingsItem
icon="play-story"
label="Сторис"