Files
hyprcrd/public/js/modules/gallery.js
T
thandClaude Opus 4.6 f465306c1d global tooltip system, migrate all title attrs to data-tip/data-help
New tooltip.js module with styled tooltips (data-tip) and multi-line
inline help (data-help). Migrates all ~70 native title attributes
across index.php, JS modules, and all plugins. Adds inline help on
9 strategic UI elements (split, superview, zen, extract, assets, etc).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 19:55:17 +02:00

351 lines
17 KiB
JavaScript

// ── Assets (images, audio, PDFs) ──
import { $, esc, api, getCsrf } from './util.js';
const AUDIO_EXT = /\.(mp3|ogg|wav|m4a)$/i;
const PDF_EXT = /\.pdf$/i;
const IMAGE_EXT = /\.(png|jpe?g|gif|webp)$/i;
function fileType(url) {
if (IMAGE_EXT.test(url)) return 'image';
if (AUDIO_EXT.test(url)) return 'audio';
if (PDF_EXT.test(url)) return 'pdf';
return 'other';
}
function isAudio(url) { return AUDIO_EXT.test(url); }
function mediaTile(url, extraClass = '') {
const type = fileType(url);
if (type === 'audio') {
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>`;
}
if (type === 'pdf') {
const name = url.split('/').pop();
return `<div class="aspect-square bg-t-bg border ${extraClass} rounded overflow-hidden flex flex-col items-center justify-center gap-2 p-3">
<i class="ph ph-file-pdf text-3xl text-t-danger"></i>
<span class="font-pixel text-[8px] text-t-muted truncate w-full text-center">${esc(name)}</span>
</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>`;
}
let activeFilter = 'all';
import { state } from './state.js';
import { showDialog } from './dialog.js';
// Cards with full bodies — fetched fresh by openGallery so we don't
// depend on state.cards which may have body=null during the two-phase
// lazy load (loadCards loads /api/cards/meta first, then batches of 25
// with bodies). Without this, most cards look body-less and every file
// appears orphaned until the last batch completes.
let galleryCards = [];
function getReferencedUrls() {
const urls = new Set();
for (const card of galleryCards) {
const body = card.body || '';
let m;
// Markdown images: ![alt](url)
const mdRe = /!\[[^\]]*\]\(([^)]+)\)/g;
while ((m = mdRe.exec(body)) !== null) urls.add(m[1].split(/\s/)[0]);
// HTML images
const htmlRe = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
while ((m = htmlRe.exec(body)) !== null) urls.add(m[1]);
// Slide-image blocks
const slideRe = /```slide-image\s*\n([\s\S]*?)(?:\n```|$)/g;
while ((m = slideRe.exec(body)) !== null) {
const srcMatch = m[1].match(/^\s*src\s*:\s*([^\n]+)/m);
if (srcMatch) urls.add(srcMatch[1].trim());
}
// Markdown links to uploads (PDFs, other assets): [text](uploads/...)
const linkRe = /\[[^\]]*\]\((uploads\/[^)]+)\)/g;
while ((m = linkRe.exec(body)) !== null) urls.add(m[1]);
// Plain URL mentions (catches any format we missed above)
const plainRe = /uploads\/[a-f0-9]{32}\.[a-z0-9]+/gi;
while ((m = plainRe.exec(body)) !== null) urls.add(m[0]);
}
return urls;
}
function findCardForUrl(url) {
for (const card of galleryCards) {
const body = card.body || '';
if (body.includes(url)) return card;
}
return null;
}
export async function openGallery() {
const el = $('gallery');
if (!el) return;
// Fetch both file list and full card bodies in parallel. Using
// api('api/cards') (not state.cards) guarantees bodies are present
// — state.cards may still be in the two-phase lazy-load with
// body=null on most entries.
let files = [], cards = [];
try {
[files, cards] = await Promise.all([
api('api/uploads'),
api('api/cards'),
]);
} catch {}
files = Array.isArray(files) ? files : [];
galleryCards = Array.isArray(cards) ? cards : [];
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} asset${total !== 1 ? 's' : ''}${orphaned.length ? ` · ${orphaned.length} orphaned` : ''}`;
// Tab filter
const allFiles = [...orphaned, ...linked];
const applyFilter = (filter) => {
activeFilter = filter;
document.querySelectorAll('#gallery-tabs .gallery-tab').forEach(t => {
t.classList.toggle('active', t.dataset.filter === filter);
});
let visibleCount = 0;
grid.querySelectorAll('.gallery-item').forEach(item => {
const url = item.dataset.url || '';
const type = fileType(url);
const show = filter === 'all' || type === filter;
item.style.display = show ? '' : 'none';
if (show) visibleCount++;
});
// Hide section headers when no items in that section are visible
grid.querySelectorAll('[data-section]:not(.gallery-item)').forEach(hdr => {
const section = hdr.dataset.section;
const hasVisible = !!grid.querySelector(`.gallery-item[data-section="${section}"]:not([style*="display: none"])`);
hdr.style.display = hasVisible ? '' : 'none';
});
// Show/hide the empty-filter placeholder
let placeholder = grid.querySelector('.gallery-filter-empty');
if (visibleCount === 0 && total > 0) {
if (!placeholder) {
placeholder = document.createElement('div');
placeholder.className = 'gallery-filter-empty col-span-full text-center py-16';
const icons = { image: 'ph-image', audio: 'ph-music-note', pdf: 'ph-file-pdf' };
const icon = icons[filter] || 'ph-folder-open';
placeholder.innerHTML = `<i class="ph ${icon} text-4xl text-t-dim mb-2 block"></i><p class="font-pixel text-[10px] text-t-dim">no ${filter} assets</p>`;
grid.appendChild(placeholder);
}
placeholder.style.display = '';
} else if (placeholder) {
placeholder.style.display = 'none';
}
};
document.querySelectorAll('#gallery-tabs .gallery-tab').forEach(t => {
t.onclick = () => applyFilter(t.dataset.filter);
});
if (!total) {
grid.innerHTML = `<div class="col-span-full text-center py-16">
<i class="ph ph-folder-open text-4xl text-t-dim mb-2 block"></i>
<p class="font-pixel text-[10px] text-t-dim cursor-blink">no assets</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" data-section="orphaned"><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}" data-url="${esc(f.url)}" data-section="orphaned">
<div class="relative">
${mediaTile(f.url, 'border-t-danger/30 opacity-60')}
<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}" data-tip="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-accent rounded border-0 cursor-pointer hover:bg-t-accent hover:text-t-bg transition-colors" data-new-slide="${f.name}" data-tip="new slide"><i class="ph ph-image-square 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}" data-tip="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" data-section="linked"><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)}" data-url="${esc(img.url)}" data-section="linked">
${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 (images) or open in new tab (PDFs)
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) return;
const type = fileType(f.url);
if (type === 'pdf') window.open(f.url, '_blank');
else if (type === 'image') 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();
const type = fileType('uploads/' + name);
const body = type === 'pdf'
? `[📄 ${name}](uploads/${name})`
: `![${label}](uploads/${name})`;
window._openModal({ id: null, title: label, body, color: '#38bdf8', bucket_id: null });
});
});
// Orphan: inline new slide button (creates image slide with slide-image block)
grid.querySelectorAll('[data-new-slide]').forEach(btn => {
btn.addEventListener('click', e => {
e.stopPropagation();
const name = btn.dataset.newSlide;
const label = name.replace(/\.[^.]+$/, '');
closeGallery();
const body = '```slide-image\nsrc: uploads/' + name + '\n```';
window._openModal({ id: null, title: label, body, 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: `Delete "${name}"?`, danger: true, okLabel: 'Delete' });
if (!ok) return;
}
await fetch(`api/uploads/${name}`, { method: 'DELETE', headers: { 'X-CSRF-Token': getCsrf() } });
openGallery();
});
});
}
// Apply the active filter (persists across re-opens within a session)
applyFilter(activeFilter);
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-slide 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-image-square text-sm"></i><span class="font-pixel text-[10px]">New slide</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-slide').addEventListener('click', async () => {
const name = file.url.split('/').pop().replace(/\.[^.]+$/, '');
close();
closeGallery();
const body = '```slide-image\nsrc: ' + file.url + '\n```';
window._openModal({ id: null, title: name, body, color: '#38bdf8', bucket_id: null });
});
overlay.querySelector('.orphan-lb-delete').addEventListener('click', async () => {
const ok = await showDialog({ title: 'delete_image', message: `Delete "${file.name}"?`, 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);
// Upload button
$('gallery-upload')?.addEventListener('click', () => $('gallery-upload-file')?.click());
$('gallery-upload-file')?.addEventListener('change', async e => {
const files = Array.from(e.target.files || []);
if (!files.length) return;
for (const file of files) {
const form = new FormData();
form.append('file', file, file.name);
try {
await fetch('api/upload', {
method: 'POST',
body: form,
headers: { 'X-CSRF-Token': getCsrf() },
});
} catch {}
}
e.target.value = '';
await openGallery();
});