/* Project dashboard UI: board (kanban), gallery and list views, a side panel to edit a project, see its git/storage/tool info and start actions. Icons come from the Lucide sprite served at /icons.svg. */ const STATUS = [ { key: 'idea', label: 'Idee', icon: 'lightbulb', color: '#94a3b8' }, { key: 'active', label: 'Aktiv', icon: 'rocket', color: '#22c55e' }, { key: 'paused', label: 'Pausiert', icon: 'circle-pause', color: '#f59e0b' }, { key: 'done', label: 'Fertig', icon: 'circle-check', color: '#3b82f6' }, { key: 'archived', label: 'Archiviert', icon: 'archive', color: '#8b5cf6' }, ] const STATUS_BY = Object.fromEntries(STATUS.map((s) => [s.key, s])) const PRIO_ORDER = { high: 0, medium: 1, low: 2 } const PRIO_LABEL = { high: 'Hoch', medium: 'Mittel', low: 'Niedrig' } const TECH_ICON = { Unity: 'box', Node: 'hexagon', Electron: 'atom', Expo: 'smartphone', Capacitor: 'smartphone', Vite: 'zap', React: 'atom', '.NET': 'code-xml', Flutter: 'feather', Android: 'smartphone', 'C++/CMake': 'cpu', Python: 'square-terminal', Web: 'globe', Arduino: 'circuit-board', } const GIT_ICON = { green: 'cloud-check', yellow: 'cloud-upload', red: 'cloud-off' } const TIER = { Cache: { label: 'Cache', hint: 'immer neu erzeugbar', cls: 'ok', icon: 'recycle' }, Release: { label: 'Fertiger Build', hint: 'Version – bewusst löschen', cls: 'warn', icon: 'package' }, Output: { label: 'Rohbilder', hint: 'Generator-Output', cls: 'warn', icon: 'images' }, } const ACTION_ICON = { 'Einrichten': 'download', 'Starten': 'play', 'Bauen': 'hammer', 'Werkzeuge': 'wand-sparkles', 'Öffnen': 'folder-open', } let projects = [] let totals = null let scanState = null let cleanupAvailable = false let editing = null let editingTasks = [] let searchTerm = '' let quickFilter = 'all' let activeView = 'board' let scanTimer = null /* ── helpers ──────────────────────────────────────────────────────────── */ const ic = (name, cls = '') => `` // ?r= keeps the browser cache apart when two projects folders have a project of the same name const thumbUrl = (name) => `/api/projects/${encodeURIComponent(name)}/thumb?r=${encodeURIComponent(activeRoots.join(','))}` const api = (name, what) => `/api/projects/${encodeURIComponent(name)}/${what}` function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])) } function timeAgo(iso) { if (!iso) return '' const days = Math.floor((Date.now() - new Date(iso)) / 86400000) if (days <= 0) return 'heute' if (days === 1) return 'gestern' if (days < 30) return `vor ${days} T.` if (days < 365) return `vor ${Math.floor(days / 30)} Mon.` return `vor ${Math.floor(days / 365)} J.` } function fmtMB(mb) { if (mb == null) return '–' if (mb >= 1024) return `${(mb / 1024).toFixed(1).replace('.', ',')} GB` return `${Math.round(mb)} MB` } function nameColor(name) { let hash = 0 for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0 const h = Math.abs(hash) % 360 return `linear-gradient(135deg, hsl(${h} 62% 58%), hsl(${(h + 40) % 360} 62% 48%))` } function initialsOf(name) { const parts = name.split(/[\s_\-.]+/).filter(Boolean) if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase() return name.slice(0, 2).toUpperCase() } // Project icon with letter fallback: the image sits on top of the initials // and removes itself when the project has no picture. function avatar(p, cls = '') { return `
${escapeHtml(initialsOf(p.name))}
` } const deletableMB = (p) => p.storage ? p.storage.deletable.Cache + p.storage.deletable.Release + p.storage.deletable.Output : 0 // last change = newest file in the project (server: lib/activity.js), else last commit / folder date const lastActivity = (p) => p.lastChange?.at ?? p.lastCommit?.date ?? p.mtime function fmtDate(iso, withYear = true) { if (!iso) return '–' return new Date(iso).toLocaleDateString('de-DE', withYear ? { day: '2-digit', month: '2-digit', year: '2-digit' } : { day: '2-digit', month: '2-digit' }) } function changeTitle(p) { const at = lastActivity(p) const when = new Date(at).toLocaleString('de-DE', { dateStyle: 'full', timeStyle: 'short' }) if (p.lastChange) return `Letzte Änderung: ${when}\n${p.lastChange.file}${p.lastChange.partial ? '\n(großes Projekt – nur teilweise durchsucht)' : ''}` return p.lastChange === undefined ? `Wird ermittelt … (bisher: ${when})` : `Letzte Änderung: ${when}` } function sizeTitle(p) { if (p.storage?.sizeMB == null) return 'Ordnergröße: noch nicht gescannt („Alle scannen“ oben)' return `Ordnergröße: ${fmtMB(p.storage.sizeMB)} (gescannt ${timeAgo(p.storage.at)})${deletableMB(p) >= 1 ? ` · davon ${fmtMB(deletableMB(p))} aufräumbar` : ''}` } function factsHtml(p) { return `
${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'} ${ic('file-pen', 'sm')}${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}
` } function gitHtml(git, short = false) { const label = short ? ({ green: 'Gesichert', yellow: 'Ungesichert', red: 'Kein Remote' })[git.level] : git.label return `${ic(GIT_ICON[git.level], 'sm')}${escapeHtml(label)}` } // Backup state of one project (p.lastBackup from the server: own or full backup, newer one) // days after which an un-backed-up change counts as "Backup fällig" (Einstellungen → Backup) let BACKUP_FRESH_DAYS = 7 function cloudInfo(p) { const l = p.lastBackup if (!l) return { level: 'red', short: 'nie', label: 'Backup: noch nie gesichert' } const days = (Date.now() - new Date(l.at)) / 86400000 const when = new Date(l.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' }) const level = l.ok === false ? 'red' : days > BACKUP_FRESH_DAYS ? 'yellow' : 'green' const extra = l.ok === false ? ' – unvollständig' : days > BACKUP_FRESH_DAYS ? ` – älter als ${BACKUP_FRESH_DAYS} Tage` : '' const due = backupDue(p) ? ' · seitdem geändert: Backup fällig' : '' return { level, short: timeAgo(l.at), label: `Backup: gesichert ${when} (${l.how})${extra}${due}` } } // changed since the last backup (or never backed up) and that backup is older than the reminder time function backupDue(p) { const changed = p.lastChange?.at if (!changed || p.folder === '_Tools') return false const l = p.lastBackup if (!l) return true return changed > l.at && Date.now() - new Date(l.at) > BACKUP_FRESH_DAYS * 86400000 } function cloudBadge(p, cls = 'tbadge') { const c = cloudInfo(p) return `${ic('hard-drive')}` } function cloudChip(p) { const c = cloudInfo(p) return `${ic('hard-drive', 'sm')}${escapeHtml(c.short)}` } // itch.io: p.published = { url, title, source: 'auto' | 'manual' } (server, lib/itch.js) function pubTitle(p) { const x = p.published return x ? `Auf itch.io veröffentlicht${x.title ? `: ${x.title}` : ''} (${x.source === 'manual' ? 'manuell eingetragen' : 'automatisch erkannt'}) – Klick öffnet die Seite` : '' } // favorites: a star to toggle (tiles, panel) or a small mark (cards, rows) const favMark = (p) => (p.favorite ? `${ic('star', 'sm')}` : '') const favBtn = (p, cls = '') => `` async function toggleFavorite(p) { try { const res = await fetch(`/api/projects/${encodeURIComponent(p.name)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ favorite: !p.favorite }), }) const r = await res.json().catch(() => ({})) if (!res.ok) throw new Error(r.error ?? 'Speichern fehlgeschlagen') for (const x of [p, projects.find((y) => y.name === p.name), editing?.name === p.name ? editing : null]) if (x) x.favorite = r.favorite render() if (editing?.name === p.name) { const el = document.getElementById('pFav') el.innerHTML = favBtn(editing) wireFav(el, editing) } toast(r.favorite ? `${p.name} ist jetzt Favorit` : `${p.name} ist kein Favorit mehr`, 'star') } catch (e) { toast(e.message, 'triangle-alert') } } function wireFav(el, p) { for (const b of el.querySelectorAll('[data-fav]')) { b.onclick = (e) => { e.stopPropagation(); toggleFavorite(p) } b.addEventListener('mousedown', (e) => e.stopPropagation()) } } function pubChip(p, short = false) { if (!p.published) return '' return `${ic('rocket', 'sm')}${short ? '' : 'itch.io'}` } function pubBadge(p) { if (!p.published) return '' return `${ic('rocket')}` } function statusHtml(key) { const s = STATUS_BY[key] ?? STATUS[0] return `${ic(s.icon, 'sm')}${s.label}` } function prioHtml(prio) { const icon = prio === 'high' ? 'flame' : prio === 'low' ? 'chevron-down' : 'equal' return `${ic(icon, 'sm')}${PRIO_LABEL[prio]}` } // Which projects folder a project is from - only shown when several are on screen. // A project from a subfolder (scanner) also names the folder it lies in. function rootTag(p, short = false) { const parent = p.parent ? `${ic('folder-tree', 'sm')}${short ? '' : ' '}${escapeHtml(p.parent.split('\\').pop())}` : '' if (!multiRoot() || !p.rootName) return parent const path = roots.find((r) => r.id === p.root)?.path ?? '' return `${ic('folder', 'sm')}${short ? '' : ' '}${escapeHtml(p.rootName)}${parent}` } function techChips(types) { return (types ?? []).map((t) => `${ic(TECH_ICON[t] ?? 'code', 'sm')}${escapeHtml(t)}`).join('') } function warnChips(p) { const b = [] if (deletableMB(p) >= 100) b.push(`${ic('brush-cleaning', 'sm')}${fmtMB(deletableMB(p))}`) if (p.tech?.needsInstall) b.push(`${ic('download', 'sm')}npm install`) if (p.tools?.generators?.some((g) => g.kind === 'copy')) b.push(`${ic('copy', 'sm')}Generator-Kopie`) else if (p.tools?.generators?.length) b.push(`${ic('wand-sparkles', 'sm')}ComfyGen`) if (!p.hasIcon) b.push(`${ic('image-off', 'sm')}kein Icon`) return b.join('') } /* ── data ─────────────────────────────────────────────────────────────── */ let rootDir = '' // first shown projects folder let rootPaths = [] // all shown projects folders let roots = [] // registered projects folders [{ id, name, path }] let activeRoots = [] // ids of the shown ones (several possible) const multiRoot = () => activeRoots.length > 1 // optional features (Einstellungen → Allgemein → Funktionen) let FEATURES = { itch: false } const itchOn = () => !!FEATURES.itch async function load() { const res = await fetch(`/api/projects?target=${encodeURIComponent(curTargetId())}`) const data = await res.json() projects = data.projects totals = data.totals scanState = data.scan cleanupAvailable = data.cleanupAvailable rootDir = data.root ?? '' rootPaths = data.rootPaths ?? (rootDir ? [rootDir] : []) roots = data.roots ?? [] activeRoots = data.activeRoots ?? (data.activeRoot ? [data.activeRoot] : []) BACKUP_FRESH_DAYS = data.remindDays ?? 7 FEATURES = data.features ?? { itch: false } document.body.classList.toggle('no-itch', !itchOn()) renderRootPicker() if (editing) editing = projects.find((p) => p.name === editing.name) ?? editing render() renderBackupButton() // "last change" dates are all known → the backup reminder can count if (!data.activityPending && backup) remindBackup() if (scanState?.running) pollScan() // last-change dates are still being collected in the background → refresh once more clearTimeout(load.again) if (data.activityPending > 0) load.again = setTimeout(load, 2500) if (data.setupNeeded) openSettings(true) // first start: choose the projects folder // projects found in subfolders that were never looked at: one hint per session if (data.nestedHint > 0 && !load.nestedHinted && !data.setupNeeded) { load.nestedHinted = true setTimeout(() => toast(`${data.nestedHint} ${data.nestedHint === 1 ? 'Projekt' : 'Projekte'} in Unterordnern gefunden – Klick zum Ansehen`, 'folder-tree', openNested), 1500) } } /* ── new project / clone ──────────────────────────────────────────────── */ const newDlg = document.getElementById('newDlg') function openNewProject(from = '') { closeEditor() const sel = document.getElementById('nFrom') sel.innerHTML = `` + [...projects].sort((a, b) => a.name.localeCompare(b.name, 'de')).map((p) => ``).join('') sel.value = from document.getElementById('nRoot').innerHTML = roots.map((r) => ``).join('') // default: the folder of the template, else the first shown one document.getElementById('nRoot').value = projects.find((p) => p.name === from)?.root ?? activeRoots[0] ?? '' document.getElementById('nExcl').textContent = (settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.venv']).join(', ') document.getElementById('nName').value = from ? `${from} - Kopie` : '' document.getElementById('nError').style.display = 'none' syncNewDlg() newDlg.showModal() document.getElementById('nName').select() } function syncNewDlg() { const clone = !!document.getElementById('nFrom').value document.getElementById('nCloneOpts').hidden = !clone document.getElementById('nEmptyHint').hidden = clone document.getElementById('newTitle').textContent = clone ? 'Projekt klonen' : 'Neues Projekt' document.querySelector('#nOk span').textContent = clone ? 'Klonen' : 'Anlegen' } document.getElementById('nFrom').addEventListener('change', () => { const from = document.getElementById('nFrom').value const name = document.getElementById('nName') // keep a typed name, replace only the suggested one if (!name.value.trim() || / - Kopie$/.test(name.value)) name.value = from ? `${from} - Kopie` : '' syncNewDlg() }) document.getElementById('nCancel').onclick = () => newDlg.close() document.getElementById('btnNew').onclick = () => openNewProject('') document.getElementById('btnClone').onclick = () => { if (editing) openNewProject(editing.name) } /* ── rename / move a project ──────────────────────────────────────────── */ const moveDlg = document.getElementById('moveDlg') let moving = null const driveOf = (p) => (p.match(/^([A-Za-z]:|\\\\[^\\]+\\[^\\]+)/)?.[1] ?? '').toLowerCase() function openMove(p) { moving = p const from = roots.find((r) => r.id === p.root) document.getElementById('mvFrom').textContent = `Jetzt: ${from ? `${from.path}\\` : ''}${p.folder ?? p.name}` document.getElementById('mvName').value = p.folder ?? p.name document.getElementById('mvRoot').innerHTML = roots.map((r) => ``).join('') document.getElementById('mvRoot').value = p.root ?? activeRoots[0] ?? '' document.getElementById('mvCopyOk').checked = false document.getElementById('mvError').style.display = 'none' syncMove() moveDlg.showModal() document.getElementById('mvName').select() } function syncMove() { const from = roots.find((r) => r.id === moving?.root) const to = roots.find((r) => r.id === document.getElementById('mvRoot').value) document.getElementById('mvCopy').hidden = !(from && to && driveOf(from.path) !== driveOf(to.path)) } document.getElementById('mvRoot').addEventListener('change', syncMove) document.getElementById('mvCancel').onclick = () => moveDlg.close() document.getElementById('btnMove').onclick = () => { if (editing) openMove(editing) } document.getElementById('moveForm').addEventListener('submit', async (e) => { e.preventDefault() const err = document.getElementById('mvError') err.style.display = 'none' if (!document.getElementById('mvCopy').hidden && !document.getElementById('mvCopyOk').checked) { err.innerHTML = `${ic('triangle-alert')}
Bitte bestätigen, dass kopiert und das Original danach gelöscht wird.
` err.style.display = '' return } const ok = document.getElementById('mvOk') ok.disabled = true ok.querySelector('span').textContent = document.getElementById('mvCopy').hidden ? 'Wird umbenannt…' : 'Wird kopiert…' try { const r = await postJson(api(moving.name, 'move'), { name: document.getElementById('mvName').value, root: document.getElementById('mvRoot').value }) moveDlg.close() closeEditor() toast(r.shown ? `Jetzt: „${r.name}“ in „${r.rootName}“` : `„${r.name}“ nach „${r.rootName}“ verschoben (wird gerade nicht angezeigt)`, 'folder-pen') await load() const p = r.shown && projects.find((x) => x.name === r.key) if (p) openEditor(p) } catch (ex) { err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(ex.message)}
` err.style.display = '' } finally { ok.disabled = false ok.querySelector('span').textContent = 'Übernehmen' } }) document.getElementById('newForm').addEventListener('submit', async (e) => { e.preventDefault() const ok = document.getElementById('nOk') const err = document.getElementById('nError') const from = document.getElementById('nFrom').value const root = document.getElementById('nRoot').value err.style.display = 'none' ok.disabled = true const label = ok.querySelector('span').textContent ok.querySelector('span').textContent = from ? 'Wird kopiert…' : 'Wird angelegt…' try { const r = await postJson('/api/projects/new', { name: document.getElementById('nName').value, root, from, withGit: document.getElementById('nGit').checked, skipBuild: document.getElementById('nSkipBuild').checked, }) newDlg.close() toast(`${r.cloned ? 'Klon' : 'Projekt'} „${r.name}“ angelegt`, 'folder-plus') if (r.shown) { await load() const p = projects.find((x) => x.name === r.key) if (p) openEditor(p) } } catch (ex) { err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(ex.message)}
` err.style.display = '' } finally { ok.disabled = false ok.querySelector('span').textContent = label } }) /* ── projects folder quick switch (dropdown next to the logo) ─────────── */ const rootMenu = document.getElementById('rootMenu') const rootBtn = document.getElementById('rootBtn') // Each row: [☑ box = add/remove from the view] [name = show only this folder] function renderRootPicker() { const cur = roots.filter((r) => activeRoots.includes(r.id)) document.getElementById('rootName').textContent = !cur.length ? 'Projekte' : cur.length === 1 ? cur[0].name : cur.length === roots.length && cur.length > 2 ? `Alle Ordner (${cur.length})` : cur.map((r) => r.name).join(' + ') rootBtn.title = cur.length ? `Projektordner – angezeigt:\n${cur.map((r) => r.path).join('\n')}` : 'Projektordner wählen' rootMenu.setAttribute('aria-multiselectable', 'true') rootMenu.innerHTML = roots.map((r) => { const on = activeRoots.includes(r.id) return `
` }).join('') + (roots.length > 1 ? `` : '') + `${roots.length ? '
' : ''}` + (hasPicker ? `` : '') + ` ` } // Adds folders via the server and (optionally) switches to the first new one. async function addRoots(paths, activate) { const r = await postJson('/api/roots/add', { paths, activate }) settingsCache = r if (!r.added.length) { toast('Schon in der Liste', 'info'); return r } if (activate) { closeEditor(); searchTerm = ''; document.getElementById('search').value = '' } await load() if (activate) await loadBackup() toast(r.added.length === 1 ? `Projektordner „${r.added[0].name}“ hinzugefügt` : `${r.added.length} Projektordner hinzugefügt`, 'folder-plus') return r } // "Ordner hinzufügen…" (desktop app): folder dialog → add → switch to it async function addRootByPicker() { const chosen = await pickFolder('Ordner mit Projekten wählen', rootDir) if (!chosen) return try { await addRoots([chosen], true) } catch (e) { toast(e.message, 'triangle-alert') } } // "Mehrere Ordner einlesen…": dialog with the subfolder checklist const rootDlg = document.getElementById('rootDlg') function openRootImport() { document.getElementById('rdBody').innerHTML = '' document.getElementById('rdError').style.display = 'none' rootDlg.showModal() document.getElementById('rdPath').focus() } function listRootImport() { document.getElementById('rdError').style.display = 'none' return importList({ dir: document.getElementById('rdPath').value, body: document.getElementById('rdBody'), have: roots.map((r) => r.path.toLowerCase().replace(/[\\/]+$/, '')), onAdd: async (picked) => { try { await addRoots(picked, document.getElementById('rdActivate').checked) rootDlg.close() } catch (e) { const err = document.getElementById('rdError') err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(e.message)}
` err.style.display = '' throw e } }, }) } document.getElementById('rdList').onclick = listRootImport document.getElementById('rdPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listRootImport() } }) document.getElementById('rdPick').onclick = async () => { const input = document.getElementById('rdPath') const chosen = await pickFolder('Übergeordneten Ordner wählen', input.value) if (chosen) { input.value = chosen; listRootImport() } } document.getElementById('rdClose').onclick = () => rootDlg.close() function toggleRootMenu(open = rootMenu.hidden) { rootMenu.hidden = !open rootBtn.setAttribute('aria-expanded', String(open)) if (open) (rootMenu.querySelector('[aria-selected="true"]') ?? rootMenu.querySelector('button'))?.focus() } // Shows the given folders (ids, in list order). keepOpen: the menu stays open (ticking boxes). async function showRoots(ids, keepOpen = false) { if (!keepOpen) toggleRootMenu(false) ids = roots.map((r) => r.id).filter((id) => ids.includes(id)) if (!ids.length || ids.join('|') === activeRoots.join('|')) return const prev = activeRoots activeRoots = ids // tick right away; the projects follow when loaded renderRootPicker() try { await postJson('/api/roots/active', { ids }) closeEditor() searchTerm = '' document.getElementById('search').value = '' await load() await loadBackup() if (!keepOpen) toast(`Projektordner: ${roots.filter((r) => ids.includes(r.id)).map((r) => r.name).join(' + ')}`, 'folder-open') } catch (e) { activeRoots = prev renderRootPicker() toast(e.message, 'triangle-alert') } } rootBtn.onclick = (e) => { e.stopPropagation(); toggleRootMenu() } rootMenu.addEventListener('click', (e) => { e.stopPropagation() const b = e.target.closest('button') if (!b) return if (b.hasAttribute('data-root-manage')) { toggleRootMenu(false); openSettings(false); return } if (b.hasAttribute('data-root-add')) { toggleRootMenu(false); addRootByPicker(); return } if (b.hasAttribute('data-root-import')) { toggleRootMenu(false); openRootImport(); return } if (b.hasAttribute('data-root-nested')) { toggleRootMenu(false); openNested(); return } if (b.hasAttribute('data-root-all')) { showRoots(roots.map((r) => r.id)); return } const t = b.dataset.rootToggle if (t) { const next = activeRoots.includes(t) ? activeRoots.filter((x) => x !== t) : [...activeRoots, t] if (!next.length) return toast('Mindestens ein Ordner bleibt angezeigt', 'info') showRoots(next, true) return } showRoots([b.dataset.root]) }) rootMenu.addEventListener('keydown', (e) => { const items = [...rootMenu.querySelectorAll('button')] const i = items.indexOf(document.activeElement) if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus() } if (e.key === 'Escape') { e.stopPropagation(); toggleRootMenu(false); rootBtn.focus() } }) document.addEventListener('click', () => { if (!rootMenu.hidden) toggleRootMenu(false) }) /* ── settings (projects folder, backup target) ────────────────────────── */ let settingsCache = null let settingsSetup = false // In the desktop app (WebView2) the exe shows a real folder dialog; in a // normal browser the user types the path. const hasPicker = !!window.chrome?.webview const pickWaiters = new Map() if (hasPicker) { window.chrome.webview.addEventListener('message', (e) => { const m = e.data if ((m?.type === 'folderPicked' || m?.type === 'filePicked') && pickWaiters.has(m.id)) { pickWaiters.get(m.id)(m.path ?? ''); pickWaiters.delete(m.id) } if (m?.type === 'appSettings') showAppSettings(m) }) } else document.body.classList.add('no-picker') // window options of the desktop app (tray, autostart) - kept by the launcher, not in settings.json let appSettingsSent = null function showAppSettings(m) { document.getElementById('appWin').hidden = false document.getElementById('fTray').checked = !!m.tray document.getElementById('fAutostart').checked = !!m.autostart if (appSettingsSent) { const what = appSettingsSent appSettingsSent = null toast(what === 'tray' ? (m.tray ? 'Läuft beim Schließen im Hintergrund weiter' : 'Schließen beendet das Dashboard') : (m.autostart ? 'Startet mit Windows' : 'Startet nicht mehr mit Windows'), 'app-window') } } if (hasPicker) { for (const id of ['fTray', 'fAutostart']) { document.getElementById(id).addEventListener('change', (e) => { e.stopPropagation() appSettingsSent = id === 'fTray' ? 'tray' : 'autostart' window.chrome.webview.postMessage({ type: 'appSettings', [appSettingsSent]: e.target.checked }) }) } } function pickDialog(type, title, initial) { return new Promise((resolve) => { const id = Math.random().toString(36).slice(2) pickWaiters.set(id, resolve) window.chrome.webview.postMessage({ type, id, title, initial }) }) } const pickFolder = (title, initial) => pickDialog('pickFolder', title, initial) const pickFile = (title, initial) => pickDialog('pickFile', title, initial) async function openSettings(setup) { settingsSetup = !!setup closeEditor(); closeBackup() try { settingsCache = await (await fetch('/api/settings')).json() } catch {} if (hasPicker) window.chrome.webview.postMessage({ type: 'getAppSettings' }) const s = settingsCache ?? { roots: [], backup: { targets: [], excludeDirs: [] } } shownRootIds = s.activeRoots ?? [s.activeRoot] document.getElementById('fRoots').innerHTML = (s.roots ?? []).map((r) => rootRow(r)).join('') || rootRow() document.getElementById('fImport').hidden = true document.getElementById('fImportBody').innerHTML = '' document.getElementById('fTargets').innerHTML = (s.backup?.targets ?? []).map(targetRow).join('') setExDirs(s.backup?.excludeDirs ?? []) document.getElementById('fRemind').value = s.backup?.remindDays ?? 7 const au = s.backup?.auto ?? { interval: 'off', time: '20:00', weekday: 5, target: 'all' } document.getElementById('fAutoInt').value = au.interval document.getElementById('fAutoTime').value = au.time document.getElementById('fAutoDay').value = String(au.weekday) document.getElementById('fAutoTarget').innerHTML = `` + (s.backup?.targets ?? []).map((t) => ``).join('') document.getElementById('fAutoTarget').value = au.target if (!document.getElementById('fAutoTarget').value) document.getElementById('fAutoTarget').value = 'all' syncAuto() renderAutoStatus() document.getElementById('fItchProfile').value = s.itchProfile ?? '' document.getElementById('fFeatItch').checked = !!s.features?.itch syncFeatures() if (s.features?.itch) loadItchStatus() document.getElementById('spData').innerHTML = s.dataDir ? `
Einstellungen
${escapeHtml(s.dataDir)}
Scan- & Backup-Stand
im selben Ordner (scan.json, backup.json)
Darstellung
Hell / System / Dunkel – oben rechts in der Leiste
` : '' document.getElementById('spWelcome').style.display = setup ? '' : 'none' document.getElementById('spTitle').textContent = setup ? 'Einrichten' : 'Einstellungen' document.getElementById('spError').style.display = 'none' for (const b of document.querySelectorAll('#spTabs button')) b.classList.remove('has-err') setSettingsTab('folders') refreshSettingsRows() const panel = document.getElementById('spanel') panel.classList.remove('dirty') panel.classList.toggle('setup', settingsSetup) panel.classList.add('open') panel.setAttribute('aria-hidden', 'false') document.getElementById('overlay').classList.add('open') } // "12 Spiele gefunden · ohne Projekt: X, Y" under the itch.io profile field async function loadItchStatus(refresh = false) { const el = document.getElementById('spItch') el.className = 'spstatus' el.innerHTML = `${ic('loader')}
itch.io wird gelesen…
` try { const r = refresh ? await postJson('/api/itch/refresh', {}) : await (await fetch('/api/itch')).json() if (!r.profile) { el.innerHTML = ''; return } const un = r.unmatched ?? [] el.className = `spstatus ${r.error ? 'err' : 'ok'}` el.innerHTML = r.error ? `${ic('triangle-alert')}
${escapeHtml(r.error)}
` : `${ic('circle-check')}
${r.games.length} Spiele gefunden.` + (un.length ? ` Ohne Projekt: ${un.map((g) => `${escapeHtml(g.title)}`).join(', ')} – im Projekt unter „Bearbeiten“ den Link eintragen.` : ' Alle einem Projekt zugeordnet.') + '
' } catch (e) { el.className = 'spstatus err'; el.textContent = e.message } } document.getElementById('btnItchRefresh').onclick = async () => { await loadItchStatus(true); load() } function closeSettings() { if (settingsSetup) return // the projects folder is required const panel = document.getElementById('spanel') if (!panel.classList.contains('open')) return panel.classList.remove('open') panel.setAttribute('aria-hidden', 'true') if (!editing && !document.getElementById('bpanel').classList.contains('open')) document.getElementById('overlay').classList.remove('open') } async function saveSettings() { const err = document.getElementById('spError') err.style.display = 'none' const body = { roots: [...document.querySelectorAll('#fRoots .rrow')] .map((r) => ({ id: r.dataset.id, name: r.querySelector('.tname').value, path: r.querySelector('.tpath').value })) .filter((r) => r.path.trim()), activeRoots: settingsCache?.activeRoots ?? [], targets: [...document.querySelectorAll('#fTargets .trow')] .map((r) => ({ id: r.dataset.id, name: r.querySelector('.tname').value, path: r.querySelector('.tpath').value })) .filter((t) => t.path.trim()), excludeDirs: getExDirs(), remindDays: Number(document.getElementById('fRemind').value) || 7, auto: { interval: document.getElementById('fAutoInt').value, time: document.getElementById('fAutoTime').value || '20:00', weekday: Number(document.getElementById('fAutoDay').value), target: document.getElementById('fAutoTarget').value || 'all', }, itchProfile: document.getElementById('fItchProfile').value, features: { itch: document.getElementById('fFeatItch').checked }, } const btn = document.getElementById('spSave') btn.disabled = true try { settingsCache = await postJson('/api/settings', body) settingsSetup = false document.getElementById('spanel').classList.remove('dirty') closeSettings() toast('Einstellungen gespeichert', 'save') await loadBackup() await load() } catch (e) { err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(e.message)}
` err.style.display = '' // mark (and show) the tab the error belongs to const tab = /Backup-Ziel/.test(e.message) ? 'backup' : /itch/i.test(e.message) ? 'itch' : 'folders' for (const b of document.querySelectorAll('#spTabs button')) b.classList.toggle('has-err', b.dataset.stab === tab) setSettingsTab(tab) } finally { btn.disabled = false } } /* automatic backup (settings → Backup) */ function syncAuto() { const v = document.getElementById('fAutoInt').value document.getElementById('fAutoTimeWrap').hidden = !['daily', 'weekly'].includes(v) document.getElementById('fAutoDayWrap').hidden = v !== 'weekly' document.getElementById('fAutoTargetWrap').hidden = v === 'off' || (settingsCache?.backup?.targets?.length ?? 0) < 2 } document.getElementById('fAutoInt').addEventListener('change', syncAuto) // "heute 20:00", "morgen 20:00", "Fr., 14.11. 20:00" function fmtWhen(iso) { const d = new Date(iso), now = new Date() const time = d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }) if (d - now < 60000) return 'gleich' const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime() const diff = Math.round((day(d) - day(now)) / 86400000) return diff === 0 ? `heute ${time}` : diff === 1 ? `morgen ${time}` : `${d.toLocaleDateString('de-DE', { weekday: 'short', day: 'numeric', month: 'numeric' })} ${time}` } function renderAutoStatus() { const el = document.getElementById('spAuto') const sch = backup?.schedule if (!sch || sch.interval === 'off') { el.className = 'spstatus'; el.innerHTML = ''; return } const r = sch.lastResult const last = r ? (r.ok ? `Zuletzt erfolgreich ${timeAgo(r.at)}.` : `Letzter Versuch ${timeAgo(r.at)} fehlgeschlagen – ${escapeHtml(r.targets.filter((t) => !t.ok).map((t) => `${t.name}: ${t.error ?? 'Fehler'}`).join('; '))}`) : 'Noch nie automatisch gesichert.' el.className = `spstatus ${r && !r.ok ? 'err' : r ? 'ok' : ''}` el.innerHTML = `${ic(sch.running ? 'loader' : r && !r.ok ? 'triangle-alert' : 'calendar-clock')}
${sch.running ? 'Läuft gerade. ' : sch.next ? `Nächstes automatisches Backup: ${fmtWhen(sch.next)}. ` : ''}${last}
` } /* settings tabs, dirty marker, Ctrl+S */ // the itch.io tab follows the switch right away (saved with "Speichern") function syncFeatures() { const on = document.getElementById('fFeatItch').checked const btn = document.querySelector('#spTabs button[data-stab="itch"]') btn.style.display = on ? '' : 'none' if (!on && btn.classList.contains('active')) setSettingsTab('general') } document.getElementById('fFeatItch').addEventListener('change', () => { syncFeatures() if (document.getElementById('fFeatItch').checked) loadItchStatus() }) function setSettingsTab(tab) { for (const b of document.querySelectorAll('#spTabs button')) b.classList.toggle('active', b.dataset.stab === tab) for (const p of document.querySelectorAll('#spanel [data-spane]')) p.hidden = p.dataset.spane !== tab } for (const b of document.querySelectorAll('#spTabs button')) b.onclick = () => setSettingsTab(b.dataset.stab) const markSettingsDirty = () => document.getElementById('spanel').classList.add('dirty') document.getElementById('spanel').addEventListener('input', (e) => { if (!e.target.closest('#fImport, #appWin')) markSettingsDirty() }) document.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's' && document.getElementById('spanel').classList.contains('open')) { e.preventDefault() saveSettings() } }) document.getElementById('spOpenData').onclick = async () => { try { await postJson('/api/datadir/open') } catch (e) { toast(e.message, 'triangle-alert') } } // "Durchsuchen…": data-for = input id, or (in a target/folder row) the row's path input document.getElementById('spanel').addEventListener('click', async (e) => { const b = e.target.closest('.pickbtn') if (!b || !hasPicker) return const row = b.closest('.trow, .rrow') const input = row ? row.querySelector('.tpath') : document.getElementById(b.dataset.for) const chosen = await pickFolder(b.dataset.title, input.value) if (!chosen) return input.value = chosen const name = row?.querySelector('.tname') if (name && !name.value) { name.value = row.classList.contains('rrow') ? folderName(chosen) : shortTargetName(chosen); name.size = nameSize(name.value) } if (row) { markSettingsDirty(); refreshSettingsRows() } if (b.dataset.for === 'fImportPath') listImport() }) // One list entry (projects folder or backup target): [icon] name + badges / path / info line [actions] const folderName = (p) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || p let shownRootIds = [] // folders shown on the board (badge "angezeigt") // the name field grows with its text, so the badges sit right after it const nameSize = (v) => Math.min(40, Math.max(10, (v ?? '').length + 2)) function settingsItem(kind, x, placeholder) { const isRoot = kind === 'root' return `
${ic(isRoot ? 'folder' : 'hard-drive')}
` } const rootRow = (r = { id: '', name: '', path: '' }) => settingsItem('root', r, 'z. B. D:\\Projekte') const targetRow = (t = { id: '', name: '', path: '' }) => settingsItem('target', t, 'z. B. E:\\Backup\\Projekte oder \\\\NAS\\Freigabe\\Projekte') // badges and info lines depend on the order (first = main folder / default target) function refreshSettingsRows() { const rows = [...document.querySelectorAll('#fRoots .rrow')] rows.forEach((row, i) => { const id = row.dataset.id const name = row.querySelector('.tname').value.trim() || folderName(row.querySelector('.tpath').value.trim()) const n = id && shownRootIds.includes(id) ? projects.filter((p) => p.root === id).length : null row.querySelector('.sbadges').innerHTML = (i === 0 ? `${ic('star')}Hauptordner ` : '') + (id && shownRootIds.includes(id) ? `${ic('eye')}angezeigt` : '') row.querySelector('.sstat').innerHTML = row.querySelector('.tpath').value.trim() ? `${n != null ? `${n} Projekte` : ''}${i === 0 ? 'Backup direkt ins Ziel' : `Backup in Unterordner „${escapeHtml(name)}“`}` : 'Pfad eintragen oder Ordner wählen' row.querySelector('[data-up]').disabled = i === 0 }) const trows = [...document.querySelectorAll('#fTargets .trow')] trows.forEach((row, i) => { const st = backup?.targets?.find((t) => t.id === row.dataset.id) const last = st?.last row.querySelector('.sbadges').innerHTML = (i === 0 ? `Standard ` : '') + (!row.dataset.id ? '' : last ? `${last.ok ? 'gesichert' : 'unvollständig'} ${timeAgo(last.at)}` : 'noch nie komplett') row.querySelector('.sstat').innerHTML = row.dataset.id ? '' : 'Neu – wird beim Speichern geprüft' row.querySelector('[data-up]').disabled = i === 0 }) document.getElementById('spnFolders').textContent = rows.length || '' document.getElementById('spnTargets').textContent = trows.length || '' } const rowRootPaths = () => [...document.querySelectorAll('#fRoots .rrow .tpath')].map((i) => i.value.trim().toLowerCase().replace(/[\\/]+$/, '')).filter(Boolean) function addRootRow(r) { const box = document.getElementById('fRoots') // replace a single empty row (first start) instead of adding below it const empty = [...box.querySelectorAll('.rrow')].find((x) => !x.querySelector('.tpath').value.trim() && !x.querySelector('.tname').value.trim()) if (empty && r) empty.remove() box.insertAdjacentHTML('beforeend', rootRow(r)) markSettingsDirty() refreshSettingsRows() return box.lastElementChild } document.getElementById('fAddRoot').onclick = () => addRootRow().querySelector('.tpath').focus() // ↑ / ✕ in both lists for (const id of ['fRoots', 'fTargets']) { const list = document.getElementById(id) list.addEventListener('click', (e) => { const row = e.target.closest('.sitem') if (!row) return if (e.target.closest('[data-rm]')) row.remove() else if (e.target.closest('[data-up]') && row.previousElementSibling) row.parentNode.insertBefore(row, row.previousElementSibling) else return markSettingsDirty() refreshSettingsRows() }) list.addEventListener('input', (e) => { if (e.target.classList.contains('tname')) e.target.size = nameSize(e.target.value) refreshSettingsRows() }) } // "Nicht sichern" as chips: Enter or comma adds, ✕ removes, Backspace in the empty field removes the last const exBox = document.getElementById('fExDirs') const exInput = document.getElementById('fExInput') function addExChip(v) { v = v.trim() if (!v || getExDirs(false).some((x) => x.toLowerCase() === v.toLowerCase())) return exInput.insertAdjacentHTML('beforebegin', `${escapeHtml(v)}`) } function setExDirs(list) { for (const c of exBox.querySelectorAll('.xchip')) c.remove() exInput.value = '' for (const v of list) addExChip(v) } // withPending: also what is still typed in the field function getExDirs(withPending = true) { const list = [...exBox.querySelectorAll('.xchip')].map((c) => c.dataset.v) if (withPending) for (const v of exInput.value.split(',')) if (v.trim() && !list.includes(v.trim())) list.push(v.trim()) return list } exInput.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault() for (const v of exInput.value.split(',')) addExChip(v) exInput.value = '' markSettingsDirty() } else if (e.key === 'Backspace' && !exInput.value) { exBox.querySelector('.xchip:last-of-type')?.remove() markSettingsDirty() } }) exBox.addEventListener('click', (e) => { const rm = e.target.closest('.xchip button') if (rm) { rm.closest('.xchip').remove(); markSettingsDirty(); return } exInput.focus() }) // "Mehrere einlesen…": list the subfolders of a folder, tick the ones to add document.getElementById('fImportOpen').onclick = () => { const box = document.getElementById('fImport') box.hidden = !box.hidden if (!box.hidden) document.getElementById('fImportPath').focus() } document.getElementById('fImportList').onclick = () => listImport() document.getElementById('fImportPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listImport() } }) function listImport() { return importList({ dir: document.getElementById('fImportPath').value, body: document.getElementById('fImportBody'), have: rowRootPaths(), onAdd: (picked) => { for (const p of picked) addRootRow({ id: '', name: folderName(p), path: p }) document.getElementById('fImport').hidden = true toast(`${picked.length} Projektordner hinzugefügt – Speichern nicht vergessen`, 'folder-plus') }, }) } // Lists the subfolders of `dir` in `body` as checkboxes (plus the folder itself); // folders in `have` (lower-case paths) are shown as already added. onAdd(paths) gets the ticked ones. async function importList({ dir, body, have, onAdd }) { dir = (dir ?? '').trim() if (!dir) return body.innerHTML = `
${ic('loader', 'sm')} wird gelesen…
` try { const res = await fetch(`/api/subfolders?path=${encodeURIComponent(dir)}`) const r = await res.json() if (!res.ok) throw new Error(r.error ?? res.statusText) const haveSet = new Set(have) const known = (p) => haveSet.has(p.toLowerCase().replace(/[\\/]+$/, '')) const item = (f, label, extra, self = false) => `` body.innerHTML = `
${item({ path: r.path }, `Diesen Ordner selbst (${escapeHtml(folderName(r.path))})`, `${r.folders.length} Projekte`, true)} ${r.folders.map((f) => item(f, escapeHtml(f.name), `${f.count} Unterordner`)).join('') || '
Keine Unterordner.
'}
` body.querySelector('[data-imp-all]').onclick = () => { const boxes = [...body.querySelectorAll('input:not(:disabled):not([data-self])')] const on = !boxes.every((c) => c.checked) for (const c of boxes) c.checked = on } body.querySelector('[data-imp-add]').onclick = async (e) => { const picked = [...body.querySelectorAll('input:checked:not(:disabled)')].map((c) => c.dataset.path) if (!picked.length) return toast('Nichts ausgewählt', 'info') const btn = e.currentTarget btn.disabled = true try { await onAdd(picked); body.innerHTML = '' } finally { btn.disabled = false } } } catch (e) { body.innerHTML = `
${ic('triangle-alert')}
${escapeHtml(e.message)}
` } } // short display name of a backup target: "MYCLOUD-NESYFV" for \\MYCLOUD-NESYFV\..., "E: Backup" for E:\Backup const shortTargetName = (p) => p.match(/^\\\\([^\\]+)/)?.[1] ?? (p.match(/^([A-Za-z]:)/) ? `${p.slice(0, 2)} ${p.split('\\').filter(Boolean).pop() ?? ''}`.trim() : p.split('\\').pop()) document.getElementById('fAddTarget').onclick = () => { document.getElementById('fTargets').insertAdjacentHTML('beforeend', targetRow()) markSettingsDirty() refreshSettingsRows() document.querySelector('#fTargets .trow:last-child .tpath').focus() } document.getElementById('btnSettings').onclick = () => openSettings(false) document.getElementById('btnCloseSettings').onclick = closeSettings document.getElementById('spCancel').onclick = closeSettings document.getElementById('spSave').onclick = saveSettings async function postJson(url, body) { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body ?? {}), }) let data = {} try { data = await res.json() } catch {} if (!res.ok) { // a route the running server doesn't know yet: it's older than this page if (res.status === 404 && !data.error) { checkVersion(); throw new Error('Der Server ist veraltet – oben „Neu starten“ klicken.') } throw new Error(data.error ?? `HTTP ${res.status}`) } return data } /* ── update banner: server code or page changed since start ───────────── */ let uiStampAtLoad = null async function checkVersion() { let v try { const res = await fetch('/api/version', { cache: 'no-store' }) // 404: a server from before this check - certainly older than this page v = res.status === 404 ? { stale: true } : await res.json() } catch { return } if (uiStampAtLoad === null) uiStampAtLoad = v.uiStamp ?? 0 const banner = document.getElementById('updBanner') const btn = document.getElementById('updBtn') if (v.stale) { document.getElementById('updText').textContent = 'Das Dashboard wurde aktualisiert – der Server muss neu starten, damit alles funktioniert.' btn.innerHTML = `${ic('refresh-cw')}Neu starten` btn.onclick = restartServer banner.hidden = false } else if (v.uiStamp > uiStampAtLoad) { document.getElementById('updText').textContent = 'Neue Version der Oberfläche – Seite neu laden.' btn.innerHTML = `${ic('refresh-cw')}Neu laden` btn.onclick = () => location.reload() banner.hidden = false } else banner.hidden = true } async function restartServer() { const btn = document.getElementById('updBtn') btn.disabled = true btn.innerHTML = `${ic('loader')}Startet neu…` try { let before = null try { before = (await (await fetch('/api/version', { cache: 'no-store' })).json()).pid } catch {} const r = await fetch('/api/restart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }) if (r.status === 409) throw new Error((await r.json()).error) // a server from before this feature has no restart: it must be closed by hand if (!r.ok) throw new Error('Dieser Server kann sich noch nicht selbst neu starten – Dashboard einmal schließen und wieder öffnen.') const until = Date.now() + 20000 while (Date.now() < until) { await new Promise((ok) => setTimeout(ok, 700)) try { const v = await (await fetch('/api/version', { cache: 'no-store' })).json() if (v.pid && v.pid !== before) { location.reload(); return } } catch {} } throw new Error('Server antwortet nicht – Dashboard schließen und wieder öffnen.') } catch (e) { toast(e.message, 'triangle-alert') btn.disabled = false btn.innerHTML = `${ic('refresh-cw')}Neu starten` } } checkVersion() setInterval(checkVersion, 60000) window.addEventListener('focus', checkVersion) document.addEventListener('visibilitychange', () => { if (!document.hidden) checkVersion() }) async function patchProject(name, body) { const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) patchProject.error = res.ok ? '' : ((await res.json().catch(() => ({}))).error ?? '') return res.ok } // onClick: the toast becomes clickable (and stays a bit longer) function toast(text, icon = 'info', onClick = null) { const el = document.getElementById('toast') el.innerHTML = `${ic(icon)}${escapeHtml(text)}` el.classList.add('show') el.style.pointerEvents = onClick ? 'auto' : '' el.style.cursor = onClick ? 'pointer' : '' el.onclick = onClick ? () => { el.classList.remove('show'); onClick() } : null clearTimeout(toast.t) toast.t = setTimeout(() => el.classList.remove('show'), onClick ? 8000 : 3400) } const runAction = async (name, id) => { try { const r = await postJson(api(name, 'run'), { id }) toast(`Gestartet: ${r.label}`, 'play') } catch (e) { toast(e.message, 'triangle-alert') } } /* ── filtering & sorting ──────────────────────────────────────────────── */ const QUICK = [ { key: 'all', label: 'Alle', icon: 'layers', test: () => true }, { key: 'nobackup', label: 'Ohne Remote', icon: 'cloud-off', test: (p) => p.git.level === 'red' }, { key: 'unsaved', label: 'Ungesichert', icon: 'cloud-upload', test: (p) => p.git.level === 'yellow' }, { key: 'due', label: 'Backup fällig', icon: 'clock-alert', test: backupDue }, { key: 'cleanable', label: 'Aufräumbar', icon: 'brush-cleaning', test: (p) => deletableMB(p) >= 100 }, { key: 'install', label: 'npm install', icon: 'download', test: (p) => p.tech?.needsInstall }, { key: 'noicon', label: 'Ohne Icon', icon: 'image-off', test: (p) => !p.hasIcon }, { key: 'gencopy', label: 'Generator-Kopie', icon: 'copy', test: (p) => p.tools?.generators?.some((g) => g.kind === 'copy') }, { key: 'fav', label: 'Favoriten', icon: 'star', test: (p) => !!p.favorite }, { key: 'itch', label: 'itch.io', icon: 'rocket', feature: 'itch', test: (p) => !!p.published }, { key: 'noitch', label: 'Fertig, nicht auf itch', icon: 'circle-off', feature: 'itch', test: (p) => p.status === 'done' && !p.published }, ] function matchesSearch(p) { const term = searchTerm.trim().toLowerCase() if (!term) return true return p.name.toLowerCase().includes(term) || p.notes.toLowerCase().includes(term) || (p.description ?? '').toLowerCase().includes(term) || (p.tags ?? []).some((t) => t.toLowerCase().includes(term)) || (p.tech?.types ?? []).some((t) => t.toLowerCase().includes(term)) } function visibleProjects({ useStatus = true } = {}) { const q = QUICK.find((x) => x.key === quickFilter) ?? QUICK[0] const status = document.getElementById('fltStatus').value return projects.filter((p) => matchesSearch(p) && q.test(p) && (!useStatus || status === 'all' || p.status === status)) } function sortProjects(items) { const sort = document.getElementById('fltSort').value return [...items].sort((a, b) => { if (!!a.favorite !== !!b.favorite) return a.favorite ? -1 : 1 // favorites always first if (sort === 'name') return a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }) if (sort === 'priority') return (PRIO_ORDER[a.priority] - PRIO_ORDER[b.priority]) || (new Date(lastActivity(b)) - new Date(lastActivity(a))) if (sort === 'size') return (b.storage?.sizeMB ?? -1) - (a.storage?.sizeMB ?? -1) if (sort === 'clean') return deletableMB(b) - deletableMB(a) return new Date(lastActivity(b)) - new Date(lastActivity(a)) }) } /* ── header: KPIs, quick filters ──────────────────────────────────────── */ function renderKpis() { const t = totals ?? { sizeMB: 0, cacheMB: 0, allMB: 0, scanned: 0, noBackup: 0 } const active = projects.filter((p) => p.status === 'active').length const running = scanState?.running const pct = running && scanState.total ? Math.round((scanState.done / scanState.total) * 100) : 0 document.getElementById('kpis').innerHTML = `
${ic('layers', 'lg')}
${projects.length}
Projekte · ${active} aktiv
${ic('shield-alert', 'lg')}
${t.noBackup}
ohne Git-Remote
${ic('hard-drive', 'lg')}
${t.scanned ? fmtMB(t.sizeMB) : '–'}
${t.scanned ? `belegt (${t.scanned} gescannt)` : 'noch nicht gescannt'}
${ic('brush-cleaning', 'lg')}
${t.scanned ? fmtMB(t.allMB) : '–'}
${t.scanned ? `aufräumbar · Cache ${fmtMB(t.cacheMB)}` : 'aufräumbar'}
${running ? `
${escapeHtml(scanState.current.join(', '))}
` : scanState?.error ? `
${ic('triangle-alert', 'sm')} Scan-Fehler
` : '
Größe & löschbare Ordner messen
'}
` document.getElementById('btnScanAll').onclick = () => startScan(null) for (const el of document.querySelectorAll('.kpi[data-quick]')) { el.onclick = () => { quickFilter = quickFilter === el.dataset.quick ? 'all' : el.dataset.quick; render() } } } function renderQuickFilters() { const base = projects.filter(matchesSearch) // a filter of a switched-off feature (Einstellungen → Allgemein) is gone; if it was active: back to "Alle" if (QUICK.some((q) => q.key === quickFilter && q.feature && !FEATURES[q.feature])) quickFilter = 'all' document.getElementById('chipfilters').innerHTML = QUICK.filter((q) => !q.feature || FEATURES[q.feature]).map((q) => { const n = base.filter(q.test).length if (q.key !== 'all' && n === 0 && quickFilter !== q.key) return '' return `` }).join('') for (const b of document.querySelectorAll('.fchip')) b.onclick = () => { quickFilter = b.dataset.q; render() } } function render() { document.getElementById('count').textContent = !rootDir ? 'Noch kein Projektordner gewählt' : rootPaths.length > 1 ? `${projects.length} Projekte aus ${rootPaths.length} Ordnern` : `${projects.length} Ordner unter ${rootDir}` renderKpis() renderQuickFilters() updateToolbarForView() renderHome() renderBoard() renderGallery() renderList() renderTasks() } // Status filter makes no sense on the board (columns = status), sorting none on tasks. function updateToolbarForView() { document.getElementById('selStatusWrap').style.display = activeView === 'board' ? 'none' : '' document.getElementById('selSortWrap').style.display = activeView === 'tasks' ? 'none' : '' document.getElementById('boardMode').style.display = activeView === 'board' ? '' : 'none' } /* ── scan ─────────────────────────────────────────────────────────────── */ function pollScan() { clearTimeout(scanTimer) scanTimer = setTimeout(async () => { try { scanState = await (await fetch('/api/scan')).json() } catch { return } renderKpis() // the storage page shows results as they come in if (activeView === 'storage') loadStorage() if (scanState.running) pollScan() else { await load() if (editing) loadDetails(editing.name) toast('Scan fertig', 'circle-check') } }, 1500) } async function startScan(name) { try { const r = await postJson('/api/scan', name ? { name } : {}) scanState = r.state renderKpis() if (activeView === 'storage') loadStorage() pollScan() } catch (e) { toast(e.message, 'triangle-alert') } } /* ── quick start ▶ ────────────────────────────────────────────────────── */ // p.quickStart comes from the server: own start command, main exe or first start action function quickStartTitle(p) { const q = p.quickStart return q ? `Starten: ${q.label}${q.detail ? ` (${q.detail})` : ''}` : '' } function qsButton(p) { if (!p.quickStart) return '' return `` } // Card/row corner: [VS Code] [▶]. placeholder keeps rows aligned when a project has no ▶. // explorer: also an [Explorer] button in front. function qsGroup(p, placeholder = false, explorer = false) { const ex = explorer ? `` : '' const vs = `` return `${ex}${vs}${qsButton(p) || (placeholder ? '' : '')}` } function wireQuickStart(el, p) { const wire = (b, fn) => { b.onclick = (e) => { e.stopPropagation(); fn() } b.draggable = false b.addEventListener('mousedown', (e) => e.stopPropagation()) } for (const b of el.querySelectorAll('[data-qs]')) wire(b, () => runAction(p.name, p.quickStart.id)) for (const b of el.querySelectorAll('[data-vs]')) wire(b, () => runAction(p.name, 'vscode')) for (const b of el.querySelectorAll('[data-ex]')) wire(b, () => runAction(p.name, 'explorer')) } /* ── board ────────────────────────────────────────────────────────────── */ // 'cards' = full cards, 'rows' = one compact line per project (both draggable) let boardMode = (() => { try { return localStorage.getItem('dash.boardMode') === 'rows' ? 'rows' : 'cards' } catch { return 'cards' } })() function setBoardMode(mode) { boardMode = mode === 'rows' ? 'rows' : 'cards' for (const b of document.querySelectorAll('#boardMode button')) b.classList.toggle('active', b.dataset.mode === boardMode) try { localStorage.setItem('dash.boardMode', boardMode) } catch {} renderBoard() } // compact two-line row: [prio] [icon] name / size · last change · git · backup · tasks [▶] function rowHtml(p) { const c = cloudInfo(p) const open = (p.tasks ?? []).filter((t) => !t.done).length const prioTitle = `Priorität ${PRIO_LABEL[p.priority]}` return `
${avatar(p)}
${favMark(p)}${escapeHtml(p.name)} ${rootTag(p, true)} ${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'} ${ic('file-pen', 'sm')}${fmtDate(lastActivity(p))}${fmtDate(lastActivity(p), false)} ${ic(GIT_ICON[p.git.level], 'sm')} ${ic('hard-drive', 'sm')} ${open ? `${ic('list-checks', 'sm')}${open}` : ''} ${p.published ? `${ic('rocket', 'sm')}` : ''}
${qsGroup(p, true, true)}
` } function cardHtml(p) { const total = (p.tasks ?? []).length const done = (p.tasks ?? []).filter((t) => t.done).length const tags = (p.tags ?? []).map((t) => `${ic('tag', 'sm')}${escapeHtml(t)}`).join('') return `
${avatar(p)}
${favMark(p)}${escapeHtml(p.name)}
${prioHtml(p.priority)}
${qsGroup(p, false, true)}
${p.lastCommit ? `
${ic('git-commit-horizontal', 'sm')}${escapeHtml(p.lastCommit.message)}
` : ''} ${factsHtml(p)}
${gitHtml(p.git)}${cloudChip(p)}${pubChip(p)}
${multiRoot() || p.parent ? `
${rootTag(p)}
` : ''}
${techChips(p.tech?.types)}${warnChips(p)}${tags}
${p.notes ? `
${escapeHtml(p.notes)}
` : ''} ${total ? `
${ic('list-checks', 'sm')}${done}/${total}
` : ''}` } function renderBoard() { const board = document.getElementById('board') board.innerHTML = '' const visible = visibleProjects({ useStatus: false }) for (const col of STATUS) { const items = visible .filter((p) => p.status === col.key) .sort((a, b) => (PRIO_ORDER[a.priority] - PRIO_ORDER[b.priority]) || (new Date(lastActivity(b)) - new Date(lastActivity(a)))) const colEl = document.createElement('div') colEl.className = 'column' colEl.innerHTML = `

${ic(col.icon, 'sm')}${col.label}${items.length}

` colEl.addEventListener('dragover', (e) => { e.preventDefault(); colEl.classList.add('drag-over') }) colEl.addEventListener('dragleave', () => colEl.classList.remove('drag-over')) colEl.addEventListener('drop', async (e) => { e.preventDefault() colEl.classList.remove('drag-over') const name = e.dataTransfer.getData('text/plain') const project = projects.find((p) => p.name === name) if (!project || project.status === col.key) return if (await patchProject(name, { status: col.key })) { toast(`${name} → ${col.label}`, col.icon); load() } }) // cards live in their own scroll area, so the page never grows const cardsEl = document.createElement('div') cardsEl.className = 'cards' colEl.appendChild(cardsEl) if (!items.length) cardsEl.innerHTML = `
${ic('inbox')}
` for (const p of items) { const card = document.createElement('div') card.className = boardMode === 'rows' ? 'card row' : 'card' card.draggable = true card.innerHTML = boardMode === 'rows' ? rowHtml(p) : cardHtml(p) card.addEventListener('dragstart', (e) => { e.dataTransfer.setData('text/plain', p.name); card.classList.add('dragging') }) card.addEventListener('dragend', () => card.classList.remove('dragging')) card.onclick = () => openEditor(p) wireQuickStart(card, p) cardsEl.appendChild(card) } board.appendChild(colEl) } } /* ── gallery ──────────────────────────────────────────────────────────── */ function renderGallery() { const grid = document.getElementById('galleryGrid') const items = sortProjects(visibleProjects()) if (!items.length) { grid.innerHTML = `
${ic('search-x', 'xl')}
Keine Projekte gefunden.
`; return } grid.innerHTML = '' for (const p of items) { const tile = document.createElement('div') tile.className = 'tile' tile.title = p.name tile.innerHTML = `
${escapeHtml(initialsOf(p.name))} ${statusHtml(p.status)} ${favBtn(p, 'onthumb')} ${pubBadge(p)}${cloudBadge(p)}${ic(GIT_ICON[p.git.level])}
${escapeHtml(p.name)}
${qsGroup(p, false, true)}
${techChips(p.tech?.types)}
${prioHtml(p.priority)}${rootTag(p, true)}${p.storage?.sizeMB != null ? `${ic('hard-drive', 'sm')} ${fmtMB(p.storage.sizeMB)} · ` : ''}${timeAgo(lastActivity(p))}
` wireQuickStart(tile, p) wireFav(tile, p) tile.onclick = () => openEditor(p) grid.appendChild(tile) } } /* ── list ─────────────────────────────────────────────────────────────── */ // cls: used by CSS container queries to hide columns in narrow windows const LIST_COLS = [ { label: 'Projekt', sort: 'name' }, { label: 'Status', cls: 'c-status' }, { label: 'Git' }, { label: 'Backup' }, { label: 'Technik', cls: 'c-tech' }, { label: 'Größe', sort: 'size', num: true }, { label: 'Aufräumbar', sort: 'clean', num: true, cls: 'c-clean' }, { label: 'Aktivität', sort: 'mtime', cls: 'c-act' }, { label: '' }, ] function renderList() { const table = document.getElementById('listTable') const items = sortProjects(visibleProjects()) const sort = document.getElementById('fltSort').value table.innerHTML = `${LIST_COLS.map((c) => `${c.label}${c.sort === sort ? ' ' + ic('arrow-down', 'sm') : ''}`).join('')} ${items.map((p) => `
${avatar(p)}${favMark(p)}${escapeHtml(p.name)}${rootTag(p, true)}
${statusHtml(p.status)}${pubChip(p, true)}
${gitHtml(p.git, true)} ${cloudChip(p)}
${techChips(p.tech?.types)}${p.tech?.needsInstall ? `${ic('download', 'sm')}install` : ''}
${fmtMB(p.storage?.sizeMB)} ${p.storage ? fmtMB(deletableMB(p)) : '–'} ${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}
${p.quickStart ? `` : ''}
`).join('') || `Keine Projekte gefunden.`}` for (const th of table.querySelectorAll('th[data-sort]')) { th.onclick = () => { document.getElementById('fltSort').value = th.dataset.sort; render() } } for (const tr of table.querySelectorAll('tbody tr[data-name]')) { const p = projects.find((x) => x.name === tr.dataset.name) tr.onclick = () => openEditor(p) wireQuickStart(tr, p) for (const b of tr.querySelectorAll('button[data-a]')) { b.onclick = (e) => { e.stopPropagation() if (b.dataset.a === 'details') openEditor(p) else runAction(p.name, b.dataset.a) } } } } // views with their own header (no project KPIs / filter toolbar) const WIDE_VIEWS = ['storage', 'activity'] /* ── simple / advanced view (switch in the header) ────────────────────── */ // simple: calm tiles, only the essentials; advanced: everything. Stored per // browser (dash.mode). Default: advanced for an existing setup (a view was // stored before), simple for a fresh one. let uiMode = 'advanced' function lastAdvView() { try { const v = localStorage.getItem('dash.advView'); if (['board', 'gallery', 'list'].includes(v)) return v } catch {} return 'board' } function initUiMode() { let m = null try { m = localStorage.getItem('dash.mode') ?? (localStorage.getItem('dash.view') ? 'advanced' : 'simple') } catch {} m = new URLSearchParams(location.search).get('ui') ?? m applyUiMode(m === 'simple' ? 'simple' : 'advanced') } function applyUiMode(m) { uiMode = m document.body.classList.toggle('simple', m === 'simple') for (const b of document.querySelectorAll('#modeSeg button')) b.classList.toggle('active', b.dataset.ui === m) } function setUiMode(m) { applyUiMode(m) try { localStorage.setItem('dash.mode', m) } catch {} setView(m === 'simple' ? (ADV_VIEWS.includes(activeView) ? 'home' : activeView) : (activeView === 'home' ? lastAdvView() : activeView)) render() if (editing) { openEditor(editing); } } for (const b of document.querySelectorAll('#modeSeg button')) b.onclick = () => setUiMode(b.dataset.ui) // "Projekte" page of the simple view: status pills + tiles, newest first let homeStatus = 'all' const HOME_PILLS = [ { key: 'all', label: 'Alle', test: (p) => p.status !== 'archived' }, { key: 'active', label: 'Aktiv' }, { key: 'idea', label: 'Ideen' }, { key: 'paused', label: 'Pausiert' }, { key: 'done', label: 'Fertig' }, { key: 'archived', label: 'Archiv' }, ] const pillTest = (q) => q.test ?? ((p) => p.status === q.key) function renderHome() { const base = projects.filter(matchesSearch) document.getElementById('homeBar').innerHTML = HOME_PILLS.map((q) => { const n = base.filter(pillTest(q)).length if (q.key !== 'all' && !n && homeStatus !== q.key) return '' return `` }).join('') for (const b of document.querySelectorAll('#homeBar .hpill')) b.onclick = () => { homeStatus = b.dataset.hs; renderHome() } const pill = HOME_PILLS.find((q) => q.key === homeStatus) ?? HOME_PILLS[0] const items = base.filter(pillTest(pill)).sort((a, b) => new Date(lastActivity(b)) - new Date(lastActivity(a))) const grid = document.getElementById('homeGrid') if (!items.length) { grid.innerHTML = `
${ic('search-x', 'xl')}
Keine Projekte gefunden.
`; return } grid.innerHTML = '' // "Alle": favorites get their own row on top const favs = homeStatus === 'all' ? items.filter((p) => p.favorite) : [] const head = (icon, text) => { const h = document.createElement('div'); h.className = 'hgroup'; h.innerHTML = `${ic(icon, 'sm')}${text}`; grid.appendChild(h) } if (favs.length) head('star', 'Favoriten') const ordered = favs.length ? [...favs, null, ...items.filter((p) => !p.favorite)] : items for (const p of ordered) { if (!p) { head('layout-grid', 'Alle Projekte'); continue } const desc = (p.description || p.notes || '').split(/\r?\n/).map((x) => x.trim()).find(Boolean) ?? '' const due = backupDue(p) const tile = document.createElement('div') tile.className = 'htile' tile.innerHTML = `
${favBtn(p, 'ontile')}
${escapeHtml(initialsOf(p.name))}
${escapeHtml(p.name)}
${statusHtml(p.status)}${rootTag(p, true)}
${desc ? escapeHtml(desc) : 'Keine Beschreibung'}
${due ? `` : ''} ${timeAgo(lastActivity(p))} ${qsGroup(p, false, true)}
` wireQuickStart(tile, p) wireFav(tile, p) tile.onclick = () => openEditor(p) grid.appendChild(tile) } } const ADV_VIEWS = ['board', 'gallery', 'list'] function setView(view) { if (uiMode === 'simple' && ADV_VIEWS.includes(view)) view = 'home' if (uiMode === 'advanced' && view === 'home') view = lastAdvView() activeView = view for (const el of document.querySelectorAll('.view')) el.classList.toggle('active', el.id === view) for (const btn of document.querySelectorAll('#tabs button')) btn.classList.toggle('active', btn.dataset.view === view) document.body.classList.toggle('view-wide', WIDE_VIEWS.includes(view)) updateToolbarForView() try { localStorage.setItem('dash.view', view); if (ADV_VIEWS.includes(view)) localStorage.setItem('dash.advView', view) } catch {} if (view === 'storage') loadStorage() if (view === 'activity') loadActivity() } /* ── activity page: calendar heatmap of active projects per day ───────── */ let actData = null let actDay = null let actRange = 7 const DOW = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] const MONTHS = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'] const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` const parseDay = (k) => { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d) } const fmtDay = (k) => parseDay(k).toLocaleDateString('de-DE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }) const nActive = (k) => actData?.days[k]?.projects.length ?? 0 // 0 · 1 · 2 · 3–4 · 5+ active projects const levelOf = (n) => (n <= 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n <= 4 ? 3 : 4) const LEVEL_LABEL = ['keins', '1 Projekt', '2 Projekte', '3–4 Projekte', '5+ Projekte'] async function loadActivity() { try { actData = await (await fetch('/api/activity')).json() } catch { return } if (!actDay || !actData.days[actDay]) { // default: today, else the last day with activity actDay = actData.days[actData.today] ? actData.today : Object.keys(actData.days).sort().pop() ?? actData.today } renderActivity() clearTimeout(loadActivity.t) // last-change dates still being collected → refresh until complete if (actData.pending && activeView === 'activity') loadActivity.t = setTimeout(loadActivity, 3000) } // heatmap grid: weeks as columns (Monday first), `weeks` back from this week function heatGrid(weeks, cell, title) { const today = parseDay(actData?.today ?? dayKey(new Date())) const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7)) const start = new Date(monday); start.setDate(monday.getDate() - (weeks - 1) * 7) let html = DOW.map((d, i) => (i % 2 === 0 ? `${d}` : '')).join('') let lastMonth = -1 for (let w = 0; w < weeks; w++) { const first = new Date(start); first.setDate(start.getDate() + w * 7) if (first.getMonth() !== lastMonth && first.getDate() <= 7) { html += `${MONTHS[first.getMonth()]}` lastMonth = first.getMonth() } else if (w === 0) lastMonth = first.getMonth() for (let r = 0; r < 7; r++) { const d = new Date(first); d.setDate(first.getDate() + r) const k = dayKey(d) const future = d > today html += `` } } return html } function renderActivity() { if (!actData) return const keys = Object.keys(actData.days).filter((k) => nActive(k) > 0).sort() // streaks: consecutive active days; the current one may end yesterday let longest = 0, run = 0, prev = null for (const k of keys) { run = prev && (parseDay(k) - parseDay(prev)) === 86400000 ? run + 1 : 1 longest = Math.max(longest, run); prev = k } let current = 0 const t = parseDay(actData.today) const d = new Date(t) if (!nActive(dayKey(d))) d.setDate(d.getDate() - 1) while (nActive(dayKey(d))) { current++; d.setDate(d.getDate() - 1) } const best = keys.reduce((b, k) => (nActive(k) > (b ? nActive(b) : 0) ? k : b), null) document.getElementById('acKpis').innerHTML = `
Aktive Tage
${keys.length}
im letzten Jahr
Aktuelle Serie
${current} ${current === 1 ? 'Tag' : 'Tage'}
am Stück mit Arbeit
Längste Serie
${longest} ${longest === 1 ? 'Tag' : 'Tage'}
im letzten Jahr
Vollster Tag
${best ? `${nActive(best)} Projekte` : '–'}
${best ? parseDay(best).toLocaleDateString('de-DE') : ''}
` document.getElementById('acPending').textContent = actData.pending ? `· ${actData.pending} Projekte werden noch gelesen…` : '' document.getElementById('acLegend').innerHTML = `weniger${[0, 1, 2, 3, 4].map((l) => ``).join('')}mehr aktive Projekte` const heat = document.getElementById('acHeat') heat.innerHTML = heatGrid(53, (k) => levelOf(nActive(k)), (k) => `${fmtDay(k)}: ${nActive(k)} Projekte`) heat.querySelector(`[data-day="${actDay}"]`)?.classList.add('sel') // start scrolled to the newest weeks on narrow screens heat.parentElement.scrollLeft = heat.parentElement.scrollWidth renderActDay() renderActTop() } function actRow(p, meta) { return `` } const actMeta = (files, commits) => [files ? `${files} ${files === 1 ? 'Datei' : 'Dateien'}` : '', commits ? `${commits} ${commits === 1 ? 'Commit' : 'Commits'}` : ''].filter(Boolean).join(' · ') function renderActDay() { const e = actData.days[actDay] document.getElementById('acDayTitle').textContent = fmtDay(actDay) document.getElementById('acDay').innerHTML = e?.projects.length ? `
${e.projects.map((p) => actRow(p.name, actMeta(p.files, p.commits))).join('')}
` : '
An diesem Tag wurde nichts geändert.
' } function renderActTop() { const since = parseDay(actData.today); since.setDate(since.getDate() - actRange + 1) const agg = new Map() for (const [k, e] of Object.entries(actData.days)) { if (parseDay(k) < since) continue for (const p of e.projects) { const a = agg.get(p.name) ?? { days: 0, files: 0, commits: 0, last: k } a.days++; a.files += p.files; a.commits += p.commits; if (k > a.last) a.last = k agg.set(p.name, a) } } const list = [...agg].sort((a, b) => b[1].days - a[1].days || b[1].last.localeCompare(a[1].last)).slice(0, 15) document.getElementById('acTop').innerHTML = list.length ? `
${list.map(([n, a]) => actRow(n, `${a.days} ${a.days === 1 ? 'Tag' : 'Tage'} · zuletzt ${timeAgo(parseDay(a.last).toISOString())}`)).join('')}
` : '
In diesem Zeitraum keine Änderungen.
' } const acHeat = document.getElementById('acHeat') const acTip = document.getElementById('acTip') acHeat.addEventListener('click', (e) => { const c = e.target.closest('.hc:not(.future)') if (!c) return actDay = c.dataset.day for (const x of acHeat.querySelectorAll('.hc.sel')) x.classList.remove('sel') c.classList.add('sel') renderActDay() }) acHeat.addEventListener('mousemove', (e) => { const c = e.target.closest('.hc:not(.future)') if (!c) { acTip.hidden = true; return } const ev = actData.days[c.dataset.day] acTip.innerHTML = `${escapeHtml(fmtDay(c.dataset.day))}
aktive Projekte${ev?.projects.length ?? 0}
` + (ev ? `
Dateien / Commits${ev.files} / ${ev.commits}
` + ev.projects.slice(0, 4).map((p) => `
${escapeHtml(p.name)}${actMeta(p.files, p.commits)}
`).join('') : '') acTip.hidden = false const card = acHeat.closest('.stcard').getBoundingClientRect() let x = e.clientX - card.left + 14, y = e.clientY - card.top + 14 if (x + acTip.offsetWidth > card.width - 8) x = e.clientX - card.left - acTip.offsetWidth - 14 acTip.style.left = `${x}px`; acTip.style.top = `${y}px` }) acHeat.addEventListener('mouseleave', () => { acTip.hidden = true }) for (const id of ['acDay', 'acTop']) { document.getElementById(id).addEventListener('click', (e) => { const b = e.target.closest('[data-proj]') const p = b && projects.find((x) => x.name === b.dataset.proj) if (p) openEditor(p) }) } for (const b of document.querySelectorAll('#acRange button')) b.onclick = () => { actRange = +b.dataset.range for (const x of document.querySelectorAll('#acRange button')) x.classList.toggle('active', x === b) renderActTop() } // small heatmap (26 weeks) in a project's Info tab async function loadProjectActivity(name) { const box = document.getElementById('actMini') let a try { a = await (await fetch(api(name, 'activity'))).json() } catch { return } if (!box.isConnected || editing?.name !== name) return const score = (k) => (a.files?.[k] ?? 0) + (a.commits?.[k] ?? 0) * 5 // 0 · 1–4 · 5–19 · 20–59 · 60+ (files + 5 × commits) const lv = (k) => { const s = score(k); return s <= 0 ? 0 : s < 5 ? 1 : s < 20 ? 2 : s < 60 ? 3 : 4 } const saved = actData actData = { today: a.today, days: {} } // heatGrid reads "today" from here box.innerHTML = `
${heatGrid(26, lv, (k) => `${fmtDay(k)}: ${actMeta(a.files?.[k] ?? 0, a.commits?.[k] ?? 0) || 'nichts'}`)}
` actData = saved for (const c of box.querySelectorAll('.hc:not(.future)')) c.title = c.getAttribute('aria-label') const days = new Set([...Object.keys(a.files ?? {}), ...Object.keys(a.commits ?? {})]) const cut = new Date(); cut.setDate(cut.getDate() - 182) const n = [...days].filter((k) => parseDay(k) >= cut).length document.getElementById('actMiniInfo').textContent = a.files === null ? 'wird noch gelesen…' : `${n} aktive Tage im letzten halben Jahr` } /* ── storage page: treemap, biggest projects, biggest regenerable folders ─ */ let storageData = null let stPath = [] // [] = all projects · [project] · [project, folder] let stSelected = new Set() const TIER_KEYS = ['Cache', 'Release', 'Output'] const TIER_SHORT = { Cache: 'Cache', Release: 'Builds', Output: 'Rohbilder' } const tierVar = (t) => `var(--t-${t.toLowerCase()})` const fmtMB1 = (mb) => (mb >= 1024 ? `${(mb / 1024).toLocaleString('de-DE', { maximumFractionDigits: mb >= 10240 ? 0 : 1 })} GB` : `${Math.round(mb).toLocaleString('de-DE')} MB`) async function loadStorage() { try { storageData = await (await fetch('/api/storage')).json() } catch { return } // a project that went away (folder switch, rename) leaves the drill-down if (stPath.length && !storageData.projects.some((p) => p.name === stPath[0])) stPath = [] renderStorage() } function renderStorage() { if (!storageData) return renderStorageKpis() renderTreemap() renderStorageTop() renderHogs() } function renderStorageKpis() { const ps = storageData.projects const scanned = ps.filter((p) => p.sizeMB != null) const total = scanned.reduce((s, p) => s + p.sizeMB, 0) const del = { Cache: 0, Release: 0, Output: 0 } for (const p of scanned) for (const t of TIER_KEYS) del[t] += p.deletable?.[t] ?? 0 const delAll = del.Cache + del.Release + del.Output const oldest = scanned.reduce((o, p) => (!o || p.at < o ? p.at : o), null) const scan = storageData.scan const bar = TIER_KEYS.filter((t) => del[t] > 0).map((t) => ``).join('') + (total > delAll ? `` : '') document.getElementById('stKpis').innerHTML = `
Belegt
${fmtMB1(total)}
${scanned.length} Projekte gemessen
Aufräumbar
${fmtMB1(delAll)}
${TIER_KEYS.map((t) => `${TIER_SHORT[t]} ${fmtMB1(del[t])}`).join('')}
Anteil aufräumbar
${total ? Math.round((delAll / total) * 100) : 0} %
vom belegten Platz
Gemessen
${scanned.length} / ${ps.length}
${scan?.running ? `${ic('loader', 'sm')} läuft: ${scan.done}/${scan.total}` : oldest ? `ältester Stand ${timeAgo(oldest)}` : 'noch nichts gemessen'}
` document.getElementById('stScanAll').onclick = () => startScan() } // Squarified treemap (Bruls et al.): items sorted by value, laid out in rows // along the shorter side so tiles stay close to square. -> [{ item, x, y, w, h }] function squarify(items, x, y, w, h) { const out = [] const total = items.reduce((s, it) => s + it.value, 0) if (!total || w <= 0 || h <= 0) return out const scale = (w * h) / total let rest = items.map((it) => ({ it, a: it.value * scale })).filter((r) => r.a > 0) const worst = (row, side) => { const s = row.reduce((t, r) => t + r.a, 0) let max = 0, min = Infinity for (const r of row) { max = Math.max(max, r.a); min = Math.min(min, r.a) } return Math.max((side * side * max) / (s * s), (s * s) / (side * side * min)) } while (rest.length) { const side = Math.min(w, h) const row = [rest[0]] let i = 1 while (i < rest.length && worst([...row, rest[i]], side) <= worst(row, side)) row.push(rest[i++]) rest = rest.slice(i) const s = row.reduce((t, r) => t + r.a, 0) if (w >= h) { // column on the left const cw = s / h let cy = y for (const r of row) { const rh = r.a / cw; out.push({ item: r.it, x, y: cy, w: cw, h: rh }); cy += rh } x += cw; w -= cw } else { // row on top const rh = s / w let cx = x for (const r of row) { const rw = r.a / rh; out.push({ item: r.it, x: cx, y, w: rw, h: rh }); cx += rw } y += rh; h -= rh } } return out } // cleanup info for a path inside a project (rel = "Library" or "android\app") function tierInfo(p, rel) { const full = rel ? `${p.folder}\\${rel}` : p.folder const exact = p.candidates.find((c) => !c.skip && c.path.toLowerCase() === full.toLowerCase()) const inside = { Cache: 0, Release: 0, Output: 0 } const pre = (full + '\\').toLowerCase() for (const c of p.candidates) if (!c.skip && c.path.toLowerCase().startsWith(pre)) inside[c.tier] += c.mb return { tier: exact?.tier ?? null, inside } } const dlStrip = (inside, totalMB) => { const segs = TIER_KEYS.filter((t) => inside[t] > 0) if (!segs.length || !totalMB) return '' // strip width = share of the tile that can go const share = Math.min(1, segs.reduce((s, t) => s + inside[t], 0) / totalMB) return `
${segs.map((t) => ``).join('')}
` } function renderTreemap() { const box = document.getElementById('stTree') const W = box.clientWidth, H = box.clientHeight const ps = storageData.projects const proj = stPath.length ? ps.find((p) => p.name === stPath[0]) : null const crumbs = [``] if (proj) crumbs.push(`›${stPath.length > 1 ? `` : `${escapeHtml(proj.name)}`}`) if (stPath.length > 1) crumbs.push(`›${escapeHtml(stPath[1])}`) if (proj) crumbs.push(``) document.getElementById('stCrumbs').innerHTML = crumbs.join('') document.getElementById('stLegend').innerHTML = TIER_KEYS.map((t) => `${TIER_SHORT[t]}`).join('') + 'Rest' let html = '' const tile = (r, cls, label, sub, attrs, extra = '') => { const big = r.w > 46 && r.h > 30 return `
${big ? `${escapeHtml(label)}${r.h > 44 ? `${sub}` : ''}` : ''}${extra}
` } if (!proj) { const items = ps.filter((p) => p.sizeMB > 0).sort((a, b) => b.sizeMB - a.sizeMB).map((p) => ({ value: p.sizeMB, p })) if (!items.length) { box.innerHTML = `
Noch nichts gemessen – oben „Alle messen“.
`; return } const draw = (list, x, y, w, h) => squarify(list, x, y, w, h).map((r) => { const p = r.item.p const inside = { Cache: p.deletable?.Cache ?? 0, Release: p.deletable?.Release ?? 0, Output: p.deletable?.Output ?? 0 } return tile(r, '', p.name, fmtMB1(p.sizeMB), `data-proj="${escapeHtml(p.name)}"`, dlStrip(inside, p.sizeMB)) }).join('') const groups = multiRoot() ? roots.filter((rt) => activeRoots.includes(rt.id)).map((rt) => ({ rt, list: items.filter((i) => i.p.root === rt.id) })).filter((g) => g.list.length) : [] if (groups.length > 1) { // one block per projects folder, with its name on top for (const g of squarify(groups.map((g) => ({ value: g.list.reduce((s, i) => s + i.value, 0), g })), 0, 0, W, H)) { html += `
${escapeHtml(g.item.g.rt.name)} · ${fmtMB1(g.item.value)}
` html += draw(g.item.g.list, g.x + 2, g.y + 18, g.w - 4, g.h - 20) } } else html = draw(items, 0, 0, W, H) } else { const level = stPath.length > 1 ? proj.tree?.find((c) => c.name === stPath[1])?.children : proj.tree if (!level?.length) { box.innerHTML = `
${proj.sizeMB == null ? 'Dieses Projekt wurde noch nicht gemessen.' : 'Für die Aufteilung nach Ordnern das Projekt neu messen.'}

` document.getElementById('stScanOne').onclick = () => startScan(proj.name) return } const items = level.filter((c) => c.mb > 0).map((c) => ({ value: c.mb, c })) html = squarify(items, 0, 0, W, H).map((r) => { const c = r.item.c const rel = stPath.length > 1 ? `${stPath[1]}\\${c.name}` : c.name const info = c.files || c.merged ? { tier: null, inside: { Cache: 0, Release: 0, Output: 0 } } : tierInfo(proj, rel) const drill = stPath.length === 1 && c.children?.length > 1 const cls = `${info.tier ? `t-${info.tier}` : ''} ${drill ? '' : 'flat'}` return tile(r, cls, c.name, fmtMB1(c.mb), `data-rel="${escapeHtml(rel)}" data-name="${escapeHtml(c.name)}" ${drill ? 'data-drill' : ''}`, info.tier ? '' : dlStrip(info.inside, c.mb)) }).join('') } box.innerHTML = html } // tooltip + clicks on the treemap const stTree = document.getElementById('stTree') const stTip = document.getElementById('stTip') stTree.addEventListener('mousemove', (e) => { const t = e.target.closest('.tm') if (!t) { stTip.hidden = true; return } const ps = storageData?.projects ?? [] let html = '' if (t.dataset.proj) { const p = ps.find((x) => x.name === t.dataset.proj) const d = p.deletable ?? {} html = `${escapeHtml(p.name)}
Größe${fmtMB1(p.sizeMB)}
` + TIER_KEYS.filter((k) => d[k] > 0).map((k) => `
${TIER_SHORT[k]}${fmtMB1(d[k])}
`).join('') + (multiRoot() ? `
Ordner${escapeHtml(p.rootName)}
` : '') + `
gemessen${timeAgo(p.at)}
` } else { const proj = ps.find((x) => x.name === stPath[0]) const level = stPath.length > 1 ? proj.tree.find((c) => c.name === stPath[1]).children : proj.tree const c = level.find((x) => x.name === t.dataset.name) const info = c.files || c.merged ? null : tierInfo(proj, t.dataset.rel) html = `${escapeHtml(t.dataset.rel)}
Größe${fmtMB1(c.mb)}
` + (info?.tier ? `
Löschbar${TIER_SHORT[info.tier]}
` : '') + (info ? TIER_KEYS.filter((k) => info.inside[k] > 0).map((k) => `
darin ${TIER_SHORT[k]}${fmtMB1(info.inside[k])}
`).join('') : '') + (t.hasAttribute('data-drill') ? '
Klick: Unterordner
' : '') } stTip.innerHTML = html stTip.hidden = false const card = stTree.parentElement.getBoundingClientRect() let x = e.clientX - card.left + 14, y = e.clientY - card.top + 14 if (x + stTip.offsetWidth > card.width - 8) x = e.clientX - card.left - stTip.offsetWidth - 14 if (y + stTip.offsetHeight > card.height - 8) y = e.clientY - card.top - stTip.offsetHeight - 14 stTip.style.left = `${x}px`; stTip.style.top = `${y}px` }) stTree.addEventListener('mouseleave', () => { stTip.hidden = true }) const stDrill = (t) => { if (!t) return if (t.dataset.proj) stPath = [t.dataset.proj] else if (t.hasAttribute('data-drill')) stPath = [stPath[0], t.dataset.name] else return stTip.hidden = true renderTreemap() } stTree.addEventListener('click', (e) => stDrill(e.target.closest('.tm'))) stTree.addEventListener('keydown', (e) => { if (e.key === 'Enter') stDrill(e.target.closest('.tm')) }) document.getElementById('stCrumbs').addEventListener('click', (e) => { const b = e.target.closest('button') if (!b) return if (b.hasAttribute('data-open')) { const p = projects.find((x) => x.name === stPath[0]); if (p) { openEditor(p); setSection?.('info') } return } stPath = stPath.slice(0, +b.dataset.crumb) renderTreemap() }) new ResizeObserver(() => { if (activeView === 'storage' && storageData) renderTreemap() }).observe(stTree) function renderStorageTop() { const top = storageData.projects.filter((p) => p.sizeMB > 0).sort((a, b) => b.sizeMB - a.sizeMB).slice(0, 10) const max = top[0]?.sizeMB ?? 1 document.getElementById('stTop').innerHTML = top.length ? `
${top.map((p) => { const d = p.deletable ?? {} const del = TIER_KEYS.reduce((s, t) => s + (d[t] ?? 0), 0) const segs = TIER_KEYS.filter((t) => d[t] > 0).map((t) => ``).join('') + (p.sizeMB > del ? `` : '') return `` }).join('')}
` : '
Noch nichts gemessen.
' } document.getElementById('stTop').addEventListener('click', (e) => { const b = e.target.closest('[data-proj]') if (!b) return stPath = [b.dataset.proj] renderTreemap() document.getElementById('stTree').scrollIntoView({ block: 'nearest', behavior: 'smooth' }) }) // global list of regenerable folders, biggest first function renderHogs() { const can = storageData.cleanupAvailable const rows = storageData.projects.flatMap((p) => p.candidates.filter((c) => !c.skip).map((c) => ({ ...c, p }))) .sort((a, b) => b.mb - a.mb).slice(0, 30) const keyOf = (r) => `${r.p.name}|${r.path}` // first render: Cache preselected (always regenerable) if (!renderHogs.done) { for (const r of rows) if (r.tier === 'Cache') stSelected.add(keyOf(r)); renderHogs.done = true } for (const k of [...stSelected]) if (!rows.some((r) => keyOf(r) === k)) stSelected.delete(k) document.getElementById('stHogs').innerHTML = rows.length ? `${can ? '' : ''}ProjektOrdnerArtGröße ${rows.map((r) => ` ${can ? `` : ''} ${escapeHtml(r.p.name)} ${escapeHtml(inProject(r.path, r.p.folder))} ${TIER_SHORT[r.tier]} ${fmtMB1(r.mb)}`).join('')}` : 'Nichts zum Aufräumen gefunden (oder noch nicht gemessen).' updateHogSel(rows) renderHogs.rows = rows } function updateHogSel(rows = renderHogs.rows ?? []) { const sel = rows.filter((r) => stSelected.has(`${r.p.name}|${r.path}`)) const mb = sel.reduce((s, r) => s + r.mb, 0) document.getElementById('stSel').textContent = sel.length ? `${sel.length} ausgewählt · ${fmtMB1(mb)}` : storageData?.cleanupAvailable ? '' : 'Löschen braucht cleanup.ps1' document.getElementById('stDelete').disabled = !sel.length } document.getElementById('stHogs').addEventListener('click', (e) => { const tr = e.target.closest('tr[data-k]') if (!tr || !storageData?.cleanupAvailable) return const cb = tr.querySelector('input') if (e.target !== cb) cb.checked = !cb.checked if (cb.checked) stSelected.add(tr.dataset.k); else stSelected.delete(tr.dataset.k) updateHogSel() }) document.getElementById('stDelete').onclick = async () => { const sel = (renderHogs.rows ?? []).filter((r) => stSelected.has(`${r.p.name}|${r.path}`)) if (!sel.length) return const mb = sel.reduce((s, r) => s + r.mb, 0) if (!confirm(`${sel.length} Ordner (${fmtMB1(mb)}) endgültig löschen?\n\n${sel.map((r) => `${r.p.name}: ${inProject(r.path, r.p.folder)}`).join('\n')}\n\nSie lassen sich neu erzeugen (npm install, Build …).`)) return const btn = document.getElementById('stDelete') btn.disabled = true btn.innerHTML = `${ic('loader')}Lösche…` const byProject = new Map() for (const r of sel) byProject.set(r.p.name, [...(byProject.get(r.p.name) ?? []), r.path]) let failed = 0 for (const [name, paths] of byProject) { try { await postJson(api(name, 'clean'), { paths }) } catch (e) { failed++; toast(`${name}: ${e.message}`, 'triangle-alert') } } stSelected.clear() btn.innerHTML = `${ic('trash')}Ausgewählte löschen` if (!failed) toast(`${fmtMB1(mb)} freigegeben`, 'brush-cleaning') await loadStorage() load() } /* ── tasks view (all projects) ────────────────────────────────────────── */ let taskMode = 'open' // open | done | all const STATUS_ORDER = { active: 0, paused: 1, idea: 2, done: 3, archived: 4 } const newTaskId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6) // Saves a project's full task list; the UI updates first, a failure reloads. async function saveTasks(p, tasks) { p.tasks = tasks renderTasks() updateTaskCount() if (!(await patchProject(p.name, { tasks }))) { toast('Speichern fehlgeschlagen', 'triangle-alert'); load() } } function updateTaskCount() { const open = projects.reduce((n, p) => n + (p.tasks ?? []).filter((t) => !t.done).length, 0) document.getElementById('taskCount').textContent = open || '' } function renderTasks() { updateTaskCount() const term = searchTerm.trim().toLowerCase() const q = QUICK.find((x) => x.key === quickFilter) ?? QUICK[0] const status = document.getElementById('fltStatus').value // project picker for "add": active projects first const sel = document.getElementById('taskProject') const prev = sel.value || editing?.name const ordered = [...projects].sort((a, b) => (STATUS_ORDER[a.status] - STATUS_ORDER[b.status]) || a.name.localeCompare(b.name, 'de')) sel.innerHTML = ordered.map((p) => ``).join('') if (prev && projects.some((p) => p.name === prev)) sel.value = prev const groups = [] for (const p of ordered) { if (!q.test(p) || (status !== 'all' && p.status !== status)) continue const projectHit = !term || p.name.toLowerCase().includes(term) || (p.tags ?? []).some((t) => t.toLowerCase().includes(term)) const tasks = (p.tasks ?? []).filter((t) => (taskMode === 'all' || (taskMode === 'open' ? !t.done : t.done)) && (projectHit || t.text.toLowerCase().includes(term))) if (tasks.length) groups.push({ p, tasks }) } const el = document.getElementById('taskGroups') el.classList.toggle('isEmpty', !groups.length) if (!groups.length) { el.innerHTML = `
${ic(taskMode === 'done' ? 'inbox' : 'party-popper', 'xl')}
${taskMode === 'open' ? 'Keine offenen Aufgaben.' : 'Keine Aufgaben gefunden.'}
Oben ein Projekt wählen und eine Aufgabe eintragen.
` return } el.innerHTML = groups.map(({ p, tasks }) => { const all = p.tasks ?? [] const done = all.filter((t) => t.done).length return `
${avatar(p)}${escapeHtml(p.name)}${statusHtml(p.status)}${done}/${all.length}
${tasks.map((t) => `
${escapeHtml(t.text)}
`).join('')}
` }).join('') for (const g of el.querySelectorAll('.tgroup')) { const p = projects.find((x) => x.name === g.dataset.name) g.querySelector('.tg-head').onclick = () => openEditor(p) for (const row of g.querySelectorAll('.titem')) { const id = row.dataset.id row.querySelector('input').onchange = (e) => saveTasks(p, (p.tasks ?? []).map((t) => (t.id === id ? { ...t, done: e.target.checked } : t))) row.querySelector('.del').onclick = () => saveTasks(p, (p.tasks ?? []).filter((t) => t.id !== id)) } const input = g.querySelector('.tg-add input') input.onkeydown = (e) => { if (e.key !== 'Enter' || !input.value.trim()) return const text = input.value.trim() saveTasks(p, [...(p.tasks ?? []), { id: newTaskId(), text, done: false }]).then(() => { const again = document.querySelector(`.tgroup[data-name="${CSS.escape(p.name)}"] .tg-add input`) again?.focus() }) } } } function addTaskTop() { const input = document.getElementById('taskNew') const text = input.value.trim() const p = projects.find((x) => x.name === document.getElementById('taskProject').value) if (!text || !p) return input.value = '' if (taskMode === 'done') setTaskMode('open') saveTasks(p, [...(p.tasks ?? []), { id: newTaskId(), text, done: false }]) toast(`Aufgabe zu ${p.name} hinzugefügt`, 'list-checks') input.focus() } function setTaskMode(mode) { taskMode = mode for (const b of document.querySelectorAll('#taskMode button')) b.classList.toggle('active', b.dataset.mode === mode) renderTasks() } /* ── side panel ───────────────────────────────────────────────────────── */ function setSection(sec) { for (const el of document.querySelectorAll('.psec')) el.classList.toggle('active', el.id === `sec-${sec}`) for (const btn of document.querySelectorAll('#ptabs button')) btn.classList.toggle('active', btn.dataset.sec === sec) } function renderTaskList() { const ul = document.getElementById('taskList') ul.innerHTML = '' for (const t of editingTasks) { const li = document.createElement('li') li.className = t.done ? 'done' : '' const cb = document.createElement('input') cb.type = 'checkbox' cb.checked = t.done cb.onchange = () => { t.done = cb.checked; renderTaskList() } const span = document.createElement('span') span.textContent = t.text const del = document.createElement('button') del.className = 'btn ghost' del.innerHTML = ic('trash', 'sm') del.onclick = () => { editingTasks = editingTasks.filter((x) => x !== t); renderTaskList() } li.append(cb, span, del) ul.appendChild(li) } } function addTaskFromInput() { const input = document.getElementById('taskInput') const text = input.value.trim() if (!text) return editingTasks.push({ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text, done: false }) input.value = '' renderTaskList() input.focus() } // cleanup paths are "\rest" (relative to the projects folder) → "rest" // (projects in subfolders: folder is "Sammel\A", so strip the whole folder, not up to the first \) const inProject = (p, folder) => { const pre = folder ? `${folder}\\` : '' return pre && p.toLowerCase().startsWith(pre.toLowerCase()) ? p.slice(pre.length) : p.slice(p.indexOf('\\') + 1) } // opts: { id } for jump targets, { right } html at the end of the heading function section(icon, title, body, opts = {}) { return `

${ic(icon)}${title}${opts.right ? `${opts.right}` : ''}

${body}
` } // "→ in Aktionen": switches the tab and scrolls to the section const jumpLink = (id, label = 'Aktionen') => `${label}${ic('arrow-right', 'sm')}` function bindJumps(root) { for (const a of root.querySelectorAll('.jump')) a.onclick = (e) => { e.preventDefault() setSection('actions') document.getElementById(a.dataset.jump)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) } } /* Info tab: read only - what the project is and how it stands */ function renderInfo(name, d) { const p = projects.find((x) => x.name === name) ?? editing const g = d.git const s = d.storage const del = s ? s.deletable.Cache + s.deletable.Release + s.deletable.Output : 0 const c = cloudInfo(p) const overview = `
Ordner
${escapeHtml(d.path)}
Status
${statusHtml(p.status)} · Priorität ${PRIO_LABEL[p.priority] ?? '–'}
Geändert
${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}${p.lastChange?.file ? ` · ${escapeHtml(p.lastChange.file)}` : ''}
Backup
${ic('hard-drive', 'sm')}${escapeHtml(c.short)}${backupDue(p) ? ' fällig' : ''}
Größe
${s ? `${fmtMB(s.sizeMB)} · gescannt ${timeAgo(s.at)}${del >= 1 ? ` · ${fmtMB(del)} aufräumbar` : ''}` : 'noch nicht gescannt'}
` const gitBody = g.isRepo ? `
Status
${gitHtml(g)}${g.dirty ? ` · ${g.dirty} Änderungen nicht committet` : ''}
Branch
${ic('git-branch', 'sm')} ${escapeHtml(g.branch)}${g.upstream ? ` → ${escapeHtml(g.upstream)}` : ''}${g.ahead ? ` · ${g.ahead} nicht gepusht` : ''}
Remote
${g.remote ? `${escapeHtml(g.remote)}` : 'keins – liegt nur auf dieser Platte'}
Letzter Commit
${g.lastCommit ? `${g.lastCommit.date} · ${escapeHtml(g.lastCommit.message)}` : '–'}
` : `
${gitHtml(g)}
Kein Git-Repository – Änderungen sind nirgends gesichert.
` const ip = d.itchPack ?? { exists: false } const itchBody = `
Veröffentlicht
${p.published ? `${escapeHtml(p.published.title || p.published.url)}` : 'nein'}
Seiten-Paket
${ip.exists ? `${escapeHtml(ip.rel)} · ${timeAgo(ip.at)}` : 'noch keins'}
` const arcs = d.archives ?? [] const arcBody = arcs.length ? `
${arcs.slice(0, 8).map((a) => `
${new Date(a.at).toLocaleDateString('de-DE')}
${escapeHtml(a.name)} · ${fmtMB(a.mb)}
`).join('')}
${arcs.length > 8 ? `
… und ${arcs.length - 8} ältere
` : ''}` : '
Noch keine ZIPs in releases\\.
' const gens = d.tools.generators const genBody = gens.length ? `
${gens.map((x) => `
${escapeHtml(x.rel)}
${x.kind === 'comfygen' ? `${ic('wand-sparkles', 'sm')}nutzt _Tools\\ComfyGen` : `${ic('copy', 'sm')}eigene Kopie
${escapeHtml(x.scripts.join(', '))}
`}
`).join('')}
` : '
Kein Generator-Ordner.
' const genDir = gens.find((x) => x.kind === 'comfygen') const iconBody = d.icon ? `
${escapeHtml(d.icon)}
` : `
${ic('image-off', 'sm')}kein Icon gefunden
${genDir ? 'Mit ComfyGen erzeugen (Prompt „icon“ in prompts.py eintragen):' : 'Generator-Vorlage aus _Tools\\ComfyGen\\template kopieren, dann:'}
cd "${escapeHtml(d.path)}\\${escapeHtml(genDir ? genDir.rel : 'sprite-generator')}" && gen generate icon && gen adopt icon` // description: own text (.dashboard.json), else the README's intro as a suggestion const desc = p.description ?? '' const descBody = desc ? `
${escapeHtml(desc)}
` : d.readme ? `
${escapeHtml(d.readme)}
${ic('file-text', 'sm')} Aus der README – noch keine eigene Beschreibung.
` : '
Noch keine Beschreibung. Kurz notieren, was das für ein Projekt ist.
' const descEdit = `` const el = document.getElementById('sec-info') el.innerHTML = section('notebook-text', 'Beschreibung', `
${descBody}
${descEdit}`, { id: 'info-desc', right: `${ic('pencil', 'sm')}${desc ? 'Ändern' : 'Schreiben'}` }) + section('info', 'Übersicht', overview, { right: del >= 1 ? `${jumpLink('act-clean', 'Aufräumen')}` : '' }) + section('git-branch', 'Git', gitBody, { adv: true, right: jumpLink('act-git', g.isRepo ? 'Push & Remote' : 'Einrichten') }) + (name === '_Tools' || !itchOn() ? '' : section('rocket', 'itch.io', itchBody, { adv: true, right: jumpLink('act-itch', ip.exists ? 'Ansehen' : 'Erzeugen') })) + section('cpu', 'Technik', `
${techChips(d.tech.types) || 'nicht erkannt'}${d.tech.needsInstall ? `${ic('download', 'sm')}npm install nötig` : ''}
`, { adv: true }) + `

${ic('activity')}Aktivität

wird geladen…
` + section('file-archive', 'Release-Archive', arcBody, { adv: true, right: jumpLink('act-zip', 'ZIP erstellen') }) + section('wand-sparkles', 'Generator', genBody, { adv: true }) + section('image', 'App-Icon', iconBody, { adv: true }) bindJumps(el) bindDescription(name, d, el) loadProjectActivity(name) } function bindDescription(name, d, el) { const view = el.querySelector('.pdesc-view') const edit = el.querySelector('.pdesc-edit') const ta = document.getElementById('fDesc') const link = document.getElementById('btnDescEdit') const open = (text) => { ta.value = text view.hidden = true edit.hidden = false link.style.visibility = 'hidden' ta.focus() } const close = () => { view.hidden = false; edit.hidden = true; link.style.visibility = '' } const save = async (text) => { try { const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ description: text }), }) const r = await res.json().catch(() => ({})) if (!res.ok) throw new Error(r.error ?? 'Speichern fehlgeschlagen') for (const p of [editing, projects.find((x) => x.name === name)]) if (p) p.description = r.description toast(r.description ? 'Beschreibung gespeichert' : 'Beschreibung entfernt', 'notebook-text') if (editing?.name === name) renderInfo(name, d) } catch (e) { toast(e.message, 'triangle-alert') } } link.onclick = (e) => { e.preventDefault(); open(editing?.description || '') } document.getElementById('btnDescTake')?.addEventListener('click', () => save(d.readme)) document.getElementById('btnDescReadme')?.addEventListener('click', () => { ta.value = ta.value.trim() ? `${ta.value.trim()}\n\n${d.readme}` : d.readme; ta.focus() }) document.getElementById('btnDescCancel').onclick = close document.getElementById('btnDescSave').onclick = () => save(ta.value) ta.onkeydown = (e) => { if (e.key === 'Enter' && e.ctrlKey) { e.preventDefault(); save(ta.value) } if (e.key === 'Escape') { e.stopPropagation(); close() } } } /* Aktionen tab: everything that does something, grouped */ function gitActionsHtml(name, d) { const g = d.git if (!g.isRepo) { return `
Kein Git-Repository – Änderungen sind nirgends gesichert.
` } const key = d.sshKey const keyHint = key ? `
${ic('key-round', 'sm')} SSH-Schlüssel: ${escapeHtml(key.file)}
` : `
${ic('key-round', 'sm')} Kein SSH-Schlüssel gefunden. Anlegen mit ssh-keygen -t ed25519, dann den Inhalt von .ssh\\id_ed25519.pub bei GitHub/GitLab eintragen.
` const pushBox = !g.remote ? '' : g.dirty ? `
` : `
${g.ahead ? '' : 'nichts Neues zu pushen'}
` return `${pushBox}
${g.remote ? '' : '
Noch kein Remote – erst eintragen, dann erscheint hier „Push“.
'} ${keyHint}
Push läuft in einem eigenen Konsolenfenster (dort erscheinen SSH-Passphrase und Fehler).
` } function archiveHtml(name, d) { const s = d.storage const folder = editing?.folder ?? name const releaseCands = new Set((s?.candidates ?? []).filter((c) => c.Tier === 'Release' && !c.Skip).map((c) => inProject(c.Path, folder).toLowerCase())) const rd = d.releaseDirs ?? [] return `
Landet in ${escapeHtml(folder)}\\releases\\ mit Datum im Namen${rd.length ? '' : ' – kein Build-Ordner gefunden (dist, builds, release, publish …)'}.
` } function itchActionHtml(name, d) { const ip = d.itchPack ?? { exists: false } const p = projects.find((x) => x.name === name) ?? editing if (!ip.exists) { return `
Startet Claude Code mit dem Skill itchiocreater in einer Konsole: Titel, Tagline, Beschreibung, alle Felder, Cover/Banner (ComfyUI) und Screenshots landen in docs\\itchio\\. Rückfragen dort beantworten.
` } return `
${p?.published ? `${ic('external-link')}` : ''}
${escapeHtml(ip.rel)} · zuletzt geändert ${timeAgo(ip.at)}
` } function cleanHtml(d) { const s = d.storage let body if (!s) body = '
Noch nicht gescannt – erst scannen, dann zeigt sich, was weg kann.
' else { const rows = s.candidates.filter((c) => c.MB >= 1 || c.Skip) body = `
Größe
${fmtMB(s.sizeMB)} · gescannt ${timeAgo(s.at)}
Löschbar
Cache ${fmtMB(s.deletable.Cache)} · Builds ${fmtMB(s.deletable.Release)} · Rohbilder ${fmtMB(s.deletable.Output)}
` body += rows.length ? `${rows.map((c) => ``).join('')}
${escapeHtml(inProject(c.Path, editing?.folder))} ${ic(TIER[c.Tier].icon, 'sm')}${TIER[c.Tier].label}${c.Skip ? ` ${ic('lock', 'sm')}in git` : ''} ${fmtMB(c.MB)}
Cache ist vorausgewählt (immer neu erzeugbar). Fertige Builds und Rohbilder nur bewusst anhaken.
` : `
${ic('sparkles', 'sm')} Nichts zum Aufräumen.
` } const hasRows = s && s.candidates.some((c) => c.MB >= 1 && !c.Skip) body += `
${hasRows ? `` : ''}
` return body } function renderActions(name, d) { const groups = {} for (const a of d.actions) (groups[a.group] ??= []).push(a) const ACT_ICON = (a) => a.id === 'vscode' ? 'code-xml' : a.id === 'explorer' ? 'folder-open' : a.id === 'console' ? 'square-terminal' : a.id.startsWith('unity') ? 'box' : a.id.startsWith('exe:') ? 'app-window' : a.id.startsWith('bat:') ? 'file-terminal' : a.id === 'web' ? 'globe' : a.id.startsWith('gen:') ? 'wand-sparkles' : a.id.startsWith('npm-install') ? 'download' : ACTION_ICON[a.group] // the project's own programs (exe + html pages) come first, as big start buttons; // the pin chooses which one the ▶ on the cards starts const programs = groups['Programm'] ?? [] const hasBuild = !!groups['Bauen'] const prog = d.program // { rel, missing } or null const progHtml = (programs.length ? `
${programs.map((a, i) => { const pinned = a.id === 'program' return `
${a.rel ? `` : ''}
` }).join('')}
` : `
Keine fertige exe oder HTML-Seite im Projekt gefunden.${hasBuild ? ' Unter „Bauen“ erzeugen, dann hier starten.' : ''}
`) + (prog?.missing ? `
${ic('triangle-alert', 'sm')} Festgelegte Datei fehlt: ${escapeHtml(prog.rel)} – neu wählen oder zurücksetzen.
` : '') + `
${ic('pin', 'sm')}Für ▶ starten festlegen${prog ? `: ${escapeHtml(prog.rel)}` : ' (automatisch)'}
${hasPicker ? `` : ''} ${prog ? `` : ''}
exe, html, bat oder lnk – Pfad im Projekt.
` const btnGroup = (g) => groups[g] ? section(ACTION_ICON[g], g, `
${groups[g].map((a) => ``).join('')}
`, { adv: !['Starten', 'Öffnen'].includes(g) }) : '' const head = (icon, title) => `
${ic(icon, 'sm')}${title}
` const tools = name === '_Tools' projectLastBackup = d.lastBackup ?? null projectTargets = d.backupTargets ?? [] const el = document.getElementById('sec-actions') el.innerHTML = head('play', 'Starten') + section('app-window', 'Programm', progHtml) + btnGroup('Starten') + btnGroup('Einrichten') + btnGroup('Bauen') + head('shield-check', 'Sichern & Versionieren') + section('git-branch', 'Git', gitActionsHtml(name, d), { id: 'act-git', adv: true }) + (tools ? '' : section('hard-drive-upload', 'Backup', '
', { id: 'act-backup' })) + head('rocket', 'Veröffentlichen') + section('file-archive', 'Release-ZIP', archiveHtml(name, d), { id: 'act-zip', adv: true }) + (tools || !itchOn() ? '' : section('rocket', 'itch.io-Seite', itchActionHtml(name, d), { id: 'act-itch', adv: true })) + head('brush-cleaning', 'Aufräumen') + section('hard-drive', 'Speicher', cleanHtml(d), { id: 'act-clean', adv: true }) + (groups['Werkzeuge'] || groups['Öffnen'] ? head('wrench', 'Werkzeuge') + btnGroup('Werkzeuge') + btnGroup('Öffnen') : '') + `
${ic('shield-check', 'sm')} Programme starten direkt, Befehle und .bat laufen sichtbar in einem eigenen Konsolenfenster. Eigenen Start-Befehl unter „Bearbeiten“ festlegen.
` for (const btn of el.querySelectorAll('.act')) btn.onclick = () => runAction(name, btn.dataset.id) for (const btn of el.querySelectorAll('.pin')) btn.onclick = () => setProgram(name, btn.dataset.rel) const input = document.getElementById('fProgram') document.getElementById('btnSetProgram').onclick = () => setProgram(name, input.value) input.onkeydown = (e) => { if (e.key === 'Enter') setProgram(name, input.value) } document.getElementById('btnClearProgram')?.addEventListener('click', () => setProgram(name, '')) document.getElementById('btnPickProgram')?.addEventListener('click', async () => { const file = await pickFile(`Programm für ${name} wählen`, d.path) if (file) setProgram(name, file) }) bindGit(name, d) bindArchive(name) bindItch(name) bindClean(name, d) renderProjectBackup(name) if (!backup) loadBackup() } function bindGit(name, d) { const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn } const refreshInfo = () => { load(); loadDetails(name) } on('btnPush', async () => { try { await postJson(api(name, 'push')); toast('Push läuft in eigener Konsole', 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') } }) on('btnCommitPush', async () => { const msg = document.getElementById('gMsg').value.trim() if (!msg) { document.getElementById('gMsg').focus(); return toast('Bitte eine Commit-Nachricht eingeben', 'info') } try { await postJson(api(name, 'push'), { message: msg }); toast('Commit & Push läuft in eigener Konsole', 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') } }) on('btnRemote', async () => { try { await postJson(api(name, 'remote'), { url: document.getElementById('gRemote').value }); toast('Remote gespeichert', 'link'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') } }) const rem = document.getElementById('gRemote') if (rem) rem.onkeydown = (e) => { if (e.key === 'Enter') document.getElementById('btnRemote').click() } on('btnGitInit', async () => { try { await postJson(api(name, 'git-init')); toast('Git eingerichtet (Branch main)', 'git-branch'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') } }) on('btnCopyKey', async () => { try { await navigator.clipboard.writeText(d.sshKey.key); toast('SSH-Schlüssel kopiert', 'copy') } catch { toast('Kopieren nicht möglich', 'triangle-alert') } }) } function bindArchive(name) { const arcSel = document.getElementById('arcWhat') const syncArc = () => { document.getElementById('arcDelWrap').style.display = arcSel.selectedOptions[0]?.dataset.del ? '' : 'none' } arcSel.onchange = syncArc syncArc() document.getElementById('btnArc').onclick = async (e) => { const btn = e.currentTarget const what = arcSel.value const del = document.getElementById('arcDel').checked && !!arcSel.selectedOptions[0]?.dataset.del if (del && !confirm(`ZIP von „${what}“ erstellen und den Ordner danach löschen?`)) return btn.disabled = true btn.innerHTML = `${ic('loader')}Packe…` try { const r = await postJson(api(name, 'archive'), { what, deleteAfter: del }) toast(`${r.name} (${fmtMB(r.mb)})${r.deleted ? ' – Build-Ordner gelöscht' : ''}`, 'file-archive') loadDetails(name) if (r.deleted) load() } catch (ex) { toast(ex.message, 'triangle-alert') btn.disabled = false btn.innerHTML = `${ic('file-archive')}ZIP erstellen` } } document.getElementById('btnArcOpen').onclick = () => postJson(api(name, 'archive/open')).catch((ex) => toast(ex.message, 'triangle-alert')) } function bindItch(name) { document.getElementById('btnItchGen')?.addEventListener('click', async () => { try { const r = await postJson(api(name, 'itch/generate')) toast(r.update ? 'Claude Code prüft das itch.io-Paket – siehe Konsole' : 'Claude Code erstellt das itch.io-Paket – siehe Konsole', 'sparkles') } catch (e) { toast(e.message, 'triangle-alert') } }) document.getElementById('btnItchView')?.addEventListener('click', () => openItch(name)) document.getElementById('btnItchOpen')?.addEventListener('click', () => postJson(api(name, 'itch/open')).catch((e) => toast(e.message, 'triangle-alert'))) } function bindClean(name, d) { const s = d.storage document.getElementById('btnScanOne').onclick = () => startScan(name) const clean = document.getElementById('btnClean') if (clean) clean.onclick = async () => { const paths = [...document.querySelectorAll('.candcb:checked')].map((cb) => cb.dataset.path) if (!paths.length) return toast('Nichts ausgewählt') const mb = s.candidates.filter((c) => paths.includes(c.Path)).reduce((a, c) => a + c.MB, 0) if (!confirm(`${paths.length} Ordner (${fmtMB(mb)}) in „${name}“ endgültig löschen?\n\n${paths.map((x) => inProject(x, editing?.folder)).join('\n')}`)) return clean.disabled = true clean.innerHTML = `${ic('loader')}Lösche…` try { const r = await postJson(api(name, 'clean'), { paths }) toast(`${r.deleted.length} gelöscht, ${String(r.freedGB).replace('.', ',')} GB frei${r.failed.length ? ` · ${r.failed.length} gesperrt (Programm offen?)` : ''}`, 'brush-cleaning') await load() loadDetails(name) } catch (e) { toast(e.message, 'triangle-alert'); clean.disabled = false; clean.innerHTML = `${ic('trash')}Ausgewählte löschen` } } } /* ── projects in subfolders (scanner, lib/nested.js) ──────────────────── */ let nestData = null let nestDeep = false async function openNested(deep = false) { const dlg = document.getElementById('nestDlg') nestDeep = deep // keep what was ticked before a re-scan (deep) const prev = new Map([...document.querySelectorAll('#nestBody input[data-rel]')].map((cb) => [`${cb.dataset.root}|${cb.dataset.rel}`, cb.checked])) document.getElementById('nestBody').innerHTML = `
${ic('loader', 'sm')} Suche…
` document.getElementById('nestDeep').hidden = deep if (!dlg.open) dlg.showModal() try { const r = await fetch(`/api/nested/scan${deep ? '?deep=1' : ''}`) nestData = await r.json() if (!r.ok) throw new Error(nestData.error) renderNested(dlg.open && deep ? prev : new Map()) } catch (e) { document.getElementById('nestBody').innerHTML = `
Fehler: ${escapeHtml(e.message)}
` } } function renderNested(prev) { const item = (root, x, preset) => { const k = `${root.id}|${x.rel}` const on = prev.has(k) ? prev.get(k) : preset const parts = x.rel.split('\\') return `` } const roots = nestData.roots ?? [] const html = roots.map((r) => { const groups = r.containers.map((c) => `
${ic('folder', 'sm')}${escapeHtml(c.rel)}Sammelordner · wird ausgeblendet, wenn etwas übernommen ist
${c.projects.map((x) => item(r, x, x.chosen || !x.ignored)).join('')}
`).join('') const inner = r.inProjects.length ? `
${ic('folder-git-2', 'sm')}In Projektenmeist Teil des Projekts – nur bei Bedarf ankreuzen
${r.inProjects.map((x) => item(r, x, x.chosen)).join('')}
` : '' const n = r.containers.reduce((a, c) => a + c.projects.length, 0) + r.inProjects.length return `

${ic('folders')}${escapeHtml(r.name)} ${escapeHtml(r.path)} · ${n} gefunden

${groups + inner || `
Keine Projekte in Unterordnern${nestDeep ? '' : ' (Sammelordner)'}.
`}
` }).join('') document.getElementById('nestBody').innerHTML = `
Angekreuzte Ordner erscheinen als eigene Projekte. Ein Sammelordner ohne eigenes Projekt (kein git, README, package.json …) wird dann ausgeblendet. Auf der Platte ändert sich nichts.
${html || '
Keine Projektordner eingerichtet.
'}` } async function saveNested() { const out = {} for (const r of nestData?.roots ?? []) out[r.id] = { chosen: [], ignored: [] } for (const cb of document.querySelectorAll('#nestBody input[data-rel]')) out[cb.dataset.root]?.[cb.checked ? 'chosen' : 'ignored'].push(cb.dataset.rel) const btn = document.getElementById('nestOk') btn.disabled = true try { const r = await postJson('/api/nested', { roots: out }) document.getElementById('nestDlg').close() await load() toast(r.chosen ? `${r.chosen} ${r.chosen === 1 ? 'Projekt' : 'Projekte'} aus Unterordnern übernommen` : 'Keine Projekte aus Unterordnern', 'folder-tree') } catch (e) { toast(e.message, 'triangle-alert') } finally { btn.disabled = false } } /* ── itch.io copy view (docs\itchio of the project, lib/itchpack.js) ───── */ let itchName = null let itchData = null async function copyText(text, what) { try { await navigator.clipboard.writeText(text); toast(`${what} kopiert`, 'copy') } catch { toast('Kopieren nicht möglich', 'triangle-alert') } } // formatted: pastes as rich text into itch.io's description editor async function copyHtml(html, what) { try { const tmp = document.createElement('div') tmp.innerHTML = html await navigator.clipboard.write([new ClipboardItem({ 'text/html': new Blob([html], { type: 'text/html' }), 'text/plain': new Blob([tmp.innerText], { type: 'text/plain' }), })]) toast(`${what} formatiert kopiert`, 'copy') } catch { copyText(html, `${what} (HTML)`) } } async function openItch(name) { itchName = name const dlg = document.getElementById('itchDlg') document.getElementById('itchTitle').textContent = `itch.io-Seite · ${name}` document.getElementById('itchBody').innerHTML = `
${ic('loader', 'sm')} Lädt…
` if (!dlg.open) dlg.showModal() try { const r = await fetch(api(name, 'itch')) itchData = await r.json() if (!r.ok) throw new Error(itchData.error) renderItch() } catch (e) { document.getElementById('itchBody').innerHTML = `
Fehler: ${escapeHtml(e.message)}
` } } const ITCH_SHORT_MAX = 120 // itch.io "Short description or tagline" function htmlText(html) { const t = document.createElement('template') t.innerHTML = html return (t.content.textContent ?? '').replace(/\s+/g, ' ').trim() } function firstParagraph(html) { const t = document.createElement('template') t.innerHTML = html const p = [...t.content.querySelectorAll('p')].map((x) => x.textContent.replace(/\s+/g, ' ').trim()).find((x) => x.length > 30) return p ?? '' } // ≤ 120 characters: the first part before " – " / ". " if it fits, else cut at a word function shorten(s) { s = String(s ?? '').trim() if (!s || s.length <= ITCH_SHORT_MAX) return s for (const sep of [' – ', ' - ', '. ', ': ', ', ']) { let cut = '' for (const part of s.split(sep)) { const next = cut ? cut + sep + part : part if (next.length > ITCH_SHORT_MAX) break cut = next } if (cut.length >= 40) return cut.replace(/[,:;–-]\s*$/, '').trim() + (sep === '. ' && !/[.!?]$/.test(cut) ? '.' : '') } return s.slice(0, ITCH_SHORT_MAX - 1).replace(/\s+\S*$/, '') + '…' } // itch.io tag ideas from the texts and the tech (lowercase, hyphenated like on itch) const TAG_RULES = [ [/\bidle\b/, ['idle', 'incremental']], [/clicker/, ['clicker']], [/incremental/, ['incremental']], [/puzzle|riddle/, ['puzzle', 'casual']], [/\brpg\b|role[- ]playing/, ['rpg']], [/rogue(like|lite)/, ['roguelike']], [/platform(er)?/, ['platformer']], [/shoot|bullet/, ['shooter']], [/tower defen[cs]e/, ['tower-defense']], [/strateg/, ['strategy']], [/simulat|management|manage\b|tycoon/, ['simulation', 'management']], [/arcade/, ['arcade']], [/high ?score|leaderboard/, ['high-score']], [/retro|8-bit|16-bit/, ['retro']], [/pixel/, ['pixel-art']], [/\b3d\b/, ['3d']], [/\b2d\b/, ['2d']], [/fantasy|magic|dragon/, ['fantasy']], [/horror|creepy|scary/, ['horror']], [/sci-?fi|spaceship|outer space|galaxy|alien|robot/, ['sci-fi']], [/relax|cozy|calm|chill/, ['relaxing', 'cozy']], [/cute/, ['cute']], [/funny|humou?r|silly/, ['funny']], [/physics|ragdoll/, ['physics']], [/survival/, ['survival']], [/card game|card-game|deck-?build/, ['card-game']], [/rhythm/, ['rhythm']], [/racing|race car|kart/, ['racing']], [/fight|combat|duel|arena/, ['fighting']], [/medieval|knight|castle/, ['medieval']], [/roman|rome|gladiator|ancient/, ['historical']], [/zombie/, ['zombies']], [/ocean|underwater|fish|aquarium/, ['underwater']], [/time attack|timer|speed/, ['time-attack']], [/multiplayer|co-?op\b/, ['multiplayer']], [/local (co-?op|multiplayer)|split ?screen/, ['local-multiplayer']], [/gamepad|controller/, ['controller']], [/mouse only|mouse-only/, ['mouse-only']], [/touch|mobile|android/, ['mobile']], [/short|minutes/, ['short']], [/procedural|random(ly)? generated/, ['procedural-generation']], [/singleplayer|single-player|solo/, ['singleplayer']], [/\bvr\b|virtual reality|quest/, ['virtual-reality']], ] function suggestTags(text, techTypes) { const t = String(text).toLowerCase() const out = [] const add = (x) => { if (!out.includes(x)) out.push(x) } for (const [re, tags] of TAG_RULES) if (re.test(t)) tags.forEach(add) if (techTypes.includes('Unity')) add('unity') if (techTypes.some((x) => ['Web', 'Vite'].includes(x))) add('html5') if (!/multiplayer/.test(t)) add('singleplayer') add('indie') if (!out.includes('3d') && !out.includes('2d')) add('2d') if (!out.some((x) => ['rpg', 'horror', 'strategy', 'roguelike'].includes(x))) add('casual') return out.slice(0, 16) } const ITCH_KINDS = [ ['cover', 'Cover (Cover image)'], ['theme', 'Banner & Hintergrund (Edit theme)'], ['promo', 'Promo-Bilder'], ['screenshot', 'Screenshots'], ['other', 'Weitere Bilder'], ] function renderItch() { const d = itchData const name = itchName const body = document.getElementById('itchBody') if (!d.exists) { body.innerHTML = `
Noch kein itch.io-Paket im Projekt. „itch.io-Seite erzeugen“ in Aktionen startet Claude Code.
` return } const row = (label, f, extra = '') => { const v = f?.copy ?? '' return `
${label}
${v ? escapeHtml(v) : `${f?.placeholder ? 'noch offen' : 'nicht gefunden'}`}${extra}
` } // short description: itch.io allows 120 characters; a longer one gets a shortened suggestion const descText = htmlText(d.descriptionHtml ?? '') const tl = d.tagline?.copy ?? '' const tlCount = tl ? ` ${tl.length} / ${ITCH_SHORT_MAX}` : '' const shortSugg = tl.length > ITCH_SHORT_MAX ? shorten(tl) : !tl ? shorten(firstParagraph(d.descriptionHtml ?? '')) : '' const shortRow = shortSugg ? row(tl ? 'Kürzer (Vorschlag)' : 'Short description (Vorschlag)', { copy: shortSugg }, ` ${shortSugg.length} / ${ITCH_SHORT_MAX}`) : '' const words = descText ? descText.split(/\s+/).filter(Boolean).length : 0 const htmlBlock = (key, title, html, info = '') => html == null ? '' : `

${ic('file-code')}${title}${info ? ` ${info}` : ''}

` const otherFields = d.fields.filter((f) => !/^tags/i.test(f.key)) // tags: the package's own (click = copy one) + suggestions from the texts and the tech const tagField = d.fields.find((f) => /^tags/i.test(f.key)) const ownTags = (tagField?.copy ?? '').split(/,\s*/).map((t) => t.trim().toLowerCase()).filter(Boolean) const genre = d.fields.find((f) => /^genre/i.test(f.key))?.text ?? '' const sugg = suggestTags(`${d.title?.copy ?? ''} ${tl} ${genre} ${descText}`, editing?.tech?.types ?? []).filter((t) => !ownTags.includes(t)) const tagChips = (list, cls) => list.map((t) => ``).join('') const tagsBlock = `

${ic('tags')}Tags itch erlaubt 10 · Klick kopiert einen Tag ${ownTags.length ? `` : ''}

${ownTags.length ? `
Im Paket (${ownTags.length})${tagChips(ownTags, 'own')}
` : '
Im Paket stehen noch keine Tags.
'} ${sugg.length ? `
Beispiele / Ideen${tagChips(sugg, 'sugg')}
` : ''}
` const imgs = d.images ?? [] const imgUrl = (rel) => `${api(name, 'itch/file')}?f=${encodeURIComponent(rel)}` const gallery = ITCH_KINDS.map(([k, label]) => { const list = imgs.filter((i) => i.kind === k) if (!list.length) return '' return `
${label} · ${list.length}
${list.map((i) => ``).join('')}
` }).join('') body.innerHTML = `

${ic('type')}Texte

${row('Title', d.title)} ${row('Short description', d.tagline, tlCount)} ${shortRow}
${d.descriptionHtml == null ? `

${ic('file-code')}Description

Keine description.html im Paket – „Ergänzen mit Claude“ in Aktionen erzeugt sie.
` : ''} ${htmlBlock('desc', 'Description', d.descriptionHtml, `${words} Wörter`)} ${tagsBlock} ${htmlBlock('install', 'Install instructions', d.installHtml)}

${ic('images')}Bilder Klick zeigt die Datei im Explorer – von dort in itch.io ziehen

${gallery || '
Keine Bilder im Paket.
'} ${d.media?.length ? `
${ic('film', 'sm')} Weitere Dateien: ${d.media.map(escapeHtml).join(', ')}
` : ''}
${otherFields.length ? `

${ic('list')}Weitere Felder („Edit game“)

${otherFields.map((f) => `
${escapeHtml(f.key)}
${f.placeholder ? 'noch offen' : escapeHtml(f.text)}
`).join('')}
` : ''}
${ic('shield-check', 'sm')} Nichts wird automatisch hochgeladen – Texte kopieren, Bilder aus dem Ordner auf itch.io ziehen.
` const html = { desc: d.descriptionHtml, install: d.installHtml } for (const f of body.querySelectorAll('iframe[data-html]')) { f.srcdoc = `${html[f.dataset.html]}` } for (const b of body.querySelectorAll('[data-copy]')) b.onclick = () => copyText(b.dataset.copy, b.dataset.what) for (const b of body.querySelectorAll('[data-rich]')) b.onclick = () => copyHtml(html[b.dataset.rich], b.dataset.rich === 'desc' ? 'Description' : 'Install-Text') for (const b of body.querySelectorAll('[data-raw]')) b.onclick = () => copyText(html[b.dataset.raw], 'HTML') for (const b of body.querySelectorAll('.ishot')) b.onclick = () => postJson(api(name, 'itch/open'), { f: b.dataset.file }).catch((e) => toast(e.message, 'triangle-alert')) } // Saves the program the ▶ starts ('' = choose automatically again). async function setProgram(name, program) { try { const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ program }), }) const r = await res.json().catch(() => ({})) if (!res.ok) throw new Error(r.error ?? 'Speichern fehlgeschlagen') toast(r.program ? `▶ startet jetzt: ${r.program}` : '▶ wählt wieder automatisch', 'pin') if (editing?.name === name) { editing.program = r.program; loadDetails(name) } load() } catch (e) { toast(e.message, 'triangle-alert') } } /* ── per-project backup ("Sichern" in Aktionen) ─────────────────────── */ let projectLastBackup = null let projectTargets = [] // [{ id, name, last }] – this project on every backup target function renderProjectBackup(name) { const el = document.getElementById('pbackupBody') if (!el || editing?.name !== name) return const b = backup const t = curTarget() const busy = backupBusy() // the job belongs to this project; while it runs it also decides the shown target const mine = b && b.scope === name && (busy || b.target === t?.id) const last = projectLastBackup if (b?.notConfigured) { el.innerHTML = `
${ic('hard-drive-upload')}
Noch kein Backup-Ziel festgelegt (z. B. externe Platte oder NAS).
` document.getElementById('pbSetup').onclick = () => openSettings(false) return } const shownT = busy && mine ? (b.targets.find((x) => x.id === b.target) ?? t) : t let html = targetTabs(busy ? b.target : null) + `
Zuletzt gesichert
${last ? `${new Date(last.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(last.at)}) · ${last.how}` : 'noch nie'}
Ziel
${escapeHtml(shownT ? `${shownT.path}\\${name}` : '…')}
${projectTargets.length > 1 ? `
Alle Ziele
${projectTargets.map((x) => { const lv = !x.last ? 'red' : (Date.now() - new Date(x.last.at)) / 86400000 > BACKUP_FRESH_DAYS ? 'yellow' : 'green' return `${ic('hard-drive', 'sm')}${escapeHtml(x.name)} · ${x.last ? timeAgo(x.last.at) : 'nie'}` }).join('')}
` : ''}
` if (busy && mine && b.phase === 'checking') { html += `
${ic('loader')}
Prüfe, was im Backup fehlt…
` } else if (busy && mine && b.phase === 'copying') { const pr = b.progress const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0 html += `
Kopiere… ${pct} %${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien
${escapeHtml(pr.current)}
` } else if (busy) { html += `
${ic('hourglass')}
Es läuft gerade ein anderes Backup (${b.scope ? escapeHtml(b.scope) : 'alle Projekte'}). Danach geht es hier.
` } else if (mine && b.phase === 'done') { const l = shownT?.lastByProject?.[name] html += l && l.files ? `
${ic('circle-check')}
Gesichert. ${l.files.toLocaleString('de-DE')} Dateien (${fmtBytes(l.bytes)}) neu ins Backup kopiert.
` : `
${ic('circle-check')}
Alles aktuell. Im Backup fehlte nichts.
` } else if (mine && b.phase === 'error') { html += `
${ic('triangle-alert')}
${escapeHtml(b.error)}
` } else if (mine && b.phase === 'cancelled') { html += `
${ic('circle-x')}
Abgebrochen. Bereits kopierte Dateien bleiben im Backup.
` } html += `
${busy && mine ? `` : ``}
Prüft das Projekt im Backup und kopiert nur fehlende und geänderte Dateien. Gelöscht wird dort nichts.
` el.innerHTML = html const save = document.getElementById('pbSave') if (save) save.onclick = async () => { try { backup = await postJson('/api/backup/check', { project: name, autoCopy: true, target: curTargetId() }) renderProjectBackup(name) loadBackup() } catch (e) { toast(e.message, 'triangle-alert') } } const cancel = document.getElementById('pbCancel') if (cancel) cancel.onclick = () => backupAction('cancel') } async function loadDetails(name) { try { const res = await fetch(`${api(name, 'details')}?target=${encodeURIComponent(curTargetId())}`) const d = await res.json() if (!res.ok) throw new Error(d.error) if (editing?.name !== name) return renderInfo(name, d) renderActions(name, d) } catch (e) { document.getElementById('sec-info').innerHTML = `
Fehler: ${escapeHtml(e.message)}
` } } function openEditor(p) { closeBackup() editing = p editingTasks = (p.tasks ?? []).map((t) => ({ ...t })) document.getElementById('pAvatar').innerHTML = avatar(p, 'lg') document.getElementById('panelTitle').textContent = p.name document.getElementById('pFav').innerHTML = favBtn(p) wireFav(document.getElementById('pFav'), p) document.getElementById('panelSub').innerHTML = uiMode === 'simple' ? `${statusHtml(p.status)}${rootTag(p)}` : `${statusHtml(p.status)}${gitHtml(p.git, true)}${techChips(p.tech?.types)}${pubChip(p)}` document.getElementById('fStatus').value = p.status document.getElementById('fPriority').value = p.priority document.getElementById('fTags').value = (p.tags ?? []).join(', ') document.getElementById('fThumb').value = p.thumbnail ?? '' document.getElementById('fStart').value = p.start ?? '' document.getElementById('fItch').value = p.itch ?? '' document.getElementById('fItchHint').innerHTML = p.itch === '-' ? `${ic('circle-off', 'sm')} als „nicht veröffentlicht“ markiert` : p.published?.source === 'auto' ? `${ic('sparkles', 'sm')} automatisch erkannt: ${escapeHtml(p.published.title)} – ${escapeHtml(p.published.url)}` : p.published ? '' : `${ic('info', 'sm')} nicht auf dem itch.io-Profil gefunden` document.getElementById('fNotes').value = p.notes renderTaskList() const loading = `
${ic('loader', 'sm')} Lädt…
` document.getElementById('sec-info').innerHTML = loading document.getElementById('sec-actions').innerHTML = loading document.getElementById('overlay').classList.add('open') document.getElementById('panel').classList.add('open') document.getElementById('panel').setAttribute('aria-hidden', 'false') loadDetails(p.name) } function closeEditor() { editing = null editingTasks = [] document.getElementById('overlay').classList.remove('open') document.getElementById('panel').classList.remove('open') document.getElementById('panel').setAttribute('aria-hidden', 'true') } async function saveEditor() { if (!editing) return const body = { status: document.getElementById('fStatus').value, priority: document.getElementById('fPriority').value, notes: document.getElementById('fNotes').value, tags: document.getElementById('fTags').value.split(',').map((s) => s.trim()).filter(Boolean), thumbnail: document.getElementById('fThumb').value.trim(), start: document.getElementById('fStart').value.trim(), itch: document.getElementById('fItch').value.trim(), tasks: editingTasks, } if (await patchProject(editing.name, body)) { toast('Gespeichert', 'save') closeEditor() load() } else toast(patchProject.error || 'Speichern fehlgeschlagen', 'triangle-alert') } /* ── backup (NAS) ─────────────────────────────────────────────────────── */ let backup = null let backupTimer = null const fmtBytes = (b) => (b ?? 0) < 1048576 ? `${Math.max(b ? 1 : 0, Math.round((b ?? 0) / 1024))} KB` : fmtMB(b / 1048576) const backupBusy = () => backup && (backup.phase === 'checking' || backup.phase === 'copying') // Selected backup target (several possible): cards, tiles and "Sichern" use this one. let backupTargetId = '' try { backupTargetId = localStorage.getItem('dash.backupTarget') ?? '' } catch {} function curTarget() { const list = backup?.targets ?? [] return list.find((t) => t.id === backupTargetId) ?? list[0] ?? null } const curTargetId = () => curTarget()?.id ?? backupTargetId function selectTarget(id) { if (id === curTargetId()) return backupTargetId = id try { localStorage.setItem('dash.backupTarget', id) } catch {} renderBackupButton() if (document.getElementById('bpanel').classList.contains('open')) renderBackup() load() if (editing) loadDetails(editing.name) } // reiter for the targets; disabled while a backup runs on another one function targetTabs(busyId) { const list = backup?.targets ?? [] if (list.length < 2) return '' const cur = curTargetId() return `
${list.map((t) => ``).join('')}
` } document.addEventListener('click', (e) => { const b = e.target.closest('.ttabs [data-target]') if (b && !b.disabled) selectTarget(b.dataset.target) }) async function loadBackup() { const wasBusy = backupBusy() const wasAuto = backup?.auto try { backup = await (await fetch('/api/backup')).json() } catch { return } if (wasBusy && !backupBusy()) { load() // refresh the backup badges on cards/tiles/list if (wasAuto) toast(backup.phase === 'done' ? 'Automatisches Backup fertig' : `Automatisches Backup: ${backup.error ?? 'abgebrochen'}`, backup.phase === 'done' ? 'circle-check' : 'triangle-alert') } else if (!wasBusy && backupBusy() && backup.auto) toast('Automatisches Backup läuft …', 'hard-drive-upload') renderBackupButton() if (document.getElementById('spanel').classList.contains('open')) renderAutoStatus() if (document.getElementById('bpanel').classList.contains('open')) renderBackup() if (editing) { const own = curTarget()?.lastByProject?.[editing.name] if (own && (!projectLastBackup || own.at > projectLastBackup.at)) projectLastBackup = { ...own, how: 'Projekt' } renderProjectBackup(editing.name) } clearTimeout(backupTimer) if (backupBusy()) backupTimer = setTimeout(loadBackup, 1000) } function renderBackupButton() { const sub = document.getElementById('backupSub') if (!backup) return const btn = document.getElementById('btnBackup') btn.title = (backup.targets ?? []).map((t) => `${t.name}: ${t.last ? 'zuletzt ' + timeAgo(t.last.at) : 'noch nie komplett gesichert'}`).join('\n') || 'Backup-Ziel einrichten' if (backup.notConfigured) { sub.textContent = '· einrichten'; sub.classList.add('warn'); return } const t = curTarget() const last = t?.last const prefix = backup.targets.length > 1 ? `· ${t.name} ` : '· ' if (backup.phase === 'checking') sub.textContent = backup.auto ? '· auto: prüft…' : '· prüft…' else if (backup.phase === 'copying') { const pr = backup.progress sub.textContent = `· ${backup.auto ? 'auto ' : ''}${pr.bytesTotal ? Math.round((pr.bytes / pr.bytesTotal) * 100) : 0} %` } else if (dueCount()) sub.textContent = `· ${dueCount()} fällig` else if (last) sub.textContent = `${prefix}${timeAgo(last.at)}` else sub.textContent = `${prefix}noch nie` const old = last && (Date.now() - new Date(last.at)) > BACKUP_FRESH_DAYS * 86400000 sub.classList.toggle('warn', !last || old || last.ok === false || dueCount() > 0) if (dueCount()) btn.title += `\n\n${dueCount()} Projekte seit dem letzten Backup geändert (älter als ${BACKUP_FRESH_DAYS} Tage) – Filter „Backup fällig“` } const dueCount = () => projects.filter(backupDue).length // once a day: a hint when backups are due function remindBackup() { const n = dueCount() if (!n || backup?.notConfigured || backupBusy()) return const today = new Date().toISOString().slice(0, 10) try { if (localStorage.getItem('dash.backupReminded') === today) return; localStorage.setItem('dash.backupReminded', today) } catch {} toast(`Backup fällig: ${n} ${n === 1 ? 'Projekt wurde' : 'Projekte wurden'} seit dem letzten Backup geändert – oben auf „Backup“ klicken`, 'clock-alert') } async function backupAction(what) { try { backup = await postJson(`/api/backup/${what}`, what === 'check' ? { target: curTargetId() } : {}) renderBackup() loadBackup() } catch (e) { toast(e.message, 'triangle-alert') } } function renderBackup() { let b = backup if (!b) return if (b.notConfigured) { document.getElementById('bpTarget').textContent = 'kein Ziel festgelegt' document.getElementById('bpBody').innerHTML = `
${ic('hard-drive-upload')}
Noch kein Backup-Ziel festgelegt. Wähle einen Ordner auf einer externen Platte, einem NAS oder einem anderen Laufwerk.
` document.getElementById('bpSetup').onclick = () => openSettings(false) return } // a running job shows its own target; otherwise the selected one (and its last result only if the job was for it) const busy = backupBusy() const jobT = b.targets.find((t) => t.id === b.target) const t = busy && jobT ? jobT : curTarget() const phase = busy || (jobT && jobT.id === t.id) ? b.phase : 'idle' document.getElementById('bpTarget').innerHTML = `${ic('folder', 'sm')} ${escapeHtml(b.source)} ${ic('arrow-right', 'sm')} ${escapeHtml(t.path)}` const tl = t.last const last = tl ? `
Letztes Backup
${new Date(tl.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(tl.at)})
Kopiert
${tl.files.toLocaleString('de-DE')} Dateien · ${fmtBytes(tl.bytes)}${tl.ok === false ? ' · unvollständig' : ''}
` : `
Auf „${escapeHtml(t.name)}“ wurde über das Dashboard noch kein Komplett-Backup gemacht.
` let body = targetTabs(busy ? b.target : null) + section('clock-3', `Status – ${escapeHtml(t.name)}`, last) b = { ...b, phase } if (b.scope && b.phase !== 'idle') { body += `
${ic('folder')}
Der aktuelle Lauf betrifft nur das Projekt ${escapeHtml(b.scope)} (gestartet über „Sichern“ im Projekt).
` } if (b.phase === 'checking') { body += `
${ic('loader')}
Prüfe, was neu ist und im Backup fehlt…
Dauert über das Netzwerk etwa 1–2 Minuten.
` } else if (b.phase === 'copying') { const pr = b.progress const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0 body += section('hard-drive-upload', 'Kopiere…', `
${pct} %${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien
${escapeHtml(pr.current)}
`) + `
Das Fenster bitte offen lassen, bis das Backup fertig ist.
` } else if (b.phase === 'ready' && b.check) { const c = b.check if (!c.files) { body += `
${ic('circle-check')}
Alles aktuell. Im Backup fehlt nichts.
` } else { body += section('scan-search', `Ergebnis der Prüfung ${timeAgo(c.at)}`, `
${ic('file-plus', 'sm')}Neu
${c.newFiles.toLocaleString('de-DE')}
${fmtBytes(c.newBytes)}
${ic('file-pen', 'sm')}Geändert
${c.changedFiles.toLocaleString('de-DE')}
${fmtBytes(c.changedBytes)}
${ic('archive', 'sm')}Nur im Backup
${c.extraFiles.toLocaleString('de-DE')}
bleiben erhalten
${c.projects.slice(0, 15).map((p) => ``).join('')}
${escapeHtml(p.name)}${p.files.toLocaleString('de-DE')} Dateien${fmtBytes(p.bytes)}
${c.projects.length > 15 ? `
+ ${c.projects.length - 15} weitere Projekte
` : ''}`) } body += `
${c.files ? `` : ''}
` } else { if (b.phase === 'done') body += `
${ic('circle-check')}
Backup fertig. ${tl && !b.scope ? `${tl.files.toLocaleString('de-DE')} Dateien, ${fmtBytes(tl.bytes)} kopiert.` : ''}
` if (b.phase === 'cancelled') body += `
${ic('circle-x')}
Abgebrochen. Bereits kopierte Dateien bleiben im Backup.
` if (b.phase === 'error') body += `
${ic('triangle-alert')}
${escapeHtml(b.error)}
` body += `
` } body += `
${ic('shield-check', 'sm')} Im Backup wird nie etwas gelöscht – nur neue und geänderte Dateien kommen dazu. Nicht gesichert (wird neu erzeugt): ${escapeHtml((settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.gradle', '.venv']).join(', '))}. Ziel und Ausnahmen: Einstellungen (Zahnrad oben).
` document.getElementById('bpBody').innerHTML = body const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn } on('bpCheck', () => backupAction('check')) on('bpCopy', () => backupAction('copy')) on('bpCancel', () => backupAction('cancel')) } function openBackup() { closeEditor() document.getElementById('overlay').classList.add('open') document.getElementById('bpanel').classList.add('open') document.getElementById('bpanel').setAttribute('aria-hidden', 'false') renderBackup() loadBackup() } function closeBackup() { document.getElementById('bpanel').classList.remove('open') document.getElementById('bpanel').setAttribute('aria-hidden', 'true') if (!editing) document.getElementById('overlay').classList.remove('open') } /* ── theme ────────────────────────────────────────────────────────────── */ // Theme mode: 'light', 'dark' or 'system' (follows Windows, also live when it changes). const systemDark = matchMedia('(prefers-color-scheme: dark)') let themeMode = 'system' function applyTheme() { const theme = themeMode === 'system' ? (systemDark.matches ? 'dark' : 'light') : themeMode document.documentElement.dataset.theme = theme for (const b of document.querySelectorAll('#themeSeg button')) b.classList.toggle('active', b.dataset.mode === themeMode) } function setThemeMode(mode) { themeMode = ['light', 'dark', 'system'].includes(mode) ? mode : 'system' applyTheme() try { localStorage.setItem('dash.theme', themeMode) } catch {} } function initTheme() { let saved = null try { saved = localStorage.getItem('dash.theme') } catch {} saved = new URLSearchParams(location.search).get('theme') ?? saved themeMode = ['light', 'dark', 'system'].includes(saved) ? saved : 'system' applyTheme() } systemDark.addEventListener('change', () => { if (themeMode === 'system') applyTheme() }) for (const b of document.querySelectorAll('#themeSeg button')) b.onclick = () => setThemeMode(b.dataset.mode) /* ── wiring ───────────────────────────────────────────────────────────── */ document.getElementById('btnCancel').onclick = closeEditor document.getElementById('btnClose').onclick = closeEditor document.getElementById('btnSave').onclick = saveEditor document.getElementById('btnAddTask').onclick = addTaskFromInput document.getElementById('taskInput').addEventListener('keydown', (e) => { if (e.key === 'Enter') addTaskFromInput() }) document.getElementById('btnOpenFolder').onclick = () => { if (editing) runAction(editing.name, 'explorer') } document.getElementById('btnVsCode').onclick = () => { if (editing) runAction(editing.name, 'vscode') } document.getElementById('overlay').onclick = () => { closeEditor(); closeBackup(); closeSettings() } document.getElementById('btnBackup').onclick = () => (backup?.notConfigured ? openSettings(false) : openBackup()) for (const b of document.querySelectorAll('#taskMode button')) b.onclick = () => setTaskMode(b.dataset.mode) for (const b of document.querySelectorAll('#boardMode button')) { b.onclick = () => setBoardMode(b.dataset.mode); b.classList.toggle('active', b.dataset.mode === boardMode) } document.getElementById('taskNewBtn').onclick = addTaskTop document.getElementById('taskNew').addEventListener('keydown', (e) => { if (e.key === 'Enter') addTaskTop() }) document.getElementById('btnCloseBackup').onclick = closeBackup document.getElementById('search').addEventListener('input', (e) => { searchTerm = e.target.value; render() }) for (const btn of document.querySelectorAll('#tabs button')) btn.onclick = () => { setView(btn.dataset.view); render() } for (const btn of document.querySelectorAll('#ptabs button')) btn.onclick = () => setSection(btn.dataset.sec) document.getElementById('nestClose').onclick = () => document.getElementById('nestDlg').close() document.getElementById('nestCancel').onclick = () => document.getElementById('nestDlg').close() document.getElementById('nestDeep').onclick = () => openNested(true) document.getElementById('nestOk').onclick = saveNested document.getElementById('fNestedOpen').onclick = () => openNested() document.getElementById('itchClose').onclick =() => document.getElementById('itchDlg').close() document.getElementById('itchReload').onclick = () => itchName && openItch(itchName) document.getElementById('itchOpenDir').onclick = () => itchName && postJson(api(itchName, 'itch/open')).catch((e) => toast(e.message, 'triangle-alert')) document.getElementById('fltStatus').addEventListener('change', render) document.getElementById('fltSort').addEventListener('change', render) document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { if (!rootMenu.hidden) { toggleRootMenu(false); return } closeEditor(); closeBackup(); closeSettings() } if (e.key === '/' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') { e.preventDefault(); document.getElementById('search').focus() } }) // Deep links: #gallery, #list, #board/ (opens the panel), #list//info const [hashView, hashProject, hashSec] = decodeURIComponent(location.hash.slice(1)).split('/') const VIEWS = ['home', 'board', 'gallery', 'list', 'tasks', 'storage', 'activity'] initTheme() initUiMode() if (VIEWS.includes(hashView)) setView(hashView) else try { const v = localStorage.getItem('dash.view'); if (VIEWS.includes(v)) setView(v) } catch {} // nothing stored (first start): the simple view starts on its tile page if (uiMode === 'simple' && ADV_VIEWS.includes(activeView)) setView('home') function openFromHash(project, sec) { const p = project && projects.find((x) => x.name === project) if (p) { openEditor(p); if (sec) setSection(sec) } } load().then(() => { openFromHash(hashProject, hashSec); if (hashView === 'backup') openBackup() }) loadBackup() // an automatic backup can start any time: look once a minute (while busy, loadBackup polls every second) setInterval(() => { if (!backupBusy()) loadBackup() }, 60000) window.addEventListener('hashchange', () => { const [v, project, sec] = decodeURIComponent(location.hash.slice(1)).split('/') if (VIEWS.includes(v)) { setView(v); render() } openFromHash(project, sec) })