Вложения: видео без пустых полос, карточка файла, размеры по-русски

- Горизонтальное видео в чате и в канале занимает свою высоту (раньше – рамка 20rem с
  пустыми полосами сверху и снизу, как будто вложение не догрузилось): ориентация теперь
  определяется и для видео, по метаданным, как уже было у фото.
- Карточка файла в личке: значок документа вместо эмодзи-скрепки, круглая кнопка со
  стрелкой вместо голого слова «Скачать», которое на телефоне падало отдельной строкой под
  именем и не выглядело кнопкой. Во время загрузки в кнопке спиннер и проценты.
  Тосты после скачивания – «Файл сохранён» / «Файл скачан» вместо технических.
- Размер файла по-русски: «93 КБ», «1,4 МБ» (было «93.4 KB», «1.40 MB») – во всех
  местах, где показывается размер вложения.
This commit is contained in:
q
2026-10-13 04:33:25 +03:00
parent f2ba7ce630
commit 3f0d71f788
5 changed files with 76 additions and 63 deletions
+21 -15
View File
@@ -1,8 +1,10 @@
// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать».
// Общие для ленты чата и экрана «Медиа и файлы».
import { decryptDmFileToBlob, downloadAndDecryptDmFile, formatDmFileSize } from '../services/dm-file-service.js';
import { getAttachmentKind } from '../services/attachment-format.js';
import { decryptDmFileToBlob, downloadAndDecryptDmFile } from '../services/dm-file-service.js';
import { formatBytes, getAttachmentKind } from '../services/attachment-format.js';
import { showToast } from '../services/channels-ux.js';
import { iconHtml } from './ui-icon.js';
import { createSpinner } from './feedback.js';
// Картинки и видео в личке показываются так же, как в каналах (карусель + просмотрщик),
// только файл сначала расшифровывается. Большие файлы остаются карточками со «Скачать»,
@@ -42,7 +44,8 @@ export function createDmFileAttachmentCard(attachment) {
const fileIcon = document.createElement('span');
fileIcon.className = 'dm-file-card__icon';
fileIcon.textContent = '📎';
fileIcon.setAttribute('aria-hidden', 'true');
fileIcon.innerHTML = iconHtml('doc');
const fileCopy = document.createElement('span');
fileCopy.className = 'dm-file-card__copy';
@@ -51,21 +54,28 @@ export function createDmFileAttachmentCard(attachment) {
fileName.textContent = attachment.name || 'file';
const fileMeta = document.createElement('span');
fileMeta.className = 'dm-file-card__meta';
const metaParts = [formatDmFileSize(attachment.size)];
const metaParts = [formatBytes(attachment.size)];
if (Number(attachment?.version || 1) >= 2) metaParts.push('BitTorrent v2');
fileMeta.textContent = metaParts.join(' · ');
fileCopy.append(fileName, fileMeta);
// Круглая кнопка со стрелкой; пока файл качается и расшифровывается – проценты в ней же.
const downloadBtn = document.createElement('button');
downloadBtn.type = 'button';
downloadBtn.className = 'ui-button dm-file-card__download';
downloadBtn.textContent = 'Скачать';
downloadBtn.className = 'dm-file-card__download';
downloadBtn.title = 'Скачать';
downloadBtn.setAttribute('aria-label', `Скачать ${attachment.name || 'файл'}`);
const showDownloadIcon = () => {
downloadBtn.classList.remove('is-busy');
downloadBtn.innerHTML = iconHtml('download');
};
showDownloadIcon();
downloadBtn.addEventListener('click', async (event) => {
event.stopPropagation();
if (downloadBtn.disabled) return;
downloadBtn.disabled = true;
const previousLabel = downloadBtn.textContent;
downloadBtn.textContent = 'Скачивание…';
downloadBtn.classList.add('is-busy');
downloadBtn.replaceChildren(createSpinner({ size: 'sm', label: 'Скачивание' }));
try {
const result = await downloadAndDecryptDmFile(attachment, {
onProgress: ({ processedBytes, totalBytes }) => {
@@ -75,18 +85,14 @@ export function createDmFileAttachmentCard(attachment) {
},
});
if (!result?.cancelled) {
showToast(
result?.streamed
? 'Файл расшифрован по частям и сохранён напрямую на диск'
: 'Файл расшифрован и передан браузеру для сохранения',
{ timeoutMs: 1800 },
);
// Сохранён сразу на диск (по частям) или отдан браузеру – для человека это одно и то же.
showToast(result?.streamed ? 'Файл сохранён' : 'Файл скачан', { timeoutMs: 1600 });
}
} catch (error) {
showToast(error?.message || 'Не удалось скачать файл', { kind: 'error', timeoutMs: 2800 });
} finally {
downloadBtn.disabled = false;
downloadBtn.textContent = previousLabel;
showDownloadIcon();
}
});
+18 -11
View File
@@ -17,12 +17,16 @@ export function escapeHtml(text) {
.replaceAll("'", ''');
}
// Размер файла по-русски: «83 Б», «93 КБ», «1,4 МБ»; после 10 – без дробной части.
export function formatBytes(bytes) {
const value = Number(bytes || 0);
if (!Number.isFinite(value) || value <= 0) return '0 B';
if (value < 1024) return `${value} B`;
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
return `${(value / (1024 * 1024)).toFixed(2)} MB`;
if (!Number.isFinite(value) || value <= 0) return '0 Б';
for (const [unit, size] of [['ГБ', 1024 ** 3], ['МБ', 1024 ** 2], ['КБ', 1024]]) {
if (value < size) continue;
const amount = value / size;
return `${amount.toLocaleString('ru-RU', { maximumFractionDigits: amount >= 10 ? 0 : 1 })} ${unit}`;
}
return `${Math.round(value)} Б`;
}
function normalizeName(name) {
@@ -241,16 +245,18 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
onOpen?.();
});
// Горизонтальное фото или видео занимает свою высоту, а не рамку 20rem с пустыми полосами.
const applyMediaLayout = (media, width, height) => {
const isLandscape = width > 0 && height > 0 && width > height;
media.classList.toggle('is-landscape', isLandscape);
frame.classList.toggle('is-landscape', isLandscape);
slide.classList.toggle('has-landscape-media', isLandscape);
slide.parentElement?.classList.toggle('has-landscape-media', isLandscape);
};
const bindImageLayout = (img) => {
img.addEventListener('load', () => {
frame.classList.add('is-loaded');
const naturalWidth = Number(img.naturalWidth || 0);
const naturalHeight = Number(img.naturalHeight || 0);
const isLandscape = naturalWidth > 0 && naturalHeight > 0 && naturalWidth > naturalHeight;
img.classList.toggle('is-landscape', isLandscape);
frame.classList.toggle('is-landscape', isLandscape);
slide.classList.toggle('has-landscape-media', isLandscape);
slide.parentElement?.classList.toggle('has-landscape-media', isLandscape);
applyMediaLayout(img, Number(img.naturalWidth || 0), Number(img.naturalHeight || 0));
}, { once: true });
};
@@ -280,6 +286,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
const videoSize = formatBytes(item.size);
info.textContent = videoSize;
video.addEventListener('loadedmetadata', () => {
applyMediaLayout(video, Number(video.videoWidth || 0), Number(video.videoHeight || 0));
const duration = formatVideoDuration(video.duration);
info.textContent = duration ? `${videoSize} · ${duration}` : videoSize;
// Metadata сама по себе не гарантирует первого кадра. Переход к самому