/* Project dashboard UI: board (kanban), gallery and list views, a side panel
to edit a project, see its git/storage/tool info and start actions.
Icons come from the Lucide sprite served at /icons.svg. */
const STATUS = [
{ key: 'idea', label: 'Idee', icon: 'lightbulb', color: '#94a3b8' },
{ key: 'active', label: 'Aktiv', icon: 'rocket', color: '#22c55e' },
{ key: 'paused', label: 'Pausiert', icon: 'circle-pause', color: '#f59e0b' },
{ key: 'done', label: 'Fertig', icon: 'circle-check', color: '#3b82f6' },
{ key: 'archived', label: 'Archiviert', icon: 'archive', color: '#8b5cf6' },
]
const STATUS_BY = Object.fromEntries(STATUS.map((s) => [s.key, s]))
const PRIO_ORDER = { high: 0, medium: 1, low: 2 }
const PRIO_LABEL = { high: 'Hoch', medium: 'Mittel', low: 'Niedrig' }
const TECH_ICON = {
Unity: 'box', Node: 'hexagon', Electron: 'atom', Expo: 'smartphone', Capacitor: 'smartphone', Vite: 'zap',
React: 'atom', '.NET': 'code-xml', Flutter: 'feather', Android: 'smartphone', 'C++/CMake': 'cpu',
Python: 'square-terminal', Web: 'globe', Arduino: 'circuit-board',
}
const GIT_ICON = { green: 'cloud-check', yellow: 'cloud-upload', red: 'cloud-off' }
const TIER = {
Cache: { label: 'Cache', hint: 'immer neu erzeugbar', cls: 'ok', icon: 'recycle' },
Release: { label: 'Fertiger Build', hint: 'Version – bewusst löschen', cls: 'warn', icon: 'package' },
Output: { label: 'Rohbilder', hint: 'Generator-Output', cls: 'warn', icon: 'images' },
}
const ACTION_ICON = {
'Einrichten': 'download', 'Starten': 'play', 'Bauen': 'hammer', 'Werkzeuge': 'wand-sparkles', 'Öffnen': 'folder-open',
}
let projects = []
let totals = null
let scanState = null
let cleanupAvailable = false
let editing = null
let editingTasks = []
let searchTerm = ''
let quickFilter = 'all'
let activeView = 'board'
let scanTimer = null
/* ── helpers ──────────────────────────────────────────────────────────── */
const ic = (name, cls = '') => ` `
// ?r= keeps the browser cache apart when two projects folders have a project of the same name
const thumbUrl = (name) => `/api/projects/${encodeURIComponent(name)}/thumb?r=${encodeURIComponent(activeRoots.join(','))}`
const api = (name, what) => `/api/projects/${encodeURIComponent(name)}/${what}`
function escapeHtml(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
}
function timeAgo(iso) {
if (!iso) return ''
const days = Math.floor((Date.now() - new Date(iso)) / 86400000)
if (days <= 0) return 'heute'
if (days === 1) return 'gestern'
if (days < 30) return `vor ${days} T.`
if (days < 365) return `vor ${Math.floor(days / 30)} Mon.`
return `vor ${Math.floor(days / 365)} J.`
}
function fmtMB(mb) {
if (mb == null) return '–'
if (mb >= 1024) return `${(mb / 1024).toFixed(1).replace('.', ',')} GB`
return `${Math.round(mb)} MB`
}
function nameColor(name) {
let hash = 0
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0
const h = Math.abs(hash) % 360
return `linear-gradient(135deg, hsl(${h} 62% 58%), hsl(${(h + 40) % 360} 62% 48%))`
}
function initialsOf(name) {
const parts = name.split(/[\s_\-.]+/).filter(Boolean)
if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase()
return name.slice(0, 2).toUpperCase()
}
// Project icon with letter fallback: the image sits on top of the initials
// and removes itself when the project has no picture.
function avatar(p, cls = '') {
return `
${escapeHtml(initialsOf(p.name))}
`
}
const deletableMB = (p) => p.storage ? p.storage.deletable.Cache + p.storage.deletable.Release + p.storage.deletable.Output : 0
// last change = newest file in the project (server: lib/activity.js), else last commit / folder date
const lastActivity = (p) => p.lastChange?.at ?? p.lastCommit?.date ?? p.mtime
function fmtDate(iso, withYear = true) {
if (!iso) return '–'
return new Date(iso).toLocaleDateString('de-DE', withYear ? { day: '2-digit', month: '2-digit', year: '2-digit' } : { day: '2-digit', month: '2-digit' })
}
function changeTitle(p) {
const at = lastActivity(p)
const when = new Date(at).toLocaleString('de-DE', { dateStyle: 'full', timeStyle: 'short' })
if (p.lastChange) return `Letzte Änderung: ${when}\n${p.lastChange.file}${p.lastChange.partial ? '\n(großes Projekt – nur teilweise durchsucht)' : ''}`
return p.lastChange === undefined ? `Wird ermittelt … (bisher: ${when})` : `Letzte Änderung: ${when}`
}
function sizeTitle(p) {
if (p.storage?.sizeMB == null) return 'Ordnergröße: noch nicht gescannt („Alle scannen“ oben)'
return `Ordnergröße: ${fmtMB(p.storage.sizeMB)} (gescannt ${timeAgo(p.storage.at)})${deletableMB(p) >= 1 ? ` · davon ${fmtMB(deletableMB(p))} aufräumbar` : ''}`
}
function factsHtml(p) {
return `
${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'}
${ic('file-pen', 'sm')}${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}
`
}
function gitHtml(git, short = false) {
const label = short ? ({ green: 'Gesichert', yellow: 'Ungesichert', red: 'Kein Remote' })[git.level] : git.label
return `${ic(GIT_ICON[git.level], 'sm')}${escapeHtml(label)} `
}
// Backup state of one project (p.lastBackup from the server: own or full backup, newer one)
const BACKUP_FRESH_DAYS = 7
function cloudInfo(p) {
const l = p.lastBackup
if (!l) return { level: 'red', short: 'nie', label: 'Backup: noch nie gesichert' }
const days = (Date.now() - new Date(l.at)) / 86400000
const when = new Date(l.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })
const level = l.ok === false ? 'red' : days > BACKUP_FRESH_DAYS ? 'yellow' : 'green'
const extra = l.ok === false ? ' – unvollständig' : days > BACKUP_FRESH_DAYS ? ` – älter als ${BACKUP_FRESH_DAYS} Tage` : ''
return { level, short: timeAgo(l.at), label: `Backup: gesichert ${when} (${l.how})${extra}` }
}
function cloudBadge(p, cls = 'tbadge') {
const c = cloudInfo(p)
return `${ic('hard-drive')} `
}
function cloudChip(p) {
const c = cloudInfo(p)
return `${ic('hard-drive', 'sm')}${escapeHtml(c.short)} `
}
// itch.io: p.published = { url, title, source: 'auto' | 'manual' } (server, lib/itch.js)
function pubTitle(p) {
const x = p.published
return x ? `Auf itch.io veröffentlicht${x.title ? `: ${x.title}` : ''} (${x.source === 'manual' ? 'manuell eingetragen' : 'automatisch erkannt'}) – Klick öffnet die Seite` : ''
}
function pubChip(p, short = false) {
if (!p.published) return ''
return `${ic('rocket', 'sm')}${short ? '' : 'itch.io'} `
}
function pubBadge(p) {
if (!p.published) return ''
return `${ic('rocket')} `
}
function statusHtml(key) {
const s = STATUS_BY[key] ?? STATUS[0]
return `${ic(s.icon, 'sm')}${s.label} `
}
function prioHtml(prio) {
const icon = prio === 'high' ? 'flame' : prio === 'low' ? 'chevron-down' : 'equal'
return `${ic(icon, 'sm')}${PRIO_LABEL[prio]} `
}
// Which projects folder a project is from - only shown when several are on screen.
function rootTag(p, short = false) {
if (!multiRoot() || !p.rootName) return ''
const path = roots.find((r) => r.id === p.root)?.path ?? ''
return `${ic('folder', 'sm')}${short ? '' : ' '}${escapeHtml(p.rootName)} `
}
function techChips(types) {
return (types ?? []).map((t) => `${ic(TECH_ICON[t] ?? 'code', 'sm')}${escapeHtml(t)} `).join('')
}
function warnChips(p) {
const b = []
if (deletableMB(p) >= 100) b.push(`${ic('brush-cleaning', 'sm')}${fmtMB(deletableMB(p))} `)
if (p.tech?.needsInstall) b.push(`${ic('download', 'sm')}npm install `)
if (p.tools?.generators?.some((g) => g.kind === 'copy')) b.push(`${ic('copy', 'sm')}Generator-Kopie `)
else if (p.tools?.generators?.length) b.push(`${ic('wand-sparkles', 'sm')}ComfyGen `)
if (!p.hasIcon) b.push(`${ic('image-off', 'sm')}kein Icon `)
return b.join('')
}
/* ── data ─────────────────────────────────────────────────────────────── */
let rootDir = '' // first shown projects folder
let rootPaths = [] // all shown projects folders
let roots = [] // registered projects folders [{ id, name, path }]
let activeRoots = [] // ids of the shown ones (several possible)
const multiRoot = () => activeRoots.length > 1
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] : [])
renderRootPicker()
if (editing) editing = projects.find((p) => p.name === editing.name) ?? editing
render()
if (scanState?.running) pollScan()
// last-change dates are still being collected in the background → refresh once more
clearTimeout(load.again)
if (data.activityPending > 0) load.again = setTimeout(load, 2500)
if (data.setupNeeded) openSettings(true) // first start: choose the projects folder
}
/* ── new project / clone ──────────────────────────────────────────────── */
const newDlg = document.getElementById('newDlg')
function openNewProject(from = '') {
closeEditor()
const sel = document.getElementById('nFrom')
sel.innerHTML = `Leeres Projekt ` +
[...projects].sort((a, b) => a.name.localeCompare(b.name, 'de')).map((p) => `Klon von: ${escapeHtml(p.name)} `).join('')
sel.value = from
document.getElementById('nRoot').innerHTML = roots.map((r) => `${escapeHtml(r.name)} – ${escapeHtml(r.path)} `).join('')
// default: the folder of the template, else the first shown one
document.getElementById('nRoot').value = projects.find((p) => p.name === from)?.root ?? activeRoots[0] ?? ''
document.getElementById('nExcl').textContent = (settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.venv']).join(', ')
document.getElementById('nName').value = from ? `${from} - Kopie` : ''
document.getElementById('nError').style.display = 'none'
syncNewDlg()
newDlg.showModal()
document.getElementById('nName').select()
}
function syncNewDlg() {
const clone = !!document.getElementById('nFrom').value
document.getElementById('nCloneOpts').hidden = !clone
document.getElementById('nEmptyHint').hidden = clone
document.getElementById('newTitle').textContent = clone ? 'Projekt klonen' : 'Neues Projekt'
document.querySelector('#nOk span').textContent = clone ? 'Klonen' : 'Anlegen'
}
document.getElementById('nFrom').addEventListener('change', () => {
const from = document.getElementById('nFrom').value
const name = document.getElementById('nName')
// keep a typed name, replace only the suggested one
if (!name.value.trim() || / - Kopie$/.test(name.value)) name.value = from ? `${from} - Kopie` : ''
syncNewDlg()
})
document.getElementById('nCancel').onclick = () => newDlg.close()
document.getElementById('btnNew').onclick = () => openNewProject('')
document.getElementById('btnClone').onclick = () => { if (editing) openNewProject(editing.name) }
document.getElementById('newForm').addEventListener('submit', async (e) => {
e.preventDefault()
const ok = document.getElementById('nOk')
const err = document.getElementById('nError')
const from = document.getElementById('nFrom').value
const root = document.getElementById('nRoot').value
err.style.display = 'none'
ok.disabled = true
const label = ok.querySelector('span').textContent
ok.querySelector('span').textContent = from ? 'Wird kopiert…' : 'Wird angelegt…'
try {
const r = await postJson('/api/projects/new', {
name: document.getElementById('nName').value, root, from,
withGit: document.getElementById('nGit').checked, skipBuild: document.getElementById('nSkipBuild').checked,
})
newDlg.close()
toast(`${r.cloned ? 'Klon' : 'Projekt'} „${r.name}“ angelegt`, 'folder-plus')
if (r.shown) {
await load()
const p = projects.find((x) => x.name === r.key)
if (p) openEditor(p)
}
} catch (ex) {
err.innerHTML = `${ic('triangle-alert')}${escapeHtml(ex.message)}
`
err.style.display = ''
} finally {
ok.disabled = false
ok.querySelector('span').textContent = label
}
})
/* ── projects folder quick switch (dropdown next to the logo) ─────────── */
const rootMenu = document.getElementById('rootMenu')
const rootBtn = document.getElementById('rootBtn')
// Each row: [☑ box = add/remove from the view] [name = show only this folder]
function renderRootPicker() {
const cur = roots.filter((r) => activeRoots.includes(r.id))
document.getElementById('rootName').textContent =
!cur.length ? 'Projekte' : cur.length === 1 ? cur[0].name : cur.length === roots.length && cur.length > 2 ? `Alle Ordner (${cur.length})` : cur.map((r) => r.name).join(' + ')
rootBtn.title = cur.length ? `Projektordner – angezeigt:\n${cur.map((r) => r.path).join('\n')}` : 'Projektordner wählen'
rootMenu.setAttribute('aria-multiselectable', 'true')
rootMenu.innerHTML = roots.map((r) => {
const on = activeRoots.includes(r.id)
return `
${ic(on ? 'square-check' : 'square', 'sm')}
${escapeHtml(r.name)} ${escapeHtml(r.path)}
`
}).join('') +
(roots.length > 1 ? `${ic('layers', 'sm')} Alle Ordner anzeigen ` : '') +
`${roots.length ? '
' : ''}` +
(hasPicker ? `${ic('folder-plus', 'sm')} Ordner hinzufügen… ` : '') +
`${ic('folders', 'sm')} Mehrere Ordner einlesen…
${ic('settings', 'sm')} Projektordner verwalten… `
}
// Adds folders via the server and (optionally) switches to the first new one.
async function addRoots(paths, activate) {
const r = await postJson('/api/roots/add', { paths, activate })
settingsCache = r
if (!r.added.length) { toast('Schon in der Liste', 'info'); return r }
if (activate) { closeEditor(); searchTerm = ''; document.getElementById('search').value = '' }
await load()
if (activate) await loadBackup()
toast(r.added.length === 1 ? `Projektordner „${r.added[0].name}“ hinzugefügt` : `${r.added.length} Projektordner hinzugefügt`, 'folder-plus')
return r
}
// "Ordner hinzufügen…" (desktop app): folder dialog → add → switch to it
async function addRootByPicker() {
const chosen = await pickFolder('Ordner mit Projekten wählen', rootDir)
if (!chosen) return
try { await addRoots([chosen], true) } catch (e) { toast(e.message, 'triangle-alert') }
}
// "Mehrere Ordner einlesen…": dialog with the subfolder checklist
const rootDlg = document.getElementById('rootDlg')
function openRootImport() {
document.getElementById('rdBody').innerHTML = ''
document.getElementById('rdError').style.display = 'none'
rootDlg.showModal()
document.getElementById('rdPath').focus()
}
function listRootImport() {
document.getElementById('rdError').style.display = 'none'
return importList({
dir: document.getElementById('rdPath').value,
body: document.getElementById('rdBody'),
have: roots.map((r) => r.path.toLowerCase().replace(/[\\/]+$/, '')),
onAdd: async (picked) => {
try {
await addRoots(picked, document.getElementById('rdActivate').checked)
rootDlg.close()
} catch (e) {
const err = document.getElementById('rdError')
err.innerHTML = `${ic('triangle-alert')}${escapeHtml(e.message)}
`
err.style.display = ''
throw e
}
},
})
}
document.getElementById('rdList').onclick = listRootImport
document.getElementById('rdPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listRootImport() } })
document.getElementById('rdPick').onclick = async () => {
const input = document.getElementById('rdPath')
const chosen = await pickFolder('Übergeordneten Ordner wählen', input.value)
if (chosen) { input.value = chosen; listRootImport() }
}
document.getElementById('rdClose').onclick = () => rootDlg.close()
function toggleRootMenu(open = rootMenu.hidden) {
rootMenu.hidden = !open
rootBtn.setAttribute('aria-expanded', String(open))
if (open) (rootMenu.querySelector('[aria-selected="true"]') ?? rootMenu.querySelector('button'))?.focus()
}
// Shows the given folders (ids, in list order). keepOpen: the menu stays open (ticking boxes).
async function showRoots(ids, keepOpen = false) {
if (!keepOpen) toggleRootMenu(false)
ids = roots.map((r) => r.id).filter((id) => ids.includes(id))
if (!ids.length || ids.join('|') === activeRoots.join('|')) return
const prev = activeRoots
activeRoots = ids // tick right away; the projects follow when loaded
renderRootPicker()
try {
await postJson('/api/roots/active', { ids })
closeEditor()
searchTerm = ''
document.getElementById('search').value = ''
await load()
await loadBackup()
if (!keepOpen) toast(`Projektordner: ${roots.filter((r) => ids.includes(r.id)).map((r) => r.name).join(' + ')}`, 'folder-open')
} catch (e) {
activeRoots = prev
renderRootPicker()
toast(e.message, 'triangle-alert')
}
}
rootBtn.onclick = (e) => { e.stopPropagation(); toggleRootMenu() }
rootMenu.addEventListener('click', (e) => {
e.stopPropagation()
const b = e.target.closest('button')
if (!b) return
if (b.hasAttribute('data-root-manage')) { toggleRootMenu(false); openSettings(false); return }
if (b.hasAttribute('data-root-add')) { toggleRootMenu(false); addRootByPicker(); return }
if (b.hasAttribute('data-root-import')) { toggleRootMenu(false); openRootImport(); return }
if (b.hasAttribute('data-root-all')) { showRoots(roots.map((r) => r.id)); return }
const t = b.dataset.rootToggle
if (t) {
const next = activeRoots.includes(t) ? activeRoots.filter((x) => x !== t) : [...activeRoots, t]
if (!next.length) return toast('Mindestens ein Ordner bleibt angezeigt', 'info')
showRoots(next, true)
return
}
showRoots([b.dataset.root])
})
rootMenu.addEventListener('keydown', (e) => {
const items = [...rootMenu.querySelectorAll('button')]
const i = items.indexOf(document.activeElement)
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus() }
if (e.key === 'Escape') { e.stopPropagation(); toggleRootMenu(false); rootBtn.focus() }
})
document.addEventListener('click', () => { if (!rootMenu.hidden) toggleRootMenu(false) })
/* ── settings (projects folder, backup target) ────────────────────────── */
let settingsCache = null
let settingsSetup = false
// In the desktop app (WebView2) the exe shows a real folder dialog; in a
// normal browser the user types the path.
const hasPicker = !!window.chrome?.webview
const pickWaiters = new Map()
if (hasPicker) {
window.chrome.webview.addEventListener('message', (e) => {
const m = e.data
if ((m?.type === 'folderPicked' || m?.type === 'filePicked') && pickWaiters.has(m.id)) { pickWaiters.get(m.id)(m.path ?? ''); pickWaiters.delete(m.id) }
})
} else document.body.classList.add('no-picker')
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 {}
const s = settingsCache ?? { roots: [], backup: { targets: [], excludeDirs: [] } }
document.getElementById('fRoots').innerHTML = (s.roots ?? []).map((r) => rootRow(r, (s.activeRoots ?? [s.activeRoot]).includes(r.id))).join('') || rootRow()
document.getElementById('fImport').hidden = true
document.getElementById('fImportBody').innerHTML = ''
document.getElementById('fTargets').innerHTML = (s.backup?.targets ?? []).map(targetRow).join('') || targetRow()
document.getElementById('fExDirs').value = (s.backup?.excludeDirs ?? []).join(', ')
document.getElementById('fItchProfile').value = s.itchProfile ?? ''
loadItchStatus()
document.getElementById('spData').innerHTML = s.dataDir ? `${ic('database', 'sm')} Einstellungen gespeichert in ${escapeHtml(s.dataDir)}` : ''
document.getElementById('spWelcome').style.display = setup ? '' : 'none'
document.getElementById('spTitle').textContent = setup ? 'Einrichten' : 'Einstellungen'
document.getElementById('spError').style.display = 'none'
const panel = document.getElementById('spanel')
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.innerHTML = `${ic('loader', 'sm')} itch.io wird gelesen…`
try {
const r = refresh ? await postJson('/api/itch/refresh', {}) : await (await fetch('/api/itch')).json()
if (!r.profile) { el.innerHTML = 'Leer = keine itch.io-Anzeige.'; return }
const un = r.unmatched ?? []
el.innerHTML = r.error
? `${ic('triangle-alert', 'sm')} ${escapeHtml(r.error)}`
: `${ic('rocket', 'sm')} ${r.games.length} Spiele gefunden.` +
(un.length ? ` Ohne Projekt: ${un.map((g) => `${escapeHtml(g.title)} `).join(', ')} – im Projekt unter „Bearbeiten“ den Link eintragen.` : ' Alle einem Projekt zugeordnet.')
} catch (e) { el.textContent = e.message }
}
document.getElementById('btnItchRefresh').onclick = async () => { await loadItchStatus(true); load() }
function closeSettings() {
if (settingsSetup) return // the projects folder is required
const panel = document.getElementById('spanel')
if (!panel.classList.contains('open')) return
panel.classList.remove('open')
panel.setAttribute('aria-hidden', 'true')
if (!editing && !document.getElementById('bpanel').classList.contains('open')) document.getElementById('overlay').classList.remove('open')
}
async function saveSettings() {
const err = document.getElementById('spError')
err.style.display = 'none'
const body = {
roots: [...document.querySelectorAll('#fRoots .rrow')]
.map((r) => ({ id: r.dataset.id, name: r.querySelector('.tname').value, path: r.querySelector('.tpath').value }))
.filter((r) => r.path.trim()),
activeRoots: settingsCache?.activeRoots ?? [],
targets: [...document.querySelectorAll('#fTargets .trow')]
.map((r) => ({ id: r.dataset.id, name: r.querySelector('.tname').value, path: r.querySelector('.tpath').value }))
.filter((t) => t.path.trim()),
excludeDirs: document.getElementById('fExDirs').value.split(',').map((x) => x.trim()).filter(Boolean),
itchProfile: document.getElementById('fItchProfile').value,
}
try {
settingsCache = await postJson('/api/settings', body)
settingsSetup = false
closeSettings()
toast('Einstellungen gespeichert', 'save')
await loadBackup()
await load()
} catch (e) {
err.innerHTML = `${ic('triangle-alert')}${escapeHtml(e.message)}
`
err.style.display = ''
}
}
// "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)
if (b.dataset.for === 'fImportPath') listImport()
})
// projects folder rows: [name] [path] [Durchsuchen…] [↑] [x]; the active one is marked
const folderName = (p) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || p
function rootRow(r = { id: '', name: '', path: '' }, active = false) {
return `
${ic('folder-search')}Durchsuchen…
${ic('arrow-up')}
${ic('x')}
`
}
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))
return box.lastElementChild
}
document.getElementById('fAddRoot').onclick = () => addRootRow().querySelector('.tpath').focus()
document.getElementById('fRoots').addEventListener('click', (e) => {
const row = e.target.closest('.rrow')
if (e.target.closest('[data-rrm]')) row.remove()
else if (e.target.closest('[data-rup]') && row.previousElementSibling) row.parentNode.insertBefore(row, row.previousElementSibling)
})
// "Mehrere einlesen…": list the subfolders of a folder, tick the ones to add
document.getElementById('fImportOpen').onclick = () => {
const box = document.getElementById('fImport')
box.hidden = !box.hidden
if (!box.hidden) document.getElementById('fImportPath').focus()
}
document.getElementById('fImportList').onclick = () => listImport()
document.getElementById('fImportPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listImport() } })
function listImport() {
return importList({
dir: document.getElementById('fImportPath').value,
body: document.getElementById('fImportBody'),
have: rowRootPaths(),
onAdd: (picked) => {
for (const p of picked) addRootRow({ id: '', name: folderName(p), path: p })
document.getElementById('fImport').hidden = true
toast(`${picked.length} Projektordner hinzugefügt – Speichern nicht vergessen`, 'folder-plus')
},
})
}
// Lists the subfolders of `dir` in `body` as checkboxes (plus the folder itself);
// folders in `have` (lower-case paths) are shown as already added. onAdd(paths) gets the ticked ones.
async function importList({ dir, body, have, onAdd }) {
dir = (dir ?? '').trim()
if (!dir) return
body.innerHTML = `${ic('loader', 'sm')} wird gelesen…
`
try {
const res = await fetch(`/api/subfolders?path=${encodeURIComponent(dir)}`)
const r = await res.json()
if (!res.ok) throw new Error(r.error ?? res.statusText)
const haveSet = new Set(have)
const known = (p) => haveSet.has(p.toLowerCase().replace(/[\\/]+$/, ''))
const item = (f, label, extra, self = false) => `
${ic('folder', 'sm')}${label} ${known(f.path) ? 'schon in der Liste' : extra} `
body.innerHTML = `
${item({ path: r.path }, `
Diesen Ordner selbst (${escapeHtml(folderName(r.path))})`, `${r.folders.length} Projekte`, true)}
${r.folders.map((f) => item(f, escapeHtml(f.name), `${f.count} Unterordner`)).join('') || '
Keine Unterordner.
'}
${ic('list-checks')}Alle Unterordner
${ic('plus')}Ausgewählte hinzufügen
`
body.querySelector('[data-imp-all]').onclick = () => {
const boxes = [...body.querySelectorAll('input:not(:disabled):not([data-self])')]
const on = !boxes.every((c) => c.checked)
for (const c of boxes) c.checked = on
}
body.querySelector('[data-imp-add]').onclick = async (e) => {
const picked = [...body.querySelectorAll('input:checked:not(:disabled)')].map((c) => c.dataset.path)
if (!picked.length) return toast('Nichts ausgewählt', 'info')
const btn = e.currentTarget
btn.disabled = true
try { await onAdd(picked); body.innerHTML = '' } finally { btn.disabled = false }
}
} catch (e) {
body.innerHTML = `${ic('triangle-alert')}
${escapeHtml(e.message)}
`
}
}
// backup target rows in the settings: [name] [path] [Durchsuchen…] [x]
const shortTargetName = (p) => p.match(/^\\\\([^\\]+)/)?.[1] ?? (p.match(/^([A-Za-z]:)/) ? `${p.slice(0, 2)} ${p.split('\\').filter(Boolean).pop() ?? ''}`.trim() : p.split('\\').pop())
function targetRow(t = { id: '', name: '', path: '' }) {
return `
${ic('folder-search')}Durchsuchen…
${ic('x')}
`
}
document.getElementById('fAddTarget').onclick = () => {
document.getElementById('fTargets').insertAdjacentHTML('beforeend', targetRow())
document.querySelector('#fTargets .trow:last-child .tpath').focus()
}
document.getElementById('fTargets').addEventListener('click', (e) => { if (e.target.closest('[data-trm]')) e.target.closest('.trow').remove() })
document.getElementById('btnSettings').onclick = () => openSettings(false)
document.getElementById('btnCloseSettings').onclick = closeSettings
document.getElementById('spCancel').onclick = closeSettings
document.getElementById('spSave').onclick = saveSettings
async function postJson(url, body) {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body ?? {}),
})
let data = {}
try { data = await res.json() } catch {}
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`)
return data
}
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
}
function toast(text, icon = 'info') {
const el = document.getElementById('toast')
el.innerHTML = `${ic(icon)}${escapeHtml(text)} `
el.classList.add('show')
clearTimeout(toast.t)
toast.t = setTimeout(() => el.classList.remove('show'), 3400)
}
const runAction = async (name, id) => {
try {
const r = await postJson(api(name, 'run'), { id })
toast(`Gestartet: ${r.label}`, 'play')
} catch (e) { toast(e.message, 'triangle-alert') }
}
/* ── filtering & sorting ──────────────────────────────────────────────── */
const QUICK = [
{ key: 'all', label: 'Alle', icon: 'layers', test: () => true },
{ key: 'nobackup', label: 'Ohne Remote', icon: 'cloud-off', test: (p) => p.git.level === 'red' },
{ key: 'unsaved', label: 'Ungesichert', icon: 'cloud-upload', test: (p) => p.git.level === 'yellow' },
{ key: 'cleanable', label: 'Aufräumbar', icon: 'brush-cleaning', test: (p) => deletableMB(p) >= 100 },
{ key: 'install', label: 'npm install', icon: 'download', test: (p) => p.tech?.needsInstall },
{ key: 'noicon', label: 'Ohne Icon', icon: 'image-off', test: (p) => !p.hasIcon },
{ key: 'gencopy', label: 'Generator-Kopie', icon: 'copy', test: (p) => p.tools?.generators?.some((g) => g.kind === 'copy') },
{ key: 'itch', label: 'itch.io', icon: 'rocket', test: (p) => !!p.published },
{ key: 'noitch', label: 'Fertig, nicht auf itch', icon: 'circle-off', 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.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 (sort === 'name') return a.name.localeCompare(b.name, 'de', { sensitivity: 'base' })
if (sort === 'priority') return (PRIO_ORDER[a.priority] - PRIO_ORDER[b.priority]) || (new Date(lastActivity(b)) - new Date(lastActivity(a)))
if (sort === 'size') return (b.storage?.sizeMB ?? -1) - (a.storage?.sizeMB ?? -1)
if (sort === 'clean') return deletableMB(b) - deletableMB(a)
return new Date(lastActivity(b)) - new Date(lastActivity(a))
})
}
/* ── header: KPIs, quick filters ──────────────────────────────────────── */
function renderKpis() {
const t = totals ?? { sizeMB: 0, cacheMB: 0, allMB: 0, scanned: 0, noBackup: 0 }
const active = projects.filter((p) => p.status === 'active').length
const running = scanState?.running
const pct = running && scanState.total ? Math.round((scanState.done / scanState.total) * 100) : 0
document.getElementById('kpis').innerHTML = `
${ic('layers', 'lg')}
${projects.length}
Projekte · ${active} aktiv
${ic('shield-alert', 'lg')}
${t.noBackup}
ohne Git-Remote
${ic('hard-drive', 'lg')}
${t.scanned ? fmtMB(t.sizeMB) : '–'}
${t.scanned ? `belegt (${t.scanned} gescannt)` : 'noch nicht gescannt'}
${ic('brush-cleaning', 'lg')}
${t.scanned ? fmtMB(t.allMB) : '–'}
${t.scanned ? `aufräumbar · Cache ${fmtMB(t.cacheMB)}` : 'aufräumbar'}
${ic(running ? 'loader' : 'scan-search')}${running ? `Scan ${scanState.done}/${scanState.total}` : 'Alle scannen'}
${running ? `
${escapeHtml(scanState.current.join(', '))}
`
: scanState?.error ? `
${ic('triangle-alert', 'sm')} Scan-Fehler
`
: '
Größe & löschbare Ordner messen
'}
`
document.getElementById('btnScanAll').onclick = () => startScan(null)
for (const el of document.querySelectorAll('.kpi[data-quick]')) {
el.onclick = () => { quickFilter = quickFilter === el.dataset.quick ? 'all' : el.dataset.quick; render() }
}
}
function renderQuickFilters() {
const base = projects.filter(matchesSearch)
document.getElementById('chipfilters').innerHTML = QUICK.map((q) => {
const n = base.filter(q.test).length
if (q.key !== 'all' && n === 0 && quickFilter !== q.key) return ''
return `${ic(q.icon, 'sm')}${q.label} ${n} `
}).join('')
for (const b of document.querySelectorAll('.fchip')) b.onclick = () => { quickFilter = b.dataset.q; render() }
}
function render() {
document.getElementById('count').textContent = !rootDir ? 'Noch kein Projektordner gewählt'
: rootPaths.length > 1 ? `${projects.length} Projekte aus ${rootPaths.length} Ordnern` : `${projects.length} Ordner unter ${rootDir}`
renderKpis()
renderQuickFilters()
updateToolbarForView()
renderBoard()
renderGallery()
renderList()
renderTasks()
}
// Status filter makes no sense on the board (columns = status), sorting none on tasks.
function updateToolbarForView() {
document.getElementById('selStatusWrap').style.display = activeView === 'board' ? 'none' : ''
document.getElementById('selSortWrap').style.display = activeView === 'tasks' ? 'none' : ''
document.getElementById('boardMode').style.display = activeView === 'board' ? '' : 'none'
}
/* ── scan ─────────────────────────────────────────────────────────────── */
function pollScan() {
clearTimeout(scanTimer)
scanTimer = setTimeout(async () => {
try { scanState = await (await fetch('/api/scan')).json() } catch { return }
renderKpis()
if (scanState.running) pollScan()
else {
await load()
if (editing) loadDetails(editing.name)
toast('Scan fertig', 'circle-check')
}
}, 1500)
}
async function startScan(name) {
try {
const r = await postJson('/api/scan', name ? { name } : {})
scanState = r.state
renderKpis()
pollScan()
} catch (e) { toast(e.message, 'triangle-alert') }
}
/* ── quick start ▶ ────────────────────────────────────────────────────── */
// p.quickStart comes from the server: own start command, main exe or first start action
function quickStartTitle(p) {
const q = p.quickStart
return q ? `Starten: ${q.label}${q.detail ? ` (${q.detail})` : ''}` : ''
}
function qsButton(p) {
if (!p.quickStart) return ''
return `${ic('play')} `
}
// Card/row corner: [VS Code] [▶]. placeholder keeps rows aligned when a project has no ▶.
// explorer: also an [Explorer] button in front (gallery tiles).
function qsGroup(p, placeholder = false, explorer = false) {
const ex = explorer ? `${ic('folder-open')} ` : ''
const vs = `${ic('code-xml')} `
return `${ex}${vs}${qsButton(p) || (placeholder ? ' ' : '')} `
}
function wireQuickStart(el, p) {
const wire = (b, fn) => {
b.onclick = (e) => { e.stopPropagation(); fn() }
b.draggable = false
b.addEventListener('mousedown', (e) => e.stopPropagation())
}
for (const b of el.querySelectorAll('[data-qs]')) wire(b, () => runAction(p.name, p.quickStart.id))
for (const b of el.querySelectorAll('[data-vs]')) wire(b, () => runAction(p.name, 'vscode'))
for (const b of el.querySelectorAll('[data-ex]')) wire(b, () => runAction(p.name, 'explorer'))
}
/* ── board ────────────────────────────────────────────────────────────── */
// 'cards' = full cards, 'rows' = one compact line per project (both draggable)
let boardMode = (() => { try { return localStorage.getItem('dash.boardMode') === 'rows' ? 'rows' : 'cards' } catch { return 'cards' } })()
function setBoardMode(mode) {
boardMode = mode === 'rows' ? 'rows' : 'cards'
for (const b of document.querySelectorAll('#boardMode button')) b.classList.toggle('active', b.dataset.mode === boardMode)
try { localStorage.setItem('dash.boardMode', boardMode) } catch {}
renderBoard()
}
// compact two-line row: [prio] [icon] name / size · last change · git · backup · tasks [▶]
function rowHtml(p) {
const c = cloudInfo(p)
const open = (p.tasks ?? []).filter((t) => !t.done).length
const prioTitle = `Priorität ${PRIO_LABEL[p.priority]}`
return `
${avatar(p)}
${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)}
`
}
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)}
${escapeHtml(p.name)}
${rootTag(p, true)}${prioHtml(p.priority)}
${qsGroup(p)}
${p.lastCommit ? `${ic('git-commit-horizontal', 'sm')}${escapeHtml(p.lastCommit.message)}
` : ''}
${factsHtml(p)}
${gitHtml(p.git)}${cloudChip(p)}${pubChip(p)}
${techChips(p.tech?.types)}${warnChips(p)}${tags}
${p.notes ? `${escapeHtml(p.notes)}
` : ''}
${total ? `${ic('list-checks', 'sm')}
${done}/${total} ` : ''}`
}
function renderBoard() {
const board = document.getElementById('board')
board.innerHTML = ''
const visible = visibleProjects({ useStatus: false })
for (const col of STATUS) {
const items = visible
.filter((p) => p.status === col.key)
.sort((a, b) => (PRIO_ORDER[a.priority] - PRIO_ORDER[b.priority]) || (new Date(lastActivity(b)) - new Date(lastActivity(a))))
const colEl = document.createElement('div')
colEl.className = 'column'
colEl.innerHTML = ` ${ic(col.icon, 'sm')}${col.label}${items.length} `
colEl.addEventListener('dragover', (e) => { e.preventDefault(); colEl.classList.add('drag-over') })
colEl.addEventListener('dragleave', () => colEl.classList.remove('drag-over'))
colEl.addEventListener('drop', async (e) => {
e.preventDefault()
colEl.classList.remove('drag-over')
const name = e.dataTransfer.getData('text/plain')
const project = projects.find((p) => p.name === name)
if (!project || project.status === col.key) return
if (await patchProject(name, { status: col.key })) { toast(`${name} → ${col.label}`, col.icon); load() }
})
// cards live in their own scroll area, so the page never grows
const cardsEl = document.createElement('div')
cardsEl.className = 'cards'
colEl.appendChild(cardsEl)
if (!items.length) cardsEl.innerHTML = `${ic('inbox')}
`
for (const p of items) {
const card = document.createElement('div')
card.className = boardMode === 'rows' ? 'card row' : 'card'
card.draggable = true
card.innerHTML = boardMode === 'rows' ? rowHtml(p) : cardHtml(p)
card.addEventListener('dragstart', (e) => { e.dataTransfer.setData('text/plain', p.name); card.classList.add('dragging') })
card.addEventListener('dragend', () => card.classList.remove('dragging'))
card.onclick = () => openEditor(p)
wireQuickStart(card, p)
cardsEl.appendChild(card)
}
board.appendChild(colEl)
}
}
/* ── gallery ──────────────────────────────────────────────────────────── */
function renderGallery() {
const grid = document.getElementById('galleryGrid')
const items = sortProjects(visibleProjects())
if (!items.length) { grid.innerHTML = `${ic('search-x', 'xl')}
Keine Projekte gefunden.
`; return }
grid.innerHTML = ''
for (const p of items) {
const tile = document.createElement('div')
tile.className = 'tile'
tile.title = p.name
tile.innerHTML = `
${escapeHtml(initialsOf(p.name))}
${statusHtml(p.status)}
${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)
tile.onclick = () => openEditor(p)
grid.appendChild(tile)
}
}
/* ── list ─────────────────────────────────────────────────────────────── */
// cls: used by CSS container queries to hide columns in narrow windows
const LIST_COLS = [
{ label: 'Projekt', sort: 'name' }, { label: 'Status', cls: 'c-status' }, { label: 'Git' }, { label: 'Backup' }, { label: 'Technik', cls: 'c-tech' },
{ label: 'Größe', sort: 'size', num: true }, { label: 'Aufräumbar', sort: 'clean', num: true, cls: 'c-clean' },
{ label: 'Aktivität', sort: 'mtime', cls: 'c-act' }, { label: '' },
]
function renderList() {
const table = document.getElementById('listTable')
const items = sortProjects(visibleProjects())
const sort = document.getElementById('fltSort').value
table.innerHTML = `${LIST_COLS.map((c) => `${c.label}${c.sort === sort ? ' ' + ic('arrow-down', 'sm') : ''} `).join('')}
${items.map((p) => `
${avatar(p)}${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 ? `${ic('play')} ` : '' + ic('play') + ' '}
${ic('folder-open')}
${ic('code-xml')}
${ic('chevron-right')}
`).join('') || `Keine Projekte gefunden. `} `
for (const th of table.querySelectorAll('th[data-sort]')) {
th.onclick = () => { document.getElementById('fltSort').value = th.dataset.sort; render() }
}
for (const tr of table.querySelectorAll('tbody tr[data-name]')) {
const p = projects.find((x) => x.name === tr.dataset.name)
tr.onclick = () => openEditor(p)
wireQuickStart(tr, p)
for (const b of tr.querySelectorAll('button[data-a]')) {
b.onclick = (e) => {
e.stopPropagation()
if (b.dataset.a === 'details') openEditor(p)
else runAction(p.name, b.dataset.a)
}
}
}
}
function setView(view) {
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)
updateToolbarForView()
try { localStorage.setItem('dash.view', view) } catch {}
}
/* ── tasks view (all projects) ────────────────────────────────────────── */
let taskMode = 'open' // open | done | all
const STATUS_ORDER = { active: 0, paused: 1, idea: 2, done: 3, archived: 4 }
const newTaskId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6)
// Saves a project's full task list; the UI updates first, a failure reloads.
async function saveTasks(p, tasks) {
p.tasks = tasks
renderTasks()
updateTaskCount()
if (!(await patchProject(p.name, { tasks }))) { toast('Speichern fehlgeschlagen', 'triangle-alert'); load() }
}
function updateTaskCount() {
const open = projects.reduce((n, p) => n + (p.tasks ?? []).filter((t) => !t.done).length, 0)
document.getElementById('taskCount').textContent = open || ''
}
function renderTasks() {
updateTaskCount()
const term = searchTerm.trim().toLowerCase()
const q = QUICK.find((x) => x.key === quickFilter) ?? QUICK[0]
const status = document.getElementById('fltStatus').value
// project picker for "add": active projects first
const sel = document.getElementById('taskProject')
const prev = sel.value || editing?.name
const ordered = [...projects].sort((a, b) => (STATUS_ORDER[a.status] - STATUS_ORDER[b.status]) || a.name.localeCompare(b.name, 'de'))
sel.innerHTML = ordered.map((p) => `${escapeHtml(p.name)} `).join('')
if (prev && projects.some((p) => p.name === prev)) sel.value = prev
const groups = []
for (const p of ordered) {
if (!q.test(p) || (status !== 'all' && p.status !== status)) continue
const projectHit = !term || p.name.toLowerCase().includes(term) || (p.tags ?? []).some((t) => t.toLowerCase().includes(term))
const tasks = (p.tasks ?? []).filter((t) =>
(taskMode === 'all' || (taskMode === 'open' ? !t.done : t.done)) &&
(projectHit || t.text.toLowerCase().includes(term)))
if (tasks.length) groups.push({ p, tasks })
}
const el = document.getElementById('taskGroups')
el.classList.toggle('isEmpty', !groups.length)
if (!groups.length) {
el.innerHTML = `${ic(taskMode === 'done' ? 'inbox' : 'party-popper', 'xl')}
${taskMode === 'open' ? 'Keine offenen Aufgaben.' : 'Keine Aufgaben gefunden.'}
Oben ein Projekt wählen und eine Aufgabe eintragen.
`
return
}
el.innerHTML = groups.map(({ p, tasks }) => {
const all = p.tasks ?? []
const done = all.filter((t) => t.done).length
return ``
}).join('')
for (const g of el.querySelectorAll('.tgroup')) {
const p = projects.find((x) => x.name === g.dataset.name)
g.querySelector('.tg-head').onclick = () => openEditor(p)
for (const row of g.querySelectorAll('.titem')) {
const id = row.dataset.id
row.querySelector('input').onchange = (e) =>
saveTasks(p, (p.tasks ?? []).map((t) => (t.id === id ? { ...t, done: e.target.checked } : t)))
row.querySelector('.del').onclick = () => saveTasks(p, (p.tasks ?? []).filter((t) => t.id !== id))
}
const input = g.querySelector('.tg-add input')
input.onkeydown = (e) => {
if (e.key !== 'Enter' || !input.value.trim()) return
const text = input.value.trim()
saveTasks(p, [...(p.tasks ?? []), { id: newTaskId(), text, done: false }]).then(() => {
const again = document.querySelector(`.tgroup[data-name="${CSS.escape(p.name)}"] .tg-add input`)
again?.focus()
})
}
}
}
function addTaskTop() {
const input = document.getElementById('taskNew')
const text = input.value.trim()
const p = projects.find((x) => x.name === document.getElementById('taskProject').value)
if (!text || !p) return
input.value = ''
if (taskMode === 'done') setTaskMode('open')
saveTasks(p, [...(p.tasks ?? []), { id: newTaskId(), text, done: false }])
toast(`Aufgabe zu ${p.name} hinzugefügt`, 'list-checks')
input.focus()
}
function setTaskMode(mode) {
taskMode = mode
for (const b of document.querySelectorAll('#taskMode button')) b.classList.toggle('active', b.dataset.mode === mode)
renderTasks()
}
/* ── side panel ───────────────────────────────────────────────────────── */
function setSection(sec) {
for (const el of document.querySelectorAll('.psec')) el.classList.toggle('active', el.id === `sec-${sec}`)
for (const btn of document.querySelectorAll('#ptabs button')) btn.classList.toggle('active', btn.dataset.sec === sec)
}
function renderTaskList() {
const ul = document.getElementById('taskList')
ul.innerHTML = ''
for (const t of editingTasks) {
const li = document.createElement('li')
li.className = t.done ? 'done' : ''
const cb = document.createElement('input')
cb.type = 'checkbox'
cb.checked = t.done
cb.onchange = () => { t.done = cb.checked; renderTaskList() }
const span = document.createElement('span')
span.textContent = t.text
const del = document.createElement('button')
del.className = 'btn ghost'
del.innerHTML = ic('trash', 'sm')
del.onclick = () => { editingTasks = editingTasks.filter((x) => x !== t); renderTaskList() }
li.append(cb, span, del)
ul.appendChild(li)
}
}
function addTaskFromInput() {
const input = document.getElementById('taskInput')
const text = input.value.trim()
if (!text) return
editingTasks.push({ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text, done: false })
input.value = ''
renderTaskList()
input.focus()
}
// cleanup paths are "\rest" (relative to the projects folder) → "rest"
const inProject = (p) => p.slice(p.indexOf('\\') + 1)
function section(icon, title, body) {
return `
${ic(icon)}${title} ${body}`
}
function renderInfo(name, d) {
const g = d.git
const key = d.sshKey
const keyHint = key
? `${ic('key-round', 'sm')} SSH-Schlüssel: ${escapeHtml(key.file)} ${ic('copy', 'sm')}kopieren
`
: `${ic('key-round', 'sm')} Kein SSH-Schlüssel gefunden. Anlegen mit ssh-keygen -t ed25519, dann den Inhalt von .ssh\\id_ed25519.pub bei GitHub/GitLab eintragen.
`
const pushBox = !g.remote ? '' : g.dirty
? `
${ic('cloud-upload')}Commit & Push
${ic('upload')}Push
`
: `${ic('cloud-upload')}git push${g.ahead ? ` (${g.ahead})` : ''}
`
const gitBody = g.isRepo
? `
Status
${gitHtml(g)}
Branch
${ic('git-branch', 'sm')} ${escapeHtml(g.branch)}${g.upstream ? ` → ${escapeHtml(g.upstream)}` : ''}
Letzter Commit
${g.lastCommit ? `${g.lastCommit.date} · ${escapeHtml(g.lastCommit.message)}` : '–'}
${ic('link', 'sm')}Remote (origin) – SSH oder https
${ic('save')}Speichern
${g.remote ? '' : 'Noch kein Remote – das Projekt liegt nur auf dieser Platte.
'}
${pushBox}
${keyHint}
Push läuft in einem eigenen Konsolenfenster (dort erscheinen SSH-Passphrase und Fehler).
`
: `${gitHtml(g)}
Kein Git-Repository – Änderungen sind nirgends gesichert.
${ic('git-branch')}Git einrichten
`
const gens = d.tools.generators
const genBody = gens.length
? `${gens.map((x) => `
${escapeHtml(x.rel)}
${x.kind === 'comfygen'
? `
${ic('wand-sparkles', 'sm')}nutzt _Tools\\ComfyGen `
: `
${ic('copy', 'sm')}eigene Kopie ${escapeHtml(x.scripts.join(', '))}
`}
`).join('')}
`
: 'Kein Generator-Ordner.
'
const genDir = gens.find((x) => x.kind === 'comfygen')
const iconBody = d.icon
? `${escapeHtml(d.icon)}
`
: `${ic('image-off', 'sm')}kein Icon gefunden
${genDir ? 'Mit ComfyGen erzeugen (Prompt „icon“ in prompts.py eintragen):' : 'Generator-Vorlage aus _Tools\\ComfyGen\\template kopieren, dann:'}
cd "${escapeHtml(d.path)}\\${escapeHtml(genDir ? genDir.rel : 'sprite-generator')}" && gen generate icon && gen adopt icon`
const s = d.storage
let storageBody
if (!s) storageBody = 'Noch nicht gescannt.
'
else {
const rows = s.candidates.filter((c) => c.MB >= 1 || c.Skip)
storageBody = `Größe
${fmtMB(s.sizeMB)} · gescannt ${timeAgo(s.at)}
Löschbar
Cache ${fmtMB(s.deletable.Cache)} · Builds ${fmtMB(s.deletable.Release)} · Rohbilder ${fmtMB(s.deletable.Output)}
`
storageBody += rows.length
? `
${ic('trash')}Ausgewählte löschen
Cache ist vorausgewählt (immer neu erzeugbar). Fertige Builds und Rohbilder nur bewusst anhaken.
`
: `${ic('sparkles', 'sm')} Nichts zum Aufräumen.
`
}
storageBody += `${ic('scan-search')}${s ? 'Neu scannen' : 'Scannen'}
`
document.getElementById('sec-info').innerHTML =
section('cloud', 'Git & Backup', gitBody) +
section('cpu', 'Technik', `${techChips(d.tech.types) || 'nicht erkannt '}${d.tech.needsInstall ? `${ic('download', 'sm')}npm install nötig ` : ''}
`) +
section('hard-drive', 'Speicher', storageBody) +
section('wand-sparkles', 'Generator', genBody) +
section('image', 'App-Icon', iconBody)
document.getElementById('btnScanOne').onclick = () => startScan(name)
const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn }
const refreshInfo = () => { load(); loadDetails(name) }
on('btnPush', async () => {
try { await postJson(api(name, 'push')); toast('Push läuft in eigener Konsole', 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') }
})
on('btnCommitPush', async () => {
const msg = document.getElementById('gMsg').value.trim()
if (!msg) { document.getElementById('gMsg').focus(); return toast('Bitte eine Commit-Nachricht eingeben', 'info') }
try { await postJson(api(name, 'push'), { message: msg }); toast('Commit & Push läuft in eigener Konsole', 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') }
})
on('btnRemote', async () => {
try { await postJson(api(name, 'remote'), { url: document.getElementById('gRemote').value }); toast('Remote gespeichert', 'link'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') }
})
const rem = document.getElementById('gRemote')
if (rem) rem.onkeydown = (e) => { if (e.key === 'Enter') document.getElementById('btnRemote').click() }
on('btnGitInit', async () => {
try { await postJson(api(name, 'git-init')); toast('Git eingerichtet (Branch main)', 'git-branch'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') }
})
on('btnCopyKey', async () => {
try { await navigator.clipboard.writeText(d.sshKey.key); toast('SSH-Schlüssel kopiert', 'copy') } catch { toast('Kopieren nicht möglich', 'triangle-alert') }
})
const clean = document.getElementById('btnClean')
if (clean) clean.onclick = async () => {
const paths = [...document.querySelectorAll('.candcb:checked')].map((cb) => cb.dataset.path)
if (!paths.length) return toast('Nichts ausgewählt')
const mb = s.candidates.filter((c) => paths.includes(c.Path)).reduce((a, c) => a + c.MB, 0)
if (!confirm(`${paths.length} Ordner (${fmtMB(mb)}) in „${name}“ endgültig löschen?\n\n${paths.map(inProject).join('\n')}`)) return
clean.disabled = true
clean.innerHTML = `${ic('loader')}Lösche…`
try {
const r = await postJson(api(name, 'clean'), { paths })
toast(`${r.deleted.length} gelöscht, ${String(r.freedGB).replace('.', ',')} GB frei${r.failed.length ? ` · ${r.failed.length} gesperrt (Programm offen?)` : ''}`, 'brush-cleaning')
await load()
loadDetails(name)
} catch (e) { toast(e.message, 'triangle-alert'); clean.disabled = false; clean.innerHTML = `${ic('trash')}Ausgewählte löschen` }
}
}
function renderActions(name, d) {
const groups = {}
for (const a of d.actions) (groups[a.group] ??= []).push(a)
const order = ['Einrichten', 'Starten', 'Bauen', 'Werkzeuge', 'Öffnen']
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 `
${ic(a.id.startsWith('html:') || /\.html?$/i.test(a.rel ?? '') ? 'globe' : 'play', 'lg')}
${escapeHtml(a.label)} ${escapeHtml(a.detail ?? '')}
${a.rel ? `${ic('pin', 'sm')} ` : ''}
`
}).join('')}
`
: `Keine fertige exe oder HTML-Seite im Projekt gefunden.${hasBuild ? ' Unter „Bauen“ erzeugen, dann hier starten.' : ''}
`)
+ (prog?.missing ? `${ic('triangle-alert', 'sm')} Festgelegte Datei fehlt: ${escapeHtml(prog.rel)} – neu wählen oder zurücksetzen.
` : '')
+ ``
projectLastBackup = d.lastBackup ?? null
projectTargets = d.backupTargets ?? []
document.getElementById('sec-actions').innerHTML = section('app-window', 'Programm starten', progHtml)
+ (name === '_Tools' ? '' : section('hard-drive-upload', 'Sichern', '
'))
+ order.filter((g) => groups[g]).map((g) =>
section(ACTION_ICON[g], g, `${groups[g].map((a) =>
`${ic(ACT_ICON(a))}${escapeHtml(a.label)} `).join('')}
`)).join('')
+ `${ic('shield-check', 'sm')} Programme starten direkt, Befehle und .bat laufen sichtbar in einem eigenen Konsolenfenster. Eigenen Start-Befehl unter „Bearbeiten“ festlegen.
`
for (const btn of document.querySelectorAll('#sec-actions .act')) btn.onclick = () => runAction(name, btn.dataset.id)
for (const btn of document.querySelectorAll('#sec-actions .pin')) btn.onclick = () => setProgram(name, btn.dataset.rel)
const input = document.getElementById('fProgram')
document.getElementById('btnSetProgram').onclick = () => setProgram(name, input.value)
input.onkeydown = (e) => { if (e.key === 'Enter') setProgram(name, input.value) }
document.getElementById('btnClearProgram')?.addEventListener('click', () => setProgram(name, ''))
document.getElementById('btnPickProgram')?.addEventListener('click', async () => {
const file = await pickFile(`Programm für ${name} wählen`, d.path)
if (file) setProgram(name, file)
})
renderProjectBackup(name)
if (!backup) loadBackup()
}
// Saves the program the ▶ starts ('' = choose automatically again).
async function setProgram(name, program) {
try {
const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ program }),
})
const r = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(r.error ?? 'Speichern fehlgeschlagen')
toast(r.program ? `▶ startet jetzt: ${r.program}` : '▶ wählt wieder automatisch', 'pin')
if (editing?.name === name) { editing.program = r.program; loadDetails(name) }
load()
} catch (e) { toast(e.message, 'triangle-alert') }
}
/* ── per-project backup ("Sichern" in Aktionen) ─────────────────────── */
let projectLastBackup = null
let projectTargets = [] // [{ id, name, last }] – this project on every backup target
function renderProjectBackup(name) {
const el = document.getElementById('pbackupBody')
if (!el || editing?.name !== name) return
const b = backup
const t = curTarget()
const busy = backupBusy()
// the job belongs to this project; while it runs it also decides the shown target
const mine = b && b.scope === name && (busy || b.target === t?.id)
const last = projectLastBackup
if (b?.notConfigured) {
el.innerHTML = `${ic('hard-drive-upload')}
Noch kein Backup-Ziel festgelegt (z. B. externe Platte oder NAS).
${ic('settings')}Backup-Ziel einrichten
`
document.getElementById('pbSetup').onclick = () => openSettings(false)
return
}
const shownT = busy && mine ? (b.targets.find((x) => x.id === b.target) ?? t) : t
let html = targetTabs(busy ? b.target : null) + `Zuletzt gesichert
${last
? `${new Date(last.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(last.at)}) · ${last.how} `
: 'noch nie '}
Ziel
${escapeHtml(shownT ? `${shownT.path}\\${name}` : '…')}
${projectTargets.length > 1 ? `
Alle Ziele
${projectTargets.map((x) => {
const lv = !x.last ? 'red' : (Date.now() - new Date(x.last.at)) / 86400000 > BACKUP_FRESH_DAYS ? 'yellow' : 'green'
return `${ic('hard-drive', 'sm')}${escapeHtml(x.name)} · ${x.last ? timeAgo(x.last.at) : 'nie'} `
}).join('')}
` : ''}
`
if (busy && mine && b.phase === 'checking') {
html += `${ic('loader')}
Prüfe, was im Backup fehlt…
`
} else if (busy && mine && b.phase === 'copying') {
const pr = b.progress
const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0
html += `Kopiere… ${pct} % ${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien
${escapeHtml(pr.current)}
`
} else if (busy) {
html += `${ic('hourglass')}
Es läuft gerade ein anderes Backup (${b.scope ? escapeHtml(b.scope) : 'alle Projekte'}). Danach geht es hier.
`
} else if (mine && b.phase === 'done') {
const l = shownT?.lastByProject?.[name]
html += l && l.files
? `${ic('circle-check')}
Gesichert. ${l.files.toLocaleString('de-DE')} Dateien (${fmtBytes(l.bytes)}) neu ins Backup kopiert.
`
: `${ic('circle-check')}
Alles aktuell. Im Backup fehlte nichts.
`
} else if (mine && b.phase === 'error') {
html += `${ic('triangle-alert')}
${escapeHtml(b.error)}
`
} else if (mine && b.phase === 'cancelled') {
html += `${ic('circle-x')}
Abgebrochen. Bereits kopierte Dateien bleiben im Backup.
`
}
html += `${busy && mine
? `${ic('circle-x')}Abbrechen `
: `${ic('hard-drive-upload')}Jetzt sichern `}
Prüft das Projekt im Backup und kopiert nur fehlende und geänderte Dateien. Gelöscht wird dort nichts.
`
el.innerHTML = html
const save = document.getElementById('pbSave')
if (save) save.onclick = async () => {
try {
backup = await postJson('/api/backup/check', { project: name, autoCopy: true, target: curTargetId() })
renderProjectBackup(name)
loadBackup()
} catch (e) { toast(e.message, 'triangle-alert') }
}
const cancel = document.getElementById('pbCancel')
if (cancel) cancel.onclick = () => backupAction('cancel')
}
async function loadDetails(name) {
try {
const res = await fetch(`${api(name, 'details')}?target=${encodeURIComponent(curTargetId())}`)
const d = await res.json()
if (!res.ok) throw new Error(d.error)
if (editing?.name !== name) return
renderInfo(name, d)
renderActions(name, d)
} catch (e) {
document.getElementById('sec-info').innerHTML = `Fehler: ${escapeHtml(e.message)}
`
}
}
function openEditor(p) {
closeBackup()
editing = p
editingTasks = (p.tasks ?? []).map((t) => ({ ...t }))
document.getElementById('pAvatar').innerHTML = avatar(p, 'lg')
document.getElementById('panelTitle').textContent = p.name
document.getElementById('panelSub').innerHTML = `${statusHtml(p.status)}${gitHtml(p.git, true)}${techChips(p.tech?.types)}${pubChip(p)}`
document.getElementById('fStatus').value = p.status
document.getElementById('fPriority').value = p.priority
document.getElementById('fTags').value = (p.tags ?? []).join(', ')
document.getElementById('fThumb').value = p.thumbnail ?? ''
document.getElementById('fStart').value = p.start ?? ''
document.getElementById('fItch').value = p.itch ?? ''
document.getElementById('fItchHint').innerHTML = p.itch === '-'
? `${ic('circle-off', 'sm')} als „nicht veröffentlicht“ markiert`
: p.published?.source === 'auto'
? `${ic('sparkles', 'sm')} automatisch erkannt: ${escapeHtml(p.published.title)} – ${escapeHtml(p.published.url)}`
: p.published ? '' : `${ic('info', 'sm')} nicht auf dem itch.io-Profil gefunden`
document.getElementById('fNotes').value = p.notes
renderTaskList()
const loading = `${ic('loader', 'sm')} Lädt…
`
document.getElementById('sec-info').innerHTML = loading
document.getElementById('sec-actions').innerHTML = loading
document.getElementById('overlay').classList.add('open')
document.getElementById('panel').classList.add('open')
document.getElementById('panel').setAttribute('aria-hidden', 'false')
loadDetails(p.name)
}
function closeEditor() {
editing = null
editingTasks = []
document.getElementById('overlay').classList.remove('open')
document.getElementById('panel').classList.remove('open')
document.getElementById('panel').setAttribute('aria-hidden', 'true')
}
async function saveEditor() {
if (!editing) return
const body = {
status: document.getElementById('fStatus').value,
priority: document.getElementById('fPriority').value,
notes: document.getElementById('fNotes').value,
tags: document.getElementById('fTags').value.split(',').map((s) => s.trim()).filter(Boolean),
thumbnail: document.getElementById('fThumb').value.trim(),
start: document.getElementById('fStart').value.trim(),
itch: document.getElementById('fItch').value.trim(),
tasks: editingTasks,
}
if (await patchProject(editing.name, body)) {
toast('Gespeichert', 'save')
closeEditor()
load()
} else toast(patchProject.error || 'Speichern fehlgeschlagen', 'triangle-alert')
}
/* ── backup (NAS) ─────────────────────────────────────────────────────── */
let backup = null
let backupTimer = null
const fmtBytes = (b) => (b ?? 0) < 1048576 ? `${Math.max(b ? 1 : 0, Math.round((b ?? 0) / 1024))} KB` : fmtMB(b / 1048576)
const backupBusy = () => backup && (backup.phase === 'checking' || backup.phase === 'copying')
// Selected backup target (several possible): cards, tiles and "Sichern" use this one.
let backupTargetId = ''
try { backupTargetId = localStorage.getItem('dash.backupTarget') ?? '' } catch {}
function curTarget() {
const list = backup?.targets ?? []
return list.find((t) => t.id === backupTargetId) ?? list[0] ?? null
}
const curTargetId = () => curTarget()?.id ?? backupTargetId
function selectTarget(id) {
if (id === curTargetId()) return
backupTargetId = id
try { localStorage.setItem('dash.backupTarget', id) } catch {}
renderBackupButton()
if (document.getElementById('bpanel').classList.contains('open')) renderBackup()
load()
if (editing) loadDetails(editing.name)
}
// reiter for the targets; disabled while a backup runs on another one
function targetTabs(busyId) {
const list = backup?.targets ?? []
if (list.length < 2) return ''
const cur = curTargetId()
return `${list.map((t) => `${ic('hard-drive', 'sm')}${escapeHtml(t.name)} `).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()
try { backup = await (await fetch('/api/backup')).json() } catch { return }
if (wasBusy && !backupBusy()) load() // refresh the backup badges on cards/tiles/list
renderBackupButton()
if (document.getElementById('bpanel').classList.contains('open')) renderBackup()
if (editing) {
const own = curTarget()?.lastByProject?.[editing.name]
if (own && (!projectLastBackup || own.at > projectLastBackup.at)) projectLastBackup = { ...own, how: 'Projekt' }
renderProjectBackup(editing.name)
}
clearTimeout(backupTimer)
if (backupBusy()) backupTimer = setTimeout(loadBackup, 1000)
}
function renderBackupButton() {
const sub = document.getElementById('backupSub')
if (!backup) return
const btn = document.getElementById('btnBackup')
btn.title = (backup.targets ?? []).map((t) => `${t.name}: ${t.last ? 'zuletzt ' + timeAgo(t.last.at) : 'noch nie komplett gesichert'}`).join('\n') || 'Backup-Ziel einrichten'
if (backup.notConfigured) { sub.textContent = '· einrichten'; sub.classList.add('warn'); return }
const t = curTarget()
const last = t?.last
const prefix = backup.targets.length > 1 ? `· ${t.name} ` : '· '
if (backup.phase === 'checking') sub.textContent = '· prüft…'
else if (backup.phase === 'copying') {
const pr = backup.progress
sub.textContent = `· ${pr.bytesTotal ? Math.round((pr.bytes / pr.bytesTotal) * 100) : 0} %`
} else if (last) sub.textContent = `${prefix}${timeAgo(last.at)}`
else sub.textContent = `${prefix}noch nie`
const old = last && (Date.now() - new Date(last.at)) > 7 * 86400000
sub.classList.toggle('warn', !last || old || last.ok === false)
}
async function backupAction(what) {
try {
backup = await postJson(`/api/backup/${what}`, what === 'check' ? { target: curTargetId() } : {})
renderBackup()
loadBackup()
} catch (e) { toast(e.message, 'triangle-alert') }
}
function renderBackup() {
let b = backup
if (!b) return
if (b.notConfigured) {
document.getElementById('bpTarget').textContent = 'kein Ziel festgelegt'
document.getElementById('bpBody').innerHTML = `${ic('hard-drive-upload')}
Noch kein Backup-Ziel festgelegt. Wähle einen Ordner auf einer externen Platte, einem NAS oder einem anderen Laufwerk.
${ic('settings')}Backup-Ziel einrichten
`
document.getElementById('bpSetup').onclick = () => openSettings(false)
return
}
// a running job shows its own target; otherwise the selected one (and its last result only if the job was for it)
const busy = backupBusy()
const jobT = b.targets.find((t) => t.id === b.target)
const t = busy && jobT ? jobT : curTarget()
const phase = busy || (jobT && jobT.id === t.id) ? b.phase : 'idle'
document.getElementById('bpTarget').innerHTML = `${ic('folder', 'sm')} ${escapeHtml(b.source)} ${ic('arrow-right', 'sm')} ${escapeHtml(t.path)}`
const tl = t.last
const last = tl
? `Letztes Backup
${new Date(tl.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(tl.at)})
Kopiert
${tl.files.toLocaleString('de-DE')} Dateien · ${fmtBytes(tl.bytes)}${tl.ok === false ? ' · unvollständig ' : ''}
`
: `Auf „${escapeHtml(t.name)}“ wurde über das Dashboard noch kein Komplett-Backup gemacht.
`
let body = targetTabs(busy ? b.target : null) + section('clock-3', `Status – ${escapeHtml(t.name)}`, last)
b = { ...b, phase }
if (b.scope && b.phase !== 'idle') {
body += `${ic('folder')}
Der aktuelle Lauf betrifft nur das Projekt ${escapeHtml(b.scope)} (gestartet über „Sichern“ im Projekt).
`
}
if (b.phase === 'checking') {
body += `${ic('loader')}
Prüfe, was neu ist und im Backup fehlt… Dauert über das Netzwerk etwa 1–2 Minuten.
${ic('circle-x')}Abbrechen
`
} else if (b.phase === 'copying') {
const pr = b.progress
const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0
body += section('hard-drive-upload', 'Kopiere…', `
${pct} % ${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien
${escapeHtml(pr.current)}
`)
+ `${ic('circle-x')}Abbrechen
Das Fenster bitte offen lassen, bis das Backup fertig ist.
`
} else if (b.phase === 'ready' && b.check) {
const c = b.check
if (!c.files) {
body += `${ic('circle-check')}
Alles aktuell. Im Backup fehlt nichts.
`
} else {
body += section('scan-search', `Ergebnis der Prüfung ${timeAgo(c.at)} `, `
${ic('file-plus', 'sm')}Neu
${c.newFiles.toLocaleString('de-DE')}
${fmtBytes(c.newBytes)}
${ic('file-pen', 'sm')}Geändert
${c.changedFiles.toLocaleString('de-DE')}
${fmtBytes(c.changedBytes)}
${ic('archive', 'sm')}Nur im Backup
${c.extraFiles.toLocaleString('de-DE')}
bleiben erhalten
${c.projects.slice(0, 15).map((p) => `${escapeHtml(p.name)} ${p.files.toLocaleString('de-DE')} Dateien ${fmtBytes(p.bytes)} `).join('')}
${c.projects.length > 15 ? `+ ${c.projects.length - 15} weitere Projekte
` : ''}`)
}
body += `
${ic('refresh-cw')}Neu prüfen
${c.files ? `${ic('hard-drive-upload')}Jetzt kopieren (${fmtBytes(c.bytes)}) ` : ''}
`
} else {
if (b.phase === 'done') body += `${ic('circle-check')}
Backup fertig. ${tl && !b.scope ? `${tl.files.toLocaleString('de-DE')} Dateien, ${fmtBytes(tl.bytes)} kopiert.` : ''}
`
if (b.phase === 'cancelled') body += `${ic('circle-x')}
Abgebrochen. Bereits kopierte Dateien bleiben im Backup.
`
if (b.phase === 'error') body += `${ic('triangle-alert')}
${escapeHtml(b.error)}
`
body += `${ic('scan-search')}Prüfen, was neu ist
`
}
body += `${ic('shield-check', 'sm')} Im Backup wird nie etwas gelöscht – nur neue und geänderte Dateien kommen dazu.
Nicht gesichert (wird neu erzeugt): ${escapeHtml((settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.gradle', '.venv']).join(', '))}.
Ziel und Ausnahmen: Einstellungen (Zahnrad oben).
`
document.getElementById('bpBody').innerHTML = body
const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn }
on('bpCheck', () => backupAction('check'))
on('bpCopy', () => backupAction('copy'))
on('bpCancel', () => backupAction('cancel'))
}
function openBackup() {
closeEditor()
document.getElementById('overlay').classList.add('open')
document.getElementById('bpanel').classList.add('open')
document.getElementById('bpanel').setAttribute('aria-hidden', 'false')
renderBackup()
loadBackup()
}
function closeBackup() {
document.getElementById('bpanel').classList.remove('open')
document.getElementById('bpanel').setAttribute('aria-hidden', 'true')
if (!editing) document.getElementById('overlay').classList.remove('open')
}
/* ── theme ────────────────────────────────────────────────────────────── */
// Theme mode: 'light', 'dark' or 'system' (follows Windows, also live when it changes).
const systemDark = matchMedia('(prefers-color-scheme: dark)')
let themeMode = 'system'
function applyTheme() {
const theme = themeMode === 'system' ? (systemDark.matches ? 'dark' : 'light') : themeMode
document.documentElement.dataset.theme = theme
for (const b of document.querySelectorAll('#themeSeg button')) b.classList.toggle('active', b.dataset.mode === themeMode)
}
function setThemeMode(mode) {
themeMode = ['light', 'dark', 'system'].includes(mode) ? mode : 'system'
applyTheme()
try { localStorage.setItem('dash.theme', themeMode) } catch {}
}
function initTheme() {
let saved = null
try { saved = localStorage.getItem('dash.theme') } catch {}
saved = new URLSearchParams(location.search).get('theme') ?? saved
themeMode = ['light', 'dark', 'system'].includes(saved) ? saved : 'system'
applyTheme()
}
systemDark.addEventListener('change', () => { if (themeMode === 'system') applyTheme() })
for (const b of document.querySelectorAll('#themeSeg button')) b.onclick = () => setThemeMode(b.dataset.mode)
/* ── wiring ───────────────────────────────────────────────────────────── */
document.getElementById('btnCancel').onclick = closeEditor
document.getElementById('btnClose').onclick = closeEditor
document.getElementById('btnSave').onclick = saveEditor
document.getElementById('btnAddTask').onclick = addTaskFromInput
document.getElementById('taskInput').addEventListener('keydown', (e) => { if (e.key === 'Enter') addTaskFromInput() })
document.getElementById('btnOpenFolder').onclick = () => { if (editing) runAction(editing.name, 'explorer') }
document.getElementById('btnVsCode').onclick = () => { if (editing) runAction(editing.name, 'vscode') }
document.getElementById('overlay').onclick = () => { closeEditor(); closeBackup(); closeSettings() }
document.getElementById('btnBackup').onclick = () => (backup?.notConfigured ? openSettings(false) : openBackup())
for (const b of document.querySelectorAll('#taskMode button')) b.onclick = () => setTaskMode(b.dataset.mode)
for (const b of document.querySelectorAll('#boardMode button')) { b.onclick = () => setBoardMode(b.dataset.mode); b.classList.toggle('active', b.dataset.mode === boardMode) }
document.getElementById('taskNewBtn').onclick = addTaskTop
document.getElementById('taskNew').addEventListener('keydown', (e) => { if (e.key === 'Enter') addTaskTop() })
document.getElementById('btnCloseBackup').onclick = closeBackup
document.getElementById('search').addEventListener('input', (e) => { searchTerm = e.target.value; render() })
for (const btn of document.querySelectorAll('#tabs button')) btn.onclick = () => { setView(btn.dataset.view); render() }
for (const btn of document.querySelectorAll('#ptabs button')) btn.onclick = () => setSection(btn.dataset.sec)
document.getElementById('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 = ['board', 'gallery', 'list', 'tasks']
initTheme()
if (VIEWS.includes(hashView)) setView(hashView)
else try { const v = localStorage.getItem('dash.view'); if (VIEWS.includes(v)) setView(v) } catch {}
function openFromHash(project, sec) {
const p = project && projects.find((x) => x.name === project)
if (p) { openEditor(p); if (sec) setSection(sec) }
}
load().then(() => { openFromHash(hashProject, hashSec); if (hashView === 'backup') openBackup() })
loadBackup()
window.addEventListener('hashchange', () => {
const [v, project, sec] = decodeURIComponent(location.hash.slice(1)).split('/')
if (VIEWS.includes(v)) { setView(v); render() }
openFromHash(project, sec)
})