1713 lines
95 KiB
JavaScript
1713 lines
95 KiB
JavaScript
/* 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 = '') => `<svg class="i ${cls}"><use href="/icons.svg#${name}"/></svg>`
|
||
// ?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 `<div class="avatar ${cls}" style="--c:${nameColor(p.name)}">${escapeHtml(initialsOf(p.name))}<img loading="lazy" src="${thumbUrl(p.name)}" alt="" onerror="this.remove()"></div>`
|
||
}
|
||
|
||
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 `<div class="facts">
|
||
<span title="${escapeHtml(sizeTitle(p))}">${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'}</span>
|
||
<span title="${escapeHtml(changeTitle(p))}">${ic('file-pen', 'sm')}${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}</span>
|
||
</div>`
|
||
}
|
||
|
||
function gitHtml(git, short = false) {
|
||
const label = short ? ({ green: 'Gesichert', yellow: 'Ungesichert', red: 'Kein Remote' })[git.level] : git.label
|
||
return `<span class="git ${git.level}" title="${escapeHtml(git.label)}">${ic(GIT_ICON[git.level], 'sm')}<span class="gl">${escapeHtml(label)}</span></span>`
|
||
}
|
||
|
||
// 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 `<span class="${cls} ${c.level}" title="${escapeHtml(c.label)}">${ic('hard-drive')}</span>`
|
||
}
|
||
function cloudChip(p) {
|
||
const c = cloudInfo(p)
|
||
return `<span class="bk ${c.level}" title="${escapeHtml(c.label)}">${ic('hard-drive', 'sm')}${escapeHtml(c.short)}</span>`
|
||
}
|
||
|
||
// 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 `<a class="chip pub" href="${escapeHtml(p.published.url)}" target="_blank" draggable="false" onclick="event.stopPropagation()" title="${escapeHtml(pubTitle(p))}">${ic('rocket', 'sm')}${short ? '' : 'itch.io'}</a>`
|
||
}
|
||
function pubBadge(p) {
|
||
if (!p.published) return ''
|
||
return `<a class="tbadge pub" href="${escapeHtml(p.published.url)}" target="_blank" draggable="false" onclick="event.stopPropagation()" title="${escapeHtml(pubTitle(p))}">${ic('rocket')}</a>`
|
||
}
|
||
|
||
function statusHtml(key) {
|
||
const s = STATUS_BY[key] ?? STATUS[0]
|
||
return `<span class="st ${s.key}">${ic(s.icon, 'sm')}${s.label}</span>`
|
||
}
|
||
|
||
function prioHtml(prio) {
|
||
const icon = prio === 'high' ? 'flame' : prio === 'low' ? 'chevron-down' : 'equal'
|
||
return `<span class="prio ${prio}" title="Priorität ${PRIO_LABEL[prio]}">${ic(icon, 'sm')}${PRIO_LABEL[prio]}</span>`
|
||
}
|
||
|
||
// 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 `<span class="rtag" title="Projektordner: ${escapeHtml(p.rootName)}${path ? ` (${escapeHtml(path)})` : ''}">${ic('folder', 'sm')}${short ? '' : ' '}${escapeHtml(p.rootName)}</span>`
|
||
}
|
||
|
||
function techChips(types) {
|
||
return (types ?? []).map((t) => `<span class="chip tech">${ic(TECH_ICON[t] ?? 'code', 'sm')}${escapeHtml(t)}</span>`).join('')
|
||
}
|
||
|
||
function warnChips(p) {
|
||
const b = []
|
||
if (deletableMB(p) >= 100) b.push(`<span class="chip warn" title="Cache ${fmtMB(p.storage.deletable.Cache)} · Builds ${fmtMB(p.storage.deletable.Release)} · Rohbilder ${fmtMB(p.storage.deletable.Output)}">${ic('brush-cleaning', 'sm')}${fmtMB(deletableMB(p))}</span>`)
|
||
if (p.tech?.needsInstall) b.push(`<span class="chip warn">${ic('download', 'sm')}npm install</span>`)
|
||
if (p.tools?.generators?.some((g) => g.kind === 'copy')) b.push(`<span class="chip bad">${ic('copy', 'sm')}Generator-Kopie</span>`)
|
||
else if (p.tools?.generators?.length) b.push(`<span class="chip ok">${ic('wand-sparkles', 'sm')}ComfyGen</span>`)
|
||
if (!p.hasIcon) b.push(`<span class="chip neutral">${ic('image-off', 'sm')}kein Icon</span>`)
|
||
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 = `<option value="">Leeres Projekt</option>` +
|
||
[...projects].sort((a, b) => a.name.localeCompare(b.name, 'de')).map((p) => `<option value="${escapeHtml(p.name)}">Klon von: ${escapeHtml(p.name)}</option>`).join('')
|
||
sel.value = from
|
||
document.getElementById('nRoot').innerHTML = roots.map((r) => `<option value="${escapeHtml(r.id)}">${escapeHtml(r.name)} – ${escapeHtml(r.path)}</option>`).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')}<div>${escapeHtml(ex.message)}</div>`
|
||
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 `<div class="rmrow">
|
||
<button type="button" class="rmbox" data-root-toggle="${escapeHtml(r.id)}" role="checkbox" aria-checked="${on}" title="${on ? 'Aus der Ansicht nehmen' : 'Zur Ansicht dazunehmen'}">${ic(on ? 'square-check' : 'square', 'sm')}</button>
|
||
<button type="button" role="option" data-root="${escapeHtml(r.id)}" aria-selected="${on}" title="Nur diesen Ordner anzeigen">
|
||
<span style="min-width:0"><span class="rn">${escapeHtml(r.name)}</span><span class="rp">${escapeHtml(r.path)}</span></span>
|
||
</button></div>`
|
||
}).join('') +
|
||
(roots.length > 1 ? `<button type="button" data-root-all><span class="chk">${ic('layers', 'sm')}</span>Alle Ordner anzeigen</button>` : '') +
|
||
`${roots.length ? '<div class="sep"></div>' : ''}` +
|
||
(hasPicker ? `<button type="button" data-root-add><span class="chk">${ic('folder-plus', 'sm')}</span>Ordner hinzufügen…</button>` : '') +
|
||
`<button type="button" data-root-import><span class="chk">${ic('folders', 'sm')}</span>Mehrere Ordner einlesen…</button>
|
||
<button type="button" data-root-manage><span class="chk">${ic('settings', 'sm')}</span>Projektordner verwalten…</button>`
|
||
}
|
||
|
||
// 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')}<div>${escapeHtml(e.message)}</div>`
|
||
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 <code>${escapeHtml(s.dataDir)}</code>` : ''
|
||
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) => `<a href="${escapeHtml(g.url)}" target="_blank">${escapeHtml(g.title)}</a>`).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')}<div>${escapeHtml(e.message)}</div>`
|
||
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 `<div class="rrow${active ? ' active' : ''}" data-id="${escapeHtml(r.id)}">
|
||
<input type="text" class="tname" placeholder="Name" value="${escapeHtml(r.name)}" title="${active ? 'Gerade aktiv' : ''}">
|
||
<input type="text" class="tpath" placeholder="z. B. D:\\Projekte" value="${escapeHtml(r.path)}">
|
||
<button class="btn pickbtn" type="button" data-title="Ordner mit Projekten wählen">${ic('folder-search')}Durchsuchen…</button>
|
||
<button class="btn ghost" type="button" data-rup title="Nach oben (der erste Ordner wird direkt ins Backup-Ziel gesichert)">${ic('arrow-up')}</button>
|
||
<button class="btn ghost" type="button" data-rrm title="Aus der Liste entfernen (auf der Platte wird nichts gelöscht)">${ic('x')}</button>
|
||
</div>`
|
||
}
|
||
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 = `<div class="hint">${ic('loader', 'sm')} wird gelesen…</div>`
|
||
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) => `<label class="${known(f.path) ? 'dis' : ''}"><input type="checkbox" data-path="${escapeHtml(f.path)}" ${self ? 'data-self' : ''} ${known(f.path) ? 'disabled checked' : ''}>
|
||
${ic('folder', 'sm')}<span>${label}</span><span class="n">${known(f.path) ? 'schon in der Liste' : extra}</span></label>`
|
||
body.innerHTML = `<div class="implist">
|
||
${item({ path: r.path }, `<i>Diesen Ordner selbst</i> (${escapeHtml(folderName(r.path))})`, `${r.folders.length} Projekte`, true)}
|
||
${r.folders.map((f) => item(f, escapeHtml(f.name), `${f.count} Unterordner`)).join('') || '<div class="hint">Keine Unterordner.</div>'}
|
||
</div>
|
||
<div class="rowbtns">
|
||
<button class="btn" type="button" data-imp-all>${ic('list-checks')}Alle Unterordner</button>
|
||
<button class="btn primary" type="button" data-imp-add>${ic('plus')}Ausgewählte hinzufügen</button>
|
||
</div>`
|
||
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 = `<div class="msg err">${ic('triangle-alert')}<div>${escapeHtml(e.message)}</div></div>`
|
||
}
|
||
}
|
||
|
||
// 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 `<div class="trow" data-id="${escapeHtml(t.id)}">
|
||
<input type="text" class="tname" placeholder="Name, z. B. USB" value="${escapeHtml(t.name)}">
|
||
<input type="text" class="tpath" placeholder="z. B. E:\\Backup\\Projekte oder \\\\NAS\\Freigabe\\Projekte" value="${escapeHtml(t.path)}">
|
||
<button class="btn pickbtn" type="button" data-title="Ordner für das Backup wählen">${ic('folder-search')}Durchsuchen…</button>
|
||
<button class="btn ghost" type="button" data-trm title="Ziel entfernen (im Backup selbst wird nichts gelöscht)">${ic('x')}</button>
|
||
</div>`
|
||
}
|
||
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)}<span>${escapeHtml(text)}</span>`
|
||
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 = `
|
||
<div class="kpi c-accent"><div class="ico">${ic('layers', 'lg')}</div><div><div class="val">${projects.length}</div><div class="lbl">Projekte · ${active} aktiv</div></div></div>
|
||
<div class="kpi c-red click" data-quick="nobackup" title="Projekte ohne Git oder Remote anzeigen"><div class="ico">${ic('shield-alert', 'lg')}</div><div><div class="val">${t.noBackup}</div><div class="lbl">ohne Git-Remote</div></div></div>
|
||
<div class="kpi c-blue"><div class="ico">${ic('hard-drive', 'lg')}</div><div><div class="val">${t.scanned ? fmtMB(t.sizeMB) : '–'}</div><div class="lbl">${t.scanned ? `belegt (${t.scanned} gescannt)` : 'noch nicht gescannt'}</div></div></div>
|
||
<div class="kpi c-yellow click" data-quick="cleanable" title="Aufräumbare Projekte anzeigen"><div class="ico">${ic('brush-cleaning', 'lg')}</div><div><div class="val">${t.scanned ? fmtMB(t.allMB) : '–'}</div><div class="lbl">${t.scanned ? `aufräumbar · Cache ${fmtMB(t.cacheMB)}` : 'aufräumbar'}</div></div></div>
|
||
<div class="kpi scanbox">
|
||
<button class="btn primary" id="btnScanAll" ${!cleanupAvailable || running ? 'disabled' : ''}>${ic(running ? 'loader' : 'scan-search')}${running ? `Scan ${scanState.done}/${scanState.total}` : 'Alle scannen'}</button>
|
||
${running ? `<div class="progress"><div style="width:${pct}%"></div></div><div class="sub">${escapeHtml(scanState.current.join(', '))}</div>`
|
||
: scanState?.error ? `<div class="sub" style="color:var(--red)" title="${escapeHtml(scanState.error)}">${ic('triangle-alert', 'sm')} Scan-Fehler</div>`
|
||
: '<div class="sub">Größe & löschbare Ordner messen</div>'}
|
||
</div>`
|
||
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 `<button class="fchip ${quickFilter === q.key ? 'active' : ''}" data-q="${q.key}" title="${q.label}">${ic(q.icon, 'sm')}<span class="fl">${q.label}</span><span class="n">${n}</span></button>`
|
||
}).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 `<button class="qs ${p.quickStart.kind === 'cmd' ? 'cmd' : ''}" data-qs title="${escapeHtml(quickStartTitle(p))}">${ic('play')}</button>`
|
||
}
|
||
// 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 ? `<button class="qs vs" data-ex title="Ordner im Explorer öffnen">${ic('folder-open')}</button>` : ''
|
||
const vs = `<button class="qs vs" data-vs title="In VS Code öffnen">${ic('code-xml')}</button>`
|
||
return `<span class="qsg">${ex}${vs}${qsButton(p) || (placeholder ? '<span class="qs-ph"></span>' : '')}</span>`
|
||
}
|
||
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 `<div class="rhead">
|
||
<span class="prio-dot ${p.priority}" title="${prioTitle}"></span>
|
||
${avatar(p)}
|
||
<div class="rmain">
|
||
<span class="name" title="${escapeHtml(p.name)}">${escapeHtml(p.name)}</span>
|
||
<span class="rsub">
|
||
${rootTag(p, true)}
|
||
<span class="rsize" title="${escapeHtml(sizeTitle(p))}">${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'}</span>
|
||
<span class="rdate" title="${escapeHtml(changeTitle(p))}">${ic('file-pen', 'sm')}<span class="dl">${fmtDate(lastActivity(p))}</span><span class="ds">${fmtDate(lastActivity(p), false)}</span></span>
|
||
<span class="ri ${p.git.level}" title="Git: ${escapeHtml(p.git.label)}">${ic(GIT_ICON[p.git.level], 'sm')}</span>
|
||
<span class="ri ${c.level}" title="${escapeHtml(c.label)}">${ic('hard-drive', 'sm')}</span>
|
||
${open ? `<span class="ri tasks" title="${open} offene Aufgaben">${ic('list-checks', 'sm')}${open}</span>` : ''}
|
||
${p.published ? `<a class="ri pub" href="${escapeHtml(p.published.url)}" target="_blank" draggable="false" onclick="event.stopPropagation()" title="${escapeHtml(pubTitle(p))}">${ic('rocket', 'sm')}</a>` : ''}
|
||
</span>
|
||
</div>
|
||
${qsGroup(p, true)}
|
||
</div>`
|
||
}
|
||
|
||
function cardHtml(p) {
|
||
const total = (p.tasks ?? []).length
|
||
const done = (p.tasks ?? []).filter((t) => t.done).length
|
||
const tags = (p.tags ?? []).map((t) => `<span class="chip tag">${ic('tag', 'sm')}${escapeHtml(t)}</span>`).join('')
|
||
return `
|
||
<div class="head">${avatar(p)}
|
||
<div style="min-width:0"><div class="name" title="${escapeHtml(p.name)}">${escapeHtml(p.name)}</div>
|
||
<div class="sub">${rootTag(p, true)}${prioHtml(p.priority)}</div></div>
|
||
${qsGroup(p)}
|
||
</div>
|
||
${p.lastCommit ? `<div class="commit" title="${escapeHtml(p.lastCommit.message)}">${ic('git-commit-horizontal', 'sm')}<span>${escapeHtml(p.lastCommit.message)}</span></div>` : ''}
|
||
${factsHtml(p)}
|
||
<div class="row2">${gitHtml(p.git)}${cloudChip(p)}${pubChip(p)}</div>
|
||
<div class="chips">${techChips(p.tech?.types)}${warnChips(p)}${tags}</div>
|
||
${p.notes ? `<div class="notes">${escapeHtml(p.notes)}</div>` : ''}
|
||
${total ? `<div class="taskbar">${ic('list-checks', 'sm')}<span>${done}/${total}</span><div class="bar"><div style="width:${Math.round((done / total) * 100)}%"></div></div></div>` : ''}`
|
||
}
|
||
|
||
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 = `<h2><span class="bar" style="--c:${col.color}"></span>${ic(col.icon, 'sm')}${col.label}<span class="n">${items.length}</span></h2>`
|
||
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 = `<div class="empty">${ic('inbox')}</div>`
|
||
|
||
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 = `<div class="empty">${ic('search-x', 'xl')}<div>Keine Projekte gefunden.</div></div>`; return }
|
||
grid.innerHTML = ''
|
||
for (const p of items) {
|
||
const tile = document.createElement('div')
|
||
tile.className = 'tile'
|
||
tile.title = p.name
|
||
tile.innerHTML = `
|
||
<div class="thumb" style="--c:${nameColor(p.name)}"><span class="ini">${escapeHtml(initialsOf(p.name))}</span>
|
||
<img loading="lazy" class="${p.hasIcon ? '' : 'photo'}" src="${thumbUrl(p.name)}" alt="" onerror="this.remove()">
|
||
${statusHtml(p.status)}
|
||
<span class="tbadges">${pubBadge(p)}${cloudBadge(p)}<span class="tbadge ${p.git.level}" title="Git: ${escapeHtml(p.git.label)}">${ic(GIT_ICON[p.git.level])}</span></span>
|
||
</div>
|
||
<div class="info">
|
||
<div class="ghead"><div class="name">${escapeHtml(p.name)}</div>${qsGroup(p, false, true)}</div>
|
||
<div class="chips">${techChips(p.tech?.types)}</div>
|
||
<div class="meta"><span style="display:flex;gap:6px;align-items:center;min-width:0">${prioHtml(p.priority)}${rootTag(p, true)}</span><span>${p.storage?.sizeMB != null ? `${ic('hard-drive', 'sm')} ${fmtMB(p.storage.sizeMB)} · ` : ''}${timeAgo(lastActivity(p))}</span></div>
|
||
</div>`
|
||
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 = `<thead><tr>${LIST_COLS.map((c) => `<th class="${c.num ? 'num' : ''} ${c.cls ?? ''}" ${c.sort ? `data-sort="${c.sort}"` : ''}>${c.label}${c.sort === sort ? ' ' + ic('arrow-down', 'sm') : ''}</th>`).join('')}</tr></thead>
|
||
<tbody>${items.map((p) => `<tr data-name="${escapeHtml(p.name)}">
|
||
<td><div class="nm" title="${escapeHtml(p.name)}">${avatar(p)}<span>${escapeHtml(p.name)}</span>${rootTag(p, true)}</div></td>
|
||
<td class="c-status"><div class="chips" style="flex-wrap:nowrap">${statusHtml(p.status)}${pubChip(p, true)}</div></td>
|
||
<td>${gitHtml(p.git, true)}</td>
|
||
<td>${cloudChip(p)}</td>
|
||
<td class="c-tech"><div class="chips" style="flex-wrap:nowrap">${techChips(p.tech?.types)}${p.tech?.needsInstall ? `<span class="chip warn">${ic('download', 'sm')}install</span>` : ''}</div></td>
|
||
<td class="num bigval">${fmtMB(p.storage?.sizeMB)}</td>
|
||
<td class="num bigval c-clean ${deletableMB(p) >= 100 ? 'clean-val' : ''}">${p.storage ? fmtMB(deletableMB(p)) : '–'}</td>
|
||
<td class="c-act" style="color:var(--muted)" title="${escapeHtml(changeTitle(p))}">${fmtDate(lastActivity(p))} <span class="hint" style="margin:0">· ${timeAgo(lastActivity(p))}</span></td>
|
||
<td><div class="acts">
|
||
${p.quickStart ? `<button class="btn ghost play" data-qs title="${escapeHtml(quickStartTitle(p))}">${ic('play')}</button>` : '<span class="btn ghost" style="visibility:hidden">' + ic('play') + '</span>'}
|
||
<button class="btn ghost" data-a="explorer" title="Explorer">${ic('folder-open')}</button>
|
||
<button class="btn ghost" data-a="vscode" title="VS Code">${ic('code-xml')}</button>
|
||
<button class="btn ghost" data-a="details" title="Details">${ic('chevron-right')}</button>
|
||
</div></td></tr>`).join('') || `<tr><td colspan="9" class="empty">Keine Projekte gefunden.</td></tr>`}</tbody>`
|
||
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) => `<option value="${escapeHtml(p.name)}">${escapeHtml(p.name)}</option>`).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 = `<div class="empty">${ic(taskMode === 'done' ? 'inbox' : 'party-popper', 'xl')}<div>${taskMode === 'open' ? 'Keine offenen Aufgaben.' : 'Keine Aufgaben gefunden.'}</div>
|
||
<div class="hint">Oben ein Projekt wählen und eine Aufgabe eintragen.</div></div>`
|
||
return
|
||
}
|
||
el.innerHTML = groups.map(({ p, tasks }) => {
|
||
const all = p.tasks ?? []
|
||
const done = all.filter((t) => t.done).length
|
||
return `<div class="tgroup" data-name="${escapeHtml(p.name)}">
|
||
<div class="tg-head" title="Projekt öffnen">${avatar(p)}<b>${escapeHtml(p.name)}</b>${statusHtml(p.status)}<span class="cnt">${done}/${all.length}</span></div>
|
||
<div class="progress"><div style="width:${all.length ? Math.round((done / all.length) * 100) : 0}%"></div></div>
|
||
${tasks.map((t) => `<div class="titem ${t.done ? 'done' : ''}" data-id="${escapeHtml(t.id)}">
|
||
<input type="checkbox" ${t.done ? 'checked' : ''}><span>${escapeHtml(t.text)}</span>
|
||
<button class="del" title="Löschen">${ic('trash', 'sm')}</button></div>`).join('')}
|
||
<div class="tg-add"><input type="text" placeholder="+ Aufgabe für ${escapeHtml(p.name)}"></div>
|
||
</div>`
|
||
}).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 "<folder>\rest" (relative to the projects folder) → "rest"
|
||
const inProject = (p) => p.slice(p.indexOf('\\') + 1)
|
||
|
||
function section(icon, title, body) {
|
||
return `<div class="card-sec"><h4>${ic(icon)}${title}</h4>${body}</div>`
|
||
}
|
||
|
||
function renderInfo(name, d) {
|
||
const g = d.git
|
||
const key = d.sshKey
|
||
const keyHint = key
|
||
? `<div class="hint">${ic('key-round', 'sm')} SSH-Schlüssel: <code>${escapeHtml(key.file)}</code> <button class="btn ghost" type="button" id="btnCopyKey" title="Öffentlichen Schlüssel kopieren – bei GitHub/GitLab unter „SSH keys“ einfügen">${ic('copy', 'sm')}kopieren</button></div>`
|
||
: `<div class="hint">${ic('key-round', 'sm')} Kein SSH-Schlüssel gefunden. Anlegen mit <code>ssh-keygen -t ed25519</code>, dann den Inhalt von <code>.ssh\\id_ed25519.pub</code> bei GitHub/GitLab eintragen.</div>`
|
||
const pushBox = !g.remote ? '' : g.dirty
|
||
? `<div class="pickrow" style="margin-top:10px">
|
||
<input type="text" id="gMsg" placeholder="Commit-Nachricht (${g.dirty} Änderungen)" maxlength="200">
|
||
<button class="btn primary" type="button" id="btnCommitPush">${ic('cloud-upload')}Commit & Push</button>
|
||
<button class="btn" type="button" id="btnPush" title="Nur bestehende Commits pushen">${ic('upload')}Push</button>
|
||
</div>`
|
||
: `<div style="margin-top:10px"><button class="btn ${g.ahead || !g.upstream ? 'primary' : ''}" type="button" id="btnPush">${ic('cloud-upload')}git push${g.ahead ? ` (${g.ahead})` : ''}</button></div>`
|
||
const gitBody = g.isRepo
|
||
? `<div class="kv">
|
||
<div>Status</div><div>${gitHtml(g)}</div>
|
||
<div>Branch</div><div>${ic('git-branch', 'sm')} ${escapeHtml(g.branch)}${g.upstream ? ` → ${escapeHtml(g.upstream)}` : ''}</div>
|
||
<div>Letzter Commit</div><div>${g.lastCommit ? `${g.lastCommit.date} · ${escapeHtml(g.lastCommit.message)}` : '–'}</div>
|
||
</div>
|
||
<label style="display:flex;gap:6px;align-items:center;font-size:12px;color:var(--muted);margin:12px 0 5px">${ic('link', 'sm')}Remote (origin) – SSH oder https</label>
|
||
<div class="pickrow">
|
||
<input type="text" id="gRemote" value="${escapeHtml(g.remote ?? '')}" placeholder="git@github.com:name/${escapeHtml(name)}.git">
|
||
<button class="btn" type="button" id="btnRemote">${ic('save')}Speichern</button>
|
||
</div>
|
||
${g.remote ? '' : '<div class="hint">Noch kein Remote – das Projekt liegt nur auf dieser Platte.</div>'}
|
||
${pushBox}
|
||
${keyHint}
|
||
<div class="hint">Push läuft in einem eigenen Konsolenfenster (dort erscheinen SSH-Passphrase und Fehler).</div>`
|
||
: `<div>${gitHtml(g)}</div><div class="hint">Kein Git-Repository – Änderungen sind nirgends gesichert.</div>
|
||
<div style="margin-top:10px"><button class="btn primary" type="button" id="btnGitInit">${ic('git-branch')}Git einrichten</button></div>`
|
||
|
||
const gens = d.tools.generators
|
||
const genBody = gens.length
|
||
? `<div class="kv">${gens.map((x) => `<div>${escapeHtml(x.rel)}</div><div>${x.kind === 'comfygen'
|
||
? `<span class="chip ok">${ic('wand-sparkles', 'sm')}nutzt _Tools\\ComfyGen</span>`
|
||
: `<span class="chip bad">${ic('copy', 'sm')}eigene Kopie</span><div class="hint">${escapeHtml(x.scripts.join(', '))}</div>`}</div>`).join('')}</div>`
|
||
: '<div class="hint">Kein Generator-Ordner.</div>'
|
||
|
||
const genDir = gens.find((x) => x.kind === 'comfygen')
|
||
const iconBody = d.icon
|
||
? `<div><img class="iconprev" src="${thumbUrl(name)}" alt="">${escapeHtml(d.icon)}</div>`
|
||
: `<div><span class="chip neutral">${ic('image-off', 'sm')}kein Icon gefunden</span></div>
|
||
<div class="hint">${genDir ? 'Mit ComfyGen erzeugen (Prompt „icon“ in prompts.py eintragen):' : 'Generator-Vorlage aus _Tools\\ComfyGen\\template kopieren, dann:'}</div>
|
||
<code class="cmd">cd "${escapeHtml(d.path)}\\${escapeHtml(genDir ? genDir.rel : 'sprite-generator')}" && gen generate icon && gen adopt icon</code>`
|
||
|
||
const s = d.storage
|
||
let storageBody
|
||
if (!s) storageBody = '<div class="hint">Noch nicht gescannt.</div>'
|
||
else {
|
||
const rows = s.candidates.filter((c) => c.MB >= 1 || c.Skip)
|
||
storageBody = `<div class="kv"><div>Größe</div><div><b>${fmtMB(s.sizeMB)}</b> <span class="hint">· gescannt ${timeAgo(s.at)}</span></div>
|
||
<div>Löschbar</div><div>Cache ${fmtMB(s.deletable.Cache)} · Builds ${fmtMB(s.deletable.Release)} · Rohbilder ${fmtMB(s.deletable.Output)}</div></div>`
|
||
storageBody += rows.length
|
||
? `<table class="cand">${rows.map((c) => `<tr>
|
||
<td><input type="checkbox" class="candcb" data-path="${escapeHtml(c.Path)}" ${c.Skip ? 'disabled' : c.Tier === 'Cache' ? 'checked' : ''}></td>
|
||
<td>${escapeHtml(inProject(c.Path))}</td>
|
||
<td><span class="chip ${TIER[c.Tier].cls}" title="${TIER[c.Tier].hint}">${ic(TIER[c.Tier].icon, 'sm')}${TIER[c.Tier].label}</span>${c.Skip ? ` <span class="chip bad">${ic('lock', 'sm')}in git</span>` : ''}</td>
|
||
<td class="mb">${fmtMB(c.MB)}</td></tr>`).join('')}</table>
|
||
<div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap"><button class="btn danger" id="btnClean">${ic('trash')}Ausgewählte löschen</button></div>
|
||
<div class="hint">Cache ist vorausgewählt (immer neu erzeugbar). Fertige Builds und Rohbilder nur bewusst anhaken.</div>`
|
||
: `<div class="hint">${ic('sparkles', 'sm')} Nichts zum Aufräumen.</div>`
|
||
}
|
||
storageBody += `<div style="margin-top:10px"><button class="btn" id="btnScanOne" ${!cleanupAvailable || scanState?.running ? 'disabled' : ''}>${ic('scan-search')}${s ? 'Neu scannen' : 'Scannen'}</button></div>`
|
||
|
||
document.getElementById('sec-info').innerHTML =
|
||
section('cloud', 'Git & Backup', gitBody) +
|
||
section('cpu', 'Technik', `<div class="chips">${techChips(d.tech.types) || '<span class="hint">nicht erkannt</span>'}${d.tech.needsInstall ? `<span class="chip warn">${ic('download', 'sm')}npm install nötig</span>` : ''}</div>`) +
|
||
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
|
||
? `<div class="progs">${programs.map((a, i) => {
|
||
const pinned = a.id === 'program'
|
||
return `<div class="progwrap">
|
||
<button class="prog act ${i === 0 ? 'first' : ''}" data-id="${escapeHtml(a.id)}" title="${escapeHtml(a.detail ?? '')}">
|
||
<span class="pico">${ic(a.id.startsWith('html:') || /\.html?$/i.test(a.rel ?? '') ? 'globe' : 'play', 'lg')}</span>
|
||
<span class="ptxt"><b>${escapeHtml(a.label)}</b><small>${escapeHtml(a.detail ?? '')}</small></span>
|
||
</button>
|
||
${a.rel ? `<button class="pin ${pinned ? 'on' : ''}" data-rel="${escapeHtml(pinned ? '' : a.rel)}" title="${pinned ? 'Nicht mehr für ▶ verwenden' : 'Für ▶ auf der Karte verwenden'}">${ic('pin', 'sm')}</button>` : ''}
|
||
</div>`
|
||
}).join('')}</div>`
|
||
: `<div class="hint">Keine fertige exe oder HTML-Seite im Projekt gefunden.${hasBuild ? ' Unter „Bauen“ erzeugen, dann hier starten.' : ''}</div>`)
|
||
+ (prog?.missing ? `<div class="hint warn">${ic('triangle-alert', 'sm')} Festgelegte Datei fehlt: <b>${escapeHtml(prog.rel)}</b> – neu wählen oder zurücksetzen.</div>` : '')
|
||
+ `<div class="progset">
|
||
<label>${ic('pin', 'sm')}Für ▶ starten (exe, html, bat, lnk – Pfad im Projekt)</label>
|
||
<div class="pickrow">
|
||
<input type="text" id="fProgram" placeholder="z. B. release\\Spiel.exe oder game\\index.html" value="${escapeHtml(prog?.rel ?? '')}">
|
||
${hasPicker ? `<button class="btn" type="button" id="btnPickProgram">${ic('file-search')}Durchsuchen…</button>` : ''}
|
||
<button class="btn primary" type="button" id="btnSetProgram">${ic('check')}Festlegen</button>
|
||
${prog ? `<button class="btn ghost" type="button" id="btnClearProgram" title="Automatisch wählen">${ic('rotate-ccw')}</button>` : ''}
|
||
</div>
|
||
</div>`
|
||
|
||
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', '<div id="pbackupBody"></div>'))
|
||
+ order.filter((g) => groups[g]).map((g) =>
|
||
section(ACTION_ICON[g], g, `<div class="actgroup">${groups[g].map((a) =>
|
||
`<button class="btn act ${g === 'Starten' || g === 'Einrichten' ? 'primary' : ''}" data-id="${escapeHtml(a.id)}" ${a.detail ? `title="${escapeHtml(a.detail)}"` : ''}>${ic(ACT_ICON(a))}${escapeHtml(a.label)}</button>`).join('')}</div>`)).join('')
|
||
+ `<div class="hint" style="margin-top:12px">${ic('shield-check', 'sm')} Programme starten direkt, Befehle und .bat laufen sichtbar in einem eigenen Konsolenfenster. Eigenen Start-Befehl unter „Bearbeiten“ festlegen.</div>`
|
||
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 = `<div class="msg info">${ic('hard-drive-upload')}<div>Noch kein Backup-Ziel festgelegt (z. B. externe Platte oder NAS).</div></div>
|
||
<div class="bactions"><button class="btn primary" id="pbSetup">${ic('settings')}Backup-Ziel einrichten</button></div>`
|
||
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) + `<div class="kv"><div>Zuletzt gesichert</div><div>${last
|
||
? `<b>${new Date(last.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })}</b> (${timeAgo(last.at)}) <span class="hint">· ${last.how}</span>`
|
||
: '<span style="color:var(--yellow)">noch nie</span>'}</div>
|
||
<div>Ziel</div><div class="hint" style="margin:0">${escapeHtml(shownT ? `${shownT.path}\\${name}` : '…')}</div>
|
||
${projectTargets.length > 1 ? `<div>Alle Ziele</div><div class="tlast">${projectTargets.map((x) => {
|
||
const lv = !x.last ? 'red' : (Date.now() - new Date(x.last.at)) / 86400000 > BACKUP_FRESH_DAYS ? 'yellow' : 'green'
|
||
return `<span class="bk ${lv}" title="${escapeHtml(x.last ? `${x.name}: ${new Date(x.last.at).toLocaleString('de-DE')} (${x.last.how})` : `${x.name}: noch nie`)}">${ic('hard-drive', 'sm')}${escapeHtml(x.name)} · ${x.last ? timeAgo(x.last.at) : 'nie'}</span>`
|
||
}).join('')}</div>` : ''}</div>`
|
||
|
||
if (busy && mine && b.phase === 'checking') {
|
||
html += `<div class="msg info">${ic('loader')}<div><b>Prüfe, was im Backup fehlt…</b></div></div>`
|
||
} 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 += `<div style="display:flex;justify-content:space-between;font-size:13px;margin-top:12px"><b>Kopiere… ${pct} %</b><span>${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}</span></div>
|
||
<div class="progress big"><div style="width:${pct}%"></div></div>
|
||
<div class="hint">${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien</div>
|
||
<div class="curfile" title="${escapeHtml(pr.current)}">${escapeHtml(pr.current)}</div>`
|
||
} else if (busy) {
|
||
html += `<div class="msg info">${ic('hourglass')}<div>Es läuft gerade ein anderes Backup (${b.scope ? escapeHtml(b.scope) : 'alle Projekte'}). Danach geht es hier.</div></div>`
|
||
} else if (mine && b.phase === 'done') {
|
||
const l = shownT?.lastByProject?.[name]
|
||
html += l && l.files
|
||
? `<div class="msg ok">${ic('circle-check')}<div><b>Gesichert.</b> ${l.files.toLocaleString('de-DE')} Dateien (${fmtBytes(l.bytes)}) neu ins Backup kopiert.</div></div>`
|
||
: `<div class="msg ok">${ic('circle-check')}<div><b>Alles aktuell.</b> Im Backup fehlte nichts.</div></div>`
|
||
} else if (mine && b.phase === 'error') {
|
||
html += `<div class="msg err">${ic('triangle-alert')}<div>${escapeHtml(b.error)}</div></div>`
|
||
} else if (mine && b.phase === 'cancelled') {
|
||
html += `<div class="msg info">${ic('circle-x')}<div>Abgebrochen. Bereits kopierte Dateien bleiben im Backup.</div></div>`
|
||
}
|
||
|
||
html += `<div class="bactions">${busy && mine
|
||
? `<button class="btn" id="pbCancel">${ic('circle-x')}Abbrechen</button>`
|
||
: `<button class="btn primary" id="pbSave" ${busy || b?.configError ? 'disabled' : ''}>${ic('hard-drive-upload')}Jetzt sichern</button>`}</div>
|
||
<div class="hint">Prüft das Projekt im Backup und kopiert nur fehlende und geänderte Dateien. Gelöscht wird dort nichts.</div>`
|
||
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 = `<div class="hint">Fehler: ${escapeHtml(e.message)}</div>`
|
||
}
|
||
}
|
||
|
||
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: <b>${escapeHtml(p.published.title)}</b> – ${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 = `<div class="hint">${ic('loader', 'sm')} Lädt…</div>`
|
||
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 `<div class="seg ttabs">${list.map((t) => `<button type="button" data-target="${escapeHtml(t.id)}" class="${t.id === cur ? 'active' : ''}" ${busyId && t.id !== busyId ? 'disabled title="Es läuft gerade ein Backup"' : ''}>${ic('hard-drive', 'sm')}${escapeHtml(t.name)}</button>`).join('')}</div>`
|
||
}
|
||
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 = `<div class="msg info">${ic('hard-drive-upload')}<div>Noch kein Backup-Ziel festgelegt. Wähle einen Ordner auf einer externen Platte, einem NAS oder einem anderen Laufwerk.</div></div>
|
||
<div class="bactions"><button class="btn primary big" id="bpSetup">${ic('settings')}Backup-Ziel einrichten</button></div>`
|
||
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
|
||
? `<div class="kv"><div>Letztes Backup</div><div><b>${new Date(tl.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })}</b> (${timeAgo(tl.at)})</div>
|
||
<div>Kopiert</div><div>${tl.files.toLocaleString('de-DE')} Dateien · ${fmtBytes(tl.bytes)}${tl.ok === false ? ' · <span style="color:var(--red)">unvollständig</span>' : ''}</div></div>`
|
||
: `<div class="hint">Auf „${escapeHtml(t.name)}“ wurde über das Dashboard noch kein Komplett-Backup gemacht.</div>`
|
||
|
||
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 += `<div class="msg info">${ic('folder')}<div>Der aktuelle Lauf betrifft nur das Projekt <b>${escapeHtml(b.scope)}</b> (gestartet über „Sichern“ im Projekt).</div></div>`
|
||
}
|
||
|
||
if (b.phase === 'checking') {
|
||
body += `<div class="msg info">${ic('loader')}<div><b>Prüfe, was neu ist und im Backup fehlt…</b><div class="hint">Dauert über das Netzwerk etwa 1–2 Minuten.</div></div></div>
|
||
<div class="bactions"><button class="btn" id="bpCancel">${ic('circle-x')}Abbrechen</button></div>`
|
||
} 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…', `
|
||
<div style="display:flex;justify-content:space-between;font-size:13px"><b>${pct} %</b><span>${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}</span></div>
|
||
<div class="progress big"><div style="width:${pct}%"></div></div>
|
||
<div class="hint">${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien</div>
|
||
<div class="curfile" title="${escapeHtml(pr.current)}">${escapeHtml(pr.current)}</div>`)
|
||
+ `<div class="bactions"><button class="btn" id="bpCancel">${ic('circle-x')}Abbrechen</button></div>
|
||
<div class="hint">Das Fenster bitte offen lassen, bis das Backup fertig ist.</div>`
|
||
} else if (b.phase === 'ready' && b.check) {
|
||
const c = b.check
|
||
if (!c.files) {
|
||
body += `<div class="msg ok">${ic('circle-check')}<div><b>Alles aktuell.</b> Im Backup fehlt nichts.</div></div>`
|
||
} else {
|
||
body += section('scan-search', `Ergebnis der Prüfung <span class="hint" style="margin:0 0 0 auto">${timeAgo(c.at)}</span>`, `
|
||
<div class="bstats">
|
||
<div class="bstat new"><div class="l">${ic('file-plus', 'sm')}Neu</div><div class="v">${c.newFiles.toLocaleString('de-DE')}</div><div class="s">${fmtBytes(c.newBytes)}</div></div>
|
||
<div class="bstat chg"><div class="l">${ic('file-pen', 'sm')}Geändert</div><div class="v">${c.changedFiles.toLocaleString('de-DE')}</div><div class="s">${fmtBytes(c.changedBytes)}</div></div>
|
||
<div class="bstat"><div class="l">${ic('archive', 'sm')}Nur im Backup</div><div class="v">${c.extraFiles.toLocaleString('de-DE')}</div><div class="s">bleiben erhalten</div></div>
|
||
</div>
|
||
<table class="bproj">${c.projects.slice(0, 15).map((p) => `<tr><td>${escapeHtml(p.name)}</td><td class="r">${p.files.toLocaleString('de-DE')} Dateien</td><td class="r">${fmtBytes(p.bytes)}</td></tr>`).join('')}</table>
|
||
${c.projects.length > 15 ? `<div class="hint">+ ${c.projects.length - 15} weitere Projekte</div>` : ''}`)
|
||
}
|
||
body += `<div class="bactions">
|
||
<button class="btn" id="bpCheck">${ic('refresh-cw')}Neu prüfen</button>
|
||
${c.files ? `<button class="btn primary" id="bpCopy">${ic('hard-drive-upload')}Jetzt kopieren (${fmtBytes(c.bytes)})</button>` : ''}
|
||
</div>`
|
||
} else {
|
||
if (b.phase === 'done') body += `<div class="msg ok">${ic('circle-check')}<div><b>Backup fertig.</b> ${tl && !b.scope ? `${tl.files.toLocaleString('de-DE')} Dateien, ${fmtBytes(tl.bytes)} kopiert.` : ''}</div></div>`
|
||
if (b.phase === 'cancelled') body += `<div class="msg info">${ic('circle-x')}<div>Abgebrochen. Bereits kopierte Dateien bleiben im Backup.</div></div>`
|
||
if (b.phase === 'error') body += `<div class="msg err">${ic('triangle-alert')}<div>${escapeHtml(b.error)}</div></div>`
|
||
body += `<div class="bactions"><button class="btn primary big" id="bpCheck" ${b.configError ? 'disabled' : ''}>${ic('scan-search')}Prüfen, was neu ist</button></div>`
|
||
}
|
||
|
||
body += `<div class="hint" style="margin-top:16px">${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).</div>`
|
||
|
||
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/<Projekt> (opens the panel), #list/<Projekt>/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)
|
||
})
|