Files
vibemake/js/document-images.js

139 lines
6.2 KiB
JavaScript

// Resolve repository paths before inserting HTML, so the browser never requests
// a README image against /project/ and briefly displays a broken image.
export function documentImageUrl(src, { filePath = 'README.md', rawUrl } = {}) {
if (!rawUrl || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src)) return src;
try {
const url = new URL(src, `https://repository.invalid/${filePath}`);
const path = decodeURIComponent(url.pathname.slice(1));
return rawUrl(path) + url.hash;
} catch { return src; }
}
export function repositoryImageType(src, options = {}) {
// Only our generated repository download URLs need MIME repair. External
// hosts keep native <img> loading (many deliberately do not allow CORS).
if (!options.rawUrl || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src)) return '';
const ext = src.split(/[?#]/)[0].split('.').pop().toLowerCase();
return { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
webp: 'image/webp', gif: 'image/gif', avif: 'image/avif', bmp: 'image/bmp', ico: 'image/x-icon' }[ext] || '';
}
export function prepareDocumentImages(html, options) {
const template = document.createElement('template');
template.innerHTML = html;
for (const img of template.content.querySelectorAll('img')) {
// README data-* attributes are user content, not trusted loader state.
delete img.dataset.documentSrc;
delete img.dataset.documentSvg;
delete img.dataset.documentMime;
const src = img.getAttribute('src');
if (!src) continue;
img.dataset.documentSrc = documentImageUrl(src, options);
const mime = repositoryImageType(src, options);
if (mime) img.dataset.documentMime = mime;
img.removeAttribute('src');
img.removeAttribute('srcset');
img.removeAttribute('sizes');
img.decoding = 'async';
// GitHub and other external hosts should not receive our project URL as a referer.
img.referrerPolicy = 'no-referrer';
}
return template.innerHTML;
}
export function hydrateDocumentImages(root, { retryDelays = [800, 2200] } = {}) {
const cleanups = [];
const begin = (img) => {
const src = img.dataset.documentSrc;
const frame = document.createElement('span');
frame.className = 'document-image';
img.replaceWith(frame);
frame.append(img);
const status = document.createElement('span');
status.className = 'document-image-status';
status.hidden = true;
const message = document.createElement('span');
message.setAttribute('role', 'status');
const retry = document.createElement('button');
retry.type = 'button'; retry.className = 'btn btn-sm'; retry.textContent = '重新加载图片';
const original = document.createElement('a');
original.href = src; original.target = '_blank'; original.rel = 'noopener noreferrer'; original.textContent = '查看原图';
status.append(message, retry, original);
frame.append(status);
let attempts = 0, timer, stopped = false, controller, objectUrl;
const releaseUrl = () => {
if (objectUrl) URL.revokeObjectURL(objectUrl);
objectUrl = undefined;
};
const request = async () => {
if (stopped || !img.isConnected) return;
controller?.abort();
releaseUrl();
img.removeAttribute('src');
if (img.dataset.documentMime) {
const pending = controller = new AbortController();
const timeout = setTimeout(() => pending.abort(), 30_000);
try {
const response = await fetch(src, { signal: pending.signal, referrerPolicy: 'no-referrer', cache: attempts ? 'reload' : 'default' });
if (!response.ok) throw new Error(`Image HTTP ${response.status}`);
const bytes = await response.blob();
if (stopped || pending !== controller || pending.signal.aborted || !img.isConnected) return;
// Repository download currently returns octet-stream + attachment +
// nosniff, including SVGs. Render only as <img>, never inline SVG HTML.
objectUrl = URL.createObjectURL(new Blob([bytes], { type: img.dataset.documentMime }));
img.src = objectUrl + new URL(src, document.baseURI).hash;
} catch {
if (!stopped && pending === controller) failed();
} finally { clearTimeout(timeout); }
return;
}
// External hosts may not allow fetch CORS. Keep native loading and signed URLs.
img.src = src;
};
const loaded = () => {
clearTimeout(timer);
img.hidden = false; status.hidden = true; frame.classList.remove('unavailable');
};
const failed = () => {
if (stopped || !img.isConnected) return;
releaseUrl();
img.hidden = true; status.hidden = false; frame.classList.add('unavailable');
const auto = attempts < retryDelays.length;
message.textContent = auto ? '图片加载中,正在重试…' : '图片暂时未能加载';
retry.hidden = auto; original.hidden = auto;
clearTimeout(timer);
if (auto) timer = setTimeout(request, retryDelays[attempts++]);
};
const manual = (event) => {
event?.preventDefault(); event?.stopPropagation();
attempts = 0; clearTimeout(timer);
retry.hidden = true; original.hidden = true; message.textContent = '图片加载中…';
request();
};
const online = () => { if (!status.hidden) manual(); };
img.addEventListener('load', loaded);
img.addEventListener('error', failed);
retry.addEventListener('click', manual);
window.addEventListener('online', online);
cleanups.push(() => {
stopped = true; clearTimeout(timer);
controller?.abort(); releaseUrl();
img.removeEventListener('load', loaded); img.removeEventListener('error', failed);
window.removeEventListener('online', online);
retry.removeEventListener('click', manual);
});
request();
};
const images = [...root.querySelectorAll('img[data-document-src]')];
let observer;
if ('IntersectionObserver' in window) {
observer = new IntersectionObserver((entries) => {
for (const entry of entries) if (entry.isIntersecting) {
observer.unobserve(entry.target); begin(entry.target);
}
}, { rootMargin: '400px' });
images.forEach((img) => observer.observe(img));
} else images.forEach(begin);
return () => { observer?.disconnect(); cleanups.forEach((cleanup) => cleanup()); };
}