/* 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' } // label/hint/short come from the dictionary (tier..*); here only style + icon const TIER = { Cache: { cls: 'ok', icon: 'recycle' }, Release: { cls: 'warn', icon: 'package' }, Output: { cls: 'warn', icon: 'images' }, } // use window.I18N.t (not the global t) – these run inside .map((t)=>…) where t is shadowed const tierLabel = (k) => window.I18N.t('tier.' + k + '.label') const tierHint = (k) => window.I18N.t('tier.' + k + '.hint') const tierShort = (k) => window.I18N.t('tier.' + k + '.short') 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 t('time.today') if (days === 1) return t('time.yesterday') if (days < 30) return t('time.daysAgo', { n: days }) if (days < 365) return t('time.monthsAgo', { n: Math.floor(days / 30) }) return t('time.yearsAgo', { n: Math.floor(days / 365) }) } 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(I18N.locale(), 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(I18N.locale(), { dateStyle: 'full', timeStyle: 'short' }) if (p.lastChange) return `${t('change.last', { when })}\n${p.lastChange.file}${p.lastChange.partial ? '\n' + t('change.partial') : ''}` return p.lastChange === undefined ? t('change.detecting', { when }) : t('change.last', { when }) } function sizeTitle(p) { if (p.storage?.sizeMB == null) return t('size.unscanned') return t('size.scanned', { size: fmtMB(p.storage.sizeMB), ago: timeAgo(p.storage.at) }) + (deletableMB(p) >= 1 ? ' · ' + t('size.cleanable', { size: fmtMB(deletableMB(p)) }) : '') } 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 ? t('git.' + git.level) : gitLabel(git) return `${ic(GIT_ICON[git.level], 'sm')}${escapeHtml(label)}` } // Git status line in the current language, built from the server's raw fields (lib/git.js) function gitLabel(g) { if (!g) return '' if (!g.isRepo) return t('gitl.noGit') if (g.label === 'Git nicht installiert') return t('gitl.notInstalled') const parts = [] if (g.dirty) parts.push(t('gitl.changed', { n: g.dirty })) if (g.ahead) parts.push(t('gitl.unpushed', { n: g.ahead })) if (g.behind) parts.push(t('gitl.behind', { n: g.behind })) if (!g.remote) return [t('gitl.noRemote'), ...parts].join(' · ') if (!g.upstream) return [t('gitl.noUpstream'), ...parts].join(' · ') return parts.length ? parts.join(' · ') : t('gitl.saved') } // 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: t('cloud.never'), label: t('cloud.neverLong') } const days = (Date.now() - new Date(l.at)) / 86400000 const when = new Date(l.at).toLocaleString(I18N.locale(), { dateStyle: 'medium', timeStyle: 'short' }) const level = l.ok === false ? 'red' : days > BACKUP_FRESH_DAYS ? 'yellow' : 'green' const extra = l.ok === false ? ' – ' + t('cloud.incomplete') : days > BACKUP_FRESH_DAYS ? ' – ' + t('cloud.olderThan', { n: BACKUP_FRESH_DAYS }) : '' const due = backupDue(p) ? ' · ' + t('cloud.dueSince') : '' return { level, short: timeAgo(l.at), label: t('cloud.savedAt', { when, how: 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 ? t('pub.title', { title: x.title ? ': ' + x.title : '', src: x.source === 'manual' ? t('pub.manual') : t('pub.auto') }) : '' } // 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 ?? t('err.saveFailed')) 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 ? t('fav.now', { name: p.name }) : t('fav.not', { name: p.name }), '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')}${t('status.' + s.key)}` } function prioHtml(prio) { const icon = prio === 'high' ? 'flame' : prio === 'low' ? 'chevron-down' : 'equal' return `${ic(icon, 'sm')}${t('prio.' + 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')}${t('warn.genCopy')}`) else if (p.tools?.generators?.length) b.push(`${ic('wand-sparkles', 'sm')}ComfyGen`) if (!p.hasIcon) b.push(`${ic('image-off', 'sm')}${t('warn.noIcon')}`) 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 let noneShown = false // deliberately no folder shown (dropdown "Keinen anzeigen") // 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 noneShown = !!data.noneShown document.getElementById('noneBox').hidden = !noneShown 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() fitHeader() // folder name / backup count may have changed the width // "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) // first start: choose the projects folder – with the guided setup tour (once per session) if (data.setupNeeded) { const opening = openSettings(true) if (!load.setupToured) { load.setupToured = true; Promise.resolve(opening).then(() => setTimeout(() => startTour('setup'), 400)) } } // 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(t(data.nestedHint === 1 ? 'nested.found1' : 'nested.foundN', { n: data.nestedHint }), '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}${t('new.copySuffix')}` : '' 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 ? t('dlg.new.titleClone') : t('dlg.new.title') document.querySelector('#nOk span').textContent = clone ? t('dlg.new.clone') : t('dlg.new.create') } 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 const suffix = t('new.copySuffix') const sfxRe = new RegExp(suffix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$') if (!name.value.trim() || sfxRe.test(name.value)) name.value = from ? `${from}${suffix}` : '' 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 = t('move.now', { path: `${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')}
${t('move.confirmCopy')}
` err.style.display = '' return } const ok = document.getElementById('mvOk') ok.disabled = true ok.querySelector('span').textContent = document.getElementById('mvCopy').hidden ? t('move.renaming') : t('move.copying') 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 ? t('move.okShown', { name: r.name, root: r.rootName }) : t('move.okHidden', { name: r.name, root: r.rootName }), '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 = t('common.apply') } }) 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 ? t('move.copying') : t('new.creating') 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(t(r.cloned ? 'new.clonedOk' : 'new.createdOk', { name: r.name }), '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 ? (roots.length ? t('root.none') : t('root.projects')) : cur.length === 1 ? cur[0].name : cur.length === roots.length && cur.length > 2 ? t('root.allN', { n: cur.length }) : cur.map((r) => r.name).join(' + ') rootBtn.title = cur.length ? t('root.shown', { list: cur.map((r) => r.path).join('\n') }) : t('root.switch') rootMenu.setAttribute('aria-multiselectable', 'true') rootMenu.innerHTML = roots.map((r) => { const on = activeRoots.includes(r.id) return `
` }).join('') + (roots.length > 1 ? `` : '') + (activeRoots.length ? `` : '') + `${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(t('root.already'), 'info'); return r } if (activate) { closeEditor(); searchTerm = ''; document.getElementById('search').value = '' } await load() if (activate) await loadBackup() toast(r.added.length === 1 ? t('root.added1', { name: r.added[0].name }) : t('root.addedN', { n: r.added.length }), 'folder-plus') return r } // "Ordner hinzufügen…" (desktop app): folder dialog → add → switch to it async function addRootByPicker() { const chosen = await pickFolder(t('pick.projectsFolder'), 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(t('pick.parentFolder'), 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.join('|') === activeRoots.join('|')) return // [] = show no folder (empty dashboard) 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(ids.length ? t('root.showing', { list: roots.filter((r) => ids.includes(r.id)).map((r) => r.name).join(' + ') }) : t('root.noneShown'), '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 } if (b.hasAttribute('data-root-none')) { showRoots([]); return } const t = b.dataset.rootToggle if (t) { const next = activeRoots.includes(t) ? activeRoots.filter((x) => x !== t) : [...activeRoots, t] 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 ? t('tray.on') : t('tray.off')) : (m.autostart ? t('autostart.on') : t('autostart.off')), '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 ? `
${t('data.settings')}
${escapeHtml(s.dataDir)}
${t('data.scanBackup')}
${t('data.sameFolder')}
${t('data.appearance')}
${t('data.appearanceVal')}
` : '' document.getElementById('spWelcome').style.display = setup ? '' : 'none' document.getElementById('spTitle').textContent = setup ? t('set.setup') : t('set.title') 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')}
${t('itch.reading')}
` 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')}
${t('itch.found', { n: r.games.length })}` + (un.length ? ' ' + t('itch.unmatched', { list: un.map((g) => `${escapeHtml(g.title)}`).join(', ') }) : ' ' + t('itch.allMatched')) + '
' } 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') if (tour?.def === TOURS.setup) endTour() // saved / closed: the setup tour is done } 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) const firstSetup = settingsSetup settingsSetup = false document.getElementById('spanel').classList.remove('dirty') closeSettings() toast(t('set.saved'), 'save') await loadBackup() await load() // first start done: show "Help & overview" so a new user learns the tool right away if (firstSetup) setTimeout(() => { helpPage = 0; renderHelp(); document.getElementById('helpDlg').showModal() }, 500) } 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(I18N.locale(), { hour: '2-digit', minute: '2-digit' }) if (d - now < 60000) return t('when.soon') const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime() const diff = Math.round((day(d) - day(now)) / 86400000) return diff === 0 ? t('when.today', { time }) : diff === 1 ? t('when.tomorrow', { time }) : `${d.toLocaleDateString(I18N.locale(), { 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 ? t('auto.lastOk', { ago: timeAgo(r.at) }) : t('auto.lastFail', { ago: timeAgo(r.at), detail: escapeHtml(r.targets.filter((x) => !x.ok).map((x) => `${x.name}: ${x.error ?? t('auto.error')}`).join('; ')) })) : t('auto.never') el.className = `spstatus ${r && !r.ok ? 'err' : r ? 'ok' : ''}` el.innerHTML = `${ic(sch.running ? 'loader' : r && !r.ok ? 'triangle-alert' : 'calendar-clock')}
${sch.running ? '' + t('auto.running') + ' ' : sch.next ? t('auto.next', { when: `${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') && e.target.id !== 'fLang') 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') } } /* settings backup / restore / reset (Einstellungen → Allgemein → Daten) */ document.getElementById('spExport').onclick = async () => { try { const data = await (await fetch('/api/settings/export')).json() const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }) const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = `project-dashboard-settings-${new Date().toISOString().slice(0, 10)}.json` a.click() setTimeout(() => URL.revokeObjectURL(a.href), 2000) toast(t('set.exported'), 'download') } catch (e) { toast(e.message, 'triangle-alert') } } document.getElementById('spImport').onclick = () => document.getElementById('spImportFile').click() document.getElementById('spImportFile').onchange = async (e) => { const file = e.target.files?.[0] e.target.value = '' if (!file) return try { const data = JSON.parse(await file.text()) if (!confirm(t('set.importConfirm'))) return await postJson('/api/settings/import', { data }) toast(t('set.imported'), 'upload') setTimeout(() => location.reload(), 600) } catch (ex) { toast(t('set.importBad') + ' ' + (ex.message ?? ''), 'triangle-alert') } } document.getElementById('spReset').onclick = async () => { if (!confirm(t('set.resetConfirm'))) return try { const r = await postJson('/api/settings/reset') toast(r.backupFile ? t('set.resetDone', { file: r.backupFile }) : t('set.resetDoneNoBackup'), 'refresh-cw') setTimeout(() => location.reload(), 900) } 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, t('row.phRoot')) const targetRow = (x = { id: '', name: '', path: '' }) => settingsItem('target', x, t('row.phTarget')) // 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')}${t('row.main')} ` : '') + (id && shownRootIds.includes(id) ? `${ic('eye')}${t('row.shown')}` : '') row.querySelector('.sstat').innerHTML = row.querySelector('.tpath').value.trim() ? `${n != null ? `${t('row.nProjects', { n })}` : ''}${i === 0 ? t('row.backupDirect') : t('row.backupSub', { name: escapeHtml(name) })}` : `${t('row.enterPath')}` row.querySelector('[data-up]').disabled = i === 0 }) const trows = [...document.querySelectorAll('#fTargets .trow')] trows.forEach((row, i) => { const st = backup?.targets?.find((x) => x.id === row.dataset.id) const last = st?.last row.querySelector('.sbadges').innerHTML = (i === 0 ? `${t('row.default')} ` : '') + (!row.dataset.id ? '' : last ? `${last.ok ? t('row.saved') : t('row.incomplete')} ${timeAgo(last.at)}` : `${t('row.neverComplete')}`) row.querySelector('.sstat').innerHTML = row.dataset.id ? '' : `${t('row.newChecked')}` 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(t('import.addedRemember', { n: picked.length }), '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')} ${t('import.reading')}
` 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 }, `${t('import.thisFolder')} (${escapeHtml(folderName(r.path))})`, t('import.nProjects', { n: r.folders.length }), true)} ${r.folders.map((f) => item(f, escapeHtml(f.name), t('import.nSub', { n: f.count }))).join('') || `
${t('import.noSub')}
`}
` 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(t('import.nothingSelected'), '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 /* help / overview dialog – paged, one topic group per page (native : Esc closes it) */ const HELP_PAGES = [ { id: 'views', t: 'help.g.views', rows: [['kanban', 'help.board'], ['layout-grid', 'help.gallery'], ['list', 'help.list'], ['list-checks', 'help.tasks'], ['activity', 'help.activity'], ['hard-drive', 'help.storage']] }, { id: 'find', t: 'help.g.find', rows: [['sliders-horizontal', 'help.mode'], ['search', 'help.search'], ['funnel', 'help.filters']] }, { id: 'project', t: 'help.g.project', rows: [['pencil', 'help.edit'], ['info', 'help.info'], ['play', 'help.actions'], ['folder-open', 'help.quick']] }, { id: 'backup', t: 'help.g.backup', rows: [['hard-drive-upload', 'help.backup'], ['clock-alert', 'help.due']] }, { id: 'misc', t: 'help.g.misc', rows: [['folders', 'help.folders'], ['languages', 'help.lang'], ['keyboard', 'help.keys']] }, { id: 'setup', t: 'help.g.setup', rows: [['folders', 'tour.setup.folders'], ['hard-drive-upload', 'tour.setup.backup'], ['sliders-horizontal', 'tour.setup.general']] }, ] let helpPage = 0 function renderHelp() { helpPage = Math.max(0, Math.min(HELP_PAGES.length - 1, helpPage)) document.getElementById('helpNav').innerHTML = HELP_PAGES.map((p, i) => ``).join('') document.getElementById('helpBody').innerHTML = `` + HELP_PAGES[helpPage].rows.map(([icon, k]) => `
${ic(icon)}
${t(k)}
`).join('') document.getElementById('helpShow').onclick = () => startTour(HELP_PAGES[helpPage].id) document.getElementById('helpDots').innerHTML = HELP_PAGES.map((_, i) => ``).join('') document.getElementById('helpPrev').disabled = helpPage === 0 document.getElementById('helpNext').disabled = helpPage === HELP_PAGES.length - 1 document.getElementById('helpBody').scrollTop = 0 } const gotoHelp = (i) => { helpPage = i; renderHelp() } document.getElementById('btnHelp').onclick = () => { helpPage = 0; renderHelp(); document.getElementById('helpDlg').showModal() } document.getElementById('helpClose').onclick = () => document.getElementById('helpDlg').close() document.getElementById('helpNav').onclick = (e) => { const b = e.target.closest('[data-hp]'); if (b) gotoHelp(+b.dataset.hp) } document.getElementById('helpPrev').onclick = () => gotoHelp(helpPage - 1) document.getElementById('helpNext').onclick = () => gotoHelp(helpPage + 1) document.getElementById('helpDlg').addEventListener('keydown', (e) => { if (e.key === 'ArrowRight' && helpPage < HELP_PAGES.length - 1) gotoHelp(helpPage + 1) if (e.key === 'ArrowLeft' && helpPage > 0) gotoHelp(helpPage - 1) }) /* ── interactive tour: spotlight walks over the real UI, section by section ── */ // Each step points at a real element (sel). before() may switch view/mode or open // a project so the element exists; steps whose element is missing are skipped. const TOURS = { views: { before: () => applyUiMode('advanced'), steps: [ { sel: '#tabs [data-view="board"]', key: 'help.board' }, { sel: '#tabs [data-view="gallery"]', key: 'help.gallery' }, { sel: '#tabs [data-view="list"]', key: 'help.list' }, { sel: '#tabs [data-view="tasks"]', key: 'help.tasks' }, { sel: '#tabs [data-view="activity"]', key: 'help.activity' }, { sel: '#tabs [data-view="storage"]', key: 'help.storage' }, ] }, find: { before: () => { applyUiMode('advanced'); setView('board') }, steps: [ { sel: '#modeSeg', key: 'help.mode' }, { sel: '.searchbox', key: 'help.search' }, { sel: '#chipfilters', key: 'help.filters' }, ] }, project: { before: () => { applyUiMode('advanced'); setView('board') }, steps: [ { sel: '#board .card .qsg', key: 'help.quick' }, { before: () => { const p = visibleProjects()[0] || projects[0]; if (p) { tour.openedEditor = true; openEditor(p) } }, wait: 480, sel: '#ptabs [data-sec="edit"]', key: 'help.edit' }, { sel: '#ptabs [data-sec="info"]', key: 'help.info' }, { sel: '#ptabs [data-sec="actions"]', key: 'help.actions' }, ] }, backup: { before: () => applyUiMode('advanced'), steps: [ { sel: '#btnBackup', key: 'help.backup' }, { sel: '#chipfilters [data-q="due"]', key: 'help.due' }, ] }, misc: { before: () => applyUiMode('advanced'), steps: [ { sel: '#rootBtn', key: 'help.folders' }, { sel: '#btnSettings', key: 'help.lang' }, { sel: '#btnHelp', key: 'help.keys' }, ] }, // first start (and Help → Setup): walks through the settings panel; manual pace, user types meanwhile setup: { auto: false, keepView: true, before: () => (document.getElementById('spanel').classList.contains('open') ? null : openSettings(false)), steps: [ { key: 'tour.setup.welcome' }, { before: () => setSettingsTab('folders'), wait: 150, sel: '#fRoots', key: 'tour.setup.folders' }, { sel: '#fImportOpen', key: 'tour.setup.import' }, { before: () => setSettingsTab('backup'), wait: 150, sel: '#fTargets:not(:empty), #fAddTarget', key: 'tour.setup.backup' }, { sel: '#fAutoInt', key: 'tour.setup.auto' }, { before: () => setSettingsTab('general'), wait: 150, sel: '#fLang', key: 'tour.setup.general' }, { sel: '.featrow:has(#fFeatItch)', key: 'tour.setup.features' }, { before: () => setSettingsTab('folders'), wait: 150, sel: '#spSave', key: 'tour.setup.save' }, ] }, } const AUTO_MS = 3400 let tour = null async function startTour(id) { const def = TOURS[id] if (!def) return document.getElementById('helpDlg').close() tour = { def, steps: def.steps, i: -1, playing: def.auto !== false, timer: null, prevView: activeView, prevMode: uiMode, openedEditor: false } try { await def.before?.() } catch {} if (!tour) return document.getElementById('tour').hidden = false setTimeout(() => tourGo(1), 320) // let a view/mode switch (or the panel sliding in) render first } // only elements that are actually on screen (hidden sections are skipped) const tourTarget = (s) => { if (!s.sel) return null const el = document.querySelector(s.sel) return el && el.getClientRects().length ? el : null } async function tourGo(dir) { if (!tour) return clearTimeout(tour.timer) let i = tour.i for (;;) { i += dir if (i < 0) { i = 0; break } if (i >= tour.steps.length) { endTour(); return } const s = tour.steps[i] if (s.before) { try { s.before() } catch {} } if (s.wait) await new Promise((r) => setTimeout(r, s.wait)) if (!tour) return // closed meanwhile if (!s.sel || tourTarget(s)) break // usable step (has target or is centered) } tour.i = i tourShow() } function tourShow() { if (!tour) return const s = tour.steps[tour.i] positionSpot(tourTarget(s)) document.getElementById('tourText').innerHTML = t(s.key) document.getElementById('tourStep').textContent = `${tour.i + 1} / ${tour.steps.length}` document.getElementById('tourPrev').disabled = tour.i === 0 document.querySelector('#tourNext span').textContent = tour.i === tour.steps.length - 1 ? t('tour.finish') : t('help.next') document.querySelector('#tourPause use').setAttribute('href', `/icons.svg#${tour.playing ? 'pause' : 'play'}`) clearTimeout(tour.timer) if (tour.playing) tour.timer = setTimeout(() => tourGo(1), AUTO_MS) } function positionSpot(el) { const spot = document.getElementById('tourSpot') const bubble = document.getElementById('tourBubble') if (el) { try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }) } catch {} const r = el.getBoundingClientRect(), pad = 6 spot.style.top = (r.top - pad) + 'px' spot.style.left = (r.left - pad) + 'px' spot.style.width = (r.width + pad * 2) + 'px' spot.style.height = (r.height + pad * 2) + 'px' const bw = Math.min(320, innerWidth - 24), bh = bubble.offsetHeight || 150 let top = r.bottom + 12 if (top + bh > innerHeight - 10) top = Math.max(10, r.top - bh - 12) let left = Math.max(12, Math.min(innerWidth - bw - 12, r.left + r.width / 2 - bw / 2)) bubble.style.top = top + 'px' bubble.style.left = left + 'px' } else { spot.style.width = spot.style.height = '0px' spot.style.top = innerHeight / 2 + 'px' spot.style.left = innerWidth / 2 + 'px' bubble.style.top = Math.max(12, innerHeight / 2 - 90) + 'px' bubble.style.left = (innerWidth / 2 - Math.min(320, innerWidth - 24) / 2) + 'px' } } function endTour() { if (!tour) return clearTimeout(tour.timer) const opened = tour.openedEditor, pv = tour.prevView, pm = tour.prevMode, keep = tour.def.keepView tour = null document.getElementById('tour').hidden = true if (opened) try { closeEditor() } catch {} if (keep) return try { applyUiMode(pm) } catch {} try { setView(pv) } catch {} } document.getElementById('tourClose').onclick = endTour document.getElementById('tourPrev').onclick = () => tourGo(-1) document.getElementById('tourNext').onclick = () => tourGo(1) document.getElementById('tourPause').onclick = () => { if (!tour) return tour.playing = !tour.playing tourShow() } addEventListener('resize', () => { if (tour) tourShow() }) addEventListener('keydown', (e) => { if (!tour) return if (e.target.closest?.('input, textarea, select, [contenteditable]')) return // typing a path etc. if (e.key === 'Escape') { e.preventDefault(); endTour() } else if (e.key === 'ArrowRight') tourGo(1) else if (e.key === 'ArrowLeft') tourGo(-1) }) 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(t('err.serverStale')) } 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 if (v.version) { const el = document.getElementById('spVersion'); if (el) el.textContent = 'v' + v.version } const banner = document.getElementById('updBanner') const btn = document.getElementById('updBtn') if (v.stale) { document.getElementById('updText').textContent = t('upd.serverStale') btn.innerHTML = `${ic('refresh-cw')}${t('upd.restart')}` btn.onclick = restartServer banner.hidden = false } else if (v.uiStamp > uiStampAtLoad) { document.getElementById('updText').textContent = t('upd.uiNew') btn.innerHTML = `${ic('refresh-cw')}${t('upd.reload')}` 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')}${t('upd.restarting')}` 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(t('upd.noRestart')) 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(t('upd.noResponse')) } catch (e) { toast(e.message, 'triangle-alert') btn.disabled = false btn.innerHTML = `${ic('refresh-cw')}${t('upd.restart')}` } } 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(t('action.started', { label: r.label }), 'play') } catch (e) { toast(e.message, 'triangle-alert') } } /* ── filtering & sorting ──────────────────────────────────────────────── */ // label is a translation key (resolved with t() at render time) const QUICK = [ { key: 'all', label: 'quick.all', icon: 'layers', test: () => true }, { key: 'nobackup', label: 'quick.nobackup', icon: 'cloud-off', test: (p) => p.git.level === 'red' }, { key: 'unsaved', label: 'quick.unsaved', icon: 'cloud-upload', test: (p) => p.git.level === 'yellow' }, { key: 'due', label: 'quick.due', icon: 'clock-alert', test: backupDue }, { key: 'cleanable', label: 'quick.cleanable', icon: 'brush-cleaning', test: (p) => deletableMB(p) >= 100 }, { key: 'install', label: 'quick.install', icon: 'download', test: (p) => p.tech?.needsInstall }, { key: 'noicon', label: 'quick.noicon', icon: 'image-off', test: (p) => !p.hasIcon }, { key: 'gencopy', label: 'quick.gencopy', icon: 'copy', test: (p) => p.tools?.generators?.some((g) => g.kind === 'copy') }, { key: 'fav', label: 'quick.fav', icon: 'star', test: (p) => !!p.favorite }, { key: 'itch', label: 'quick.itch', icon: 'rocket', feature: 'itch', test: (p) => !!p.published }, { key: 'noitch', label: 'quick.noitch', 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 tot = 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}
${t('kpi.projects', { n: active })}
${ic('shield-alert', 'lg')}
${tot.noBackup}
${t('kpi.noRemote')}
${ic('hard-drive', 'lg')}
${tot.scanned ? fmtMB(tot.sizeMB) : '–'}
${tot.scanned ? t('kpi.used', { n: tot.scanned }) : t('kpi.notScanned')}
${ic('brush-cleaning', 'lg')}
${tot.scanned ? fmtMB(tot.allMB) : '–'}
${tot.scanned ? t('kpi.cleanableCache', { cache: fmtMB(tot.cacheMB) }) : t('kpi.cleanable')}
${running ? `
${escapeHtml(scanState.current.join(', '))}
` : scanState?.error ? `
${ic('triangle-alert', 'sm')} ${t('kpi.scanError')}
` : `
${t('kpi.scanHint')}
`}
` 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() } requestAnimationFrame(fitChips) // after the rest of the toolbar (sort, board mode) has its final size } // Measured, not a fixed breakpoint (labels differ per language): too wide → icon + count only, // still too wide → the row scrolls sideways with a fade at the edge. function fitChips() { const el = document.getElementById('chipfilters') if (!el) return el.classList.remove('compact', 'more') if (el.scrollWidth > el.clientWidth + 1) el.classList.add('compact') if (el.scrollWidth > el.clientWidth + 1) el.classList.add('more') } // the toolbar's width, not the chips' (fitChips changes those itself – that would loop) new ResizeObserver(() => fitChips()).observe(document.querySelector('.toolbar')) function render() { document.getElementById('count').textContent = noneShown ? t('count.none') : !rootDir ? t('count.noFolder') : rootPaths.length > 1 ? t('count.multi', { n: projects.length, folders: rootPaths.length }) : t('count.single', { n: projects.length, dir: 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' requestAnimationFrame(fitChips) // the space left for the filter chips changed } /* ── 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(t('scan.done'), '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 ? t('qs.start', { label: 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 = t('prio.titled', { p: t('prio.' + 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')}${t('status.' + col.key)}${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} → ${t('status.' + col.key)}`, 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')}
${t('empty.noProjects')}
`; 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 // label is a translation key (resolved with t() at render time; '' = no header) const LIST_COLS = [ { label: 'col.project', sort: 'name' }, { label: 'col.status', cls: 'c-status' }, { label: 'col.git' }, { label: 'col.backup' }, { label: 'col.tech', cls: 'c-tech' }, { label: 'col.size', sort: 'size', num: true }, { label: 'col.cleanable', sort: 'clean', num: true, cls: 'c-clean' }, { label: 'col.activity', 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 ? t(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('') || `${t('empty.noProjects')}`}` 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' // layout: cards (big tiles) · compact (small tiles) · list (one row each); sort: like the toolbar const HL_STORE = (key, allowed, dflt) => { try { const v = localStorage.getItem(key); return allowed.includes(v) ? v : dflt } catch { return dflt } } let homeLayout = HL_STORE('dash.homeLayout', ['cards', 'compact', 'list'], 'cards') let homeSort = HL_STORE('dash.homeSort', ['mtime', 'name', 'size'], 'mtime') // label is a translation key (resolved with t() at render time) const HOME_PILLS = [ { key: 'all', label: 'home.all', test: (p) => p.status !== 'archived' }, { key: 'due', label: 'quick.due', test: (p) => backupDue(p), cls: 'due' }, { key: 'active', label: 'status.active' }, { key: 'idea', label: 'home.ideas' }, { key: 'paused', label: 'status.paused' }, { key: 'done', label: 'status.done' }, { key: 'archived', label: 'home.archive' }, ] const pillTest = (q) => q.test ?? ((p) => p.status === q.key) function sortHome(items) { return [...items].sort((a, b) => { if (homeSort === 'name') return a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }) if (homeSort === 'size') return (b.storage?.sizeMB ?? -1) - (a.storage?.sizeMB ?? -1) return new Date(lastActivity(b)) - new Date(lastActivity(a)) }) } const HL_SEG = [{ k: 'cards', ic: 'layout-grid', key: 'home.cards' }, { k: 'compact', ic: 'grid-2x2', key: 'home.compact' }, { k: 'list', ic: 'list', key: 'home.list' }] const HL_SORT = [{ k: 'mtime', key: 'flt.sort.mtime' }, { k: 'name', key: 'flt.sort.name' }, { k: 'size', key: 'flt.sort.size' }] function renderHome() { const base = projects.filter(matchesSearch) const pills = HOME_PILLS.map((q) => { const n = base.filter(pillTest(q)).length if (q.key !== 'all' && !n && homeStatus !== q.key) return '' return `` }).join('') const ctl = `
${HL_SEG.map((o) => ``).join('')}
` document.getElementById('homeBar').innerHTML = pills + ctl for (const b of document.querySelectorAll('#homeBar .hpill')) b.onclick = () => { homeStatus = b.dataset.hs; renderHome() } document.getElementById('homeSortSel').onchange = (e) => { homeSort = e.target.value; try { localStorage.setItem('dash.homeSort', homeSort) } catch {}; renderHome() } for (const b of document.querySelectorAll('#homeBar .hseg button')) b.onclick = () => { homeLayout = b.dataset.hl; try { localStorage.setItem('dash.homeLayout', homeLayout) } catch {}; renderHome() } const pill = HOME_PILLS.find((q) => q.key === homeStatus) ?? HOME_PILLS[0] const items = sortHome(base.filter(pillTest(pill))) const grid = document.getElementById('homeGrid') grid.className = homeLayout === 'cards' ? '' : homeLayout if (!items.length) { grid.innerHTML = `
${ic('search-x', 'xl')}
${t('empty.noProjects')}
`; 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', t('home.favorites')) const ordered = favs.length ? [...favs, null, ...items.filter((p) => !p.favorite)] : items for (const p of ordered) { if (!p) { head('layout-grid', t('home.allProjects')); 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) : t('home.noDesc')}
${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 // short weekday (0=Mon…6=Sun) and month (0=Jan…) in the current language, via Intl const dowShort = (i) => new Intl.DateTimeFormat(I18N.locale(), { weekday: 'short', timeZone: 'UTC' }).format(new Date(Date.UTC(2024, 0, 1 + i))) const monthShort = (m) => new Intl.DateTimeFormat(I18N.locale(), { month: 'short' }).format(new Date(2024, m, 1)) 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(I18N.locale(), { 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 levelLabel = (l) => window.I18N.t('act.level.' + l) 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 = Array.from({ length: 7 }, (_, i) => (i % 2 === 0 ? `${dowShort(i)}` : '')).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 += `${monthShort(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) const T = window.I18N.t const daysWord = (n) => T(n === 1 ? 'act.day1' : 'act.daysN', { n }) document.getElementById('acKpis').innerHTML = `
${T('act.activeDays')}
${keys.length}
${T('act.pastYear')}
${T('act.currentStreak')}
${daysWord(current)}
${T('act.streakSub')}
${T('act.longestStreak')}
${daysWord(longest)}
${T('act.pastYear')}
${T('act.fullestDay')}
${best ? T('act.nProjects', { n: nActive(best) }) : '–'}
${best ? parseDay(best).toLocaleDateString(I18N.locale()) : ''}
` document.getElementById('acPending').textContent = actData.pending ? '· ' + T('act.pending', { n: actData.pending }) : '' document.getElementById('acLegend').innerHTML = `${T('act.less')}${[0, 1, 2, 3, 4].map((l) => ``).join('')}${T('act.more')}` const heat = document.getElementById('acHeat') heat.innerHTML = heatGrid(53, (k) => levelOf(nActive(k)), (k) => `${fmtDay(k)}: ${T('act.nProjects', { n: nActive(k) })}`) 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 ? t(files === 1 ? 'act.file1' : 'act.filesN', { n: files }) : '', commits ? t(commits === 1 ? 'act.commit1' : 'act.commitsN', { n: 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('')}
` : `
${t('act.nothingDay')}
` } 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, `${t(a.days === 1 ? 'act.day1' : 'act.daysN', { n: a.days })} · ${t('act.lastAgo', { ago: timeAgo(parseDay(a.last).toISOString()) })}`)).join('')}
` : `
${t('act.noChangesRange')}
` } 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 = { get Cache() { return tierShort('Cache') }, get Release() { return tierShort('Release') }, get Output() { return tierShort('Output') } } const tierVar = (t) => `var(--t-${t.toLowerCase()})` const fmtMB1 = (mb) => (mb >= 1024 ? `${(mb / 1024).toLocaleString(I18N.locale(), { maximumFractionDigits: mb >= 10240 ? 0 : 1 })} GB` : `${Math.round(mb).toLocaleString(I18N.locale())} 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 ? `` : '') const T = window.I18N.t document.getElementById('stKpis').innerHTML = `
${T('st.used')}
${fmtMB1(total)}
${T('st.nMeasured', { n: scanned.length })}
${T('st.cleanable')}
${fmtMB1(delAll)}
${TIER_KEYS.map((k) => `${TIER_SHORT[k]} ${fmtMB1(del[k])}`).join('')}
${T('st.cleanableShare')}
${total ? Math.round((delAll / total) * 100) : 0} %
${T('st.ofUsed')}
${T('st.measuredCount')}
${scanned.length} / ${ps.length}
${scan?.running ? `${ic('loader', 'sm')} ${T('st.runningN', { done: scan.done, total: scan.total })}` : oldest ? `${T('st.oldest', { ago: timeAgo(oldest) })}` : `${T('st.nothingMeasured')}`}
` 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('') + `${t('tier.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 = `
${t('st.nothingMeasuredHint')}
`; 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 ? t('st.projUnmeasured') : t('st.projRemeasure')}

` 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 ?? {} const T = window.I18N.t html = `${escapeHtml(p.name)}
${T('st.size')}${fmtMB1(p.sizeMB)}
` + TIER_KEYS.filter((k) => d[k] > 0).map((k) => `
${TIER_SHORT[k]}${fmtMB1(d[k])}
`).join('') + (multiRoot() ? `
${T('st.folder')}${escapeHtml(p.rootName)}
` : '') + `
${T('st.measured')}${timeAgo(p.at)}
` } else { const T = window.I18N.t 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)}
${T('st.size')}${fmtMB1(c.mb)}
` + (info?.tier ? `
${T('st.deletable')}${TIER_SHORT[info.tier]}
` : '') + (info ? TIER_KEYS.filter((k) => info.inside[k] > 0).map((k) => `
${T('st.inside', { s: TIER_SHORT[k] })}${fmtMB1(info.inside[k])}
`).join('') : '') + (t.hasAttribute('data-drill') ? `
${T('st.clickSub')}
` : '') } 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('')}
` : `
${t('st.nothingMeasured2')}
` } 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 ? '' : ''}${t('col.project')}${t('st.folder')}${t('st.kind')}${t('st.size')} ${rows.map((r) => ` ${can ? `` : ''} ${escapeHtml(r.p.name)} ${escapeHtml(inProject(r.path, r.p.folder))} ${TIER_SHORT[r.tier]} ${fmtMB1(r.mb)}`).join('')}` : `${t('st.nothingToClean')}` 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 ? t('st.selected', { n: sel.length, size: fmtMB1(mb) }) : storageData?.cleanupAvailable ? '' : t('st.needCleanup') 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(t('st.confirmDelete', { n: sel.length, size: fmtMB1(mb) }) + '\n\n' + sel.map((r) => `${r.p.name}: ${inProject(r.path, r.p.folder)}`).join('\n') + '\n\n' + t('st.regenHint'))) return const btn = document.getElementById('stDelete') btn.disabled = true btn.innerHTML = `${ic('loader')}${t('st.deleting')}` 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')}${t('st.deleteSelected')}` if (!failed) toast(t('st.freed', { size: fmtMB1(mb) }), '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(t('err.saveFailed'), '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' ? t('tasks.noOpen') : t('tasks.noneFound')}
${t('tasks.addHint')}
` 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((x) => `
${escapeHtml(x.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(t('tasks.added', { name: p.name }), '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 = `
${t('info.folder')}
${escapeHtml(d.path)}
${t('panel.status')}
${statusHtml(p.status)} · ${t('prio.titled', { p: p.priority ? t('prio.' + p.priority) : '–' })}
${t('info.changed')}
${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}${p.lastChange?.file ? ` · ${escapeHtml(p.lastChange.file)}` : ''}
${t('btn.backup')}
${ic('hard-drive', 'sm')}${escapeHtml(c.short)}${backupDue(p) ? ` ${t('info.due')}` : ''}
${t('st.size')}
${s ? `${fmtMB(s.sizeMB)} · ${t('info.scannedAgo', { ago: timeAgo(s.at) })}${del >= 1 ? ` · ${fmtMB(del)} ${t('size.cleanableWord')}` : ''}` : `${t('kpi.notScanned')}`}
` const gitBody = g.isRepo ? `
${t('panel.status')}
${gitHtml(g)}${g.dirty ? ` · ${t('info.uncommitted', { n: g.dirty })}` : ''}
${t('info.branch')}
${ic('git-branch', 'sm')} ${escapeHtml(g.branch)}${g.upstream ? ` → ${escapeHtml(g.upstream)}` : ''}${g.ahead ? ` · ${t('info.notPushed', { n: g.ahead })}` : ''}
${t('info.remote')}
${g.remote ? `${escapeHtml(g.remote)}` : `${t('info.noRemoteShort')}`}
${t('info.lastCommit')}
${g.lastCommit ? `${g.lastCommit.date} · ${escapeHtml(g.lastCommit.message)}` : '–'}
` : `
${gitHtml(g)}
${t('info.noRepo')}
` const ip = d.itchPack ?? { exists: false } const itchBody = `
${t('info.published')}
${p.published ? `${escapeHtml(p.published.title || p.published.url)}` : `${t('info.no')}`}
${t('info.pagePack')}
${ip.exists ? `${escapeHtml(ip.rel)} · ${timeAgo(ip.at)}` : `${t('info.noneYet')}`}
` const arcs = d.archives ?? [] const arcBody = arcs.length ? `
${arcs.slice(0, 8).map((a) => `
${new Date(a.at).toLocaleDateString(I18N.locale())}
${escapeHtml(a.name)} · ${fmtMB(a.mb)}
`).join('')}
${arcs.length > 8 ? `
${t('info.moreOlder', { n: arcs.length - 8 })}
` : ''}` : `
${t('info.noZips')}
` const gens = d.tools.generators const genBody = gens.length ? `
${gens.map((x) => `
${escapeHtml(x.rel)}
${x.kind === 'comfygen' ? `${ic('wand-sparkles', 'sm')}${t('info.usesComfyGen')}` : `${ic('copy', 'sm')}${t('info.ownCopy')}
${escapeHtml(x.scripts.join(', '))}
`}
`).join('')}
` : `
${t('info.noGenerator')}
` const genDir = gens.find((x) => x.kind === 'comfygen') const iconBody = d.icon ? `
${escapeHtml(d.icon)}
` : `
${ic('image-off', 'sm')}${t('info.noIconFound')}
${genDir ? t('info.iconComfyGen') : t('info.iconTemplate')}
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')} ${t('desc.fromReadme')}
` : `
${t('desc.none')}
` const descEdit = `` const el = document.getElementById('sec-info') el.innerHTML = section('notebook-text', t('info.description'), `
${descBody}
${descEdit}`, { id: 'info-desc', right: `${ic('pencil', 'sm')}${desc ? t('desc.edit') : t('desc.write')}` }) + section('info', t('info.overview'), overview, { right: del >= 1 ? `${jumpLink('act-clean', t('info.cleanUp'))}` : '' }) + section('git-branch', 'Git', gitBody, { adv: true, right: jumpLink('act-git', g.isRepo ? t('info.pushRemote') : t('set.setup')) }) + (name === '_Tools' || !itchOn() ? '' : section('rocket', 'itch.io', itchBody, { adv: true, right: jumpLink('act-itch', ip.exists ? t('info.view') : t('info.generate')) })) + section('cpu', t('info.tech'), `
${techChips(d.tech.types) || `${t('info.notDetected')}`}${d.tech.needsInstall ? `${ic('download', 'sm')}${t('info.npmNeeded')}` : ''}
`, { adv: true }) + `

${ic('activity')}${t('tab.activity')}

${t('info.loading')}
` + section('file-archive', t('info.releaseArchives'), arcBody, { adv: true, right: jumpLink('act-zip', t('info.makeZip')) }) + section('wand-sparkles', t('info.generator'), genBody, { adv: true }) + section('image', t('info.appIcon'), 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 ?? t('err.saveFailed')) for (const p of [editing, projects.find((x) => x.name === name)]) if (p) p.description = r.description toast(r.description ? t('desc.saved') : t('desc.removed'), '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 `
${t('info.noRepo')}
` } const key = d.sshKey const keyHint = key ? `
${ic('key-round', 'sm')} ${t('git.sshKey')}: ${escapeHtml(key.file)}
` : `
${ic('key-round', 'sm')} ${t('git.noSshKey')}
` const pushBox = !g.remote ? '' : g.dirty ? `
` : `
${g.ahead ? '' : t('git.nothingNew')}
` return `${pushBox}
${g.remote ? '' : `
${t('git.noRemoteYet')}
`} ${keyHint}
${t('git.pushConsole')}
` } 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 `
${t('arc.lands', { folder: escapeHtml(folder) })}${rd.length ? '' : t('arc.noBuild')}.
` } function itchActionHtml(name, d) { const ip = d.itchPack ?? { exists: false } const p = projects.find((x) => x.name === name) ?? editing if (!ip.exists) { return `
${t('itchA.generateHint')}
` } return `
${p?.published ? `${ic('external-link')}` : ''}
${escapeHtml(ip.rel)} · ${t('itchA.lastChanged', { ago: timeAgo(ip.at) })}
` } function cleanHtml(d) { const s = d.storage let body if (!s) body = `
${t('clean.unscanned')}
` else { const rows = s.candidates.filter((c) => c.MB >= 1 || c.Skip) body = `
${t('st.size')}
${fmtMB(s.sizeMB)} · ${t('info.scannedAgo', { ago: timeAgo(s.at) })}
${t('st.deletable')}
Cache ${fmtMB(s.deletable.Cache)} · Builds ${fmtMB(s.deletable.Release)} · ${tierShort('Output')} ${fmtMB(s.deletable.Output)}
` body += rows.length ? `${rows.map((c) => ``).join('')}
${escapeHtml(inProject(c.Path, editing?.folder))} ${ic(TIER[c.Tier].icon, 'sm')}${tierLabel(c.Tier)}${c.Skip ? ` ${ic('lock', 'sm')}${t('clean.inGit')}` : ''} ${fmtMB(c.MB)}
${t('clean.cacheHint')}
` : `
${ic('sparkles', 'sm')} ${t('clean.nothing')}
` } 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('')}
` : `
${t('prog.noneFound')}${hasBuild ? ' ' + t('prog.buildFirst') : ''}
`) + (prog?.missing ? `
${ic('triangle-alert', 'sm')} ${t('prog.missing', { rel: escapeHtml(prog.rel) })}
` : '') + `
${ic('pin', 'sm')}${t('prog.setForPlay')}${prog ? `: ${escapeHtml(prog.rel)}` : ' ' + t('prog.automatic')}
${hasPicker ? `` : ''} ${prog ? `` : ''}
${t('prog.pathHint')}
` // server group names (keys) → display labels const actGroupLabel = (g) => ({ Programm: t('act.g.program'), Starten: t('act.g.start'), Einrichten: t('set.setup'), Bauen: t('act.g.build'), Werkzeuge: t('act.g.tools'), 'Öffnen': t('act.g.open') }[g] ?? g) const btnGroup = (g) => groups[g] ? section(ACTION_ICON[g], actGroupLabel(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', t('act.g.start')) + section('app-window', t('act.g.program'), progHtml) + btnGroup('Starten') + btnGroup('Einrichten') + btnGroup('Bauen') + head('shield-check', t('act.h.save')) + section('git-branch', 'Git', gitActionsHtml(name, d), { id: 'act-git', adv: true }) + (tools ? '' : section('hard-drive-upload', t('btn.backup'), '
', { id: 'act-backup' })) + head('rocket', t('act.h.publish')) + section('file-archive', t('act.releaseZip'), archiveHtml(name, d), { id: 'act-zip', adv: true }) + (tools || !itchOn() ? '' : section('rocket', t('dlg.itch.title'), itchActionHtml(name, d), { id: 'act-itch', adv: true })) + head('brush-cleaning', t('info.cleanUp')) + section('hard-drive', t('tab.storage'), cleanHtml(d), { id: 'act-clean', adv: true }) + (groups['Werkzeuge'] || groups['Öffnen'] ? head('wrench', t('act.g.tools')) + btnGroup('Werkzeuge') + btnGroup('Öffnen') : '') + `
${ic('shield-check', 'sm')} ${t('act.consoleHint')}
` + (tools ? '' : head('triangle-alert', t('danger.title')) + `
${t('danger.hint')}
`) document.getElementById('btnDeleteProject')?.addEventListener('click', () => deleteProject(name, d)) 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(t('prog.pickFor', { name }), 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(t('git.pushRunning'), '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(t('git.enterMsg'), 'info') } try { await postJson(api(name, 'push'), { message: msg }); toast(t('git.commitPushRunning'), 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') } }) on('btnRemote', async () => { try { await postJson(api(name, 'remote'), { url: document.getElementById('gRemote').value }); toast(t('git.remoteSaved'), '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(t('git.initDone'), 'git-branch'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') } }) on('btnCopyKey', async () => { try { await navigator.clipboard.writeText(d.sshKey.key); toast(t('git.keyCopied'), 'copy') } catch { toast(t('err.copyFailed'), '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(t('arc.confirmDel', { what }))) return btn.disabled = true btn.innerHTML = `${ic('loader')}${t('arc.packing')}` try { const r = await postJson(api(name, 'archive'), { what, deleteAfter: del }) toast(`${r.name} (${fmtMB(r.mb)})${r.deleted ? ' – ' + t('arc.buildDeleted') : ''}`, 'file-archive') loadDetails(name) if (r.deleted) load() } catch (ex) { toast(ex.message, 'triangle-alert') btn.disabled = false btn.innerHTML = `${ic('file-archive')}${t('info.makeZip')}` } } 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 ? t('itchA.checking') : t('itchA.creating'), '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(t('import.nothingSelected')) const mb = s.candidates.filter((c) => paths.includes(c.Path)).reduce((a, c) => a + c.MB, 0) if (!confirm(t('clean.confirmDel', { n: paths.length, size: fmtMB(mb), name }) + '\n\n' + paths.map((x) => inProject(x, editing?.folder)).join('\n'))) return clean.disabled = true clean.innerHTML = `${ic('loader')}${t('st.deleting')}` try { const r = await postJson(api(name, 'clean'), { paths }) toast(t('clean.result', { n: r.deleted.length, gb: String(r.freedGB).replace('.', ',') }) + (r.failed.length ? ' · ' + t('clean.locked', { n: r.failed.length }) : ''), 'brush-cleaning') await load() loadDetails(name) } catch (e) { toast(e.message, 'triangle-alert'); clean.disabled = false; clean.innerHTML = `${ic('trash')}${t('st.deleteSelected')}` } } } /* ── 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')} ${t('nest.searching')}
` 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 = `
${t('nest.error')}: ${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)}${t('nest.collection')}
${c.projects.map((x) => item(r, x, x.chosen || !x.ignored)).join('')}
`).join('') const inner = r.inProjects.length ? `
${ic('folder-git-2', 'sm')}${t('nest.inProjects')}${t('nest.inProjectsHint')}
${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)} · ${t('nest.nFound', { n })}

${groups + inner || `
${nestDeep ? t('nest.noneDeep') : t('nest.none')}
`}
` }).join('') document.getElementById('nestBody').innerHTML = `
${t('nest.explain')}
${html || `
${t('nest.noFolders')}
`}` } 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 ? t(r.chosen === 1 ? 'nest.adopted1' : 'nest.adoptedN', { n: r.chosen }) : t('nest.adoptedNone'), '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(t('copy.ok', { what }), 'copy') } catch { toast(t('err.copyFailed'), '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(t('copy.okFormatted', { what }), 'copy') } catch { copyText(html, `${what} (HTML)`) } } async function openItch(name) { itchName = name const dlg = document.getElementById('itchDlg') document.getElementById('itchTitle').textContent = `${t('dlg.itch.title')} · ${name}` document.getElementById('itchBody').innerHTML = `
${ic('loader', 'sm')} ${t('itch.loading')}
` 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 = `
${t('nest.error')}: ${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) } // second element is a translation key (resolved at render time) const ITCH_KINDS = [ ['cover', 'itch.kind.cover'], ['theme', 'itch.kind.theme'], ['promo', 'itch.kind.promo'], ['screenshot', 'itch.kind.screenshot'], ['other', 'itch.kind.other'], ] function renderItch() { const d = itchData const name = itchName const body = document.getElementById('itchBody') if (!d.exists) { body.innerHTML = `
${t('itch.noPackage')}
` return } const row = (label, f, extra = '') => { const v = f?.copy ?? '' return `
${label}
${v ? escapeHtml(v) : `${f?.placeholder ? t('itch.openField') : t('itch.notFound')}`}${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 ? t('itch.shorter') : t('itch.shortSugg'), { 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((x) => ``).join('') const tagsBlock = `

${ic('tags')}Tags ${t('itch.tagsHint')} ${ownTags.length ? `` : ''}

${ownTags.length ? `
${t('itch.inPackage', { n: ownTags.length })}${tagChips(ownTags, 'own')}
` : `
${t('itch.noTags')}
`} ${sugg.length ? `
${t('itch.examples')}${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 `
${t(label)} · ${list.length}
${list.map((i) => ``).join('')}
` }).join('') body.innerHTML = `

${ic('type')}${t('itch.texts')}

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

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

${t('itch.noDescHtml')}
` : ''} ${htmlBlock('desc', 'Description', d.descriptionHtml, t('itch.nWords', { n: words }))} ${tagsBlock} ${htmlBlock('install', 'Install instructions', d.installHtml)}

${ic('images')}${t('itch.images')} ${t('itch.imagesHint')}

${gallery || `
${t('itch.noImages')}
`} ${d.media?.length ? `
${ic('film', 'sm')} ${t('itch.moreFiles')}: ${d.media.map(escapeHtml).join(', ')}
` : ''}
${otherFields.length ? `

${ic('list')}${t('itch.moreFields')}

${otherFields.map((f) => `
${escapeHtml(f.key)}
${f.placeholder ? `${t('itch.openField')}` : escapeHtml(f.text)}
`).join('')}
` : ''}
${ic('shield-check', 'sm')} ${t('itch.nothingUploaded')}
` 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' : t('itch.installText')) 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 ?? t('err.saveFailed')) toast(r.program ? t('prog.nowStarts', { prog: r.program }) : t('prog.autoAgain'), 'pin') if (editing?.name === name) { editing.program = r.program; loadDetails(name) } load() } catch (e) { toast(e.message, 'triangle-alert') } } // Permanently deletes the whole project folder (server: /delete). Two confirms. async function deleteProject(name, d) { if (!confirm(t('danger.confirm1', { name, path: d?.path ?? name }))) return if (!confirm(t('danger.confirm2', { name }))) return try { await postJson(api(name, 'delete')) toast(t('danger.deleted', { name }), 'trash') closeEditor() await load() await loadBackup() } 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 = window.I18N.t 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')}
${T('pbackup.noTarget')}
` 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) + `
${T('pbackup.lastSaved')}
${last ? `${new Date(last.at).toLocaleString(I18N.locale(), { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(last.at)}) · ${last.how}` : `${T('cloud.never')}`}
${T('pbackup.target')}
${escapeHtml(shownT ? `${shownT.path}\\${name}` : '…')}
${projectTargets.length > 1 ? `
${T('pbackup.allTargets')}
${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) : T('cloud.never')}` }).join('')}
` : ''}
` if (busy && mine && b.phase === 'checking') { html += `
${ic('loader')}
${T('pbackup.checking')}
` } 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 += `
${T('pbackup.copyingPct', { pct })}${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
${T('pbackup.nFiles', { done: pr.files.toLocaleString(I18N.locale()), total: pr.filesTotal.toLocaleString(I18N.locale()) })}
${escapeHtml(pr.current)}
` } else if (busy) { html += `
${ic('hourglass')}
${T('pbackup.otherRunning', { scope: b.scope ? escapeHtml(b.scope) : T('pbackup.allProjects') })}
` } else if (mine && b.phase === 'done') { const l = shownT?.lastByProject?.[name] html += l && l.files ? `
${ic('circle-check')}
${T('pbackup.savedBold')} ${T('pbackup.copiedN', { n: l.files.toLocaleString(I18N.locale()), size: fmtBytes(l.bytes) })}
` : `
${ic('circle-check')}
${T('pbackup.upToDate')} ${T('pbackup.nothingMissing')}
` } else if (mine && b.phase === 'error') { html += `
${ic('triangle-alert')}
${escapeHtml(b.error)}
` } else if (mine && b.phase === 'cancelled') { html += `
${ic('circle-x')}
${T('pbackup.cancelled')}
` } html += `
${busy && mine ? `` : ``}
${T('pbackup.hint')}
` 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 = `
${t('nest.error')}: ${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')} ${t('edit.itchNot')}` : p.published?.source === 'auto' ? `${ic('sparkles', 'sm')} ${t('edit.itchAuto', { title: escapeHtml(p.published.title) })} – ${escapeHtml(p.published.url)}` : p.published ? '' : `${ic('info', 'sm')} ${t('edit.itchNotFound')}` document.getElementById('fNotes').value = p.notes renderTaskList() const loading = `
${ic('loader', 'sm')} ${t('itch.loading')}
` 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(t('edit.saved'), 'save') closeEditor() load() } else toast(patchProject.error || t('err.saveFailed'), '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((x) => ``).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' ? t('backup.autoDone') : t('backup.autoFail', { err: backup.error ?? t('backup.cancelledWord') }), backup.phase === 'done' ? 'circle-check' : 'triangle-alert') } else if (!wasBusy && backupBusy() && backup.auto) toast(t('backup.autoRunning'), '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') const T = window.I18N.t btn.title = (backup.targets ?? []).map((x) => `${x.name}: ${x.last ? T('backup.lastAgo', { ago: timeAgo(x.last.at) }) : T('backup.neverComplete')}`).join('\n') || T('pbackup.setupTarget') if (backup.notConfigured) { sub.textContent = '· ' + T('backup.setup'); 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 ? '· ' + T('backup.autoChecking') : '· ' + T('backup.checkingShort') 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 = `· ${T('backup.nDue', { n: dueCount() })}` else if (last) sub.textContent = `${prefix}${timeAgo(last.at)}` else sub.textContent = `${prefix}${T('cloud.never')}` 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${T('backup.dueTitle', { n: dueCount(), days: BACKUP_FRESH_DAYS })}` fitHeader() } 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(t(n === 1 ? 'backup.remind1' : 'backup.remindN', { n }), '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() { const T = window.I18N.t let b = backup if (!b) return if (b.notConfigured) { document.getElementById('bpTarget').textContent = T('backup.noTargetShort') document.getElementById('bpBody').innerHTML = `
${ic('hard-drive-upload')}
${T('backup.noTargetLong')}
` 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 ? `
${T('backup.lastBackup')}
${new Date(tl.at).toLocaleString(I18N.locale(), { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(tl.at)})
${T('backup.copied')}
${T('backup.nFilesCell', { n: tl.files.toLocaleString(I18N.locale()) })} · ${fmtBytes(tl.bytes)}${tl.ok === false ? ` · ${T('cloud.incomplete')}` : ''}
` : `
${T('backup.noneOnTarget', { name: escapeHtml(t.name) })}
` let body = targetTabs(busy ? b.target : null) + section('clock-3', T('backup.statusOf', { name: escapeHtml(t.name) }), last) b = { ...b, phase } if (b.scope && b.phase !== 'idle') { body += `
${ic('folder')}
${T('backup.scopeNote', { scope: escapeHtml(b.scope) })}
` } if (b.phase === 'checking') { body += `
${ic('loader')}
${T('backup.checkingLong')}
${T('backup.checkingTime')}
` } 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', T('backup.copyingTitle'), `
${pct} %${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
${T('pbackup.nFiles', { done: pr.files.toLocaleString(I18N.locale()), total: pr.filesTotal.toLocaleString(I18N.locale()) })}
${escapeHtml(pr.current)}
`) + `
${T('backup.keepOpen')}
` } else if (b.phase === 'ready' && b.check) { const c = b.check if (!c.files) { body += `
${ic('circle-check')}
${T('pbackup.upToDate')} ${T('backup.nothingMissing')}
` } else { body += section('scan-search', `${T('backup.checkResult')} ${timeAgo(c.at)}`, `
${ic('file-plus', 'sm')}${T('backup.new')}
${c.newFiles.toLocaleString(I18N.locale())}
${fmtBytes(c.newBytes)}
${ic('file-pen', 'sm')}${T('backup.changed')}
${c.changedFiles.toLocaleString(I18N.locale())}
${fmtBytes(c.changedBytes)}
${ic('archive', 'sm')}${T('backup.onlyInBackup')}
${c.extraFiles.toLocaleString(I18N.locale())}
${T('backup.kept')}
${c.projects.slice(0, 15).map((p) => ``).join('')}
${escapeHtml(p.name)}${T('backup.nFilesCell', { n: p.files.toLocaleString(I18N.locale()) })}${fmtBytes(p.bytes)}
${c.projects.length > 15 ? `
${T('backup.moreProjects', { n: c.projects.length - 15 })}
` : ''}`) } body += `
${c.files ? `` : ''}
` } else { if (b.phase === 'done') body += `
${ic('circle-check')}
${T('backup.done')} ${tl && !b.scope ? T('backup.doneN', { n: tl.files.toLocaleString(I18N.locale()), size: fmtBytes(tl.bytes) }) : ''}
` if (b.phase === 'cancelled') body += `
${ic('circle-x')}
${T('pbackup.cancelled')}
` if (b.phase === 'error') body += `
${ic('triangle-alert')}
${escapeHtml(b.error)}
` body += `
` } body += `
${ic('shield-check', 'sm')} ${T('backup.footerHint', { exclude: escapeHtml((settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.gradle', '.venv']).join(', ')) })}
` 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) /* ── language (Einstellungen → Allgemein) ─────────────────────────────── */ // Static text is swapped by I18N via data-i18n attributes; dynamic parts are // re-rendered here after a switch. English is the default (see i18n.js). function initLang() { const sel = document.getElementById('fLang') if (sel) { sel.innerHTML = Object.entries(I18N.langs).map(([code, name]) => ``).join('') sel.value = I18N.get() sel.addEventListener('change', () => I18N.set(sel.value)) } I18N.onChange(() => { const sl = document.getElementById('fLang'); if (sl) sl.value = I18N.get() try { render() } catch {} try { renderBackupButton() } catch {} try { renderRootPicker() } catch {} if (editing) try { openEditor(editing) } catch {} const sp = document.getElementById('spanel') if (sp.classList.contains('open')) { I18N.apply(sp); try { renderAutoStatus() } catch {} } try { if (document.getElementById('helpDlg').open) renderHelp() } catch {} }) } /* ── start screen: progress while the projects are read ───────────────── */ // 1/2 projects (git, sizes, tech - the first /api/projects), 2/2 "last change" of // every project (lib/activity.js, background). Shows count, bar and time left. let boot = null function startBoot() { const el = document.getElementById('boot') boot = { step: 1, t0: Date.now(), timer: null, loaded: false } el.hidden = false document.getElementById('bootSkip').onclick = endBoot const tick = async () => { if (!boot) return try { const r = await (await fetch('/api/progress')).json() if (!boot) return if (boot.step === 1) { const pj = r.projects showBoot(1, pj.phase === 'itch' ? t('boot.itch') : t('boot.reading2'), pj.done, pj.total) } else { const total = r.activity.total || 1 const done = Math.max(0, total - r.activity.pending) if (!r.activity.pending) return endBoot() showBoot(2, t('boot.changes'), done, total) } } catch {} if (boot) boot.timer = setTimeout(tick, 300) } // only worth a screen when it takes a moment boot.timer = setTimeout(tick, 150) } function showBoot(step, label, done, total) { if (boot.shownStep !== step) { boot.shownStep = step; boot.t0 = Date.now(); boot.d0 = done } const pct = total ? Math.min(100, Math.round((done / total) * 100)) : 0 document.getElementById('bootStep').textContent = t('boot.step', { step }) document.getElementById('bootLabel').textContent = label document.getElementById('bootBar').style.width = `${pct}%` document.getElementById('bootCount').textContent = total ? `${done} / ${total}` : '' // time left from the speed of this step so far const secs = (Date.now() - boot.t0) / 1000 const rate = (done - (boot.d0 ?? 0)) / Math.max(secs, 0.1) const left = rate > 0 && total > done ? Math.ceil((total - done) / rate) : null document.getElementById('bootEta').textContent = left == null ? t('boot.estimating') : left < 2 ? t('boot.almost') : left < 60 ? t('boot.etaS', { s: left }) : t('boot.etaMin', { m: Math.ceil(left / 60) }) } // the projects are there: step 2 only while "last change" is still being collected function bootLoaded() { if (!boot) return if (noneShown || !projects.length || document.getElementById('spanel').classList.contains('open')) return endBoot() boot.step = 2 } function endBoot() { if (!boot) return clearTimeout(boot.timer) boot = null const el = document.getElementById('boot') el.classList.add('done') setTimeout(() => { el.hidden = true }, 250) } /* ── header: gets more compact step by step when it does not fit ──────── */ function fitHeader() { const bar = document.querySelector('.topbar') const levels = 4 for (let i = 1; i <= levels; i++) document.body.classList.remove(`hc${i}`) for (let i = 1; i <= levels && bar.scrollWidth > bar.clientWidth + 1; i++) document.body.classList.add(`hc${i}`) } new ResizeObserver(fitHeader).observe(document.querySelector('.topbar')) window.addEventListener('resize', fitHeader) /* ── 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() initLang() 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) } } document.getElementById('noneOpen').onclick = (e) => { e.stopPropagation(); toggleRootMenu(true) } startBoot() load().then(() => { bootLoaded(); 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) })