Files
file-upload/static/helpers.js
T
2026-08-27 19:35:30 +08:00

59 lines
2.1 KiB
JavaScript

'use strict';
// ---------------------------------------------------------------------------
// 纯函数 + 倒计时 interval
// 与 app.js 同 <script> 内共享 (load order: app → helpers → batch).
// ---------------------------------------------------------------------------
function formatRemain(iso) {
const ms = new Date(iso).getTime() - Date.now();
if (ms <= 0) return '已过期';
const s = Math.floor(ms / 1000);
if (s < 60) return `剩 ${s} 秒`;
const m = Math.floor(s / 60);
if (m < 60) return `剩 ${m} 分钟`;
const h = Math.floor(m / 60);
if (h < 24) return `剩 ${h} 小时${m % 60 ? ' ' + (m % 60) + ' 分' : ''}`;
const d = Math.floor(h / 24);
return `剩 ${d}${h % 24 ? ' ' + (h % 24) + ' 小时' : ''}`;
}
function isAlmostExpired(iso) {
const ms = new Date(iso).getTime() - Date.now();
return ms > 0 && ms < 60 * 60 * 1000; // < 1h
}
setInterval(() => {
document.querySelectorAll('[data-expires]').forEach(el => {
el.textContent = formatRemain(el.dataset.expires);
el.classList.toggle('danger', isAlmostExpired(el.dataset.expires));
});
}, 1000);
function iconFor(ext) {
const map = { pdf:'📄', zip:'📦', rar:'📦', '7z':'📦', txt:'📄', md:'📄',
png:'🖼', jpg:'🖼', jpeg:'🖼', gif:'🖼', webp:'🖼', svg:'🖼',
mp4:'🎬', mov:'🎬', avi:'🎬', mkv:'🎬',
mp3:'🎵', wav:'🎵', flac:'🎵',
xls:'📊', xlsx:'📊', csv:'📊',
doc:'📃', docx:'📃', ppt:'📽', pptx:'📽' };
return map[ext] || '📁';
}
function formatSize(b) {
if (b == null || isNaN(b)) return '-';
if (b < 1024) return b + ' B';
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(2) + ' MB';
return (b / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}
function formatTime(iso) {
const d = new Date(iso);
const pad = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}