Files
hyprcrd/public/js/modules/gallery.js
T
2026-04-09 19:14:52 +02:00

204 lines
9.8 KiB
JavaScript

// ── Image gallery ──
import { $, esc, api, getCsrf } from './util.js';
const AUDIO_EXT = /\.(mp3|ogg|wav|m4a)$/i;
function isAudio(url) { return AUDIO_EXT.test(url); }
function mediaTile(url, extraClass = '') {
if (isAudio(url)) {
return `<div class="aspect-square bg-t-bg border ${extraClass} rounded overflow-hidden flex flex-col items-center justify-center gap-2 p-2">
<i class="ph ph-music-note text-2xl text-t-dim"></i>
<audio controls preload="metadata" src="${url}" class="w-full" style="height:28px"></audio>
</div>`;
}
return `<div class="aspect-square bg-t-bg border ${extraClass} rounded overflow-hidden">
<img src="${url}" class="w-full h-full object-cover ${extraClass.includes('danger') ? 'opacity-60' : ''}" loading="lazy">
</div>`;
}
import { state } from './state.js';
import { showDialog } from './dialog.js';
function getReferencedUrls() {
const urls = new Set();
for (const card of state.cards) {
const body = card.body || '';
let m;
const mdRe = /!\[[^\]]*\]\(([^)]+)\)/g;
while ((m = mdRe.exec(body)) !== null) urls.add(m[1].split(/\s/)[0]);
const htmlRe = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
while ((m = htmlRe.exec(body)) !== null) urls.add(m[1]);
}
return urls;
}
function findCardForUrl(url) {
for (const card of state.cards) {
const body = card.body || '';
if (body.includes(url)) return card;
}
return null;
}
export async function openGallery() {
const el = $('gallery');
if (!el) return;
const files = await api('api/uploads');
const referenced = getReferencedUrls();
const grid = $('gallery-grid');
const count = $('gallery-count');
const linked = [];
const orphaned = [];
for (const f of files) {
const card = findCardForUrl(f.url);
if (card) {
linked.push({ ...f, cardId: card.id, cardTitle: card.title, cardColor: card.color });
} else {
orphaned.push(f);
}
}
const total = linked.length + orphaned.length;
if (count) count.textContent = `${total} image${total !== 1 ? 's' : ''}${orphaned.length ? ` · ${orphaned.length} orphaned` : ''}`;
if (!total) {
grid.innerHTML = `<div class="col-span-full text-center py-16">
<i class="ph ph-image text-4xl text-t-dim mb-2 block"></i>
<p class="font-pixel text-[10px] text-t-dim">no images</p></div>`;
} else {
let html = '';
if (orphaned.length) {
html += `<div class="col-span-full font-pixel text-[10px] text-t-danger flex items-center gap-1.5 pt-2"><i class="ph ph-warning text-xs"></i>orphaned (not used by any card)</div>`;
html += orphaned.map(f => `
<div class="gallery-item group cursor-pointer" data-orphan="${f.name}">
<div class="relative aspect-square bg-t-bg border border-t-danger/30 rounded overflow-visible">
<img src="${f.url}" class="w-full h-full object-cover opacity-60 rounded" loading="lazy">
<div style="position:absolute;top:4px;right:4px;display:flex;gap:4px;" class="opacity-0 group-hover:opacity-100 transition-opacity">
<button class="w-6 h-6 flex items-center justify-center bg-black/80 text-t-accent rounded border-0 cursor-pointer hover:bg-t-accent hover:text-t-bg transition-colors" data-new-orphan="${f.name}" title="new card"><i class="ph ph-plus text-sm"></i></button>
<button class="w-6 h-6 flex items-center justify-center bg-black/80 text-t-danger rounded border-0 cursor-pointer hover:bg-t-danger hover:text-t-bg transition-colors" data-del-orphan="${f.name}" title="delete"><i class="ph ph-trash text-sm"></i></button>
</div>
</div>
<div class="mt-1 font-pixel text-[8px] text-t-dim truncate">${esc(f.name)}</div>
</div>`).join('');
}
if (linked.length) {
if (orphaned.length) html += `<div class="col-span-full font-pixel text-[10px] text-t-muted flex items-center gap-1.5 pt-3"><i class="ph ph-link text-xs"></i>linked to cards</div>`;
html += linked.map(img => `
<div class="gallery-item group relative cursor-pointer" data-card-id="${img.cardId}" data-gallery-origin="${encodeURIComponent(img.url)}">
${mediaTile(img.url, 'border-t-border')}
<div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity rounded flex flex-col justify-end p-2">
<div class="flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full shrink-0" style="background:${img.cardColor}"></span>
<span class="font-pixel text-[9px] text-white truncate">${esc(img.cardTitle)}</span>
</div>
</div>
</div>`).join('');
}
grid.innerHTML = html;
// Linked image clicks → open card
grid.querySelectorAll('[data-card-id]').forEach(item => {
item.addEventListener('click', () => {
window._openDetail(item.dataset.cardId, {
fromGallery: true,
galleryOrigin: item.dataset.galleryOrigin || null,
});
});
});
// Orphan: click to enlarge
grid.querySelectorAll('[data-orphan]').forEach(item => {
item.addEventListener('click', e => {
if (e.target.closest('button')) return;
const name = item.dataset.orphan;
const f = orphaned.find(o => o.name === name);
if (f && !isAudio(f.url)) openOrphanLightbox(f);
});
});
// Orphan: inline new card button
grid.querySelectorAll('[data-new-orphan]').forEach(btn => {
btn.addEventListener('click', e => {
e.stopPropagation();
const name = btn.dataset.newOrphan;
const label = name.replace(/\.[^.]+$/, '');
closeGallery();
window._openModal({ id: null, title: label, body: `![${label}](uploads/${name})`, color: '#38bdf8', bucket_id: null });
});
});
// Orphan: inline delete button
grid.querySelectorAll('[data-del-orphan]').forEach(btn => {
btn.addEventListener('click', async e => {
e.stopPropagation();
const name = btn.dataset.delOrphan;
if (localStorage.getItem('hyprcrd-confirm-delete') !== '0') {
const ok = await showDialog({ title: 'delete_image', message: `"${name}" loeschen?`, danger: true, okLabel: 'delete' });
if (!ok) return;
}
await fetch(`api/uploads/${name}`, { method: 'DELETE', headers: { 'X-CSRF-Token': getCsrf() } });
openGallery();
});
});
}
el.classList.add('open');
}
function openOrphanLightbox(file) {
let overlay = document.querySelector('.orphan-lightbox');
if (overlay) overlay.remove();
overlay = document.createElement('div');
overlay.className = 'orphan-lightbox';
overlay.style.cssText = 'position:fixed;inset:0;z-index:200;display:flex;align-items:center;justify-content:center;background:rgba(2,6,23,0.92);';
overlay.innerHTML = `
<img src="${file.url}" style="max-width:min(92vw,1400px);max-height:85vh;object-fit:contain;border:1px solid var(--t-border);box-shadow:0 16px 60px rgba(0,0,0,0.55);">
<div style="position:fixed;bottom:24px;left:50%;transform:translateX(-50%);display:flex;gap:8px;">
<button class="orphan-lb-create flex items-center gap-1.5 px-3 py-1.5 text-xs border border-t-accent text-t-accent hover:bg-t-accent hover:text-t-bg transition-colors" style="border-radius:4px;">
<i class="ph ph-plus text-sm"></i><span class="font-pixel text-[10px]">new card</span>
</button>
<button class="orphan-lb-delete flex items-center gap-1.5 px-3 py-1.5 text-xs border border-t-danger text-t-danger hover:bg-t-danger hover:text-t-bg transition-colors" style="border-radius:4px;">
<i class="ph ph-trash text-sm"></i><span class="font-pixel text-[10px]">delete</span>
</button>
</div>
<button style="position:fixed;top:12px;right:12px;color:rgba(255,255,255,0.6);font-size:20px;background:none;border:none;cursor:pointer;" class="orphan-lb-close">
<i class="ph ph-x"></i>
</button>
`;
const close = () => overlay.remove();
overlay.addEventListener('click', e => { if (e.target === overlay) close(); });
overlay.querySelector('.orphan-lb-close').addEventListener('click', close);
overlay.querySelector('.orphan-lb-create').addEventListener('click', async () => {
const name = file.url.split('/').pop().replace(/\.[^.]+$/, '');
close();
closeGallery();
window._openModal({ id: null, title: name, body: `![${name}](${file.url})`, color: '#38bdf8', bucket_id: null });
});
overlay.querySelector('.orphan-lb-delete').addEventListener('click', async () => {
const ok = await showDialog({ title: 'delete_image', message: `"${file.name}" loeschen?`, danger: true, okLabel: 'delete' });
if (!ok) return;
await fetch(`api/uploads/${file.name}`, { method: 'DELETE', headers: { 'X-CSRF-Token': getCsrf() } });
close();
openGallery();
});
document.body.appendChild(overlay);
}
export function closeGallery() {
$('gallery')?.classList.remove('open');
}
$('gallery-close')?.addEventListener('click', closeGallery);
$('gallery')?.addEventListener('click', e => { if (e.target === $('gallery')) closeGallery(); });
$('gallery-btn')?.addEventListener('click', openGallery);