Files
mtusi2026lab5/src/Messenger.Api/wwwroot/attachments.js
T

206 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let token = null, generation = 0, activeLoads = 0;
const cards = new Set(), waiters = [];
let active = null, viewer = null, returnFocus = null;
const observer = new IntersectionObserver(entries => {
for (const entry of entries) {
const card = entry.target.attachment;
card.visible = entry.isIntersecting;
if (card.visible) void load(card).catch(() => {});
else if (active !== card) release(card);
}
}, { rootMargin: '400px' });
const paths = {
download: 'M12 3v12m-5-5 5 5 5-5M5 17v4h14v-4',
close: 'm6 6 12 12M18 6 6 18',
zoom: 'M10 4a6 6 0 1 0 0 12 6 6 0 0 0 0-12m4.5 10.5L21 21M7 10h6m-3-3v6',
left: 'm15 5-7 7 7 7', right: 'm9 5 7 7-7 7'
};
function icon(name) {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
const path = document.createElementNS(svg.namespaceURI, 'path'); path.setAttribute('d', paths[name]);
svg.append(path); return svg;
}
function control(label, name, action) {
const button = document.createElement('button'); button.type = 'button';
button.title = label; button.setAttribute('aria-label', label); button.append(icon(name));
button.addEventListener('click', action); return button;
}
function bytes(size) { return size < 1048576 ? Math.max(1, Math.round(size / 1024)) + ' КБ' : (size / 1048576).toFixed(1) + ' МБ'; }
export function attachmentSession(value) {
generation++; token = value;
if (viewer?.open) viewer.close();
clearAttachmentCards();
}
export function clearAttachmentCards() {
if (viewer?.open) viewer.close();
for (const card of cards) { card.disposed = true; observer.unobserve(card.root); release(card); }
cards.clear();
}
function release(card) {
card.controller?.abort();
if (card.url) URL.revokeObjectURL(card.url);
card.download.disabled = true;
card.url = null; card.image.removeAttribute('src'); card.root.classList.remove('is-ready');
}
async function load(card) {
if (card.url) return;
if (card.promise) return card.promise;
const session = token, version = generation;
if (!session || card.disposed) throw new Error('Сессия недоступна');
card.promise = (async () => {
if (activeLoads >= 2) await new Promise(resolve => waiters.push(resolve));
activeLoads++;
try {
if (card.disposed || version !== generation || (!card.visible && active !== card)) return;
card.root.classList.remove('has-error'); card.status.textContent = 'Загрузка изображения…';
const controller = new AbortController(); card.controller = controller;
const signal = controller.signal;
const options = {headers:{Authorization:'Bearer ' + session},credentials:'omit',cache:'no-store',signal};
let firstCheck=true;
while (firstCheck || !card.meta || card.meta.status === 'queued' || card.meta.status === 'processing') {
firstCheck=false;
const response = await fetch(`/api/v1/attachments/${card.id}`, {...options, signal:AbortSignal.any([signal,AbortSignal.timeout(15000)])});
if (!response.ok) throw new Error('Изображение недоступно');
card.meta = await response.json();
card.name.textContent = card.meta.filename;
card.size.textContent = bytes(card.meta.size_bytes);
card.open.setAttribute('aria-label', 'Открыть ' + card.meta.filename + ' на весь экран');
if (card.meta.status === 'queued' || card.meta.status === 'processing') {
card.status.textContent = card.meta.status === 'queued' ? 'В очереди…' : 'Обрабатывается…';
if(active === card && viewer?.open) viewer.status.textContent=card.status.textContent;
await new Promise((resolve,reject)=>{
const done=()=>{signal.removeEventListener('abort',cancel);resolve();};
const timer=setTimeout(done,1200);
const cancel=()=>{clearTimeout(timer);reject(new DOMException('Cancelled','AbortError'));};
signal.addEventListener('abort',cancel,{once:true});
if(signal.aborted)cancel();
});
}
}
if(card.meta.status === 'failed') throw new Error('Не удалось обработать изображение');
const response = await fetch(`/api/v1/attachments/${card.id}/content`, options);
if (!response.ok) throw new Error('Изображение недоступно');
const blob = await response.blob();
if (card.disposed || version !== generation || controller.signal.aborted) return;
card.url = URL.createObjectURL(blob); card.image.src = card.url;
card.image.alt = card.meta.filename; card.root.classList.add('is-ready');
card.download.disabled = false;
card.status.textContent = '';
} catch (error) {
if (error.name !== 'AbortError' && !card.disposed && version === generation) {
card.root.classList.add('has-error'); card.status.textContent = card.meta?.status === 'failed' ? 'Не удалось обработать изображение' : 'Не удалось загрузить. Нажмите, чтобы повторить.';
}
throw error;
} finally {
card.promise = null; activeLoads--; waiters.shift()?.();
if (card.controller?.signal.aborted && !card.disposed && version === generation && (card.visible || active === card))
queueMicrotask(() => { void load(card).catch(() => {}); });
}
})();
return card.promise;
}
export function attachmentCard(id) {
const root = document.createElement('div'); root.className = 'attachment-card';
const image = document.createElement('img'); image.alt = ''; image.decoding = 'async';
const open = document.createElement('button'); open.type = 'button'; open.className = 'attachment-preview';
open.setAttribute('aria-label', 'Открыть изображение на весь экран');
const status = document.createElement('span'); status.className = 'attachment-status'; status.textContent = 'Загрузка изображения…';
const hint = document.createElement('span'); hint.className = 'attachment-expand'; hint.append(icon('zoom'));
open.append(image, status, hint);
const info = document.createElement('div'); info.className = 'attachment-info';
const label = document.createElement('span'); label.className = 'attachment-label';
const name = document.createElement('span'); name.className = 'attachment-name'; name.textContent = 'Изображение';
const size = document.createElement('span'); size.className = 'attachment-size'; label.append(name, size);
const card = {id, root, open, image, status, name, size, url:null, meta:null, visible:false, disposed:false, promise:null};
const download = control('Скачать изображение', 'download', () => save(card));
download.className = 'attachment-download'; download.disabled = true; card.download = download;
info.append(label, download); root.append(open, info); root.attachment = card;
open.addEventListener('click', () => { if (root.classList.contains('has-error')) { void load(card).catch(() => {}); } else openViewer(card); });
cards.add(card); observer.observe(root); return root;
}
function save(card) {
if (!card?.url) return;
const link = document.createElement('a'); link.href = card.url; link.download = card.meta?.filename || 'image';
document.body.append(link); link.click(); link.remove();
}
function gallery() {
return [...cards].filter(card => !card.disposed && card.root.isConnected).sort((a,b) =>
a.root.compareDocumentPosition(b.root) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
}
function move(direction) {
const items = gallery(), index = items.indexOf(active), next = items[index + direction];
if (next) void show(next);
}
function zoom() {
if (!active?.url) return;
viewer.classList.toggle('is-zoomed');
viewer.zoom.setAttribute('aria-pressed', String(viewer.classList.contains('is-zoomed')));
viewer.stage.scrollTo(0, 0);
}
function createViewer() {
const dialog = document.createElement('dialog'); dialog.className = 'image-viewer';
dialog.setAttribute('aria-label', 'Просмотр изображения');
const header = document.createElement('header'); header.className = 'image-viewer-header';
const label = document.createElement('div'); label.className = 'image-viewer-label';
const name = document.createElement('strong'), detail = document.createElement('span');label.append(name, detail);
const actions = document.createElement('div');actions.className = 'image-viewer-actions';
const zoomButton = control('Увеличить изображение', 'zoom', zoom); zoomButton.setAttribute('aria-pressed','false');
const download = control('Скачать оригинал', 'download', () => save(active));
const close = control('Закрыть просмотр', 'close', () => dialog.close());
actions.append(zoomButton, download, close); header.append(label, actions);
const stage = document.createElement('div'); stage.className = 'image-viewer-stage';
const image = document.createElement('img'); image.alt = '';
const status = document.createElement('p');status.className = 'image-viewer-status';status.setAttribute('role','status');
stage.append(image, status);
const previous = control('Предыдущее изображение', 'left', () => move(-1)); previous.className = 'image-viewer-prev';
const next = control('Следующее изображение', 'right', () => move(1)); next.className = 'image-viewer-next';
dialog.append(header, stage, previous, next); document.body.append(dialog);
Object.assign(dialog, {picture:image, nameLabel:name, detail, status, stage, download, zoom:zoomButton, previous, next});
dialog.addEventListener('click', event => { if (event.target === stage || event.target === dialog) dialog.close(); });
image.addEventListener('dblclick', zoom);
dialog.addEventListener('keydown', event => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); move(event.key === 'ArrowLeft' ? -1 : 1); }
});
let touch = null;
stage.addEventListener('touchstart', e => {touch = e.touches.length === 1 ? [e.touches[0].clientX, e.touches[0].clientY] : null;},{passive:true});
stage.addEventListener('touchend', e => {
if (!touch || dialog.classList.contains('is-zoomed')) return;
const dx=e.changedTouches[0].clientX-touch[0], dy=e.changedTouches[0].clientY-touch[1];touch=null;
if (Math.abs(dx)>65 && Math.abs(dx)>Math.abs(dy)*1.5) move(dx<0?1:-1);
},{passive:true});
dialog.addEventListener('close', () => {
const previousCard=active;active=null;dialog.picture.removeAttribute('src');
document.documentElement.classList.remove('viewing-image');
if(previousCard && !previousCard.visible) release(previousCard);
if(returnFocus?.isConnected) returnFocus.focus({preventScroll:true});
});
return dialog;
}
function openViewer(card) {
if (!viewer) viewer=createViewer();
if (!viewer.open) {returnFocus=document.activeElement;viewer.showModal();document.documentElement.classList.add('viewing-image');}
void show(card);
}
async function show(card) {
const previous=active;active=card;
if(previous && previous!==card && !previous.visible) release(previous);
viewer.classList.remove('is-zoomed');viewer.zoom.setAttribute('aria-pressed','false');
viewer.stage.scrollTo(0,0);viewer.picture.removeAttribute('src');viewer.picture.alt='';
viewer.nameLabel.textContent=card.meta?.filename || 'Изображение';viewer.detail.textContent='';
viewer.status.textContent='Загрузка…';viewer.download.disabled=true;viewer.zoom.disabled=true;
const items=gallery(), index=items.indexOf(card);
viewer.previous.hidden=index<=0;viewer.next.hidden=index===items.length-1;
try {
await load(card);
if(active!==card || !viewer.open || !card.url) return;
viewer.picture.src=card.url;viewer.picture.alt=card.meta.filename;
viewer.nameLabel.textContent=card.meta.filename;
viewer.detail.textContent=`${index+1} из ${items.length} · ${bytes(card.meta.size_bytes)}`;
viewer.status.textContent='';viewer.download.disabled=false;viewer.zoom.disabled=false;
} catch {if(active===card) viewer.status.textContent='Изображение недоступно. Закройте просмотр и повторите загрузку.';}
}