SHA256
542 lines
22 KiB
JavaScript
542 lines
22 KiB
JavaScript
import { t, th } from '../i18n/index.js';
|
||
import { formatNumber } from '../i18n/format.js';
|
||
import { openMediaViewer } from '../components/media-viewer.js';
|
||
import { buildArweaveDataUrl, sha256HexFromArrayBuffer, validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||
import { resolvePublicFileUrl } from './public-file-service.js';
|
||
|
||
const ATTACH_BLOCK_RE = /^<(?:SHiNE|S):(attach|att);([^>]*)>\n?/u;
|
||
export const MAX_MESSAGE_ATTACHMENTS = 10;
|
||
const RECENT_UNAVAILABLE_MS = 20 * 60 * 1000;
|
||
const IMAGE_EXTENSIONS = new Set(['apng', 'avif', 'bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
|
||
const VIDEO_EXTENSIONS = new Set(['avi', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ogg', 'ogv', 'webm']);
|
||
|
||
export function escapeHtml(text) {
|
||
return String(text || '')
|
||
.replaceAll('&', '&')
|
||
.replaceAll('<', '<')
|
||
.replaceAll('>', '>')
|
||
.replaceAll('"', '"')
|
||
.replaceAll("'", ''');
|
||
}
|
||
|
||
// Размер файла по-русски: «83 Б», «93 КБ», «1,4 МБ»; после 10 – без дробной части.
|
||
export function formatBytes(bytes) {
|
||
const value = Number(bytes || 0);
|
||
if (!Number.isFinite(value) || value <= 0) return t('remaining.attachments.text_0_b');
|
||
for (const [unit, size] of [[t('remaining.attachments.gb'), 1024 ** 3], [t('remaining.attachments.mb'), 1024 ** 2], [t('remaining.attachments.kb'), 1024]]) {
|
||
if (value < size) continue;
|
||
const amount = value / size;
|
||
return `${formatNumber(amount, { maximumFractionDigits: amount >= 10 ? 0 : 1 })} ${unit}`;
|
||
}
|
||
return t('remaining.attachments.bytes', { count: Math.round(value) });
|
||
}
|
||
|
||
function normalizeName(name) {
|
||
const clean = String(name || 'file')
|
||
.replace(/[\u0000-\u001f\u007f]/g, '')
|
||
.replace(/[\\/]/g, '_')
|
||
.trim();
|
||
return clean || 'file';
|
||
}
|
||
|
||
export function normalizeAttachment(input = {}) {
|
||
const txId = String(input.ar || input.txId || '').trim();
|
||
const sha256Hex = String(input.sha256 || input.sha256Hex || '').trim().toLowerCase();
|
||
const pr = String(input.pr || '').trim();
|
||
const mm = String(input.mm || '').trim();
|
||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
||
if (!/^[A-Za-z0-9_-]{43}$/.test(pr) && !validateSha256Hex(sha256Hex)) throw new Error('Некорректный идентификатор файла');
|
||
if (pr && !/^[A-Za-z0-9_-]{43}$/.test(pr)) throw new Error('Некорректный Pieces Root');
|
||
if (mm && (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(mm) || mm.length > 127)) throw new Error('Некорректный MIME');
|
||
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
||
return { v: 1, name, size, sha256: sha256Hex, pr, mm, ar: txId, uploadedAtMs: Number(input.uploadedAtMs || 0) || Date.now() };
|
||
}
|
||
|
||
export function buildAttachmentBlock(attachment) {
|
||
const item = normalizeAttachment(attachment);
|
||
const encodedName = encodeURIComponent(item.name);
|
||
const id = item.pr ? `;pr=${item.pr}` : `;sha256=${item.sha256}`;
|
||
const mmPart = item.mm ? `;mm=${item.mm}` : '';
|
||
const arPart = item.ar ? `;ar=${item.ar}` : '';
|
||
return `<S:att;v=1;nm=${encodedName};sz=${item.size}${id}${mmPart}${arPart}>`;
|
||
}
|
||
|
||
export function composeMessageWithAttachments(text, attachments = []) {
|
||
const cleanText = String(text || '').trim();
|
||
const rows = (Array.isArray(attachments) ? attachments : [])
|
||
.slice(0, MAX_MESSAGE_ATTACHMENTS)
|
||
.map(buildAttachmentBlock);
|
||
if (!rows.length) return cleanText;
|
||
return `${rows.join('\n')}${cleanText ? `\n${cleanText}` : ''}`;
|
||
}
|
||
|
||
function parseFields(rawFields) {
|
||
const out = {};
|
||
String(rawFields || '').split(';').forEach((part) => {
|
||
const eq = part.indexOf('=');
|
||
if (eq <= 0) return;
|
||
const key = part.slice(0, eq).trim();
|
||
const value = part.slice(eq + 1).trim();
|
||
if (key) out[key] = value;
|
||
});
|
||
return out;
|
||
}
|
||
|
||
export function parseMessageAttachments(rawText) {
|
||
let rest = String(rawText || '');
|
||
const attachments = [];
|
||
|
||
while (true) {
|
||
const match = rest.match(ATTACH_BLOCK_RE);
|
||
if (!match) break;
|
||
const fields = parseFields(match[2]);
|
||
try {
|
||
const version = Number(fields.v || 0);
|
||
if (version !== 1 && version !== 2) {
|
||
throw new Error('unsupported attachment version');
|
||
}
|
||
attachments.push(normalizeAttachment({
|
||
nm: decodeURIComponent(String(fields.nm || fields.name || 'file')),
|
||
sz: fields.sz || fields.size,
|
||
sha256: fields.sha256,
|
||
pr: fields.pr,
|
||
mm: fields.mm,
|
||
ar: fields.ar,
|
||
}));
|
||
} catch {
|
||
// Битый attach-блок скрываем из UI, но не ломаем отображение текста.
|
||
}
|
||
rest = rest.slice(match[0].length);
|
||
}
|
||
|
||
return {
|
||
attachments,
|
||
text: rest.replace(/^\n+/u, ''),
|
||
};
|
||
}
|
||
|
||
export function getAttachmentExtension(name) {
|
||
const clean = String(name || '').trim().toLowerCase();
|
||
const dot = clean.lastIndexOf('.');
|
||
if (dot < 0 || dot === clean.length - 1) return '';
|
||
return clean.slice(dot + 1).replace(/[^a-z0-9]/g, '');
|
||
}
|
||
|
||
export function getAttachmentKind(attachment = {}) {
|
||
const ext = getAttachmentExtension(attachment.name);
|
||
if (IMAGE_EXTENSIONS.has(ext)) return 'image';
|
||
if (VIDEO_EXTENSIONS.has(ext)) return 'video';
|
||
return 'file';
|
||
}
|
||
|
||
function isRecentMessage(messageTimestampMs) {
|
||
const ts = Number(messageTimestampMs || 0);
|
||
if (!Number.isFinite(ts) || ts <= 0) return false;
|
||
return Date.now() - ts < RECENT_UNAVAILABLE_MS;
|
||
}
|
||
|
||
function attachmentStorage(item) {
|
||
return item?.ar ? 'arweave' : 'server';
|
||
}
|
||
|
||
function buildCurrentServerDebugUrl(item) {
|
||
const sha = String(item?.sha256 || '').trim().toLowerCase();
|
||
if (!validateSha256Hex(sha)) return '';
|
||
return `${window.location.origin.replace(/\/$/, '')}/files/${sha}`;
|
||
}
|
||
|
||
function createUnavailableBlock(messageTimestampMs, storage = 'arweave', detail = null) {
|
||
const block = document.createElement('div');
|
||
block.className = 'message-attachment-unavailable';
|
||
if (storage === 'server') {
|
||
block.textContent = t('remaining.attachments.the_file_is_unavailable_on_the_author_s_access_server');
|
||
} else {
|
||
block.textContent = isRecentMessage(messageTimestampMs)
|
||
? t('remaining.attachments.the_file_may_not_have_propagated_to_arweave_yet_please_try')
|
||
: t('remaining.attachments.file_unavailable');
|
||
}
|
||
if (detail) {
|
||
const debug = document.createElement('pre');
|
||
debug.className = 'message-attachment-debug';
|
||
debug.textContent = [
|
||
'DEBUG server attachment',
|
||
detail.name ? `name: ${detail.name}` : '',
|
||
detail.sha256 ? `sha256: ${detail.sha256}` : '',
|
||
detail.url ? `url: ${detail.url}` : '',
|
||
detail.error ? `error: ${detail.error}` : '',
|
||
].filter(Boolean).join('\n');
|
||
block.append(debug);
|
||
}
|
||
return block;
|
||
}
|
||
|
||
function stopVideos(root) {
|
||
root.querySelectorAll('video').forEach((video) => {
|
||
try {
|
||
video.pause();
|
||
video.currentTime = 0;
|
||
} catch {
|
||
// Если браузер не даёт управлять видео, просто продолжаем перелистывание.
|
||
}
|
||
});
|
||
}
|
||
|
||
function replaceWithUnavailable(slide, messageTimestampMs, storage = 'arweave', detail = null) {
|
||
if (!slide || slide.dataset.unavailable === '1') return;
|
||
slide.dataset.unavailable = '1';
|
||
slide.replaceChildren(createUnavailableBlock(messageTimestampMs, storage, detail));
|
||
}
|
||
|
||
function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||
const card = document.createElement('div');
|
||
card.className = 'message-attachment-file-card';
|
||
card.role = 'button';
|
||
card.tabIndex = 0;
|
||
card.title = t('remaining.attachments.download_file');
|
||
card.innerHTML = `
|
||
<div class="message-attachment-file-ext">${th('remaining.html_attachment_format.file_div')}
|
||
<div class="message-attachment-file-main">
|
||
<div class="message-attachment-name">${escapeHtml(item.name)}</div>
|
||
<div class="message-attachment-meta">${escapeHtml(formatBytes(item.size))}</div>
|
||
</div>
|
||
`;
|
||
const openFile = () => window.open(url, '_blank', 'noopener');
|
||
card.addEventListener('click', (event) => {
|
||
event.stopPropagation();
|
||
openFile();
|
||
});
|
||
card.addEventListener('keydown', (event) => {
|
||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||
event.preventDefault();
|
||
openFile();
|
||
});
|
||
void fetch(url, { method: 'HEAD', cache: 'no-store' })
|
||
.then((response) => {
|
||
if (!response.ok) replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item));
|
||
})
|
||
.catch(() => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)));
|
||
return card;
|
||
}
|
||
|
||
function formatVideoDuration(seconds) {
|
||
if (!Number.isFinite(seconds) || seconds < 0) return '';
|
||
const wholeSeconds = Math.floor(seconds);
|
||
const hours = Math.floor(wholeSeconds / 3600);
|
||
const minutes = Math.floor((wholeSeconds % 3600) / 60);
|
||
const secondsPart = String(wholeSeconds % 60).padStart(2, '0');
|
||
return hours > 0
|
||
? `${hours}:${String(minutes).padStart(2, '0')}:${secondsPart}`
|
||
: `${String(minutes).padStart(2, '0')}:${secondsPart}`;
|
||
}
|
||
|
||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }) {
|
||
const frame = document.createElement('div');
|
||
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
|
||
frame.role = 'button';
|
||
frame.tabIndex = 0;
|
||
frame.title = kind === 'video' ? t('remaining.attachments.open_video') : t('remaining.attachments.open_image');
|
||
frame.addEventListener('click', (event) => {
|
||
event.stopPropagation();
|
||
onOpen?.();
|
||
});
|
||
frame.addEventListener('keydown', (event) => {
|
||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||
event.preventDefault();
|
||
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');
|
||
applyMediaLayout(img, Number(img.naturalWidth || 0), Number(img.naturalHeight || 0));
|
||
}, { once: true });
|
||
};
|
||
|
||
if (kind === 'image') {
|
||
const img = document.createElement('img');
|
||
img.className = 'message-attachment-media';
|
||
img.src = url;
|
||
img.alt = item.name;
|
||
img.loading = 'lazy';
|
||
bindImageLayout(img);
|
||
img.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||
frame.append(img);
|
||
} else {
|
||
const video = document.createElement('video');
|
||
video.className = 'message-attachment-media';
|
||
video.src = url;
|
||
video.preload = 'metadata';
|
||
video.muted = true;
|
||
video.playsInline = true;
|
||
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||
video.addEventListener('loadeddata', () => frame.classList.add('is-loaded'), { once: true });
|
||
|
||
// Размер известен из S:att, длительность появляется после получения метаданных.
|
||
// <video> сам запрашивает небольшие диапазоны через HTTP Range, без fetch всего файла.
|
||
const info = document.createElement('span');
|
||
info.className = 'message-attachment-video-info';
|
||
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 сама по себе не гарантирует первого кадра. Переход к самому
|
||
// началу видео побуждает браузер запросить только нужные части файла.
|
||
if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA && Number.isFinite(video.duration) && video.duration > 0) {
|
||
try { video.currentTime = Math.min(0.05, video.duration); } catch { /* зависит от кодека */ }
|
||
}
|
||
}, { once: true });
|
||
const play = document.createElement('span');
|
||
play.className = 'message-attachment-play';
|
||
play.textContent = '▶';
|
||
frame.append(video, play, info);
|
||
}
|
||
|
||
return frame;
|
||
}
|
||
|
||
function mimeTypeForAttachment(item, kind) {
|
||
const ext = getAttachmentExtension(item?.name);
|
||
if (kind === 'image') {
|
||
if (ext === 'svg') return 'image/svg+xml';
|
||
if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg';
|
||
if (ext === 'png') return 'image/png';
|
||
if (ext === 'gif') return 'image/gif';
|
||
if (ext === 'webp') return 'image/webp';
|
||
if (ext === 'avif') return 'image/avif';
|
||
if (ext === 'bmp') return 'image/bmp';
|
||
if (ext === 'apng') return 'image/apng';
|
||
return 'application/octet-stream';
|
||
}
|
||
if (kind === 'video') {
|
||
if (ext === 'mp4' || ext === 'm4v') return 'video/mp4';
|
||
if (ext === 'webm') return 'video/webm';
|
||
if (ext === 'ogg' || ext === 'ogv') return 'video/ogg';
|
||
if (ext === 'mov') return 'video/quicktime';
|
||
if (ext === 'mpeg' || ext === 'mpg') return 'video/mpeg';
|
||
if (ext === 'avi') return 'video/x-msvideo';
|
||
if (ext === 'mkv') return 'video/x-matroska';
|
||
}
|
||
return 'application/octet-stream';
|
||
}
|
||
|
||
const attachmentObjectUrls = new Map();
|
||
let attachmentObjectUrlObserver = null;
|
||
|
||
function registerAttachmentObjectUrl(owner, url) {
|
||
if (!owner || !url) return;
|
||
if (!owner.isConnected) {
|
||
URL.revokeObjectURL(url);
|
||
return;
|
||
}
|
||
const urls = attachmentObjectUrls.get(owner) || new Set();
|
||
urls.add(url);
|
||
attachmentObjectUrls.set(owner, urls);
|
||
if (attachmentObjectUrlObserver) return;
|
||
attachmentObjectUrlObserver = new MutationObserver(() => {
|
||
attachmentObjectUrls.forEach((ownedUrls, element) => {
|
||
if (element.isConnected) return;
|
||
ownedUrls.forEach((ownedUrl) => URL.revokeObjectURL(ownedUrl));
|
||
attachmentObjectUrls.delete(element);
|
||
});
|
||
if (!attachmentObjectUrls.size) {
|
||
attachmentObjectUrlObserver.disconnect();
|
||
attachmentObjectUrlObserver = null;
|
||
}
|
||
});
|
||
attachmentObjectUrlObserver.observe(document.documentElement, { childList: true, subtree: true });
|
||
}
|
||
|
||
async function resolveAttachmentDisplayUrl(item, options = {}) {
|
||
if (item.ar) {
|
||
return { url: buildArweaveDataUrl({ gateway: options.gateway, txId: item.ar }), objectUrl: false };
|
||
}
|
||
|
||
const serverUrl = await resolvePublicFileUrl({
|
||
sha256: item.sha256,
|
||
pr: item.pr,
|
||
authorLogin: options.authorLogin,
|
||
solanaEndpoint: options.solanaEndpoint,
|
||
fallbackServerLogin: options.fallbackServerLogin,
|
||
});
|
||
if (item.pr) return { url: serverUrl, objectUrl: false };
|
||
// Public MVP: direct URL, no image downloads, media viewer or full SHA checks.
|
||
return { url: serverUrl, objectUrl: false };
|
||
}
|
||
|
||
export function createAttachmentCarouselElement(attachments = [], {
|
||
gateway = '',
|
||
messageTimestampMs = 0,
|
||
authorLogin = '',
|
||
solanaEndpoint = '',
|
||
fallbackServerLogin = '',
|
||
// Свой источник файла: async (item) => ({ url, objectUrl }). Нужен личным сообщениям,
|
||
// где вложение зашифровано и описано не S:att, а своим тех-блоком (без sha256).
|
||
resolveUrl = null,
|
||
} = {}) {
|
||
const items = (Array.isArray(attachments) ? attachments : [])
|
||
.slice(0, MAX_MESSAGE_ATTACHMENTS)
|
||
.map((raw) => {
|
||
if (resolveUrl) return raw && typeof raw === 'object' ? { ...raw, name: normalizeName(raw.name), size: Number(raw.size || 0) } : null;
|
||
try {
|
||
return normalizeAttachment(raw);
|
||
} catch {
|
||
return null;
|
||
}
|
||
})
|
||
.filter(Boolean);
|
||
const wrap = document.createElement('div');
|
||
wrap.className = 'message-attachments message-attachment-carousel';
|
||
wrap.addEventListener('click', (event) => event.stopPropagation());
|
||
if (!items.length) return wrap;
|
||
|
||
// Public attachments are a simple file list. The DM renderer supplies resolveUrl
|
||
// and retains its separate encrypted-file carousel/viewer unchanged.
|
||
if (!resolveUrl) {
|
||
wrap.className = 'message-attachments message-attachment-list';
|
||
const options = { gateway, authorLogin, solanaEndpoint, fallbackServerLogin };
|
||
for (const item of items) {
|
||
const slot = document.createElement('div');
|
||
slot.className = 'message-attachment-item';
|
||
slot.textContent = t('remaining.attachments.loading_file');
|
||
wrap.append(slot);
|
||
void resolveAttachmentDisplayUrl(item, options)
|
||
.then(({ url }) => slot.replaceChildren(createFileCard({ item, url, messageTimestampMs, slide: slot })))
|
||
.catch(() => slot.replaceChildren(createUnavailableBlock(messageTimestampMs, attachmentStorage(item))));
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
let index = 0;
|
||
let pointerStartX = 0;
|
||
let renderGeneration = 0;
|
||
const resolved = new Map();
|
||
const pending = new Map();
|
||
const options = { gateway, authorLogin, solanaEndpoint, fallbackServerLogin };
|
||
|
||
const viewport = document.createElement('div');
|
||
viewport.className = 'message-attachment-carousel-viewport';
|
||
const slide = document.createElement('div');
|
||
slide.className = 'message-attachment-slide';
|
||
const prev = document.createElement('button');
|
||
prev.type = 'button';
|
||
prev.className = 'ui-button message-attachment-arrow message-attachment-arrow--prev';
|
||
prev.textContent = '‹';
|
||
prev.setAttribute('aria-label', t('remaining.attachments.previous_attachment'));
|
||
const next = document.createElement('button');
|
||
next.type = 'button';
|
||
next.className = 'ui-button message-attachment-arrow message-attachment-arrow--next';
|
||
next.textContent = '›';
|
||
next.setAttribute('aria-label', t('remaining.attachments.next_attachment'));
|
||
const counter = document.createElement('div');
|
||
counter.className = 'message-attachment-counter';
|
||
wrap.classList.toggle('has-single-attachment', items.length <= 1);
|
||
|
||
const getResolved = (itemIndex) => {
|
||
if (resolved.has(itemIndex)) return Promise.resolve(resolved.get(itemIndex));
|
||
if (pending.has(itemIndex)) return pending.get(itemIndex);
|
||
const promise = Promise.resolve(resolveUrl ? resolveUrl(items[itemIndex]) : resolveAttachmentDisplayUrl(items[itemIndex], options))
|
||
.then((value) => {
|
||
resolved.set(itemIndex, value);
|
||
pending.delete(itemIndex);
|
||
if (value.objectUrl) registerAttachmentObjectUrl(wrap, value.url);
|
||
return value;
|
||
})
|
||
.catch((error) => {
|
||
pending.delete(itemIndex);
|
||
throw error;
|
||
});
|
||
pending.set(itemIndex, promise);
|
||
return promise;
|
||
};
|
||
|
||
const openViewer = (itemIndex) => {
|
||
const entries = items
|
||
.map((item, i) => {
|
||
const kind = getAttachmentKind(item);
|
||
if (kind !== 'image' && kind !== 'video') return null;
|
||
if (item.ar) return { i, kind, url: buildArweaveDataUrl({ gateway, txId: item.ar }), name: item.name };
|
||
const cached = resolved.get(i);
|
||
return cached ? { i, kind, url: cached.url, name: item.name } : null;
|
||
})
|
||
.filter(Boolean);
|
||
const viewerIndex = Math.max(0, entries.findIndex((entry) => entry.i === itemIndex));
|
||
if (entries.length) openMediaViewer(entries, viewerIndex);
|
||
};
|
||
|
||
const render = () => {
|
||
const generation = ++renderGeneration;
|
||
stopVideos(wrap);
|
||
const item = items[index];
|
||
const currentIndex = index;
|
||
const kind = getAttachmentKind(item);
|
||
viewport.classList.remove('has-landscape-media');
|
||
slide.className = 'message-attachment-slide';
|
||
slide.dataset.unavailable = '0';
|
||
slide.replaceChildren();
|
||
|
||
const loading = document.createElement('div');
|
||
loading.className = 'message-attachment-unavailable';
|
||
loading.textContent = t('remaining.attachments.loading_file');
|
||
slide.append(loading);
|
||
|
||
void getResolved(currentIndex)
|
||
.then(({ url }) => {
|
||
if (generation !== renderGeneration || currentIndex !== index || !wrap.isConnected) return;
|
||
slide.replaceChildren(!resolveUrl
|
||
? createFileCard({ item, url, messageTimestampMs, slide })
|
||
: (kind === 'file' ? createFileCard({ item, url, messageTimestampMs, slide })
|
||
: createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen: () => openViewer(currentIndex) })));
|
||
})
|
||
.catch((error) => {
|
||
if (generation !== renderGeneration || currentIndex !== index || !wrap.isConnected) return;
|
||
replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item), {
|
||
name: item?.name || '',
|
||
sha256: item?.sha256 || '',
|
||
url: buildCurrentServerDebugUrl(item) || error?.message?.match(/https?:\/\/\S+/)?.[0] || '',
|
||
error: error?.message || String(error || ''),
|
||
});
|
||
});
|
||
|
||
prev.hidden = items.length <= 1 || index <= 0;
|
||
next.hidden = items.length <= 1 || index >= items.length - 1;
|
||
counter.hidden = items.length <= 1;
|
||
counter.textContent = items.length > 1 ? t('remaining.attachments.counter', { current: index + 1, total: items.length }) : '';
|
||
};
|
||
|
||
const move = (delta) => {
|
||
const nextIndex = Math.max(0, Math.min(items.length - 1, index + delta));
|
||
if (nextIndex === index) return;
|
||
index = nextIndex;
|
||
render();
|
||
};
|
||
|
||
prev.addEventListener('click', (event) => { event.stopPropagation(); move(-1); });
|
||
next.addEventListener('click', (event) => { event.stopPropagation(); move(1); });
|
||
viewport.addEventListener('pointerdown', (event) => { pointerStartX = event.clientX; });
|
||
viewport.addEventListener('pointerup', (event) => {
|
||
const dx = event.clientX - pointerStartX;
|
||
if (Math.abs(dx) >= 40) move(dx < 0 ? 1 : -1);
|
||
});
|
||
|
||
viewport.append(slide, prev, next);
|
||
wrap.append(viewport, counter);
|
||
render();
|
||
return wrap;
|
||
}
|
||
|
||
export function createAttachmentListElement(attachments = [], options = {}) {
|
||
return createAttachmentCarouselElement(attachments, options);
|
||
}
|